diff --git "a/data/test.jsonl" "b/data/test.jsonl" new file mode 100644--- /dev/null +++ "b/data/test.jsonl" @@ -0,0 +1,568 @@ +{"task_id": "BaPSF__bapsflib-41_x1", "level": 1, "source": "swerebench", "repo": "BaPSF/bapsflib", "image": "swerebench/sweb.eval.x86_64.bapsf_1776_bapsflib-41:latest", "base_commit": "08a56b9001c607982778b16f15a30dd88ba3cf31", "num_bugs": 1, "bugs": [{"instance_id": "BaPSF__bapsflib-41", "base_commit": "08a56b9001c607982778b16f15a30dd88ba3cf31", "gold_patch": "diff --git a/bapsflib/_hdf/utils/helpers.py b/bapsflib/_hdf/utils/helpers.py\nindex 28cdde8..4e103c5 100644\n--- a/bapsflib/_hdf/utils/helpers.py\n+++ b/bapsflib/_hdf/utils/helpers.py\n@@ -561,7 +561,8 @@ def condition_shotnum(shotnum: Any,\n 'array would be NULL')\n \n elif isinstance(shotnum, np.ndarray):\n- shotnum = shotnum.squeeze()\n+ if shotnum.ndim != 1:\n+ shotnum = shotnum.squeeze()\n if shotnum.ndim != 1 \\\n or not np.issubdtype(shotnum.dtype, np.integer) \\\n or bool(shotnum.dtype.names):\n", "test_patch": "diff --git a/bapsflib/_hdf/utils/tests/test_helpers.py b/bapsflib/_hdf/utils/tests/test_helpers.py\nindex bb7c8e0..a280cd1 100644\n--- a/bapsflib/_hdf/utils/tests/test_helpers.py\n+++ b/bapsflib/_hdf/utils/tests/test_helpers.py\n@@ -663,6 +663,8 @@ class TestConditionShotnum(TestBase):\n \n # shotnum valid\n sn = [\n+ (np.array([12], np.int32),\n+ np.array([12], np.uint32)),\n (np.array([-5, 0, 10], np.int32),\n np.array([10], np.uint32)),\n (np.array([20, 30], np.int32),\n", "FAIL_TO_PASS": ["bapsflib/_hdf/utils/tests/test_helpers.py::TestConditionShotnum::test_shotnum_ndarray"]}], "all_FAIL_TO_PASS": ["bapsflib/_hdf/utils/tests/test_helpers.py::TestConditionShotnum::test_shotnum_ndarray"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "DataDog__dd-trace-py-1054_x1", "level": 1, "source": "swerebench", "repo": "DataDog/dd-trace-py", "image": "swerebench/sweb.eval.x86_64.datadog_1776_dd-trace-py-1054:latest", "base_commit": "3576559cfcfe8491bb4deef498c059080f3162f6", "num_bugs": 1, "bugs": [{"instance_id": "DataDog__dd-trace-py-1054", "base_commit": "3576559cfcfe8491bb4deef498c059080f3162f6", "gold_patch": "diff --git a/ddtrace/tracer.py b/ddtrace/tracer.py\nindex bc238ca5d..8ecba7564 100644\n--- a/ddtrace/tracer.py\n+++ b/ddtrace/tracer.py\n@@ -38,11 +38,14 @@ class Tracer(object):\n DEFAULT_HOSTNAME = environ.get('DD_AGENT_HOST', environ.get('DATADOG_TRACE_AGENT_HOSTNAME', 'localhost'))\n DEFAULT_PORT = int(environ.get('DD_TRACE_AGENT_PORT', 8126))\n DEFAULT_DOGSTATSD_PORT = int(get_env('dogstatsd', 'port', 8125))\n+ DEFAULT_AGENT_URL = environ.get('DD_TRACE_AGENT_URL', 'http://%s:%d' % (DEFAULT_HOSTNAME, DEFAULT_PORT))\n \n- def __init__(self):\n+ def __init__(self, url=DEFAULT_AGENT_URL):\n \"\"\"\n Create a new ``Tracer`` instance. A global tracer is already initialized\n for common usage, so there is no need to initialize your own ``Tracer``.\n+\n+ :param url: The Datadog agent URL.\n \"\"\"\n self.log = log\n self.sampler = None\n@@ -52,11 +55,36 @@ class Tracer(object):\n self._dogstatsd_host = self.DEFAULT_HOSTNAME\n self._dogstatsd_port = self.DEFAULT_DOGSTATSD_PORT\n \n+ uds_path = None\n+ https = None\n+ hostname = self.DEFAULT_HOSTNAME\n+ port = self.DEFAULT_PORT\n+ if url is not None:\n+ url_parsed = compat.parse.urlparse(url)\n+ if url_parsed.scheme in ('http', 'https'):\n+ hostname = url_parsed.hostname\n+ port = url_parsed.port\n+ https = url_parsed.scheme == 'https'\n+ # FIXME This is needed because of the way of configure() works right now, where it considers `port=None`\n+ # to be \"no port set so let's use the default\".\n+ # It should go away when we remove configure()\n+ if port is None:\n+ if https:\n+ port = 443\n+ else:\n+ port = 80\n+ elif url_parsed.scheme == 'unix':\n+ uds_path = url_parsed.path\n+ else:\n+ raise ValueError('Unknown scheme `%s` for agent URL' % url_parsed.scheme)\n+\n # Apply the default configuration\n self.configure(\n enabled=True,\n- hostname=self.DEFAULT_HOSTNAME,\n- port=self.DEFAULT_PORT,\n+ hostname=hostname,\n+ port=port,\n+ https=https,\n+ uds_path=uds_path,\n sampler=AllSampler(),\n context_provider=DefaultContextProvider(),\n )\n@@ -112,6 +140,7 @@ class Tracer(object):\n \"\"\"Returns the current Tracer Context Provider\"\"\"\n return self._context_provider\n \n+ # TODO: deprecate this method and make sure users create a new tracer if they need different parameters\n def configure(self, enabled=None, hostname=None, port=None, uds_path=None, https=None,\n dogstatsd_host=None, dogstatsd_port=None, sampler=None, context_provider=None,\n wrap_executor=None, priority_sampling=None, settings=None, collect_metrics=None):\n@@ -172,13 +201,16 @@ class Tracer(object):\n if hostname is not None or port is not None or uds_path is not None or https is not None or \\\n filters is not None or priority_sampling is not None:\n # Preserve hostname and port when overriding filters or priority sampling\n- default_hostname = self.DEFAULT_HOSTNAME\n- default_port = self.DEFAULT_PORT\n+ # This is clumsy and a good reason to get rid of this configure() API\n if hasattr(self, 'writer') and hasattr(self.writer, 'api'):\n default_hostname = self.writer.api.hostname\n default_port = self.writer.api.port\n if https is None:\n https = self.writer.api.https\n+ else:\n+ default_hostname = self.DEFAULT_HOSTNAME\n+ default_port = self.DEFAULT_PORT\n+\n self.writer = AgentWriter(\n hostname or default_hostname,\n port or default_port,\ndiff --git a/docs/installation_quickstart.rst b/docs/installation_quickstart.rst\nindex ec19ddc2b..0f158f30f 100644\n--- a/docs/installation_quickstart.rst\n+++ b/docs/installation_quickstart.rst\n@@ -34,6 +34,28 @@ For more advanced usage of ``ddtrace-run`` refer to the documentation :ref:`here\n To find out how to trace your own code manually refer to the documentation :ref:`here`.\n \n \n+Configuration\n+~~~~~~~~~~~~~\n+\n+You can configure some parameters of the library by setting environment\n+variable before starting your application and importing the library:\n+\n+.. list-table::\n+ :header-rows: 1\n+ :widths: 1 1 2\n+\n+ * - Configuration Variable\n+ - Configuration Type\n+ - Default Value\n+ - Value Description\n+ * - ``DD_TRACE_AGENT_URL``\n+ - URL\n+ - ``http://localhost:8126``\n+ - The URL to use to connect the Datadog agent. The url can starts with\n+ ``http://`` to connect using HTTP or with ``unix://`` to use a Unix\n+ Domain Socket.\n+\n+\n OpenTracing\n -----------\n \n", "test_patch": "diff --git a/tests/test_tracer.py b/tests/test_tracer.py\nindex 51e93de41..22d822727 100644\n--- a/tests/test_tracer.py\n+++ b/tests/test_tracer.py\n@@ -8,6 +8,7 @@ import sys\n from unittest.case import SkipTest\n \n import mock\n+import pytest\n \n import ddtrace\n from ddtrace.ext import system\n@@ -499,3 +500,30 @@ def test_excepthook():\n mock.call('datadog.tracer.uncaught_exceptions', 1, tags=['class:Foobar']),\n ))\n assert called\n+\n+\n+def test_tracer_url():\n+ t = ddtrace.Tracer()\n+ assert t.writer.api.hostname == 'localhost'\n+ assert t.writer.api.port == 8126\n+\n+ t = ddtrace.Tracer(url='http://foobar:12')\n+ assert t.writer.api.hostname == 'foobar'\n+ assert t.writer.api.port == 12\n+\n+ t = ddtrace.Tracer(url='unix:///foobar')\n+ assert t.writer.api.uds_path == '/foobar'\n+\n+ t = ddtrace.Tracer(url='http://localhost')\n+ assert t.writer.api.hostname == 'localhost'\n+ assert t.writer.api.port == 80\n+ assert not t.writer.api.https\n+\n+ t = ddtrace.Tracer(url='https://localhost')\n+ assert t.writer.api.hostname == 'localhost'\n+ assert t.writer.api.port == 443\n+ assert t.writer.api.https\n+\n+ with pytest.raises(ValueError) as e:\n+ t = ddtrace.Tracer(url='foo://foobar:12')\n+ assert str(e) == 'Unknown scheme `https` for agent URL'\n", "FAIL_TO_PASS": ["tests/test_tracer.py::test_tracer_url"]}], "all_FAIL_TO_PASS": ["tests/test_tracer.py::test_tracer_url"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PyPSA__linopy-412_x1", "level": 1, "source": "swerebench", "repo": "PyPSA/linopy", "image": "swerebench/sweb.eval.x86_64.pypsa_1776_linopy-412:latest", "base_commit": "9b80b320a3961f3696de0b8aa249ab10026746bf", "num_bugs": 1, "bugs": [{"instance_id": "PyPSA__linopy-412", "base_commit": "9b80b320a3961f3696de0b8aa249ab10026746bf", "gold_patch": "diff --git a/doc/release_notes.rst b/doc/release_notes.rst\nindex 787c633..0a42d6b 100644\n--- a/doc/release_notes.rst\n+++ b/doc/release_notes.rst\n@@ -5,6 +5,7 @@ Upcoming Version\n ----------------\n \n * The internal handling of `Solution` objects was improved for more consistency. Solution objects created from solver calls now preserve the exact index names from the input file.\n+* Multiplication of a linear expression by a constant value may now introduce new dimensions.\n \n Version 0.4.4\n --------------\ndiff --git a/linopy/expressions.py b/linopy/expressions.py\nindex fedda73..cf6443b 100644\n--- a/linopy/expressions.py\n+++ b/linopy/expressions.py\n@@ -448,9 +448,9 @@ class LinearExpression:\n expr = print_single_expression(\n self.coeffs, self.vars, self.const, self.model\n )\n- lines.append(f\"{header_string}\\n{'-'*len(header_string)}\\n{expr}\")\n+ lines.append(f\"{header_string}\\n{'-' * len(header_string)}\\n{expr}\")\n else:\n- lines.append(f\"{header_string}\\n{'-'*len(header_string)}\\n\")\n+ lines.append(f\"{header_string}\\n{'-' * len(header_string)}\\n\")\n \n return \"\\n\".join(lines)\n \n@@ -555,7 +555,7 @@ class LinearExpression:\n def _multiply_by_constant(self, other: int | float | DataArray) -> LinearExpression:\n multiplier = as_dataarray(other, coords=self.coords, dims=self.coord_dims)\n coeffs = self.coeffs * multiplier\n- assert set(coeffs.shape) == set(self.coeffs.shape)\n+ assert all(coeffs.sizes[d] == s for d, s in self.coeffs.sizes.items())\n const = self.const * multiplier\n return self.assign(coeffs=coeffs, const=const)\n \n@@ -1875,7 +1875,7 @@ class ScalarLinearExpression:\n return ScalarLinearExpression(coeffs, vars, self.model)\n elif not isinstance(other, ScalarLinearExpression):\n raise TypeError(\n- \"unsupported operand type(s) for +: \" f\"{type(self)} and {type(other)}\"\n+ f\"unsupported operand type(s) for +: {type(self)} and {type(other)}\"\n )\n \n coeffs = self.coeffs + other.coeffs\n@@ -1901,7 +1901,7 @@ class ScalarLinearExpression:\n other = other.to_scalar_linexpr(1)\n elif not isinstance(other, ScalarLinearExpression):\n raise TypeError(\n- \"unsupported operand type(s) for -: \" f\"{type(self)} and {type(other)}\"\n+ f\"unsupported operand type(s) for -: {type(self)} and {type(other)}\"\n )\n \n return ScalarLinearExpression(\n@@ -1918,7 +1918,7 @@ class ScalarLinearExpression:\n def __mul__(self, other: float | int) -> ScalarLinearExpression:\n if not isinstance(other, (int, float, np.number)):\n raise TypeError(\n- \"unsupported operand type(s) for *: \" f\"{type(self)} and {type(other)}\"\n+ f\"unsupported operand type(s) for *: {type(self)} and {type(other)}\"\n )\n \n return ScalarLinearExpression(\n@@ -1931,7 +1931,7 @@ class ScalarLinearExpression:\n def __div__(self, other: float | int) -> ScalarLinearExpression:\n if not isinstance(other, (int, float, np.number)):\n raise TypeError(\n- \"unsupported operand type(s) for /: \" f\"{type(self)} and {type(other)}\"\n+ f\"unsupported operand type(s) for /: {type(self)} and {type(other)}\"\n )\n return self.__mul__(1 / other)\n \n@@ -1941,7 +1941,7 @@ class ScalarLinearExpression:\n def __le__(self, other: int | float) -> AnonymousScalarConstraint:\n if not isinstance(other, (int, float, np.number)):\n raise TypeError(\n- \"unsupported operand type(s) for <=: \" f\"{type(self)} and {type(other)}\"\n+ f\"unsupported operand type(s) for <=: {type(self)} and {type(other)}\"\n )\n \n return constraints.AnonymousScalarConstraint(self, LESS_EQUAL, other)\n@@ -1949,7 +1949,7 @@ class ScalarLinearExpression:\n def __ge__(self, other: int | float) -> AnonymousScalarConstraint:\n if not isinstance(other, (int, float, np.number)):\n raise TypeError(\n- \"unsupported operand type(s) for >=: \" f\"{type(self)} and {type(other)}\"\n+ f\"unsupported operand type(s) for >=: {type(self)} and {type(other)}\"\n )\n \n return constraints.AnonymousScalarConstraint(self, GREATER_EQUAL, other)\n@@ -1957,7 +1957,7 @@ class ScalarLinearExpression:\n def __eq__(self, other: int | float) -> AnonymousScalarConstraint: # type: ignore\n if not isinstance(other, (int, float, np.number)):\n raise TypeError(\n- \"unsupported operand type(s) for ==: \" f\"{type(self)} and {type(other)}\"\n+ f\"unsupported operand type(s) for ==: {type(self)} and {type(other)}\"\n )\n \n return constraints.AnonymousScalarConstraint(self, EQUAL, other)\n", "test_patch": "diff --git a/test/test_linear_expression.py b/test/test_linear_expression.py\nindex 0de9c3c..017d165 100644\n--- a/test/test_linear_expression.py\n+++ b/test/test_linear_expression.py\n@@ -246,9 +246,14 @@ def test_linear_expression_with_constant(m, x, y):\n \n def test_linear_expression_with_constant_multiplication(m, x, y):\n expr = x + 1\n- expr = expr * 10\n- assert isinstance(expr, LinearExpression)\n- assert (expr.const == 10).all()\n+\n+ obs = expr * 10\n+ assert isinstance(obs, LinearExpression)\n+ assert (obs.const == 10).all()\n+\n+ obs = expr * pd.Series([1, 2, 3], index=pd.RangeIndex(3, name=\"new_dim\"))\n+ assert isinstance(obs, LinearExpression)\n+ assert obs.shape == (2, 3, 1)\n \n \n def test_linear_expression_multi_indexed(u):\n", "FAIL_TO_PASS": ["test/test_linear_expression.py::test_linear_expression_with_constant_multiplication"]}], "all_FAIL_TO_PASS": ["test/test_linear_expression.py::test_linear_expression_with_constant_multiplication"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Pylons__colander-321_x1", "level": 1, "source": "swerebench", "repo": "Pylons/colander", "image": "swerebench/sweb.eval.x86_64.pylons_1776_colander-321:latest", "base_commit": "b7acdff5e83e41208c323f8cac52c48ff6328a85", "num_bugs": 1, "bugs": [{"instance_id": "Pylons__colander-321", "base_commit": "b7acdff5e83e41208c323f8cac52c48ff6328a85", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 43c932c..669d34e 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -1,3 +1,10 @@\n+Unreleased\n+==========\n+\n+- Number once again will allow you to serialize None to colander.null, this\n+ reverts an accidental revert. See\n+ https://github.com/Pylons/colander/issues/204#issuecomment-459556100\n+\n 1.6.0 (2019-01-31)\n ==================\n \ndiff --git a/colander/__init__.py b/colander/__init__.py\nindex 8bddfd6..728eceb 100644\n--- a/colander/__init__.py\n+++ b/colander/__init__.py\n@@ -1399,7 +1399,7 @@ class Number(SchemaType):\n num = None\n \n def serialize(self, node, appstruct):\n- if appstruct is null:\n+ if appstruct in (null, None):\n return null\n \n try:\n", "test_patch": "diff --git a/colander/tests/test_colander.py b/colander/tests/test_colander.py\nindex 12b904e..0d911d7 100644\n--- a/colander/tests/test_colander.py\n+++ b/colander/tests/test_colander.py\n@@ -1752,6 +1752,14 @@ class TestInteger(unittest.TestCase):\n result = typ.serialize(node, val)\n self.assertEqual(result, colander.null)\n \n+ def test_serialize_none(self):\n+ import colander\n+\n+ node = DummySchemaNode(None)\n+ typ = self._makeOne()\n+ result = typ.serialize(node, None)\n+ self.assertEqual(result, colander.null)\n+\n def test_deserialize_emptystring(self):\n import colander\n \n@@ -1812,6 +1820,21 @@ class TestFloat(unittest.TestCase):\n result = typ.serialize(node, val)\n self.assertEqual(result, colander.null)\n \n+ def test_serialize_none(self):\n+ import colander\n+\n+ node = DummySchemaNode(None)\n+ typ = self._makeOne()\n+ result = typ.serialize(node, None)\n+ self.assertEqual(result, colander.null)\n+\n+ def test_serialize_zero(self):\n+ val = 0\n+ node = DummySchemaNode(None)\n+ typ = self._makeOne()\n+ result = typ.serialize(node, val)\n+ self.assertEqual(result, '0.0')\n+\n def test_serialize_emptystring(self):\n import colander\n \n@@ -1865,6 +1888,21 @@ class TestDecimal(unittest.TestCase):\n result = typ.serialize(node, val)\n self.assertEqual(result, colander.null)\n \n+ def test_serialize_none(self):\n+ import colander\n+\n+ node = DummySchemaNode(None)\n+ typ = self._makeOne()\n+ result = typ.serialize(node, None)\n+ self.assertEqual(result, colander.null)\n+\n+ def test_serialize_zero(self):\n+ val = 0\n+ node = DummySchemaNode(None)\n+ typ = self._makeOne()\n+ result = typ.serialize(node, val)\n+ self.assertEqual(result, '0')\n+\n def test_serialize_emptystring(self):\n import colander\n \n", "FAIL_TO_PASS": ["colander/tests/test_colander.py::TestInteger::test_serialize_none", "colander/tests/test_colander.py::TestFloat::test_serialize_none", "colander/tests/test_colander.py::TestDecimal::test_serialize_none"]}], "all_FAIL_TO_PASS": ["colander/tests/test_colander.py::TestInteger::test_serialize_none", "colander/tests/test_colander.py::TestFloat::test_serialize_none", "colander/tests/test_colander.py::TestDecimal::test_serialize_none"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Sceptre__sceptre-1219_x1", "level": 1, "source": "swerebench", "repo": "Sceptre/sceptre", "image": "swerebench/sweb.eval.x86_64.sceptre_1776_sceptre-1219:latest", "base_commit": "3ed957f22889a197f4b4ec585ef243a6cf34eb24", "num_bugs": 1, "bugs": [{"instance_id": "Sceptre__sceptre-1219", "base_commit": "3ed957f22889a197f4b4ec585ef243a6cf34eb24", "gold_patch": "diff --git a/sceptre/diffing/stack_differ.py b/sceptre/diffing/stack_differ.py\nindex 69011c6..87931e1 100644\n--- a/sceptre/diffing/stack_differ.py\n+++ b/sceptre/diffing/stack_differ.py\n@@ -1,7 +1,7 @@\n import difflib\n import logging\n from abc import abstractmethod\n-from typing import NamedTuple, Dict, List, Optional, Callable, Tuple, Generic, TypeVar\n+from typing import NamedTuple, Dict, List, Optional, Callable, Tuple, Generic, TypeVar, Union\n \n import cfn_flip\n import deepdiff\n@@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)\n class StackConfiguration(NamedTuple):\n \"\"\"A data container to represent the comparable parts of a Stack.\"\"\"\n stack_name: str\n- parameters: Dict[str, str]\n+ parameters: Dict[str, Union[str, List[str]]]\n stack_tags: Dict[str, str]\n notifications: List[str]\n role_arn: Optional[str]\n@@ -128,7 +128,7 @@ class StackDiffer(Generic[DiffType]):\n )\n \n def _create_generated_config(self, stack: Stack) -> StackConfiguration:\n- parameters = self._extract_parameters_dict(stack)\n+ parameters = self._extract_parameters_from_generated_stack(stack)\n stack_configuration = StackConfiguration(\n stack_name=stack.external_name,\n parameters=parameters,\n@@ -139,13 +139,9 @@ class StackDiffer(Generic[DiffType]):\n \n return stack_configuration\n \n- def _extract_parameters_dict(self, stack: Stack) -> dict:\n- \"\"\"Extracts a USABLE dict of parameters from the stack.\n-\n- Because stack parameters often contain resolvers referencing stacks that might not exist yet\n- (such as when producing a diff on a yet-to-be-deployed stack), we cannot always resolve the\n- stack parameters. Therefore, we need to resolve them (if possible) and fall back to a\n- different representation of that resolver, if necessary.\n+ def _extract_parameters_from_generated_stack(self, stack: Stack) -> dict:\n+ \"\"\"Extracts a usable dict of parameters from the stack, performing some minor transformations\n+ to match the what CloudFormation does on its end.\n \n :param stack: The stack to extract the parameters from\n :return: A dictionary of stack parameters to be compared.\n@@ -153,8 +149,8 @@ class StackDiffer(Generic[DiffType]):\n formatted_parameters = {}\n for key, value in stack.parameters.items():\n if isinstance(value, list):\n- value = ','.join(value)\n- formatted_parameters[key] = value\n+ value = ','.join(item.rstrip('\\n') for item in value)\n+ formatted_parameters[key] = value.rstrip('\\n')\n \n return formatted_parameters\n \n@@ -170,7 +166,7 @@ class StackDiffer(Generic[DiffType]):\n return None\n return StackConfiguration(\n parameters={\n- param['ParameterKey']: param['ParameterValue'].rstrip('\\n')\n+ param['ParameterKey']: param['ParameterValue']\n for param\n in stack.get('Parameters', [])\n },\n@@ -193,6 +189,14 @@ class StackDiffer(Generic[DiffType]):\n generated_template_summary = stack_actions.fetch_local_template_summary()\n \n if deployed_config is not None:\n+ # Trailing linebreaks sometimes get removed by CloudFormation in certain circumstances\n+ # and can sometimes come from using the !file_contents resolver, but ultimately they\n+ # shouldn't affect the diff. We'll ignore all trailing linebreaks.\n+ self._remove_terminating_linebreaks_from_deployed_parameters(\n+ deployed_template_summary,\n+ deployed_config\n+ )\n+\n # If the parameter is not passed by Sceptre and the value on the deployed parameter is\n # the default value, we'll actually remove it from the deployed parameters list so it\n # doesn't show up as a false positive.\n@@ -207,6 +211,27 @@ class StackDiffer(Generic[DiffType]):\n # parameter values will be masked.\n self._mask_no_echo_parameters(generated_template_summary, generated_config)\n \n+ def _remove_terminating_linebreaks_from_deployed_parameters(\n+ self,\n+ template_summary: Optional[dict],\n+ deployed_config: StackConfiguration\n+ ):\n+ if template_summary is None:\n+ return\n+\n+ parameter_types = {\n+ parameter['ParameterKey']: parameter['ParameterType']\n+ for parameter in template_summary['Parameters']\n+ }\n+\n+ for key, value in deployed_config.parameters.items():\n+ parameter_type = parameter_types[key]\n+ if parameter_type == 'CommaDelimitedList':\n+ # If it's a list of strings, remove trailing linebreaks for each item\n+ value = ','.join([item.rstrip('\\n') for item in value.split(',')])\n+\n+ deployed_config.parameters[key] = value.rstrip('\\n')\n+\n def _remove_deployed_default_parameters_that_arent_passed(\n self,\n template_summary: dict,\n", "test_patch": "diff --git a/tests/test_diffing/test_stack_differ.py b/tests/test_diffing/test_stack_differ.py\nindex 8392bfd..a416499 100644\n--- a/tests/test_diffing/test_stack_differ.py\n+++ b/tests/test_diffing/test_stack_differ.py\n@@ -353,6 +353,49 @@ class TestStackDiffer:\n self.expected_generated_config\n )\n \n+ def test_diff__parameter_has_identical_string_linebreak__compares_identical_configs(self):\n+ self.deployed_parameters['param'] = self.deployed_parameters['param'] + '\\n'\n+ self.parameters_on_stack_config['param'] = self.parameters_on_stack_config['param'] + '\\n'\n+\n+ self.differ.diff(self.actions)\n+ generated_config = deepcopy(self.expected_generated_config._asdict())\n+ generated_parameters = generated_config.pop('parameters')\n+ expected_config = StackConfiguration(\n+ parameters={\n+ key: value.rstrip('\\n')\n+ for key, value in generated_parameters.items()\n+ },\n+ **generated_config,\n+ )\n+\n+ self.command_capturer.compare_stack_configurations.assert_called_with(\n+ expected_config,\n+ expected_config\n+ )\n+\n+ def test_diff__parameter_has_identical_list_linebreaks__compares_identical_configs(self):\n+ self.deployed_parameter_types['param'] = 'CommaDelimitedList'\n+ self.deployed_parameters['param'] = 'testing\\n,this\\n,out\\n'\n+ self.parameters_on_stack_config['param'] = [\n+ 'testing\\n',\n+ 'this\\n',\n+ 'out\\n'\n+ ]\n+\n+ self.differ.diff(self.actions)\n+ generated_config = deepcopy(self.expected_generated_config._asdict())\n+ generated_parameters = generated_config.pop('parameters')\n+ generated_parameters['param'] = 'testing,this,out'\n+ expected_config = StackConfiguration(\n+ parameters=generated_parameters,\n+ **generated_config,\n+ )\n+\n+ self.command_capturer.compare_stack_configurations.assert_called_with(\n+ expected_config,\n+ expected_config\n+ )\n+\n def test_diff__no_echo_default_parameter__generated_stack_doesnt_pass_parameter__compares_identical_configs(self):\n self.deployed_parameters['new'] = '****'\n self.deployed_parameter_defaults['new'] = 'default value'\n", "FAIL_TO_PASS": ["tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__parameter_has_identical_string_linebreak__compares_identical_configs", "tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__parameter_has_identical_list_linebreaks__compares_identical_configs"]}], "all_FAIL_TO_PASS": ["tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__parameter_has_identical_string_linebreak__compares_identical_configs", "tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__parameter_has_identical_list_linebreaks__compares_identical_configs"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "CODAIT__exchange-metadata-converter-25_x1", "level": 1, "source": "swerebench", "repo": "CODAIT/exchange-metadata-converter", "image": "swerebench/sweb.eval.x86_64.codait_1776_exchange-metadata-converter-25:latest", "base_commit": "a5432d877fe947a12c169d2d84c22e034d555289", "num_bugs": 1, "bugs": [{"instance_id": "CODAIT__exchange-metadata-converter-25", "base_commit": "a5432d877fe947a12c169d2d84c22e034d555289", "gold_patch": "diff --git a/metadata_converter/apply.py b/metadata_converter/apply.py\nindex f20d451..34cd14f 100644\n--- a/metadata_converter/apply.py\n+++ b/metadata_converter/apply.py\n@@ -16,6 +16,8 @@\n from argparse import ArgumentParser\n from pathlib import Path\n from ruamel.yaml import YAML\n+from ruamel.yaml.tokens import CommentToken\n+from ruamel.yaml.comments import CommentedMap\n import re\n import sys\n \n@@ -48,11 +50,70 @@ def replace(yaml_dict, template_dict):\n :rtype: dict\n \"\"\"\n \n+ def get_metadata(template_dict, key):\n+ # If d is an instance of ruamel.yaml.comments.CommentedMap\n+ # this method returns the metadata associated with the\n+ # provided property key\n+\n+ if not isinstance(template_dict, CommentedMap):\n+ return None\n+\n+ d = template_dict\n+\n+ metadata = {\n+ 'comment': None,\n+ 'comment_text': None,\n+ 'annotations': set()\n+ }\n+ # raw comment, e.g. \"# @optional another comment\\n\"\n+ if key in d.ca.items:\n+ if (len(d.ca.items.get(key)) > 2) and \\\n+ isinstance(d.ca.items.get(key)[2], CommentToken):\n+ metadata['comment'] = d.ca.items.get(key)[2].value\n+ # comment text, e.g. \"another comment\"\n+ metadata['comment_text'] = metadata['comment']\n+ # extract embedded annotations, e.g. \"@optional\"\n+ if metadata['comment'] is not None:\n+ # Extract @... annotations\n+ for match in re.finditer('@([a-zA-Z]+)',\n+ metadata['comment'],\n+ re.I):\n+ metadata['annotations'].add(match.group(1).lower())\n+ # Remove noise from the comment, such as annotations\n+ # comment characters and whitespace characters\n+ # - Remove annotations\n+ for annotation in metadata['annotations']:\n+ metadata['comment_text'] =\\\n+ metadata['comment_text'].replace('@{}'.format(annotation),\n+ '')\n+ # - Remove '#' and whitespaces from the beginning of each line\n+ # This needs to be done twice to handle empty comments properly.\n+ metadata['comment_text'] = re.sub(r'^\\s*#\\s*',\n+ '',\n+ metadata['comment_text'],\n+ flags=re.MULTILINE)\n+ metadata['comment_text'] = re.sub(r'^\\s*#\\s*',\n+ '',\n+ metadata['comment_text'],\n+ flags=re.MULTILINE)\n+ # - remove whitespace chars from the end of each line\n+ metadata['comment_text'] = re.sub(r'\\s*$',\n+ '',\n+ metadata['comment_text'],\n+ flags=re.MULTILINE)\n+\n+ # - remove newline from the end\n+ metadata['comment_text'] = metadata['comment_text'].strip()\n+\n+ if len(metadata['comment_text']) == 0:\n+ metadata['comment_text'] = None\n+ return metadata\n+\n # pre-compile the {{...}} placeholder search expression\n # outside `do_replace` to avoid doing it multiple times\n p = re.compile(r'{{([\\w\\.]+)}}', re.VERBOSE)\n \n- def process_string(yaml_dict, str):\n+ def process_string(yaml_dict, str, metadata):\n # determine whether {{...}} placeholder\n # replacement is required\n r = p.search(str)\n@@ -63,19 +124,25 @@ def replace(yaml_dict, template_dict):\n for property in r.group(1).split('.'):\n root = root.get(property)\n if root is None:\n- raise PlaceholderNotFoundError(r.group(1))\n+ # check annotations to determine appropriate\n+ # behavior\n+ if metadata is not None and\\\n+ 'optional' in metadata['annotations']:\n+ return None\n+ else:\n+ raise PlaceholderNotFoundError(r.group(1))\n return root\n \n- def process_list(yaml_dict, list_in):\n+ def process_list(yaml_dict, list_in, metadata):\n list_out = []\n for v in list_in:\n # if v is a string process it\n if(isinstance(v, str)):\n- list_out.append(process_string(yaml_dict, v))\n+ list_out.append(process_string(yaml_dict, v, metadata))\n elif(isinstance(v, dict)):\n list_out.append(do_replace(yaml_dict, v))\n elif(isinstance(v, list)):\n- list_out.append(process_list(yaml_dict, v))\n+ list_out.append(process_list(yaml_dict, v, metadata))\n else:\n raise NotImplementedError(\n 'Support for properties of type {} in lists '\n@@ -103,18 +170,23 @@ def replace(yaml_dict, template_dict):\n for key in template_dict.keys():\n val = template_dict[key]\n # print('Key: {} Value: {} Type: {}'.format(key, val, type(val)))\n+ metadata = get_metadata(template_dict, key)\n if val is None:\n # NoneType - no value\n template_out[key] = None\n elif isinstance(val, str):\n # process string\n- template_out[key] = process_string(yaml_dict, val)\n+ template_out[key] = process_string(yaml_dict,\n+ val,\n+ metadata)\n elif isinstance(val, dict):\n # process the dictionary recursively\n template_out[key] = do_replace(yaml_dict, val)\n elif isinstance(val, list):\n # process each list item\n- template_out[key] = process_list(yaml_dict, val)\n+ template_out[key] = process_list(yaml_dict,\n+ val,\n+ metadata)\n else:\n raise NotImplementedError(\n 'Support for properties of type {} is not implemented.'\ndiff --git a/setup.py b/setup.py\nindex d3a2bc7..5ab9ac3 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -22,7 +22,7 @@ with open('README.md') as readme:\n setup(\n name='exchange-metadata-converter',\n packages=find_packages(),\n- version='0.0.6',\n+ version='0.0.7',\n license='Apache-2.0',\n description='exchange metadata converters',\n long_description=README,\n", "test_patch": "diff --git a/tests/inputs/annotations.yaml b/tests/inputs/annotations.yaml\nnew file mode 100644\nindex 0000000..84678c1\n--- /dev/null\n+++ b/tests/inputs/annotations.yaml\n@@ -0,0 +1,6 @@\n+# This YAML document does not define the following properties:\n+# noprop1value, noprop2value, noprop3value, noprop3value,\n+# noprop4value, noprop5value, noprop6value\n+unused_property: True\n+hey:\n+ we_are_a_match: 'Then let us pair up!'\n\\ No newline at end of file\ndiff --git a/tests/templates/annotations.yaml b/tests/templates/annotations.yaml\nnew file mode 100644\nindex 0000000..890c6e3\n--- /dev/null\n+++ b/tests/templates/annotations.yaml\n@@ -0,0 +1,46 @@\n+# test level-0 properties; each one is annotated with\n+# optional and should therefore not raise an error\n+property1: '{{noprop1value}}' # @optional\n+property2: '{{noprop2value}}' # comment @optional\n+property3: '{{noprop3value}}' # more comments @optional\n+property4: '{{noprop4value}}' # more @optional comments\n+property5: '{{noprop5value}}' # more @bogus comments @optional\n+property6: '{{noprop6value}}' # more \n+ # @bogus comments\n+ # \n+ # @optional\n+property7:\n+ property8: '{{noprop8value}}' # property8 is\n+ # \n+ # an @optional property\n+ # we are @very @very @lucky\n+property9: # annotations work in dicts\n+ property10:\n+ property11: '{{noprop11value}}' # this @optional property\n+ # is @fine\n+property12: # annotations work in lists\n+ - property12a: '{{hey.we_are_a_match}}' # @optional does not apply\n+ property12b: '{{noprop12bvalue}}' # sweet, it's @optional\n+ property12c: a_constant!\n+property13: # annotations are case insensitive\n+ property14: \n+ property15:\n+ property16a: '{{noprop16avalue}}' # @OPTIONAL\n+ property16b: '{{noprop16bvalue}}' # an @Optional property\n+ property16c: '{{noprop16cvalue}}' # another @OptioNAl property\n+ property17: all is good # Nothing @opTioNAL here\n+ property18: '{{hey.we_are_a_match}}'# nothing @OPTIONal here either\n+---\n+property1: '{{noprop1value}}' #\n+---\n+property1: '{{noprop1value}}' # just a comment\n+---\n+property1: '{{noprop1value}}' # @notarecognizedannotation\n+---\n+property1: '{{noprop1value}}' # more\n+ # is not always @better\n+ #\n+---\n+property1: # @optional does not apply\n+ property1a: '{{noprop1avalue}}' # because we fail here\n+\ndiff --git a/tests/test_annotations.py b/tests/test_annotations.py\nnew file mode 100644\nindex 0000000..e11616d\n--- /dev/null\n+++ b/tests/test_annotations.py\n@@ -0,0 +1,114 @@\n+#\n+# Copyright 2020 IBM Corporation\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+from metadata_converter.apply import replace\n+from metadata_converter.apply import PlaceholderNotFoundError\n+from pathlib import Path\n+from ruamel.yaml import YAML\n+import unittest\n+\n+yaml = YAML()\n+yaml.default_flow_style = False\n+\n+#\n+# Tests template annotations: @optional\n+#\n+\n+\n+class TestAnnotations(unittest.TestCase):\n+\n+ def setUp(self):\n+\n+ self.placeholder_file = 'tests/inputs/annotations.yaml'\n+\n+ self.in_yamls = yaml.load(Path(self.placeholder_file))\n+\n+ self.template_file = 'tests/templates/annotations.yaml'\n+\n+ self.template_yamls = list(yaml.load_all(Path(self.template_file)))\n+ self.assertEqual(len(self.template_yamls), 6)\n+\n+ def test_optional_annotation(self):\n+\n+ try:\n+ out_dict = replace(self.in_yamls, self.template_yamls[0])\n+ self.assertTrue(out_dict is not None)\n+ self.assertTrue(isinstance(out_dict, dict))\n+ self.assertIsNone(out_dict['property1'])\n+ self.assertIsNone(out_dict['property2'])\n+ self.assertIsNone(out_dict['property3'])\n+ self.assertIsNone(out_dict['property4'])\n+ self.assertIsNone(out_dict['property5'])\n+ self.assertIsNone(out_dict['property6'])\n+ self.assertIsNone(out_dict['property7']['property8'])\n+ self.assertIsNone(\n+ out_dict['property9']['property10']['property11'])\n+ self.assertEqual(\n+ out_dict['property12'][0]['property12a'],\n+ self.in_yamls['hey']['we_are_a_match'])\n+ self.assertIsNone(\n+ out_dict['property12'][0]['property12b'])\n+ self.assertEqual(\n+ self.template_yamls[0]['property12'][0]['property12c'],\n+ out_dict['property12'][0]['property12c'])\n+ self.assertIsNone(\n+ out_dict['property13']['property14']\n+ ['property15']['property16a'])\n+ self.assertIsNone(\n+ out_dict['property13']['property14']\n+ ['property15']['property16b'])\n+ self.assertIsNone(\n+ out_dict['property13']['property14']\n+ ['property15']['property16c'])\n+ self.assertEqual(out_dict['property13']\n+ ['property14']['property17'],\n+ self.template_yamls[0]['property13']['property14']\n+ ['property17'])\n+ self.assertEqual(out_dict['property13']\n+ ['property14']['property18'],\n+ self.in_yamls['hey']['we_are_a_match'])\n+ except Exception as e:\n+ self.assertTrue(False, e)\n+\n+ def test_without_optional_annotation(self):\n+\n+ # self.template_yamls contains multipe documents with\n+ # references to an undefined placeholder\n+ for index in [1, 2, 3, 4]:\n+ try:\n+ # should fail\n+ replace(self.in_yamls, self.template_yamls[index])\n+ self.assertTrue(False)\n+ except PlaceholderNotFoundError as pnfe:\n+ self.assertEqual('{{' + pnfe.placeholder + '}}',\n+ self.template_yamls[index]['property1'])\n+ except Exception as e:\n+ self.assertTrue(False, e)\n+\n+ for index in [5]:\n+ try:\n+ # should fail\n+ replace(self.in_yamls, self.template_yamls[index])\n+ self.assertTrue(False)\n+ except PlaceholderNotFoundError as pnfe:\n+ self.assertEqual('{{' + pnfe.placeholder + '}}',\n+ self.template_yamls[index]\n+ .get('property1').get('property1a'))\n+ except Exception as e:\n+ self.assertTrue(False, e)\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\n", "FAIL_TO_PASS": ["tests/test_annotations.py::TestAnnotations::test_optional_annotation"]}], "all_FAIL_TO_PASS": ["tests/test_annotations.py::TestAnnotations::test_optional_annotation"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "FactoryBoy__factory_boy-1067_x1", "level": 1, "source": "swerebench", "repo": "FactoryBoy/factory_boy", "image": "swerebench/sweb.eval.x86_64.factoryboy_1776_factory_boy-1067:latest", "base_commit": "7ed1e5417e06c3d83e0495a67508b3868de53823", "num_bugs": 1, "bugs": [{"instance_id": "FactoryBoy__factory_boy-1067", "base_commit": "7ed1e5417e06c3d83e0495a67508b3868de53823", "gold_patch": "diff --git a/factory/declarations.py b/factory/declarations.py\nindex 70abe35..951b45f 100644\n--- a/factory/declarations.py\n+++ b/factory/declarations.py\n@@ -536,7 +536,7 @@ class Maybe(BaseDeclaration):\n return target\n \n def evaluate_pre(self, instance, step, overrides):\n- choice = self.decider.evaluate(instance=instance, step=step, extra={})\n+ choice = self.decider.evaluate_pre(instance=instance, step=step, overrides={})\n target = self.yes if choice else self.no\n # The value can't be POST_INSTANTIATION, checked in __init__;\n # evaluate it as `evaluate_pre`\n", "test_patch": "diff --git a/tests/test_regression.py b/tests/test_regression.py\nindex a9ea1c6..2cca0bd 100644\n--- a/tests/test_regression.py\n+++ b/tests/test_regression.py\n@@ -51,3 +51,24 @@ class FakerRegressionTests(unittest.TestCase):\n \n unknown_author = AuthorFactory(unknown=True)\n self.assertEqual(\"\", unknown_author.fullname)\n+\n+ def test_evaluated_without_locale(self):\n+ \"\"\"Regression test for `KeyError: 'locale'` raised in `evaluate`.\n+\n+ See #965\n+\n+ \"\"\"\n+ class AuthorFactory(factory.Factory):\n+ fullname = factory.Faker(\"name\")\n+ pseudonym = factory.Maybe(\n+ decider=factory.Faker(\"pybool\"),\n+ yes_declaration=\"yes\",\n+ no_declaration=\"no\",\n+ )\n+\n+ class Meta:\n+ model = Author\n+\n+ author = AuthorFactory()\n+\n+ self.assertIn(author.pseudonym, [\"yes\", \"no\"])\n", "FAIL_TO_PASS": ["tests/test_regression.py::FakerRegressionTests::test_evaluated_without_locale"]}], "all_FAIL_TO_PASS": ["tests/test_regression.py::FakerRegressionTests::test_evaluated_without_locale"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Shopify__shopify_python_api-177_x1", "level": 1, "source": "swerebench", "repo": "Shopify/shopify_python_api", "image": "swerebench/sweb.eval.x86_64.shopify_1776_shopify_python_api-177:latest", "base_commit": "c29e0ecbed9de67dd923f980a3ac053922dab75e", "num_bugs": 1, "bugs": [{"instance_id": "Shopify__shopify_python_api-177", "base_commit": "c29e0ecbed9de67dd923f980a3ac053922dab75e", "gold_patch": "diff --git a/shopify/resources/image.py b/shopify/resources/image.py\nindex a0e82ef..b408261 100644\n--- a/shopify/resources/image.py\n+++ b/shopify/resources/image.py\n@@ -23,7 +23,7 @@ class Image(ShopifyResource):\n return super(Image, self).__getattr__(name)\n \n def attach_image(self, data, filename=None):\n- self.attributes[\"attachment\"] = base64.b64encode(data)\n+ self.attributes[\"attachment\"] = base64.b64encode(data).decode()\n if filename:\n self.attributes[\"filename\"] = filename\n \n", "test_patch": "diff --git a/test/image_test.py b/test/image_test.py\nindex 1234898..bde789e 100644\n--- a/test/image_test.py\n+++ b/test/image_test.py\n@@ -1,5 +1,6 @@\n import shopify\n from test.test_helper import TestCase\n+import base64\n \n class ImageTest(TestCase):\n \n@@ -13,6 +14,19 @@ class ImageTest(TestCase):\n self.assertEqual('http://cdn.shopify.com/s/files/1/0006/9093/3842/products/ipod-nano.png?v=1389388540', image.src)\n self.assertEqual(850703190, image.id)\n \n+ def test_attach_image(self):\n+ self.fake(\"products/632910392/images\", method='POST', body=self.load_fixture('image'), headers={'Content-type': 'application/json'})\n+ image = shopify.Image({'product_id':632910392})\n+ image.position = 1\n+ binary_in = base64.b64decode(\"R0lGODlhbgCMAPf/APbr48VySrxTO7IgKt2qmKQdJeK8lsFjROG5p/nz7Zg3MNmnd7Q1MLNVS9GId71hSJMZIuzTu4UtKbeEeakhKMl8U8WYjfr18YQaIbAf==\")\n+ image.attach_image(data=binary_in, filename='ipod-nano.png')\n+ image.save()\n+ binary_out = base64.b64decode(image.attachment)\n+\n+ self.assertEqual('http://cdn.shopify.com/s/files/1/0006/9093/3842/products/ipod-nano.png?v=1389388540', image.src)\n+ self.assertEqual(850703190, image.id)\n+ self.assertEqual(binary_in, binary_out)\n+\n def test_create_image_then_add_parent_id(self):\n self.fake(\"products/632910392/images\", method='POST', body=self.load_fixture('image'), headers={'Content-type': 'application/json'})\n image = shopify.Image()\n", "FAIL_TO_PASS": ["test/image_test.py::ImageTest::test_attach_image"]}], "all_FAIL_TO_PASS": ["test/image_test.py::ImageTest::test_attach_image"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Benardi__touvlo-34_x1", "level": 1, "source": "swerebench", "repo": "Benardi/touvlo", "image": "swerebench/sweb.eval.x86_64.benardi_1776_touvlo-34:latest", "base_commit": "0e1ee71ebec9a09370f928dd96d0ae11f3bba404", "num_bugs": 1, "bugs": [{"instance_id": "Benardi__touvlo-34", "base_commit": "0e1ee71ebec9a09370f928dd96d0ae11f3bba404", "gold_patch": "diff --git a/touvlo/utils.py b/touvlo/utils.py\nindex fdf47db..ca8531c 100644\n--- a/touvlo/utils.py\n+++ b/touvlo/utils.py\n@@ -35,7 +35,7 @@ def g_grad(x):\n \n \n def gradient_descent(X, y, grad, initial_theta,\n- alpha, num_iters, _lambda=None):\n+ alpha, num_iters, **kwargs):\n \"\"\"This function performs parameter optimization via gradient descent.\n \n :param X: Features' dataset plus bias column.\n@@ -56,22 +56,12 @@ def gradient_descent(X, y, grad, initial_theta,\n :param num_iters: Number of times the optimization will be performed.\n :type num_iters: int\n \n- :param _lambda: Weight of the penalty term.\n- :type _lambda: float\n-\n :returns: Optimized model parameters.\n :rtype: numpy.array\n \"\"\"\n- if _lambda is not None:\n- theta = copy(initial_theta)\n-\n- for _ in range(num_iters):\n- theta = theta - alpha * grad(theta, X, y, _lambda)\n-\n- else:\n- theta = copy(initial_theta)\n- for _ in range(num_iters):\n- theta = theta - alpha * grad(theta, X, y)\n+ theta = copy(initial_theta)\n+ for _ in range(num_iters):\n+ theta = theta - alpha * grad(X, y, theta, **kwargs)\n \n return theta\n \n", "test_patch": "diff --git a/tests/test_utils.py b/tests/test_utils.py\nindex d695ead..5adeb9b 100644\n--- a/tests/test_utils.py\n+++ b/tests/test_utils.py\n@@ -4,7 +4,7 @@ import pytest\n from numpy import array, cos, sin, exp\n from numpy.testing import assert_allclose\n \n-from touvlo.utils import numerical_grad, g_grad\n+from touvlo.utils import numerical_grad, g_grad, gradient_descent\n \n \n class TestLogisticRegression:\n@@ -82,3 +82,45 @@ class TestLogisticRegression:\n assert_allclose(g_grad(z),\n [0.196612, 0.235004, 0.25, 0.235004, 0.196612],\n rtol=0, atol=0.001, equal_nan=False)\n+\n+ def test_gradient_descent1(self, err):\n+ def grad(X, y, theta):\n+ m = len(y)\n+ grad = (1 / m) * (X.T).dot(X.dot(theta) - y)\n+ return grad\n+\n+ X = array([[0, 1, 2], [-1, 5, 3], [2, 0, 1]])\n+ initial_theta = array([[0], [0], [0]])\n+ y = array([[0.3], [1.2], [0.5]])\n+ num_iters = 3\n+ alpha = 1\n+\n+ assert_allclose(array([[-46.415], [276.248], [192.204]]),\n+ gradient_descent(X, y, grad, initial_theta,\n+ alpha, num_iters),\n+ rtol=0, atol=0.001, equal_nan=False)\n+\n+ def test_gradient_descent2(self, err):\n+ def grad(X, y, theta, schleem, plumbus, wubba, lubba):\n+ m = len(y)\n+ grad = (schleem / (m * wubba))\n+ grad = grad * (X.T).dot(X.dot(theta) - y)\n+ grad = grad + plumbus / (2 * lubba)\n+ return grad\n+\n+ X = array([[0, 1, 2], [-1, 5, 3], [2, 0, 1]])\n+ initial_theta = array([[0], [0], [0]])\n+ y = array([[0.3], [1.2], [0.5]])\n+ num_iters = 5\n+ plumbus = 0.8\n+ schleem = 0.6\n+ wubba = 3.4\n+ lubba = 2.7\n+ alpha = 0.01\n+\n+ assert_allclose(array([[-0.0078777], [0.0106179], [0.0060865]]),\n+ gradient_descent(X, y, grad, initial_theta,\n+ alpha, num_iters, lubba=lubba,\n+ schleem=schleem, wubba=wubba,\n+ plumbus=plumbus),\n+ rtol=0, atol=0.001, equal_nan=False)\n", "FAIL_TO_PASS": ["tests/test_utils.py::TestLogisticRegression::test_gradient_descent1", "tests/test_utils.py::TestLogisticRegression::test_gradient_descent2"]}], "all_FAIL_TO_PASS": ["tests/test_utils.py::TestLogisticRegression::test_gradient_descent1", "tests/test_utils.py::TestLogisticRegression::test_gradient_descent2"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ModellingWebLab__cellmlmanip-167_x1", "level": 1, "source": "swerebench", "repo": "ModellingWebLab/cellmlmanip", "image": "swerebench/sweb.eval.x86_64.modellingweblab_1776_cellmlmanip-167:latest", "base_commit": "fc8ab9ff9b9712aab0ffe98eb376e8cba5de61c9", "num_bugs": 1, "bugs": [{"instance_id": "ModellingWebLab__cellmlmanip-167", "base_commit": "fc8ab9ff9b9712aab0ffe98eb376e8cba5de61c9", "gold_patch": "diff --git a/cellmlmanip/model.py b/cellmlmanip/model.py\nindex 1167056..5e014f6 100644\n--- a/cellmlmanip/model.py\n+++ b/cellmlmanip/model.py\n@@ -198,13 +198,13 @@ class Model(object):\n rhs_units, self.units.ureg.get_base_units(rhs_units)\n )\n \n- def get_equations_for(self, symbols, lexicographical_sort=True, recurse=True, strip_units=True):\n+ def get_equations_for(self, symbols, recurse=True, strip_units=True):\n \"\"\"Get all equations for a given collection of symbols.\n \n- Results are sorted in topographical order.\n- :param symbols: the symbols to get the equations for\n- :param lexicographical_sort: indicates whether the result is sorted in lexicographical order first\n- :param recurse: indicates whether to recurse the equation graph, or to return only the top level equations\n+ Results are sorted first by dependencies, then by variable name.\n+\n+ :param symbols: the symbols to get the equations for.\n+ :param recurse: indicates whether to recurse the equation graph, or to return only the top level equations.\n :param strip_units: if ``True``, all ``sympy.Dummy`` objects representing number with units will be replaced\n with ordinary sympy number objects.\n \"\"\"\n@@ -215,10 +215,7 @@ class Model(object):\n graph = self.graph\n \n # Get sorted list of symbols\n- if lexicographical_sort:\n- sorted_symbols = nx.lexicographical_topological_sort(graph, key=str)\n- else:\n- sorted_symbols = nx.topological_sort(graph)\n+ sorted_symbols = nx.lexicographical_topological_sort(graph, key=str)\n \n # Create set of symbols for which we require equations\n required_symbols = set()\n@@ -506,7 +503,20 @@ class Model(object):\n \n # And replace the equation with one with the rhs subbed with sympy.Number objects\n if subs_dict:\n- graph.nodes[node]['equation'] = sympy.Eq(equation.lhs, equation.rhs.subs(subs_dict))\n+ # Update rhs\n+ rhs = equation.rhs.subs(subs_dict)\n+\n+ # Check if simplification removed dependencies on other variables, and if so remove the corresponding\n+ # edges.\n+ refs = self.find_symbols_and_derivatives([rhs])\n+ edges = list(graph.in_edges(equation.lhs))\n+ for edge in edges:\n+ ref = edge[0]\n+ if ref not in refs:\n+ graph.remove_edge(ref, equation.lhs)\n+\n+ # Replace equation\n+ graph.nodes[node]['equation'] = sympy.Eq(equation.lhs, rhs)\n \n # Cache graph and return\n self._graph_with_sympy_numbers = graph\n", "test_patch": "diff --git a/tests/test_model_functions.py b/tests/test_model_functions.py\nindex 58dd7a7..0cff687 100644\n--- a/tests/test_model_functions.py\n+++ b/tests/test_model_functions.py\n@@ -4,7 +4,7 @@ import pytest\n import sympy as sp\n \n from cellmlmanip import parser\n-from cellmlmanip.model import VariableDummy\n+from cellmlmanip.model import Model, VariableDummy\n \n from . import shared\n \n@@ -154,93 +154,123 @@ class TestModelFunctions():\n 'Derivative(_Ca_handling_by_the_SR$F2, _environment$time), '\\\n 'Derivative(_Ca_handling_by_the_SR$F3, _environment$time)]'\n \n- # also tested by model_units\n- def test_get_equations_for(self, basic_model):\n- \"\"\" Tests Model.get_equations_for() works correctly.\n- Note: the basic model has 1 equation dsv11/dt = 1 which is not\n- related to a symbol and so has no equations that can be retrieved\n- by symbol\n+ def test_get_equations_for(self):\n+ \"\"\"\n+ Tests Model.get_equations_for().\n \"\"\"\n \n- symbol_a = basic_model.get_symbol_by_cmeta_id(\"sv11\")\n- equation = basic_model.get_equations_for([symbol_a])\n- assert len(equation) == 0\n-\n- symbol_t = basic_model.get_symbol_by_name(\"environment$time\")\n-\n- equation1 = basic_model.get_equations_for([symbol_t])\n- assert len(equation1) == 0\n-\n- # also tested by model_units\n- def test_get_equations_for_1(self, aslanidi_model):\n- \"\"\" Tests Model.get_equations_for() works correctly. \"\"\"\n-\n- symbol_a = aslanidi_model.get_symbol_by_ontology_term(shared.OXMETA, \"membrane_capacitance\")\n- equation = aslanidi_model.get_equations_for([symbol_a])\n- assert len(equation) == 1\n- assert equation[0].lhs == symbol_a\n- assert equation[0].rhs == 5e-5\n-\n- def test_get_equations_for_2(self, hh_model):\n- \"\"\" Tests Model.get_equations_for() works correctly. \"\"\"\n-\n- # Test get_equations_for with topgraphical lexicographical ordering\n-\n- # Get ordered equations\n- membrane_fast_sodium_current = hh_model.get_symbol_by_ontology_term(shared.OXMETA,\n- 'membrane_fast_sodium_current')\n- equations = hh_model.get_equations_for([membrane_fast_sodium_current])\n- top_level_equations = hh_model.get_equations_for([membrane_fast_sodium_current], recurse=False)\n-\n- # There should be 4 in this model\n- assert len(equations) == 4\n-\n- # There should be 3 top level (non recursed) in this model\n- assert len(top_level_equations) == 3\n-\n- # Expected equations\n- ER = sp.Eq(sp.Dummy('membrane$E_R'), sp.numbers.Float(-75.0))\n- ENa = sp.Eq(sp.Dummy('sodium_channel$E_Na'),\n- sp.add.Add(sp.Dummy('membrane$E_R'), sp.numbers.Float(115.0)))\n- gNa = sp.Eq(sp.Dummy('sodium_channel$g_Na'), sp.numbers.Float(120.0))\n- iNa = sp.Eq(sp.Dummy('sodium_channel$i_Na'),\n- sp.Dummy('sodium_channel_m_gate$m') ** 3.0 * sp.Dummy('sodium_channel$g_Na') *\n- sp.Dummy('sodium_channel_h_gate$h') * (sp.Dummy('membrane$V') -\n- sp.Dummy('sodium_channel$E_Na')))\n-\n- # Get order as strings, for easy comparison\n- ER, ENa, gNa, iNa = str(ER), str(ENa), str(gNa), str(iNa)\n- expected_order = [ER, ENa, gNa, iNa]\n-\n- # Check equations against expected equations\n- equations = [str(eq) for eq in equations]\n- assert equations == expected_order\n-\n- # Check topologically (but not lexicographically) ordered equations\n- unordered_equations = hh_model.get_equations_for([membrane_fast_sodium_current], False)\n- unordered_equations = [str(eq) for eq in unordered_equations]\n-\n- # Each equation should be both in the ordered and unordered equations\n- assert set(unordered_equations) == set(equations)\n-\n- # ER should come before ENa\n- assert unordered_equations.index(ER) < unordered_equations.index(ENa)\n-\n- # ENa and gNa should come before iNa\n- assert unordered_equations.index(ENa) < unordered_equations.index(iNa)\n- assert unordered_equations.index(gNa) < unordered_equations.index(iNa)\n-\n- def test_get_equations_for_with_dummies(self, hh_model):\n-\n- # Tests using get_equations_for without replacing dummies with sp numbers\n- # Get ordered equations\n- ina = hh_model.get_symbol_by_ontology_term(shared.OXMETA, 'membrane_fast_sodium_current')\n- equations = hh_model.get_equations_for([ina], recurse=False, strip_units=False)\n-\n- for eq in equations:\n- if eq.lhs.name == 'sodium_channel$g_Na':\n- assert isinstance(eq.rhs, sp.Dummy)\n- break\n+ m = Model('simplification')\n+ u = 'dimensionless'\n+ t = m.add_variable('t', u)\n+ y1 = m.add_variable('y1', u, initial_value=10)\n+ y2 = m.add_variable('y2', u, initial_value=20)\n+ y3 = m.add_variable('y3', u, initial_value=30)\n+ v1 = m.add_variable('v1', u)\n+ v2 = m.add_variable('v2', u)\n+ v3 = m.add_variable('v3', u)\n+ v4 = m.add_variable('v4', u)\n+ v5 = m.add_variable('v5', u)\n+ a1 = m.add_variable('a1', u)\n+\n+ # dy1/dt = 1\n+ m.add_equation(sp.Eq(sp.Derivative(y1, t), m.add_number(1, u)))\n+ # dy2/dt = v1 --> Doesn't simplify, reference to v1 is maintained\n+ m.add_equation(sp.Eq(sp.Derivative(y2, t), v1))\n+ # dy3/dt = v2 * (2 + dy1/dt)\n+ m.add_equation(sp.Eq(sp.Derivative(y3, t), sp.Mul(v2, sp.Add(m.add_number(2, u), sp.Derivative(y1, t)))))\n+ # v1 = (5 - 5) * v3 --> Simplifies to 0\n+ m.add_equation(sp.Eq(v1, sp.Mul(sp.Add(m.add_number(5, u), m.add_number(-5, u)), v3)))\n+ # v2 = 23 + v4 --> Doesn't simplify, reference to v4 is maintained\n+ m.add_equation(sp.Eq(v2, sp.Add(m.add_number(23, u), v4)))\n+ # v3 = 2 / 3\n+ m.add_equation(sp.Eq(v3, sp.Mul(m.add_number(2, u), sp.Pow(m.add_number(3, u), sp.S.NegativeOne))))\n+ # v4 = -23\n+ m.add_equation(sp.Eq(v4, m.add_number(-23, u)))\n+ # v5 = v3 + v4\n+ m.add_equation(sp.Eq(v5, sp.Add(v3, v4)))\n+ # a1 = v5 + v2 + v1 + t\n+ m.add_equation(sp.Eq(a1, sp.Add(v5, v2, v1, t)))\n+\n+ # Simplified equations\n+ e_v1 = sp.Eq(v1, sp.Number(0))\n+ e_v2 = sp.Eq(v2, sp.Add(v4, sp.Number(23)))\n+ e_v3 = sp.Eq(v3, sp.Number(2 / 3))\n+ e_v4 = sp.Eq(v4, sp.Number(-23))\n+ e_v5 = sp.Eq(v5, sp.Add(v3, v4))\n+ e_a1 = sp.Eq(a1, sp.Add(v1, v2, v5, t))\n+\n+ d_y1 = sp.Derivative(y1, t)\n+ d_y2 = sp.Derivative(y2, t)\n+ d_y3 = sp.Derivative(y3, t)\n+\n+ e_y1 = sp.Eq(d_y1, sp.Number(1))\n+ e_y2 = sp.Eq(d_y2, v1)\n+ e_y3 = sp.Eq(d_y3, sp.Mul(v2, sp.Add(sp.Number(2), d_y1)))\n+\n+ # v1 with simplification: [v1=0] (simplified)\n+ eqs = m.get_equations_for([v1])\n+ assert eqs[0] == e_v1\n+ assert len(eqs) == 1\n+\n+ # v1 without simplification: [v3=2/3, v1=(5-5)*v3]\n+ eqs = m.get_equations_for([v1], strip_units=False)\n+ assert eqs[0] == m.graph.nodes[v3]['equation']\n+ assert eqs[1] == m.graph.nodes[v1]['equation']\n+ assert len(eqs) == 2\n+\n+ # dy1/dt with simplification: [dy1/dt=1]\n+ eqs = m.get_equations_for([d_y1])\n+ assert eqs[0] == e_y1\n+ assert len(eqs) == 1\n+\n+ # dy2/dt with simplification: [v1=0, dy2/dt=v1]\n+ eqs = m.get_equations_for([d_y2])\n+ assert eqs[0] == e_v1\n+ assert eqs[1] == e_y2\n+ assert len(eqs) == 2\n+\n+ # dy2/dt without simplification: [v3=2/3, v1=(5-5)*v3, dy2/dt=v1]\n+ eqs = m.get_equations_for([d_y2], strip_units=False)\n+ assert eqs[0] == m.graph.nodes[v3]['equation']\n+ assert eqs[1] == m.graph.nodes[v1]['equation']\n+ assert eqs[2] == m.graph.nodes[d_y2]['equation']\n+ assert len(eqs) == 3\n+\n+ # dy3/dt with simpification: [dy1/dt=1, v4=-23, v2=v4+23, dy2/dt=v2*(2+dy1/dt)]\n+ eqs = m.get_equations_for([d_y3])\n+ assert e_y3 in eqs\n+ assert e_y1 in eqs\n+ assert e_v2 in eqs\n+ assert e_v4 in eqs\n+ assert len(eqs) == 4\n+\n+ # a1 with simplification: [v1=0, v3=2/3, v4=-23, v2=v4+23, v5=v3+v4, a1=v1+v2+v5]\n+ eqs = m.get_equations_for([a1])\n+ assert eqs[0] == e_v1\n+ assert eqs[1] == e_v3\n+ assert eqs[2] == e_v4\n+ assert eqs[3] == e_v2\n+ assert eqs[4] == e_v5\n+ assert eqs[5] == e_a1\n+ assert len(eqs) == 6\n+\n+ # a1 with only one level of recursion\n+ eqs = m.get_equations_for([a1], recurse=False)\n+ assert eqs[0] == e_v1\n+ assert eqs[1] == e_v2\n+ assert eqs[2] == e_v5\n+ assert eqs[3] == e_a1\n+ assert len(eqs) == 4\n+\n+ # Multiple input symbols: [d_y1=1, v1=0, d_y2=v1, v4=-23, v2=23+v4, d_y3=v2*(2+d_y1)]\n+ eqs = m.get_equations_for([d_y1, d_y2, d_y3])\n+ assert eqs[0] == e_y1\n+ assert eqs[1] == e_v1\n+ assert eqs[2] == e_y2\n+ assert eqs[3] == e_v4\n+ assert eqs[4] == e_v2\n+ assert eqs[5] == e_y3\n+ assert len(eqs) == 6\n \n def test_get_value(self, aslanidi_model):\n \"\"\" Tests Model.get_value() works correctly. \"\"\"\ndiff --git a/tests/test_model_units.py b/tests/test_model_units.py\nindex 6db3b26..79f184c 100644\n--- a/tests/test_model_units.py\n+++ b/tests/test_model_units.py\n@@ -12,25 +12,6 @@ class TestModelUnits:\n symbol = simple_units_model.get_symbol_by_cmeta_id(\"b\")\n assert symbol.is_Symbol\n \n- def test_equations(self, simple_units_model):\n- \"\"\" Tests the Model.get_equations_for function.\"\"\"\n- symbol_a = simple_units_model.get_symbol_by_cmeta_id(\"a\")\n- equation = simple_units_model.get_equations_for([symbol_a])\n- assert len(equation) == 1\n- assert equation[0].lhs == symbol_a\n- assert equation[0].rhs == 1.0\n-\n- def test_equations_2(self, simple_units_model):\n- \"\"\" Tests the Model.get_equations_for function. \"\"\"\n- symbol_a = simple_units_model.get_symbol_by_cmeta_id(\"a\")\n- symbol_b = simple_units_model.get_symbol_by_cmeta_id(\"b\")\n- equation = simple_units_model.get_equations_for([symbol_b])\n- assert len(equation) == 2\n- assert equation[0].lhs == symbol_a\n- assert equation[0].rhs == 1.0\n- assert equation[1].lhs == symbol_b\n- assert equation[1].rhs == 2.0 / symbol_a\n-\n def test_units(self, simple_units_model):\n \"\"\" Tests units read and calculated from a model. \"\"\"\n symbol_a = simple_units_model.get_symbol_by_cmeta_id(\"a\")\n", "FAIL_TO_PASS": ["tests/test_model_functions.py::TestModelFunctions::test_get_equations_for"]}], "all_FAIL_TO_PASS": ["tests/test_model_functions.py::TestModelFunctions::test_get_equations_for"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NVIDIA__hpc-container-maker-244_x1", "level": 1, "source": "swerebench", "repo": "NVIDIA/hpc-container-maker", "image": "swerebench/sweb.eval.x86_64.nvidia_1776_hpc-container-maker-244:latest", "base_commit": "5d48c54e7ae8412841be766f5434be5924cbc5d6", "num_bugs": 1, "bugs": [{"instance_id": "NVIDIA__hpc-container-maker-244", "base_commit": "5d48c54e7ae8412841be766f5434be5924cbc5d6", "gold_patch": "diff --git a/docs/building_blocks.md b/docs/building_blocks.md\nindex 79a20c8..4d8b12d 100644\n--- a/docs/building_blocks.md\n+++ b/docs/building_blocks.md\n@@ -2007,6 +2007,9 @@ packages. For Ubuntu, setting this flag to True enables the\n distributions, setting this flag to True enables the Software\n Collections (SCL) repository. The default is False.\n \n+- __extra_tools__: Boolean flag to specify whether to also install\n+`clang-format` and `clang-tidy`. The default is False.\n+\n - __version__: The version of the LLVM compilers to install. Note that\n the version refers to the Linux distribution packaging, not the\n actual compiler version. For Ubuntu, the version is appended to\ndiff --git a/hpccm/building_blocks/llvm.py b/hpccm/building_blocks/llvm.py\nindex 06e3f87..be8632c 100644\n--- a/hpccm/building_blocks/llvm.py\n+++ b/hpccm/building_blocks/llvm.py\n@@ -21,6 +21,7 @@ from __future__ import unicode_literals\n from __future__ import print_function\n \n from distutils.version import StrictVersion\n+import logging\n \n import hpccm.config\n import hpccm.templates.envvars\n@@ -54,6 +55,9 @@ class llvm(bb_base, hpccm.templates.envvars):\n distributions, setting this flag to True enables the Software\n Collections (SCL) repository. The default is False.\n \n+ extra_tools: Boolean flag to specify whether to also install\n+ `clang-format` and `clang-tidy`. The default is False.\n+\n version: The version of the LLVM compilers to install. Note that\n the version refers to the Linux distribution packaging, not the\n actual compiler version. For Ubuntu, the version is appended to\n@@ -90,6 +94,7 @@ class llvm(bb_base, hpccm.templates.envvars):\n self.__compiler_debs = [] # Filled in below\n self.__compiler_rpms = [] # Filled in below\n self.__extra_repo = kwargs.get('extra_repository', False)\n+ self.__extra_tools = kwargs.get('extra_tools', False)\n self.__ospackages = kwargs.get('ospackages', []) # Filled in below\n self.__runtime_debs = [] # Filled in below\n self.__runtime_rpms = [] # Filled in below\n@@ -123,10 +128,22 @@ class llvm(bb_base, hpccm.templates.envvars):\n # version is the new default\n self.__commands.append('update-alternatives --install /usr/bin/clang clang $(which clang-{}) 30'.format(self.__version))\n self.__commands.append('update-alternatives --install /usr/bin/clang++ clang++ $(which clang++-{}) 30'.format(self.__version))\n+\n+ # Install and configure clang-format and clang-tidy\n+ if self.__extra_tools:\n+ self.__compiler_debs.append('clang-format-{}'.format(\n+ self.__version))\n+ self.__compiler_debs.append('clang-tidy-{}'.format(\n+ self.__version))\n+ self.__commands.append('update-alternatives --install /usr/bin/clang-format clang-format $(which clang-format-{}) 30'.format(self.__version))\n+ self.__commands.append('update-alternatives --install /usr/bin/clang-tidy clang-tidy $(which clang-tidy-{}) 30'.format(self.__version))\n else:\n self.__compiler_debs = ['clang', 'libomp-dev']\n self.__runtime_debs = ['libclang1', 'libomp5']\n \n+ if self.__extra_tools:\n+ self.__compiler_debs.extend(['clang-format', 'clang-tidy'])\n+\n elif hpccm.config.g_linux_distro == linux_distro.CENTOS:\n # Dependencies on the GNU compiler\n self.__ospackages = ['gcc', 'gcc-c++']\n@@ -140,6 +157,9 @@ class llvm(bb_base, hpccm.templates.envvars):\n self.__compiler_rpms = ['llvm-toolset-8.0.1']\n self.__runtime_rpms = ['llvm-libs-8.0.1', 'libomp']\n compiler_version = '8'\n+\n+ if self.__extra_tools:\n+ self.__compiler_rpms.append('clang-tools-extra-8.0.1')\n else:\n # CentOS 7\n self.__compiler_rpms = [\n@@ -151,6 +171,9 @@ class llvm(bb_base, hpccm.templates.envvars):\n 'llvm-toolset-{}-compiler-rt'.format(self.__version)]\n compiler_version = '4.8.2'\n \n+ if self.__extra_tools:\n+ self.__compiler_rpms.append('llvm-toolset-{}-clang-tools-extra'.format(self.__version))\n+\n # Setup environment for devtoolset\n self.environment_variables['PATH'] = '/opt/rh/llvm-toolset-{}/root/usr/bin:$PATH'.format(self.__version)\n self.environment_variables['LD_LIBRARY_PATH'] = '/opt/rh/llvm-toolset-{}/root/usr/lib64:$LD_LIBRARY_PATH'.format(self.__version)\n@@ -160,11 +183,17 @@ class llvm(bb_base, hpccm.templates.envvars):\n # CentOS 8\n self.__runtime_rpms = ['llvm-libs', 'libomp']\n compiler_version = '8'\n+\n+ if self.__extra_tools:\n+ self.__compiler_rpms.append('clang-tools-extra')\n else:\n # CentOS 7\n self.__runtime_rpms = ['llvm-libs', 'libgomp']\n compiler_version = '4.8.2'\n \n+ if self.__extra_tools: # pragma: no cover\n+ logging.warning('llvm extra tools are not available for default CentOS 7, specify a LLVM version')\n+\n # The default llvm configuration for CentOS is unable to\n # locate some gcc components. Setup the necessary gcc\n # environment.\n", "test_patch": "diff --git a/test/test_llvm.py b/test/test_llvm.py\nindex b683eec..3803656 100644\n--- a/test/test_llvm.py\n+++ b/test/test_llvm.py\n@@ -84,23 +84,27 @@ ENV CPATH=/usr/lib/gcc/x86_64-redhat-linux/8/include:$CPATH''')\n @docker\n def test_version_ubuntu(self):\n \"\"\"LLVM compiler version\"\"\"\n- l = llvm(extra_repository=True, version='6.0')\n+ l = llvm(extra_repository=True, extra_tools=True, version='6.0')\n self.assertEqual(str(l),\n r'''# LLVM compiler\n RUN apt-get update -y && \\\n DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \\\n clang-6.0 \\\n+ clang-format-6.0 \\\n+ clang-tidy-6.0 \\\n libomp-dev && \\\n rm -rf /var/lib/apt/lists/*\n RUN update-alternatives --install /usr/bin/clang clang $(which clang-6.0) 30 && \\\n- update-alternatives --install /usr/bin/clang++ clang++ $(which clang++-6.0) 30''')\n+ update-alternatives --install /usr/bin/clang++ clang++ $(which clang++-6.0) 30 && \\\n+ update-alternatives --install /usr/bin/clang-format clang-format $(which clang-format-6.0) 30 && \\\n+ update-alternatives --install /usr/bin/clang-tidy clang-tidy $(which clang-tidy-6.0) 30''')\n \n @x86_64\n @centos\n @docker\n def test_version_centos(self):\n \"\"\"LLVM compiler version\"\"\"\n- l = llvm(extra_repository=True, version='7')\n+ l = llvm(extra_repository=True, extra_tools=True, version='7')\n self.assertEqual(str(l),\n r'''# LLVM compiler\n RUN yum install -y \\\n@@ -110,6 +114,7 @@ RUN yum install -y \\\n RUN yum install -y centos-release-scl && \\\n yum install -y \\\n llvm-toolset-7-clang \\\n+ llvm-toolset-7-clang-tools-extra \\\n llvm-toolset-7-libomp-devel && \\\n rm -rf /var/cache/yum/*\n ENV CPATH=/usr/lib/gcc/x86_64-redhat-linux/4.8.2/include:$CPATH \\\n@@ -162,6 +167,40 @@ ENV COMPILER_PATH=/usr/lib/gcc/aarch64-redhat-linux/8:$COMPILER_PATH \\\n with self.assertRaises(RuntimeError):\n llvm()\n \n+ @x86_64\n+ @ubuntu\n+ @docker\n+ def test_extra_tools_ubuntu(self):\n+ \"\"\"clang-format and clang-tidy\"\"\"\n+ l = llvm(extra_tools=True)\n+ self.assertEqual(str(l),\n+r'''# LLVM compiler\n+RUN apt-get update -y && \\\n+ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \\\n+ clang \\\n+ clang-format \\\n+ clang-tidy \\\n+ libomp-dev && \\\n+ rm -rf /var/lib/apt/lists/*''')\n+\n+ @x86_64\n+ @centos8\n+ @docker\n+ def test_extra_tools_centos8(self):\n+ \"\"\"Default llvm building block\"\"\"\n+ l = llvm(extra_tools=True, version='8')\n+ self.assertEqual(str(l),\n+r'''# LLVM compiler\n+RUN yum install -y \\\n+ gcc \\\n+ gcc-c++ && \\\n+ rm -rf /var/cache/yum/*\n+RUN yum install -y \\\n+ clang-tools-extra-8.0.1 \\\n+ llvm-toolset-8.0.1 && \\\n+ rm -rf /var/cache/yum/*\n+ENV CPATH=/usr/lib/gcc/x86_64-redhat-linux/8/include:$CPATH''')\n+\n @x86_64\n @ubuntu\n @docker\n", "FAIL_TO_PASS": ["test/test_llvm.py::Test_llvm::test_extra_tools_centos8", "test/test_llvm.py::Test_llvm::test_extra_tools_ubuntu", "test/test_llvm.py::Test_llvm::test_version_centos", "test/test_llvm.py::Test_llvm::test_version_ubuntu"]}], "all_FAIL_TO_PASS": ["test/test_llvm.py::Test_llvm::test_extra_tools_centos8", "test/test_llvm.py::Test_llvm::test_extra_tools_ubuntu", "test/test_llvm.py::Test_llvm::test_version_centos", "test/test_llvm.py::Test_llvm::test_version_ubuntu"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MindscapeHQ__raygun4py-82_x1", "level": 1, "source": "swerebench", "repo": "MindscapeHQ/raygun4py", "image": "swerebench/sweb.eval.x86_64.mindscapehq_1776_raygun4py-82:latest", "base_commit": "16d2e7a3ebcca16548e5ec806c85b3edfda95930", "num_bugs": 1, "bugs": [{"instance_id": "MindscapeHQ__raygun4py-82", "base_commit": "16d2e7a3ebcca16548e5ec806c85b3edfda95930", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 9a8e114..d80a3f8 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -1,3 +1,7 @@\n+## 4.2.2 (23/01/2019):\n+Bugfixes\n+ - Fix `set_request_details` builder method not returning self causing it to be unchainable\n+\n ## 4.2.1 (18/12/2018):\n Bugfixes\n - Set version correctly in crash report sent to Raygun API ([#78](https://github.com/MindscapeHQ/raygun4py/pull/79))\ndiff --git a/python2/raygun4py/version.py b/python2/raygun4py/version.py\nindex 53fb41b..3cd825b 100644\n--- a/python2/raygun4py/version.py\n+++ b/python2/raygun4py/version.py\n@@ -2,4 +2,4 @@\n # 1) we don't load dependencies by storing it in __init__.py\n # 2) we can import it in setup.py for the same reason\n # 3) we can import it into your module module\n-__version__ = '4.2.1'\n+__version__ = '4.2.2'\ndiff --git a/python3/raygun4py/raygunmsgs.py b/python3/raygun4py/raygunmsgs.py\nindex c419558..6d3c318 100644\n--- a/python3/raygun4py/raygunmsgs.py\n+++ b/python3/raygun4py/raygunmsgs.py\n@@ -97,6 +97,8 @@ class RaygunMessageBuilder(object):\n rg_request_details = http_utilities.build_wsgi_compliant_request(request)\n self.raygunMessage.details['request'] = rg_request_details\n \n+ return self\n+\n \n def set_version(self, version):\n self.raygunMessage.details['version'] = version\ndiff --git a/python3/raygun4py/version.py b/python3/raygun4py/version.py\nindex 53fb41b..3cd825b 100644\n--- a/python3/raygun4py/version.py\n+++ b/python3/raygun4py/version.py\n@@ -2,4 +2,4 @@\n # 1) we don't load dependencies by storing it in __init__.py\n # 2) we can import it in setup.py for the same reason\n # 3) we can import it into your module module\n-__version__ = '4.2.1'\n+__version__ = '4.2.2'\n", "test_patch": "diff --git a/python3/tests/test_raygunmsgs.py b/python3/tests/test_raygunmsgs.py\nindex 2f0b3e0..be16405 100644\n--- a/python3/tests/test_raygunmsgs.py\n+++ b/python3/tests/test_raygunmsgs.py\n@@ -109,6 +109,12 @@ class TestRaygunMessageBuilder(unittest.TestCase):\n self.assertEqual(self.builder.raygunMessage.details['request']['headers']['Referer'],\n \"https://www.google.com/\")\n \n+ def test_set_request_details_allows_chaining(self):\n+ self.builder \\\n+ .set_request_details(self.raw_wsgi_request) \\\n+ .set_tags(['foo', 'bar'])\n+\n+\n class TestRaygunErrorMessage(unittest.TestCase):\n class GrandchildError(Exception):\n pass\n", "FAIL_TO_PASS": ["python3/tests/test_raygunmsgs.py::TestRaygunMessageBuilder::test_set_request_details_allows_chaining"]}], "all_FAIL_TO_PASS": ["python3/tests/test_raygunmsgs.py::TestRaygunMessageBuilder::test_set_request_details_allows_chaining"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Colin-b__requests_auth-50_x1", "level": 1, "source": "swerebench", "repo": "Colin-b/requests_auth", "image": "swerebench/sweb.eval.x86_64.colin-b_1776_requests_auth-50:latest", "base_commit": "c220bac07169e5c9f5c0b3d7dd4031e6fdd72936", "num_bugs": 1, "bugs": [{"instance_id": "Colin-b__requests_auth-50", "base_commit": "c220bac07169e5c9f5c0b3d7dd4031e6fdd72936", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nnew file mode 100644\nindex 0000000..e7a8d22\n--- /dev/null\n+++ b/.travis.yml\n@@ -0,0 +1,14 @@\n+language: python\n+python:\n+ - \"3.6\"\n+ - \"3.7\"\n+ - \"3.8\"\n+install:\n+ - pip install .[testing]\n+script:\n+ - pytest\n+deploy:\n+ provider: pypi\n+ username: __token__\n+ edge: true\n+ distributions: \"sdist bdist_wheel\"\n\\ No newline at end of file\ndiff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 25a73e5..e8f57bf 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -6,6 +6,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n ## [Unreleased]\n \n+## [5.0.1] - 2019-11-28\n+### Added\n+- Allow to use & between authentication classes.\n+\n+### Fixed\n+- Avoid DeprecationWarning in case multi auth is used with +\n+- Avoid packaging tests (introduced in 5.0.0)\n+\n ## [5.0.0] - 2019-11-21\n ### Changed\n - OAuth2ClientCredentials username parameter is now client_id\n@@ -106,7 +114,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n ### Added\n - Public release\n \n-[Unreleased]: https://github.com/Colin-b/requests_auth/compare/v5.0.0...HEAD\n+[Unreleased]: https://github.com/Colin-b/requests_auth/compare/v5.0.1...HEAD\n+[5.0.1]: https://github.com/Colin-b/requests_auth/compare/v5.0.0...v5.0.1\n [5.0.0]: https://github.com/Colin-b/requests_auth/compare/v4.1.0...v5.0.0\n [4.1.0]: https://github.com/Colin-b/requests_auth/compare/v4.0.1...v4.1.0\n [4.0.1]: https://github.com/Colin-b/requests_auth/compare/v4.0.0...v4.0.1\ndiff --git a/_config.yml b/_config.yml\ndeleted file mode 100644\nindex c419263..0000000\n--- a/_config.yml\n+++ /dev/null\n@@ -1,1 +0,0 @@\n-theme: jekyll-theme-cayman\n\\ No newline at end of file\ndiff --git a/requests_auth/authentication.py b/requests_auth/authentication.py\nindex 27aac84..4a00ebd 100644\n--- a/requests_auth/authentication.py\n+++ b/requests_auth/authentication.py\n@@ -82,9 +82,14 @@ class SupportMultiAuth:\n \"\"\"Inherit from this class to be able to use your class with requests_auth provided authentication classes.\"\"\"\n \n def __add__(self, other):\n- if isinstance(other, Auths):\n- return Auths(self, *other.authentication_modes)\n- return Auths(self, other)\n+ if isinstance(other, _MultiAuth):\n+ return _MultiAuth(self, *other.authentication_modes)\n+ return _MultiAuth(self, other)\n+\n+ def __and__(self, other):\n+ if isinstance(other, _MultiAuth):\n+ return _MultiAuth(self, *other.authentication_modes)\n+ return _MultiAuth(self, other)\n \n \n class BrowserAuth:\n@@ -1121,14 +1126,10 @@ class NTLM(requests.auth.AuthBase, SupportMultiAuth):\n return r\n \n \n-class Auths(requests.auth.AuthBase):\n+class _MultiAuth(requests.auth.AuthBase):\n \"\"\"Authentication using multiple authentication methods.\"\"\"\n \n def __init__(self, *authentication_modes):\n- warnings.warn(\n- \"Auths class will be removed in the future. Use + instead.\",\n- DeprecationWarning,\n- )\n self.authentication_modes = authentication_modes\n \n def __call__(self, r):\n@@ -1137,6 +1138,20 @@ class Auths(requests.auth.AuthBase):\n return r\n \n def __add__(self, other):\n- if isinstance(other, Auths):\n- return Auths(*self.authentication_modes, *other.authentication_modes)\n- return Auths(*self.authentication_modes, other)\n+ if isinstance(other, _MultiAuth):\n+ return _MultiAuth(*self.authentication_modes, *other.authentication_modes)\n+ return _MultiAuth(*self.authentication_modes, other)\n+\n+ def __and__(self, other):\n+ if isinstance(other, _MultiAuth):\n+ return _MultiAuth(*self.authentication_modes, *other.authentication_modes)\n+ return _MultiAuth(*self.authentication_modes, other)\n+\n+\n+class Auths(_MultiAuth):\n+ def __init__(self, *authentication_modes):\n+ warnings.warn(\n+ \"Auths class will be removed in the future. Use + instead.\",\n+ DeprecationWarning,\n+ )\n+ super().__init__(*authentication_modes)\ndiff --git a/requests_auth/version.py b/requests_auth/version.py\nindex ffe1d01..f309563 100644\n--- a/requests_auth/version.py\n+++ b/requests_auth/version.py\n@@ -3,4 +3,4 @@\n # Major should be incremented in case there is a breaking change. (eg: 2.5.8 -> 3.0.0)\n # Minor should be incremented in case there is an enhancement. (eg: 2.5.8 -> 2.6.0)\n # Patch should be incremented in case there is a bug fix. (eg: 2.5.8 -> 2.5.9)\n-__version__ = \"5.0.0\"\n+__version__ = \"5.0.1\"\ndiff --git a/setup.py b/setup.py\nindex f1d298b..ae20ee1 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -13,7 +13,7 @@ setup(\n author_email=\"colin.bounouar.dev@gmail.com\",\n maintainer=\"Colin Bounouar\",\n maintainer_email=\"colin.bounouar.dev@gmail.com\",\n- url=\"https://github.com/Colin-b/requests_auth\",\n+ url=\"https://colin-b.github.io/requests_auth/\",\n description=\"Authentication for Requests\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n@@ -41,7 +41,7 @@ setup(\n \"apikey\",\n \"multiple\",\n ],\n- packages=find_packages(exclude=[\"tests\"]),\n+ packages=find_packages(exclude=[\"tests*\"]),\n install_requires=[\n # Used for Base Authentication and to communicate with OAuth2 servers\n \"requests==2.*\"\n@@ -56,6 +56,7 @@ setup(\n },\n python_requires=\">=3.6\",\n project_urls={\n+ \"GitHub\": \"https://github.com/Colin-b/requests_auth\",\n \"Changelog\": \"https://github.com/Colin-b/requests_auth/blob/master/CHANGELOG.md\",\n \"Issues\": \"https://github.com/Colin-b/requests_auth/issues\",\n },\n", "test_patch": "diff --git a/tests/test_multiple_authentication.py b/tests/test_add_operator.py\nsimilarity index 97%\nrename from tests/test_multiple_authentication.py\nrename to tests/test_add_operator.py\nindex 6956378..f1856f1 100644\n--- a/tests/test_multiple_authentication.py\n+++ b/tests/test_add_operator.py\n@@ -16,16 +16,6 @@ def test_basic_and_api_key_authentication_can_be_combined(responses: RequestsMoc\n assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n \n \n-def test_basic_and_api_key_authentication_can_be_combined_deprecated(\n- responses: RequestsMock,\n-):\n- basic_auth = requests_auth.Basic(\"test_user\", \"test_pwd\")\n- api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n- header = get_header(responses, requests_auth.Auths(basic_auth, api_key_auth))\n- assert header.get(\"Authorization\") == \"Basic dGVzdF91c2VyOnRlc3RfcHdk\"\n- assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n-\n-\n def test_header_api_key_and_multiple_authentication_can_be_combined(\n token_cache, responses: RequestsMock\n ):\ndiff --git a/tests/test_and_operator.py b/tests/test_and_operator.py\nnew file mode 100644\nindex 0000000..68250fd\n--- /dev/null\n+++ b/tests/test_and_operator.py\n@@ -0,0 +1,391 @@\n+import datetime\n+\n+from responses import RequestsMock\n+import requests\n+\n+import requests_auth\n+from tests.oauth2_helper import token_cache, browser_mock, BrowserMock, create_token\n+from tests.auth_helper import get_header\n+\n+\n+def test_basic_and_api_key_authentication_can_be_combined(responses: RequestsMock):\n+ basic_auth = requests_auth.Basic(\"test_user\", \"test_pwd\")\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ header = get_header(responses, basic_auth & api_key_auth)\n+ assert header.get(\"Authorization\") == \"Basic dGVzdF91c2VyOnRlc3RfcHdk\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+\n+\n+def test_header_api_key_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ api_key_auth3 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key3\", header_name=\"X-Api-Key3\"\n+ )\n+ header = get_header(responses, api_key_auth & (api_key_auth2 & api_key_auth3))\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+ assert header.get(\"X-Api-Key3\") == \"my_provided_api_key3\"\n+\n+\n+def test_multiple_auth_and_header_api_key_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ api_key_auth3 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key3\", header_name=\"X-Api-Key3\"\n+ )\n+ header = get_header(responses, (api_key_auth & api_key_auth2) & api_key_auth3)\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+ assert header.get(\"X-Api-Key3\") == \"my_provided_api_key3\"\n+\n+\n+def test_multiple_auth_and_multiple_auth_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ api_key_auth3 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key3\", header_name=\"X-Api-Key3\"\n+ )\n+ api_key_auth4 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key4\", header_name=\"X-Api-Key4\"\n+ )\n+ header = get_header(\n+ responses, (api_key_auth & api_key_auth2) & (api_key_auth3 & api_key_auth4)\n+ )\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+ assert header.get(\"X-Api-Key3\") == \"my_provided_api_key3\"\n+ assert header.get(\"X-Api-Key4\") == \"my_provided_api_key4\"\n+\n+\n+def test_basic_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ basic_auth = requests_auth.Basic(\"test_user\", \"test_pwd\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ api_key_auth3 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key3\", header_name=\"X-Api-Key3\"\n+ )\n+ header = get_header(responses, basic_auth & (api_key_auth2 & api_key_auth3))\n+ assert header.get(\"Authorization\") == \"Basic dGVzdF91c2VyOnRlc3RfcHdk\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+ assert header.get(\"X-Api-Key3\") == \"my_provided_api_key3\"\n+\n+\n+def test_query_api_key_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ api_key_auth = requests_auth.QueryApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.QueryApiKey(\n+ \"my_provided_api_key2\", query_parameter_name=\"api_key2\"\n+ )\n+ api_key_auth3 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key3\", header_name=\"X-Api-Key3\"\n+ )\n+\n+ # Mock a dummy response\n+ responses.add(responses.GET, \"http://authorized_only\")\n+ # Send a request to this dummy URL with authentication\n+ response = requests.get(\n+ \"http://authorized_only\", auth=api_key_auth & (api_key_auth2 & api_key_auth3)\n+ )\n+ # Return headers received on this dummy URL\n+ assert (\n+ response.request.path_url\n+ == \"/?api_key=my_provided_api_key&api_key2=my_provided_api_key2\"\n+ )\n+ assert response.request.headers.get(\"X-Api-Key3\") == \"my_provided_api_key3\"\n+\n+\n+def test_oauth2_resource_owner_password_and_api_key_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ resource_owner_password_auth = requests_auth.OAuth2ResourceOwnerPasswordCredentials(\n+ \"http://provide_access_token\", username=\"test_user\", password=\"test_pwd\"\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ header = get_header(responses, resource_owner_password_auth & api_key_auth)\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+\n+\n+def test_oauth2_resource_owner_password_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ resource_owner_password_auth = requests_auth.OAuth2ResourceOwnerPasswordCredentials(\n+ \"http://provide_access_token\", username=\"test_user\", password=\"test_pwd\"\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ header = get_header(\n+ responses, resource_owner_password_auth & (api_key_auth & api_key_auth2)\n+ )\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+\n+\n+def test_oauth2_client_credential_and_api_key_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ resource_owner_password_auth = requests_auth.OAuth2ClientCredentials(\n+ \"http://provide_access_token\", client_id=\"test_user\", client_secret=\"test_pwd\"\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ header = get_header(responses, resource_owner_password_auth & api_key_auth)\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+\n+\n+def test_oauth2_client_credential_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock\n+):\n+ resource_owner_password_auth = requests_auth.OAuth2ClientCredentials(\n+ \"http://provide_access_token\", client_id=\"test_user\", client_secret=\"test_pwd\"\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ header = get_header(\n+ responses, resource_owner_password_auth & (api_key_auth & api_key_auth2)\n+ )\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+\n+\n+def test_oauth2_authorization_code_and_api_key_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock, browser_mock: BrowserMock\n+):\n+ authorization_code_auth = requests_auth.OAuth2AuthorizationCode(\n+ \"http://provide_code\", \"http://provide_access_token\"\n+ )\n+ tab = browser_mock.add_response(\n+ opened_url=\"http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F\",\n+ reply_url=\"http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de\",\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ header = get_header(responses, authorization_code_auth & api_key_auth)\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ tab.assert_success(\n+ \"You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab.\"\n+ )\n+\n+\n+def test_oauth2_authorization_code_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock, browser_mock: BrowserMock\n+):\n+ authorization_code_auth = requests_auth.OAuth2AuthorizationCode(\n+ \"http://provide_code\", \"http://provide_access_token\"\n+ )\n+ tab = browser_mock.add_response(\n+ opened_url=\"http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F\",\n+ reply_url=\"http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de\",\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ header = get_header(\n+ responses, authorization_code_auth & (api_key_auth & api_key_auth2)\n+ )\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+ tab.assert_success(\n+ \"You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab.\"\n+ )\n+\n+\n+def test_oauth2_pkce_and_api_key_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock, browser_mock: BrowserMock, monkeypatch\n+):\n+ monkeypatch.setattr(requests_auth.authentication.os, \"urandom\", lambda x: b\"1\" * 63)\n+ pkce_auth = requests_auth.OAuth2AuthorizationCodePKCE(\n+ \"http://provide_code\", \"http://provide_access_token\"\n+ )\n+ tab = browser_mock.add_response(\n+ opened_url=\"http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F&code_challenge=5C_ph_KZ3DstYUc965SiqmKAA-ShvKF4Ut7daKd3fjc&code_challenge_method=S256\",\n+ reply_url=\"http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de\",\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ header = get_header(responses, pkce_auth & api_key_auth)\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ tab.assert_success(\n+ \"You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab.\"\n+ )\n+\n+\n+def test_oauth2_pkce_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock, browser_mock: BrowserMock, monkeypatch\n+):\n+ monkeypatch.setattr(requests_auth.authentication.os, \"urandom\", lambda x: b\"1\" * 63)\n+ pkce_auth = requests_auth.OAuth2AuthorizationCodePKCE(\n+ \"http://provide_code\", \"http://provide_access_token\"\n+ )\n+ tab = browser_mock.add_response(\n+ opened_url=\"http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F&code_challenge=5C_ph_KZ3DstYUc965SiqmKAA-ShvKF4Ut7daKd3fjc&code_challenge_method=S256\",\n+ reply_url=\"http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de\",\n+ )\n+ responses.add(\n+ responses.POST,\n+ \"http://provide_access_token\",\n+ json={\n+ \"access_token\": \"2YotnFZFEjr1zCsicMWpAA\",\n+ \"token_type\": \"example\",\n+ \"expires_in\": 3600,\n+ \"refresh_token\": \"tGzv3JOkF0XG5Qx2TlKWIA\",\n+ \"example_parameter\": \"example_value\",\n+ },\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ header = get_header(responses, pkce_auth & (api_key_auth & api_key_auth2))\n+ assert header.get(\"Authorization\") == \"Bearer 2YotnFZFEjr1zCsicMWpAA\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+ tab.assert_success(\n+ \"You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab.\"\n+ )\n+\n+\n+def test_oauth2_implicit_and_api_key_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock, browser_mock: BrowserMock\n+):\n+ implicit_auth = requests_auth.OAuth2Implicit(\"http://provide_token\")\n+ expiry_in_1_hour = datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n+ token = create_token(expiry_in_1_hour)\n+ tab = browser_mock.add_response(\n+ opened_url=\"http://provide_token?response_type=token&state=42a85b271b7a652ca3cc4c398cfd3f01b9ad36bf9c945ba823b023e8f8b95c4638576a0e3dcc96838b838bec33ec6c0ee2609d62ed82480b3b8114ca494c0521&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F\",\n+ reply_url=\"http://localhost:5000\",\n+ data=f\"access_token={token}&state=42a85b271b7a652ca3cc4c398cfd3f01b9ad36bf9c945ba823b023e8f8b95c4638576a0e3dcc96838b838bec33ec6c0ee2609d62ed82480b3b8114ca494c0521\",\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ header = get_header(responses, implicit_auth & api_key_auth)\n+ assert header.get(\"Authorization\") == f\"Bearer {token}\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ tab.assert_success(\n+ \"You are now authenticated on 42a85b271b7a652ca3cc4c398cfd3f01b9ad36bf9c945ba823b023e8f8b95c4638576a0e3dcc96838b838bec33ec6c0ee2609d62ed82480b3b8114ca494c0521. You may close this tab.\"\n+ )\n+\n+\n+def test_oauth2_implicit_and_multiple_authentication_can_be_combined(\n+ token_cache, responses: RequestsMock, browser_mock: BrowserMock\n+):\n+ implicit_auth = requests_auth.OAuth2Implicit(\"http://provide_token\")\n+ expiry_in_1_hour = datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n+ token = create_token(expiry_in_1_hour)\n+ tab = browser_mock.add_response(\n+ opened_url=\"http://provide_token?response_type=token&state=42a85b271b7a652ca3cc4c398cfd3f01b9ad36bf9c945ba823b023e8f8b95c4638576a0e3dcc96838b838bec33ec6c0ee2609d62ed82480b3b8114ca494c0521&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F\",\n+ reply_url=\"http://localhost:5000\",\n+ data=f\"access_token={token}&state=42a85b271b7a652ca3cc4c398cfd3f01b9ad36bf9c945ba823b023e8f8b95c4638576a0e3dcc96838b838bec33ec6c0ee2609d62ed82480b3b8114ca494c0521\",\n+ )\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ api_key_auth2 = requests_auth.HeaderApiKey(\n+ \"my_provided_api_key2\", header_name=\"X-Api-Key2\"\n+ )\n+ header = get_header(responses, implicit_auth & (api_key_auth & api_key_auth2))\n+ assert header.get(\"Authorization\") == f\"Bearer {token}\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n+ assert header.get(\"X-Api-Key2\") == \"my_provided_api_key2\"\n+ tab.assert_success(\n+ \"You are now authenticated on 42a85b271b7a652ca3cc4c398cfd3f01b9ad36bf9c945ba823b023e8f8b95c4638576a0e3dcc96838b838bec33ec6c0ee2609d62ed82480b3b8114ca494c0521. You may close this tab.\"\n+ )\ndiff --git a/tests/test_auths.py b/tests/test_auths.py\nnew file mode 100644\nindex 0000000..5435f79\n--- /dev/null\n+++ b/tests/test_auths.py\n@@ -0,0 +1,16 @@\n+import pytest\n+from responses import RequestsMock\n+\n+import requests_auth\n+from tests.auth_helper import get_header\n+\n+\n+def test_basic_and_api_key_authentication_can_be_combined_deprecated(\n+ responses: RequestsMock,\n+):\n+ basic_auth = requests_auth.Basic(\"test_user\", \"test_pwd\")\n+ api_key_auth = requests_auth.HeaderApiKey(\"my_provided_api_key\")\n+ with pytest.warns(DeprecationWarning):\n+ header = get_header(responses, requests_auth.Auths(basic_auth, api_key_auth))\n+ assert header.get(\"Authorization\") == \"Basic dGVzdF91c2VyOnRlc3RfcHdk\"\n+ assert header.get(\"X-Api-Key\") == \"my_provided_api_key\"\n", "FAIL_TO_PASS": ["tests/test_and_operator.py::test_basic_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_header_api_key_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_multiple_auth_and_header_api_key_can_be_combined", "tests/test_and_operator.py::test_multiple_auth_and_multiple_auth_can_be_combined", "tests/test_and_operator.py::test_basic_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_query_api_key_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_resource_owner_password_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_resource_owner_password_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_client_credential_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_client_credential_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_authorization_code_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_authorization_code_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_pkce_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_pkce_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_implicit_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_implicit_and_multiple_authentication_can_be_combined"]}], "all_FAIL_TO_PASS": ["tests/test_and_operator.py::test_basic_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_header_api_key_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_multiple_auth_and_header_api_key_can_be_combined", "tests/test_and_operator.py::test_multiple_auth_and_multiple_auth_can_be_combined", "tests/test_and_operator.py::test_basic_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_query_api_key_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_resource_owner_password_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_resource_owner_password_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_client_credential_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_client_credential_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_authorization_code_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_authorization_code_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_pkce_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_pkce_and_multiple_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_implicit_and_api_key_authentication_can_be_combined", "tests/test_and_operator.py::test_oauth2_implicit_and_multiple_authentication_can_be_combined"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ESSS__oop-ext-21_x1", "level": 1, "source": "swerebench", "repo": "ESSS/oop-ext", "image": "swerebench/sweb.eval.x86_64.esss_1776_oop-ext-21:latest", "base_commit": "00000f0c728003d078fa48a7a0b121725326d491", "num_bugs": 1, "bugs": [{"instance_id": "ESSS__oop-ext-21", "base_commit": "00000f0c728003d078fa48a7a0b121725326d491", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex f98b109..41e5a14 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -1,6 +1,11 @@\n-0.5.0 (2019-12-12)\n+0.5.1 (2019-12-20)\n ==================\n \n+* Fixes an issue (#20) where mocked `classmethods` weren't considered a valid method during internal checks.\n+\n+0.5.0 (2019-12-12)\n+------------------\n+\n * Add optional argument ``requires_declaration`` so users can decide whether or not ``@ImplementsInterface`` declarations are necessary.\n \n 0.4.0 (2019-12-03)\ndiff --git a/src/oop_ext/interface/_interface.py b/src/oop_ext/interface/_interface.py\nindex c84ffa2..5fd1ffa 100644\n--- a/src/oop_ext/interface/_interface.py\n+++ b/src/oop_ext/interface/_interface.py\n@@ -590,10 +590,13 @@ def _IsMethod(member):\n 3) instances of Method (should it be implementors of \"IMethod\"?)\n \n \"\"\"\n+ from unittest import mock\n+\n return (\n inspect.isfunction(member)\n or inspect.ismethod(member)\n or isinstance(member, Method)\n+ or isinstance(member, mock.MagicMock)\n )\n \n \n", "test_patch": "diff --git a/src/oop_ext/interface/_tests/test_interface.py b/src/oop_ext/interface/_tests/test_interface.py\nindex 60bcc10..8beb611 100644\n--- a/src/oop_ext/interface/_tests/test_interface.py\n+++ b/src/oop_ext/interface/_tests/test_interface.py\n@@ -814,11 +814,13 @@ def test_interface_subclass_mocked(mocker, check_before, autospec):\n pass\n \n if check_before:\n- interface.IsImplementation(Bar, II)\n+ interface.IsImplementation(Bar, II, requires_declaration=False)\n+ interface.IsImplementation(Bar, II, requires_declaration=True)\n \n mocker.patch.object(Foo, \"foo\", autospec=autospec)\n \n- assert interface.IsImplementation(Bar, II) == (autospec or check_before)\n+ assert interface.IsImplementation(Bar, II, requires_declaration=False)\n+ assert interface.IsImplementation(Bar, II, requires_declaration=True)\n \n \n def testErrorOnInterfaceDeclaration():\n@@ -882,3 +884,23 @@ def testIsImplementationOfAny():\n AssertImplements(a_obj, _InterfM3)\n assert IsImplementationOfAny(A, [_InterfM1, _InterfM2, _InterfM3, _InterfM4])\n assert not IsImplementationOfAny(A, [_InterfM1, _InterfM2, _InterfM4])\n+\n+\n+def testClassMethodBug(mocker):\n+ \"\"\"\n+ Issue #20\n+ \"\"\"\n+\n+ class IFoo(Interface):\n+ @classmethod\n+ def foo(cls):\n+ \"\"\n+\n+ @ImplementsInterface(IFoo)\n+ class FooImplementation:\n+ @classmethod\n+ def foo(cls):\n+ \"\"\n+\n+ mocker.spy(FooImplementation, \"foo\")\n+ AssertImplements(FooImplementation, IFoo, requires_declaration=True)\n", "FAIL_TO_PASS": ["src/oop_ext/interface/_tests/test_interface.py::test_interface_subclass_mocked[False-False]", "src/oop_ext/interface/_tests/test_interface.py::testClassMethodBug"]}], "all_FAIL_TO_PASS": ["src/oop_ext/interface/_tests/test_interface.py::test_interface_subclass_mocked[False-False]", "src/oop_ext/interface/_tests/test_interface.py::testClassMethodBug"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MIT-LCP__wfdb-python-492_x1", "level": 1, "source": "swerebench", "repo": "MIT-LCP/wfdb-python", "image": "swerebench/sweb.eval.x86_64.mit-lcp_1776_wfdb-python-492:latest", "base_commit": "634c6a1354d6476965f0e0f09075ccca60b90337", "num_bugs": 1, "bugs": [{"instance_id": "MIT-LCP__wfdb-python-492", "base_commit": "634c6a1354d6476965f0e0f09075ccca60b90337", "gold_patch": "diff --git a/wfdb/io/convert/csv.py b/wfdb/io/convert/csv.py\nindex 3cfd25a..4817a0e 100644\n--- a/wfdb/io/convert/csv.py\n+++ b/wfdb/io/convert/csv.py\n@@ -33,6 +33,7 @@ def csv_to_wfdb(\n header=True,\n delimiter=\",\",\n verbose=False,\n+ write_dir=\"\",\n ):\n \"\"\"\n Read a WFDB header file and return either a `Record` object with the\n@@ -235,6 +236,10 @@ def csv_to_wfdb(\n verbose : bool, optional\n Whether to print all the information read about the file (True) or\n not (False).\n+ write_dir : str, optional\n+ The directory where the output files will be saved. If write_dir is not\n+ provided, the output files will be saved in the same directory as the\n+ input file.\n \n Returns\n -------\n@@ -291,6 +296,7 @@ def csv_to_wfdb(\n df_CSV = pd.read_csv(file_name, delimiter=delimiter, header=None)\n if verbose:\n print(\"Successfully read CSV\")\n+\n # Extract the entire signal from the dataframe\n p_signal = df_CSV.values\n # The dataframe should be in (`sig_len`, `n_sig`) dimensions\n@@ -300,10 +306,11 @@ def csv_to_wfdb(\n n_sig = p_signal.shape[1]\n if verbose:\n print(\"Number of signals: {}\".format(n_sig))\n+\n # Check if signal names are valid and set defaults\n if not sig_name:\n if header:\n- sig_name = df_CSV.columns.to_list()\n+ sig_name = df_CSV.columns.tolist()\n if any(map(str.isdigit, sig_name)):\n print(\n \"WARNING: One or more of your signal names are numbers, this \"\n@@ -318,15 +325,12 @@ def csv_to_wfdb(\n if verbose:\n print(\"Signal names: {}\".format(sig_name))\n \n- # Set the output header file name to be the same, remove path\n- if os.sep in file_name:\n- file_name = file_name.split(os.sep)[-1]\n- record_name = file_name.replace(\".csv\", \"\")\n+ record_name = os.path.splitext(os.path.basename(file_name))[0]\n if verbose:\n- print(\"Output header: {}.hea\".format(record_name))\n+ print(\"Record name: {}.hea\".format(record_name))\n \n # Replace the CSV file tag with DAT\n- dat_file_name = file_name.replace(\".csv\", \".dat\")\n+ dat_file_name = record_name + \".dat\"\n dat_file_name = [dat_file_name] * n_sig\n if verbose:\n print(\"Output record: {}\".format(dat_file_name[0]))\n@@ -450,7 +454,6 @@ def csv_to_wfdb(\n if verbose:\n print(\"Record generated successfully\")\n return record\n-\n else:\n # Write the information to a record and header file\n wrsamp(\n@@ -465,6 +468,7 @@ def csv_to_wfdb(\n comments=comments,\n base_time=base_time,\n base_date=base_date,\n+ write_dir=write_dir,\n )\n if verbose:\n print(\"File generated successfully\")\n", "test_patch": "diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml\nindex fd6afbf..c1d170a 100644\n--- a/.github/workflows/run-tests.yml\n+++ b/.github/workflows/run-tests.yml\n@@ -19,9 +19,9 @@ jobs:\n os: [windows-latest, ubuntu-latest, macos-latest]\n python-version: [\"3.8\", \"3.9\", \"3.10\", \"3.11\"]\n steps:\n- - uses: actions/checkout@v3\n+ - uses: actions/checkout@v2\n - name: Set up Python ${{ matrix.python-version }}\n- uses: actions/setup-python@v4\n+ uses: actions/setup-python@v2\n with:\n python-version: ${{ matrix.python-version }}\n - name: Install dependencies\n@@ -69,7 +69,7 @@ jobs:\n build-documentation:\n runs-on: ubuntu-20.04\n steps:\n- - uses: actions/checkout@v3\n+ - uses: actions/checkout@v2\n - name: Install dependencies\n run: |\n python -m pip install --upgrade pip\ndiff --git a/tests/io/test_convert.py b/tests/io/test_convert.py\nindex aa7ba78..cf97f70 100644\n--- a/tests/io/test_convert.py\n+++ b/tests/io/test_convert.py\n@@ -1,14 +1,22 @@\n+import os\n+import shutil\n+import unittest\n+\n import numpy as np\n \n from wfdb.io.record import rdrecord\n from wfdb.io.convert.edf import read_edf\n+from wfdb.io.convert.csv import csv_to_wfdb\n+\n \n+class TestEdfToWfdb:\n+ \"\"\"\n+ Tests for the io.convert.edf module.\n+ \"\"\"\n \n-class TestConvert:\n def test_edf_uniform(self):\n \"\"\"\n EDF format conversion to MIT for uniform sample rates.\n-\n \"\"\"\n # Uniform sample rates\n record_MIT = rdrecord(\"sample-data/n16\").__dict__\n@@ -60,7 +68,6 @@ def test_edf_uniform(self):\n def test_edf_non_uniform(self):\n \"\"\"\n EDF format conversion to MIT for non-uniform sample rates.\n-\n \"\"\"\n # Non-uniform sample rates\n record_MIT = rdrecord(\"sample-data/wave_4\").__dict__\n@@ -108,3 +115,65 @@ def test_edf_non_uniform(self):\n \n target_results = len(fields) * [True]\n assert np.array_equal(test_results, target_results)\n+\n+\n+class TestCsvToWfdb(unittest.TestCase):\n+ \"\"\"\n+ Tests for the io.convert.csv module.\n+ \"\"\"\n+\n+ def setUp(self):\n+ \"\"\"\n+ Create a temporary directory containing data for testing.\n+\n+ Load 100.dat file for comparison to 100.csv file.\n+ \"\"\"\n+ self.test_dir = \"test_output\"\n+ os.makedirs(self.test_dir, exist_ok=True)\n+\n+ self.record_100_csv = \"sample-data/100.csv\"\n+ self.record_100_dat = rdrecord(\"sample-data/100\", physical=True)\n+\n+ def tearDown(self):\n+ \"\"\"\n+ Remove the temporary directory after the test.\n+ \"\"\"\n+ if os.path.exists(self.test_dir):\n+ shutil.rmtree(self.test_dir)\n+\n+ def test_write_dir(self):\n+ \"\"\"\n+ Call the function with the write_dir argument.\n+ \"\"\"\n+ csv_to_wfdb(\n+ file_name=self.record_100_csv,\n+ fs=360,\n+ units=\"mV\",\n+ write_dir=self.test_dir,\n+ )\n+\n+ # Check if the output files are created in the specified directory\n+ base_name = os.path.splitext(os.path.basename(self.record_100_csv))[0]\n+ expected_dat_file = os.path.join(self.test_dir, f\"{base_name}.dat\")\n+ expected_hea_file = os.path.join(self.test_dir, f\"{base_name}.hea\")\n+\n+ self.assertTrue(os.path.exists(expected_dat_file))\n+ self.assertTrue(os.path.exists(expected_hea_file))\n+\n+ # Check that newly written file matches the 100.dat file\n+ record_write = rdrecord(os.path.join(self.test_dir, base_name))\n+\n+ self.assertEqual(record_write.fs, 360)\n+ self.assertEqual(record_write.fs, self.record_100_dat.fs)\n+ self.assertEqual(record_write.units, [\"mV\", \"mV\"])\n+ self.assertEqual(record_write.units, self.record_100_dat.units)\n+ self.assertEqual(record_write.sig_name, [\"MLII\", \"V5\"])\n+ self.assertEqual(record_write.sig_name, self.record_100_dat.sig_name)\n+ self.assertEqual(record_write.p_signal.size, 1300000)\n+ self.assertEqual(\n+ record_write.p_signal.size, self.record_100_dat.p_signal.size\n+ )\n+\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n", "FAIL_TO_PASS": ["tests/io/test_convert.py::TestCsvToWfdb::test_write_dir"]}], "all_FAIL_TO_PASS": ["tests/io/test_convert.py::TestCsvToWfdb::test_write_dir"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "QuickPay__quickpay-python-client-13_x1", "level": 1, "source": "swerebench", "repo": "QuickPay/quickpay-python-client", "image": "swerebench/sweb.eval.x86_64.quickpay_1776_quickpay-python-client-13:latest", "base_commit": "d74eb0caf3d12ff53617b156f5f6f35189cf13b3", "num_bugs": 1, "bugs": [{"instance_id": "QuickPay__quickpay-python-client-13", "base_commit": "d74eb0caf3d12ff53617b156f5f6f35189cf13b3", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nnew file mode 100644\nindex 0000000..3ae5eb0\n--- /dev/null\n+++ b/CHANGELOG.md\n@@ -0,0 +1,7 @@\n+# Change Log\n+All notable changes to this project will be documented in this file.\n+This project adheres to [Semantic Versioning](http://semver.org/).\n+\n+## [UNRELEASED] - 0000-00-00\n+### Added\n+- Support callback_url in API requests (#10)\n\\ No newline at end of file\ndiff --git a/quickpay_api_client/api.py b/quickpay_api_client/api.py\nindex 72ef0f1..0295f02 100644\n--- a/quickpay_api_client/api.py\n+++ b/quickpay_api_client/api.py\n@@ -50,6 +50,10 @@ class QPApi(object):\n \"User-Agent\": \"quickpay-python-client, v%s\" % quickpay_api_client.__version__\n }\n \n+ callback_url = kwargs.pop(\"callback_url\", None)\n+ if callback_url:\n+ headers[\"Quickpay-Callback-Url\"] = callback_url\n+\n if self.secret:\n headers[\"Authorization\"\n ] = \"Basic {0}\".format(_base64_encode(self.secret))\n", "test_patch": "diff --git a/quickpay_api_client/tests/api_tests.py b/quickpay_api_client/tests/api_tests.py\nindex 8133e8f..066235b 100644\n--- a/quickpay_api_client/tests/api_tests.py\n+++ b/quickpay_api_client/tests/api_tests.py\n@@ -43,6 +43,15 @@ class TestApi(object):\n assert_equal(req_headers['Accept-Version'], 'v10')\n assert req_headers['User-Agent']\n \n+ @responses.activate\n+ def test_callback_url_headers(self):\n+ self.setup_request()\n+ callback_url = \"https://foo.bar\"\n+ res = self.api.perform(\"get\", \"/test\", callback_url=callback_url)\n+\n+ req_headers = responses.calls[0].request.headers\n+ assert_equal(req_headers['Quickpay-Callback-Url'], callback_url)\n+\n @responses.activate\n def test_perform_when_raw(self):\n self.setup_request()\n", "FAIL_TO_PASS": ["quickpay_api_client/tests/api_tests.py::TestApi::test_callback_url_headers"]}], "all_FAIL_TO_PASS": ["quickpay_api_client/tests/api_tests.py::TestApi::test_callback_url_headers"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MatterMiners__tardis-119_x1", "level": 1, "source": "swerebench", "repo": "MatterMiners/tardis", "image": "swerebench/sweb.eval.x86_64.matterminers_1776_tardis-119:latest", "base_commit": "60d00ae8a6adc720903632ef823941418210ccd7", "num_bugs": 1, "bugs": [{"instance_id": "MatterMiners__tardis-119", "base_commit": "60d00ae8a6adc720903632ef823941418210ccd7", "gold_patch": "diff --git a/docs/source/executors/executors.rst b/docs/source/executors/executors.rst\nindex 2bb46bb..711d444 100644\n--- a/docs/source/executors/executors.rst\n+++ b/docs/source/executors/executors.rst\n@@ -7,9 +7,13 @@ Executors\n .. container:: left-col\n \n All executors can be loaded using YAML tags using the (`!Tag`) syntax. More details are available in the\n- `PyYAML documentation`_\n+ `PyYAML documentation`_.\n+\n+ Alternatively you can also use the legacy `COBalD object initialisation syntax`_ to construct executors.\n+ But it is discouraged.\n \n .. _PyYAML documentation: https://pyyaml.org/wiki/PyYAMLDocumentation\n+ .. _COBalD object initialisation syntax: https://cobald.readthedocs.io/en/latest/source/daemon/config.html#object-references\n \n Shell Executor\n --------------\n@@ -26,6 +30,12 @@ Shell Executor\n \n !ShellExecutor\n \n+ .. rubric:: Example configuration (`COBalD` legacy object initialisation)\n+\n+ .. code-block:: yaml\n+\n+ __type__: tardis.utilities.executors.shellexecutor.ShellExecutor\n+\n SSH Executor\n ------------\n \n@@ -49,3 +59,12 @@ SSH Executor\n client_keys:\n - /opt/tardis/ssh/tardis\n \n+ .. rubric:: Example configuration (`COBalD` legacy object initialisation)\n+\n+ .. code-block:: yaml\n+\n+ __type__: tardis.utilities.executors.sshexecutor.SSHExecutor\n+ host: login.dorie.somewherein.de\n+ username: clown\n+ client_keys:\n+ - /opt/tardis/ssh/tardis\ndiff --git a/tardis/configuration/configuration.py b/tardis/configuration/configuration.py\nindex b02bc0f..f5ea52d 100644\n--- a/tardis/configuration/configuration.py\n+++ b/tardis/configuration/configuration.py\n@@ -6,22 +6,26 @@ from ..utilities.attributedict import convert_to_attribute_dict\n from ..utilities.executors import * # noqa: F403, F401\n from ..utilities.simulators import * # noqa: F403, F401\n \n+from cobald.daemon.config.mapping import Translator\n+\n from base64 import b64encode\n import os\n import yaml\n \n \n-def encode_user_data(obj):\n+def translate_config(obj):\n if isinstance(obj, AttributeDict):\n for key, value in obj.items():\n- if key == \"user_data\":\n+ if key == \"user_data\": # base64 encode user data\n with open(os.path.join(os.getcwd(), obj[key]), \"rb\") as f:\n obj[key] = b64encode(f.read())\n+ elif key == \"__type__\": # do legacy object initialisation\n+ return Translator().translate_hierarchy(obj)\n else:\n- obj[key] = encode_user_data(value)\n+ obj[key] = translate_config(value)\n return obj\n elif isinstance(obj, list):\n- return [encode_user_data(item) for item in obj]\n+ return [translate_config(item) for item in obj]\n else:\n return obj\n \n@@ -42,5 +46,5 @@ class Configuration(Borg):\n \"\"\"\n with open(config_file, \"r\") as config_file:\n self._shared_state.update(\n- encode_user_data(convert_to_attribute_dict(yaml.safe_load(config_file)))\n+ translate_config(convert_to_attribute_dict(yaml.safe_load(config_file)))\n )\n", "test_patch": "diff --git a/tests/configuration_t/Sites.yml b/tests/configuration_t/Sites.yml\nindex 8c5a8c9..4274fc6 100644\n--- a/tests/configuration_t/Sites.yml\n+++ b/tests/configuration_t/Sites.yml\n@@ -1,8 +1,17 @@\n Sites:\n - name: EXOSCALE\n adapter: CloudStack\n+ - name: SLURM\n+ adapter: Slurm\n \n EXOSCALE:\n MachineTypeConfiguration:\n Micro:\n- user_data: tests/data/exoscale.ini\n\\ No newline at end of file\n+ user_data: tests/data/exoscale.ini\n+SLURM:\n+ executor:\n+ __type__: tardis.utilities.executors.sshexecutor.SSHExecutor\n+ host: somehost.de\n+ username: someuser\n+ client_keys:\n+ - \"where the private key is\"\ndiff --git a/tests/configuration_t/test_configuration.py b/tests/configuration_t/test_configuration.py\nindex 9c0ed59..81d1155 100644\n--- a/tests/configuration_t/test_configuration.py\n+++ b/tests/configuration_t/test_configuration.py\n@@ -1,4 +1,5 @@\n from tardis.configuration.configuration import Configuration\n+from tardis.utilities.executors.sshexecutor import SSHExecutor\n \n from unittest import TestCase\n import os\n@@ -24,22 +25,37 @@ class TestConfiguration(TestCase):\n self.configuration1.load_config(os.path.join(self.test_path, \"Sites.yml\"))\n self.assertEqual(id(self.configuration1.Sites), id(self.configuration2.Sites))\n self.assertEqual(\n- self.configuration1.Sites, [dict(name=\"EXOSCALE\", adapter=\"CloudStack\")]\n+ self.configuration1.Sites,\n+ [\n+ dict(name=\"EXOSCALE\", adapter=\"CloudStack\"),\n+ dict(name=\"SLURM\", adapter=\"Slurm\"),\n+ ],\n )\n self.assertEqual(\n self.configuration2.CloudStackAIO,\n {\"api_key\": \"asdfghjkl\", \"api_secret\": \"qwertzuiop\"},\n )\n \n- def test_base64_encoded_user_data(self):\n- result = (\n+ def test_translate_config(self):\n+ b64_result = (\n b\"I2Nsb3VkLWNvbmZpZwoKd3JpdGVfZmlsZXM6CiAgLSBwYXRoOiAvZXRjL2huc2NpY2xvdWQvc2l0ZS1pZC5jZmcKICAgIGNvbn\",\n b\"RlbnQ6IHwKICAgICAgRXhvc2NhbGUKICAgIHBlcm1pc3Npb25zOiAnMDY0NCcK\",\n )\n self.configuration1.load_config(os.path.join(self.test_path, \"Sites.yml\"))\n self.assertEqual(\n self.configuration1.EXOSCALE.MachineTypeConfiguration.Micro.user_data,\n- b\"\".join(result),\n+ b\"\".join(b64_result),\n+ )\n+\n+ executor = self.configuration1.SLURM.executor\n+ self.assertIsInstance(executor, SSHExecutor)\n+ self.assertEqual(\n+ executor._parameters,\n+ dict(\n+ host=\"somehost.de\",\n+ username=\"someuser\",\n+ client_keys=[\"where the private key is\"],\n+ ),\n )\n \n def test_access_missing_attribute(self):\n", "FAIL_TO_PASS": ["tests/configuration_t/test_configuration.py::TestConfiguration::test_translate_config"]}], "all_FAIL_TO_PASS": ["tests/configuration_t/test_configuration.py::TestConfiguration::test_translate_config"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PaccMann__paccmann_datasets-13_x1", "level": 1, "source": "swerebench", "repo": "PaccMann/paccmann_datasets", "image": "swerebench/sweb.eval.x86_64.paccmann_1776_paccmann_datasets-13:latest", "base_commit": "def0673e39f2e6a6e86f6d2456eab4e7b770980f", "num_bugs": 1, "bugs": [{"instance_id": "PaccMann__paccmann_datasets-13", "base_commit": "def0673e39f2e6a6e86f6d2456eab4e7b770980f", "gold_patch": "diff --git a/pytoda/smiles/transforms.py b/pytoda/smiles/transforms.py\nindex 6a9288f..a40439f 100644\n--- a/pytoda/smiles/transforms.py\n+++ b/pytoda/smiles/transforms.py\n@@ -95,7 +95,7 @@ class ToTensor(Transform):\n \"\"\"\n return torch.tensor(\n token_indexes, dtype=self.dtype, device=self.device\n- ).view(-1, 1)\n+ ).view(-1, 1).squeeze()\n \n \n class RemoveIsomery(Transform):\n", "test_patch": "diff --git a/pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py b/pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py\nindex f3033fb..10861c0 100644\n--- a/pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py\n+++ b/pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py\n@@ -111,10 +111,7 @@ class TestDrugSensitivityDataset(unittest.TestCase):\n np.testing.assert_almost_equal(\n token_indexes_tensor.numpy(),\n np.array(\n- [\n- [padding_index], [padding_index], [c_index],\n- [o_index]\n- ]\n+ [padding_index, padding_index, c_index, o_index]\n )\n )\n np.testing.assert_almost_equal(\n@@ -176,7 +173,7 @@ class TestDrugSensitivityDataset(unittest.TestCase):\n ic50_batch\n )\n ) in enumerate(data_loader):\n- self.assertEqual(token_indexes_batch.size(), (2, 4, 1))\n+ self.assertEqual(token_indexes_batch.size(), (2, 4))\n self.assertEqual(gene_expression_batch.size(), (2, 4))\n self.assertEqual(ic50_batch.size(), (2, 1))\n if batch_index > 4:\ndiff --git a/pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py b/pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py\nindex cbd7c76..8043634 100644\n--- a/pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py\n+++ b/pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py\n@@ -111,10 +111,7 @@ class TestDrugSensitivityDataset(unittest.TestCase):\n np.testing.assert_almost_equal(\n token_indexes_tensor.numpy(),\n np.array(\n- [\n- [padding_index], [padding_index], [c_index],\n- [o_index]\n- ]\n+ [padding_index, padding_index, c_index, o_index]\n )\n )\n np.testing.assert_almost_equal(\n@@ -176,7 +173,7 @@ class TestDrugSensitivityDataset(unittest.TestCase):\n ic50_batch\n )\n ) in enumerate(data_loader):\n- self.assertEqual(token_indexes_batch.size(), (2, 4, 1))\n+ self.assertEqual(token_indexes_batch.size(), (2, 4))\n self.assertEqual(gene_expression_batch.size(), (2, 4))\n self.assertEqual(ic50_batch.size(), (2, 1))\n if batch_index > 4:\ndiff --git a/pytoda/datasets/tests/test_smiles_eager_dataset.py b/pytoda/datasets/tests/test_smiles_eager_dataset.py\nindex 2479c3c..7c79c5b 100644\n--- a/pytoda/datasets/tests/test_smiles_eager_dataset.py\n+++ b/pytoda/datasets/tests/test_smiles_eager_dataset.py\n@@ -169,7 +169,7 @@ class TestSMILESDatasetEagerBackend(unittest.TestCase):\n smiles_dataset, batch_size=4, shuffle=True\n )\n for batch_index, batch in enumerate(data_loader):\n- self.assertEqual(batch.shape, (4, 4, 1))\n+ self.assertEqual(batch.shape, (4, 4))\n if batch_index > 10:\n break\n \ndiff --git a/pytoda/datasets/tests/test_smiles_lazy_dataset.py b/pytoda/datasets/tests/test_smiles_lazy_dataset.py\nindex 01b5929..d2791f3 100644\n--- a/pytoda/datasets/tests/test_smiles_lazy_dataset.py\n+++ b/pytoda/datasets/tests/test_smiles_lazy_dataset.py\n@@ -169,7 +169,7 @@ class TestSMILESDatasetLazyBackend(unittest.TestCase):\n smiles_dataset, batch_size=4, shuffle=True\n )\n for batch_index, batch in enumerate(data_loader):\n- self.assertEqual(batch.shape, (4, 4, 1))\n+ self.assertEqual(batch.shape, (4, 4))\n if batch_index > 10:\n break\n \n", "FAIL_TO_PASS": ["pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py::TestDrugSensitivityDataset::test___getitem__", "pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py::TestDrugSensitivityDataset::test_data_loader", "pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py::TestDrugSensitivityDataset::test___getitem__", "pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py::TestDrugSensitivityDataset::test_data_loader", "pytoda/datasets/tests/test_smiles_eager_dataset.py::TestSMILESDatasetEagerBackend::test_data_loader", "pytoda/datasets/tests/test_smiles_lazy_dataset.py::TestSMILESDatasetLazyBackend::test_data_loader"]}], "all_FAIL_TO_PASS": ["pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py::TestDrugSensitivityDataset::test___getitem__", "pytoda/datasets/tests/test_drug_sensitivity_eager_dataset.py::TestDrugSensitivityDataset::test_data_loader", "pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py::TestDrugSensitivityDataset::test___getitem__", "pytoda/datasets/tests/test_drug_sensitivity_lazy_dataset.py::TestDrugSensitivityDataset::test_data_loader", "pytoda/datasets/tests/test_smiles_eager_dataset.py::TestSMILESDatasetEagerBackend::test_data_loader", "pytoda/datasets/tests/test_smiles_lazy_dataset.py::TestSMILESDatasetLazyBackend::test_data_loader"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "JoaquinAmatRodrigo__skforecast-819_x1", "level": 1, "source": "swerebench", "repo": "JoaquinAmatRodrigo/skforecast", "image": "swerebench/sweb.eval.x86_64.joaquinamatrodrigo_1776_skforecast-819:latest", "base_commit": "42efb43980ea0f9739bcf54a30643e9ea18a1556", "num_bugs": 1, "bugs": [{"instance_id": "JoaquinAmatRodrigo__skforecast-819", "base_commit": "42efb43980ea0f9739bcf54a30643e9ea18a1556", "gold_patch": "diff --git a/skforecast/ForecasterAutoreg/ForecasterAutoreg.py b/skforecast/ForecasterAutoreg/ForecasterAutoreg.py\nindex bde93a71..f93b7626 100644\n--- a/skforecast/ForecasterAutoreg/ForecasterAutoreg.py\n+++ b/skforecast/ForecasterAutoreg/ForecasterAutoreg.py\n@@ -1058,14 +1058,14 @@ class ForecasterAutoreg(ForecasterBase):\n \n def _create_predict_inputs(\n self,\n- steps: int,\n+ steps: Union[int, str, pd.Timestamp], \n last_window: Optional[Union[pd.Series, pd.DataFrame]] = None,\n exog: Optional[Union[pd.Series, pd.DataFrame]] = None,\n predict_boot: bool = False,\n use_in_sample_residuals: bool = True,\n use_binned_residuals: bool = False,\n- check_inputs: bool = True\n- ) -> Tuple[np.ndarray, Optional[np.ndarray], pd.Index]:\n+ check_inputs: bool = True,\n+ ) -> Tuple[np.ndarray, Optional[np.ndarray], pd.Index, int]:\n \"\"\"\n Create the inputs needed for the first iteration of the prediction \n process. As this is a recursive process, the last window is updated at \n@@ -1073,8 +1073,9 @@ class ForecasterAutoreg(ForecasterBase):\n \n Parameters\n ----------\n- steps : int\n- Number of future steps predicted.\n+ steps : int, str, pandas Timestamp\n+ If steps is int, number of steps to predict. \n+ If str or pandas Datetime, the prediction will be up to that date.\n last_window : pandas Series, pandas DataFrame, default `None`\n Series values used to create the predictors (lags) needed in the \n first iteration of the prediction (t + 1).\n@@ -1112,6 +1113,8 @@ class ForecasterAutoreg(ForecasterBase):\n Exogenous variable/s included as predictor/s.\n prediction_index : pandas Index\n Index of the predictions.\n+ steps: int\n+ Number of future steps predicted.\n \n \"\"\"\n \n@@ -1176,13 +1179,14 @@ class ForecasterAutoreg(ForecasterBase):\n else:\n exog_values = None\n \n- prediction_index = expand_index(\n- index = last_window_index,\n- steps = steps\n- )\n+ prediction_index, steps = expand_index(\n+ index = last_window_index,\n+ steps = steps,\n+ )\n+\n+ return last_window_values, exog_values, prediction_index, steps\n+\n \n- return last_window_values, exog_values, prediction_index\n- \n def _recursive_predict(\n self,\n steps: int,\n@@ -1311,9 +1315,8 @@ class ForecasterAutoreg(ForecasterBase):\n \n \"\"\"\n \n- last_window_values, exog_values, prediction_index = self._create_predict_inputs(\n+ last_window_values, exog_values, prediction_index, steps = self._create_predict_inputs(\n steps=steps, last_window=last_window, exog=exog\n- )\n \n predictions = self._recursive_predict(\n steps = steps,\n@@ -1357,7 +1360,7 @@ class ForecasterAutoreg(ForecasterBase):\n \n def predict(\n self,\n- steps: int,\n+ steps: Union[int, str, pd.Timestamp],\n last_window: Optional[Union[pd.Series, pd.DataFrame]] = None,\n exog: Optional[Union[pd.Series, pd.DataFrame]] = None,\n check_inputs: bool = True\n@@ -1368,8 +1371,9 @@ class ForecasterAutoreg(ForecasterBase):\n \n Parameters\n ----------\n- steps : int\n- Number of future steps predicted.\n+ steps : int, str, pandas Timestamp\n+ If steps is int, number of steps to predict. \n+ If str or pandas Datetime, the prediction will be up to that date.\n last_window : pandas Series, pandas DataFrame, default `None`\n Series values used to create the predictors (lags) needed in the \n first iteration of the prediction (t + 1).\n@@ -1390,10 +1394,10 @@ class ForecasterAutoreg(ForecasterBase):\n \n \"\"\"\n \n- last_window_values, exog_values, prediction_index = self._create_predict_inputs(\n+ last_window_values, exog_values, prediction_index, steps = self._create_predict_inputs(\n steps=steps, last_window=last_window, exog=exog, check_inputs=check_inputs\n )\n- \n+\n predictions = self._recursive_predict(\n steps = steps,\n last_window_values = last_window_values,\n@@ -1421,7 +1425,7 @@ class ForecasterAutoreg(ForecasterBase):\n \n def predict_bootstrapping(\n self,\n- steps: int,\n+ steps: Union[int, str, pd.Timestamp],\n last_window: Optional[pd.Series] = None,\n exog: Optional[Union[pd.Series, pd.DataFrame]] = None,\n n_boot: int = 250,\n@@ -1437,8 +1441,9 @@ class ForecasterAutoreg(ForecasterBase):\n \n Parameters\n ----------\n- steps : int\n- Number of future steps predicted.\n+ steps : int, str, pandas Timestamp\n+ If steps is int, number of steps to predict. \n+ If str or pandas Datetime, the prediction will be up to that date.\n last_window : pandas Series, default `None`\n Series values used to create the predictors (lags) needed in the \n first iteration of the prediction (t + 1).\n@@ -1483,7 +1488,8 @@ class ForecasterAutoreg(ForecasterBase):\n (\n last_window_values,\n exog_values,\n- prediction_index\n+ prediction_index,\n+ steps\n ) = self._create_predict_inputs(\n steps = steps, \n last_window = last_window, \n@@ -1563,7 +1569,7 @@ class ForecasterAutoreg(ForecasterBase):\n \n def predict_interval(\n self,\n- steps: int,\n+ steps: Union[int, str, pd.Timestamp],\n last_window: Optional[pd.Series] = None,\n exog: Optional[Union[pd.Series, pd.DataFrame]] = None,\n interval: list = [5, 95],\n@@ -1579,8 +1585,9 @@ class ForecasterAutoreg(ForecasterBase):\n \n Parameters\n ----------\n- steps : int\n- Number of future steps predicted.\n+ steps : int, str, pandas Timestamp\n+ If steps is int, number of steps to predict. \n+ If str or pandas Datetime, the prediction will be up to that date.\n last_window : pandas Series, default `None`\n Series values used to create the predictors (lags) needed in the \n first iteration of the prediction (t + 1).\n@@ -1659,7 +1666,7 @@ class ForecasterAutoreg(ForecasterBase):\n \n def predict_quantiles(\n self,\n- steps: int,\n+ steps: Union[int, str, pd.Timestamp],\n last_window: Optional[pd.Series] = None,\n exog: Optional[Union[pd.Series, pd.DataFrame]] = None,\n quantiles: list = [0.05, 0.5, 0.95],\n@@ -1675,8 +1682,9 @@ class ForecasterAutoreg(ForecasterBase):\n \n Parameters\n ----------\n- steps : int\n- Number of future steps predicted.\n+ steps : int, str, pandas Timestamp\n+ If steps is int, number of steps to predict. \n+ If str or pandas Datetime, the prediction will be up to that date.\n last_window : pandas Series, default `None`\n Series values used to create the predictors (lags) needed in the \n first iteration of the prediction (t + 1).\n@@ -1742,7 +1750,7 @@ class ForecasterAutoreg(ForecasterBase):\n \n def predict_dist(\n self,\n- steps: int,\n+ steps: Union[int, str, pd.Timestamp],\n distribution: object,\n last_window: Optional[pd.Series] = None,\n exog: Optional[Union[pd.Series, pd.DataFrame]] = None,\n@@ -1758,8 +1766,9 @@ class ForecasterAutoreg(ForecasterBase):\n \n Parameters\n ----------\n- steps : int\n- Number of future steps predicted.\n+ steps : int, str, pandas Timestamp\n+ If steps is int, number of steps to predict. \n+ If str or pandas Datetime, the prediction will be up to that date.\n distribution : Object\n A distribution object from scipy.stats.\n last_window : pandas Series, default `None`\ndiff --git a/skforecast/utils/utils.py b/skforecast/utils/utils.py\nindex 204475fe..4a99cb51 100644\n--- a/skforecast/utils/utils.py\n+++ b/skforecast/utils/utils.py\n@@ -1472,8 +1472,9 @@ def exog_to_direct_numpy(\n \n def expand_index(\n index: Union[pd.Index, None], \n- steps: int\n-) -> pd.Index:\n+ steps: Union[int, str, pd.Timestamp],\n+ **kwargs\n+) -> Tuple[pd.Index, int]:\n \"\"\"\n Create a new index of length `steps` starting at the end of the index.\n \n@@ -1481,8 +1482,11 @@ def expand_index(\n ----------\n index : pandas Index, None\n Original index.\n- steps : int\n- Number of steps to expand.\n+ steps : int, str, pandas Timestamp]\n+ If steps is int, number of steps to expand. If str or pandas Datetime, \n+ expand index to this date (str must be convertible to pandas Datetime format).\n+ **kwargs\n+ Additional keyword arguments to pass to `pd.to_datetime()`.\n \n Returns\n -------\n@@ -1490,7 +1494,24 @@ def expand_index(\n New index.\n \n \"\"\"\n- \n+\n+ if isinstance(steps, (str, pd.Timestamp)):\n+ # Changes `steps` to integer based on datetime expansion\n+ if not isinstance(index, pd.DatetimeIndex):\n+ raise ValueError( \"Argument `index` must be a pandas DatetimeIndex when `steps` is a datetime.\")\n+ \n+ else:\n+ target_date = pd.to_datetime(steps, **kwargs)\n+ last_date = pd.to_datetime(index[-1])\n+ if target_date <= last_date:\n+ raise ValueError(\"The provided date is earlier than or equal to the last observation date.\")\n+ \n+ steps_diff = pd.date_range(start=last_date, end=target_date, freq=index.freq)\n+ steps = len(steps_diff) - 1\n+\n+ elif not isinstance(steps, int):\n+ raise TypeError(\"Argument `steps` must be an integer, string or pandas Timestamp.\")\n+\n if isinstance(index, pd.Index):\n \n if isinstance(index, pd.DatetimeIndex):\n@@ -1514,7 +1535,7 @@ def expand_index(\n stop = steps\n )\n \n- return new_index\n+ return new_index, steps\n \n \n def transform_numpy(\n", "test_patch": "diff --git a/skforecast/utils/tests/test_expand_index.py b/skforecast/utils/tests/test_expand_index.py\nindex 788b84a9..40c36a23 100644\n--- a/skforecast/utils/tests/test_expand_index.py\n+++ b/skforecast/utils/tests/test_expand_index.py\n@@ -5,6 +5,68 @@ import pandas as pd\n from skforecast.utils import expand_index\n \n \n+def test_ValueError_expand_index_when_date_is_before_last_index():\n+ \"\"\"\n+ Test ValueError is raised when the provided date is earlier than or equal to the last date in index.\n+ \"\"\"\n+ index = pd.DatetimeIndex(['1990-01-01', '1990-01-02', '1990-01-03'], \n+ dtype='datetime64[ns]', freq='D')\n+ err_msg = \"The provided date is earlier than or equal to the last observation date.\"\n+ \n+ with pytest.raises(ValueError, match=err_msg):\n+ expand_index(index, steps='1990-01-02')\n+\n+\n+def test_ValueError_expand_index_when_index_is_not_DatetimeIndex():\n+ \"\"\"\n+ Test ValueError is raised when `steps` is a date but the index is not a DatetimeIndex.\n+ \"\"\"\n+ index = pd.RangeIndex(start=0, stop=3, step=1)\n+ err_msg = \"Argument `index` must be a pandas DatetimeIndex when `steps` is a datetime.\"\n+ \n+ with pytest.raises(ValueError, match=err_msg):\n+ expand_index(index, steps='1990-01-10')\n+\n+\n+def test_output_expand_index_when_steps_is_string_date():\n+ \"\"\"\n+ Test values returned by expand_index when `steps` is a string date.\n+ \"\"\"\n+ index = pd.DatetimeIndex(['1990-01-01', '1990-01-02', '1990-01-03'],\n+ dtype='datetime64[ns]', freq='D')\n+ expected = pd.DatetimeIndex(['1990-01-04', '1990-01-05', '1990-01-06', '1990-01-07'],\n+ dtype='datetime64[ns]', freq='D')\n+ results, _ = expand_index(index, steps='1990-01-07')\n+ \n+ assert (results == expected).all()\n+\n+\n+def test_output_expand_index_when_steps_is_Timestamp():\n+ \"\"\"\n+ Test values returned by expand_index when `steps` is a pd.Timestamp.\n+ \"\"\"\n+ index = pd.DatetimeIndex(['1990-01-01', '1990-01-02', '1990-01-03'],\n+ dtype='datetime64[ns]', freq='D')\n+ expected = pd.DatetimeIndex(['1990-01-04', '1990-01-05', '1990-01-06', '1990-01-07'],\n+ dtype='datetime64[ns]', freq='D')\n+ results, _ = expand_index(index, steps=pd.Timestamp('1990-01-07'))\n+ \n+ assert (results == expected).all()\n+\n+\n+def test_output_expand_index_when_steps_is_string_date_with_kwargs():\n+ \"\"\"\n+ Test values returned by expand_index when `steps` is a string date and `kwargs` are passed.\n+ \"\"\"\n+ index = pd.DatetimeIndex(['1990-01-01', '1990-01-02', '1990-01-03'],\n+ dtype='datetime64[ns]', freq='D')\n+ expected = pd.DatetimeIndex(['1990-01-04', '1990-01-05', '1990-01-06', '1990-01-07'],\n+ dtype='datetime64[ns]', freq='D')\n+ results, _ = expand_index(index, steps='1990-07-01', format='%Y-%d-%m')\n+ \n+ assert (results == expected).all()\n+\n+\n def test_TypeError_expand_index_when_index_is_no_pandas_DatetimeIndex_or_RangeIndex():\n \"\"\"\n Test TypeError is raised when input is not a pandas DatetimeIndex or RangeIndex.\n@@ -24,7 +86,7 @@ def test_output_expand_index_when_index_is_DatetimeIndex():\n dtype='datetime64[ns]', freq='D')\n expected = pd.DatetimeIndex(['1990-01-04', '1990-01-05', '1990-01-06'],\n dtype='datetime64[ns]', freq='D')\n- results = expand_index(index, steps=3)\n+ results, _ = expand_index(index, steps=3)\n \n assert (results == expected).all()\n \n@@ -35,7 +97,7 @@ def test_output_expand_index_when_index_is_RangeIndex():\n \"\"\"\n index = pd.RangeIndex(start=0, stop=3, step=1)\n expected = pd.RangeIndex(start=3, stop=6, step=1)\n- results = expand_index(index, steps=3)\n+ results, _ = expand_index(index, steps=3)\n \n assert (results == expected).all()\n \n@@ -46,6 +108,6 @@ def test_output_expand_index_when_index_is_not_pandas_index():\n \"\"\"\n index = ['0', '1', '2']\n expected = pd.RangeIndex(start=0, stop=3, step=1)\n- results = expand_index(index, steps=3)\n+ results, _ = expand_index(index, steps=3)\n \n- assert (results == expected).all()\n\\ No newline at end of file\n+ assert (results == expected).all()\n", "FAIL_TO_PASS": ["skforecast/utils/tests/test_expand_index.py::test_ValueError_expand_index_when_date_is_before_last_index", "skforecast/utils/tests/test_expand_index.py::test_ValueError_expand_index_when_index_is_not_DatetimeIndex", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_steps_is_string_date", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_steps_is_Timestamp", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_steps_is_string_date_with_kwargs", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_index_is_DatetimeIndex", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_index_is_RangeIndex", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_index_is_not_pandas_index"]}], "all_FAIL_TO_PASS": ["skforecast/utils/tests/test_expand_index.py::test_ValueError_expand_index_when_date_is_before_last_index", "skforecast/utils/tests/test_expand_index.py::test_ValueError_expand_index_when_index_is_not_DatetimeIndex", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_steps_is_string_date", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_steps_is_Timestamp", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_steps_is_string_date_with_kwargs", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_index_is_DatetimeIndex", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_index_is_RangeIndex", "skforecast/utils/tests/test_expand_index.py::test_output_expand_index_when_index_is_not_pandas_index"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MasoniteFramework__core-16_x1", "level": 1, "source": "swerebench", "repo": "MasoniteFramework/core", "image": "swerebench/sweb.eval.x86_64.masoniteframework_1776_core-16:latest", "base_commit": "3f87388490aa65aa2906f9f3e6727d70f16c5509", "num_bugs": 1, "bugs": [{"instance_id": "MasoniteFramework__core-16", "base_commit": "3f87388490aa65aa2906f9f3e6727d70f16c5509", "gold_patch": "diff --git a/masonite/drivers/UploadDiskDriver.py b/masonite/drivers/UploadDiskDriver.py\nindex 410f732..e3721bc 100644\n--- a/masonite/drivers/UploadDiskDriver.py\n+++ b/masonite/drivers/UploadDiskDriver.py\n@@ -12,6 +12,8 @@ class UploadDiskDriver(object):\n if not location:\n location = self.config.DRIVERS['disk']['location']\n \n+ location += '/'\n+ \n open(location + filename, 'wb').write(fileitem.file.read())\n \n return location + filename\ndiff --git a/masonite/request.py b/masonite/request.py\nindex 8036a6f..7586018 100644\n--- a/masonite/request.py\n+++ b/masonite/request.py\n@@ -196,11 +196,18 @@ class Request(object):\n # if the url contains a parameter variable like @id:int\n if '@' in url:\n url = url.replace('@', '').replace(':int', '').replace(':string', '')\n- print('url after @', url)\n- compiled_url += '/' + str(self.param(url)) + '/' \n+ compiled_url += str(self.param(url)) + '/' \n else:\n- compiled_url += url\n- print('compiled_url:', compiled_url)\n+ compiled_url += url + '/'\n+\n+ # The loop isn't perfect and may have an unwanted trailing slash\n+ if compiled_url.endswith('/') and not self.redirect_url.endswith('/'):\n+ compiled_url = compiled_url[:-1]\n+ \n+ # The loop isn't perfect and may have 2 slashes next to eachother\n+ if '//' in compiled_url:\n+ compiled_url = compiled_url.replace('//', '/')\n+\n return compiled_url\n \n def has_subdomain(self):\ndiff --git a/setup.py b/setup.py\nindex 8e9a335..668e018 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -10,7 +10,7 @@ setup(\n 'masonite.testsuite',\n 'masonite.queues',\n ],\n- version='1.3.1',\n+ version='1.3.2',\n install_requires=[\n 'validator.py==1.2.5',\n 'cryptography==2.1.4',\n", "test_patch": "diff --git a/tests/test_requests.py b/tests/test_requests.py\nindex d68c2d8..f9b640f 100644\n--- a/tests/test_requests.py\n+++ b/tests/test_requests.py\n@@ -149,3 +149,58 @@ def test_request_has_subdomain_returns_bool():\n request.environ['HTTP_HOST'] = 'test.localhost.com'\n \n assert request.has_subdomain() is True\n+\n+def test_redirect_compiles_url():\n+ app = App()\n+ app.bind('Request', REQUEST)\n+ request = app.make('Request').load_app(app)\n+\n+ request.redirect('test/url')\n+\n+ assert request.compile_route_to_url() == '/test/url'\n+\n+def test_redirect_compiles_url_with_multiple_slashes():\n+ app = App()\n+ app.bind('Request', REQUEST)\n+ request = app.make('Request').load_app(app)\n+\n+ request.redirect('test/url/here')\n+\n+ assert request.compile_route_to_url() == '/test/url/here'\n+\n+def test_redirect_compiles_url_with_trailing_slash():\n+ app = App()\n+ app.bind('Request', REQUEST)\n+ request = app.make('Request').load_app(app)\n+\n+ request.redirect('test/url/here/')\n+\n+ assert request.compile_route_to_url() == '/test/url/here/'\n+\n+def test_redirect_compiles_url_with_parameters():\n+ app = App()\n+ app.bind('Request', REQUEST)\n+ request = app.make('Request').load_app(app)\n+\n+ request.redirect('test/@id').send({'id': '1'})\n+\n+ assert request.compile_route_to_url() == '/test/1'\n+\n+def test_redirect_compiles_url_with_multiple_parameters():\n+ app = App()\n+ app.bind('Request', REQUEST)\n+ request = app.make('Request').load_app(app)\n+\n+ request.redirect('test/@id/@test').send({'id': '1', 'test': 'user'})\n+\n+ assert request.compile_route_to_url() == '/test/1/user'\n+\n+def test_redirect_compiles_url_with_http():\n+ app = App()\n+ app.bind('Request', REQUEST)\n+ request = app.make('Request').load_app(app)\n+\n+ request.redirect('http://google.com')\n+\n+ assert request.compile_route_to_url() == 'http://google.com'\n+\n", "FAIL_TO_PASS": ["tests/test_requests.py::test_redirect_compiles_url", "tests/test_requests.py::test_redirect_compiles_url_with_multiple_slashes", "tests/test_requests.py::test_redirect_compiles_url_with_trailing_slash", "tests/test_requests.py::test_redirect_compiles_url_with_parameters", "tests/test_requests.py::test_redirect_compiles_url_with_multiple_parameters"]}], "all_FAIL_TO_PASS": ["tests/test_requests.py::test_redirect_compiles_url", "tests/test_requests.py::test_redirect_compiles_url_with_multiple_slashes", "tests/test_requests.py::test_redirect_compiles_url_with_trailing_slash", "tests/test_requests.py::test_redirect_compiles_url_with_parameters", "tests/test_requests.py::test_redirect_compiles_url_with_multiple_parameters"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Ch00k__ffmpy-84_x1", "level": 1, "source": "swerebench", "repo": "Ch00k/ffmpy", "image": "swerebench/sweb.eval.x86_64.ch00k_1776_ffmpy-84:latest", "base_commit": "69724733ea38cb3ac4bd2c8915c91bf9071d7270", "num_bugs": 1, "bugs": [{"instance_id": "Ch00k__ffmpy-84", "base_commit": "69724733ea38cb3ac4bd2c8915c91bf9071d7270", "gold_patch": "diff --git a/ffmpy/__init__.py b/ffmpy/__init__.py\nnew file mode 100644\nindex 0000000..fc682bb\n--- /dev/null\n+++ b/ffmpy/__init__.py\n@@ -0,0 +1,3 @@\n+from .ffmpy import FFExecutableNotFoundError, FFmpeg, FFprobe, FFRuntimeError\n+\n+__all__ = [\"FFmpeg\", \"FFprobe\", \"FFExecutableNotFoundError\", \"FFRuntimeError\"]\ndiff --git a/ffmpy.py b/ffmpy/ffmpy.py\nsimilarity index 100%\nrename from ffmpy.py\nrename to ffmpy/ffmpy.py\ndiff --git a/py.typed b/ffmpy/py.typed\nsimilarity index 100%\nrename from py.typed\nrename to ffmpy/py.typed\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 01e7dfc..bce62a5 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -40,7 +40,7 @@ classifiers = [\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS :: MacOS X\",\n ]\n-packages = [{ include = \"ffmpy.py\" }, { include = \"py.typed\" }]\n+packages = [{ include = \"ffmpy\" }]\n \n [tool.poetry.dependencies]\n python = \"^3.8\"\n", "test_patch": "diff --git a/tests/test_cmd_execution.py b/tests/test_cmd_execution.py\nindex fd9f559..576e242 100644\n--- a/tests/test_cmd_execution.py\n+++ b/tests/test_cmd_execution.py\n@@ -202,7 +202,7 @@ def test_terminate_process() -> None:\n assert ff.process.returncode == -15\n \n \n-@mock.patch(\"ffmpy.subprocess.Popen\")\n+@mock.patch(\"ffmpy.ffmpy.subprocess.Popen\")\n def test_custom_env(popen_mock: mock.MagicMock) -> None:\n ff = FFmpeg()\n popen_mock.return_value.communicate.return_value = (\"output\", \"error\")\n@@ -213,7 +213,7 @@ def test_custom_env(popen_mock: mock.MagicMock) -> None:\n )\n \n \n-@mock.patch(\"ffmpy.subprocess.Popen\")\n+@mock.patch(\"ffmpy.ffmpy.subprocess.Popen\")\n def test_arbitraty_popen_kwargs(popen_mock: mock.MagicMock) -> None:\n ff = FFmpeg()\n popen_mock.return_value.communicate.return_value = (\"output\", \"error\")\n", "FAIL_TO_PASS": ["tests/test_cmd_execution.py::test_custom_env", "tests/test_cmd_execution.py::test_arbitraty_popen_kwargs"]}], "all_FAIL_TO_PASS": ["tests/test_cmd_execution.py::test_custom_env", "tests/test_cmd_execution.py::test_arbitraty_popen_kwargs"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "RightBrain-Networks__auto-semver-51_x1", "level": 1, "source": "swerebench", "repo": "RightBrain-Networks/auto-semver", "image": "swerebench/sweb.eval.x86_64.rightbrain-networks_1776_auto-semver-51:latest", "base_commit": "eaebfcc3297fd1adb355069691cbf5e95eb31731", "num_bugs": 1, "bugs": [{"instance_id": "RightBrain-Networks__auto-semver-51", "base_commit": "eaebfcc3297fd1adb355069691cbf5e95eb31731", "gold_patch": "diff --git a/Jenkinsfile b/Jenkinsfile\nindex cbbd435..10aee15 100644\n--- a/Jenkinsfile\n+++ b/Jenkinsfile\n@@ -1,4 +1,4 @@\n-library('pipeline-library')\n+library('pipeline-library@bugfix/durable-task-workaround')\n \n pipeline {\n options { timestamps() }\n@@ -18,7 +18,7 @@ pipeline {\n stage('Self Version') {\n steps {\n withCredentials([usernamePassword(credentialsId: env.DOCKER_CREDENTIALS, usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {\n- sh(\"docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}\")\n+ sh(\"docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD\")\n }\n runAutoSemver(\"rightbrainnetworks/auto-semver:${SELF_SEMVER_TAG}\")\n }\n@@ -59,6 +59,7 @@ pipeline {\n agent {\n docker {\n image \"rightbrainnetworks/auto-semver:${env.VERSION}\"\n+ args \"--privileged\"\n }\n }\n steps\n@@ -85,7 +86,7 @@ pipeline {\n // Authenticate & push to DockerHub\n withCredentials([usernamePassword(credentialsId: env.DOCKER_CREDENTIALS, usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {\n sh(\"\"\"\n- docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}\n+ docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD\n docker push rightbrainnetworks/auto-semver:${env.VERSION}\n \"\"\")\n }\ndiff --git a/semver/__init__.py b/semver/__init__.py\nindex da6a610..e0075ee 100644\n--- a/semver/__init__.py\n+++ b/semver/__init__.py\n@@ -1,6 +1,8 @@\n import argparse\n import re\n import subprocess\n+import sys\n+import traceback\n from enum import IntEnum\n from semver.utils import get_tag_version\n from semver.logger import logging, logger, console_logger\n@@ -59,7 +61,7 @@ class SemVer(object):\n message = str(p.stdout.read())\n branch = b.stdout.read().decode('utf-8').rstrip()\n logger.info('Main branch is ' + branch)\n- matches = GET_COMMIT_MESSAGE.search(message)\n+ matches = GET_COMMIT_MESSAGE.search(message.replace('\\\\n','\\n').replace('\\\\',''))\n if matches:\n if str(matches.group(4)) == branch:\n self.merged_branch = matches.group(2)\n@@ -111,7 +113,7 @@ class SemVer(object):\n config_file = file.read()\n \n # version repo\n- logger.debug(\"Running bumpversion of type: \" + self.version_type)\n+ logger.debug(\"Running bumpversion of type: \" + str(self.version_type.name))\n bump_version(get_tag_version(), self.version_type)\n return self\n \n@@ -146,20 +148,22 @@ class SemVer(object):\n return self\n \n def main():\n- try:\n- parser = argparse.ArgumentParser(description='Bump Semantic Version.')\n- parser.add_argument('-n','--no-push', help='Do not try to push', action='store_false', dest='push')\n- parser.add_argument('-g','--global-user', help='Set git user at a global level, helps in jenkins', action='store_true', dest='global_user')\n- parser.add_argument('-D', '--debug', help='Sets logging level to DEBUG', action='store_true', dest='debug', default=False)\n- args = parser.parse_args()\n-\n+ parser = argparse.ArgumentParser(description='Bump Semantic Version.')\n+ parser.add_argument('-n','--no-push', help='Do not try to push', action='store_false', dest='push')\n+ parser.add_argument('-g','--global-user', help='Set git user at a global level, helps in jenkins', action='store_true', dest='global_user')\n+ parser.add_argument('-D', '--debug', help='Sets logging level to DEBUG', action='store_true', dest='debug', default=False)\n+ args = parser.parse_args()\n \n- if args.debug:\n- console_logger.setLevel(logging.DEBUG)\n \n+ if args.debug:\n+ console_logger.setLevel(logging.DEBUG)\n+ try:\n SemVer(global_user=args.global_user).run(push=args.push)\n except Exception as e:\n logger.error(e)\n+ if args.debug:\n+ tb = sys.exc_info()[2]\n+ traceback.print_tb(tb)\n if e == NO_MERGE_FOUND:\n exit(1)\n elif e == NOT_MAIN_BRANCH:\n", "test_patch": "diff --git a/semver/tests.py b/semver/tests.py\nindex 6383cd0..63025fa 100644\n--- a/semver/tests.py\n+++ b/semver/tests.py\n@@ -158,6 +158,13 @@ class TestGetCommitMessageRegex(unittest.TestCase):\n def test_non_merge_message(self):\n matches = GET_COMMIT_MESSAGE.search(\"Example unrelated commit message that should get 0 matches\")\n self.assertEqual(matches, None)\n+ def test_gitlab_merge_with_double_quotes(self):\n+ matches = GET_COMMIT_MESSAGE.search(\"Merge branch 'branch' into 'master'\\n\\n\\\"Message in quotes!\\\"\")\n+ if matches:\n+ self.assertEqual(matches.group(4), \"master\")\n+ self.assertEqual(matches.group(2), \"branch\")\n+ else:\n+ self.assertTrue(False)\n \n class TestVersionBumping(unittest.TestCase):\n def test_patch_bump(self):\n", "FAIL_TO_PASS": ["semver/tests.py::TestSemverObject::test_run_no_merge"]}], "all_FAIL_TO_PASS": ["semver/tests.py::TestSemverObject::test_run_no_merge"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "CybOXProject__mixbox-35_x1", "level": 1, "source": "swerebench", "repo": "CybOXProject/mixbox", "image": "swerebench/sweb.eval.x86_64.cyboxproject_1776_mixbox-35:latest", "base_commit": "bab51cfd20757f9a64a61571631203dbbc3644f8", "num_bugs": 1, "bugs": [{"instance_id": "CybOXProject__mixbox-35", "base_commit": "bab51cfd20757f9a64a61571631203dbbc3644f8", "gold_patch": "diff --git a/mixbox/dates.py b/mixbox/dates.py\nindex be279e1..794e0b0 100644\n--- a/mixbox/dates.py\n+++ b/mixbox/dates.py\n@@ -73,10 +73,10 @@ def serialize_date(value):\n \"\"\"\n if not value:\n return None\n- elif isinstance(value, datetime.date):\n- return value.isoformat()\n elif isinstance(value, datetime.datetime):\n return value.date().isoformat()\n+ elif isinstance(value, datetime.date):\n+ return value.isoformat()\n else:\n return parse_date(value).isoformat()\n \ndiff --git a/mixbox/fields.py b/mixbox/fields.py\nindex f623c6b..cad106a 100644\n--- a/mixbox/fields.py\n+++ b/mixbox/fields.py\n@@ -373,7 +373,7 @@ class DateField(TypedField):\n return serialize_date(value)\n \n def binding_value(self, value):\n- return serialize_datetime(value)\n+ return serialize_date(value)\n \n \n class CDATAField(TypedField):\n", "test_patch": "diff --git a/tests/dates_tests.py b/tests/dates_tests.py\nindex f139939..d3be86b 100644\n--- a/tests/dates_tests.py\n+++ b/tests/dates_tests.py\n@@ -15,6 +15,12 @@ class DatesTests(unittest.TestCase):\n dstr = \"2015-04-01\"\n parsed = dates.parse_date(dstr)\n self.assertEqual(dstr, parsed.isoformat())\n+ \n+ def test_serialize_datetime_as_date(self):\n+ now = dates.now()\n+ self.assertTrue(isinstance(now, datetime.datetime))\n+ nowstr = dates.serialize_date(now)\n+ self.assertEquals(nowstr, now.date().isoformat())\n \n def test_parse_datetime(self):\n dtstr = '2015-04-02T16:44:30.423149+00:00'\n", "FAIL_TO_PASS": ["tests/dates_tests.py::DatesTests::test_serialize_datetime_as_date"]}], "all_FAIL_TO_PASS": ["tests/dates_tests.py::DatesTests::test_serialize_datetime_as_date"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Qiskit__qiskit-bot-11_x1", "level": 1, "source": "swerebench", "repo": "Qiskit/qiskit-bot", "image": "swerebench/sweb.eval.x86_64.qiskit_1776_qiskit-bot-11:latest", "base_commit": "5ea3821a60f14f7892654b3cd86f883f218c3120", "num_bugs": 1, "bugs": [{"instance_id": "Qiskit__qiskit-bot-11", "base_commit": "5ea3821a60f14f7892654b3cd86f883f218c3120", "gold_patch": "diff --git a/qiskit_bot/config.py b/qiskit_bot/config.py\nindex dcf0600..45dbd1e 100644\n--- a/qiskit_bot/config.py\n+++ b/qiskit_bot/config.py\n@@ -28,6 +28,7 @@ default_changelog_categories = {\n 'Changelog: API Change': 'Changed',\n 'Changelog: Removal': 'Removed',\n 'Changelog: Bugfix': 'Fixed',\n+ 'Changelog: None': None,\n }\n \n \ndiff --git a/qiskit_bot/release_process.py b/qiskit_bot/release_process.py\nindex 441bc90..9871343 100644\n--- a/qiskit_bot/release_process.py\n+++ b/qiskit_bot/release_process.py\n@@ -200,6 +200,9 @@ def _generate_changelog(repo, log_string, categories, show_missing=False):\n label_found = False\n for label in labels:\n if label in changelog_dict:\n+ if categories[label] is None:\n+ label_found = True\n+ break\n changelog_dict[label].append(summary)\n label_found = True\n if not label_found:\n@@ -217,7 +220,7 @@ def _generate_changelog(repo, log_string, categories, show_missing=False):\n if show_missing:\n if missing_list:\n changelog += ('\\n')\n- changelog += '## No changelog entry\\n'\n+ changelog += '## Missing changelog entry\\n'\n for entry in missing_list:\n changelog += '- %s\\n' % entry\n return changelog\n", "test_patch": "diff --git a/tests/test_release_process.py b/tests/test_release_process.py\nindex 0633380..99abeaf 100644\n--- a/tests/test_release_process.py\n+++ b/tests/test_release_process.py\n@@ -922,10 +922,45 @@ qiskit-terra==0.16.0\n config.default_changelog_categories, True)\n expected = \"\"\"# Changelog\n \n-## No changelog entry\n+## Missing changelog entry\n - Tune performance of optimize_1q_decomposition (#5682)\n - Change collect_1q_runs return for performance (#5685)\n - Add unroll step to level2 passmanager optimization loop (#5671)\n+\"\"\"\n+ self.assertEqual(res, expected)\n+\n+ @unittest.mock.patch.object(release_process, 'git')\n+ def test_generate_changelog_with_changelog_none(self, git_mock):\n+ repo = unittest.mock.MagicMock()\n+ repo.name = 'qiskit-terra'\n+ repo.gh_repo.get_branches.return_value = []\n+ repo.gh_repo = unittest.mock.MagicMock()\n+\n+ def fake_get_pull(number):\n+ result = unittest.mock.MagicMock()\n+ if number == 5685:\n+ labels_obj = unittest.mock.MagicMock()\n+ labels_obj.name = 'Changelog: None'\n+ result.labels = [labels_obj]\n+ else:\n+ result.labels = []\n+ return result\n+\n+ repo.gh_repo.get_pull = fake_get_pull\n+ repo.repo_config = {'branch_on_release': True}\n+ fake_log = \"\"\"5a7f41344 Tune performance of optimize_1q_decomposition (#5682)\n+6e2542243 Change collect_1q_runs return for performance (#5685)\n+25eb58a29 Add unroll step to level2 passmanager optimization loop (#5671)\n+\"\"\"\n+ git_mock.get_git_log.return_value = fake_log.encode('utf8')\n+ res = release_process._generate_changelog(\n+ repo, '0.17.0...0.16.0',\n+ config.default_changelog_categories, True)\n+ expected = \"\"\"# Changelog\n+\n+## Missing changelog entry\n+- Tune performance of optimize_1q_decomposition (#5682)\n+- Add unroll step to level2 passmanager optimization loop (#5671)\n \"\"\"\n self.assertEqual(res, expected)\n \n", "FAIL_TO_PASS": ["tests/test_release_process.py::TestReleaseProcess::test_generate_changelog_with_changelog_none", "tests/test_release_process.py::TestReleaseProcess::test_generate_changelog_with_invalid_PR_number"]}], "all_FAIL_TO_PASS": ["tests/test_release_process.py::TestReleaseProcess::test_generate_changelog_with_changelog_none", "tests/test_release_process.py::TestReleaseProcess::test_generate_changelog_with_invalid_PR_number"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PEtab-dev__libpetab-python-152_x1", "level": 1, "source": "swerebench", "repo": "PEtab-dev/libpetab-python", "image": "swerebench/sweb.eval.x86_64.petab-dev_1776_libpetab-python-152:latest", "base_commit": "7a0b77ef6d968a4600497763df0ca791caa24768", "num_bugs": 1, "bugs": [{"instance_id": "PEtab-dev__libpetab-python-152", "base_commit": "7a0b77ef6d968a4600497763df0ca791caa24768", "gold_patch": "diff --git a/petab/problem.py b/petab/problem.py\nindex 517b91c..f523803 100644\n--- a/petab/problem.py\n+++ b/petab/problem.py\n@@ -87,8 +87,9 @@ class Problem:\n \n @staticmethod\n def from_files(\n- sbml_file: Union[str, Path, None] = None,\n- condition_file: Union[str, Path, None] = None,\n+ sbml_file: Union[str, Path] = None,\n+ condition_file:\n+ Union[str, Path, Iterable[Union[str, Path]]] = None,\n measurement_file: Union[str, Path,\n Iterable[Union[str, Path]]] = None,\n parameter_file: Union[str, Path,\n@@ -115,7 +116,8 @@ class Problem:\n observable_df = None\n \n if condition_file:\n- condition_df = conditions.get_condition_df(condition_file)\n+ condition_df = core.concat_tables(condition_file,\n+ conditions.get_condition_df)\n \n if measurement_file:\n # If there are multiple tables, we will merge them\n@@ -198,7 +200,10 @@ class Problem:\n \n problem0 = yaml_config['problems'][0]\n \n- yaml.assert_single_condition_and_sbml_file(problem0)\n+ if len(problem0[SBML_FILES]) > 1:\n+ # TODO https://github.com/PEtab-dev/libpetab-python/issues/6\n+ raise NotImplementedError(\n+ 'Support for multiple models is not yet implemented.')\n \n if isinstance(yaml_config[PARAMETER_FILE], list):\n parameter_file = [\n@@ -213,7 +218,8 @@ class Problem:\n if problem0[SBML_FILES] else None,\n measurement_file=[get_path(f)\n for f in problem0[MEASUREMENT_FILES]],\n- condition_file=get_path(problem0[CONDITION_FILES][0]),\n+ condition_file=[get_path(f)\n+ for f in problem0[CONDITION_FILES]],\n parameter_file=parameter_file,\n visualization_files=[\n get_path(f) for f in problem0.get(VISUALIZATION_FILES, [])],\n", "test_patch": "diff --git a/tests/test_petab.py b/tests/test_petab.py\nindex 62e74e8..0e0c4e0 100644\n--- a/tests/test_petab.py\n+++ b/tests/test_petab.py\n@@ -1,8 +1,10 @@\n import copy\n import pickle\n import tempfile\n+from io import StringIO\n from math import nan\n from pathlib import Path\n+from tempfile import TemporaryDirectory\n \n import libsbml\n import numpy as np\n@@ -10,6 +12,7 @@ import pandas as pd\n import petab\n import pytest\n from petab.C import *\n+from yaml import safe_load\n \n \n @pytest.fixture\n@@ -452,6 +455,33 @@ def test_concat_measurements():\n petab.measurements.get_measurement_df))\n \n \n+def test_concat_condition_df():\n+ df1 = pd.DataFrame(data={\n+ CONDITION_ID: ['condition1', 'condition2'],\n+ 'par1': [1.1, 1.2],\n+ 'par2': [2.1, 2.2],\n+ 'par3': [3.1, 3.2]\n+ }).set_index(CONDITION_ID)\n+\n+ assert df1.equals(petab.concat_tables(df1, petab.get_condition_df))\n+\n+ df2 = pd.DataFrame(data={\n+ CONDITION_ID: ['condition3'],\n+ 'par1': [1.3],\n+ 'par2': [2.3],\n+ }).set_index(CONDITION_ID)\n+\n+ df_expected = pd.DataFrame(data={\n+ CONDITION_ID: ['condition1', 'condition2', 'condition3'],\n+ 'par1': [1.1, 1.2, 1.3],\n+ 'par2': [2.1, 2.2, 2.3],\n+ 'par3': [3.1, 3.2, np.nan],\n+ }).set_index(CONDITION_ID)\n+ assert df_expected.equals(\n+ petab.concat_tables((df1, df2), petab.get_condition_df)\n+ )\n+\n+\n def test_get_observable_ids(petab_problem): # pylint: disable=W0621\n \"\"\"Test if observable ids functions returns correct value.\"\"\"\n assert set(petab_problem.get_observable_ids()) == {'observable_1'}\n@@ -535,3 +565,68 @@ def test_load_remote():\n assert petab_problem.sbml_model is not None\n assert petab_problem.measurement_df is not None \\\n and not petab_problem.measurement_df.empty\n+\n+\n+def test_problem_from_yaml_v1_empty():\n+ \"\"\"Test loading PEtab version 1 yaml without any files\"\"\"\n+ yaml_config = \"\"\"\n+ format_version: 1\n+ parameter_file:\n+ problems:\n+ - condition_files: []\n+ measurement_files: []\n+ observable_files: []\n+ sbml_files: []\n+ \"\"\"\n+ yaml_config = safe_load(StringIO(yaml_config))\n+ petab.Problem.from_yaml(yaml_config)\n+\n+\n+def test_problem_from_yaml_v1_multiple_files():\n+ \"\"\"Test loading PEtab version 1 yaml with multiple condition / measurement\n+ / observable files\"\"\"\n+ yaml_config = \"\"\"\n+ format_version: 1\n+ parameter_file:\n+ problems:\n+ - condition_files: [conditions1.tsv, conditions2.tsv]\n+ measurement_files: [measurements1.tsv, measurements2.tsv]\n+ observable_files: [observables1.tsv, observables2.tsv]\n+ sbml_files: []\n+ \"\"\"\n+\n+ with TemporaryDirectory() as tmpdir:\n+ yaml_path = Path(tmpdir, \"problem.yaml\")\n+ with open(yaml_path, 'w') as f:\n+ f.write(yaml_config)\n+\n+ for i in (1, 2):\n+ condition_df = pd.DataFrame({\n+ CONDITION_ID: [f\"condition{i}\"],\n+ })\n+ condition_df.set_index([CONDITION_ID], inplace=True)\n+ petab.write_condition_df(condition_df,\n+ Path(tmpdir, f\"conditions{i}.tsv\"))\n+\n+ measurement_df = pd.DataFrame({\n+ SIMULATION_CONDITION_ID: [f\"condition{i}\"],\n+ OBSERVABLE_ID: [f\"observable{i}\"],\n+ TIME: [i],\n+ MEASUREMENT: [1]\n+ })\n+ petab.write_measurement_df(measurement_df,\n+ Path(tmpdir, f\"measurements{i}.tsv\"))\n+\n+ observables_df = pd.DataFrame({\n+ OBSERVABLE_ID: [f\"observable{i}\"],\n+ OBSERVABLE_FORMULA: [1],\n+ NOISE_FORMULA: [1],\n+ })\n+ petab.write_observable_df(observables_df,\n+ Path(tmpdir, f\"observables{i}.tsv\"))\n+\n+ petab_problem = petab.Problem.from_yaml(yaml_path)\n+\n+ assert petab_problem.measurement_df.shape[0] == 2\n+ assert petab_problem.observable_df.shape[0] == 2\n+ assert petab_problem.condition_df.shape[0] == 2\n", "FAIL_TO_PASS": ["tests/test_petab.py::test_problem_from_yaml_v1_empty", "tests/test_petab.py::test_problem_from_yaml_v1_multiple_files"]}], "all_FAIL_TO_PASS": ["tests/test_petab.py::test_problem_from_yaml_v1_empty", "tests/test_petab.py::test_problem_from_yaml_v1_multiple_files"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NeuralEnsemble__python-neo-1297_x1", "level": 1, "source": "swerebench", "repo": "NeuralEnsemble/python-neo", "image": "swerebench/sweb.eval.x86_64.neuralensemble_1776_python-neo-1297:latest", "base_commit": "f608309c5ce031ecd905349c140b07a3dafb057d", "num_bugs": 1, "bugs": [{"instance_id": "NeuralEnsemble__python-neo-1297", "base_commit": "f608309c5ce031ecd905349c140b07a3dafb057d", "gold_patch": "diff --git a/neo/io/__init__.py b/neo/io/__init__.py\nindex 22b6df66..4aa31692 100644\n--- a/neo/io/__init__.py\n+++ b/neo/io/__init__.py\n@@ -451,8 +451,23 @@ def list_candidate_ios(file_or_folder, ignore_patterns=['*.ini', 'README.txt', '\n # if only file prefix was provided, e.g /mydatafolder/session1-\n # to select all files sharing the `session1-` prefix\n elif file_or_folder.parent.exists():\n- filenames = file_or_folder.parent.glob(file_or_folder.name + '*')\n-\n+ filenames = list(file_or_folder.parent.glob(file_or_folder.name + '*'))\n+ # if filenames empty and suffix is provided then non-existent file\n+ # may be written in current dir. So run check for io\n+ if len(filenames)==0 and file_or_folder.suffix:\n+ suffix = file_or_folder.suffix[1:].lower()\n+ if suffix not in io_by_extension:\n+ raise ValueError(f'{suffix} is not a supported format of any IO.')\n+ return io_by_extension[suffix]\n+\n+ # If non-existent file in non-existent dir is given check if this \n+ # structure could be created with an io writing the file\n+ elif file_or_folder.suffix:\n+ suffix = file_or_folder.suffix[1:].lower()\n+ if suffix not in io_by_extension:\n+ raise ValueError(f'{suffix} is not a supported format of any IO.')\n+ return io_by_extension[suffix]\n+ \n else:\n raise ValueError(f'{file_or_folder} does not contain data files of a supported format')\n \n", "test_patch": "diff --git a/neo/test/iotest/test_get_io.py b/neo/test/iotest/test_get_io.py\nnew file mode 100644\nindex 00000000..b43499b0\n--- /dev/null\n+++ b/neo/test/iotest/test_get_io.py\n@@ -0,0 +1,41 @@\n+from pathlib import Path\n+from tempfile import TemporaryDirectory\n+from neo.io import get_io, list_candidate_ios, NixIO\n+\n+\n+def test_list_candidate_ios_non_existant_file():\n+ # use plexon io suffix for testing here\n+ non_existant_file = Path('non_existant_folder/non_existant_file.plx')\n+ non_existant_file.unlink(missing_ok=True)\n+ ios = list_candidate_ios(non_existant_file)\n+\n+ assert ios\n+\n+ # cleanup\n+ non_existant_file.unlink(missing_ok=True)\n+\n+\n+def test_list_candidate_ios_filename_stub():\n+ # create dummy folder with dummy files\n+ with TemporaryDirectory(prefix='filename_stub_test_') as test_folder:\n+ test_folder = Path(test_folder)\n+ test_filename = (test_folder / 'dummy_file.nix')\n+ test_filename.touch()\n+ filename_stub = test_filename.with_suffix('')\n+\n+ # check that io is found even though file suffix was not provided\n+ ios = list_candidate_ios(filename_stub)\n+\n+ assert NixIO in ios\n+\n+\n+def test_get_io_non_existant_file_writable_io():\n+ # use nixio for testing with writable io\n+ non_existant_file = Path('non_existant_file.nix')\n+ non_existant_file.unlink(missing_ok=True)\n+ io = get_io(non_existant_file)\n+\n+ assert isinstance(io, NixIO)\n+\n+ # cleanup\n+ non_existant_file.unlink(missing_ok=True)\n", "FAIL_TO_PASS": ["neo/test/iotest/test_get_io.py::test_list_candidate_ios_non_existant_file", "neo/test/iotest/test_get_io.py::test_get_io_non_existant_file_writable_io"]}], "all_FAIL_TO_PASS": ["neo/test/iotest/test_get_io.py::test_list_candidate_ios_non_existant_file", "neo/test/iotest/test_get_io.py::test_get_io_non_existant_file_writable_io"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NCAS-CMS__cfdm-114_x1", "level": 1, "source": "swerebench", "repo": "NCAS-CMS/cfdm", "image": "swerebench/sweb.eval.x86_64.ncas-cms_1776_cfdm-114:latest", "base_commit": "d5222488853a0ffc0b444f2892f94840acc1c853", "num_bugs": 1, "bugs": [{"instance_id": "NCAS-CMS__cfdm-114", "base_commit": "d5222488853a0ffc0b444f2892f94840acc1c853", "gold_patch": "diff --git a/Changelog.rst b/Changelog.rst\nindex ca53e24bb..09a754780 100644\n--- a/Changelog.rst\n+++ b/Changelog.rst\n@@ -1,3 +1,12 @@\n+version NEXT\n+------------\n+----\n+\n+**2021-??-??**\n+\n+* Fix for zero-sized unlimited dimensions when read from a grouped\n+ netCDF file (https://github.com/NCAS-CMS/cfdm/issues/113)\n+\n version 1.8.8.0\n ---------------\n ----\ndiff --git a/cfdm/core/__init__.py b/cfdm/core/__init__.py\nindex edbaa0db6..970af7907 100644\n--- a/cfdm/core/__init__.py\n+++ b/cfdm/core/__init__.py\n@@ -3,9 +3,9 @@\n '''\n \n __author__ = 'David Hassell'\n-__date__ = '2020-12-18'\n+__date__ = '2020-01-15'\n __cf_version__ = '1.8'\n-__version__ = '1.8.8.0'\n+__version__ = '1.8.8.1'\n \n from distutils.version import LooseVersion\n import platform\ndiff --git a/cfdm/read_write/netcdf/netcdfread.py b/cfdm/read_write/netcdf/netcdfread.py\nindex 4d5147610..4b1287f12 100644\n--- a/cfdm/read_write/netcdf/netcdfread.py\n+++ b/cfdm/read_write/netcdf/netcdfread.py\n@@ -288,6 +288,10 @@ class NetCDFRead(IORead):\n for flat_file in self.read_vars['flat_files']:\n flat_file.close()\n \n+ # Close the original grouped file (v1.8.8.1)\n+ if 'nc_grouped' in self.read_vars:\n+ self.read_vars['nc_grouped'].close()\n+\n def file_open(self, filename, flatten=True, verbose=None):\n '''Open the netCDf file for reading.\n \n@@ -341,6 +345,7 @@ class NetCDFRead(IORead):\n flat_nc = netCDF4.Dataset(flat_file, 'w',\n diskless=True,\n persist=False)\n+\n flat_nc.set_fill_off()\n \n # Flatten the file\n@@ -348,7 +353,12 @@ class NetCDFRead(IORead):\n lax_mode=True,\n _copy_data=False)\n \n- nc.close()\n+ # Store the original grouped file. This is primarily\n+ # because the unlimited dimensions in the flattened\n+ # dataset have size 0, since it contains no\n+ # data. (v1.8.8.1)\n+ g['nc_grouped'] = nc\n+\n nc = flat_nc\n \n g['has_groups'] = True\n@@ -831,6 +841,7 @@ class NetCDFRead(IORead):\n variable_groups = {}\n variable_group_attributes = {}\n variable_basename = {}\n+ variable_grouped_dataset = {}\n \n dimension_groups = {}\n dimension_basename = {}\n@@ -970,6 +981,8 @@ class NetCDFRead(IORead):\n # variable path\n ncvar = ncvar[1:]\n flattener_variables[ncvar] = ncvar\n+\n+ variable_grouped_dataset[ncvar] = g['nc_grouped']\n # --- End: if\n \n variable_attributes[ncvar] = {}\n@@ -1057,6 +1070,10 @@ class NetCDFRead(IORead):\n # The netCDF4 dataset object for each variable\n g['variable_dataset'] = variable_dataset\n \n+ # The original gouped dataset for each variable (empty if the\n+ # original dataset is not grouped) v1.8.8.1\n+ g['variable_grouped_dataset'] = variable_grouped_dataset\n+\n # The name of the file containing the each variable\n g['variable_filename'] = variable_filename\n \n@@ -1074,7 +1091,19 @@ class NetCDFRead(IORead):\n # The netCDF dimensions of the parent file\n internal_dimension_sizes = {}\n for name, dimension in nc.dimensions.items():\n- internal_dimension_sizes[name] = dimension.size\n+ if (\n+ has_groups\n+ and dimension_isunlimited[flattener_dimensions[name]]\n+ ):\n+ # For grouped datasets, get the unlimited dimension\n+ # size from the original grouped dataset, because\n+ # unlimited dimensions have size 0 in the flattened\n+ # dataset (because it contains no data) (v1.8.8.1)\n+ group, ncdim = self._netCDF4_group(g['nc_grouped'],\n+ flattener_dimensions[name])\n+ internal_dimension_sizes[name] = group.dimensions[ncdim].size\n+ else:\n+ internal_dimension_sizes[name] = dimension.size\n \n if g['has_groups']:\n internal_dimension_sizes = {\n@@ -4579,7 +4608,20 @@ class NetCDFRead(IORead):\n '''\n g = self.read_vars\n \n- variable = g['variables'].get(ncvar)\n+ if g['has_groups']:\n+ # Get the variable from the original grouped file. This is\n+ # primarily so that unlimited dimensions don't come out\n+ # with size 0 (v1.8.8.1)\n+ group, name = self._netCDF4_group(\n+ g['variable_grouped_dataset'][ncvar], ncvar\n+ )\n+# path = ncvar.split('/')\n+# for group_name in path[1:-1]:\n+# group = group[group_name]\n+ variable = group.variables.get(name)\n+ else:\n+ variable = g['variables'].get(ncvar)\n+\n if variable is None:\n return None\n \n@@ -4596,6 +4638,7 @@ class NetCDFRead(IORead):\n ndim = variable.ndim\n shape = variable.shape\n size = variable.size\n+\n if size < 2:\n size = int(size)\n \n@@ -6262,4 +6305,37 @@ class NetCDFRead(IORead):\n \n return out\n \n+ def _netCDF4_group(self, nc, name):\n+ '''Given a dataset and a variable or dimension name, return the group\n+object for the name, and the name within the group.\n+\n+ .. versionadded:: 1.8.8.1\n+\n+ :Parameters:\n+\n+ nc: `netCDF4._netCDF4.Dataset` or `netCDF4._netCDF4.Group`\n+\n+ name: `str`\n+\n+ :Returns:\n+\n+ `netCDF4._netCDF4.Dataset` or `netCDF4._netCDF4.Group`, `str`\n+\n+ **Examples:**\n+\n+ >>> group, name = n._netCDF4_group(nc, 'time')\n+ >>> group.name, name\n+ ('/', 'time')\n+ >>> group, name = n._netCDF4_group(nc, '/surfacelayer/Z')\n+ >>> group.name, name\n+ ('surfacelayer', 'Z')\n+\n+ '''\n+ group = nc\n+ path = name.split('/')\n+ for group_name in path[1:-1]:\n+ group = group[group_name]\n+\n+ return group, path[-1]\n+\n # --- End: class\ndiff --git a/docs/source/contributing.rst b/docs/source/contributing.rst\nindex 6c44f87dc..c9dc1dc7b 100644\n--- a/docs/source/contributing.rst\n+++ b/docs/source/contributing.rst\n@@ -102,6 +102,7 @@ a work in progress, you can mark it initially as a draft pull request.\n We would like to acknowledge and thank all those who have contributed\n ideas, code, and documentation to the cfdm library:\n \n+* Alan Iwi\n * Allyn Treshansky\n * Bryan Lawrence\n * David Hassell\n", "test_patch": "diff --git a/cfdm/test/test_groups.py b/cfdm/test/test_groups.py\nindex da77ea373..bf7c8052c 100644\n--- a/cfdm/test/test_groups.py\n+++ b/cfdm/test/test_groups.py\n@@ -9,7 +9,7 @@ import netCDF4\n import cfdm\n \n \n-n_tmpfiles = 8\n+n_tmpfiles = 9\n tmpfiles = [tempfile.mkstemp('_test_groups.nc', dir=os.getcwd())[1]\n for i in range(n_tmpfiles)]\n (\n@@ -21,6 +21,7 @@ tmpfiles = [tempfile.mkstemp('_test_groups.nc', dir=os.getcwd())[1]\n grouped_file2,\n grouped_file3,\n grouped_file4,\n+ grouped_file5,\n ) = tmpfiles\n \n \n@@ -405,6 +406,42 @@ class GroupsTest(unittest.TestCase):\n h = h[0]\n self.assertTrue(f.equals(h, verbose=3))\n \n+ def test_groups_unlimited_dimension(self):\n+ f = cfdm.example_field(0)\n+\n+ # Create an unlimited dimension in the root group\n+ key = f.domain_axis_key('time')\n+ domain_axis = f.constructs[key]\n+ domain_axis.nc_set_unlimited(True)\n+\n+ f.insert_dimension(key, 0, inplace=True)\n+\n+ key = f.domain_axis_key('latitude')\n+ domain_axis = f.constructs[key]\n+ domain_axis.nc_set_unlimited(True)\n+ domain_axis.nc_set_dimension_groups(['forecast'])\n+\n+ # ------------------------------------------------------------\n+ # Move the latitude coordinate to the /forecast group. Note\n+ # that this will drag its netDF dimension along with it,\n+ # because it's a dimension coordinate variable\n+ # ------------------------------------------------------------\n+ lat = f.construct('latitude')\n+ lat.nc_set_variable_groups(['forecast'])\n+\n+ # ------------------------------------------------------------\n+ # Move the field construct to the /forecast/model group\n+ # ------------------------------------------------------------\n+ f.nc_set_variable_groups(['forecast', 'model'])\n+\n+ grouped_file = grouped_file5\n+ cfdm.write(f, grouped_file5, verbose=1)\n+\n+ h = cfdm.read(grouped_file, verbose=1)\n+ self.assertEqual(len(h), 1)\n+ h = h[0]\n+ self.assertTrue(f.equals(h, verbose=3))\n+\n # --- End: class\n \n \n", "FAIL_TO_PASS": ["cfdm/test/test_groups.py::GroupsTest::test_groups_unlimited_dimension"]}], "all_FAIL_TO_PASS": ["cfdm/test/test_groups.py::GroupsTest::test_groups_unlimited_dimension"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "GenericMappingTools__pygmt-1258_x1", "level": 1, "source": "swerebench", "repo": "GenericMappingTools/pygmt", "image": "swerebench/sweb.eval.x86_64.genericmappingtools_1776_pygmt-1258:latest", "base_commit": "53b4e7416989e76be4ae2b19d352b076c4dd4fa1", "num_bugs": 1, "bugs": [{"instance_id": "GenericMappingTools__pygmt-1258", "base_commit": "53b4e7416989e76be4ae2b19d352b076c4dd4fa1", "gold_patch": "diff --git a/examples/gallery/3d_plots/scatter3d.py b/examples/gallery/3d_plots/scatter3d.py\nindex 568c2de7..0c70581f 100644\n--- a/examples/gallery/3d_plots/scatter3d.py\n+++ b/examples/gallery/3d_plots/scatter3d.py\n@@ -47,7 +47,7 @@ fig.plot3d(\n y=df.sepal_length,\n z=df.petal_length,\n # Vary each symbol size according to another feature (sepal width, scaled by 0.1)\n- sizes=0.1 * df.sepal_width,\n+ size=0.1 * df.sepal_width,\n # Use 3D cubes (\"u\") as symbols, with size in centimeter units (\"c\")\n style=\"uc\",\n # Points colored by categorical number code\ndiff --git a/pygmt/src/plot3d.py b/pygmt/src/plot3d.py\nindex 85b4826c..e6944c8e 100644\n--- a/pygmt/src/plot3d.py\n+++ b/pygmt/src/plot3d.py\n@@ -6,6 +6,7 @@ from pygmt.exceptions import GMTInvalidInput\n from pygmt.helpers import (\n build_arg_string,\n data_kind,\n+ deprecate_parameter,\n fmt_docstring,\n is_nonstr_iter,\n kwargs_to_strings,\n@@ -43,8 +44,9 @@ from pygmt.helpers import (\n t=\"transparency\",\n )\n @kwargs_to_strings(R=\"sequence\", c=\"sequence_comma\", i=\"sequence_comma\", p=\"sequence\")\n+@deprecate_parameter(\"sizes\", \"size\", \"v0.4.0\", remove_version=\"v0.6.0\")\n def plot3d(\n- self, x=None, y=None, z=None, data=None, sizes=None, direction=None, **kwargs\n+ self, x=None, y=None, z=None, data=None, size=None, direction=None, **kwargs\n ):\n r\"\"\"\n Plot lines, polygons, and symbols in 3-D.\n@@ -80,8 +82,8 @@ def plot3d(\n Either a data file name or a 2d numpy array with the tabular data.\n Use parameter ``columns`` to choose which columns are x, y, z,\n color, and size, respectively.\n- sizes : 1d array\n- The sizes of the data points in units specified in ``style``.\n+ size : 1d array\n+ The size of the data points in units specified in ``style``.\n Only valid if using ``x``/``y``/``z``.\n direction : list of two 1d arrays\n If plotting vectors (using ``style='V'`` or ``style='v'``), then\n@@ -179,12 +181,12 @@ def plot3d(\n )\n extra_arrays.append(kwargs[\"G\"])\n del kwargs[\"G\"]\n- if sizes is not None:\n+ if size is not None:\n if kind != \"vectors\":\n raise GMTInvalidInput(\n- \"Can't use arrays for sizes if data is matrix or file.\"\n+ \"Can't use arrays for 'size' if data is a matrix or a file.\"\n )\n- extra_arrays.append(sizes)\n+ extra_arrays.append(size)\n \n for flag in [\"I\", \"t\"]:\n if flag in kwargs and is_nonstr_iter(kwargs[flag]):\n", "test_patch": "diff --git a/pygmt/tests/test_plot3d.py b/pygmt/tests/test_plot3d.py\nindex 492e95a9..05708f7f 100644\n--- a/pygmt/tests/test_plot3d.py\n+++ b/pygmt/tests/test_plot3d.py\n@@ -110,7 +110,7 @@ def test_plot3d_fail_no_data(data, region):\n \n def test_plot3d_fail_color_size_intensity(data, region):\n \"\"\"\n- Should raise an exception if array color, sizes and intensity are used with\n+ Should raise an exception if array color, size and intensity are used with\n matrix.\n \"\"\"\n fig = Figure()\n@@ -118,7 +118,7 @@ def test_plot3d_fail_color_size_intensity(data, region):\n with pytest.raises(GMTInvalidInput):\n fig.plot3d(style=\"c0.2c\", color=data[:, 2], **kwargs)\n with pytest.raises(GMTInvalidInput):\n- fig.plot3d(style=\"cc\", sizes=data[:, 2], color=\"red\", **kwargs)\n+ fig.plot3d(style=\"cc\", size=data[:, 2], color=\"red\", **kwargs)\n with pytest.raises(GMTInvalidInput):\n fig.plot3d(style=\"cc\", intensity=data[:, 2], color=\"red\", **kwargs)\n \n@@ -178,7 +178,7 @@ def test_plot3d_sizes(data, region):\n z=data[:, 2],\n zscale=5,\n perspective=[225, 30],\n- sizes=0.5 * data[:, 2],\n+ size=0.5 * data[:, 2],\n region=region,\n projection=\"X10c\",\n # Using inches instead of cm because of upstream bug at\n@@ -203,7 +203,7 @@ def test_plot3d_colors_sizes(data, region):\n zscale=5,\n perspective=[225, 30],\n color=data[:, 2],\n- sizes=0.5 * data[:, 2],\n+ size=0.5 * data[:, 2],\n region=region,\n projection=\"X6c\",\n # Using inches instead of cm because of upstream bug at\n@@ -231,7 +231,7 @@ def test_plot3d_colors_sizes_proj(data, region):\n projection=\"M20c\",\n frame=[\"af\", \"zaf\"],\n color=data[:, 2],\n- sizes=data[:, 2],\n+ size=data[:, 2],\n # Using inches instead of cm because of upstream bug at\n # https://github.com/GenericMappingTools/gmt/issues/4386\n style=\"ui\",\n@@ -343,7 +343,7 @@ def test_plot3d_sizes_colors_transparencies():\n frame=True,\n style=\"uc\",\n color=color,\n- sizes=size,\n+ size=size,\n cmap=\"gray\",\n transparency=transparency,\n )\n@@ -458,3 +458,30 @@ def test_plot3d_scalar_xyz():\n x=1.5, y=-1.5, z=1.5, style=\"s1c\", color=\"blue\", zscale=True, perspective=True\n )\n return fig\n+\n+\n+@pytest.mark.mpl_image_compare(filename=\"test_plot3d_sizes.png\")\n+def test_plot3d_deprecate_sizes_to_size(data, region):\n+ \"\"\"\n+ Make sure that the old parameter \"sizes\" is supported and it reports an\n+ warning.\n+\n+ Modified from the test_plot3d_sizes() test.\n+ \"\"\"\n+ fig = Figure()\n+ with pytest.warns(expected_warning=FutureWarning) as record:\n+ fig.plot3d(\n+ x=data[:, 0],\n+ y=data[:, 1],\n+ z=data[:, 2],\n+ zscale=5,\n+ perspective=[225, 30],\n+ sizes=0.5 * data[:, 2],\n+ region=region,\n+ projection=\"X10c\",\n+ style=\"ui\",\n+ color=\"blue\",\n+ frame=[\"af\", \"zaf\"],\n+ )\n+ assert len(record) == 1 # check that only one warning was raised\n+ return fig\n", "FAIL_TO_PASS": ["pygmt/tests/test_plot3d.py::test_plot3d_fail_color_size_intensity"]}], "all_FAIL_TO_PASS": ["pygmt/tests/test_plot3d.py::test_plot3d_fail_color_size_intensity"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "BurnzZ__scrapy-loader-upkeep-3_x1", "level": 1, "source": "swerebench", "repo": "BurnzZ/scrapy-loader-upkeep", "image": "swerebench/sweb.eval.x86_64.burnzz_1776_scrapy-loader-upkeep-3:latest", "base_commit": "0b36309d1c9ea814e097e06e9d7220cfef6e6f9e", "num_bugs": 1, "bugs": [{"instance_id": "BurnzZ__scrapy-loader-upkeep-3", "base_commit": "0b36309d1c9ea814e097e06e9d7220cfef6e6f9e", "gold_patch": "diff --git a/README.rst b/README.rst\nindex 6fb0e87..3112d48 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -58,8 +58,8 @@ This only works for the following ``ItemLoader`` methods:\n - ``add_xpath()``\n - ``replace_xpath()``\n \n-Spider Example\n-~~~~~~~~~~~~~~\n+Basic Spider Example\n+~~~~~~~~~~~~~~~~~~~~\n This is taken from the `examples/ \n `_\n directory.\n@@ -83,6 +83,77 @@ This should output in the stats:\n In this example, we could see that the **1st css** rule for the ``quote`` field\n has had instances of not being matched at all during the scrape.\n \n+New Feature\n+~~~~~~~~~~~\n+\n+As with the example above, we're limited only to the positional context of when\n+the ``add_css()``, ``add_xpath()``, etc were called during the execution.\n+\n+There will be cases where developers will be maintaining a large spider with a\n+lot of different parsers to handle varying layouts in the site. It would make\n+sense to have a better context to what a parser does or is for.\n+\n+A new optional ``name`` parameter is supported to provide more context around a\n+given parser. This supports the two (2) main types of creating fallback parsers:\n+\n+1. **multiple calls**\n+\n+.. code-block:: python\n+\n+ loader.add_css('NAME', 'h1::text', name='Name from h1')\n+ loader.add_css('NAME', 'meta[value=\"title\"]::attr(content)', name=\"Name from meta tag\")\n+\n+would result in something like:\n+\n+.. code-block:: python\n+\n+ { ...\n+ 'parser/QuotesItemLoader/NAME/css/1/Name from h1': 8,\n+ 'parser/QuotesItemLoader/NAME/css/1/Name from h1/missing': 2,\n+ 'parser/QuotesItemLoader/NAME/css/2/Name from meta tag': 7,\n+ 'parser/QuotesItemLoader/NAME/css/2/Name from meta tag/missing': 3,\n+ ...\n+ }\n+\n+2. **grouped parsers in a single call**\n+\n+.. code-block:: python\n+\n+ loader.add_css(\n+ 'NAME',\n+ [\n+ 'h1::text',\n+ 'meta[value=\"title\"]::attr(content)',\n+ ],\n+ name='NAMEs at the main content')\n+ loader.add_css(\n+ 'NAME',\n+ [\n+ 'footer .name::text',\n+ 'div.page-end span.name::text',\n+ ],\n+ name='NAMEs at the bottom of the page')\n+\n+would result in something like:\n+\n+.. code-block:: python\n+\n+ { ...\n+ 'parser/QuotesItemLoader/NAME/css/1/NAMEs at the main content': 8,\n+ 'parser/QuotesItemLoader/NAME/css/1/NAMEs at the main content/missing': 2,\n+ 'parser/QuotesItemLoader/NAME/css/2/NAMEs at the main content': 7,\n+ 'parser/QuotesItemLoader/NAME/css/2/NAMEs at the main content/missing': 3,\n+ 'parser/QuotesItemLoader/NAME/css/3/NAMEs at the bottom of the page': 8,\n+ 'parser/QuotesItemLoader/NAME/css/3/NAMEs at the bottom of the page/missing': 2,\n+ 'parser/QuotesItemLoader/NAME/css/4/NAMEs at the bottom of the page': 7,\n+ 'parser/QuotesItemLoader/NAME/css/4/NAMEs at the bottom of the page/missing': 3,\n+ ...\n+ }\n+\n+The latter is useful in grouping fallback parsers together if they are quite\n+related in terms of layout/arrangement in the page.\n+\n+\n Requirements\n ~~~~~~~~~~~~\n Python 3.6+\ndiff --git a/examples/README.rst b/examples/README.rst\nindex fc57fdb..037f806 100644\n--- a/examples/README.rst\n+++ b/examples/README.rst\n@@ -1,5 +1,12 @@\n Contains examples of using the ``scrapy-loader-upkeep`` package inside Scrapy.\n \n+A symlink has been included in the example project dir in order to read the\n+source code. Run the following in order to test these out:\n+\n+.. code-block:: bash\n+\n+ $ python3 -m scrapy crawl \n+\n \n Simple Example\n ~~~~~~~~~~~~~~\n@@ -41,3 +48,24 @@ This should output in the stats:\n 'parser/QuotesItemLoader/quote/css/2': 10\n ...\n }\n+\n+\n+Example using 'name' feature\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+.. code-block:: bash\n+\n+ $ scrapy crawl quotestoscrape_use_name\n+\n+This should output in the stats:\n+\n+.. code-block:: python\n+\n+ 2019-06-16 14:32:32 [scrapy.statscollectors] INFO: Dumping Scrapy stats:\n+ { ...\n+ 'parser/QuotesItemLoader/author/css/1/basic author class': 10,\n+ 'parser/QuotesItemLoader/quote/css/1/Quotes inside the box/missing': 10,\n+ 'parser/QuotesItemLoader/quote/css/2/Quotes inside the box': 10,\n+ 'parser/QuotesItemLoader/tags/css/1/underneath the author text': 10,\n+ ...\n+ }\ndiff --git a/scrapy_loader_upkeep/loader.py b/scrapy_loader_upkeep/loader.py\nindex cb47f96..805b3ce 100644\n--- a/scrapy_loader_upkeep/loader.py\n+++ b/scrapy_loader_upkeep/loader.py\n@@ -79,6 +79,9 @@ class ItemLoader(ItemLoaderOG):\n \n selector_type = selector.__name__ # either 'css' or 'xpath'\n \n+ # The optional arg in methods like `add_css()` for context in stats\n+ name = kw.get('name')\n+\n # For every call of `add_css()` and `add_xpath()` this is incremented.\n # We'll use it as the base index of the position of the logged stats.\n index = self.field_tracker[f'{field_name}_{selector_type}']\n@@ -87,10 +90,12 @@ class ItemLoader(ItemLoaderOG):\n for position, rule in enumerate(arg_to_iter(selector_rules), index):\n parsed_data = selector(rule).getall()\n values.append(parsed_data)\n- self.write_to_stats(field_name, parsed_data, position, selector_type)\n+ self.write_to_stats(field_name, parsed_data, position,\n+ selector_type, name=name)\n return flatten(values)\n \n- def write_to_stats(self, field_name, parsed_data, position, selector_type):\n+ def write_to_stats(self, field_name, parsed_data, position, selector_type,\n+ name=None):\n \"\"\"Responsible for logging the parser rules usage.\n \n NOTES: It's hard to easily denote which parser rule hasn't produced any\n@@ -111,6 +116,9 @@ class ItemLoader(ItemLoaderOG):\n f\"parser/{self.loader_name}/{field_name}/{selector_type}/{position}\"\n )\n \n+ if name:\n+ parser_label += f'/{name}'\n+\n if parsed_data in (None, []):\n parser_label += \"/missing\"\n \n", "test_patch": "diff --git a/examples/quotestoscrape/items.py b/examples/quotestoscrape/items.py\nindex 360d6f0..2eac930 100644\n--- a/examples/quotestoscrape/items.py\n+++ b/examples/quotestoscrape/items.py\n@@ -3,3 +3,4 @@ import scrapy\n class QuotesToScrapeItem(scrapy.Item):\n quote = scrapy.Field()\n author = scrapy.Field()\n+ tags = scrapy.Field()\ndiff --git a/examples/quotestoscrape/spiders/quotestoscrape.py b/examples/quotestoscrape/spiders/quotestoscrape.py\nindex 04dd31e..da8ff0e 100644\n--- a/examples/quotestoscrape/spiders/quotestoscrape.py\n+++ b/examples/quotestoscrape/spiders/quotestoscrape.py\n@@ -5,7 +5,7 @@ from ..loader import QuotesItemLoader\n \n class BaseExampleSpider(scrapy.Spider):\n \n- start_urls = ['http://quotes.toscrape.com/']\n+ start_urls = [\"http://quotes.toscrape.com/\"]\n \n \n class QuotesToScrapeSimpleSpider(BaseExampleSpider):\n@@ -22,18 +22,17 @@ class QuotesToScrapeSimpleSpider(BaseExampleSpider):\n been successfully matched.\n \"\"\"\n \n- name = 'quotestoscrape_simple'\n-\n+ name = \"quotestoscrape_simple\"\n \n def parse(self, response):\n \"\"\"Notice that in order for this enhanced ItemLoader package to work,\n we'll need to inject the stats API into it.\n \"\"\"\n \n- for quote_div in response.css('div.quote'):\n+ for quote_div in response.css(\"div.quote\"):\n loader = QuotesItemLoader(selector=quote_div, stats=self.crawler.stats)\n- loader.add_css('quote', '.quote > span[itemprop=\"text\"]::text')\n- loader.add_css('author', '.author::text')\n+ loader.add_css(\"quote\", '.quote > span[itemprop=\"text\"]::text')\n+ loader.add_css(\"author\", \".author::text\")\n yield loader.load_item()\n \n \n@@ -50,20 +49,58 @@ class QuotesToScrapeHasMissingSpider(BaseExampleSpider):\n }\n \"\"\"\n \n- name = 'quotestoscrape_has_missing'\n+ name = \"quotestoscrape_has_missing\"\n+\n+ def parse(self, response):\n+ \"\"\"Notice that in order for this enhanced ItemLoader package to work,\n+ we'll need to inject the stats API into it.\n+ \"\"\"\n+\n+ for quote_div in response.css(\"div.quote\"):\n+ loader = QuotesItemLoader(selector=quote_div, stats=self.crawler.stats)\n+ loader.add_css(\n+ \"quote\",\n+ [\n+ # This first parser rule doesn't exist at all.\n+ \".this-quote-does-not-exist span::text\",\n+ '.quote > span[itemprop=\"text\"]::text',\n+ ],\n+ )\n+ loader.add_css(\"author\", \".author::text\")\n+ yield loader.load_item()\n+\n+\n+class QuotesToScrapeUseName(BaseExampleSpider):\n+ \"\"\"Demonstrates the new feature of naming the parsers using the 'name' param.\n+\n+ 2019-06-16 14:32:32 [scrapy.statscollectors] INFO: Dumping Scrapy stats:\n+ { ...\n+ 'parser/QuotesItemLoader/author/css/1/basic author class': 10,\n+ 'parser/QuotesItemLoader/quote/css/1/Quotes inside the box/missing': 10,\n+ 'parser/QuotesItemLoader/quote/css/2/Quotes inside the box': 10,\n+ 'parser/QuotesItemLoader/tags/css/1/underneath the author text': 10,\n+ ...\n+ }\n+ \"\"\"\n \n+ name = \"quotestoscrape_use_name\"\n \n def parse(self, response):\n \"\"\"Notice that in order for this enhanced ItemLoader package to work,\n we'll need to inject the stats API into it.\n \"\"\"\n \n- for quote_div in response.css('div.quote'):\n+ for quote_div in response.css(\"div.quote\"):\n loader = QuotesItemLoader(selector=quote_div, stats=self.crawler.stats)\n- loader.add_css('quote', [\n- # This first parser rule doesn't exist at all.\n- '.this-quote-does-not-exist span::text',\n- '.quote > span[itemprop=\"text\"]::text'\n- ])\n- loader.add_css('author', '.author::text')\n+ loader.add_css(\n+ \"quote\",\n+ [\n+ # This first parser rule doesn't exist at all.\n+ \".this-quote-does-not-exist span::text\",\n+ '.quote > span[itemprop=\"text\"]::text',\n+ ],\n+ name=\"Quotes inside the box\",\n+ )\n+ loader.add_css(\"author\", \".author::text\", name=\"basic author class\")\n+ loader.add_css(\"tags\", \".tag::text\", name=\"underneath the author text\")\n yield loader.load_item()\ndiff --git a/tests/test_loader.py b/tests/test_loader.py\nindex 2a3672b..92a7f58 100644\n--- a/tests/test_loader.py\n+++ b/tests/test_loader.py\n@@ -50,9 +50,9 @@ def test_get_selector_values():\n \n loader.write_to_stats.assert_has_calls(\n [\n- mock.call(field_name, parsed_data, 1, \"css\"),\n- mock.call(field_name, parsed_data, 2, \"css\"),\n- mock.call(field_name, parsed_data, 3, \"css\"),\n+ mock.call(field_name, parsed_data, 1, \"css\", name=None),\n+ mock.call(field_name, parsed_data, 2, \"css\", name=None),\n+ mock.call(field_name, parsed_data, 3, \"css\", name=None),\n ]\n )\n \n@@ -205,16 +205,36 @@ def test_multiple_1(loader):\n mock.call(\"parser/TestItemLoader/title/css/3\"),\n ]\n )\n+ assert loader.stats.inc_value.call_count == 3\n \n \n-def test_multiple_2(loader):\n- loader.add_css('title', 'h2::text')\n- loader.add_xpath('title', '//article/h2/text()')\n+def test_multiple_1_with_name(loader):\n+ loader.add_css('title', 'h2::text', name='title from h2')\n+ loader.add_css('title', [\n+ 'article h2::text',\n+ 'article .product-title::text',\n+ ], name='title from article')\n+ loader.stats.inc_value.assert_has_calls(\n+ [\n+ mock.call(\"parser/TestItemLoader/title/css/1/title from h2\"),\n+ mock.call(\"parser/TestItemLoader/title/css/2/title from article\"),\n+ mock.call(\"parser/TestItemLoader/title/css/3/title from article\"),\n+ ]\n+ )\n+ assert loader.stats.inc_value.call_count == 3\n+\n+\n+def test_multiple_2_with_name(loader):\n+ loader.add_css('title', 'h2::text', name='title from h2')\n+ loader.add_xpath('title', '//article/h2/text()', name='title from article')\n loader.add_css('title', 'article .product-title::text')\n+ loader.add_xpath('title', '//aside/h1/text()', name='title from aside')\n loader.stats.inc_value.assert_has_calls(\n [\n- mock.call(\"parser/TestItemLoader/title/css/1\"),\n- mock.call(\"parser/TestItemLoader/title/xpath/1\"),\n+ mock.call(\"parser/TestItemLoader/title/css/1/title from h2\"),\n+ mock.call(\"parser/TestItemLoader/title/xpath/1/title from article\"),\n mock.call(\"parser/TestItemLoader/title/css/2\"),\n+ mock.call(\"parser/TestItemLoader/title/xpath/2/title from aside/missing\"),\n ]\n )\n+ assert loader.stats.inc_value.call_count == 4\n", "FAIL_TO_PASS": ["tests/test_loader.py::test_get_selector_values", "tests/test_loader.py::test_multiple_1_with_name", "tests/test_loader.py::test_multiple_2_with_name"]}], "all_FAIL_TO_PASS": ["tests/test_loader.py::test_get_selector_values", "tests/test_loader.py::test_multiple_1_with_name", "tests/test_loader.py::test_multiple_2_with_name"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Duke-GCB__lando-155_x1", "level": 1, "source": "swerebench", "repo": "Duke-GCB/lando", "image": "swerebench/sweb.eval.x86_64.duke-gcb_1776_lando-155:latest", "base_commit": "9fd8cb5d0aa19bc83f1d8d1d6936fd60e0d2238a", "num_bugs": 1, "bugs": [{"instance_id": "Duke-GCB__lando-155", "base_commit": "9fd8cb5d0aa19bc83f1d8d1d6936fd60e0d2238a", "gold_patch": "diff --git a/lando/k8s/jobmanager.py b/lando/k8s/jobmanager.py\nindex d9b893e..c73cbfb 100644\n--- a/lando/k8s/jobmanager.py\n+++ b/lando/k8s/jobmanager.py\n@@ -233,10 +233,10 @@ class JobManager(object):\n \n def _create_organize_output_config_map(self, name, filename, methods_document_content):\n config_data = {\n+ \"bespin_job_id\": self.job.id,\n \"destination_dir\": Paths.OUTPUT_RESULTS_DIR,\n \"workflow_path\": self.names.workflow_path,\n \"job_order_path\": self.names.job_order_path,\n- \"job_data_path\": \"TODO\",\n \"bespin_workflow_stdout_path\": self.names.run_workflow_stdout_path,\n \"bespin_workflow_stderr_path\": self.names.run_workflow_stderr_path,\n \"methods_template\": methods_document_content,\n", "test_patch": "diff --git a/lando/k8s/tests/test_jobmanager.py b/lando/k8s/tests/test_jobmanager.py\nindex c33208b..2a5e99e 100644\n--- a/lando/k8s/tests/test_jobmanager.py\n+++ b/lando/k8s/tests/test_jobmanager.py\n@@ -251,10 +251,10 @@ class TestJobManager(TestCase):\n data={\n 'organizeoutput.json':\n json.dumps({\n+ \"bespin_job_id\": '51',\n \"destination_dir\": \"/bespin/output-data/results\",\n \"workflow_path\": \"/bespin/job-data/workflow/someurl\",\n \"job_order_path\": \"/bespin/job-data/job-order.json\",\n- \"job_data_path\": \"TODO\",\n \"bespin_workflow_stdout_path\": \"/bespin/output-data/bespin-workflow-output.json\",\n \"bespin_workflow_stderr_path\": \"/bespin/output-data/bespin-workflow-output.log\",\n \"methods_template\": \"markdown\"\n", "FAIL_TO_PASS": ["lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_organize_output_project_job"]}], "all_FAIL_TO_PASS": ["lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_organize_output_project_job"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ARMmbed__greentea-263_x1", "level": 1, "source": "swerebench", "repo": "ARMmbed/greentea", "image": "swerebench/sweb.eval.x86_64.armmbed_1776_greentea-263:latest", "base_commit": "68508c5f4d7cf0635c75399d0ff7cfa896fdf2cc", "num_bugs": 1, "bugs": [{"instance_id": "ARMmbed__greentea-263", "base_commit": "68508c5f4d7cf0635c75399d0ff7cfa896fdf2cc", "gold_patch": "diff --git a/mbed_greentea/mbed_greentea_cli.py b/mbed_greentea/mbed_greentea_cli.py\nindex f6a13c4..446b965 100644\n--- a/mbed_greentea/mbed_greentea_cli.py\n+++ b/mbed_greentea/mbed_greentea_cli.py\n@@ -23,6 +23,7 @@ import os\n import sys\n import random\n import optparse\n+import fnmatch\n from time import time\n try:\n from Queue import Queue\n@@ -119,18 +120,6 @@ def create_filtered_test_list(ctest_test_list, test_by_names, skip_test, test_sp\n @return\n \"\"\"\n \n- def filter_names_by_prefix(test_case_name_list, prefix_name):\n- \"\"\"!\n- @param test_case_name_list List of all test cases\n- @param prefix_name Prefix of test name we are looking for\n- @result Set with names of test names starting with 'prefix_name'\n- \"\"\"\n- result = list()\n- for test_name in test_case_name_list:\n- if test_name.startswith(prefix_name):\n- result.append(test_name)\n- return sorted(result)\n-\n filtered_ctest_test_list = ctest_test_list\n test_list = None\n invalid_test_names = []\n@@ -143,17 +132,15 @@ def create_filtered_test_list(ctest_test_list, test_by_names, skip_test, test_sp\n gt_logger.gt_log(\"test case filter (specified with -n option)\")\n \n for test_name in set(test_list):\n- if test_name.endswith('*'):\n- # This 'star-sufix' filter allows users to filter tests with fixed prefixes\n- # Example: -n 'TESTS-mbed_drivers* will filter all test cases with name starting with 'TESTS-mbed_drivers'\n- for test_name_filtered in filter_names_by_prefix(ctest_test_list.keys(), test_name[:-1]):\n- gt_logger.gt_log_tab(\"test filtered in '%s'\"% gt_logger.gt_bright(test_name_filtered))\n- filtered_ctest_test_list[test_name_filtered] = ctest_test_list[test_name_filtered]\n- elif test_name not in ctest_test_list:\n- invalid_test_names.append(test_name)\n+ gt_logger.gt_log_tab(test_name)\n+ matches = [test for test in ctest_test_list.keys() if fnmatch.fnmatch(test, test_name)]\n+ gt_logger.gt_log_tab(str(ctest_test_list))\n+ if matches:\n+ for match in matches:\n+ gt_logger.gt_log_tab(\"test filtered in '%s'\"% gt_logger.gt_bright(match))\n+ filtered_ctest_test_list[match] = ctest_test_list[match]\n else:\n- gt_logger.gt_log_tab(\"test filtered in '%s'\"% gt_logger.gt_bright(test_name))\n- filtered_ctest_test_list[test_name] = ctest_test_list[test_name]\n+ invalid_test_names.append(test_name)\n \n if skip_test:\n test_list = skip_test.split(',')\n", "test_patch": "diff --git a/test/mbed_gt_cli.py b/test/mbed_gt_cli.py\nindex 0646c20..8f4a1eb 100644\n--- a/test/mbed_gt_cli.py\n+++ b/test/mbed_gt_cli.py\n@@ -21,6 +21,36 @@ import sys\n import unittest\n \n from mbed_greentea import mbed_greentea_cli\n+from mbed_greentea.tests_spec import TestSpec\n+\n+test_spec_def = {\n+ \"builds\": {\n+ \"K64F-ARM\": {\n+ \"platform\": \"K64F\",\n+ \"toolchain\": \"ARM\",\n+ \"base_path\": \"./.build/K64F/ARM\",\n+ \"baud_rate\": 115200,\n+ \"tests\": {\n+ \"mbed-drivers-test-generic_tests\":{\n+ \"binaries\":[\n+ {\n+ \"binary_type\": \"bootable\",\n+ \"path\": \"./.build/K64F/ARM/mbed-drivers-test-generic_tests.bin\"\n+ }\n+ ]\n+ },\n+ \"mbed-drivers-test-c_strings\":{\n+ \"binaries\":[\n+ {\n+ \"binary_type\": \"bootable\",\n+ \"path\": \"./.build/K64F/ARM/mbed-drivers-test-c_strings.bin\"\n+ }\n+ ]\n+ }\n+ }\n+ }\n+ }\n+}\n \n class GreenteaCliFunctionality(unittest.TestCase):\n \n@@ -86,5 +116,36 @@ class GreenteaCliFunctionality(unittest.TestCase):\n os.chdir(curr_dir)\n shutil.rmtree(test1_dir)\n \n+ def test_create_filtered_test_list(self):\n+ test_spec = TestSpec()\n+ test_spec.parse(test_spec_def)\n+ test_build = test_spec.get_test_builds()[0]\n+\n+ test_list = mbed_greentea_cli.create_filtered_test_list(test_build.get_tests(),\n+ 'mbed-drivers-test-generic_*',\n+ None,\n+ test_spec=test_spec)\n+ self.assertEqual(set(test_list.keys()), set(['mbed-drivers-test-generic_tests']))\n+\n+ test_list = mbed_greentea_cli.create_filtered_test_list(test_build.get_tests(),\n+ '*_strings',\n+ None,\n+ test_spec=test_spec)\n+ self.assertEqual(set(test_list.keys()), set(['mbed-drivers-test-c_strings']))\n+\n+ test_list = mbed_greentea_cli.create_filtered_test_list(test_build.get_tests(),\n+ 'mbed*s',\n+ None,\n+ test_spec=test_spec)\n+ expected = set(['mbed-drivers-test-c_strings', 'mbed-drivers-test-generic_tests'])\n+ self.assertEqual(set(test_list.keys()), expected)\n+\n+ test_list = mbed_greentea_cli.create_filtered_test_list(test_build.get_tests(),\n+ '*-drivers-*',\n+ None,\n+ test_spec=test_spec)\n+ expected = set(['mbed-drivers-test-c_strings', 'mbed-drivers-test-generic_tests'])\n+ self.assertEqual(set(test_list.keys()), expected)\n+\n if __name__ == '__main__':\n unittest.main()\ndiff --git a/test/mbed_gt_target_info.py b/test/mbed_gt_target_info.py\nindex e630e7b..a12ba09 100644\n--- a/test/mbed_gt_target_info.py\n+++ b/test/mbed_gt_target_info.py\n@@ -416,7 +416,7 @@ mbed-gcc 1.1.0\n with patch(\"mbed_greentea.mbed_target_info.walk\") as _walk:\n _walk.return_value = iter([(\"\", [\"foo\"], []), (\"foo\", [], [\"targets.json\"])])\n result = list(mbed_target_info._find_targets_json(\"bogus_path\"))\n- self.assertEqual(result, [\"foo/targets.json\"])\n+ self.assertEqual(result, [os.path.join(\"foo\", \"targets.json\")])\n \n def test_find_targets_json_ignored(self):\n with patch(\"mbed_greentea.mbed_target_info.walk\") as _walk:\n", "FAIL_TO_PASS": ["test/mbed_gt_cli.py::GreenteaCliFunctionality::test_create_filtered_test_list"]}], "all_FAIL_TO_PASS": ["test/mbed_gt_cli.py::GreenteaCliFunctionality::test_create_filtered_test_list"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MushroomMaula__fastapi_login-48_x1", "level": 1, "source": "swerebench", "repo": "MushroomMaula/fastapi_login", "image": "swerebench/sweb.eval.x86_64.mushroommaula_1776_fastapi_login-48:latest", "base_commit": "f50e980dd0be40946109077d5f40c6c3a2702aca", "num_bugs": 1, "bugs": [{"instance_id": "MushroomMaula__fastapi_login-48", "base_commit": "f50e980dd0be40946109077d5f40c6c3a2702aca", "gold_patch": "diff --git a/fastapi_login/fastapi_login.py b/fastapi_login/fastapi_login.py\nindex ed75a80..ea07735 100644\n--- a/fastapi_login/fastapi_login.py\n+++ b/fastapi_login/fastapi_login.py\n@@ -308,7 +308,7 @@ class LoginManager(OAuth2PasswordBearer):\n \"\"\"\n try:\n payload = self._get_payload(token)\n- except self.not_authenticated_exception:\n+ except type(self.not_authenticated_exception):\n # We got an error while decoding the token\n return False\n \n@@ -369,5 +369,5 @@ class LoginManager(OAuth2PasswordBearer):\n # it's not a good idea to return the Exception\n # so we set the user to None\n request.state.user = None\n- \n+\n return await call_next(request)\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 64fc115..3b2e503 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -85,5 +85,4 @@ class CustomAuthException(Exception):\n \n @pytest.fixture\n def custom_exception():\n-\n return CustomAuthException\ndiff --git a/tests/test_basic_functionality.py b/tests/test_basic_functionality.py\nindex 0317b43..993d40d 100644\n--- a/tests/test_basic_functionality.py\n+++ b/tests/test_basic_functionality.py\n@@ -68,8 +68,8 @@ def test_token_from_cookie_raises(clean_manager):\n clean_manager._token_from_cookie(request)\n \n assert exc_info.value == InvalidCredentialsException\n- \n- \n+\n+\n def test_token_from_cookie_returns_none_auto_error_off(clean_manager):\n clean_manager.auto_error = False\n request = Mock(cookies={clean_manager.cookie_name: \"\"})\n@@ -116,5 +116,6 @@ def test_has_scopes_missing_scopes(clean_manager, default_data):\n required_scopes = scopes + [\"write\"]\n assert clean_manager.has_scopes(token, SecurityScopes(scopes=required_scopes)) is False\n \n-\n-\n+def test_has_scopes_invalid_token(clean_manager):\n+ token = \"invalid-token\"\n+ assert not clean_manager.has_scopes(token, SecurityScopes(scopes=[\"test\"]))\n", "FAIL_TO_PASS": ["tests/test_basic_functionality.py::test_has_scopes_invalid_token"]}], "all_FAIL_TO_PASS": ["tests/test_basic_functionality.py::test_has_scopes_invalid_token"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "DKISTDC__dkist-340_x1", "level": 1, "source": "swerebench", "repo": "DKISTDC/dkist", "image": "swerebench/sweb.eval.x86_64.dkistdc_1776_dkist-340:latest", "base_commit": "983c1f120de20a935e4aa7efc257472f80e1781a", "num_bugs": 1, "bugs": [{"instance_id": "DKISTDC__dkist-340", "base_commit": "983c1f120de20a935e4aa7efc257472f80e1781a", "gold_patch": "diff --git a/changelog/340.bugfix.rst b/changelog/340.bugfix.rst\nnew file mode 100644\nindex 0000000..8b22d1d\n--- /dev/null\n+++ b/changelog/340.bugfix.rst\n@@ -0,0 +1,1 @@\n+Fix a bug with `dkist.net.transfer_complete_datasets` where a length one ``UnifiedResponse`` would cause an error.\ndiff --git a/changelog/340.feature.rst b/changelog/340.feature.rst\nnew file mode 100644\nindex 0000000..eb59200\n--- /dev/null\n+++ b/changelog/340.feature.rst\n@@ -0,0 +1,1 @@\n+`dkist.net.transfer_complete_datasets` will now only create one Globus task for all datasets it downloads.\ndiff --git a/dkist/net/globus/transfer.py b/dkist/net/globus/transfer.py\nindex 90e711b..2669738 100644\n--- a/dkist/net/globus/transfer.py\n+++ b/dkist/net/globus/transfer.py\n@@ -1,7 +1,6 @@\n \"\"\"\n Functions and helpers for orchestrating and monitoring transfers using Globus.\n \"\"\"\n-import copy\n import json\n import time\n import pathlib\n@@ -19,43 +18,50 @@ from .endpoints import (auto_activate_endpoint, get_data_center_endpoint_id,\n __all__ = [\"watch_transfer_progress\", \"start_transfer_from_file_list\"]\n \n \n-def start_transfer_from_file_list(src_endpoint, dst_endpoint, dst_base_path, file_list,\n- src_base_path=None, recursive=False, label=None):\n+def start_transfer_from_file_list(\n+ src_endpoint: str,\n+ dst_endpoint: str,\n+ dst_base_path: PathLike,\n+ file_list: list[PathLike],\n+ src_base_path: PathLike = None,\n+ recursive: bool | list[bool] = False,\n+ label: str = None\n+) -> str:\n \"\"\"\n Start a new transfer task for a list of files.\n \n Parameters\n ----------\n- src_endpoint : `str`\n+ src_endpoint\n The endpoint to copy file from. Can be any identifier accepted by\n `~dkist.net.globus.get_endpoint_id`.\n \n- dst_endpoint : `str`\n+ dst_endpoint\n The endpoint to copy file to. Can be any identifier accepted by\n `~dkist.net.globus.get_endpoint_id`.\n \n- dst_base_path : `~pathlib.Path`\n+ dst_base_path\n The destination path, must be accessible from the endpoint, will be\n created if it does not exist.\n \n- file_list : `list`\n+ file_list\n The list of file paths on the ``src_endpoint`` to transfer to the ``dst_endpoint``.\n \n- src_base_path : `~pathlib.Path`, optional\n+ src_base_path\n The path prefix on the items in ``file_list`` to be stripped before\n copying to ``dst_base_path``. i.e. if the file path in ``path_list`` is\n ``/spam/eggs/filename.fits`` and ``src_base_path`` is ``/spam`` the\n ``eggs/`` folder will be copied to ``dst_base_path``. By default only\n the filenames are kept, and none of the directories.\n \n- recursive : `bool` or `list` of `bool`, optional\n+ recursive\n Controls if the path in ``file_list`` is added to the Globus task with\n the recursive flag or not.\n This should be `True` if the element of ``file_list`` is a directory.\n If you need to set this per-item in ``file_list`` it should be a `list`\n of `bool` of equal length as ``file_list``.\n \n- label : `str`\n+ label\n Label for the Globus transfer. If None then a default will be used.\n \n Returns\n@@ -87,17 +93,20 @@ def start_transfer_from_file_list(src_endpoint, dst_endpoint, dst_base_path, fil\n sync_level=\"checksum\",\n verify_checksum=True)\n \n- dst_base_path = pathlib.Path(dst_base_path)\n- src_file_list = copy.copy(file_list)\n- dst_file_list = []\n- for src_file in src_file_list:\n- # If a common prefix is not specified just copy the filename\n- if not src_base_path:\n- src_filepath = src_file.name\n- else:\n- # Otherwise use the filepath relative to the base path\n- src_filepath = src_file.relative_to(src_base_path)\n- dst_file_list.append(dst_base_path / src_filepath)\n+ src_file_list = file_list\n+ if not isinstance(dst_base_path, (list, tuple)):\n+ dst_base_path = pathlib.Path(dst_base_path)\n+ dst_file_list = []\n+ for src_file in src_file_list:\n+ # If a common prefix is not specified just copy the filename or last directory\n+ if not src_base_path:\n+ src_filepath = src_file.name\n+ else:\n+ # Otherwise use the filepath relative to the base path\n+ src_filepath = src_file.relative_to(src_base_path)\n+ dst_file_list.append(dst_base_path / src_filepath)\n+ else:\n+ dst_file_list = dst_base_path\n \n for src_file, dst_file, rec in zip(src_file_list, dst_file_list, recursive):\n transfer_manifest.add_item(str(src_file), str(dst_file), recursive=rec)\n@@ -265,12 +274,12 @@ def watch_transfer_progress(task_id, tfr_client, poll_interval=5,\n \n def _orchestrate_transfer_task(file_list: list[PathLike],\n recursive: list[bool],\n- destination_path: PathLike = \"/~/\",\n+ destination_path: PathLike | list[PathLike] = \"/~/\",\n destination_endpoint: str = None,\n *,\n progress: bool | Literal[\"verbose\"] = True,\n wait: bool = True,\n- label=None):\n+ label: str = None):\n \"\"\"\n Transfer the files given in file_list to the path on ``destination_endpoint``.\n \ndiff --git a/dkist/net/helpers.py b/dkist/net/helpers.py\nindex 7627d06..67314d9 100644\n--- a/dkist/net/helpers.py\n+++ b/dkist/net/helpers.py\n@@ -13,6 +13,7 @@ from sunpy.net.attr import or_\n from sunpy.net.base_client import QueryResponseRow\n from sunpy.net.fido_factory import UnifiedResponse\n \n+from dkist.net import conf\n from dkist.net.attrs import Dataset\n from dkist.net.client import DKISTClient, DKISTQueryResponseTable\n from dkist.net.globus.transfer import _orchestrate_transfer_task\n@@ -35,6 +36,25 @@ def _get_dataset_inventory(dataset_id: str | Iterable[str]) -> DKISTQueryRespons\n return results\n \n \n+def _get_globus_path_for_dataset(dataset: QueryResponseRow):\n+ \"\"\"\n+ Given a dataset ID get the directory on the source endpoint.\n+ \"\"\"\n+ if not isinstance(dataset, QueryResponseRow):\n+ raise TypeError(\"Input should be a single row of dataset inventory.\")\n+\n+ # At this point we only have one dataset, and it should be a row not a table\n+ dataset_id = dataset[\"Dataset ID\"]\n+ proposal_id = dataset[\"Primary Proposal ID\"]\n+ bucket = dataset[\"Storage Bucket\"]\n+\n+ return Path(conf.dataset_path.format(\n+ datasetId=dataset_id,\n+ primaryProposalId=proposal_id,\n+ bucket=bucket\n+ ))\n+\n+\n def transfer_complete_datasets(datasets: str | Iterable[str] | QueryResponseRow | DKISTQueryResponseTable | UnifiedResponse,\n path: PathLike = \"/~/\",\n destination_endpoint: str = None,\n@@ -52,14 +72,13 @@ def transfer_complete_datasets(datasets: str | Iterable[str] | QueryResponseRow\n ``Fido.search``.\n \n path\n- The path to save the data in, must be accessible by the Globus\n- endpoint.\n- The default value is ``/~/``.\n- It is possible to put placeholder strings in the path with any key\n- from the dataset inventory dictionary which can be accessed as\n- ``ds.meta['inventory']``. An example of this would be\n- ``path=\"~/dkist/{datasetId}\"`` to save the files in a folder named\n- with the dataset ID being downloaded.\n+ The path to save the data in, must be accessible by the Globus endpoint.\n+ The default value is ``/~/``. It is possible to put placeholder strings\n+ in the path with any key from inventory which can be shown with\n+ :meth:`dkist.utils.inventory.path_format_keys`. An example of this\n+ would be ``path=\"~/dkist/{primary_proposal_id}\"`` to save the files in a\n+ folder named for the proposal id. **Note** that ``{dataset_id}`` is\n+ always added to the path if it is not already the last element.\n \n destination_endpoint\n A unique specifier for a Globus endpoint. If `None` a local\n@@ -87,18 +106,22 @@ def transfer_complete_datasets(datasets: str | Iterable[str] | QueryResponseRow\n The path to the directories containing the dataset(s) on the destination endpoint.\n \n \"\"\"\n- # Avoid circular import\n- from dkist.net import conf\n+ path = Path(path)\n+ if path.parts[-1] != \"{dataset_id}\":\n+ path = path / \"{dataset_id}\"\n \n- if isinstance(datasets, (DKISTQueryResponseTable, QueryResponseRow)):\n- # These we don't have to pre-process\n+ if isinstance(datasets, DKISTQueryResponseTable):\n+ # This we don't have to pre-process\n pass\n \n+ elif isinstance(datasets, QueryResponseRow):\n+ datasets = DKISTQueryResponseTable(datasets)\n+\n elif isinstance(datasets, UnifiedResponse):\n # If we have a UnifiedResponse object, it could contain one or more dkist tables.\n # Stack them and then treat them like we were passed a single table with many rows.\n datasets = datasets[\"dkist\"]\n- if len(datasets) > 1:\n+ if isinstance(datasets, UnifiedResponse) and len(datasets) > 1:\n datasets = table.vstack(datasets, metadata_conflicts=\"silent\")\n \n elif isinstance(datasets, str) or all(isinstance(d, str) for d in datasets):\n@@ -109,45 +132,38 @@ def transfer_complete_datasets(datasets: str | Iterable[str] | QueryResponseRow\n # Anything else, error\n raise TypeError(f\"{type(datasets)} is of an unknown type, it should be search results or one or more dataset IDs.\")\n \n- if not isinstance(datasets, QueryResponseRow) and len(datasets) > 1:\n- paths = []\n- for record in datasets:\n- paths.append(transfer_complete_datasets(record,\n- path=path,\n- destination_endpoint=destination_endpoint,\n- progress=progress,\n- wait=wait,\n- label=label))\n- return paths\n-\n- # ensure a length one table is a row\n- if len(datasets) == 1:\n- datasets = datasets[0]\n \n- # At this point we only have one dataset, and it should be a row not a table\n- dataset = datasets\n- dataset_id = dataset[\"Dataset ID\"]\n- proposal_id = dataset[\"Primary Proposal ID\"]\n- bucket = dataset[\"Storage Bucket\"]\n+ source_paths = []\n+ for record in datasets:\n+ source_paths.append(_get_globus_path_for_dataset(record))\n \n- path_inv = path_format_inventory(dict(dataset))\n- destination_path = Path(path.format(**path_inv))\n+ destination_paths = []\n+ for dataset in datasets:\n+ dataset_id = dataset[\"Dataset ID\"]\n+ proposal_id = dataset[\"Primary Proposal ID\"]\n+ bucket = dataset[\"Storage Bucket\"]\n \n- file_list = [Path(conf.dataset_path.format(\n- datasetId=dataset_id,\n- primaryProposalId=proposal_id,\n- bucket=bucket\n- ))]\n+ path_inv = path_format_inventory(dict(dataset))\n+ destination_paths.append(Path(str(path).format(**path_inv)))\n+\n+ if not label:\n+ now = datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M\")\n+ datasetids = \",\".join(datasets[\"Dataset ID\"])\n+ if len(datasetids) > 80:\n+ datasetids = f\"{len(datasets['Dataset ID'])} datasets\"\n+ label = f\"DKIST Python Tools - {now} - {datasetids}\"\n \n- now = datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M\")\n- label = f\"DKIST Python Tools - {now} {dataset_id}\" if label is None else label\n+ # Globus limits labels to 128 characters, so truncate if needed\n+ # In principle this can't happen because of the truncation above, but just in case\n+ if len(label) > 128:\n+ label = label[:125] + \"...\" # pragma: no cover\n \n- _orchestrate_transfer_task(file_list,\n+ _orchestrate_transfer_task(source_paths,\n recursive=True,\n- destination_path=destination_path,\n+ destination_path=destination_paths,\n destination_endpoint=destination_endpoint,\n progress=progress,\n wait=wait,\n label=label)\n \n- return destination_path / dataset_id\n+ return destination_paths\ndiff --git a/dkist/utils/inventory.py b/dkist/utils/inventory.py\nindex 9f9f77c..440ce53 100644\n--- a/dkist/utils/inventory.py\n+++ b/dkist/utils/inventory.py\n@@ -85,7 +85,7 @@ def _key_clean(key):\n return key.lower()\n \n \n-def path_format_keys(keymap):\n+def path_format_keys(keymap=INVENTORY_KEY_MAP):\n \"\"\"\n Return a list of all valid keys for path formatting.\n \"\"\"\n", "test_patch": "diff --git a/dkist/net/globus/tests/test_transfer.py b/dkist/net/globus/tests/test_transfer.py\nindex 35f186c..2149147 100644\n--- a/dkist/net/globus/tests/test_transfer.py\n+++ b/dkist/net/globus/tests/test_transfer.py\n@@ -107,6 +107,20 @@ def test_start_transfer_src_base(mocker, transfer_client, mock_endpoints):\n assert f\"{os.path.sep}b{os.path.sep}\" + filepath.name == tfr[\"destination_path\"]\n \n \n+def test_start_transfer_multiple_paths(mocker, transfer_client, mock_endpoints):\n+ submit_mock = mocker.patch(\"globus_sdk.TransferClient.submit_transfer\",\n+ return_value={\"task_id\": \"task_id\"})\n+ mocker.patch(\"globus_sdk.TransferClient.get_submission_id\",\n+ return_value={\"value\": \"wibble\"})\n+ file_list = list(map(Path, [\"/a/name.fits\", \"/a/name2.fits\"]))\n+ dst_list = list(map(Path, [\"/aplace/newname.fits\", \"/anotherplace/newname2.fits\"]))\n+ start_transfer_from_file_list(\"a\", \"b\", dst_list, file_list)\n+ transfer_manifest = submit_mock.call_args_list[0][0][0][\"DATA\"]\n+\n+ for filepath, tfr in zip(dst_list, transfer_manifest):\n+ assert str(filepath) == tfr[\"destination_path\"]\n+\n+\n def test_process_event_list(transfer_client, mock_task_event_list):\n (events,\n json_events,\ndiff --git a/dkist/net/tests/test_helpers.py b/dkist/net/tests/test_helpers.py\nindex 6223d2d..2d63342 100644\n--- a/dkist/net/tests/test_helpers.py\n+++ b/dkist/net/tests/test_helpers.py\n@@ -39,11 +39,11 @@ def test_download_default_keywords(orchestrate_transfer_mock, keywords):\n )\n \n if keywords[\"label\"] is None:\n- keywords[\"label\"] = f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} AAAA\"\n+ keywords[\"label\"] = f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} - AAAA\"\n orchestrate_transfer_mock.assert_called_once_with(\n [Path(\"/data/pm_1_10/AAAA\")],\n recursive=True,\n- destination_path=Path(\"/~\"),\n+ destination_path=[Path(\"/~/AAAA\")],\n **keywords\n )\n \n@@ -79,11 +79,11 @@ def test_transfer_from_dataset_id(mocker, orchestrate_transfer_mock):\n orchestrate_transfer_mock.assert_called_once_with(\n [Path(\"/data/pm_1_10/AAAA\")],\n recursive=True,\n- destination_path=Path(\"/~\"),\n+ destination_path=[Path(\"/~/AAAA\")],\n destination_endpoint=None,\n progress=True,\n wait=True,\n- label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} AAAA\"\n+ label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} - AAAA\"\n )\n \n get_inv_mock.assert_called_once_with(\"AAAA\")\n@@ -113,32 +113,50 @@ def test_transfer_from_multiple_dataset_id(mocker, orchestrate_transfer_mock):\n \n transfer_complete_datasets([\"AAAA\", \"BBBB\"])\n \n- orchestrate_transfer_mock.assert_has_calls(\n- [\n- mocker.call(\n- [Path(\"/data/pm_1_10/AAAA\")],\n- recursive=True,\n- destination_path=Path(\"/~\"),\n- destination_endpoint=None,\n- progress=True,\n- wait=True,\n- label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} AAAA\",\n- ),\n- mocker.call(\n- [Path(\"/data/pm_1_10/BBBB\")],\n- recursive=True,\n- destination_path=Path(\"/~\"),\n- destination_endpoint=None,\n- progress=True,\n- wait=True,\n- label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} BBBB\",\n- ),\n- ]\n+ orchestrate_transfer_mock.assert_called_once_with(\n+ [Path(\"/data/pm_1_10/AAAA\"), Path(\"/data/pm_1_10/BBBB\")],\n+ recursive=True,\n+ destination_path=[Path(\"/~/AAAA\"), Path(\"/~/BBBB\")],\n+ destination_endpoint=None,\n+ progress=True,\n+ wait=True,\n+ label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} - AAAA,BBBB\",\n )\n \n get_inv_mock.assert_called_once_with([\"AAAA\", \"BBBB\"])\n \n \n+def test_transfer_from_many_dataset_id(mocker, orchestrate_transfer_mock):\n+ \"\"\"Check that the short label is used when downloading many datasets\"\"\"\n+\n+ many_ds = [a*4 for a in \"ABCDEFGHIJKLMNOPQ\"]\n+ get_inv_mock = mocker.patch(\n+ \"dkist.net.helpers._get_dataset_inventory\",\n+ autospec=True,\n+ return_value=DKISTQueryResponseTable([\n+ {\n+ \"Dataset ID\": _id,\n+ \"Primary Proposal ID\": \"pm_1_10\",\n+ \"Storage Bucket\": \"data\",\n+ \"Wavelength Max\": 856,\n+ \"Wavelength Min\": 854,\n+ } for _id in many_ds\n+ ]),\n+ )\n+\n+ transfer_complete_datasets(many_ds)\n+\n+ orchestrate_transfer_mock.assert_called_once_with(\n+ mocker.ANY,\n+ recursive=mocker.ANY,\n+ destination_path=mocker.ANY,\n+ destination_endpoint=mocker.ANY,\n+ progress=mocker.ANY,\n+ wait=mocker.ANY,\n+ label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} - {len(many_ds)} datasets\"\n+ )\n+\n+\n def test_transfer_from_table(orchestrate_transfer_mock, mocker):\n res = DKISTQueryResponseTable(\n {\n@@ -153,21 +171,11 @@ def test_transfer_from_table(orchestrate_transfer_mock, mocker):\n transfer_complete_datasets(res, label=\"fibble\")\n \n kwargs = {\"progress\": True, \"wait\": True, \"destination_endpoint\": None, \"label\": \"fibble\"}\n- orchestrate_transfer_mock.assert_has_calls(\n- [\n- mocker.call(\n- [Path(\"/data/pm_1_10/A\")],\n- recursive=True,\n- destination_path=Path(\"/~\"),\n- **kwargs\n- ),\n- mocker.call(\n- [Path(\"/data/pm_2_20/B\")],\n- recursive=True,\n- destination_path=Path(\"/~\"),\n- **kwargs\n- ),\n- ]\n+ orchestrate_transfer_mock.assert_called_once_with(\n+ [Path(\"/data/pm_1_10/A\"), Path(\"/data/pm_2_20/B\")],\n+ recursive=True,\n+ destination_path=[Path(\"/~/A\"), Path(\"/~/B\")],\n+ **kwargs\n )\n \n \n@@ -190,7 +198,7 @@ def test_transfer_from_length_one_table(orchestrate_transfer_mock, mocker):\n mocker.call(\n [Path(\"/data/pm_1_10/A\")],\n recursive=True,\n- destination_path=Path(\"/~\"),\n+ destination_path=[Path(\"/~/A\")],\n **kwargs\n ),\n ]\n@@ -216,7 +224,7 @@ def test_transfer_from_row(orchestrate_transfer_mock, mocker):\n mocker.call(\n [Path(\"/data/pm_1_10/A\")],\n recursive=True,\n- destination_path=Path(\"/~\"),\n+ destination_path=[Path(\"/~/A\")],\n **kwargs\n ),\n ]\n@@ -249,21 +257,11 @@ def test_transfer_from_UnifiedResponse(orchestrate_transfer_mock, mocker):\n transfer_complete_datasets(res, label=\"fibble\")\n \n kwargs = {\"progress\": True, \"wait\": True, \"destination_endpoint\": None, \"label\": \"fibble\"}\n- orchestrate_transfer_mock.assert_has_calls(\n- [\n- mocker.call(\n- [Path(\"/data/pm_1_10/A\")],\n- recursive=True,\n- destination_path=Path(\"/~\"),\n- **kwargs\n- ),\n- mocker.call(\n- [Path(\"/data/pm_2_20/B\")],\n- recursive=True,\n- destination_path=Path(\"/~\"),\n- **kwargs\n- ),\n- ]\n+ orchestrate_transfer_mock.assert_called_once_with(\n+ [Path(\"/data/pm_1_10/A\"), Path(\"/data/pm_2_20/B\")],\n+ recursive=True,\n+ destination_path=[Path(\"/~/A\"), Path(\"/~/B\")],\n+ **kwargs\n )\n \n \n@@ -288,11 +286,30 @@ def test_transfer_path_interpolation(orchestrate_transfer_mock, mocker):\n orchestrate_transfer_mock.assert_called_once_with(\n [Path(\"/data/pm_1_10/AAAA\")],\n recursive=True,\n- destination_path=Path(\"HIT/AAAA\"),\n+ destination_path=[Path(\"HIT/AAAA\")],\n destination_endpoint=None,\n progress=True,\n wait=True,\n- label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} AAAA\"\n+ label=f\"DKIST Python Tools - {datetime.datetime.now().strftime('%Y-%m-%dT%H-%M')} - AAAA\"\n )\n \n get_inv_mock.assert_called_once_with(\"AAAA\")\n+\n+\n+def test_transfer_dataset_wrong_type(mocker, orchestrate_transfer_mock):\n+ \"\"\"\n+ Test that transfer fails if `_get_globus_path_for_dataset` is given bad input.\n+ In practice this should never happen in the wild because of error catching elsewhere,\n+ but worth checking in case that changes.\n+ \"\"\"\n+ get_inv_mock = mocker.patch(\"dkist.net.helpers._get_dataset_inventory\",\n+ autospec=True,\n+ return_value=\"This is not a QueryResponseRow\")\n+\n+ with pytest.raises(TypeError, match=\"Input should be a single row of dataset inventory.\"):\n+ transfer_complete_datasets(\"AAAA\")\n+\n+ # Also check that just giving a bad type to transfer_complete_datasets fails\n+ # Again, shouldn't happen but we'll check anyway\n+ with pytest.raises(TypeError, match=\"is of an unknown type, it should be search results or one or more dataset IDs.\"):\n+ transfer_complete_datasets([42])\n", "FAIL_TO_PASS": ["dkist/net/globus/tests/test_transfer.py::test_start_transfer_multiple_paths", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords0]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords1]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords2]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords3]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords4]", "dkist/net/tests/test_helpers.py::test_transfer_from_dataset_id", "dkist/net/tests/test_helpers.py::test_transfer_from_multiple_dataset_id", "dkist/net/tests/test_helpers.py::test_transfer_from_many_dataset_id", "dkist/net/tests/test_helpers.py::test_transfer_from_table", "dkist/net/tests/test_helpers.py::test_transfer_from_length_one_table", "dkist/net/tests/test_helpers.py::test_transfer_from_row", "dkist/net/tests/test_helpers.py::test_transfer_from_UnifiedResponse", "dkist/net/tests/test_helpers.py::test_transfer_path_interpolation", "dkist/net/tests/test_helpers.py::test_transfer_dataset_wrong_type"]}], "all_FAIL_TO_PASS": ["dkist/net/globus/tests/test_transfer.py::test_start_transfer_multiple_paths", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords0]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords1]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords2]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords3]", "dkist/net/tests/test_helpers.py::test_download_default_keywords[keywords4]", "dkist/net/tests/test_helpers.py::test_transfer_from_dataset_id", "dkist/net/tests/test_helpers.py::test_transfer_from_multiple_dataset_id", "dkist/net/tests/test_helpers.py::test_transfer_from_many_dataset_id", "dkist/net/tests/test_helpers.py::test_transfer_from_table", "dkist/net/tests/test_helpers.py::test_transfer_from_length_one_table", "dkist/net/tests/test_helpers.py::test_transfer_from_row", "dkist/net/tests/test_helpers.py::test_transfer_from_UnifiedResponse", "dkist/net/tests/test_helpers.py::test_transfer_path_interpolation", "dkist/net/tests/test_helpers.py::test_transfer_dataset_wrong_type"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Open-EO__openeo-python-client-669_x1", "level": 1, "source": "swerebench", "repo": "Open-EO/openeo-python-client", "image": "swerebench/sweb.eval.x86_64.open-eo_1776_openeo-python-client-669:latest", "base_commit": "37ba26039a93e0849727dae1ee4980642eb49392", "num_bugs": 1, "bugs": [{"instance_id": "Open-EO__openeo-python-client-669", "base_commit": "37ba26039a93e0849727dae1ee4980642eb49392", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex aa030952..7b83adab 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n ### Fixed\n \n+- `load_stac`: use fallback temporal dimension when no \"cube:dimensions\" in STAC Collection ([#666](https://github.com/Open-EO/openeo-python-client/issues/666))\n \n ## [0.35.0] - 2024-11-19\n \ndiff --git a/openeo/metadata.py b/openeo/metadata.py\nindex 1de8c38b..8b770157 100644\n--- a/openeo/metadata.py\n+++ b/openeo/metadata.py\n@@ -11,7 +11,7 @@ import pystac.extensions.eo\n import pystac.extensions.item_assets\n \n from openeo.internal.jupyter import render_component\n-from openeo.util import deep_get\n+from openeo.util import Rfc3339, deep_get\n \n _log = logging.getLogger(__name__)\n \n@@ -691,6 +691,11 @@ class _StacMetadataParser:\n if len(temporal_dims) == 1:\n name, extent = temporal_dims[0]\n return TemporalDimension(name=name, extent=extent)\n+ elif isinstance(stac_obj, pystac.Collection) and stac_obj.extent.temporal:\n+ # No explicit \"cube:dimensions\": build fallback from \"extent.temporal\",\n+ # with dimension name \"t\" (openEO API recommendation).\n+ extent = [Rfc3339(propagate_none=True).normalize(d) for d in stac_obj.extent.temporal.intervals[0]]\n+ return TemporalDimension(name=\"t\", extent=extent)\n else:\n if isinstance(stac_obj, pystac.Item):\n cube_dimensions = stac_obj.properties.get(\"cube:dimensions\", {})\ndiff --git a/openeo/rest/datacube.py b/openeo/rest/datacube.py\nindex c91fb722..f0da5884 100644\n--- a/openeo/rest/datacube.py\n+++ b/openeo/rest/datacube.py\n@@ -203,6 +203,7 @@ class DataCube(_ProcessGraphAbstraction):\n metadata = None\n if metadata:\n bands = [b if isinstance(b, str) else metadata.band_dimension.band_name(b) for b in bands]\n+ # TODO: also apply spatial/temporal filters to metadata?\n metadata = metadata.filter_bands(bands)\n arguments['bands'] = bands\n \n@@ -385,6 +386,9 @@ class DataCube(_ProcessGraphAbstraction):\n graph = PGNode(\"load_stac\", arguments=arguments)\n try:\n metadata = metadata_from_stac(url)\n+ if bands:\n+ # TODO: also apply spatial/temporal filters to metadata?\n+ metadata = metadata.filter_bands(band_names=bands)\n except Exception:\n log.warning(f\"Failed to extract cube metadata from STAC URL {url}\", exc_info=True)\n metadata = None\ndiff --git a/openeo/util.py b/openeo/util.py\nindex 6bbd4d89..44842124 100644\n--- a/openeo/util.py\n+++ b/openeo/util.py\n@@ -172,7 +172,7 @@ class Rfc3339:\n @classmethod\n def _format_datetime(cls, d: dt.datetime) -> str:\n \"\"\"Format given datetime as RFC-3339 date-time string.\"\"\"\n- if d.tzinfo not in {None, dt.timezone.utc}:\n+ if not (d.tzinfo is None or d.tzinfo.tzname(d) == \"UTC\"):\n # TODO: add support for non-UTC timezones?\n raise ValueError(f\"No support for non-UTC timezone {d.tzinfo}\")\n return d.strftime(cls._FMT_DATETIME)\ndiff --git a/setup.py b/setup.py\nindex b5a2fa75..d8ff51ea 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -30,6 +30,7 @@ tests_require = [\n \"pyproj>=3.2.0\", # Pyproj is an optional, best-effort runtime dependency\n \"dirty_equals>=0.8.0\",\n \"pyarrow>=10.0.1\", # For Parquet read/write support in pandas\n+ \"python-dateutil>=2.7.0\",\n ]\n \n docs_require = [\n", "test_patch": "diff --git a/tests/rest/test_connection.py b/tests/rest/test_connection.py\nindex a7e7d318..a447cd6b 100644\n--- a/tests/rest/test_connection.py\n+++ b/tests/rest/test_connection.py\n@@ -18,6 +18,7 @@ import shapely.geometry\n import openeo\n from openeo.capabilities import ApiVersionException\n from openeo.internal.graph_building import FlatGraphableMixin, PGNode\n+from openeo.metadata import _PYSTAC_1_9_EXTENSION_INTERFACE, TemporalDimension\n from openeo.rest import (\n CapabilitiesException,\n OpenEoApiError,\n@@ -40,7 +41,7 @@ from openeo.rest.connection import (\n )\n from openeo.rest.vectorcube import VectorCube\n from openeo.testing.stac import StacDummyBuilder\n-from openeo.util import ContextTimer, dict_no_none\n+from openeo.util import ContextTimer, deep_get, dict_no_none\n \n from .auth.test_cli import auth_config, refresh_token_store\n \n@@ -2622,6 +2623,51 @@ class TestLoadStac:\n },\n }\n \n+ @pytest.mark.skipif(\n+ not _PYSTAC_1_9_EXTENSION_INTERFACE,\n+ reason=\"No backport of implementation/test below PySTAC 1.9 extension interface\",\n+ )\n+ @pytest.mark.parametrize(\n+ [\"collection_extent\", \"dim_extent\"],\n+ [\n+ (\n+ {\"spatial\": {\"bbox\": [[3, 4, 5, 6]]}, \"temporal\": {\"interval\": [[\"2024-01-01\", \"2024-05-05\"]]}},\n+ [\"2024-01-01T00:00:00Z\", \"2024-05-05T00:00:00Z\"],\n+ ),\n+ (\n+ {\"spatial\": {\"bbox\": [[3, 4, 5, 6]]}, \"temporal\": {\"interval\": [[None, \"2024-05-05\"]]}},\n+ [None, \"2024-05-05T00:00:00Z\"],\n+ ),\n+ ],\n+ )\n+ def test_load_stac_no_cube_extension_temporal_dimension(self, con120, tmp_path, collection_extent, dim_extent):\n+ \"\"\"\n+ Metadata detection when STAC metadata does not use \"cube\" extension\n+ https://github.com/Open-EO/openeo-python-client/issues/666\n+ \"\"\"\n+ stac_path = tmp_path / \"stac.json\"\n+ stac_data = StacDummyBuilder.collection(extent=collection_extent)\n+ # No cube:dimensions, but at least \"temporal\" extent is set as indicator for having a temporal dimension\n+ assert \"cube:dimensions\" not in stac_data\n+ assert deep_get(stac_data, \"extent\", \"temporal\")\n+ stac_path.write_text(json.dumps(stac_data))\n+\n+ cube = con120.load_stac(str(stac_path))\n+ assert cube.metadata.temporal_dimension == TemporalDimension(name=\"t\", extent=dim_extent)\n+\n+ def test_load_stac_band_filtering(self, con120, tmp_path):\n+ stac_path = tmp_path / \"stac.json\"\n+ stac_data = StacDummyBuilder.collection(\n+ summaries={\"eo:bands\": [{\"name\": \"B01\"}, {\"name\": \"B02\"}, {\"name\": \"B03\"}]}\n+ )\n+ stac_path.write_text(json.dumps(stac_data))\n+\n+ cube = con120.load_stac(str(stac_path))\n+ assert cube.metadata.band_names == [\"B01\", \"B02\", \"B03\"]\n+\n+ cube = con120.load_stac(str(stac_path), bands=[\"B03\", \"B02\"])\n+ assert cube.metadata.band_names == [\"B03\", \"B02\"]\n+\n \n @pytest.mark.parametrize(\n \"data\",\ndiff --git a/tests/test_metadata.py b/tests/test_metadata.py\nindex fce90186..a11bc6aa 100644\n--- a/tests/test_metadata.py\n+++ b/tests/test_metadata.py\n@@ -849,6 +849,10 @@ def test_metadata_from_stac_collection_bands_from_item_assets(test_data, tmp_pat\n assert warn_count == (0 if eo_extension_is_declared else 1)\n \n \n+@pytest.mark.skipif(\n+ not _PYSTAC_1_9_EXTENSION_INTERFACE,\n+ reason=\"No backport of implementation/test below PySTAC 1.9 extension interface\",\n+)\n @pytest.mark.parametrize(\n [\"stac_dict\", \"expected\"],\n [\n@@ -868,7 +872,7 @@ def test_metadata_from_stac_collection_bands_from_item_assets(test_data, tmp_pat\n ),\n (\n StacDummyBuilder.collection(),\n- None,\n+ (\"t\", [\"2024-01-01T00:00:00Z\", \"2024-05-05T00:00:00Z\"]),\n ),\n (\n StacDummyBuilder.collection(\ndiff --git a/tests/test_util.py b/tests/test_util.py\nindex 345c1f99..803efd54 100644\n--- a/tests/test_util.py\n+++ b/tests/test_util.py\n@@ -7,6 +7,7 @@ import re\n import unittest.mock as mock\n from typing import List, Union\n \n+import dateutil.tz\n import pyproj\n import pytest\n import shapely.geometry\n@@ -87,21 +88,12 @@ class TestRfc3339:\n assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime([2020, 3, 17, 12, 34, 56])\n assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(2020, 3, 17, 12, 34, 56)\n assert \"2020-03-17T12:34:00Z\" == rfc3339.datetime(2020, 3, 17, 12, 34)\n- assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(\n- (2020, \"3\", 17, \"12\", \"34\", 56)\n- )\n- assert \"2020-09-17T12:34:56Z\" == rfc3339.datetime(\n- [2020, \"09\", 17, \"12\", \"34\", 56]\n- )\n- assert \"2020-09-17T12:34:56Z\" == rfc3339.datetime(\n- 2020, \"09\", \"17\", \"12\", \"34\", 56\n- )\n- assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(\n- dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=None)\n- )\n- assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(\n- dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=dt.timezone.utc)\n- )\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime((2020, \"3\", 17, \"12\", \"34\", 56))\n+ assert \"2020-09-17T12:34:56Z\" == rfc3339.datetime([2020, \"09\", 17, \"12\", \"34\", 56])\n+ assert \"2020-09-17T12:34:56Z\" == rfc3339.datetime(2020, \"09\", \"17\", \"12\", \"34\", 56)\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=None))\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=dt.timezone.utc))\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=dateutil.tz.UTC))\n assert \"2020-03-17T12:34:56Z\" == rfc3339.datetime(\n dt.datetime(\n *(2020, 3, 17, 12, 34, 56),\n@@ -125,15 +117,10 @@ class TestRfc3339:\n \"2020-03-17T12:34:56.44546546Z\"\n )\n assert \"2020-03-17\" == rfc3339.normalize(dt.date(2020, 3, 17))\n- assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(\n- dt.datetime(2020, 3, 17, 12, 34, 56)\n- )\n- assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(\n- dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=None)\n- )\n- assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(\n- dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=dt.timezone.utc)\n- )\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(dt.datetime(2020, 3, 17, 12, 34, 56))\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=None))\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=dt.timezone.utc))\n+ assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(dt.datetime(2020, 3, 17, 12, 34, 56, tzinfo=dateutil.tz.UTC))\n assert \"2020-03-17T12:34:56Z\" == rfc3339.normalize(\n dt.datetime(\n *(2020, 3, 17, 12, 34, 56),\n", "FAIL_TO_PASS": ["tests/rest/test_connection.py::TestLoadStac::test_load_stac_no_cube_extension_temporal_dimension[collection_extent0-dim_extent0]", "tests/rest/test_connection.py::TestLoadStac::test_load_stac_no_cube_extension_temporal_dimension[collection_extent1-dim_extent1]", "tests/rest/test_connection.py::TestLoadStac::test_load_stac_band_filtering", "tests/test_metadata.py::test_metadata_from_stac_temporal_dimension[stac_dict3-expected3]", "tests/test_util.py::TestRfc3339::test_datetime", "tests/test_util.py::TestRfc3339::test_normalize"]}], "all_FAIL_TO_PASS": ["tests/rest/test_connection.py::TestLoadStac::test_load_stac_no_cube_extension_temporal_dimension[collection_extent0-dim_extent0]", "tests/rest/test_connection.py::TestLoadStac::test_load_stac_no_cube_extension_temporal_dimension[collection_extent1-dim_extent1]", "tests/rest/test_connection.py::TestLoadStac::test_load_stac_band_filtering", "tests/test_metadata.py::test_metadata_from_stac_temporal_dimension[stac_dict3-expected3]", "tests/test_util.py::TestRfc3339::test_datetime", "tests/test_util.py::TestRfc3339::test_normalize"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Parquery__swagger-to-141_x1", "level": 1, "source": "swerebench", "repo": "Parquery/swagger-to", "image": "swerebench/sweb.eval.x86_64.parquery_1776_swagger-to-141:latest", "base_commit": "d0427c9f56e0a30a04e0777eb874954c99f1c90a", "num_bugs": 1, "bugs": [{"instance_id": "Parquery__swagger-to-141", "base_commit": "d0427c9f56e0a30a04e0777eb874954c99f1c90a", "gold_patch": "diff --git a/swagger_to/intermediate.py b/swagger_to/intermediate.py\nindex c4dc496..8a26b91 100644\n--- a/swagger_to/intermediate.py\n+++ b/swagger_to/intermediate.py\n@@ -432,12 +432,7 @@ def _recursively_strip_descriptions(schema_dict: MutableMapping[str, Any]) -> Mu\n new_schema_dict = collections.OrderedDict() # type: MutableMapping[str, Any]\n \n for key, value in schema_dict.items():\n- if key.lower() == 'description':\n- if not isinstance(value, str):\n- raise ValueError(\"Expected the value in a schema to be a string, but got: {}\".format(type(value)))\n-\n- new_schema_dict[key] = value.strip()\n- elif isinstance(value, list):\n+ if isinstance(value, list):\n lst = [] # type: List[Any]\n for item in value:\n if isinstance(item, (dict, collections.OrderedDict)):\n@@ -451,6 +446,11 @@ def _recursively_strip_descriptions(schema_dict: MutableMapping[str, Any]) -> Mu\n new_schema_dict[key] = _recursively_strip_descriptions(schema_dict=value)\n elif isinstance(value, swagger_to.swagger.RawDict):\n new_schema_dict[key] = _recursively_strip_descriptions(schema_dict=value)\n+ elif key.lower() == 'description':\n+ if not isinstance(value, str):\n+ raise ValueError(\"Expected the value in a schema to be a string, but got: {}\".format(type(value)))\n+\n+ new_schema_dict[key] = value.strip()\n else:\n new_schema_dict[key] = value\n \n", "test_patch": "diff --git a/tests/cases/intermediate/definitions_item_description_as_object/endpoints.json b/tests/cases/intermediate/definitions_item_description_as_object/endpoints.json\nnew file mode 100644\nindex 0000000..1298ed4\n--- /dev/null\n+++ b/tests/cases/intermediate/definitions_item_description_as_object/endpoints.json\n@@ -0,0 +1,44 @@\n+[\n+ {\n+ \"consumes\": [],\n+ \"description\": \"\",\n+ \"line\": 14,\n+ \"method\": \"get\",\n+ \"operation_id\": \"get_foo\",\n+ \"parameters\": [\n+ {\n+ \"description\": \"The foo id\",\n+ \"in_what\": \"path\",\n+ \"json_schema\": {\n+ \"identifier\": \"\",\n+ \"text\": \"\"\n+ },\n+ \"line\": 21,\n+ \"name\": \"foo_id\",\n+ \"required\": true,\n+ \"typedef\": {\n+ \"description\": \"\",\n+ \"format\": \"\",\n+ \"identifier\": \"\",\n+ \"json_schema\": {\n+ \"identifier\": \"\",\n+ \"text\": \"\"\n+ },\n+ \"line\": 0,\n+ \"pattern\": \"\",\n+ \"type\": \"string\"\n+ }\n+ }\n+ ],\n+ \"path\": \"/api/v1/foo\",\n+ \"produces\": [],\n+ \"responses\": {\n+ \"200\": {\n+ \"code\": \"200\",\n+ \"description\": \"Success\",\n+ \"line\": 17,\n+ \"typedef\": null\n+ }\n+ }\n+ }\n+]\n\\ No newline at end of file\ndiff --git a/tests/cases/intermediate/definitions_item_description_as_object/intermediate_params.json b/tests/cases/intermediate/definitions_item_description_as_object/intermediate_params.json\nnew file mode 100644\nindex 0000000..9e26dfe\n--- /dev/null\n+++ b/tests/cases/intermediate/definitions_item_description_as_object/intermediate_params.json\n@@ -0,0 +1,1 @@\n+{}\n\\ No newline at end of file\ndiff --git a/tests/cases/intermediate/definitions_item_description_as_object/intermediate_typedefs.json b/tests/cases/intermediate/definitions_item_description_as_object/intermediate_typedefs.json\nnew file mode 100644\nindex 0000000..0228d9e\n--- /dev/null\n+++ b/tests/cases/intermediate/definitions_item_description_as_object/intermediate_typedefs.json\n@@ -0,0 +1,65 @@\n+{\n+ \"foo\": {\n+ \"description\": \"\",\n+ \"identifier\": \"foo\",\n+ \"json_schema\": {\n+ \"identifier\": \"foo\",\n+ \"text\": \"{\\n \\\"title\\\": \\\"foo\\\",\\n \\\"$schema\\\": \\\"http://json-schema.org/draft-04/schema#\\\",\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"id\\\": {\\n \\\"description\\\": \\\"Identifier\\\"\\n },\\n \\\"name\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"example\\\": \\\"TestJob\\\",\\n \\\"description\\\": \\\"Name of the test.\\\"\\n },\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"example\\\": \\\"TestJob\\\",\\n \\\"description\\\": \\\"Test description.\\\"\\n }\\n }\\n}\"\n+ },\n+ \"line\": 28,\n+ \"properties\": {\n+ \"id\": {\n+ \"description\": \"Identifier\",\n+ \"line\": 0,\n+ \"name\": \"id\",\n+ \"required\": false,\n+ \"typedef\": {\n+ \"description\": \"\",\n+ \"identifier\": \"\",\n+ \"json_schema\": {\n+ \"identifier\": \"\",\n+ \"text\": \"\"\n+ },\n+ \"line\": 31\n+ }\n+ },\n+ \"name\": {\n+ \"description\": \"Name of the test.\",\n+ \"line\": 0,\n+ \"name\": \"name\",\n+ \"required\": false,\n+ \"typedef\": {\n+ \"description\": \"\",\n+ \"format\": null,\n+ \"identifier\": \"\",\n+ \"json_schema\": {\n+ \"identifier\": \"\",\n+ \"text\": \"\"\n+ },\n+ \"line\": 33,\n+ \"pattern\": \"\",\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"description\": {\n+ \"description\": \"Test description.\",\n+ \"line\": 0,\n+ \"name\": \"description\",\n+ \"required\": false,\n+ \"typedef\": {\n+ \"description\": \"\",\n+ \"format\": null,\n+ \"identifier\": \"\",\n+ \"json_schema\": {\n+ \"identifier\": \"\",\n+ \"text\": \"\"\n+ },\n+ \"line\": 37,\n+ \"pattern\": \"\",\n+ \"type\": \"string\"\n+ }\n+ }\n+ },\n+ \"required\": []\n+ }\n+}\n\\ No newline at end of file\ndiff --git a/tests/cases/intermediate/definitions_item_description_as_object/swagger.yaml b/tests/cases/intermediate/definitions_item_description_as_object/swagger.yaml\nnew file mode 100644\nindex 0000000..0d77584\n--- /dev/null\n+++ b/tests/cases/intermediate/definitions_item_description_as_object/swagger.yaml\n@@ -0,0 +1,40 @@\n+# This is a valid schema, but the definition...->description object broke swagger-to.\n+# Test relates to: https://github.com/Parquery/swagger-to/issues/132\n+swagger: '2.0'\n+info:\n+ description: description\n+ version: '1.0'\n+ title: An API\n+basePath: /api/v1\n+tags:\n+- name: foo\n+ description: description\n+paths:\n+ /foo:\n+ get:\n+ operationId: get_foo\n+ responses:\n+ '200':\n+ description: Success\n+ tags:\n+ - foo\n+ parameters:\n+ - in: path\n+ description: The foo id\n+ name: foo_id\n+ required: true\n+ type: string\n+definitions:\n+ foo:\n+ type: object\n+ properties:\n+ id:\n+ description: Identifier\n+ name:\n+ type: string\n+ example: TestJob\n+ description: Name of the test.\n+ description:\n+ type: string\n+ example: TestJob\n+ description: Test description.\n\\ No newline at end of file\ndiff --git a/tests/cases/parsing/info_description_not_string/errors.txt b/tests/cases/parsing/info_description_not_string/errors.txt\nnew file mode 100644\nindex 0000000..e5878bd\n--- /dev/null\n+++ b/tests/cases/parsing/info_description_not_string/errors.txt\n@@ -0,0 +1,11 @@\n+\"info\"/\"description\":RawDict([('name', 'This is expected to fail!')]) is not of type 'string'\n+\n+Failed validating 'type' in schema['properties']['info']['properties']['description']:\n+ {'description': 'A longer description of the API. Should be different '\n+ 'from the title. GitHub Flavored Markdown is allowed.',\n+ 'type': 'string'}\n+\n+On instance['info']['description']:\n+ RawDict([('name', 'This is expected to fail!')])\n+\n+We used the JSON schema of OpenAPI 2 from: https://raw.githubusercontent.com/OAI/OpenAPI-Specification/88cd94419e117b154b67b834fa8e471bb98bd346/schemas/v2.0/schema.json\n\\ No newline at end of file\ndiff --git a/tests/cases/parsing/info_description_not_string/swagger.yaml b/tests/cases/parsing/info_description_not_string/swagger.yaml\nnew file mode 100644\nindex 0000000..20ba39f\n--- /dev/null\n+++ b/tests/cases/parsing/info_description_not_string/swagger.yaml\n@@ -0,0 +1,28 @@\n+# This is invalid schema...\n+# It confirms the validator fails at a \"description\" element that MUST be a string.\n+# Test relates to: https://github.com/Parquery/swagger-to/issues/132\n+swagger: '2.0'\n+info:\n+ description:\n+ name: This is expected to fail!\n+ version: '1.0'\n+ title: An API\n+basePath: /api/v1\n+tags:\n+- name: foo\n+ description: description\n+paths:\n+ /foo:\n+ get:\n+ operationId: get_foo\n+ responses:\n+ '200':\n+ description: Success\n+ tags:\n+ - foo\n+ parameters:\n+ - in: path\n+ description: The foo id\n+ name: foo_id\n+ required: true\n+ type: string\n\\ No newline at end of file\n", "FAIL_TO_PASS": ["tests/test_intermediate.py::TestIntermediate::test_that_it_does_not_break"]}], "all_FAIL_TO_PASS": ["tests/test_intermediate.py::TestIntermediate::test_that_it_does_not_break"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PaulSchweizer__flowpipe-127_x1", "level": 1, "source": "swerebench", "repo": "PaulSchweizer/flowpipe", "image": "swerebench/sweb.eval.x86_64.paulschweizer_1776_flowpipe-127:latest", "base_commit": "06cade8408791fde0ab422c19d5d8e73facbc234", "num_bugs": 1, "bugs": [{"instance_id": "PaulSchweizer__flowpipe-127", "base_commit": "06cade8408791fde0ab422c19d5d8e73facbc234", "gold_patch": "diff --git a/flowpipe/node.py b/flowpipe/node.py\nindex 7fc825d..a9671e9 100644\n--- a/flowpipe/node.py\n+++ b/flowpipe/node.py\n@@ -436,8 +436,13 @@ class FunctionNode(INode):\n metadata = copy.deepcopy(self.metadata)\n metadata.update(kwargs.pop(\"metadata\", {}))\n graph = kwargs.pop('graph', 'default')\n+ outputs = []\n+ for o in self.outputs.values():\n+ outputs.append(o.name)\n+ for key in o._sub_plugs.keys():\n+ outputs.append(\"{0}.{1}\".format(o.name, key))\n return self.__class__(func=self.func,\n- outputs=[o for o in self.outputs],\n+ outputs=outputs,\n metadata=metadata,\n graph=graph,\n **kwargs)\n@@ -511,7 +516,15 @@ class FunctionNode(INode):\n \n if outputs is not None:\n for output in outputs:\n- OutputPlug(output, self)\n+ if \".\" in output:\n+ parent, subplug = output.split(\".\")\n+ parent_plug = self.outputs.get(parent)\n+ if parent_plug is None:\n+ parent_plug = OutputPlug(parent, self)\n+ SubOutputPlug(subplug, self, parent_plug)\n+ else:\n+ if self.outputs.get(output) is None:\n+ OutputPlug(output, self)\n \n def to_pickle(self): # pragma: no cover\n \"\"\"Pickle the node. -- DOES NOT WORK FOR FunctionNode.\"\"\"\ndiff --git a/flowpipe/plug.py b/flowpipe/plug.py\nindex b58e4c6..85e6f65 100644\n--- a/flowpipe/plug.py\n+++ b/flowpipe/plug.py\n@@ -303,6 +303,7 @@ class SubInputPlug(IPlug):\n (OutputPlug, SubOutputPlug))\n self.key = key\n self.parent_plug = parent_plug\n+ self.parent_plug._sub_plugs[key] = self\n self.value = value\n self.is_dirty = True\n \n@@ -362,6 +363,7 @@ class SubOutputPlug(IPlug):\n (InputPlug, SubInputPlug))\n self.key = key\n self.parent_plug = parent_plug\n+ self.parent_plug._sub_plugs[key] = self\n self.value = value\n self.is_dirty = True\n \n", "test_patch": "diff --git a/tests/test_convert_function_to_node.py b/tests/test_convert_function_to_node.py\nindex 2d84466..e99a8dc 100644\n--- a/tests/test_convert_function_to_node.py\n+++ b/tests/test_convert_function_to_node.py\n@@ -182,3 +182,20 @@ def test_node_reserved_names():\n def function(func, name, identifier, inputs,\n outputs, metadata, omit, graph):\n pass\n+\n+\n+def test_create_node_with_sub_output_plugs():\n+\n+ @Node(outputs=[\"out.a\", \"out\", \"out.b\"])\n+ def function1(in_):\n+ pass\n+\n+ node = function1(name=\"contains_all_plugs\")\n+ assert len(node.outputs[\"out\"]._sub_plugs) == 2\n+\n+ @Node(outputs=[\"out.a\", \"out.b\"])\n+ def function2(in_):\n+ pass\n+\n+ node = function2(name=\"contains_only_subplugs\")\n+ assert len(node.outputs[\"out\"]._sub_plugs) == 2\n", "FAIL_TO_PASS": ["tests/test_convert_function_to_node.py::test_create_node_with_sub_output_plugs"]}], "all_FAIL_TO_PASS": ["tests/test_convert_function_to_node.py::test_create_node_with_sub_output_plugs"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Shoobx__xmldiff-117_x1", "level": 1, "source": "swerebench", "repo": "Shoobx/xmldiff", "image": "swerebench/sweb.eval.x86_64.shoobx_1776_xmldiff-117:latest", "base_commit": "8cb3fe009a1b2349499f2dcebd4752fcaed31ffc", "num_bugs": 1, "bugs": [{"instance_id": "Shoobx__xmldiff-117", "base_commit": "8cb3fe009a1b2349499f2dcebd4752fcaed31ffc", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex c35c7e7..88b864e 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -4,13 +4,13 @@ Changes\n 2.6.3 (unreleased)\n ------------------\n \n-- Nothing changed yet.\n+- And there was a namespace bug in the patch as well. #118\n \n \n 2.6.2 (2023-05-21)\n ------------------\n \n-- Solved an error in the xmlformatter when using default namespaces. #89, #113\n+- Solved an error in the xmlformatter when using default namespaces. #89\n \n \n 2.6.1 (2023-04-05)\ndiff --git a/xmldiff/patch.py b/xmldiff/patch.py\nindex d052db3..49eb35b 100644\n--- a/xmldiff/patch.py\n+++ b/xmldiff/patch.py\n@@ -16,6 +16,8 @@ class Patcher:\n \n # Save the namespace:\n self._nsmap = tree.nsmap\n+ if None in self._nsmap:\n+ del self._nsmap[None]\n \n # Copy the tree so we don't modify the original\n result = deepcopy(tree)\n", "test_patch": "diff --git a/tests/test_patch.py b/tests/test_patch.py\nindex 670167e..62ff76e 100644\n--- a/tests/test_patch.py\n+++ b/tests/test_patch.py\n@@ -121,6 +121,21 @@ class DiffPatch(unittest.TestCase):\n # top level comment differs, but that's OK.\n compare_elements(result, right.getroot())\n \n+ def test_diff_default_namespace(self):\n+ here = os.path.split(__file__)[0]\n+ lfile = os.path.join(here, \"test_data\", \"namespace.left.xml\")\n+ rfile = os.path.join(here, \"test_data\", \"namespace.right.xml\")\n+\n+ left = etree.parse(lfile)\n+ right = etree.parse(rfile)\n+ diff = diff_trees(left, right)\n+ result = Patcher().patch(diff, left)\n+\n+ # This example has top level comments, and lxml doesn't deal well\n+ # with that, so the trees are not EXACTLY the same, the trailing\n+ # top level comment differs, but that's OK.\n+ compare_elements(result, right.getroot())\n+\n \n TEST_DIFF = \"\"\"[delete, node]\n [insert, target, tag, 0]\n", "FAIL_TO_PASS": ["tests/test_patch.py::DiffPatch::test_diff_default_namespace"]}], "all_FAIL_TO_PASS": ["tests/test_patch.py::DiffPatch::test_diff_default_namespace"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Azure__pykusto-159_x1", "level": 1, "source": "swerebench", "repo": "Azure/pykusto", "image": "swerebench/sweb.eval.x86_64.azure_1776_pykusto-159:latest", "base_commit": "68121cdd79cc9c1d6b8f71e5e80df566ac6842c7", "num_bugs": 1, "bugs": [{"instance_id": "Azure__pykusto-159", "base_commit": "68121cdd79cc9c1d6b8f71e5e80df566ac6842c7", "gold_patch": "diff --git a/pykusto/_src/client.py b/pykusto/_src/client.py\nindex 66c39f6..d18fa82 100644\n--- a/pykusto/_src/client.py\n+++ b/pykusto/_src/client.py\n@@ -371,7 +371,7 @@ class Table(_ItemFetcher):\n return KQL(table_names[0])\n \n def execute(self, query: KQL, retry_config: RetryConfig = None) -> KustoResponse:\n- return self.__database.execute(query, retry_config)\n+ return self.__database.execute(query, retry_config=retry_config)\n \n def get_columns_names(self) -> Generator[str, None, None]:\n yield from self._get_item_names()\n", "test_patch": "diff --git a/test/test_client.py b/test/test_client.py\nindex 5fc05c2..930e81e 100644\n--- a/test/test_client.py\n+++ b/test/test_client.py\n@@ -222,3 +222,28 @@ class TestClient(TestBase):\n KustoError(\"Mock exception for test\", None),\n lambda: Query(table).take(5).execute(),\n )\n+\n+ def test_override_retry_config_for_query(self):\n+ num_retries = 2\n+ num_failed_attempts = num_retries - 1\n+ retry_sleep_time = 0.1\n+\n+ mock_kusto_client = self.unreliable_mock_kusto_client(num_failed_attempts)\n+ table = PyKustoClient(mock_kusto_client, fetch_by_default=False)['test_db']['mock_table']\n+ retry_config = RetryConfig(num_retries, sleep_time=retry_sleep_time, jitter=0)\n+\n+ with self.assertLogs(_logger, logging.INFO) as cm:\n+ Query(table).take(5).execute(retry_config=retry_config)\n+\n+ self.assertEqual(\n+ [RecordedQuery('test_db', 'mock_table | take 5')] * num_retries,\n+ mock_kusto_client.recorded_queries\n+ )\n+ self.assertEqual(\n+ [\n+ f\"INFO:pykusto:Attempt number {num_failed_attempts} out of {num_retries} failed, \"\n+ f\"previous sleep time was {retry_sleep_time} seconds. \"\n+ f\"Exception: KustoServiceError('Mock exception for test')\"\n+ ],\n+ cm.output\n+ )\n", "FAIL_TO_PASS": ["test/test_client.py::TestClient::test_override_retry_config_for_query"]}], "all_FAIL_TO_PASS": ["test/test_client.py::TestClient::test_override_retry_config_for_query"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "BrandwatchLtd__api_sdk-62_x1", "level": 1, "source": "swerebench", "repo": "BrandwatchLtd/api_sdk", "image": "swerebench/sweb.eval.x86_64.brandwatchltd_1776_api_sdk-62:latest", "base_commit": "0570363bdee1621b85f8290599e0c86c75bcf802", "num_bugs": 1, "bugs": [{"instance_id": "BrandwatchLtd__api_sdk-62", "base_commit": "0570363bdee1621b85f8290599e0c86c75bcf802", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\ndeleted file mode 100644\nindex b33d109..0000000\n--- a/.travis.yml\n+++ /dev/null\n@@ -1,24 +0,0 @@\n-language: python\n-\n-matrix:\n- include:\n- - python: 3.3\n- - python: 3.4\n- - python: 3.5\n- - python: 3.6\n- - python: 3.7\n- dist: xenial\n- sudo: true\n- - python: 3.7-dev\n- dist: xenial\n- sudo: true\n- - python: 3.8-dev\n- dist: xenial\n- sudo: true\n-\n-install:\n- - python setup.py install\n-\n-script:\n- - python setup.py test\n-\ndiff --git a/README.md b/README.md\nindex 7084960..15c6827 100644\n--- a/README.md\n+++ b/README.md\n@@ -1,5 +1,3 @@\n-[![Build Status](https://travis-ci.com/BrandwatchLtd/api_sdk.svg?branch=master)](https://travis-ci.com/BrandwatchLtd/api_sdk)\n-\n # Brandwatch API SDK\n \n ## Introduction\ndiff --git a/bwproject.py b/bwproject.py\nindex c879cae..3a41d39 100644\n--- a/bwproject.py\n+++ b/bwproject.py\n@@ -59,7 +59,7 @@ class BWUser:\n if \"username\" in user:\n if username is None:\n return user[\"username\"], token\n- elif user[\"username\"] == username:\n+ elif user[\"username\"].lower() == username.lower():\n return username, token\n else:\n raise KeyError(\"Username \" + username + \" does not match provided token\", user)\n@@ -84,8 +84,8 @@ class BWUser:\n \n def _read_auth(self, username, token_path):\n user_tokens = self._read_auth_file(token_path)\n- if username in user_tokens:\n- return self._test_auth(username, user_tokens[username])\n+ if username.lower() in user_tokens:\n+ return self._test_auth(username, user_tokens[username.lower()])\n else:\n raise KeyError(\"Token not found in file: \" + token_path)\n \ndiff --git a/setup.py b/setup.py\nindex 9c1d705..56c9ab2 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -23,15 +23,16 @@ setup(\n 'License :: OSI Approved :: MIT License',\n \n 'Programming Language :: Python :: 3',\n+ 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n- 'Programming Language :: Python :: 3.5',\n- 'Programming Language :: Python :: 3.6',\n- 'Programming Language :: Python :: 3.7'\n+ 'Programming Language :: Python :: 3.5'\n ],\n \n py_modules=['bwproject', 'bwresources', 'bwdata', 'filters'],\n \n- install_requires=['requests']\n+ install_requires=['requests'],\n+\n+ tests_require=['responses']\n \n )\n", "test_patch": "diff --git a/test/__init__.py b/test/__init__.py\nnew file mode 100644\nindex 0000000..e69de29\ndiff --git a/test/test_bwproject.py b/test/test_bwproject.py\nnew file mode 100644\nindex 0000000..4820262\n--- /dev/null\n+++ b/test/test_bwproject.py\n@@ -0,0 +1,69 @@\n+import unittest\n+import responses\n+import os\n+import tempfile\n+\n+from bwproject import BWProject\n+\n+\n+class TestBWProjectUsernameCaseSensitivity(unittest.TestCase):\n+\n+ USERNAME = \"example@Example.com\"\n+ ACCESS_TOKEN = \"00000000-0000-0000-0000-000000000000\"\n+ PROJECT_NAME = \"Example project\"\n+ PROJECTS = [\n+ {\n+ \"id\": 0,\n+ \"name\": PROJECT_NAME,\n+ \"description\": \"\",\n+ \"billableClientId\": 0,\n+ \"billableClientName\": \"My company\",\n+ \"timezone\": \"Africa/Abidjan\",\n+ \"billableClientIsPitch\": False\n+ }\n+ ]\n+\n+ def setUp(self):\n+ self.token_path = tempfile.NamedTemporaryFile(suffix='-tokens.txt').name\n+\n+ responses.add(responses.GET, 'https://api.brandwatch.com/projects',\n+ json={\n+ \"resultsTotal\": len(self.PROJECTS),\n+ \"resultsPage\": -1,\n+ \"resultsPageSize\": -1,\n+ \"results\": self.PROJECTS\n+ }, status=200)\n+\n+ responses.add(responses.POST, 'https://api.brandwatch.com/oauth/token',\n+ json={'access_token': self.ACCESS_TOKEN}, status=200)\n+\n+ def tearDown(self):\n+ os.unlink(self.token_path)\n+ responses.reset()\n+\n+\n+ @responses.activate\n+ def test_lowercase_username(self):\n+ self._test_username(\"example@example.com\")\n+\n+ @responses.activate\n+ def test_uppercase_username(self):\n+ self._test_username(\"EXAMPLE@EXAMPLE.COM\")\n+\n+ @responses.activate\n+ def test_mixedcase_username(self):\n+ self._test_username(\"eXaMpLe@ExAmPlE.cOm\")\n+\n+ def _test_username(self, username):\n+\n+ responses.add(responses.GET, 'https://api.brandwatch.com/me', json={\"username\": username}, status=200)\n+\n+ BWProject(username=username, project=self.PROJECT_NAME, password=\"\", token_path=self.token_path)\n+ try:\n+ BWProject(username=username, project=self.PROJECT_NAME, token_path=self.token_path)\n+ except KeyError as e:\n+ self.fail(e)\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\n", "FAIL_TO_PASS": ["test/test_bwproject.py::TestBWProjectUsernameCaseSensitivity::test_mixedcase_username", "test/test_bwproject.py::TestBWProjectUsernameCaseSensitivity::test_uppercase_username"]}], "all_FAIL_TO_PASS": ["test/test_bwproject.py::TestBWProjectUsernameCaseSensitivity::test_mixedcase_username", "test/test_bwproject.py::TestBWProjectUsernameCaseSensitivity::test_uppercase_username"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Netflix-Skunkworks__policyuniverse-147_x1", "level": 1, "source": "swerebench", "repo": "Netflix-Skunkworks/policyuniverse", "image": "swerebench/sweb.eval.x86_64.netflix-skunkworks_1776_policyuniverse-147:latest", "base_commit": "96336a5c51f0daa5cc832050b5668cd9a326e6cc", "num_bugs": 1, "bugs": [{"instance_id": "Netflix-Skunkworks__policyuniverse-147", "base_commit": "96336a5c51f0daa5cc832050b5668cd9a326e6cc", "gold_patch": "diff --git a/policyuniverse/__init__.py b/policyuniverse/__init__.py\nindex f442d13..e63a96b 100644\n--- a/policyuniverse/__init__.py\n+++ b/policyuniverse/__init__.py\n@@ -13,7 +13,6 @@ from policyuniverse.action import build_service_actions_from_service_data\n \n \n # Logging\n-logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger(__name__)\n \n # Read Input Data\ndiff --git a/policyuniverse/arn.py b/policyuniverse/arn.py\nindex 61a4e97..9aa07d6 100644\n--- a/policyuniverse/arn.py\n+++ b/policyuniverse/arn.py\n@@ -35,46 +35,46 @@ class ARN(object):\n root = False\n service = False\n \n- def __init__(self, input):\n- self.arn = input\n+ def __init__(self, raw):\n+ self.arn = raw\n arn_match = re.search(\n- r\"^arn:([^:]*):([^:]*):([^:]*):(|\\*|[\\d]{12}|cloudfront|aws):(.+)$\", input\n+ r\"^arn:([^:]*):([^:]*):([^:]*):(|\\*|[\\d]{12}|cloudfront|aws):(.+)$\", raw\n )\n if arn_match:\n if arn_match.group(2) == \"iam\" and arn_match.group(5) == \"root\":\n self.root = True\n \n- self._from_arn(arn_match, input)\n+ self._from_arn(arn_match)\n return\n \n- acct_number_match = re.search(r\"^(\\d{12})+$\", input)\n+ acct_number_match = re.search(r\"^(\\d{12})+$\", raw)\n if acct_number_match:\n- self._from_account_number(input)\n+ self._from_account_number(raw)\n return\n \n- aws_service_match = re.search(r\"^(([^.]+)(.[^.]+)?)\\.amazon(aws)?\\.com$\", input)\n+ aws_service_match = re.search(r\"^(([^.]+)(.[^.]+)?)\\.amazon(aws)?\\.com$\", raw)\n if aws_service_match:\n- self._from_aws_service(input, aws_service_match.group(1))\n+ self._from_aws_service(aws_service_match.group(1))\n return\n \n- aws_service_match = re.search(r\"^([^.]+).aws.internal$\", input)\n+ aws_service_match = re.search(r\"^([^.]+).aws.internal$\", raw)\n if aws_service_match:\n- self._from_aws_service(input, aws_service_match.group(1))\n+ self._from_aws_service(aws_service_match.group(1))\n return\n \n self.error = True\n- logger.warning(\"ARN Could not parse [{}].\".format(input))\n+ logger.debug(\"ARN Could not parse [{}].\".format(raw))\n \n- def _from_arn(self, arn_match, input):\n+ def _from_arn(self, arn_match):\n self.partition = arn_match.group(1)\n self.tech = arn_match.group(2)\n self.region = arn_match.group(3)\n self.account_number = arn_match.group(4)\n self.name = arn_match.group(5)\n \n- def _from_account_number(self, input):\n- self.account_number = input\n+ def _from_account_number(self, raw):\n+ self.account_number = raw\n \n- def _from_aws_service(self, input, service):\n+ def _from_aws_service(self, service):\n self.tech = service\n self.service = True\ndiff --git a/policyuniverse/organization.py b/policyuniverse/organization.py\nindex de96c9e..ea625ab 100644\n--- a/policyuniverse/organization.py\n+++ b/policyuniverse/organization.py\n@@ -52,19 +52,19 @@ class Organization(object):\n self.organization = orgid\n else:\n self.error = True\n- logger.warning(\"Organization Org ID parse error [{}].\".format(input))\n+ logger.debug(\"Organization Org ID parse error [{}].\".format(input))\n \n def _parse_root(self, root):\n if root.startswith(\"r-\") or root == \"*\":\n self.root = root\n else:\n self.error = True\n- logger.warning(\"Organization root parse error [{}].\".format(input))\n+ logger.debug(\"Organization root parse error [{}].\".format(input))\n \n def _parse_ou_path(self, ou):\n if self.valid_for_parent_ou or self.valid_for_child_ous:\n self.error = True\n- logger.warning(\"Organization OU validity error [{}].\".format(input))\n+ logger.debug(\"Organization OU validity error [{}].\".format(input))\n return\n \n if not ou:\n@@ -81,4 +81,4 @@ class Organization(object):\n self.ou_path.append(ou)\n else:\n self.error = True\n- logger.warning(\"Organization OU parse error [{}].\".format(input))\n+ logger.debug(\"Organization OU parse error [{}].\".format(input))\ndiff --git a/policyuniverse/statement.py b/policyuniverse/statement.py\nindex be8430c..f456a36 100644\n--- a/policyuniverse/statement.py\n+++ b/policyuniverse/statement.py\n@@ -322,7 +322,8 @@ class Statement(object):\n def _userid_internet_accessible(self, userid):\n # Trailing wildcards are okay for userids:\n # AROAIIIIIIIIIIIIIIIII:*\n- if userid.index(\"*\") == len(userid) - 1:\n+ if userid.find(\"*\") == len(userid) - 1:\n+ # note: this will also return False for a zero-length userid\n return False\n return True\n \n@@ -332,7 +333,7 @@ class Statement(object):\n \n arn = ARN(arn_input)\n if arn.error:\n- logger.warning(\"Auditor could not parse ARN {arn}.\".format(arn=arn_input))\n+ logger.debug(\"Auditor could not parse ARN {arn}.\".format(arn=arn_input))\n return \"*\" in arn_input\n \n if arn.tech == \"s3\":\n@@ -340,7 +341,7 @@ class Statement(object):\n return False\n \n if not arn.account_number and not arn.service:\n- logger.warning(\n+ logger.debug(\n \"Auditor could not parse Account Number from ARN {arn}.\".format(\n arn=arn_input\n )\n@@ -355,7 +356,7 @@ class Statement(object):\n def _organization_internet_accessible(self, org_input):\n organization = Organization(org_input)\n if organization.error:\n- logger.warning(\"Auditor could not parse Org {org}.\".format(org=org_input))\n+ logger.debug(\"Auditor could not parse Org {org}.\".format(org=org_input))\n return \"o-*\" in org_input\n \n if organization.organization == \"o-*\":\n", "test_patch": "diff --git a/policyuniverse/tests/__init__.py b/policyuniverse/tests/__init__.py\nindex e69de29..ca0e42e 100644\n--- a/policyuniverse/tests/__init__.py\n+++ b/policyuniverse/tests/__init__.py\n@@ -0,0 +1,3 @@\n+import logging\n+\n+logging.basicConfig(level=logging.INFO)\ndiff --git a/policyuniverse/tests/test_statement.py b/policyuniverse/tests/test_statement.py\nindex b55ecb4..cda547b 100644\n--- a/policyuniverse/tests/test_statement.py\n+++ b/policyuniverse/tests/test_statement.py\n@@ -396,6 +396,15 @@ statement35 = dict(\n },\n )\n \n+# AWS:userid with no *\n+statement36 = dict(\n+ Effect=\"Allow\",\n+ Principal=\"*\",\n+ Action=[\"rds:*\"],\n+ Resource=\"*\",\n+ Condition={\"StringLike\": {\"AWS:userid\": \"AROAI1111111111111111:\"}},\n+)\n+\n \n class StatementTestCase(unittest.TestCase):\n def test_statement_effect(self):\n@@ -596,3 +605,6 @@ class StatementTestCase(unittest.TestCase):\n \n # AWS:PrincipalOrgPath Wildcard\n self.assertTrue(Statement(statement35).is_internet_accessible())\n+\n+ # AWS:userid with no *\n+ self.assertTrue(Statement(statement36).is_internet_accessible())\n", "FAIL_TO_PASS": ["policyuniverse/tests/test_statement.py::StatementTestCase::test_statement_internet_accessible"]}], "all_FAIL_TO_PASS": ["policyuniverse/tests/test_statement.py::StatementTestCase::test_statement_internet_accessible"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ShawHahnLab__igseq-12_x1", "level": 1, "source": "swerebench", "repo": "ShawHahnLab/igseq", "image": "swerebench/sweb.eval.x86_64.shawhahnlab_1776_igseq-12:latest", "base_commit": "1280f70936a87dc47a557ea0603dff0e5c367a2c", "num_bugs": 1, "bugs": [{"instance_id": "ShawHahnLab__igseq-12", "base_commit": "1280f70936a87dc47a557ea0603dff0e5c367a2c", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex cd2aeb6..7aebd00 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -1,6 +1,6 @@\n # Changelog\n \n-## 0.1.1 - 2021-12-06\n+## 0.1.1 - 2021-12-07\n \n ### Changed\n \n@@ -8,6 +8,7 @@\n \n ### Fixed\n \n+ * IgBLAST output is now shown even if it crashes ([#12])\n * Header-only CSV/TSV files no longer crash the show command ([#8])\n * summarize command now works with multiple references ([#7])\n * vdj-match and summarize commands now work as intended via igblast, and all\n@@ -17,6 +18,7 @@\n * Duplicate FASTA paths found in vdj-gather will no longer result in\n duplicated output sequences ([#2])\n \n+[#12]: https://github.com/ShawHahnLab/igseq/pull/12\n [#8]: https://github.com/ShawHahnLab/igseq/pull/8\n [#7]: https://github.com/ShawHahnLab/igseq/pull/7\n [#5]: https://github.com/ShawHahnLab/igseq/pull/5\ndiff --git a/igseq/igblast.py b/igseq/igblast.py\nindex 907f130..23236d2 100644\n--- a/igseq/igblast.py\n+++ b/igseq/igblast.py\n@@ -69,10 +69,15 @@ def igblast(\n species_det = {s for s in species_det if s}\n organism = detect_organism(species_det, species)\n if not dry_run:\n- proc, _ = setup_db_dir_and_igblast(\n- [attrs[\"path\"] for attrs in attrs_list],\n- organism, query_path, db_path, threads, extra_args,\n- capture_output=True, text=True, check=True)\n+ try:\n+ proc, _ = setup_db_dir_and_igblast(\n+ [attrs[\"path\"] for attrs in attrs_list],\n+ organism, query_path, db_path, threads, extra_args,\n+ capture_output=True, text=True, check=True)\n+ except subprocess.CalledProcessError as err:\n+ sys.stdout.write(err.stdout)\n+ sys.stderr.write(err.stderr)\n+ raise util.IgSeqError(\"IgBLAST crashed\") from err\n sys.stdout.write(proc.stdout)\n sys.stderr.write(proc.stderr)\n \n", "test_patch": "diff --git a/test_igseq/test_igblast.py b/test_igseq/test_igblast.py\nindex e401183..b8cc851 100644\n--- a/test_igseq/test_igblast.py\n+++ b/test_igseq/test_igblast.py\n@@ -62,3 +62,21 @@ class TestIgblastLive(TestBase, TestLive):\n btwn(stdout, 2, 97),\n btwn(stdout_exp, 2, 97))\n self.assertEqual(stderr, \"\")\n+\n+\n+class TestIgblastLiveCrash(TestBase, TestLive):\n+ \"\"\"Test that an igblastn crash is handled\"\"\"\n+\n+ def test_igblast(self):\n+ \"\"\"Test that an igblastn crash is caught and re-raised as an IgSeqError.\n+\n+ Standard error and output from the igblastn process should still show\n+ up on stderr and stdout as usual.\n+ \"\"\"\n+ def catch_expected_error():\n+ with self.assertRaises(IgSeqError):\n+ igblast.igblast(\n+ [\"rhesus/imgt\"], self.path/\"input/query.fasta\", extra_args=[\"-bad-arg\"])\n+ stdout, stderr = self.redirect_streams(catch_expected_error)\n+ self.assertEqual(stdout, \"\")\n+ self.assertIn('Error: Unknown argument: \"bad-arg\"', stderr)\n", "FAIL_TO_PASS": ["test_igseq/test_igblast.py::TestIgblastLiveCrash::test_igblast"]}], "all_FAIL_TO_PASS": ["test_igseq/test_igblast.py::TestIgblastLiveCrash::test_igblast"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PagerDuty__pdpyras-54_x1", "level": 1, "source": "swerebench", "repo": "PagerDuty/pdpyras", "image": "swerebench/sweb.eval.x86_64.pagerduty_1776_pdpyras-54:latest", "base_commit": "4fb715ab215a500262cb61005b1a9c70ba190179", "num_bugs": 1, "bugs": [{"instance_id": "PagerDuty__pdpyras-54", "base_commit": "4fb715ab215a500262cb61005b1a9c70ba190179", "gold_patch": "diff --git a/pdpyras.py b/pdpyras.py\nindex 506440d..2143baf 100644\n--- a/pdpyras.py\n+++ b/pdpyras.py\n@@ -211,7 +211,7 @@ def tokenize_url_path(url, baseurl='https://api.pagerduty.com'):\n :type method: str\n :type url: str\n :type baseurl: str\n- :rtype: tuple \n+ :rtype: tuple\n \"\"\"\n urlnparams = url.split('#')[0].split('?') # Ignore all #'s / params\n url_nodes = urlnparams[0].lstrip('/').split('/')\n@@ -236,7 +236,7 @@ def tokenize_url_path(url, baseurl='https://api.pagerduty.com'):\n # Tokenize / classify the URL now:\n tokenized_nodes = [path_nodes[0]]\n if len(path_nodes) >= 3:\n- # It's an endpoint like one of the following \n+ # It's an endpoint like one of the following\n # /{resource}/{id}/{sub-resource}\n # We're interested in {resource} and {sub_resource}.\n # More deeply-nested endpoints not known to exist.\n@@ -340,7 +340,7 @@ class PDSession(requests.Session):\n \n * ``-1`` to retry infinitely\n * ``0`` to return the `requests.Response`_ object and exit (which is the\n- default behavior) \n+ default behavior)\n * ``n``, where ``n > 0``, to retry ``n`` times (or up\n to :attr:`max_http_attempts` total for all statuses, whichever is\n encountered first), and raise a :class:`PDClientError` after that many\n@@ -609,7 +609,7 @@ class PDSession(requests.Session):\n def stagger_cooldown(self, val):\n if type(val) not in [float, int] or val<0:\n raise ValueError(\"Cooldown randomization factor stagger_cooldown \"\n- \"must be a positive real number\") \n+ \"must be a positive real number\")\n self._stagger_cooldown = val\n \n @property\n@@ -642,7 +642,7 @@ class EventsAPISession(PDSession):\n \n @property\n def auth_header(self):\n- return {'X-Routing-Key': self.api_key}\n+ return {}\n \n def acknowledge(self, dedup_key):\n \"\"\"\n@@ -691,10 +691,16 @@ class EventsAPISession(PDSession):\n :returns:\n The deduplication key of the incident, if any.\n \"\"\"\n+\n actions = ('trigger', 'acknowledge', 'resolve')\n if action not in actions:\n raise ValueError(\"Event action must be one of: \"+', '.join(actions))\n- event = {'event_action':action}\n+\n+ event = {\n+ 'event_action':action,\n+ 'routing_key': self.api_key\n+ }\n+\n event.update(properties)\n if isinstance(dedup_key, string_types):\n event['dedup_key'] = dedup_key\n@@ -797,7 +803,7 @@ class APISession(PDSession):\n :members:\n \"\"\"\n \n- api_call_counts = None \n+ api_call_counts = None\n \"\"\"A dict object recording the number of API calls per endpoint\"\"\"\n \n api_time = None\n@@ -834,7 +840,7 @@ class APISession(PDSession):\n @property\n def auth_type(self):\n \"\"\"\n- Defines the method of API authentication. \n+ Defines the method of API authentication.\n \n By default this is \"token\"; if \"oauth2\", the API key will be used.\n \"\"\"\n@@ -917,12 +923,12 @@ class APISession(PDSession):\n query_params.update({'query':query})\n # When determining uniqueness, web/the API doesn't care about case.\n simplify = lambda s: s.lower()\n- search_term = simplify(query) \n+ search_term = simplify(query)\n equiv = lambda s: simplify(s[attribute]) == search_term\n obj_iter = self.iter_all(resource, params=query_params)\n return next(iter(filter(equiv, obj_iter)), None)\n \n- def iter_all(self, path, params=None, paginate=True, page_size=None, \n+ def iter_all(self, path, params=None, paginate=True, page_size=None,\n item_hook=None, total=False):\n \"\"\"\n Iterator for the contents of an index endpoint or query.\n@@ -947,8 +953,8 @@ class APISession(PDSession):\n pagination yet, i.e. \"nested\" endpoints like (as of this writing):\n ``/users/{id}/contact_methods`` and ``/services/{id}/integrations``\n :param page_size:\n- If set, the ``page_size`` argument will override the ``default_page_size`` \n- parameter on the session and set the ``limit`` parameter to a custom \n+ If set, the ``page_size`` argument will override the ``default_page_size``\n+ parameter on the session and set the ``limit`` parameter to a custom\n value (default is 100), altering the number of pagination results.\n :param item_hook:\n Callable object that will be invoked for each iteration, i.e. for\n@@ -1017,7 +1023,7 @@ class APISession(PDSession):\n break\n try:\n response = r.json()\n- except ValueError: \n+ except ValueError:\n self.log.debug(\"Stopping iteration on endpoint \\\"%s\\\"; API \"\n \"responded with invalid JSON.\", path)\n break\n@@ -1035,7 +1041,7 @@ class APISession(PDSession):\n \"however many can be gotten, will be included.\", path)\n if 'total' in response:\n total_count = response['total']\n- else: \n+ else:\n self.log.debug(\"Pagination and the \\\"total\\\" parameter \"\n \"are enabled in iteration, but the index endpoint %s \"\n \"responded with no \\\"total\\\" property in the response. \"\n@@ -1043,7 +1049,7 @@ class APISession(PDSession):\n \"first retrieving all records.\", path)\n offset += data['limit']\n for result in response[r_name]:\n- n += 1 \n+ n += 1\n # Call a callable object for each item, i.e. to print progress:\n if hasattr(item_hook, '__call__'):\n item_hook(result, n, total_count)\n@@ -1054,7 +1060,7 @@ class APISession(PDSession):\n \"\"\"\n Performs a GET request, returning the JSON-decoded body as a dictionary\n \n- :raises PDClientError: In the event of HTTP error \n+ :raises PDClientError: In the event of HTTP error\n \"\"\"\n return self.get(path, **kw)\n \n@@ -1063,7 +1069,7 @@ class APISession(PDSession):\n \"\"\"\n Performs a POST request, returning the JSON-decoded body as a dictionary\n \n- :raises PDClientError: In the event of HTTP error \n+ :raises PDClientError: In the event of HTTP error\n \"\"\"\n return self.post(path, **kw)\n \n@@ -1130,9 +1136,9 @@ class APISession(PDSession):\n \n :param method:\n Method of the request\n- :param response: \n+ :param response:\n Response object\n- :param suffix: \n+ :param suffix:\n Optional suffix to append to the key\n :type method: str\n :type response: `requests.Response`_\n@@ -1296,7 +1302,7 @@ class APISession(PDSession):\n \"\"\"Truncated token for secure display/identification purposes.\"\"\"\n return last_4(self.api_key)\n \n-class PDClientError(Exception): \n+class PDClientError(Exception):\n \"\"\"\n General API errors base class.\n \"\"\"\n", "test_patch": "diff --git a/test_pdpyras.py b/test_pdpyras.py\nindex 76217fd..a2d1899 100755\n--- a/test_pdpyras.py\n+++ b/test_pdpyras.py\n@@ -91,12 +91,15 @@ class EventsSessionTest(SessionTest):\n 'https://events.pagerduty.com/v2/enqueue',\n parent.request.call_args[0][1])\n self.assertDictContainsSubset(\n- {'Content-Type': 'application/json',\n- 'X-Routing-Key': 'routingkey'},\n+ {'Content-Type': 'application/json'},\n+ parent.request.call_args[1]['headers'])\n+ self.assertNotIn(\n+ 'X-Routing-Key',\n parent.request.call_args[1]['headers'])\n self.assertEqual(\n {\n 'event_action':'trigger',\n+ 'routing_key':'routingkey',\n 'payload':{\n 'summary': 'testing 123',\n 'source': 'triggered.from.pdpyras',\n@@ -108,12 +111,20 @@ class EventsSessionTest(SessionTest):\n parent.request.call_args[1]['json'])\n ddk = sess.resolve('abc123')\n self.assertEqual(\n- {'event_action':'resolve', 'dedup_key':'abc123'},\n+ {\n+ 'event_action':'resolve',\n+ 'dedup_key':'abc123',\n+ 'routing_key':'routingkey',\n+ },\n parent.request.call_args[1]['json'])\n \n ddk = sess.acknowledge('abc123')\n self.assertEqual(\n- {'event_action':'acknowledge', 'dedup_key':'abc123'},\n+ {\n+ 'event_action':'acknowledge',\n+ 'dedup_key':'abc123',\n+ 'routing_key':'routingkey',\n+ },\n parent.request.call_args[1]['json'])\n \n class APISessionTest(SessionTest):\n", "FAIL_TO_PASS": ["test_pdpyras.py::EventsSessionTest::test_send_event"]}], "all_FAIL_TO_PASS": ["test_pdpyras.py::EventsSessionTest::test_send_event"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ResearchObject__ro-crate-py-102_x1", "level": 1, "source": "swerebench", "repo": "ResearchObject/ro-crate-py", "image": "swerebench/sweb.eval.x86_64.researchobject_1776_ro-crate-py-102:latest", "base_commit": "b8668904f18b6d4060d0b29406e2f04c95b6d2f9", "num_bugs": 1, "bugs": [{"instance_id": "ResearchObject__ro-crate-py-102", "base_commit": "b8668904f18b6d4060d0b29406e2f04c95b6d2f9", "gold_patch": "diff --git a/rocrate/model/entity.py b/rocrate/model/entity.py\nindex 826b564..77d5671 100644\n--- a/rocrate/model/entity.py\n+++ b/rocrate/model/entity.py\n@@ -75,7 +75,7 @@ class Entity(MutableMapping):\n \n def __getitem__(self, key):\n v = self._jsonld[key]\n- if isinstance(v, str) or key.startswith(\"@\"):\n+ if v is None or isinstance(v, str) or key.startswith(\"@\"):\n return v\n values = v if isinstance(v, list) else [v]\n deref_values = [self.crate.dereference(_[\"@id\"], _[\"@id\"]) for _ in values]\n", "test_patch": "diff --git a/test/test_model.py b/test/test_model.py\nindex 57fad30..e71bda8 100644\n--- a/test/test_model.py\n+++ b/test/test_model.py\n@@ -295,6 +295,7 @@ def test_entity_as_mapping(tmpdir, helpers):\n \"author\": {\"@id\": orcid}},\n {\"@id\": orcid,\n \"@type\": \"Person\",\n+ \"name\": None,\n \"givenName\": \"Josiah\",\n \"familyName\": \"Carberry\"}\n ]\n@@ -305,18 +306,24 @@ def test_entity_as_mapping(tmpdir, helpers):\n json.dump(metadata, f, indent=4)\n crate = ROCrate(crate_dir)\n person = crate.dereference(orcid)\n- assert len(person) == 4\n- assert len(list(person)) == 4\n- assert set(person) == set(person.keys()) == {\"@id\", \"@type\", \"givenName\", \"familyName\"}\n- assert set(person.values()) == {orcid, \"Person\", \"Josiah\", \"Carberry\"}\n+ exp_len = len(metadata[\"@graph\"][2])\n+ assert len(person) == exp_len\n+ assert len(list(person)) == exp_len\n+ assert set(person) == set(person.keys()) == {\"@id\", \"@type\", \"name\", \"givenName\", \"familyName\"}\n+ assert set(person.values()) == {orcid, \"Person\", None, \"Josiah\", \"Carberry\"}\n assert set(person.items()) == set(zip(person.keys(), person.values()))\n+ assert person.id == orcid\n+ assert person.type == \"Person\"\n+ assert person[\"name\"] is None\n+ assert person[\"givenName\"] == \"Josiah\"\n+ assert person[\"familyName\"] == \"Carberry\"\n assert person.setdefault(\"givenName\", \"foo\") == \"Josiah\"\n- assert len(person) == 4\n+ assert len(person) == exp_len\n assert person.setdefault(\"award\", \"Oscar\") == \"Oscar\"\n- assert len(person) == 5\n+ assert len(person) == exp_len + 1\n assert \"award\" in person\n assert person.pop(\"award\") == \"Oscar\"\n- assert len(person) == 4\n+ assert len(person) == exp_len\n assert \"award\" not in person\n for key in \"@id\", \"@type\":\n with pytest.raises(KeyError):\n@@ -326,8 +333,10 @@ def test_entity_as_mapping(tmpdir, helpers):\n with pytest.raises(KeyError):\n person.pop(key)\n twin = Person(crate, orcid, properties={\n+ \"name\": None,\n \"givenName\": \"Josiah\",\n \"familyName\": \"Carberry\"\n })\n assert twin == person\n assert Person(crate, orcid) != person\n+ assert crate.root_dataset[\"author\"] is person\n", "FAIL_TO_PASS": ["test/test_model.py::test_entity_as_mapping"]}], "all_FAIL_TO_PASS": ["test/test_model.py::test_entity_as_mapping"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "HXLStandard__libhxl-python-174_x1", "level": 1, "source": "swerebench", "repo": "HXLStandard/libhxl-python", "image": "swerebench/sweb.eval.x86_64.hxlstandard_1776_libhxl-python-174:latest", "base_commit": "1bc7e92a3844dd443f9e31f478357ea7b599c831", "num_bugs": 1, "bugs": [{"instance_id": "HXLStandard__libhxl-python-174", "base_commit": "1bc7e92a3844dd443f9e31f478357ea7b599c831", "gold_patch": "diff --git a/hxl/validation.py b/hxl/validation.py\nindex 3eb1eba..922bfaf 100644\n--- a/hxl/validation.py\n+++ b/hxl/validation.py\n@@ -1508,11 +1508,6 @@ def validate(data, schema=None):\n \n issue_map = dict()\n \n- def make_rule_hash(rule):\n- \"\"\"Make a good-enough hash for a rule.\"\"\"\n- s = \"\\r\".join([str(rule.severity), str(rule.description), str(rule.tag_pattern)])\n- return base64.urlsafe_b64encode(hashlib.md5(s.encode('utf-8')).digest())[:8].decode('ascii')\n-\n def add_issue(issue):\n hash = make_rule_hash(issue.rule)\n issue_map.setdefault(hash, []).append(issue)\n@@ -1562,9 +1557,10 @@ def make_json_report(status, issue_map, schema_url=None, data_url=None):\n \n # add the issue objects\n for rule_id, locations in issue_map.items():\n- json_report['stats']['total'] += len(locations)\n- json_report['stats'][locations[0].rule.severity] += len(locations)\n- json_report['issues'].append(make_json_issue(rule_id, locations))\n+ json_issue = make_json_issue(rule_id, locations)\n+ json_report['stats']['total'] += len(json_issue['locations'])\n+ json_report['stats'][locations[0].rule.severity] += len(json_issue['locations'])\n+ json_report['issues'].append(json_issue)\n \n return json_report\n \n@@ -1581,6 +1577,15 @@ def make_json_issue(rule_id, locations):\n if not description:\n description = model.message\n \n+ # get all unique locations\n+ location_keys = set()\n+ json_locations = []\n+ for location in locations:\n+ location_key = (location.row.row_number, location.column.column_number, location.value, location.suggested_value,)\n+ if not location_key in location_keys:\n+ json_locations.append(make_json_location(location))\n+ location_keys.add(location_key)\n+\n # make the issue\n json_issue = {\n \"rule_id\": rule_id,\n@@ -1589,7 +1594,7 @@ def make_json_issue(rule_id, locations):\n \"severity\": model.rule.severity,\n \"location_count\": len(locations),\n \"scope\": model.scope,\n- \"locations\": [make_json_location(location) for location in locations]\n+ \"locations\": json_locations\n }\n \n return json_issue\n@@ -1622,4 +1627,10 @@ def make_json_location(location):\n \n return json_location\n \n+\n+def make_rule_hash(rule):\n+ \"\"\"Make a good-enough hash for a rule.\"\"\"\n+ s = \"\\r\".join([str(rule.severity), str(rule.description), str(rule.tag_pattern)])\n+ return base64.urlsafe_b64encode(hashlib.md5(s.encode('utf-8')).digest())[:8].decode('ascii')\n+\n # end\n", "test_patch": "diff --git a/tests/test_validation.py b/tests/test_validation.py\nindex 43ab00b..7e8b4f3 100644\n--- a/tests/test_validation.py\n+++ b/tests/test_validation.py\n@@ -655,8 +655,8 @@ class TestValidateDataset(unittest.TestCase):\n def test_double_correlation(self):\n \"\"\"Test correlation when more than one column has same tagspec\"\"\"\n SCHEMA = [\n- ['#valid_tag', '#valid_correlation'],\n- ['#adm1+code', '#adm1+name']\n+ ['#valid_tag', '#description', '#valid_correlation', '#valid_value+list'],\n+ ['#adm1+code', 'xxxxx', '#adm1+name', 'X001|X002']\n ]\n DATASET = [\n ['#adm1+name', '#adm1+code', '#adm1+code'],\n", "FAIL_TO_PASS": ["tests/test_validation.py::TestValidateDataset::test_double_correlation"]}], "all_FAIL_TO_PASS": ["tests/test_validation.py::TestValidateDataset::test_double_correlation"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Pylons__webob-291_x1", "level": 1, "source": "swerebench", "repo": "Pylons/webob", "image": "swerebench/sweb.eval.x86_64.pylons_1776_webob-291:latest", "base_commit": "a755ef991d7a87a4c41dbf727b84e91e90ef97ad", "num_bugs": 1, "bugs": [{"instance_id": "Pylons__webob-291", "base_commit": "a755ef991d7a87a4c41dbf727b84e91e90ef97ad", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex de5f487..7037c57 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -12,12 +12,17 @@ matrix:\n env: TOXENV=py34\n - python: 3.5\n env: TOXENV=py35\n+ - python: 3.6-dev\n+ env: TOXENV=py36\n+ - python: nightly\n+ env: TOXENV=py37\n - python: pypy\n env: TOXENV=pypy\n- - python: pypy3\n- env: TOXENV=pypy3\n - python: 3.5\n env: TOXENV=py2-cover,py3-cover,coverage\n+ allow_failures:\n+ - env: TOXENV=py36\n+ - env: TOXENV=py37\n \n install:\n - travis_retry pip install tox\ndiff --git a/CHANGES.txt b/CHANGES.txt\nindex af25400..2d1795f 100644\n--- a/CHANGES.txt\n+++ b/CHANGES.txt\n@@ -39,6 +39,9 @@ Feature\n Bugfix\n ~~~~~~\n \n+- Fixes request.PATH_SAFE to contain all of the path safe characters according\n+ to RFC3986. See https://github.com/Pylons/webob/pull/291\n+\n - WebOb's exceptions will lazily read underlying variables when inserted into\n templates to avoid expensive computations/crashes when inserting into the\n template. This had a bad performance regression on Py27 because of the way\n@@ -84,4 +87,4 @@ Bugfix\n This is used in the exception handling code so that if you use a WebOb HTTP\n Exception and pass a generator to `app_iter` WebOb won't attempt to read the\n whole thing and instead allows it to be returned to the WSGI server. See\n- https://github.com/Pylons/webob/pull/259 \n+ https://github.com/Pylons/webob/pull/259\ndiff --git a/tox.ini b/tox.ini\nindex 402fd6a..79ee9c3 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -1,7 +1,8 @@\n [tox]\n envlist =\n- py27,py33,py34,py35,pypy,pypy3,\n+ py27,py33,py34,py35,py36,py37,pypy,\n docs,{py2,py3}-cover,coverage\n+skip_missing_interpreters = True\n \n [testenv]\n # Most of these are defaults but if you specify any you can't fall back\n@@ -11,10 +12,11 @@ basepython =\n py33: python3.3\n py34: python3.4\n py35: python3.5\n+ py36: python3.6\n+ py37: python3.7\n pypy: pypy\n- pypy3: pypy3\n py2: python2.7\n- py3: python3.4\n+ py3: python3.5\n \n commands =\n pip install webob[testing]\ndiff --git a/webob/request.py b/webob/request.py\nindex 45bc6f9..191b1b7 100644\n--- a/webob/request.py\n+++ b/webob/request.py\n@@ -83,7 +83,7 @@ class _NoDefault:\n return '(No Default)'\n NoDefault = _NoDefault()\n \n-PATH_SAFE = '/:@&+$,'\n+PATH_SAFE = \"/~!$&'()*+,;=:@\"\n \n _LATIN_ENCODINGS = (\n 'ascii', 'latin-1', 'latin', 'latin_1', 'l1', 'latin1',\n", "test_patch": "diff --git a/tests/test_request.py b/tests/test_request.py\nindex 9650702..de3b149 100644\n--- a/tests/test_request.py\n+++ b/tests/test_request.py\n@@ -2558,11 +2558,17 @@ class TestRequest_functional(object):\n assert req.cookies == {'foo': '?foo'}\n \n def test_path_quoting(self):\n- path = '/:@&+$,/bar'\n+ path = \"/_.-~!$&'()*+,;=:@/bar\"\n req = self._blankOne(path)\n assert req.path == path\n assert req.url.endswith(path)\n \n+ def test_path_quoting_pct_encodes(self):\n+ path = '/[]/bar'\n+ req = self._blankOne(path)\n+ assert req.path == '/%5B%5D/bar'\n+ assert req.url.endswith('/%5B%5D/bar')\n+\n def test_params(self):\n req = self._blankOne('/?a=1&b=2')\n req.method = 'POST'\n", "FAIL_TO_PASS": ["tests/test_request.py::TestRequest_functional::test_path_quoting"]}], "all_FAIL_TO_PASS": ["tests/test_request.py::TestRequest_functional::test_path_quoting"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "SAP__python-pyodata-232_x1", "level": 1, "source": "swerebench", "repo": "SAP/python-pyodata", "image": "swerebench/sweb.eval.x86_64.sap_1776_python-pyodata-232:latest", "base_commit": "5d1490871f4b824a82dd6eaa148444a99ea4f47d", "num_bugs": 1, "bugs": [{"instance_id": "SAP__python-pyodata-232", "base_commit": "5d1490871f4b824a82dd6eaa148444a99ea4f47d", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 0f876b9..7175a5d 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).\n \n ## [Unreleased]\n \n+- model: fix edge case for Edm.DateTimeOffset.from_json() without offset - Petr Hanak\n+\n ## [1.10.0]\n \n ### Added\ndiff --git a/pyodata/v2/model.py b/pyodata/v2/model.py\nindex 065f93e..4f15c84 100644\n--- a/pyodata/v2/model.py\n+++ b/pyodata/v2/model.py\n@@ -529,6 +529,12 @@ class EdmDateTimeOffsetTypTraits(EdmPrefixedTypTraits):\n return f'/Date({ticks}{offset_in_minutes:+05})/'\n \n def from_json(self, value):\n+ # special edge case:\n+ # datetimeoffset'yyyy-mm-ddThh:mm[:ss]' = defaults to UTC, when offset value is not provided in responde data by service but the metadata is EdmDateTimeOffset\n+ # intentionally just for from_json, generation of to_json should always provide timezone info\n+ if re.match(r\"^/Date\\((?P-?\\d+)\\)/$\", value):\n+ value = value.replace(')', '+0000)')\n+\n matches = re.match(r\"^/Date\\((?P-?\\d+)(?P[+-]\\d+)\\)/$\", value)\n try:\n milliseconds_since_epoch = matches.group('milliseconds_since_epoch')\n", "test_patch": "diff --git a/tests/test_model_v2.py b/tests/test_model_v2.py\nindex 5bdef48..258dde7 100644\n--- a/tests/test_model_v2.py\n+++ b/tests/test_model_v2.py\n@@ -690,6 +690,9 @@ def test_traits_datetimeoffset(type_date_time_offset):\n def test_traits_datetimeoffset_to_literal(type_date_time_offset):\n \"\"\"Test Edm.DateTimeOffset trait: Python -> literal\"\"\"\n \n+ testdate = datetime(1, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc)\n+ assert type_date_time_offset.traits.to_literal(testdate) == \"datetimeoffset'0001-01-01T00:00:00+00:00'\"\n+\n testdate = datetime(2005, 1, 28, 18, 30, 44, 123456, tzinfo=timezone(timedelta(hours=3, minutes=40)))\n assert type_date_time_offset.traits.to_literal(testdate) == \"datetimeoffset'2005-01-28T18:30:44.123456+03:40'\"\n \n@@ -746,7 +749,7 @@ def test_traits_datetimeoffset_from_invalid_literal(type_date_time_offset):\n assert str(e_info.value).startswith('Cannot decode datetimeoffset from value xyz')\n \n \n-def test_traits_datetimeoffset_from_odata(type_date_time_offset):\n+def test_traits_datetimeoffset_from_json(type_date_time_offset):\n \"\"\"Test Edm.DateTimeOffset trait: OData -> Python\"\"\"\n \n # parsing full representation\n@@ -768,6 +771,14 @@ def test_traits_datetimeoffset_from_odata(type_date_time_offset):\n assert testdate.microsecond == 0\n assert testdate.tzinfo == timezone(-timedelta(minutes=5))\n \n+ # parsing special edge case with no offset provided, defaults to UTC\n+ testdate = type_date_time_offset.traits.from_json(\"/Date(217567986000)/\")\n+ assert testdate.year == 1976\n+ assert testdate.minute == 33\n+ assert testdate.second == 6\n+ assert testdate.microsecond == 0\n+ assert testdate.tzinfo == timezone.utc\n+\n # parsing below lowest value with workaround\n pyodata.v2.model.FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE = True\n testdate = type_date_time_offset.traits.from_json(\"/Date(-62135596800001+0001)/\")\n", "FAIL_TO_PASS": ["tests/test_model_v2.py::test_traits_datetimeoffset_from_json"]}], "all_FAIL_TO_PASS": ["tests/test_model_v2.py::test_traits_datetimeoffset_from_json"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ReproNim__reproman-436_x1", "level": 1, "source": "swerebench", "repo": "ReproNim/reproman", "image": "swerebench/sweb.eval.x86_64.repronim_1776_reproman-436:latest", "base_commit": "c291a61ba065ecb5da6b1bab1e6e5ba2447e5fd3", "num_bugs": 1, "bugs": [{"instance_id": "ReproNim__reproman-436", "base_commit": "c291a61ba065ecb5da6b1bab1e6e5ba2447e5fd3", "gold_patch": "diff --git a/reproman/resource/base.py b/reproman/resource/base.py\nindex 46c9642..74c0524 100644\n--- a/reproman/resource/base.py\n+++ b/reproman/resource/base.py\n@@ -99,6 +99,62 @@ def get_resource_backends(cls):\n if \"doc\" in b.metadata}\n \n \n+def classify_keys(cls, keys):\n+ \"\"\"Classify `keys` according to the parameters of resource `cls`.\n+\n+ Parameters\n+ ----------\n+ cls : Resource object\n+ keys : iterable\n+ Keys to classify.\n+\n+ Returns\n+ -------\n+ A dictionary where each of `keys` is classified into one of the following\n+ categories:\n+ - required\n+ a parameter that must be specified when instantiating the class (either\n+ by us or the user)\n+ - opt_user\n+ a optional parameter that is exposed to the user (i.e. a field that has\n+ a default value and \"doc\" metadata)\n+ - opt_internal\n+ a unexposed optional parameter (i.e. a field with a default value but\n+ with no \"doc\" metadata) that should not be set by the user (e.g.,\n+ status)\n+ - unknown\n+ a parameter that doesn't fall into any of the above categories\n+\n+ Raises\n+ ------\n+ A ResourceError if a required parameter isn't included in `keys`.\n+ \"\"\"\n+ all_fields = {f.name for f in attr.fields(cls)}\n+ required_params = get_required_fields(cls)\n+ required_seen = set()\n+ known = get_resource_backends(cls)\n+ cats = {\"required\": [], \"opt_user\": [], \"opt_internal\": [], \"unknown\": []}\n+ for key in keys:\n+ if key in required_params:\n+ required_seen.add(key)\n+ cat = \"required\"\n+ elif key in known:\n+ cat = \"opt_user\"\n+ elif key in all_fields:\n+ # These are attributes like id and status.\n+ cat = \"opt_internal\"\n+ else:\n+ cat = \"unknown\"\n+ cats[cat].append(key)\n+\n+ required_missing = required_params.difference(required_seen)\n+ if required_missing:\n+ raise ResourceError(\"Missing required backend parameters: {}\"\n+ .format(\", \".join(sorted(required_missing))))\n+\n+ return cats\n+\n+\n def backend_check_parameters(cls, keys):\n \"\"\"Check whether any backend parameter keys are unknown.\n \n@@ -112,14 +168,10 @@ def backend_check_parameters(cls, keys):\n ------\n ResourceError on the first unknown key encountered.\n \"\"\"\n- required_params = get_required_fields(cls)\n- for req_param in required_params:\n- if req_param not in keys:\n- raise ResourceError(\n- \"Missing required backend parameter: \" + req_param)\n- known = get_resource_backends(cls)\n- for key in keys:\n- if key not in known and key not in required_params:\n+ unknown = classify_keys(cls, keys)[\"unknown\"]\n+ if unknown:\n+ known = get_resource_backends(cls)\n+ for key in unknown:\n if known:\n import difflib\n \n@@ -169,14 +221,44 @@ class ResourceManager(object):\n for r in self.inventory:\n yield r\n \n- @staticmethod\n- def factory(config):\n+ def _filter_config(self, cls, config):\n+ \"\"\"Modify `config` to drop invalid parameters for `cls`.\n+\n+ Parameters\n+ ----------\n+ cls : Resource object\n+ config : dict\n+ Configuration parameters for a resource.\n+\n+ Returns\n+ -------\n+ A filtered (copy of) config or `config` itself if no modifications were\n+ needed.\n+ \"\"\"\n+ unknown = classify_keys(cls, config)[\"unknown\"]\n+ if unknown:\n+ config = config.copy()\n+ inv_config = self.inventory.get(config[\"name\"], {})\n+ for unk_param in unknown:\n+ msg_extra = \"\"\n+ if unk_param in inv_config:\n+ msg_extra = (\". Consider removing it from {}\"\n+ .format(self._inventory_path))\n+ lgr.warning(\"%s is not a known %s parameter%s\",\n+ unk_param, config[\"type\"], msg_extra)\n+ config.pop(unk_param)\n+ return config\n+\n+ def factory(self, config, strict=True):\n \"\"\"Factory method for creating the appropriate Container sub-class.\n \n Parameters\n ----------\n config : dict\n Configuration parameters for the resource.\n+ strict : optional\n+ When set to false, drop unknown keys from `config`, after issuing a\n+ warning, rather than raising a ResourceError.\n \n Returns\n -------\n@@ -187,12 +269,20 @@ class ResourceManager(object):\n \n type_ = config['type']\n cls = get_resource_class(type_)\n+\n+ if not strict:\n+ config = self._filter_config(cls, config)\n+\n try:\n instance = cls(**config)\n except TypeError:\n- backend_check_parameters(cls, config)\n- # The check didn't raise an exception, so this wasn't related to an\n- # unknown backend parameter.\n+ if strict:\n+ # In strict mode, the exception may be due to an unknown\n+ # backend paraemter. Call backend_check_parameters() to get a\n+ # more meaningful ResourceError.\n+ backend_check_parameters(cls, config)\n+ # Never mind. The check didn't raise an exception, so this\n+ # wasn't related to an unknown backend parameter.\n raise\n return instance\n \n@@ -272,7 +362,8 @@ class ResourceManager(object):\n -------\n A Resource object\n \"\"\"\n- return self.factory(self._get_resource_config(resref, resref_type))\n+ return self.factory(self._get_resource_config(resref, resref_type),\n+ strict=False)\n \n def _get_inventory(self):\n \"\"\"Return a dict with the config information for all resources.\n", "test_patch": "diff --git a/reproman/conftest.py b/reproman/conftest.py\nindex 1b89f70..c53e848 100644\n--- a/reproman/conftest.py\n+++ b/reproman/conftest.py\n@@ -11,6 +11,7 @@\n # Some commonly used fixtures\n \n from reproman.formats.tests.fixtures import demo1_spec, reprozip_spec2\n+from reproman.tests.fixtures import resource_manager_fixture\n \n import pytest\n \n@@ -29,3 +30,9 @@ def pytest_collection_modifyitems(config, items):\n for item in items:\n if \"integration\" in item.keywords:\n item.add_marker(skip_integration)\n+\n+\n+# This is useful for tests that need a ResourceManager instance but do not need\n+# any resources and don't plan on modifying the on-disk inventory. If you do\n+# need to modify the resources, use `resource_manager_fixture` directly.\n+resman = resource_manager_fixture(resources={}, scope=\"session\")\ndiff --git a/reproman/resource/tests/test_aws_ec2.py b/reproman/resource/tests/test_aws_ec2.py\nindex 5289f9d..3508019 100644\n--- a/reproman/resource/tests/test_aws_ec2.py\n+++ b/reproman/resource/tests/test_aws_ec2.py\n@@ -12,13 +12,12 @@ from unittest.mock import patch, call, MagicMock\n from ...utils import swallow_logs\n from ...tests.utils import assert_in\n from ...tests.skip import mark\n-from ..base import ResourceManager\n from ..ssh import SSH\n \n pytestmark = mark.skipif_no_aws_dependencies\n \n \n-def test_awsec2_class():\n+def test_awsec2_class(resman):\n \n with patch('boto3.resource') as client, \\\n patch.object(SSH, 'get_session', return_value='started_session'), \\\n@@ -34,7 +33,7 @@ def test_awsec2_class():\n 'access_key_id': 'my-aws-access-key-id',\n 'secret_access_key': 'my-aws-secret-access-key-id'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n resource.connect()\n assert resource.id is None\n assert resource.status is None\n@@ -58,7 +57,7 @@ def test_awsec2_class():\n 'access_key_id': 'my-aws-access-key-id',\n 'secret_access_key': 'my-aws-secret-access-key-id'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n try:\n resource.connect()\n except Exception as e:\n@@ -80,7 +79,7 @@ def test_awsec2_class():\n 'key_name': 'my-ssh-key',\n 'key_filename': '/home/me/.ssh/id_rsa'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n resource.connect()\n assert resource.image == 'ami-c8580bdf'\n assert resource.id == 'i-00002777d52482d9c'\n@@ -117,7 +116,7 @@ def test_awsec2_class():\n 'key_name': 'my-ssh-key',\n 'key_filename': '/home/me/.ssh/id_rsa'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n resource.connect()\n # Test retrieving more than one yield from the create method\n create_generator = resource.create()\ndiff --git a/reproman/resource/tests/test_base.py b/reproman/resource/tests/test_base.py\nindex e406261..7fd80d7 100644\n--- a/reproman/resource/tests/test_base.py\n+++ b/reproman/resource/tests/test_base.py\n@@ -11,6 +11,7 @@ import pytest\n \n from reproman.config import ConfigManager\n from reproman.resource.base import ResourceManager\n+from reproman.resource.base import Resource\n from reproman.resource.base import backend_check_parameters\n from reproman.resource.base import get_resource_class\n from reproman.resource.shell import Shell\n@@ -21,14 +22,37 @@ from reproman.support.exceptions import ResourceError\n from reproman.tests.skip import mark\n \n \n-def test_resource_manager_factory_missing_type():\n+def test_resource_manager_factory_missing_type(resman):\n with pytest.raises(MissingConfigError):\n- ResourceManager.factory({})\n+ resman.factory({})\n \n \n-def test_resource_manager_factory_unkown():\n+def test_resource_manager_factory_unkown(resman):\n with pytest.raises(ResourceError):\n- ResourceManager.factory({\"type\": \"not really a type\"})\n+ resman.factory({\"type\": \"not really a type\"})\n+\n+\n+def test_resource_manager_factory_missing_required(resman):\n+ with pytest.raises(ResourceError):\n+ resman.factory({\"type\": \"shell\"})\n+\n+\n+@pytest.mark.parametrize(\"type_\", [\"shell\", \"ssh\"])\n+def test_resource_manager_factory_invalid_param(resman, type_):\n+ config = {\"type\": type_,\n+ \"id\": \"id\",\n+ \"name\": \"name\",\n+ # All of the below are invalid in the case of shell. For ssh,\n+ # \"other\" is invalid.\n+ \"host\": \"host\",\n+ \"port\": \"port\",\n+ \"other\": \"doesntmatter\"}\n+\n+ with pytest.raises(ResourceError):\n+ resman.factory(config)\n+\n+ res = resman.factory(config, strict=False)\n+ assert isinstance(res, Resource)\n \n \n def test_backend_check_parameters_no_known():\ndiff --git a/reproman/resource/tests/test_docker_container.py b/reproman/resource/tests/test_docker_container.py\nindex 98df863..3be21a5 100644\n--- a/reproman/resource/tests/test_docker_container.py\n+++ b/reproman/resource/tests/test_docker_container.py\n@@ -13,7 +13,6 @@ from ...utils import merge_dicts\n from ...utils import swallow_logs\n from ...tests.utils import assert_in\n from ...tests.skip import mark\n-from ..base import ResourceManager\n from ...support.exceptions import ResourceError\n from ...consts import TEST_SSH_DOCKER_DIGEST\n \n@@ -30,7 +29,7 @@ setup_ubuntu = get_docker_fixture(\n \n \n @mark.skipif_no_docker_dependencies\n-def test_dockercontainer_class():\n+def test_dockercontainer_class(resman):\n \n with patch('docker.Client') as client, \\\n patch('dockerpty.start') as dockerpty, \\\n@@ -74,7 +73,7 @@ def test_dockercontainer_class():\n 'name': 'non-existent-resource',\n 'type': 'docker-container'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n resource.connect()\n assert resource.id is None\n assert resource.status is None\n@@ -84,7 +83,7 @@ def test_dockercontainer_class():\n 'name': 'duplicate-resource-name',\n 'type': 'docker-container'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n with raises(ResourceError) as ecm:\n resource.connect()\n assert ecm.value.args[0].startswith(\"Multiple container matches found\")\n@@ -96,7 +95,7 @@ def test_dockercontainer_class():\n 'engine_url': 'tcp://127.0.0.1:2375',\n 'seccomp_unconfined': True\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n resource.connect()\n assert resource.image == 'ubuntu:latest'\n assert resource.engine_url == 'tcp://127.0.0.1:2375'\n@@ -117,7 +116,7 @@ def test_dockercontainer_class():\n 'type': 'docker-container',\n 'engine_url': 'tcp://127.0.0.1:2375'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n resource.connect()\n results = merge_dicts(resource.create())\n assert results['id'] == '18b31b30e3a5'\ndiff --git a/reproman/resource/tests/test_shell.py b/reproman/resource/tests/test_shell.py\nindex d9250cf..d782af0 100644\n--- a/reproman/resource/tests/test_shell.py\n+++ b/reproman/resource/tests/test_shell.py\n@@ -17,13 +17,12 @@ from unittest.mock import patch, call\n from ...utils import merge_dicts\n from ...utils import swallow_logs\n from ...tests.utils import assert_in\n-from ..base import ResourceManager\n from ...cmd import Runner\n from ..shell import Shell, ShellSession\n from .test_session import check_session_passing_envvars\n \n \n-def test_shell_class():\n+def test_shell_class(resman):\n \n with patch.object(Runner, 'run', return_value='installed package') as runner, \\\n swallow_logs(new_level=logging.DEBUG) as log:\n@@ -33,7 +32,7 @@ def test_shell_class():\n 'name': 'my-shell',\n 'type': 'shell'\n }\n- shell = ResourceManager.factory(config)\n+ shell = resman.factory(config)\n \n command = ['apt-get', 'install', 'bc']\n shell.add_command(command)\n@@ -127,13 +126,13 @@ def test_session_passing_envvars():\n check_session_passing_envvars(ShellSession())\n \n \n-def test_shell_resource():\n+def test_shell_resource(resman):\n \n config = {\n 'name': 'test-ssh-resource',\n 'type': 'shell'\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n \n status = merge_dicts(resource.create())\n assert re.match('\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}$', status['id']) is not None\ndiff --git a/reproman/resource/tests/test_ssh.py b/reproman/resource/tests/test_ssh.py\nindex 007c442..3e577eb 100644\n--- a/reproman/resource/tests/test_ssh.py\n+++ b/reproman/resource/tests/test_ssh.py\n@@ -20,7 +20,6 @@ from ...utils import merge_dicts\n from ...utils import swallow_logs\n from ...tests.utils import assert_in\n from ...tests.skip import mark\n-from ..base import ResourceManager\n from reproman.tests.fixtures import get_docker_fixture\n from ...consts import TEST_SSH_DOCKER_DIGEST\n \n@@ -48,7 +47,7 @@ def test_setup_ssh(setup_ssh):\n assert setup_ssh['custom']['host'] == 'localhost'\n \n \n-def test_ssh_class(setup_ssh, resource_test_dir):\n+def test_ssh_class(setup_ssh, resource_test_dir, resman):\n with swallow_logs(new_level=logging.DEBUG) as log:\n \n # Test connecting to test SSH server.\n@@ -58,7 +57,7 @@ def test_ssh_class(setup_ssh, resource_test_dir):\n type='ssh',\n **setup_ssh['custom']\n )\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n updated_config = merge_dicts(resource.create())\n config.update(updated_config)\n assert re.match('\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}$',\n@@ -116,7 +115,7 @@ def test_ssh_class(setup_ssh, resource_test_dir):\n session._execute_command('non-existent-command', cwd='/path')\n \n \n-def test_ssh_resource(setup_ssh):\n+def test_ssh_resource(setup_ssh, resman):\n \n config = {\n 'name': 'ssh-test-resource',\n@@ -125,7 +124,7 @@ def test_ssh_resource(setup_ssh):\n 'user': 'root',\n 'port': 49000\n }\n- resource = ResourceManager.factory(config)\n+ resource = resman.factory(config)\n resource.connect(password='root')\n \n with pytest.raises(NotImplementedError):\n", "FAIL_TO_PASS": ["reproman/resource/tests/test_base.py::test_resource_manager_factory_invalid_param[shell]", "reproman/resource/tests/test_base.py::test_resource_manager_factory_invalid_param[ssh]"]}], "all_FAIL_TO_PASS": ["reproman/resource/tests/test_base.py::test_resource_manager_factory_invalid_param[shell]", "reproman/resource/tests/test_base.py::test_resource_manager_factory_invalid_param[ssh]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "RadioAstronomySoftwareGroup__pyuvdata-642_x1", "level": 1, "source": "swerebench", "repo": "RadioAstronomySoftwareGroup/pyuvdata", "image": "swerebench/sweb.eval.x86_64.radioastronomysoftwaregroup_1776_pyuvdata-642:latest", "base_commit": "ad4ba0e02e4f4049ba460e90f34372467d9edc91", "num_bugs": 1, "bugs": [{"instance_id": "RadioAstronomySoftwareGroup__pyuvdata-642", "base_commit": "ad4ba0e02e4f4049ba460e90f34372467d9edc91", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex f581386f..0d42d581 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -2,11 +2,14 @@\n All notable changes to this project will be documented in this file.\n \n ## [Unreleased]\n+- `utils.uvcalibrate` flag propagation bug fix\n+- `UVCal.ant2ind` indexing bug fix\n - `UVCal.get_*` methods for accessing data arrays with antenna-polarization keys\n - `utils.uvcalibrate` for automated calibration of `UVData` by `UVCal`\n \n ### Fixed\n - Fixed a bug in select that caused bls and antenna_names/numbers to be or'ed rather than and'ed together.\n+- Fixed a bug where `baseline_to_antnums` could accept a numpy array as input but not other array_like objects.\n \n ## [1.4.0] - 2019-05-23\n \ndiff --git a/pyuvdata/utils.py b/pyuvdata/utils.py\nindex 3a669b19..55394e44 100644\n--- a/pyuvdata/utils.py\n+++ b/pyuvdata/utils.py\n@@ -464,12 +464,11 @@ def uvcalibrate(uvdata, uvcal, inplace=True, prop_flags=True, flag_missing=True,\n gain[mask] = 1.0\n uvdata.flag_array[blt_inds, 0, :, pol_ind] += mask\n \n- else:\n- # apply to data\n- if uvcal.gain_convention == 'multiply':\n- uvdata.data_array[blt_inds, 0, :, pol_ind] *= gain\n- elif uvcal.gain_convention == 'divide':\n- uvdata.data_array[blt_inds, 0, :, pol_ind] /= gain\n+ # apply to data\n+ if uvcal.gain_convention == 'multiply':\n+ uvdata.data_array[blt_inds, 0, :, pol_ind] *= gain\n+ elif uvcal.gain_convention == 'divide':\n+ uvdata.data_array[blt_inds, 0, :, pol_ind] /= gain\n \n # update history\n uvdata.history += \"\\nCalibrated with pyuvdata.utils.uvcalibrate.\"\n@@ -988,16 +987,25 @@ def baseline_to_antnums(baseline, Nants_telescope):\n \"\"\"\n Get the antenna numbers corresponding to a given baseline number.\n \n- Args:\n- baseline: integer baseline number\n- Nant_telescope: integer number of antennas\n+ Parameters\n+ ----------\n+ baseline : int or array_like of ints\n+ baseline number\n+ Nant_telescope : int\n+ number of antennas\n \n- Returns:\n- tuple with the two antenna numbers corresponding to the baseline.\n+ Returns\n+ -------\n+ int or array_like of int\n+ first antenna number(s)\n+ int or array_like of int\n+ second antenna number(s)\n \"\"\"\n if Nants_telescope > 2048:\n raise Exception('error Nants={Nants}>2048 not '\n 'supported'.format(Nants=Nants_telescope))\n+\n+ baseline = np.asarray(baseline, dtype=np.int64)\n if np.min(baseline) > 2**16:\n ant2 = (baseline - 2**16) % 2048 - 1\n ant1 = (baseline - 2**16 - (ant2 + 1)) / 2048 - 1\n@@ -1011,16 +1019,23 @@ def antnums_to_baseline(ant1, ant2, Nants_telescope, attempt256=False):\n \"\"\"\n Get the baseline number corresponding to two given antenna numbers.\n \n- Args:\n- ant1: first antenna number (integer)\n- ant2: second antenna number (integer)\n- Nant_telescope: integer number of antennas\n- attempt256: Option to try to use the older 256 standard used in\n- many uvfits files (will use 2048 standard if there are more\n- than 256 antennas). Default is False.\n+ Parameters\n+ ----------\n+ ant1 : int or array_like of int\n+ first antenna number\n+ ant2 : int or array_like of int\n+ second antenna number\n+ Nant_telescope : int\n+ number of antennas\n+ attempt256 : bool\n+ Option to try to use the older 256 standard used in\n+ many uvfits files (will use 2048 standard if there are more\n+ than 256 antennas). Default is False.\n \n- Returns:\n- integer baseline number corresponding to the two antenna numbers.\n+ Returns\n+ -------\n+ int or array of int\n+ baseline number corresponding to the two antenna numbers.\n \"\"\"\n ant1, ant2 = np.int64((ant1, ant2))\n if Nants_telescope is not None and Nants_telescope > 2048:\ndiff --git a/pyuvdata/uvcal.py b/pyuvdata/uvcal.py\nindex 41f51b17..6f86fa83 100644\n--- a/pyuvdata/uvcal.py\n+++ b/pyuvdata/uvcal.py\n@@ -738,7 +738,7 @@ class UVCal(UVBase):\n if not self._has_key(antnum=antnum):\n raise ValueError(\"{} not found in ant_array\".format(antnum))\n \n- return np.argmin(self.ant_array - antnum)\n+ return np.argmin(np.abs(self.ant_array - antnum))\n \n def jpol2ind(self, jpol):\n \"\"\"\ndiff --git a/pyuvdata/uvdata.py b/pyuvdata/uvdata.py\nindex 934c71eb..7c2369e8 100644\n--- a/pyuvdata/uvdata.py\n+++ b/pyuvdata/uvdata.py\n@@ -577,15 +577,15 @@ class UVData(UVBase):\n \n Parameters\n ----------\n- baseline : int\n+ baseline : int or array_like of int\n baseline number\n \n Returns\n -------\n- int\n- first antenna number\n- int\n- second antenna number\n+ int or array_like of int\n+ first antenna number(s)\n+ int or array_like of int\n+ second antenna number(s)\n \"\"\"\n return uvutils.baseline_to_antnums(baseline, self.Nants_telescope)\n \n@@ -595,9 +595,9 @@ class UVData(UVBase):\n \n Parameters\n ----------\n- ant1 : int\n+ ant1 : int or array_like of int\n first antenna number\n- ant2 : int\n+ ant2 : int or array_like of int\n second antenna number\n attempt256 : bool\n Option to try to use the older 256 standard used in many uvfits files\n@@ -605,7 +605,7 @@ class UVData(UVBase):\n \n Returns\n -------\n- int\n+ int or array of int\n baseline number corresponding to the two antenna numbers.\n \"\"\"\n return uvutils.antnums_to_baseline(ant1, ant2, self.Nants_telescope, attempt256=attempt256)\n", "test_patch": "diff --git a/pyuvdata/tests/test_utils.py b/pyuvdata/tests/test_utils.py\nindex dd405843..01ce1e4e 100644\n--- a/pyuvdata/tests/test_utils.py\n+++ b/pyuvdata/tests/test_utils.py\n@@ -948,7 +948,7 @@ def test_uvcalibrate_apply_gains():\n \n # division calibrate\n uvc.gain_convention = 'divide'\n- uvdcal = uvutils.uvcalibrate(uvd, uvc, prop_flags=False, flag_missing=False, inplace=False)\n+ uvdcal = uvutils.uvcalibrate(uvd, uvc, prop_flags=True, flag_missing=False, inplace=False)\n np.testing.assert_array_almost_equal(uvdcal.get_data(key), uvd.get_data(key) / (uvc.get_gains(ant1) * uvc.get_gains(ant2).conj()).T)\n \n # multiplication calibrate\ndiff --git a/pyuvdata/tests/test_uvcal.py b/pyuvdata/tests/test_uvcal.py\nindex c4392f22..5f8b14bc 100644\n--- a/pyuvdata/tests/test_uvcal.py\n+++ b/pyuvdata/tests/test_uvcal.py\n@@ -1442,17 +1442,19 @@ def test_uvcal_get_methods():\n uvc = UVCal()\n uvc.read_calfits(os.path.join(DATA_PATH, 'zen.2457698.40355.xx.gain.calfits'))\n \n- # test get methods\n- key = (9, 'Jxx')\n+ # test get methods: add in a known value and make sure it is returned\n+ key = (10, 'Jxx')\n+ uvc.gain_array[1] = 0.0\n d, f, q = uvc.get_gains(key), uvc.get_flags(key), uvc.get_quality(key)\n \n # test shapes\n+ assert np.all(np.isclose(d, 0.0))\n assert d.shape == (uvc.Nfreqs, uvc.Ntimes)\n assert f.shape == (uvc.Nfreqs, uvc.Ntimes)\n assert q.shape == (uvc.Nfreqs, uvc.Ntimes)\n \n # test against by-hand indexing\n- np.testing.assert_array_almost_equal(d, uvc.gain_array[uvc.ant_array.tolist().index(9), 0, :, :, uvc.jones_array.tolist().index(-5)])\n+ np.testing.assert_array_almost_equal(d, uvc.gain_array[uvc.ant_array.tolist().index(10), 0, :, :, uvc.jones_array.tolist().index(-5)])\n \n # test variable key input\n d2 = uvc.get_gains(*key)\n@@ -1461,23 +1463,23 @@ def test_uvcal_get_methods():\n np.testing.assert_array_almost_equal(d, d2)\n d2 = uvc.get_gains(key[:1])\n np.testing.assert_array_almost_equal(d, d2)\n- d2 = uvc.get_gains(9, -5)\n+ d2 = uvc.get_gains(10, -5)\n np.testing.assert_array_almost_equal(d, d2)\n- d2 = uvc.get_gains(9, 'x')\n+ d2 = uvc.get_gains(10, 'x')\n np.testing.assert_array_almost_equal(d, d2)\n \n # check has_key\n- assert uvc._has_key(antnum=9)\n+ assert uvc._has_key(antnum=10)\n assert uvc._has_key(jpol='Jxx')\n- assert uvc._has_key(antnum=9, jpol='Jxx')\n- assert not uvc._has_key(antnum=9, jpol='Jyy')\n+ assert uvc._has_key(antnum=10, jpol='Jxx')\n+ assert not uvc._has_key(antnum=10, jpol='Jyy')\n assert not uvc._has_key(antnum=101, jpol='Jxx')\n \n # test exceptions\n pytest.raises(ValueError, uvc.get_gains, 1)\n- pytest.raises(ValueError, uvc.get_gains, (9, 'Jyy'))\n+ pytest.raises(ValueError, uvc.get_gains, (10, 'Jyy'))\n uvc.cal_type = 'delay'\n- pytest.raises(ValueError, uvc.get_gains, 9)\n+ pytest.raises(ValueError, uvc.get_gains, 10)\n \n \n def test_deprecated_x_orientation():\ndiff --git a/pyuvdata/tests/test_uvdata.py b/pyuvdata/tests/test_uvdata.py\nindex 77b63b9e..1ef3a22b 100644\n--- a/pyuvdata/tests/test_uvdata.py\n+++ b/pyuvdata/tests/test_uvdata.py\n@@ -297,7 +297,10 @@ def uvdata_baseline():\n def test_baseline_to_antnums(uvdata_baseline):\n \"\"\"Test baseline to antnum conversion for 256 & larger conventions.\"\"\"\n assert uvdata_baseline.uv_object.baseline_to_antnums(67585) == (0, 0)\n- pytest.raises(Exception, uvdata_baseline.uv_object2.baseline_to_antnums, 67585)\n+ with pytest.raises(Exception) as cm:\n+ uvdata_baseline.uv_object2.baseline_to_antnums(67585)\n+ assert str(cm.value).startswith('error Nants={Nants}>2048'\n+ ' not supported'.format(Nants=uvdata_baseline.uv_object2.Nants_telescope))\n \n ant_pairs = [(10, 20), (280, 310)]\n for pair in ant_pairs:\n@@ -313,6 +316,18 @@ def test_baseline_to_antnums(uvdata_baseline):\n assert pair == ant_pair_out\n \n \n+def test_baseline_to_antnums_vectorized(uvdata_baseline):\n+ \"\"\"Test vectorized antnum to baseline conversion.\"\"\"\n+ ant_1 = [10, 280]\n+ ant_2 = [20, 310]\n+ baseline_array = uvdata_baseline.uv_object.antnums_to_baseline(ant_1, ant_2)\n+ assert np.array_equal(baseline_array, [88085, 641335])\n+ ant_1_out, ant_2_out = uvdata_baseline.uv_object.baseline_to_antnums(baseline_array.tolist())\n+ print('out:', ant_1_out, ant_2_out)\n+ assert np.array_equal(ant_1, ant_1_out)\n+ assert np.array_equal(ant_2, ant_2_out)\n+\n+\n def test_antnums_to_baselines(uvdata_baseline):\n \"\"\"Test antums to baseline conversion for 256 & larger conventions.\"\"\"\n assert uvdata_baseline.uv_object.antnums_to_baseline(0, 0) == 67585\n", "FAIL_TO_PASS": ["pyuvdata/tests/test_utils.py::test_uvcalibrate_apply_gains", "pyuvdata/tests/test_uvcal.py::test_uvcal_get_methods", "pyuvdata/tests/test_uvdata.py::test_baseline_to_antnums_vectorized"]}], "all_FAIL_TO_PASS": ["pyuvdata/tests/test_utils.py::test_uvcalibrate_apply_gains", "pyuvdata/tests/test_uvcal.py::test_uvcal_get_methods", "pyuvdata/tests/test_uvdata.py::test_baseline_to_antnums_vectorized"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MycroftAI__lingua-franca-10_x1", "level": 1, "source": "swerebench", "repo": "MycroftAI/lingua-franca", "image": "swerebench/sweb.eval.x86_64.mycroftai_1776_lingua-franca-10:latest", "base_commit": "358fdcbcfe77c1672725ce25d7928782adb813b6", "num_bugs": 1, "bugs": [{"instance_id": "MycroftAI__lingua-franca-10", "base_commit": "358fdcbcfe77c1672725ce25d7928782adb813b6", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\ndeleted file mode 100644\nindex d21b2ce..0000000\n--- a/.travis.yml\n+++ /dev/null\n@@ -1,16 +0,0 @@\n-branches:\n- only:\n- - master\n- - dev\n-language: python\n-python:\n- - \"3.4\"\n- - \"3.5\"\n- - \"3.6\" # current default Python on Travis CI\n- - \"3.7\"\n-# command to install dependencies\n-install:\n- - pip install -r requirements.txt\n-# command to run tests\n-script:\n- - pytest\ndiff --git a/lingua_franca/lang/parse_en.py b/lingua_franca/lang/parse_en.py\nindex 9676121..7e9abd3 100644\n--- a/lingua_franca/lang/parse_en.py\n+++ b/lingua_franca/lang/parse_en.py\n@@ -899,6 +899,11 @@ def extract_datetime_en(string, dateNow, default_time):\n if hrAbs is None:\n hrAbs = 19\n used += 1\n+ elif word == \"tonight\" or word == \"night\":\n+ if hrAbs is None:\n+ hrAbs = 22\n+ #used += 1 ## NOTE this breaks other tests, TODO refactor me!\n+\n # couple of time_unit\n elif word == \"2\" and wordNext == \"of\" and \\\n wordNextNext in [\"hours\", \"minutes\", \"seconds\"]:\n@@ -920,6 +925,8 @@ def extract_datetime_en(string, dateNow, default_time):\n minOffset = 15\n if idx > 2 and words[idx - 3] in markers:\n words[idx - 3] = \"\"\n+ if words[idx - 3] == \"this\":\n+ daySpecified = True\n words[idx - 2] = \"\"\n elif wordPrev == \"within\":\n hrOffset = 1\ndiff --git a/readme.md b/readme.md\nindex 899ca41..4a3654d 100644\n--- a/readme.md\n+++ b/readme.md\n@@ -1,6 +1,6 @@\n [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE.md) [![CLA](https://img.shields.io/badge/CLA%3F-Required-blue.svg)](https://mycroft.ai/cla) [![Team](https://img.shields.io/badge/Team-Languages-violetblue.svg)](https://github.com/MycroftAI/contributors/blob/master/team/Languages.md) ![Status](https://img.shields.io/badge/-Alpha-orange.svg)\n \n-[![Build Status](https://travis-ci.org/MycroftAI/lingua-franca.svg?branch=master)](https://travis-ci.org/MycroftAI/lingua-franca) [![Coverage Status](https://coveralls.io/repos/github/MycroftAI/lingua-franca/badge.svg?branch=master)](https://coveralls.io/github/MycroftAI/lingua-franca?branch=master)\n+[![Build Status](https://travis-ci.org/MycroftAI/mycroft-core.svg?branch=master)](https://travis-ci.org/MycroftAI/mycroft-core) [![Coverage Status](https://coveralls.io/repos/github/MycroftAI/lingua-franca/badge.svg?branch=dev)](https://coveralls.io/github/MycroftAI/lingua-franca?branch=dev)\n [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)\n [![Join chat](https://img.shields.io/badge/Mattermost-join_chat-brightgreen.svg)](https://chat.mycroft.ai/community/channels/languages)\n \ndiff --git a/setup.py b/setup.py\nindex d764562..4b9583f 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -29,7 +29,7 @@ setup(\n name='lingua_franca',\n version='0.1.0',\n packages=['test', 'lingua_franca', 'lingua_franca.lang'],\n- url='https://github.com/MycroftAI/lingua-franca',\n+ url='https://github.com/MycroftAi/lingua_franca',\n license='Apache2.0',\n package_data={'': extra_files},\n include_package_data=True,\n", "test_patch": "diff --git a/test/test_parse.py b/test/test_parse.py\nindex c1510d9..b010c5d 100644\n--- a/test/test_parse.py\n+++ b/test/test_parse.py\n@@ -477,6 +477,19 @@ class TestNormalize(unittest.TestCase):\n testExtract(\"set alarm at 7:30 on weekdays\",\n \"2017-06-27 19:30:00\", \"set alarm on weekdays\")\n \n+ # TODO this test is imperfect due to \"tonight\" in the reminder, but let is pass since the date is correct\n+ testExtract(\"lets meet tonight\",\n+ \"2017-06-27 22:00:00\", \"lets meet tonight\")\n+ # TODO this test is imperfect due to \"at night\" in the reminder, but let is pass since the date is correct\n+ testExtract(\"lets meet later at night\",\n+ \"2017-06-27 22:00:00\", \"lets meet later at night\")\n+ # TODO this test is imperfect due to \"night\" in the reminder, but let is pass since the date is correct\n+ testExtract(\"what's the weather like tomorrow night\",\n+ \"2017-06-28 22:00:00\", \"what is weather like night\")\n+ # TODO this test is imperfect due to \"night\" in the reminder, but let is pass since the date is correct\n+ testExtract(\"what's the weather like next tuesday night\",\n+ \"2017-07-04 22:00:00\", \"what is weather like night\")\n+\n def test_extract_ambiguous_time_en(self):\n morning = datetime(2017, 6, 27, 8, 1, 2)\n evening = datetime(2017, 6, 27, 20, 1, 2)\n", "FAIL_TO_PASS": ["test/test_parse.py::TestNormalize::test_extractdatetime_en"]}], "all_FAIL_TO_PASS": ["test/test_parse.py::TestNormalize::test_extractdatetime_en"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PennChopMicrobiomeProgram__illqc-17_x1", "level": 1, "source": "swerebench", "repo": "PennChopMicrobiomeProgram/illqc", "image": "swerebench/sweb.eval.x86_64.pennchopmicrobiomeprogram_1776_illqc-17:latest", "base_commit": "bc504d4c93300db446ab7b70cb0660f682d07687", "num_bugs": 1, "bugs": [{"instance_id": "PennChopMicrobiomeProgram__illqc-17", "base_commit": "bc504d4c93300db446ab7b70cb0660f682d07687", "gold_patch": "diff --git a/illqclib/main.py b/illqclib/main.py\nindex e8503bf..396d282 100644\n--- a/illqclib/main.py\n+++ b/illqclib/main.py\n@@ -67,7 +67,7 @@ class Trimmomatic(object):\n \"ILLUMINACLIP:%s:2:30:10:8:true\" % self._adapter_fp,\n \"LEADING:%d\" % self.config[\"leading\"],\n \"TRAILING:%d\" % self.config[\"trailing\"],\n- \"SLIDINGWINDOW:%d:%d\" % self.config[\"slidingwindow\"],\n+ \"SLIDINGWINDOW:%d:%d\" % tuple(self.config[\"slidingwindow\"]),\n \"MINLEN:%d\" % self.config[\"minlen\"],\n ]\n \n", "test_patch": "diff --git a/test/test_main.py b/test/test_main.py\nindex 7a75113..803ed7b 100644\n--- a/test/test_main.py\n+++ b/test/test_main.py\n@@ -26,17 +26,19 @@ class ConfigTests(unittest.TestCase):\n \n \n class TrimmomaticTests(unittest.TestCase):\n+ config_vals = {\n+ \"trimmomatic_jar_fp\": \"trimmomatic-0.30.jar\",\n+ \"adapter_dir\": \"adapters\",\n+ \"adapter\": \"NexteraPE-PE\",\n+ \"leading\": 3,\n+ \"trailing\": 3,\n+ \"slidingwindow\": (4, 15),\n+ \"minlen\": 36,\n+ \"java_heapsize\":\"200M\"\n+ }\n+\n def test_make_command(self):\n- app = Trimmomatic({\n- \"trimmomatic_jar_fp\": \"trimmomatic-0.30.jar\",\n- \"adapter_dir\": \"adapters\",\n- \"adapter\": \"NexteraPE-PE\",\n- \"leading\": 3,\n- \"trailing\": 3,\n- \"slidingwindow\": (4, 15),\n- \"minlen\": 36,\n-\t \"java_heapsize\":\"200M\"\n- })\n+ app = Trimmomatic(self.config_vals)\n observed = app.make_command(\"a.fastq\", \"b.fastq\", \"mydir\")\n expected = [\n 'java', '-Xmx200M', '-jar', 'trimmomatic-0.30.jar', 'PE', '-phred33',\n@@ -47,3 +49,18 @@ class TrimmomaticTests(unittest.TestCase):\n 'LEADING:3', 'TRAILING:3', 'SLIDINGWINDOW:4:15', 'MINLEN:36',\n ]\n self.assertEqual(observed, expected)\n+\n+ def test_make_command_sliding_window_as_list(self):\n+ config_vals = self.config_vals.copy()\n+ config_vals[\"slidingwindow\"] = [6, 32]\n+ app = Trimmomatic(config_vals)\n+ observed = app.make_command(\"a.fastq\", \"b.fastq\", \"mydir\")\n+ expected = [\n+ 'java', '-Xmx200M', '-jar', 'trimmomatic-0.30.jar', 'PE', '-phred33',\n+ 'a.fastq', 'b.fastq',\n+ 'mydir/a.fastq', 'mydir/a_unpaired.fastq',\n+ 'mydir/b.fastq', 'mydir/b_unpaired.fastq',\n+ 'ILLUMINACLIP:adapters/NexteraPE-PE.fa:2:30:10:8:true',\n+ 'LEADING:3', 'TRAILING:3', 'SLIDINGWINDOW:6:32', 'MINLEN:36',\n+ ]\n+ self.assertEqual(observed, expected)\n", "FAIL_TO_PASS": ["test/test_main.py::TrimmomaticTests::test_make_command_sliding_window_as_list"]}], "all_FAIL_TO_PASS": ["test/test_main.py::TrimmomaticTests::test_make_command_sliding_window_as_list"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "EvoluxBR__greenswitch-83_x1", "level": 1, "source": "swerebench", "repo": "EvoluxBR/greenswitch", "image": "swerebench/sweb.eval.x86_64.evoluxbr_1776_greenswitch-83:latest", "base_commit": "eb210f31ff723bba75d83b09d898f7e1273eb63b", "num_bugs": 1, "bugs": [{"instance_id": "EvoluxBR__greenswitch-83", "base_commit": "eb210f31ff723bba75d83b09d898f7e1273eb63b", "gold_patch": "diff --git a/greenswitch/esl.py b/greenswitch/esl.py\nindex ef9a397..6c25f29 100644\n--- a/greenswitch/esl.py\n+++ b/greenswitch/esl.py\n@@ -217,7 +217,7 @@ class ESLProtocol(object):\n if self.connected:\n try:\n self.send('exit')\n- except (NotConnectedError, socket.error):\n+ except (NotConnectedError, socket.error, OutboundSessionHasGoneAway):\n pass\n self._run = False\n if self._receive_events_greenlet:\n", "test_patch": "diff --git a/tests/test_outbound_session.py b/tests/test_outbound_session.py\nindex ed4086c..69205b3 100644\n--- a/tests/test_outbound_session.py\n+++ b/tests/test_outbound_session.py\n@@ -68,3 +68,13 @@ class TestWhileConnectedMethod(unittest.TestCase):\n with self.assertRaises(ValueError):\n with self.outbound_session.while_connected():\n raise ValueError(\"http exception\")\n+\n+ def test_raising_OutboundSessionHasGoneAway_in_session_stop_will_pass(self):\n+ # make outbound_session.send raise OutboundSessionHasGoneAway\n+ self.outbound_session.send = mock.MagicMock(side_effect=esl.OutboundSessionHasGoneAway)\n+ # mock sock.close\n+ self.outbound_session.sock.close = mock.MagicMock()\n+\n+ # stop and assert sock.close is called\n+ self.outbound_session.stop()\n+ assert self.outbound_session.sock.close.called\n", "FAIL_TO_PASS": ["tests/test_outbound_session.py::TestWhileConnectedMethod::test_raising_OutboundSessionHasGoneAway_in_session_stop_will_pass"]}], "all_FAIL_TO_PASS": ["tests/test_outbound_session.py::TestWhileConnectedMethod::test_raising_OutboundSessionHasGoneAway_in_session_stop_will_pass"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "CoffeaTeam__coffea-572_x1", "level": 1, "source": "swerebench", "repo": "CoffeaTeam/coffea", "image": "swerebench/sweb.eval.x86_64.coffeateam_1776_coffea-572:latest", "base_commit": "2197e71dacf329910373369dfbbb4895ef0977e1", "num_bugs": 1, "bugs": [{"instance_id": "CoffeaTeam__coffea-572", "base_commit": "2197e71dacf329910373369dfbbb4895ef0977e1", "gold_patch": "diff --git a/coffea/lumi_tools/lumi_tools.py b/coffea/lumi_tools/lumi_tools.py\nindex 932eab9f..e4d92fe2 100644\n--- a/coffea/lumi_tools/lumi_tools.py\n+++ b/coffea/lumi_tools/lumi_tools.py\n@@ -34,28 +34,6 @@ class LumiData(object):\n ], # not sure what lumi:0 means, appears to be always zero (DAQ off before beam dump?)\n },\n )\n- self.index = Dict.empty(\n- key_type=types.Tuple([types.uint32, types.uint32]), value_type=types.float64\n- )\n- self.build_lumi_table()\n-\n- def build_lumi_table(self):\n- \"\"\"Build index for numba-compiled functions\n-\n- This needs to be executed upon unpickling, it should be part of\n- a custom deserialize function.\n- \"\"\"\n- runs = self._lumidata[:, 0].astype(\"u4\")\n- lumis = self._lumidata[:, 1].astype(\"u4\")\n- LumiData._build_lumi_table_kernel(runs, lumis, self._lumidata, self.index)\n-\n- @staticmethod\n- @numba.njit(parallel=False, fastmath=False)\n- def _build_lumi_table_kernel(runs, lumis, lumidata, index):\n- for i in range(len(runs)):\n- run = runs[i]\n- lumi = lumis[i]\n- index[(run, lumi)] = float(lumidata[i, 2])\n \n def get_lumi(self, runlumis):\n \"\"\"Calculate integrated lumi\n@@ -66,12 +44,28 @@ class LumiData(object):\n A 2d numpy array of ``[[run,lumi], [run,lumi], ...]`` or `LumiList` object\n of the lumiSections to integrate over.\n \"\"\"\n+ self.index = Dict.empty(\n+ key_type=types.Tuple([types.uint32, types.uint32]), value_type=types.float64\n+ )\n+ runs = self._lumidata[:, 0].astype(\"u4\")\n+ lumis = self._lumidata[:, 1].astype(\"u4\")\n+ # fill self.index\n+ LumiData._build_lumi_table_kernel(runs, lumis, self._lumidata, self.index)\n+\n if isinstance(runlumis, LumiList):\n runlumis = runlumis.array\n tot_lumi = np.zeros((1,), dtype=np.float64)\n LumiData._get_lumi_kernel(runlumis[:, 0], runlumis[:, 1], self.index, tot_lumi)\n return tot_lumi[0]\n \n+ @staticmethod\n+ @numba.njit(parallel=False, fastmath=False)\n+ def _build_lumi_table_kernel(runs, lumis, lumidata, index):\n+ for i in range(len(runs)):\n+ run = runs[i]\n+ lumi = lumis[i]\n+ index[(run, lumi)] = float(lumidata[i, 2])\n+\n @staticmethod\n @numba.njit(parallel=False, fastmath=False)\n def _get_lumi_kernel(runs, lumis, index, tot_lumi):\n@@ -100,7 +94,7 @@ class LumiMask(object):\n with open(jsonfile) as fin:\n goldenjson = json.load(fin)\n \n- self._masks = Dict.empty(key_type=types.uint32, value_type=types.uint32[:])\n+ self._masks = {}\n \n for run, lumilist in goldenjson.items():\n mask = np.array(lumilist, dtype=np.uint32).flatten()\n@@ -123,18 +117,19 @@ class LumiMask(object):\n An array of dtype `bool` where valid (run, lumi) tuples\n will have their corresponding entry set ``True``.\n \"\"\"\n+ # fill numba typed dict\n+ _masks = Dict.empty(key_type=types.uint32, value_type=types.uint32[:])\n+ for k, v in self._masks.items():\n+ _masks[k] = v\n+\n if isinstance(runs, ak.highlevel.Array):\n runs = ak.to_numpy(runs)\n if isinstance(lumis, ak.highlevel.Array):\n lumis = ak.to_numpy(lumis)\n mask_out = np.zeros(dtype=\"bool\", shape=runs.shape)\n- LumiMask._apply_run_lumi_mask(self._masks, runs, lumis, mask_out)\n+ LumiMask._apply_run_lumi_mask_kernel(_masks, runs, lumis, mask_out)\n return mask_out\n \n- @staticmethod\n- def _apply_run_lumi_mask(masks, runs, lumis, mask_out):\n- LumiMask._apply_run_lumi_mask_kernel(masks, runs, lumis, mask_out)\n-\n # This could be run in parallel, but windows does not support it\n @staticmethod\n @numba.njit(parallel=False, fastmath=True)\n", "test_patch": "diff --git a/tests/test_lumi_tools.py b/tests/test_lumi_tools.py\nindex f8914ce4..7134615f 100644\n--- a/tests/test_lumi_tools.py\n+++ b/tests/test_lumi_tools.py\n@@ -1,5 +1,7 @@\n from __future__ import print_function, division\n \n+import cloudpickle\n+\n from coffea.lumi_tools import LumiData, LumiMask, LumiList\n from coffea.util import numpy as np\n \n@@ -10,51 +12,81 @@ def test_lumidata():\n \n lumidata = LumiData(\"tests/samples/lumi_small.csv\")\n \n- runslumis = np.zeros((10, 2), dtype=np.uint32)\n- runslumis[:, 0] = lumidata._lumidata[0:10, 0]\n- runslumis[:, 1] = lumidata._lumidata[0:10, 1]\n- lumi = lumidata.get_lumi(runslumis)\n- diff = abs(lumi - 1.539941814)\n- print(\"lumi:\", lumi, \"diff:\", diff)\n- assert diff < 1e-4\n-\n- # test build_lumi_table_kernel\n- py_index = Dict.empty(\n- key_type=types.Tuple([types.uint32, types.uint32]), value_type=types.float64\n- )\n- pyruns = lumidata._lumidata[:, 0].astype(\"u4\")\n- pylumis = lumidata._lumidata[:, 1].astype(\"u4\")\n- LumiData._build_lumi_table_kernel.py_func(\n- pyruns, pylumis, lumidata._lumidata, py_index\n- )\n-\n- assert len(py_index) == len(lumidata.index)\n+ # pickle & unpickle\n+ lumidata_pickle = cloudpickle.loads(cloudpickle.dumps(lumidata))\n \n- # test get_lumi_kernel\n- py_tot_lumi = np.zeros((1,), dtype=np.float64)\n- LumiData._get_lumi_kernel.py_func(\n- runslumis[:, 0], runslumis[:, 1], py_index, py_tot_lumi\n- )\n+ # check same internal lumidata\n+ assert np.all(lumidata._lumidata == lumidata_pickle._lumidata)\n \n- assert abs(py_tot_lumi[0] - lumi) < 1e-4\n+ runslumis = np.zeros((10, 2), dtype=np.uint32)\n+ results = {\"lumi\": {}, \"index\": {}}\n+ for ld in lumidata, lumidata_pickle:\n+ runslumis[:, 0] = ld._lumidata[0:10, 0]\n+ runslumis[:, 1] = ld._lumidata[0:10, 1]\n+ lumi = ld.get_lumi(runslumis)\n+ results[\"lumi\"][ld] = lumi\n+ diff = abs(lumi - 1.539941814)\n+ print(\"lumi:\", lumi, \"diff:\", diff)\n+ assert diff < 1e-4\n+\n+ # test build_lumi_table_kernel\n+ py_index = Dict.empty(\n+ key_type=types.Tuple([types.uint32, types.uint32]), value_type=types.float64\n+ )\n+ pyruns = ld._lumidata[:, 0].astype(\"u4\")\n+ pylumis = ld._lumidata[:, 1].astype(\"u4\")\n+ LumiData._build_lumi_table_kernel.py_func(\n+ pyruns, pylumis, ld._lumidata, py_index\n+ )\n+\n+ assert len(py_index) == len(ld.index)\n+\n+ # test get_lumi_kernel\n+ py_tot_lumi = np.zeros((1,), dtype=np.float64)\n+ LumiData._get_lumi_kernel.py_func(\n+ runslumis[:, 0], runslumis[:, 1], py_index, py_tot_lumi\n+ )\n+\n+ assert abs(py_tot_lumi[0] - lumi) < 1e-4\n+\n+ # store results:\n+ results[\"lumi\"][ld] = lumi\n+ results[\"index\"][ld] = ld.index\n+\n+ assert np.all(results[\"lumi\"][lumidata] == results[\"lumi\"][lumidata_pickle])\n+ assert len(results[\"index\"][lumidata]) == len(results[\"index\"][lumidata_pickle])\n \n \n def test_lumimask():\n lumimask = LumiMask(\n \"tests/samples/Cert_294927-306462_13TeV_EOY2017ReReco_Collisions17_JSON.txt\"\n )\n+\n+ # pickle & unpickle\n+ lumimask_pickle = cloudpickle.loads(cloudpickle.dumps(lumimask))\n+\n+ # check same mask keys\n+ keys = lumimask._masks.keys()\n+ assert keys == lumimask_pickle._masks.keys()\n+ # check same mask values\n+ assert all(np.all(lumimask._masks[k] == lumimask_pickle._masks[k]) for k in keys)\n+\n runs = np.array([303825, 123], dtype=np.uint32)\n lumis = np.array([115, 123], dtype=np.uint32)\n- mask = lumimask(runs, lumis)\n- print(\"mask:\", mask)\n- assert mask[0]\n- assert not mask[1]\n \n- # test underlying py_func\n- py_mask = np.zeros(dtype=\"bool\", shape=runs.shape)\n- LumiMask._apply_run_lumi_mask_kernel.py_func(lumimask._masks, runs, lumis, py_mask)\n+ for lm in lumimask, lumimask_pickle:\n+ mask = lm(runs, lumis)\n+ print(\"mask:\", mask)\n+ assert mask[0]\n+ assert not mask[1]\n+\n+ # test underlying py_func\n+ py_mask = np.zeros(dtype=\"bool\", shape=runs.shape)\n+ LumiMask._apply_run_lumi_mask_kernel.py_func(lm._masks, runs, lumis, py_mask)\n+\n+ assert np.all(mask == py_mask)\n \n- assert np.all(mask == py_mask)\n+ assert np.all(lumimask(runs, lumis) == lumimask_pickle(runs, lumis))\n \n \n def test_lumilist():\n", "FAIL_TO_PASS": ["tests/test_lumi_tools.py::test_lumidata", "tests/test_lumi_tools.py::test_lumimask"]}], "all_FAIL_TO_PASS": ["tests/test_lumi_tools.py::test_lumidata", "tests/test_lumi_tools.py::test_lumimask"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "M0r13n__pyais-122_x1", "level": 1, "source": "swerebench", "repo": "M0r13n/pyais", "image": "swerebench/sweb.eval.x86_64.m0r13n_1776_pyais-122:latest", "base_commit": "d981d9915dfdf5ca7377afaf3bae051d975095c1", "num_bugs": 1, "bugs": [{"instance_id": "M0r13n__pyais-122", "base_commit": "d981d9915dfdf5ca7377afaf3bae051d975095c1", "gold_patch": "diff --git a/CHANGELOG.txt b/CHANGELOG.txt\nindex e74cd58..8ff882a 100644\n--- a/CHANGELOG.txt\n+++ b/CHANGELOG.txt\n@@ -1,6 +1,11 @@\n ====================\n pyais CHANGELOG\n ====================\n+-------------------------------------------------------------------------------\n+ Version 2.5.7 29 Jul 2023\n+-------------------------------------------------------------------------------\n+* bug fix: EpfdType Enum Missing InternalGNSS\n+ * closes https://github.com/M0r13n/pyais/issues/121\n -------------------------------------------------------------------------------\n Version 2.5.6 29 Jul 2023\n -------------------------------------------------------------------------------\ndiff --git a/pyais/__init__.py b/pyais/__init__.py\nindex 0e2e01e..498d89b 100644\n--- a/pyais/__init__.py\n+++ b/pyais/__init__.py\n@@ -5,7 +5,7 @@ from pyais.decode import decode\n from pyais.tracker import AISTracker, AISTrack\n \n __license__ = 'MIT'\n-__version__ = '2.5.6'\n+__version__ = '2.5.7'\n __author__ = 'Leon Morten Richter'\n \n __all__ = (\ndiff --git a/pyais/constants.py b/pyais/constants.py\nindex 65726df..016882f 100644\n--- a/pyais/constants.py\n+++ b/pyais/constants.py\n@@ -90,6 +90,7 @@ class EpfdType(IntEnum):\n IntegratedNavigationSystem = 6\n Surveyed = 7\n Galileo = 8\n+ Internal_GNSS = 15\n \n @classmethod\n def _missing_(cls, value: object) -> int:\ndiff --git a/pyais/messages.py b/pyais/messages.py\nindex fd0ee3b..c819129 100644\n--- a/pyais/messages.py\n+++ b/pyais/messages.py\n@@ -573,7 +573,7 @@ class Payload(abc.ABC):\n \n d_type = field.metadata['d_type']\n \n- if type(val) == d_type:\n+ if isinstance(val, d_type):\n # The value is already of the correct type -> nothing to do\n return val\n \n", "test_patch": "diff --git a/tests/test_decode.py b/tests/test_decode.py\nindex d5610f3..426f1f2 100644\n--- a/tests/test_decode.py\n+++ b/tests/test_decode.py\n@@ -241,8 +241,8 @@ class TestAIS(unittest.TestCase):\n assert msg[\"hour\"] == 10\n assert msg[\"minute\"] == 41\n assert msg[\"second\"] == 11\n- assert msg[\"epfd\"] == 0\n- assert msg[\"epfd\"] == EpfdType.Undefined\n+ assert msg[\"epfd\"] == 15\n+ assert msg[\"epfd\"] == EpfdType.Internal_GNSS\n \n ensure_type_for_msg_dict(msg)\n \n@@ -298,11 +298,7 @@ class TestAIS(unittest.TestCase):\n assert msg[\"mmsi\"] == 366999712\n assert msg[\"dac\"] == 366\n assert msg[\"fid\"] == 56\n- assert (\n- msg[\"data\"]\n- == b\"\\x3a\\x53\\xdb\\xb7\\xbe\\x4a\\x77\\x31\\x37\\xf8\\x7d\\x7b\\x04\\x45\\xf0\\x40\"\n- b\"\\xde\\xa0\\x5d\\x93\\xf5\\x93\\x78\\x31\\x94\\xae\\x9b\\x9d\\x9d\\xbe\\x05\\xfb\"\n- )\n+ assert msg[\"data\"] == b\"\\x3a\\x53\\xdb\\xb7\\xbe\\x4a\\x77\\x31\\x37\\xf8\\x7d\\x7b\\x04\\x45\\xf0\\x40\\xde\\xa0\\x5d\\x93\\xf5\\x93\\x78\\x31\\x94\\xae\\x9b\\x9d\\x9d\\xbe\\x05\\xfb\"\n \n ensure_type_for_msg_dict(msg)\n \n@@ -318,10 +314,7 @@ class TestAIS(unittest.TestCase):\n assert msg[\"mmsi\"] == 888888888\n assert msg[\"dac\"] == 0\n assert msg[\"fid\"] == 0\n- assert (\n- msg[\"data\"]\n- == b\"\\x02\\x934D\\x81nI;\\xbd\\xcd\\xe5\\xb7E\\xed\\xf1]\\xc0[y\\xfa#-\\xcd<\\x01\\x05\\x91\\xef\\x85\\x92\\xfbF\\xed\\x19t\\x11\\xd6\\xe7\\xdf\\xec\\x1fp\\x97\\x99\\x83M\\x8aK\\xb8\\x005'\\x1f\\xc7\\x14\\xeaTr\\xe3o\\xb8\\xda\\xb9\\x17-FJxb\\xeb5\\x1aM\"\n- )\n+ assert msg[\"data\"] == b\"\\x02\\x934D\\x81nI;\\xbd\\xcd\\xe5\\xb7E\\xed\\xf1]\\xc0[y\\xfa#-\\xcd<\\x01\\x05\\x91\\xef\\x85\\x92\\xfbF\\xed\\x19t\\x11\\xd6\\xe7\\xdf\\xec\\x1fp\\x97\\x99\\x83M\\x8aK\\xb8\\x005'\\x1f\\xc7\\x14\\xeaTr\\xe3o\\xb8\\xda\\xb9\\x17-FJxb\\xeb5\\x1aM\"\n \n ensure_type_for_msg_dict(msg)\n \n@@ -463,14 +456,8 @@ class TestAIS(unittest.TestCase):\n data = msg[\"data\"]\n bits = bytes2bits(data).to01()\n \n- assert (\n- data\n- == b'|\\x05V\\xc0p1\\xfe\\xbb\\xf5)$\\xfe3\\xfa)3\\xff\\xa0\\xfd)2\\xfd\\xb7\\x06)\"\\xfe8\\t)*\\xfd\\xe9\\x12))\\xfc\\xf7\\x00)#\\xff\\xd2\\x0c)\\xaa\\xaa'\n- )\n- assert (\n- bits\n- == \"0111110000000101010101101100000001110000001100011111111010111011111101010010100100100100111111100011001111111010001010010011001111111111101000001111110100101001001100101111110110110111000001100010100100100010111111100011100000001001001010010010101011111101111010010001001000101001001010011111110011110111000000000010100100100011111111111101001000001100001010011010101010101010\"\n- )\n+ assert data == b'|\\x05V\\xc0p1\\xfe\\xbb\\xf5)$\\xfe3\\xfa)3\\xff\\xa0\\xfd)2\\xfd\\xb7\\x06)\"\\xfe8\\t)*\\xfd\\xe9\\x12))\\xfc\\xf7\\x00)#\\xff\\xd2\\x0c)\\xaa\\xaa'\n+ assert bits == \"0111110000000101010101101100000001110000001100011111111010111011111101010010100100100100111111100011001111111010001010010011001111111111101000001111110100101001001100101111110110110111000001100010100100100010111111100011100000001001001010010010101011111101111010010001001000101001001010011111110011110111000000000010100100100011111111111101001000001100001010011010101010101010\"\n \n ensure_type_for_msg_dict(msg)\n \n@@ -488,10 +475,7 @@ class TestAIS(unittest.TestCase):\n bits = bytes2bits(data).to01()\n \n assert data == b\"&\\xb8`\\xa1 \\x00\\xfc\\x90\\x0bY\\x15\\xfc\\x8a\\rR\\x00TWn~\\xc8\\x00\"\n- assert (\n- bits\n- == \"00100110101110000110000010100001001000000000000011111100100100000000101101011001000101011111110010001010000011010101001000000000010101000101011101101110011111101100100000000000\"\n- )\n+ assert bits == \"00100110101110000110000010100001001000000000000011111100100100000000101101011001000101011111110010001010000011010101001000000000010101000101011101101110011111101100100000000000\"\n \n ensure_type_for_msg_dict(msg)\n \n@@ -753,10 +737,7 @@ class TestAIS(unittest.TestCase):\n assert msg[\"addressed\"]\n assert msg[\"structured\"]\n assert msg[\"dest_mmsi\"] == 838351848\n- assert (\n- msg[\"data\"]\n- == b\"\\xcc\\xbf\\x02\\xa1p\\xe7\\x8b\\x00\\x1c\\x01\\xb3\\xc0\\x9b\\x03\\xd2 \\xbe\\xab@\\x04\\x00\\x00\"\n- )\n+ assert msg[\"data\"] == b\"\\xcc\\xbf\\x02\\xa1p\\xe7\\x8b\\x00\\x1c\\x01\\xb3\\xc0\\x9b\\x03\\xd2 \\xbe\\xab@\\x04\\x00\\x00\"\n \n ensure_type_for_msg_dict(msg)\n \n@@ -794,10 +775,7 @@ class TestAIS(unittest.TestCase):\n \n def test_broken_messages(self):\n # Undefined epfd\n- assert (\n- decode(b\"!AIVDM,1,1,,B,4>O7m7Iu@<9qUfbtm`vSnwvH20S8,0*46\").asdict()[\"epfd\"]\n- == EpfdType.Undefined\n- )\n+ assert decode(b\"!AIVDM,1,1,,B,4>O7m7Iu@<9qUfbtm`vSnwvH20S8,0*46\").asdict()[\"epfd\"] == EpfdType.Undefined\n \n def test_multiline_message(self):\n # these messages caused issue #3\ndiff --git a/tests/test_file_stream.py b/tests/test_file_stream.py\nindex b7f301c..cbe1676 100644\n--- a/tests/test_file_stream.py\n+++ b/tests/test_file_stream.py\n@@ -136,14 +136,14 @@ class TestFileReaderStream(unittest.TestCase):\n \n self.assertEqual(len(messages), 7)\n for msg in messages:\n- assert type(msg) == NMEAMessage\n+ assert isinstance(msg, NMEAMessage)\n assert msg.is_valid\n assert msg.decode() is not None\n \n def test_reader_with_open(self):\n with FileReaderStream(self.FILENAME) as stream:\n msg = next(stream)\n- assert type(msg) == NMEAMessage\n+ assert isinstance(msg, NMEAMessage)\n assert msg.is_valid\n assert msg.decode() is not None\n \n", "FAIL_TO_PASS": ["tests/test_decode.py::TestAIS::test_msg_type_4_b"]}], "all_FAIL_TO_PASS": ["tests/test_decode.py::TestAIS::test_msg_type_4_b"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "CartoDB__cartoframes-379_x1", "level": 1, "source": "swerebench", "repo": "CartoDB/cartoframes", "image": "swerebench/sweb.eval.x86_64.cartodb_1776_cartoframes-379:latest", "base_commit": "86069f44058986062a2af21ef1f6690864784596", "num_bugs": 1, "bugs": [{"instance_id": "CartoDB__cartoframes-379", "base_commit": "86069f44058986062a2af21ef1f6690864784596", "gold_patch": "diff --git a/cartoframes/layer.py b/cartoframes/layer.py\nindex 6ddaa641..49143e33 100644\n--- a/cartoframes/layer.py\n+++ b/cartoframes/layer.py\n@@ -60,9 +60,7 @@ class BaseMap(AbstractLayer):\n \n self.source = source\n self.labels = labels\n- stem = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n- if source == 'voyager':\n- stem += 'rastertiles'\n+ stem = 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n \n if self.is_basic():\n if only_labels:\n", "test_patch": "diff --git a/test/test_layer.py b/test/test_layer.py\nindex e24117b4..c10e2133 100644\n--- a/test/test_layer.py\n+++ b/test/test_layer.py\n@@ -69,32 +69,32 @@ class TestBaseMap(unittest.TestCase):\n # ensure correct BaseMap urls are created\n # See URLs here: https://carto.com/location-data-services/basemaps/\n self.assertEqual(self.dark_map_all.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n 'dark_all/{z}/{x}/{y}.png')\n self.assertEqual(self.light_map_all.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n 'light_all/{z}/{x}/{y}.png')\n self.assertEqual(self.voyager_labels_under.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n- 'rastertiles/voyager_labels_under/{z}/{x}/{y}.png')\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n+ 'voyager_labels_under/{z}/{x}/{y}.png')\n self.assertEqual(self.dark_map_no_labels.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n 'dark_nolabels/{z}/{x}/{y}.png')\n self.assertEqual(self.light_map_no_labels.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n 'light_nolabels/{z}/{x}/{y}.png')\n self.assertEqual(self.voyager_map_no_labels.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n- 'rastertiles/voyager_nolabels/{z}/{x}/{y}.png')\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n+ 'voyager_nolabels/{z}/{x}/{y}.png')\n self.assertEqual(self.light_only_labels.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n 'light_only_labels/{z}/{x}/{y}.png')\n self.assertEqual(self.dark_only_labels.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n 'dark_only_labels/{z}/{x}/{y}.png')\n self.assertEqual(self.voyager_only_labels.url,\n- 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/'\n- 'rastertiles/voyager_only_labels/{z}/{x}/{y}.png')\n+ 'https://{s}.basemaps.cartocdn.com/rastertiles/'\n+ 'voyager_only_labels/{z}/{x}/{y}.png')\n \n # ensure self.is_basic() works as intended\n self.assertTrue(self.light_map_all.is_basic(),\ndiff --git a/test/test_maps.py b/test/test_maps.py\nindex 1e3819ce..429feac2 100644\n--- a/test/test_maps.py\n+++ b/test/test_maps.py\n@@ -62,111 +62,110 @@ class TestMaps(unittest.TestCase):\n map_name = get_map_name(self.layers,\n has_zoom=False)\n self.assertEqual(\n- map_name,\n- 'cartoframes_ver20170406_layers2_time0_baseid1_labels0_zoom0')\n+ map_name,\n+ 'cartoframes_ver20170406_layers2_time0_baseid1_labels0_zoom0')\n self.assertEqual(\n- get_map_name(self.layers, has_zoom=True),\n- 'cartoframes_ver20170406_layers2_time0_baseid1_labels0_zoom1')\n+ get_map_name(self.layers, has_zoom=True),\n+ 'cartoframes_ver20170406_layers2_time0_baseid1_labels0_zoom1')\n self.assertEqual(\n- get_map_name(self.layers_w_time, has_zoom=False),\n- 'cartoframes_ver20170406_layers3_time1_baseid1_labels1_zoom0')\n+ get_map_name(self.layers_w_time, has_zoom=False),\n+ 'cartoframes_ver20170406_layers3_time1_baseid1_labels1_zoom0')\n \n def test_map_template(self):\n \"\"\"maps.map_template_dict\"\"\"\n map_template = get_map_template(self.layers, has_zoom=False)\n- js = {\n- \"placeholders\": {\n- \"north\": {\n- \"default\": 45,\n- \"type\": \"number\"\n- },\n- \"cartocss_1\": {\n- \"default\": (\"#layer { \"\n- \"marker-fill: red; \"\n- \"marker-width: 5; \"\n- \"marker-allow-overlap: true; \"\n- \"marker-line-color: #000; \"\n- \"}\"),\n- \"type\": \"sql_ident\"\n- },\n- \"cartocss_0\": {\n- \"default\": (\"#layer { \"\n- \"marker-fill: red; \"\n- \"marker-width: 5; \"\n- \"marker-allow-overlap: true; \"\n- \"marker-line-color: #000; }\"),\n- \"type\": \"sql_ident\"\n- },\n- \"west\": {\n- \"default\": -45,\n- \"type\": \"number\"\n- },\n- \"east\": {\n- \"default\": 45,\n- \"type\": \"number\"\n- },\n- \"sql_0\": {\n- \"default\": (\"SELECT ST_PointFromText('POINT(0 0)', \"\n- \"4326) AS the_geom, 1 AS cartodb_id, \"\n- \"ST_PointFromText('Point(0 0)', 3857) AS \"\n- \"the_geom_webmercator\"),\n- \"type\": \"sql_ident\"\n- },\n- \"sql_1\": {\n- \"default\": (\"SELECT ST_PointFromText('POINT(0 0)', \"\n- \"4326) AS the_geom, 1 AS cartodb_id, \"\n- \"ST_PointFromText('Point(0 0)', 3857) AS \"\n- \"the_geom_webmercator\"),\n- \"type\": \"sql_ident\"\n- },\n- \"south\": {\n- \"default\": -45,\n- \"type\": \"number\"\n+ filledtemplate = {\n+ \"placeholders\": {\n+ \"north\": {\n+ \"default\": 45,\n+ \"type\": \"number\"\n+ },\n+ \"cartocss_1\": {\n+ \"default\": (\"#layer { \"\n+ \"marker-fill: red; \"\n+ \"marker-width: 5; \"\n+ \"marker-allow-overlap: true; \"\n+ \"marker-line-color: #000; \"\n+ \"}\"),\n+ \"type\": \"sql_ident\"\n+ },\n+ \"cartocss_0\": {\n+ \"default\": (\"#layer { \"\n+ \"marker-fill: red; \"\n+ \"marker-width: 5; \"\n+ \"marker-allow-overlap: true; \"\n+ \"marker-line-color: #000; }\"),\n+ \"type\": \"sql_ident\"\n+ },\n+ \"west\": {\n+ \"default\": -45,\n+ \"type\": \"number\"\n+ },\n+ \"east\": {\n+ \"default\": 45,\n+ \"type\": \"number\"\n+ },\n+ \"sql_0\": {\n+ \"default\": (\"SELECT ST_PointFromText('POINT(0 0)', \"\n+ \"4326) AS the_geom, 1 AS cartodb_id, \"\n+ \"ST_PointFromText('Point(0 0)', 3857) AS \"\n+ \"the_geom_webmercator\"),\n+ \"type\": \"sql_ident\"\n+ },\n+ \"sql_1\": {\n+ \"default\": (\"SELECT ST_PointFromText('POINT(0 0)', \"\n+ \"4326) AS the_geom, 1 AS cartodb_id, \"\n+ \"ST_PointFromText('Point(0 0)', 3857) AS \"\n+ \"the_geom_webmercator\"),\n+ \"type\": \"sql_ident\"\n+ },\n+ \"south\": {\n+ \"default\": -45,\n+ \"type\": \"number\"\n+ }\n+ },\n+ \"version\": \"0.0.1\",\n+ \"name\": (\"cartoframes_ver20170406_layers2_time0_baseid1_\"\n+ \"labels0_zoom0\"),\n+ \"layergroup\": {\n+ \"layers\": [\n+ {\n+ \"type\": \"http\",\n+ \"options\": {\n+ \"urlTemplate\": (\"https://{s}.basemaps.\"\n+ \"cartocdn.com/rastertiles\"\n+ \"/dark_all/{z}/{x}/{y}.\"\n+ \"png\"),\n+ \"subdomains\": \"abcd\"\n }\n },\n- \"version\": \"0.0.1\",\n- \"name\": (\"cartoframes_ver20170406_layers2_time0_baseid1_\"\n- \"labels0_zoom0\"),\n- \"layergroup\": {\n- \"layers\": [\n- {\n- \"type\": \"http\",\n- \"options\": {\n- \"urlTemplate\": (\"https://cartodb-basemaps-\"\n- \"{s}.global.ssl.fastly.net\"\n- \"/dark_all/{z}/{x}/{y}.\"\n- \"png\"),\n- \"subdomains\": \"abcd\"\n- }\n- },\n- {\n- \"type\": \"mapnik\",\n- \"options\": {\n- \"cartocss\": \"<%= cartocss_0 %>\",\n- \"sql\": \"<%= sql_0 %>\",\n- \"cartocss_version\": \"2.1.1\"\n- }\n- },\n- {\n- \"type\": \"mapnik\",\n- \"options\": {\n- \"cartocss\": \"<%= cartocss_1 %>\",\n- \"sql\": \"<%= sql_1 %>\",\n- \"cartocss_version\": \"2.1.1\"\n- }\n- }\n- ],\n- \"version\": \"1.0.1\"\n- },\n- \"view\": {\n- \"bounds\": {\n- \"west\": \"<%= west %>\",\n- \"east\": \"<%= east %>\",\n- \"north\": \"<%= north %>\",\n- \"south\": \"<%= south %>\"\n- }\n+ {\n+ \"type\": \"mapnik\",\n+ \"options\": {\n+ \"cartocss\": \"<%= cartocss_0 %>\",\n+ \"sql\": \"<%= sql_0 %>\",\n+ \"cartocss_version\": \"2.1.1\"\n }\n+ },\n+ {\n+ \"type\": \"mapnik\",\n+ \"options\": {\n+ \"cartocss\": \"<%= cartocss_1 %>\",\n+ \"sql\": \"<%= sql_1 %>\",\n+ \"cartocss_version\": \"2.1.1\"\n+ }\n+ }],\n+ \"version\": \"1.0.1\"\n+ },\n+ \"view\": {\n+ \"bounds\": {\n+ \"west\": \"<%= west %>\",\n+ \"east\": \"<%= east %>\",\n+ \"north\": \"<%= north %>\",\n+ \"south\": \"<%= south %>\"\n }\n+ }\n+ }\n \n map_template_dict = json.loads(map_template)\n- self.assertDictEqual(map_template_dict, js)\n+ self.assertDictEqual(map_template_dict, filledtemplate)\n", "FAIL_TO_PASS": ["test/test_layer.py::TestBaseMap::test_basemap_source", "test/test_maps.py::TestMaps::test_map_template"]}], "all_FAIL_TO_PASS": ["test/test_layer.py::TestBaseMap::test_basemap_source", "test/test_maps.py::TestMaps::test_map_template"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Scille__umongo-170_x1", "level": 1, "source": "swerebench", "repo": "Scille/umongo", "image": "swerebench/sweb.eval.x86_64.scille_1776_umongo-170:latest", "base_commit": "3e765b3aa7250564c2eabddd1e776e6c806fa7fa", "num_bugs": 1, "bugs": [{"instance_id": "Scille__umongo-170", "base_commit": "3e765b3aa7250564c2eabddd1e776e6c806fa7fa", "gold_patch": "diff --git a/HISTORY.rst b/HISTORY.rst\nindex 1b69669..d10faee 100644\n--- a/HISTORY.rst\n+++ b/HISTORY.rst\n@@ -7,7 +7,14 @@ dev\n * ``missing`` attribute is no longer used in umongo fields, only ``default`` is\n used. ``marshmallow_missing`` and ``marshmallow_default`` attribute can be\n used to overwrite the value to use in the pure marshmallow field returned\n- by `as_marshmallow_field` method.\n+ by ``as_marshmallow_field`` method.\n+* ``as_marshmallow_field`` does not pass ``load_from``, ``dump_to`` and\n+ ``attribute`` to the pure marshmallow field anymore. It only passes\n+ ``validate``, ``required``, ``allow_none``, ``dump_only``, ``load_only`` and\n+ ``error_messages``, as well as ``default`` and ``missing`` values inferred\n+ from umongo's ``default``. Parameters prefixed with ``marshmallow_`` in the\n+ umongo field are passed to the pure marshmallow field and override their\n+ non-prefixed counterpart.\n \n 1.2.0 (2019-02-08)\n ------------------\ndiff --git a/umongo/abstract.py b/umongo/abstract.py\nindex a8a1096..0778836 100644\n--- a/umongo/abstract.py\n+++ b/umongo/abstract.py\n@@ -117,7 +117,29 @@ class BaseField(ma_fields.Field):\n \"generating pure Marshmallow field.\")\n if 'default' in kwargs:\n kwargs['missing'] = kwargs['default']\n+\n+ # Store attributes prefixed with marshmallow_ to use them when\n+ # creating pure marshmallow Schema\n+ for attribute in (\n+ 'load_from', 'dump_to', 'attribute',\n+ 'validate', 'required', 'allow_none',\n+ 'load_only', 'dump_only', 'error_messages'\n+ ):\n+ attribute = 'marshmallow_' + attribute\n+ if attribute in kwargs:\n+ setattr(self, attribute, kwargs.pop(attribute))\n+\n+ # Infer from \"default\" parameter a default value for\n+ # marshmallow_default and marshmallow_missing\n+ def serialize_default():\n+ val = self.default() if callable(self.default) else self.default\n+ return self.serialize('foo', {'foo': val})\n+\n+ self.marshmallow_missing = kwargs.pop('marshmallow_missing', serialize_default)\n+ self.marshmallow_default = kwargs.pop('marshmallow_default', serialize_default)\n+\n super().__init__(*args, **kwargs)\n+\n # Overwrite error_messages to handle i18n translation\n self.error_messages = I18nErrorDict(self.error_messages)\n # `io_validate` will be run after `io_validate_resursive`\n@@ -128,13 +150,6 @@ class BaseField(ma_fields.Field):\n self.unique = unique\n self.instance = instance\n \n- def serialize_default():\n- val = self.default() if callable(self.default) else self.default\n- return self.serialize('foo', {'foo': val})\n-\n- self.marshmallow_missing = kwargs.get('marshmallow_missing', serialize_default)\n- self.marshmallow_default = kwargs.get('marshmallow_default', serialize_default)\n-\n def __repr__(self):\n return ('\n # Released under the \"Modified BSD Licence\" (see COPYING).\n \n+from __future__ import absolute_import, division\n+\n from six.moves import zip as izip\n \n import numpy\n@@ -232,7 +234,7 @@ def smooth(x, window_len=11, window='flat'):\n \n s = numpy.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]\n y = numpy.convolve(w/w.sum(), s, mode='valid')\n- return y[(window_len-1)/2:-(window_len-1)/2] # take off repeats on ends\n+ return y[(window_len-1)//2:-(window_len-1)//2] # take off repeats on ends\n \n def smoothing_window_length(resolution, t):\n \"\"\"Compute the length of a smooting window of *resolution* time units.\n", "test_patch": "diff --git a/src/numkit/tests/test_timeseries.py b/src/numkit/tests/test_timeseries.py\nindex b10d443..140d39d 100644\n--- a/src/numkit/tests/test_timeseries.py\n+++ b/src/numkit/tests/test_timeseries.py\n@@ -47,5 +47,8 @@ class TestRegularizedFunction(object):\n # assert_almost_equal(np.max(Y), np.max(data[1]))\n # add test for Y data (but has randomness)\n \n-\n-\n+@pytest.mark.parametrize('window', (\n+ 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'))\n+def test_smooth(data, window):\n+ a = numkit.timeseries.smooth(data[1], window=window)\n+ assert len(a) == len(data[1])\n", "FAIL_TO_PASS": ["src/numkit/tests/test_timeseries.py::test_smooth[flat]", "src/numkit/tests/test_timeseries.py::test_smooth[hanning]", "src/numkit/tests/test_timeseries.py::test_smooth[hamming]", "src/numkit/tests/test_timeseries.py::test_smooth[bartlett]", "src/numkit/tests/test_timeseries.py::test_smooth[blackman]"]}], "all_FAIL_TO_PASS": ["src/numkit/tests/test_timeseries.py::test_smooth[flat]", "src/numkit/tests/test_timeseries.py::test_smooth[hanning]", "src/numkit/tests/test_timeseries.py::test_smooth[hamming]", "src/numkit/tests/test_timeseries.py::test_smooth[bartlett]", "src/numkit/tests/test_timeseries.py::test_smooth[blackman]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "DOV-Vlaanderen__pydov-211_x1", "level": 1, "source": "swerebench", "repo": "DOV-Vlaanderen/pydov", "image": "swerebench/sweb.eval.x86_64.dov-vlaanderen_1776_pydov-211:latest", "base_commit": "325fad8fd06d5b2077366869c2f5a0017d59941b", "num_bugs": 1, "bugs": [{"instance_id": "DOV-Vlaanderen__pydov-211", "base_commit": "325fad8fd06d5b2077366869c2f5a0017d59941b", "gold_patch": "diff --git a/pydov/util/query.py b/pydov/util/query.py\nindex f7cd9a2..dae02b5 100644\n--- a/pydov/util/query.py\n+++ b/pydov/util/query.py\n@@ -7,7 +7,7 @@ from owslib.fes import (\n )\n \n \n-class PropertyInList(Or):\n+class PropertyInList(object):\n \"\"\"Filter expression to test whether a given property has one of the\n values from a list.\n \n@@ -33,19 +33,30 @@ class PropertyInList(Or):\n Raises\n ------\n ValueError\n- If the given list does not contain at least two distinct items.\n+ If the given list does not contain at least a single item.\n \n \"\"\"\n if not isinstance(lst, list) and not isinstance(lst, set):\n raise ValueError('list should be of type \"list\" or \"set\"')\n \n- if len(set(lst)) < 2:\n- raise ValueError('list should contain at least two different '\n- 'elements.')\n+ if len(set(lst)) < 1:\n+ raise ValueError('list should contain at least a single item')\n+ elif len(set(lst)) == 1:\n+ self.query = PropertyIsEqualTo(propertyname, set(lst).pop())\n+ else:\n+ self.query = Or(\n+ [PropertyIsEqualTo(propertyname, i) for i in set(lst)])\n \n- super(PropertyInList, self).__init__(\n- [PropertyIsEqualTo(propertyname, i) for i in set(lst)]\n- )\n+ def toXML(self):\n+ \"\"\"Return the XML representation of the PropertyInList query.\n+\n+ Returns\n+ -------\n+ xml : etree.ElementTree\n+ XML representation of the PropertyInList\n+\n+ \"\"\"\n+ return self.query.toXML()\n \n \n class Join(PropertyInList):\n@@ -83,9 +94,8 @@ class Join(PropertyInList):\n If `using` is None and the `on` column is not present in the\n dataframe.\n \n- If the dataframe does not contain at least two different values\n- in the `using` column. A Join is probably overkill here,\n- use PropertyIsEqualTo instead.\n+ If the dataframe does not contain at least a single non-null value\n+ in the `using` column.\n \n \"\"\"\n if using is None:\n@@ -98,8 +108,8 @@ class Join(PropertyInList):\n \n value_list = list(dataframe[using].dropna().unique())\n \n- if len(set(value_list)) < 2:\n- raise ValueError(\"dataframe should contain at least two \"\n- \"different values in column '{}'.\".format(using))\n+ if len(set(value_list)) < 1:\n+ raise ValueError(\"dataframe should contain at least a single \"\n+ \"value in column '{}'.\".format(using))\n \n super(Join, self).__init__(on, value_list)\n", "test_patch": "diff --git a/tests/test_util_query.py b/tests/test_util_query.py\nindex c14c1ed..750acc3 100644\n--- a/tests/test_util_query.py\n+++ b/tests/test_util_query.py\n@@ -1,5 +1,6 @@\n \"\"\"Module grouping tests for the pydov.util.query module.\"\"\"\n import pandas as pd\n+import numpy as np\n import pytest\n \n from pydov.util.query import (\n@@ -67,26 +68,63 @@ class TestPropertyInList(object):\n \n assert len(l_output) == 0\n \n- def test_tooshort(self):\n+ def test_list_single(self):\n \"\"\"Test the PropertyInList expression with a list containing\n a single item.\n \n- Test whether a ValueError is raised.\n+ Test whether the generated query is correct and does contain only a\n+ single PropertyIsEqualTo.\n \n \"\"\"\n- with pytest.raises(ValueError):\n- l = ['a']\n- PropertyInList('methode', l)\n+ l = ['a']\n+\n+ query = PropertyInList('methode', l)\n+ xml = query.toXML()\n+\n+ assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'\n+\n+ propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')\n+ assert propertyname.text == 'methode'\n \n- def test_tooshort_duplicate(self):\n+ literal = xml.find('./{http://www.opengis.net/ogc}Literal')\n+ assert literal.text in l\n+\n+ l.remove(literal.text)\n+ assert len(l) == 0\n+\n+ def test_list_single_duplicate(self):\n \"\"\"Test the PropertyInList expression with a list containing\n- a two identical items.\n+ a single duplicated item.\n+\n+ Test whether the generated query is correct and does contain only a\n+ single PropertyIsEqualTo.\n+\n+ \"\"\"\n+ l = ['a', 'a']\n+ l_output = ['a']\n+\n+ query = PropertyInList('methode', l)\n+ xml = query.toXML()\n+\n+ assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'\n+\n+ propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')\n+ assert propertyname.text == 'methode'\n+\n+ literal = xml.find('./{http://www.opengis.net/ogc}Literal')\n+ assert literal.text in l_output\n+\n+ l_output.remove(literal.text)\n+ assert len(l_output) == 0\n+\n+ def test_emptylist(self):\n+ \"\"\"Test the PropertyInList expression with an empty list.\n \n Test whether a ValueError is raised.\n \n \"\"\"\n with pytest.raises(ValueError):\n- l = ['a', 'a']\n+ l = []\n PropertyInList('methode', l)\n \n def test_nolist(self):\n@@ -194,38 +232,77 @@ class TestJoin(object):\n \n Join(df, 'pkey_sondering')\n \n- def test_tooshort(self):\n+ def test_single(self):\n \"\"\"Test the Join expression with a dataframe containing a single row.\n \n- Test whether a ValueError is raised.\n+ Test whether the generated query is correct and does contain only a\n+ single PropertyIsEqualTo.\n \n \"\"\"\n- with pytest.raises(ValueError):\n- l = ['https://www.dov.vlaanderen.be/data/boring/1986-068853']\n+ l = ['https://www.dov.vlaanderen.be/data/boring/1986-068853']\n \n- df = pd.DataFrame({\n- 'pkey_boring': pd.Series(l),\n- 'diepte_tot_m': pd.Series([10])\n- })\n+ df = pd.DataFrame({\n+ 'pkey_boring': pd.Series(l),\n+ 'diepte_tot_m': pd.Series([10])\n+ })\n \n- Join(df, 'pkey_boring')\n+ query = Join(df, 'pkey_boring')\n+ xml = query.toXML()\n+\n+ assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'\n+\n+ propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')\n+ assert propertyname.text == 'pkey_boring'\n \n- def test_tooshort_duplicate(self):\n+ literal = xml.find('./{http://www.opengis.net/ogc}Literal')\n+ assert literal.text in l\n+\n+ l.remove(literal.text)\n+ assert len(l) == 0\n+\n+ def test_single_duplicate(self):\n \"\"\"Test the Join expression with a dataframe containing two\n identical keys.\n \n- Test whether a ValueError is raised.\n+ Test whether the generated query is correct and does contain only a\n+ single PropertyIsEqualTo.\n \n \"\"\"\n- with pytest.raises(ValueError):\n- l = ['https://www.dov.vlaanderen.be/data/boring/1986-068853',\n- 'https://www.dov.vlaanderen.be/data/boring/1986-068853']\n+ l = ['https://www.dov.vlaanderen.be/data/boring/1986-068853',\n+ 'https://www.dov.vlaanderen.be/data/boring/1986-068853']\n+ l_output = ['https://www.dov.vlaanderen.be/data/boring/1986-068853']\n \n- df = pd.DataFrame({\n- 'pkey_boring': pd.Series(l),\n- 'diepte_tot_m': pd.Series([10, 20])\n- })\n+ df = pd.DataFrame({\n+ 'pkey_boring': pd.Series(l),\n+ 'diepte_tot_m': pd.Series([10, 20])\n+ })\n+\n+ query = Join(df, 'pkey_boring')\n+ xml = query.toXML()\n+\n+ assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'\n+\n+ propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')\n+ assert propertyname.text == 'pkey_boring'\n+\n+ literal = xml.find('./{http://www.opengis.net/ogc}Literal')\n+ assert literal.text in l_output\n+\n+ l_output.remove(literal.text)\n+ assert len(l_output) == 0\n+\n+ def test_empty(self):\n+ \"\"\"Test the Join expression with an empty dataframe.\n+\n+ Test whether a ValueError is raised\n+\n+ \"\"\"\n+ df = pd.DataFrame({\n+ 'pkey_boring': [np.nan, np.nan],\n+ 'diepte_tot_m': pd.Series([10, 20])\n+ })\n \n+ with pytest.raises(ValueError):\n Join(df, 'pkey_boring')\n \n def test_on(self):\n", "FAIL_TO_PASS": ["tests/test_util_query.py::TestPropertyInList::test_list_single", "tests/test_util_query.py::TestPropertyInList::test_list_single_duplicate", "tests/test_util_query.py::TestJoin::test_single", "tests/test_util_query.py::TestJoin::test_single_duplicate"]}], "all_FAIL_TO_PASS": ["tests/test_util_query.py::TestPropertyInList::test_list_single", "tests/test_util_query.py::TestPropertyInList::test_list_single_duplicate", "tests/test_util_query.py::TestJoin::test_single", "tests/test_util_query.py::TestJoin::test_single_duplicate"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ASFHyP3__hyp3-sdk-53_x1", "level": 1, "source": "swerebench", "repo": "ASFHyP3/hyp3-sdk", "image": "swerebench/sweb.eval.x86_64.asfhyp3_1776_hyp3-sdk-53:latest", "base_commit": "56cfb700341a0de44ee0f2f3548d5ed6c534d659", "num_bugs": 1, "bugs": [{"instance_id": "ASFHyP3__hyp3-sdk-53", "base_commit": "56cfb700341a0de44ee0f2f3548d5ed6c534d659", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 8905268..ddcacaa 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -6,6 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [PEP 440](https://www.python.org/dev/peps/pep-0440/) \n and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n+## [0.3.3](https://github.com/ASFHyP3/hyp3-sdk/compare/v0.3.2...v0.3.3)\n+### Added\n+- SDK will attach a `User-Agent` statement like `hyp3_sdk/VERSION` to all API interactions\n+\n+### Changed\n+- Providing a job list to `Batch.__init__()` is now optional; an empty batch will \n+ be created if the job list is not provided\n+- `Batch.__init__()` no longer issues a warning when creating an empty batch\n \n ## [0.3.2](https://github.com/ASFHyP3/hyp3-sdk/compare/v0.3.1...v0.3.2)\n ### Changed\ndiff --git a/hyp3_sdk/jobs.py b/hyp3_sdk/jobs.py\nindex fbe8837..7866439 100644\n--- a/hyp3_sdk/jobs.py\n+++ b/hyp3_sdk/jobs.py\n@@ -1,4 +1,3 @@\n-import warnings\n from datetime import datetime\n from pathlib import Path\n from typing import List, Optional, Union\n@@ -124,10 +123,9 @@ class Job:\n \n \n class Batch:\n- def __init__(self, jobs: List[Job]):\n- if len(jobs) == 0:\n- warnings.warn('Jobs list is empty; creating an empty Batch', UserWarning)\n-\n+ def __init__(self, jobs: Optional[List[Job]] = None):\n+ if jobs is None:\n+ jobs = []\n self.jobs = jobs\n \n def __len__(self):\n", "test_patch": "diff --git a/tests/test_jobs.py b/tests/test_jobs.py\nindex 6d25cec..400f2d8 100644\n--- a/tests/test_jobs.py\n+++ b/tests/test_jobs.py\n@@ -119,8 +119,10 @@ def test_job_download_files(tmp_path, get_mock_job):\n \n \n def test_batch_len():\n- with pytest.warns(UserWarning):\n- batch = Batch([])\n+ batch = Batch()\n+ assert len(batch) == 0\n+\n+ batch = Batch([])\n assert len(batch) == 0\n \n batch = Batch([Job.from_dict(SUCCEEDED_JOB), Job.from_dict(FAILED_JOB)])\n", "FAIL_TO_PASS": ["tests/test_jobs.py::test_batch_len"]}], "all_FAIL_TO_PASS": ["tests/test_jobs.py::test_batch_len"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MaxGhenis__microdf-80_x1", "level": 1, "source": "swerebench", "repo": "MaxGhenis/microdf", "image": "swerebench/sweb.eval.x86_64.maxghenis_1776_microdf-80:latest", "base_commit": "ec6209573968caeadc043abd18306fb88e33b4d8", "num_bugs": 1, "bugs": [{"instance_id": "MaxGhenis__microdf-80", "base_commit": "ec6209573968caeadc043abd18306fb88e33b4d8", "gold_patch": "diff --git a/ROADMAP.md b/ROADMAP.md\nindex a25fc16..5797082 100644\n--- a/ROADMAP.md\n+++ b/ROADMAP.md\n@@ -6,4 +6,4 @@\n * Presets for working with common datasets, e.g. suggesting the appropriate weight for SCF and CPS\n * Standard error calculations for surveys with replicate weight files\n \n-See the [issues page](https://github.com/MaxGhenis/microdf/issues) to view and suggest other items.\n+See the [issues page](https://github.com/MaxGhenis/microdf/issues) to see and suggest other items.\n\\ No newline at end of file\ndiff --git a/microdf/weighted.py b/microdf/weighted.py\nindex e56e59e..e0ebb77 100644\n--- a/microdf/weighted.py\n+++ b/microdf/weighted.py\n@@ -1,5 +1,6 @@\n import numpy as np\n import pandas as pd\n+import microdf as mdf\n \n \n def weight(df, col, w):\n@@ -158,7 +159,7 @@ def quantile_chg(v1, v2, w1=None, w2=None, q=np.arange(0.1, 1, 0.1)):\n q2 = weighted_quantile(v2, q, w2)\n df = pd.DataFrame([q1, q2])\n # Set decile labels.\n- q_print = [ordinal_label((i * 100)) for i in q]\n+ q_print = [mdf.ordinal_label((i * 100)) for i in q]\n # TODO: Check if other values are median\n if q[4] == 0.5:\n q_print[4] += ' (median)'\n", "test_patch": "diff --git a/microdf/tests/test_quantile_chg.py b/microdf/tests/test_quantile_chg.py\nnew file mode 100644\nindex 0000000..48cdec9\n--- /dev/null\n+++ b/microdf/tests/test_quantile_chg.py\n@@ -0,0 +1,11 @@\n+import microdf as mdf\n+\n+\n+def test_quantile_chg():\n+ mdf.quantile_chg(v1=[1, 2, 3], v2=[4, 5, 6],\n+ w1=[7, 8, 9], w2=[10, 11, 12])\n+\n+\n+def test_quantile_chg_plot():\n+ mdf.quantile_chg_plot(v1=[1, 2, 3], v2=[4, 5, 6],\n+ w1=[7, 8, 9], w2=[10, 11, 12])\n", "FAIL_TO_PASS": ["microdf/tests/test_quantile_chg.py::test_quantile_chg", "microdf/tests/test_quantile_chg.py::test_quantile_chg_plot"]}], "all_FAIL_TO_PASS": ["microdf/tests/test_quantile_chg.py::test_quantile_chg", "microdf/tests/test_quantile_chg.py::test_quantile_chg_plot"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Parquery__icontract-112_x1", "level": 1, "source": "swerebench", "repo": "Parquery/icontract", "image": "swerebench/sweb.eval.x86_64.parquery_1776_icontract-112:latest", "base_commit": "013cb1bb0294097eaa8c43776bfd4d73342a1655", "num_bugs": 1, "bugs": [{"instance_id": "Parquery__icontract-112", "base_commit": "013cb1bb0294097eaa8c43776bfd4d73342a1655", "gold_patch": "diff --git a/icontract/_checkers.py b/icontract/_checkers.py\nindex 1b27f5a..1dc79d3 100644\n--- a/icontract/_checkers.py\n+++ b/icontract/_checkers.py\n@@ -66,6 +66,27 @@ def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args:\n return mapping\n \n \n+def _not_check(check: Any, contract: Contract) -> bool:\n+ \"\"\"\n+ Negate the check value of a condition and capture missing boolyness (*e.g.*, when check is a numpy array).\n+\n+ :param check: value of the evaluated condition\n+ :param contract: corresponding to the check\n+ :return: negated check\n+ :raise: ValueError if the check could not be negated\n+ \"\"\"\n+ try:\n+ return not check\n+ except Exception as err: # pylint: disable=broad-except\n+ msg_parts = [] # type: List[str]\n+ if contract.location is not None:\n+ msg_parts.append(\"{}:\\n\".format(contract.location))\n+\n+ msg_parts.append('Failed to negate the evaluation of the condition.')\n+\n+ raise ValueError(''.join(msg_parts)) from err\n+\n+\n def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None:\n \"\"\"\n Assert that the contract holds as a precondition.\n@@ -88,7 +109,7 @@ def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any])\n \n check = contract.condition(**condition_kwargs)\n \n- if not check:\n+ if _not_check(check=check, contract=contract):\n if contract.error is not None and (inspect.ismethod(contract.error) or inspect.isfunction(contract.error)):\n assert contract.error_arg_set is not None, \"Expected error_arg_set non-None if contract.error a function.\"\n assert contract.error_args is not None, \"Expected error_args non-None if contract.error a function.\"\n@@ -127,7 +148,7 @@ def _assert_invariant(contract: Contract, instance: Any) -> None:\n else:\n check = contract.condition()\n \n- if not check:\n+ if _not_check(check=check, contract=contract):\n if contract.error is not None and (inspect.ismethod(contract.error) or inspect.isfunction(contract.error)):\n assert contract.error_arg_set is not None, \"Expected error_arg_set non-None if contract.error a function.\"\n assert contract.error_args is not None, \"Expected error_args non-None if contract.error a function.\"\n@@ -199,7 +220,7 @@ def _assert_postcondition(contract: Contract, resolved_kwargs: Mapping[str, Any]\n \n check = contract.condition(**condition_kwargs)\n \n- if not check:\n+ if _not_check(check=check, contract=contract):\n if contract.error is not None and (inspect.ismethod(contract.error) or inspect.isfunction(contract.error)):\n assert contract.error_arg_set is not None, \"Expected error_arg_set non-None if contract.error a function.\"\n assert contract.error_args is not None, \"Expected error_args non-None if contract.error a function.\"\n", "test_patch": "diff --git a/tests/test_invariant.py b/tests/test_invariant.py\nindex 114649e..302bb5d 100644\n--- a/tests/test_invariant.py\n+++ b/tests/test_invariant.py\n@@ -9,6 +9,7 @@ from typing import Optional # pylint: disable=unused-import\n \n import icontract\n import tests.error\n+import tests.mock\n \n \n class TestOK(unittest.TestCase):\n@@ -587,3 +588,19 @@ class TestInvalid(unittest.TestCase):\n self.assertIsNotNone(val_err)\n self.assertEqual(\"Expected an invariant condition with at most an argument 'self', but got: ['self', 'z']\",\n str(val_err))\n+\n+ def test_no_boolyness(self):\n+ @icontract.invariant(lambda self: tests.mock.NumpyArray([True, False]))\n+ class A:\n+ def __init__(self) -> None:\n+ pass\n+\n+ value_error = None # type: Optional[ValueError]\n+ try:\n+ _ = A()\n+ except ValueError as err:\n+ value_error = err\n+\n+ self.assertIsNotNone(value_error)\n+ self.assertEqual('Failed to negate the evaluation of the condition.',\n+ tests.error.wo_mandatory_location(str(value_error)))\ndiff --git a/tests/test_postcondition.py b/tests/test_postcondition.py\nindex 3ea09f0..7e27bdc 100644\n--- a/tests/test_postcondition.py\n+++ b/tests/test_postcondition.py\n@@ -11,6 +11,7 @@ from typing import Optional, List, Type # pylint: disable=unused-import\n \n import icontract\n import tests.error\n+import tests.mock\n \n \n class TestOK(unittest.TestCase):\n@@ -438,3 +439,18 @@ class TestInvalid(unittest.TestCase):\n self.assertEqual(\"The argument(s) of the postcondition error have not been set: ['z']. \"\n \"Does the original function define them? Did you supply them in the call?\",\n tests.error.wo_mandatory_location(str(type_error)))\n+\n+ def test_no_boolyness(self):\n+ @icontract.ensure(lambda: tests.mock.NumpyArray([True, False]))\n+ def some_func() -> None:\n+ pass\n+\n+ value_error = None # type: Optional[ValueError]\n+ try:\n+ some_func()\n+ except ValueError as err:\n+ value_error = err\n+\n+ self.assertIsNotNone(value_error)\n+ self.assertEqual('Failed to negate the evaluation of the condition.',\n+ tests.error.wo_mandatory_location(str(value_error)))\ndiff --git a/tests/test_precondition.py b/tests/test_precondition.py\nindex 01b3e99..83ba7eb 100644\n--- a/tests/test_precondition.py\n+++ b/tests/test_precondition.py\n@@ -12,6 +12,7 @@ from typing import Optional # pylint: disable=unused-import\n \n import icontract\n import tests.error\n+import tests.mock\n \n \n class TestOK(unittest.TestCase):\n@@ -450,6 +451,21 @@ class TestInvalid(unittest.TestCase):\n \"Does the original function define them? Did you supply them in the call?\",\n tests.error.wo_mandatory_location(str(type_error)))\n \n+ def test_no_boolyness(self):\n+ @icontract.require(lambda: tests.mock.NumpyArray([True, False]))\n+ def some_func() -> None:\n+ pass\n+\n+ value_error = None # type: Optional[ValueError]\n+ try:\n+ some_func()\n+ except ValueError as err:\n+ value_error = err\n+\n+ self.assertIsNotNone(value_error)\n+ self.assertEqual('Failed to negate the evaluation of the condition.',\n+ tests.error.wo_mandatory_location(str(value_error)))\n+\n \n if __name__ == '__main__':\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_invariant.py::TestInvalid::test_no_boolyness", "tests/test_postcondition.py::TestInvalid::test_no_boolyness", "tests/test_precondition.py::TestInvalid::test_no_boolyness"]}], "all_FAIL_TO_PASS": ["tests/test_invariant.py::TestInvalid::test_no_boolyness", "tests/test_postcondition.py::TestInvalid::test_no_boolyness", "tests/test_precondition.py::TestInvalid::test_no_boolyness"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ESSS__barril-46_x1", "level": 1, "source": "swerebench", "repo": "ESSS/barril", "image": "swerebench/sweb.eval.x86_64.esss_1776_barril-46:latest", "base_commit": "87ebd247c3c3fa422f4ab3b5acdefbe9e85145c7", "num_bugs": 1, "bugs": [{"instance_id": "ESSS__barril-46", "base_commit": "87ebd247c3c3fa422f4ab3b5acdefbe9e85145c7", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 58b4af4..a0d3e56 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -1,15 +1,19 @@\n+UNRELEASED\n+------------------\n+\n+* Removing ``thermodynamic temperature`` as default category for ``degF`` and ``degR`` units.\n+\n 1.9.0 (2020-02-20)\n ------------------\n \n * New ``classmethod`` ``Array.FromScalars`` that creates an ``Array`` from a ``List[Scalar]``.\n * Add new unit: \"barrel per second\" (``bbl/s``).\n \n-\n 1.8.0 (2020-01-10)\n ------------------\n \n-* Add new category: \"standard volume per standard volume\"\n-* Move unit ``sm3/sm3`` from \"volume per volume\" to \"standard volume per standard volume\"\n+* Add new category: \"standard volume per standard volume\".\n+* Move unit ``sm3/sm3`` from \"volume per volume\" to \"standard volume per standard volume\".\n \n 1.7.2 (2019-10-16)\n ------------------\ndiff --git a/src/barril/units/posc.py b/src/barril/units/posc.py\nindex a261967..e48c763 100644\n--- a/src/barril/units/posc.py\n+++ b/src/barril/units/posc.py\n@@ -2375,7 +2375,7 @@ def FillUnitDatabaseWithPosc(db=None, fill_categories=True, override_categories=\n \"degF\",\n f_base_to_unit,\n f_unit_to_base,\n- default_category=\"thermodynamic temperature\",\n+ default_category=None,\n )\n f_unit_to_base = MakeCustomaryToBase(0.0, 0.1761102, 1.0, 0.0)\n f_base_to_unit = MakeBaseToCustomary(0.0, 0.1761102, 1.0, 0.0)\n@@ -2465,7 +2465,7 @@ def FillUnitDatabaseWithPosc(db=None, fill_categories=True, override_categories=\n \"degR\",\n f_base_to_unit,\n f_unit_to_base,\n- default_category=\"thermodynamic temperature\",\n+ default_category=None,\n )\n f_unit_to_base = MakeCustomaryToBase(0.0, 0.1, 1.0, 0.0)\n f_base_to_unit = MakeBaseToCustomary(0.0, 0.1, 1.0, 0.0)\n@@ -13377,7 +13377,10 @@ def FillUnitDatabaseWithPosc(db=None, fill_categories=True, override_categories=\n valid_units=[\"K\", \"ddegC\", \"ddegF\", \"ddegK\", \"ddegR\"],\n )\n db.AddCategory(\n- \"temperature\", \"temperature\", override=override_categories, valid_units=[\"degC\"]\n+ \"temperature\",\n+ \"temperature\",\n+ override=override_categories,\n+ valid_units=[\"degC\", \"K\", \"degF\", \"degR\"],\n )\n db.AddCategory(\n \"thermodynamic temperature\",\n", "test_patch": "diff --git a/src/barril/units/_tests/test_posc.py b/src/barril/units/_tests/test_posc.py\nindex 6f63923..e341e04 100644\n--- a/src/barril/units/_tests/test_posc.py\n+++ b/src/barril/units/_tests/test_posc.py\n@@ -273,7 +273,6 @@ def testDefaultCategories(unit_database_posc):\n \"self inductance per length\",\n \"shear rate\",\n \"status\",\n- \"thermodynamic temperature\",\n \"volume per area\",\n \"volume per length\",\n \"volume per time per area\",\ndiff --git a/src/barril/units/_tests/test_posc2.py b/src/barril/units/_tests/test_posc2.py\nindex ed5486d..ee7cf75 100644\n--- a/src/barril/units/_tests/test_posc2.py\n+++ b/src/barril/units/_tests/test_posc2.py\n@@ -49,3 +49,15 @@ def testScfPerBblToM3ToM3():\n expected = 0.17776487178535644\n obtained = unit_database.Convert(\"standard volume per volume\", \"scf/bbl\", \"scm(15C)/m3\", 1.0)\n assert approx(abs(obtained - expected), 7) == 0\n+\n+\n+def testAllValidTemperatureUnitsHaveSameDefaultCategory():\n+ \"\"\"'temperature' units should have 'temperature' as defined category (#45)\"\"\"\n+ unit_database = UnitDatabase.CreateDefaultSingleton()\n+\n+ expected_category = \"temperature\"\n+ valid_temperature_units = unit_database.GetValidUnits(expected_category)\n+\n+ for unit in valid_temperature_units:\n+ T = units.Scalar(1.0, unit)\n+ assert T.category == expected_category\n", "FAIL_TO_PASS": ["src/barril/units/_tests/test_posc.py::testDefaultCategories"]}], "all_FAIL_TO_PASS": ["src/barril/units/_tests/test_posc.py::testDefaultCategories"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "CORE-GATECH-GROUP__serpent-tools-24_x1", "level": 1, "source": "swerebench", "repo": "CORE-GATECH-GROUP/serpent-tools", "image": "swerebench/sweb.eval.x86_64.core-gatech-group_1776_serpent-tools-24:latest", "base_commit": "4b93cd86c6149b94960984892dad25de6fbbb41f", "num_bugs": 1, "bugs": [{"instance_id": "CORE-GATECH-GROUP__serpent-tools-24", "base_commit": "4b93cd86c6149b94960984892dad25de6fbbb41f", "gold_patch": "diff --git a/serpentTools/__init__.py b/serpentTools/__init__.py\nindex fdaf895..8d07887 100644\n--- a/serpentTools/__init__.py\n+++ b/serpentTools/__init__.py\n@@ -3,10 +3,6 @@ from serpentTools import parsers\n \r\n \r\n # List TODOS/feature requests here for now\r\n-# Messages/Errors\r\n-# TODO: Add verbosity control\r\n-# TODO: Add specific exceptions and warnings\r\n-# TODO: Add logging module to help with warnings/exceptions/info\r\n # Compatability\r\n # TODO: Python 2 support\r\n # TODO: Test compatability with earlier numpy releases\r\n@@ -14,9 +10,10 @@ from serpentTools import parsers\n # TODO: Update rc with dictionary\r\n # TODO: Update rc with yaml file into dictionary\r\n # TODO: Capture materials with underscores for depletion\r\n-# TODO: Better version string management\r\n \r\n \r\n from ._version import get_versions\r\n __version__ = get_versions()['version']\r\n del get_versions\r\n+\r\n+settings.messages.info('Using version {}'.format(__version__))\r\ndiff --git a/serpentTools/parsers/depletion.py b/serpentTools/parsers/depletion.py\nindex 002f516..6c2ff82 100644\n--- a/serpentTools/parsers/depletion.py\n+++ b/serpentTools/parsers/depletion.py\n@@ -8,6 +8,8 @@ from drewtils.parsers import KeywordParser\n from serpentTools.objects.readers import MaterialReader\r\n from serpentTools.objects.materials import DepletedMaterial\r\n \r\n+from serpentTools.settings import messages\r\n+\r\n \r\n class DepletionReader(MaterialReader):\r\n \"\"\"Parser responsible for reading and working with depletion files.\r\n@@ -60,10 +62,13 @@ class DepletionReader(MaterialReader):\n \"\"\"Return the patterns by which to find the requested materials.\"\"\"\r\n patterns = self.settings['materials'] or ['.*']\r\n # match all materials if nothing given\r\n+ if any(['_' in pat for pat in patterns]):\r\n+ messages.warning('Materials with underscores are not supported.')\r\n return [re.compile(mat) for mat in patterns]\r\n \r\n def read(self):\r\n \"\"\"Read through the depletion file and store requested data.\"\"\"\r\n+ messages.info('Preparing to read {}'.format(self.filePath))\r\n keys = ['MAT', 'TOT'] if self.settings['processTotal'] else ['MAT']\r\n keys.extend(self.settings['metadataKeys'])\r\n separators = ['\\n', '];']\r\n@@ -74,6 +79,8 @@ class DepletionReader(MaterialReader):\n elif (('TOT' in chunk[0] and self.settings['processTotal'])\r\n or 'MAT' in chunk[0]):\r\n self._addMaterial(chunk)\r\n+ messages.info('Done reading depletion file')\r\n+ messages.debug(' found {} materials'.format(len(self.materials)))\r\n \r\n def _addMetadata(self, chunk):\r\n options = {'ZAI': 'zai', 'NAMES': 'names', 'DAYS': 'days',\r\ndiff --git a/serpentTools/settings/__init__.py b/serpentTools/settings/__init__.py\nindex 2223fc0..09f5fdb 100644\n--- a/serpentTools/settings/__init__.py\n+++ b/serpentTools/settings/__init__.py\n@@ -1,4 +1,5 @@\n \"\"\"Settings to yield control to the user.\"\"\"\r\n+from serpentTools.settings import messages\r\n \r\n defaultSettings = {\r\n 'depletion.metadataKeys': {\r\n@@ -23,6 +24,13 @@ defaultSettings = {\n 'default': True,\r\n 'description': 'Option to store the depletion data from the TOT block',\r\n 'type': bool\r\n+ },\r\n+ 'verbosity': {\r\n+ 'default': 'warning',\r\n+ 'options': messages.LOG_OPTS,\r\n+ 'type': str,\r\n+ 'description': 'Set the level of errors to be shown.',\r\n+ 'updater': messages.updateLevel\r\n }\r\n }\r\n \r\n@@ -30,12 +38,13 @@ defaultSettings = {\n class DefaultSetting(object):\r\n \"\"\"Store a single setting.\"\"\"\r\n \r\n- def __init__(self, name, default, varType, description, options):\r\n+ def __init__(self, name, default, varType, description, options, updater):\r\n self.name = name\r\n self.description = description\r\n self.default = default\r\n self.type = varType\r\n self.options = options\r\n+ self.updater = updater\r\n \r\n def __repr__(self):\r\n return ''.format(self.name, self.default)\r\n@@ -82,7 +91,8 @@ class DefaultSettingsLoader(dict):\n dict.__init__(self, self._load())\r\n self.__locked__ = True\r\n \r\n- def _load(self):\r\n+ @staticmethod\r\n+ def _load():\r\n \"\"\"Load the default setting objects.\"\"\"\r\n defaults = {}\r\n for name, value in defaultSettings.items():\r\n@@ -95,7 +105,8 @@ class DefaultSettingsLoader(dict):\n 'default': value['default'],\r\n 'varType': value['type'],\r\n 'options': options,\r\n- 'description': value['description']\r\n+ 'description': value['description'],\r\n+ 'updater': value.get('updater', None)\r\n }\r\n defaults[name] = DefaultSetting(**settingsOptions)\r\n return defaults\r\n@@ -163,14 +174,17 @@ class UserSettingsLoader(dict):\n raise KeyError('Setting {} does not exist'.format(name))\r\n self._defaultLoader[name].validate(value)\r\n # if we've made it here, then the value is valid\r\n+ if self._defaultLoader[name].updater is not None:\r\n+ value = self._defaultLoader[name].updater(value)\r\n dict.__setitem__(self, name, value)\r\n+ messages.debug('Updated setting {} to {}'.format(name, value))\r\n \r\n def getReaderSettings(self, readerName):\r\n \"\"\"Get all module-wide and reader-specific settings.\r\n \r\n Parameters\r\n ----------\r\n- readerLevel: str\r\n+ readerName: str\r\n Name of the specific reader.\r\n Will look for settings with lead with ``readerName``, e.g.\r\n ``depletion.metadataKeys``\r\ndiff --git a/serpentTools/settings/messages.py b/serpentTools/settings/messages.py\nnew file mode 100644\nindex 0000000..a0fa0b0\n--- /dev/null\n+++ b/serpentTools/settings/messages.py\n@@ -0,0 +1,84 @@\n+\"\"\"\n+System-wide methods for producing status update and errors.\n+\n+See Also\n+--------\n+https://docs.python.org/2/library/logging.html\n+https://www.python.org/dev/peps/pep-0391/\n+http://docs.python-guide.org/en/latest/writing/logging/\n+https://docs.python.org/2/howto/logging-cookbook.html#logging-cookbook\n+https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/\n+\"\"\"\n+\n+\n+import logging\n+from logging.config import dictConfig\n+\n+\n+class SerpentToolsException(Exception):\n+ \"\"\"Base-class for all exceptions in this project\"\"\"\n+ pass\n+\n+\n+LOG_OPTS = ['critical', 'error', 'warning', 'info', 'debug']\n+\n+\n+loggingConfig = {\n+ 'version': 1,\n+ 'formatters': {\n+ 'brief': {'format': '%(levelname)-8s: %(name)-15s: %(message)s'},\n+ 'precise': {\n+ 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'\n+ }\n+ },\n+ 'handlers': {\n+ 'console': {\n+ 'class': 'logging.StreamHandler',\n+ 'formatter': 'brief',\n+ 'level': logging.DEBUG,\n+ 'stream': 'ext://sys.stdout'\n+ }\n+ },\n+ 'root': {\n+ 'handlers': ['console'],\n+ 'level': logging.INFO\n+ }\n+}\n+\n+dictConfig(loggingConfig)\n+\n+__logger__ = logging.getLogger('serpentTools')\n+\n+\n+def debug(message):\n+ \"\"\"Log a debug message.\"\"\"\n+ __logger__.debug('%s', message)\n+\n+\n+def info(message):\n+ \"\"\"Log an info message, e.g. status update.\"\"\"\n+ __logger__.info('%s', message)\n+\n+\n+def warning(message):\n+ \"\"\"Log a warning that something that could go wrong or be avoided.\"\"\"\n+ __logger__.warning('%s', message)\n+\n+\n+def error(message, fatal=True):\n+ \"\"\"Log that something went wrong.\"\"\"\n+ if fatal:\n+ __logger__.critical('%s', message, exc_info=True)\n+ raise SerpentToolsException('%s', message)\n+ __logger__.error('%s', message)\n+\n+\n+def updateLevel(level):\n+ \"\"\"Set the level of the logger.\"\"\"\n+ if level.lower() not in LOG_OPTS:\n+ __logger__.setLevel('INFO')\n+ warning('Logger option {} not in options. Set to warning.')\n+ return 'warning'\n+ else:\n+ __logger__.setLevel(level.upper())\n+ return level\ndiff --git a/setup.py b/setup.py\nindex fdb65d3..5dd24b4 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -1,6 +1,8 @@\n from setuptools import setup\n import versioneer\n \n+with open('README.md') as readme:\n+ longDesc = readme.read()\n \n classifiers = [\n 'License :: OSI Approved :: MIT License',\n@@ -23,6 +25,7 @@ setupArgs = {\n 'url': 'https://github.com/CORE-GATECH-GROUP/serpent-tools',\n 'description': ('A suite of parsers designed to make interacting with '\n 'SERPENT output files simple, scriptable, and flawless'),\n+ 'long_description': longDesc,\n 'test_suite': 'serpentTools.tests',\n 'author': 'Andrew Johnson',\n 'author_email': 'ajohnson400@gatech.edu',\n", "test_patch": "diff --git a/serpentTools/tests/test_loaders.py b/serpentTools/tests/test_loaders.py\nindex f6895e1..3bbd24e 100644\n--- a/serpentTools/tests/test_loaders.py\n+++ b/serpentTools/tests/test_loaders.py\n@@ -57,7 +57,8 @@ class UserSettingsTester(unittest.TestCase):\n 'metadataKeys': ['ZAI', 'NAMES', 'DAYS', 'BU'],\r\n 'materialVariables': ['ADENS', 'MDENS', 'BURNUP'],\r\n 'materials': [],\r\n- 'processTotal': True\r\n+ 'processTotal': True,\r\n+ 'verbosity': 'warning'\r\n }\r\n actual = self.loader.getReaderSettings(readerName)\r\n self.assertDictEqual(expected, actual)\r\n", "FAIL_TO_PASS": ["serpentTools/tests/test_loaders.py::UserSettingsTester::test_returnReaderSettings"]}], "all_FAIL_TO_PASS": ["serpentTools/tests/test_loaders.py::UserSettingsTester::test_returnReaderSettings"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "SAP__data-attribute-recommendation-python-sdk-69_x1", "level": 1, "source": "swerebench", "repo": "SAP/data-attribute-recommendation-python-sdk", "image": "swerebench/sweb.eval.x86_64.sap_1776_data-attribute-recommendation-python-sdk-69:latest", "base_commit": "efa9a5a9ff52575d641f8c5290ecde5133870cd6", "num_bugs": 1, "bugs": [{"instance_id": "SAP__data-attribute-recommendation-python-sdk-69", "base_commit": "efa9a5a9ff52575d641f8c5290ecde5133870cd6", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 23cdc12..4859204 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -20,7 +20,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n ### Fixed\n \n * Log message missing model deployment ID [#59]\n+* Expose a Dataset's `validationMessage` in `DatasetValidationFailed` [#33], [#69]\n \n+[#33]: https://github.com/SAP/data-attribute-recommendation-python-sdk/issues/33\n [#46]: https://github.com/SAP/data-attribute-recommendation-python-sdk/issues/46\n [#58]: https://github.com/SAP/data-attribute-recommendation-python-sdk/pull/58\n [#59]: https://github.com/SAP/data-attribute-recommendation-python-sdk/pull/59\n@@ -28,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n [#63]: https://github.com/SAP/data-attribute-recommendation-python-sdk/pull/63\n [#64]: https://github.com/SAP/data-attribute-recommendation-python-sdk/pull/64\n [#66]: https://github.com/SAP/data-attribute-recommendation-python-sdk/pull/66\n+[#69]: https://github.com/SAP/data-attribute-recommendation-python-sdk/pull/69\n \n ## [0.6.8]\n \ndiff --git a/sap/aibus/dar/client/data_manager_client.py b/sap/aibus/dar/client/data_manager_client.py\nindex 994a62b..32b7b9f 100644\n--- a/sap/aibus/dar/client/data_manager_client.py\n+++ b/sap/aibus/dar/client/data_manager_client.py\n@@ -270,8 +270,11 @@ class DataManagerClient(BaseClientWithSession):\n raise new_exception from exception\n \n if self.is_dataset_validation_failed(response):\n- msg = \"Validation for Dataset '{}' failed with status: '{}'\".format(\n- response[\"id\"], response[\"status\"]\n+ msg = (\n+ \"Validation for Dataset '{}' failed with status '{}' and\"\n+ \" validation message: '{}'\".format(\n+ response[\"id\"], response[\"status\"], response[\"validationMessage\"]\n+ )\n )\n self.log.error(msg)\n raise DatasetValidationFailed(msg)\n", "test_patch": "diff --git a/tests/sap/aibus/dar/client/test_data_manager_client.py b/tests/sap/aibus/dar/client/test_data_manager_client.py\nindex 0208efd..08a398a 100644\n--- a/tests/sap/aibus/dar/client/test_data_manager_client.py\n+++ b/tests/sap/aibus/dar/client/test_data_manager_client.py\n@@ -456,6 +456,9 @@ class TestDataManagerClientDatasetSchema:\n \n dataset_response = self._make_dataset_response(bad_dataset_state)\n \n+ if bad_dataset_state == \"VALIDATION_FAILED\":\n+ dataset_response[\"validationMessage\"] = \"Detailed Description\"\n+\n client.session.get_from_endpoint.return_value.json.side_effect = [\n dataset_response\n ]\n@@ -466,8 +469,10 @@ class TestDataManagerClientDatasetSchema:\n )\n expected_message = (\n \"Validation for Dataset \"\n- \"'{}' failed with status: '{}'\".format(\n- dataset_response[\"id\"], bad_dataset_state\n+ \"'{}' failed with status '{}' and validation message: '{}'\".format(\n+ dataset_response[\"id\"],\n+ bad_dataset_state,\n+ dataset_response[\"validationMessage\"],\n )\n )\n \n", "FAIL_TO_PASS": ["tests/sap/aibus/dar/client/test_data_manager_client.py::TestDataManagerClientDatasetSchema::test_wait_for_validation_raises_if_validation_fails"]}], "all_FAIL_TO_PASS": ["tests/sap/aibus/dar/client/test_data_manager_client.py::TestDataManagerClientDatasetSchema::test_wait_for_validation_raises_if_validation_fails"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "LordGolias__sqf-47_x1", "level": 1, "source": "swerebench", "repo": "LordGolias/sqf", "image": "swerebench/sweb.eval.x86_64.lordgolias_1776_sqf-47:latest", "base_commit": "a9a1de31e439742cc5391c6ca7e4cd7f2c2bdf15", "num_bugs": 1, "bugs": [{"instance_id": "LordGolias__sqf-47", "base_commit": "a9a1de31e439742cc5391c6ca7e4cd7f2c2bdf15", "gold_patch": "diff --git a/sqf/analyzer.py b/sqf/analyzer.py\nindex 1c55885..b4ceea7 100644\n--- a/sqf/analyzer.py\n+++ b/sqf/analyzer.py\n@@ -426,7 +426,7 @@ class Analyzer(BaseInterpreter):\n elif case_found.keyword == Keyword('catch'):\n extra_scope = {'_exception': Anything()}\n elif case_found.keyword == Keyword('spawn'):\n- extra_scope = {'_thisScript': Script()}\n+ extra_scope = {'_thisScript': Script(), '_this': values[0]}\n elif case_found.keyword == Keyword('do') and type(values[0]) == ForType:\n extra_scope = {values[0].variable.value: Number()}\n for value, t_or_v in zip(values, case_found.types_or_values):\n", "test_patch": "diff --git a/tests/test_analyzer.py b/tests/test_analyzer.py\nindex b12b769..91bc548 100644\n--- a/tests/test_analyzer.py\n+++ b/tests/test_analyzer.py\n@@ -1052,11 +1052,21 @@ class SpecialContext(TestCase):\n analyzer = analyze(parse(code))\n self.assertEqual(analyzer.exceptions, [])\n \n- def test_spawn(self):\n+ def test_spawn_thisScript(self):\n code = '[] spawn {x = _thisScript}'\n analyzer = analyze(parse(code))\n self.assertEqual(len(analyzer.exceptions), 0)\n \n+ def test_spawn_this_typing_correct(self):\n+ code = '\"\" spawn {hint _this}'\n+ analyzer = analyze(parse(code))\n+ self.assertEqual(len(analyzer.exceptions), 0)\n+\n+ def test_spawn_this_typing_error(self):\n+ code = '[] spawn {hint _this}'\n+ analyzer = analyze(parse(code))\n+ self.assertEqual(len(analyzer.exceptions), 1)\n+\n def test_spawn_local_vars(self):\n # spawn should not use local variables because they may become undefined (error 1). Likewise,\n # the local variable becomes unused (error 2).\n", "FAIL_TO_PASS": ["tests/test_analyzer.py::SpecialContext::test_spawn_this_typing_correct"]}], "all_FAIL_TO_PASS": ["tests/test_analyzer.py::SpecialContext::test_spawn_this_typing_correct"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Alexei-Kornienko__schematics_to_swagger-7_x1", "level": 1, "source": "swerebench", "repo": "Alexei-Kornienko/schematics_to_swagger", "image": "swerebench/sweb.eval.x86_64.alexei-kornienko_1776_schematics_to_swagger-7:latest", "base_commit": "3ddc537a8ed7682e9bb709ebd749b99d7ef09473", "num_bugs": 1, "bugs": [{"instance_id": "Alexei-Kornienko__schematics_to_swagger-7", "base_commit": "3ddc537a8ed7682e9bb709ebd749b99d7ef09473", "gold_patch": "diff --git a/schematics_to_swagger/__init__.py b/schematics_to_swagger/__init__.py\nindex d108f3f..d203de0 100644\n--- a/schematics_to_swagger/__init__.py\n+++ b/schematics_to_swagger/__init__.py\n@@ -54,17 +54,24 @@ def _map_schematics_type(t):\n \n \n def model_to_definition(model):\n- fields = model.fields.items()\n+ properties = {}\n+ required = []\n+\n+ for field_name, field in model.fields.items():\n+ if field_name.startswith(f'_{model.__name__}'):\n+ continue # Exclude private fields\n+ properties[field_name] = _map_schematics_type(field)\n+ if getattr(field, 'required'):\n+ required.append(field_name)\n+\n result_info = {\n 'type': 'object',\n 'title': model.__name__,\n 'description': model.__doc__,\n- 'properties': {k: _map_schematics_type(v) for k, v in fields}\n+ 'properties': properties\n }\n- required = [k for k, v in fields if getattr(v, 'required')]\n if required:\n result_info['required'] = required\n-\n return result_info\n \n \n", "test_patch": "diff --git a/tests/models.py b/tests/models.py\nindex 5392711..7cd4582 100644\n--- a/tests/models.py\n+++ b/tests/models.py\n@@ -16,3 +16,10 @@ class WeatherStats(Model):\n last_report = types.ModelType(WeatherReport)\n prev_reports = types.ListType(types.ModelType(WeatherReport))\n date_list = types.ListType(types.DateTimeType())\n+\n+\n+class WeatherPrivateData(Model):\n+ \"\"\"Some sample model with private field\"\"\"\n+ city = types.StringType(max_length=50, metadata={'readOnly': True})\n+ temperature = types.DecimalType(required=True)\n+ __private_information = types.StringType(max_length=50)\ndiff --git a/tests/test_model.py b/tests/test_model.py\nindex ddeabe3..1ed6fba 100644\n--- a/tests/test_model.py\n+++ b/tests/test_model.py\n@@ -53,6 +53,23 @@ WEATHER_STATS_DEF = {\n }\n },\n }\n+WEATHER_PRIVATE_DATA = {\n+ 'title': 'WeatherPrivateData',\n+ 'type': 'object',\n+ 'description': 'Some sample model with private field',\n+ 'properties': {\n+ 'city': {\n+ 'type': 'string',\n+ 'maxLength': 50,\n+ 'readOnly': True\n+ },\n+ 'temperature': {\n+ 'type': 'number',\n+ 'format': 'double'\n+ }\n+ },\n+ 'required': ['temperature']\n+}\n \n \n def test_model_to_definition():\n@@ -64,7 +81,8 @@ def test_model_to_definition():\n def test_read_models_from_module():\n expected = {\n 'WeatherReport': WEATHER_REPORT_DEFINITION,\n- 'WeatherStats': WEATHER_STATS_DEF\n+ 'WeatherStats': WEATHER_STATS_DEF,\n+ 'WeatherPrivateData': WEATHER_PRIVATE_DATA\n }\n data = schematics_to_swagger.read_models_from_module(models)\n assert expected == data\n@@ -74,3 +92,9 @@ def test_compound_type():\n expected = WEATHER_STATS_DEF\n data = schematics_to_swagger.model_to_definition(models.WeatherStats)\n assert expected == data\n+\n+\n+def test_private_fields():\n+ expected = WEATHER_PRIVATE_DATA\n+ definition = schematics_to_swagger.model_to_definition(models.WeatherPrivateData)\n+ assert expected == definition\n", "FAIL_TO_PASS": ["tests/test_model.py::test_read_models_from_module", "tests/test_model.py::test_private_fields"]}], "all_FAIL_TO_PASS": ["tests/test_model.py::test_read_models_from_module", "tests/test_model.py::test_private_fields"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Ouranosinc__xclim-214_x1", "level": 1, "source": "swerebench", "repo": "Ouranosinc/xclim", "image": "swerebench/sweb.eval.x86_64.ouranosinc_1776_xclim-214:latest", "base_commit": "fdb5bdcbdffb011aa394de794fec987e9422855a", "num_bugs": 1, "bugs": [{"instance_id": "Ouranosinc__xclim-214", "base_commit": "fdb5bdcbdffb011aa394de794fec987e9422855a", "gold_patch": "diff --git a/setup.cfg b/setup.cfg\nindex 78d6b84c..c8c7e55b 100644\n--- a/setup.cfg\n+++ b/setup.cfg\n@@ -3,13 +3,13 @@ current_version = 0.9-beta\n commit = True\n tag = True\n parse = (?P\\d+)\\.(?P\\d+)(\\-(?P[a-z]+))?\n-serialize = \n+serialize =\n \t{major}.{minor}-{release}\n \t{major}.{minor}\n \n [bumpversion:part:release]\n optional_value = gamma\n-values = \n+values =\n \tbeta\n \tgamma\n \n@@ -25,13 +25,14 @@ replace = __version__ = '{new_version}'\n universal = 1\n \n [flake8]\n-exclude = \n+exclude =\n \t.git,\n \tdocs,\n-\tbuild\n+\tbuild,\n+ .eggs,\n max-line-length = 120\n max-complexity = 10\n-ignore = \n+ignore =\n \tF401\n \tF403\n \n@@ -41,6 +42,6 @@ test = pytest\n [tool:pytest]\n collect_ignore = ['setup.py']\n addopts = --verbose\n-filterwarnings = \n+filterwarnings =\n \tignore::UserWarning\n \ndiff --git a/xclim/checks.py b/xclim/checks.py\nindex ec10cf38..212b6eec 100644\n--- a/xclim/checks.py\n+++ b/xclim/checks.py\n@@ -147,7 +147,8 @@ def check_is_dataarray(comp):\n return func\n \n \n-def missing_any(da, freq, **kwds):\n+# This function can probably be made simpler once CFPeriodIndex is implemented.\n+def missing_any(da, freq, **indexer):\n r\"\"\"Return a boolean DataArray indicating whether there are missing days in the resampled array.\n \n Parameters\n@@ -156,19 +157,28 @@ def missing_any(da, freq, **kwds):\n Input array at daily frequency.\n freq : str\n Resampling frequency.\n+ **indexer : {dim: indexer, }, optional\n+ Time attribute and values over which to subset the array. For example, use season='DJF' to select winter values,\n+ month=1 to select January, or month=[6,7,8] to select summer months. If not indexer is given, all values are\n+ considered.\n \n Returns\n -------\n out : DataArray\n A boolean array set to True if any month or year has missing values.\n \"\"\"\n- c = da.notnull().resample(time=freq).sum(dim='time')\n+ from . import generic\n \n if '-' in freq:\n pfreq, anchor = freq.split('-')\n else:\n pfreq = freq\n \n+ # Compute the number of days in the time series during each period at the given frequency.\n+ selected = generic.select_time(da, **indexer)\n+ c = selected.notnull().resample(time=freq).sum(dim='time')\n+\n+ # Otherwise simply use the start and end dates to find the expected number of days.\n if pfreq.endswith('S'):\n start_time = c.indexes['time']\n end_time = start_time.shift(1, freq=freq)\n@@ -176,6 +186,22 @@ def missing_any(da, freq, **kwds):\n end_time = c.indexes['time']\n start_time = end_time.shift(-1, freq=freq)\n \n+ if indexer:\n+ # Create a full synthetic time series and compare the number of days with the original series.\n+ t0 = str(start_time[0].date())\n+ t1 = str(end_time[-1].date())\n+ cal = da.time.encoding.get('calendar')\n+ if cal:\n+ t = xr.cftime_range(t0, t1, freq='D', calendar=cal)\n+ else:\n+ t = pd.date_range(t0, t1, freq='D')\n+\n+ sda = xr.DataArray(data=np.empty(len(t)), coords={'time': t}, dims=('time', ))\n+ st = generic.select_time(sda, **indexer)\n+ sn = st.notnull().resample(time=freq).sum(dim='time')\n+ miss = sn != c\n+ return miss\n+\n n = (end_time - start_time).days\n nda = xr.DataArray(n.values, coords={'time': c.time}, dims='time')\n return c != nda\ndiff --git a/xclim/streamflow.py b/xclim/streamflow.py\nindex c176da23..34b6185e 100644\n--- a/xclim/streamflow.py\n+++ b/xclim/streamflow.py\n@@ -30,7 +30,7 @@ class Stats(Streamflow):\n indexer = kwds['indexer']\n freq = kwds['freq'] or generic.default_freq(**indexer)\n \n- miss = (checks.missing_any(generic.select_time(da, **indexer), freq) for da in args)\n+ miss = (checks.missing_any(da, freq, **indexer) for da in args)\n return reduce(np.logical_or, miss)\n \n \n", "test_patch": "diff --git a/tests/test_checks.py b/tests/test_checks.py\nindex a0be5edb..9556a265 100644\n--- a/tests/test_checks.py\n+++ b/tests/test_checks.py\n@@ -91,3 +91,29 @@ class TestMissingAnyFills:\n ts = tasmin_series(a)\n miss = checks.missing_any(ts, freq='A-JUN')\n np.testing.assert_equal(miss, [False])\n+\n+ def test_month(self, tasmin_series):\n+ ts = tasmin_series(np.zeros(36))\n+ miss = checks.missing_any(ts, freq='YS', month=7)\n+ np.testing.assert_equal(miss, [False])\n+\n+ miss = checks.missing_any(ts, freq='YS', month=8)\n+ np.testing.assert_equal(miss, [True])\n+\n+ miss = checks.missing_any(ts, freq='YS', month=[7, 8])\n+ np.testing.assert_equal(miss, [True])\n+\n+ ts = tasmin_series(np.zeros(76))\n+ miss = checks.missing_any(ts, freq='YS', month=[7, 8])\n+ np.testing.assert_equal(miss, [False])\n+\n+ def test_season(self, tasmin_series):\n+ ts = tasmin_series(np.zeros(360))\n+ miss = checks.missing_any(ts, freq='YS', season='MAM')\n+ np.testing.assert_equal(miss, [False])\n+\n+ miss = checks.missing_any(ts, freq='YS', season='JJA')\n+ np.testing.assert_array_equal(miss, [True, True])\n+\n+ miss = checks.missing_any(ts, freq='YS', season='SON')\n+ np.testing.assert_equal(miss, [False])\ndiff --git a/tests/test_streamflow.py b/tests/test_streamflow.py\nindex ddbec90e..7005c3e3 100644\n--- a/tests/test_streamflow.py\n+++ b/tests/test_streamflow.py\n@@ -25,7 +25,6 @@ class TestStats():\n out = streamflow.stats(ndq_series, freq='YS', op='min', season='MAM')\n assert out.attrs['units'] == 'm^3 s-1'\n \n- @pytest.mark.skip()\n def test_missing(self, ndq_series):\n a = ndq_series\n a = ndq_series.where(~((a.time.dt.dayofyear == 5) * (a.time.dt.year == 1902)))\n", "FAIL_TO_PASS": ["tests/test_checks.py::TestMissingAnyFills::test_month", "tests/test_checks.py::TestMissingAnyFills::test_season", "tests/test_streamflow.py::TestStats::test_missing"]}], "all_FAIL_TO_PASS": ["tests/test_checks.py::TestMissingAnyFills::test_month", "tests/test_checks.py::TestMissingAnyFills::test_season", "tests/test_streamflow.py::TestStats::test_missing"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "DataDog__datadog-lambda-python-214_x1", "level": 1, "source": "swerebench", "repo": "DataDog/datadog-lambda-python", "image": "swerebench/sweb.eval.x86_64.datadog_1776_datadog-lambda-python-214:latest", "base_commit": "1f59f3a8821aef37a02e5099a5112d938e57e9c1", "num_bugs": 1, "bugs": [{"instance_id": "DataDog__datadog-lambda-python-214", "base_commit": "1f59f3a8821aef37a02e5099a5112d938e57e9c1", "gold_patch": "diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml\nindex 0d00bfc..7d7884d 100644\n--- a/.github/workflows/build.yml\n+++ b/.github/workflows/build.yml\n@@ -101,7 +101,7 @@ jobs:\n run: sudo yarn global add serverless@^2.72.2 --prefix /usr/local\n - name: Install Crossbuild Deps\n run: |\n- sudo apt-get update\n+ sudo apt-get update --allow-releaseinfo-change --fix-missing\n sudo apt install -y qemu-user-static binfmt-support\n \n - name: Install dependencies\ndiff --git a/.github/workflows/check-size.yml b/.github/workflows/check-size.yml\nindex 69d578d..1c247e6 100644\n--- a/.github/workflows/check-size.yml\n+++ b/.github/workflows/check-size.yml\n@@ -15,7 +15,9 @@ jobs:\n python-version: 3.7\n \n - name: Install Crossbuild Deps\n- run: sudo apt install -y qemu-user-static binfmt-support\n+ run: |\n+ sudo apt-get update --allow-releaseinfo-change --fix-missing\n+ sudo apt install -y qemu-user-static binfmt-support\n \n - name: Install dependencies\n run: |\ndiff --git a/datadog_lambda/tag_object.py b/datadog_lambda/tag_object.py\nindex 7ca8512..02dc3eb 100644\n--- a/datadog_lambda/tag_object.py\n+++ b/datadog_lambda/tag_object.py\n@@ -3,6 +3,7 @@\n # This product includes software developed at Datadog (https://www.datadoghq.com/).\n # Copyright 2021 Datadog, Inc.\n \n+from decimal import Decimal\n import json\n import logging\n \n@@ -26,7 +27,7 @@ def tag_object(span, key, obj, depth=0):\n except ValueError:\n redacted = _redact_val(key, obj[0:5000])\n return span.set_tag(key, redacted)\n- if isinstance(obj, int) or isinstance(obj, float):\n+ if isinstance(obj, int) or isinstance(obj, float) or isinstance(obj, Decimal):\n return span.set_tag(key, obj)\n if isinstance(obj, list):\n for k, v in enumerate(obj):\n", "test_patch": "diff --git a/tests/test_tag_object.py b/tests/test_tag_object.py\nindex 0936f0c..cdb2941 100644\n--- a/tests/test_tag_object.py\n+++ b/tests/test_tag_object.py\n@@ -1,4 +1,5 @@\n import unittest\n+from decimal import Decimal\n \n try:\n from unittest.mock import MagicMock, patch, call\n@@ -82,3 +83,14 @@ class TestTagObject(unittest.TestCase):\n ],\n True,\n )\n+\n+ def test_decimal_tag_object(self):\n+ payload = {\"myValue\": Decimal(500.50)}\n+ spanMock = MagicMock()\n+ tag_object(spanMock, \"function.request\", payload)\n+ spanMock.set_tag.assert_has_calls(\n+ [\n+ call(\"function.request.myValue\", Decimal(500.50)),\n+ ],\n+ True,\n+ )\n", "FAIL_TO_PASS": ["tests/test_tag_object.py::TestTagObject::test_decimal_tag_object"]}], "all_FAIL_TO_PASS": ["tests/test_tag_object.py::TestTagObject::test_decimal_tag_object"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MAIF__meteole-33_x1", "level": 1, "source": "swerebench", "repo": "MAIF/meteole", "image": "swerebench/sweb.eval.x86_64.maif_1776_meteole-33:latest", "base_commit": "d094d0eb8a6094bd70d14aa3c29a06bc07168974", "num_bugs": 1, "bugs": [{"instance_id": "MAIF__meteole-33", "base_commit": "d094d0eb8a6094bd70d14aa3c29a06bc07168974", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 5d60a79..4a0c713 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -1,3 +1,11 @@\n # Changelog\n \n-## TODO\n+All notable changes to this project will be documented in this file.\n+\n+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n+\n+## [0.2.0] - January, 2024\n+\n+### Features\n+\n+* Add an optional temporary directory: `temp_dir` (#28).\ndiff --git a/README.md b/README.md\nindex ee83696..31d55ed 100644\n--- a/README.md\n+++ b/README.md\n@@ -83,7 +83,8 @@ df_arome = arome_client.get_coverage(\n pressures=None, # Optional: pressure level\n long = (-5.1413, 9.5602), # Optional: longitude\n lat = (41.33356, 51.0889), # Optional: latitude\n- coverage_id=None # Optional: an alternative to indicator/run/interval\n+ coverage_id=None, # Optional: an alternative to indicator/run/interval\n+ temp_dir=None, # Optional: Directory to store the temporary file\n )\n ```\n Note: The coverage_id can be used instead of indicator, run, and interval.\ndiff --git a/docs/pages/how_to.md b/docs/pages/how_to.md\nindex 6396a37..2dc13ec 100644\n--- a/docs/pages/how_to.md\n+++ b/docs/pages/how_to.md\n@@ -80,7 +80,8 @@ df_arome = arome_client.get_coverage(\n pressures=None, # Optional: pressure level\n long = (-5.1413, 9.5602), # Optional: longitude\n lat = (41.33356, 51.0889), # Optional: latitude\n- coverage_id=None # Optional: an alternative to indicator/run/interval\n+ coverage_id=None, # Optional: an alternative to indicator/run/interval\n+ temp_dir=None, # Optional: Directory to store the temporary file\n )\n ```\n \ndiff --git a/src/meteole/forecast.py b/src/meteole/forecast.py\nindex e8b54f6..093bd96 100644\n--- a/src/meteole/forecast.py\n+++ b/src/meteole/forecast.py\n@@ -2,7 +2,9 @@ from __future__ import annotations\n \n import datetime as dt\n import logging\n+import os\n import re\n+import shutil\n import tempfile\n from abc import ABC, abstractmethod\n from functools import reduce\n@@ -147,6 +149,7 @@ class WeatherForecast(ABC):\n run: str | None = None,\n interval: str | None = None,\n coverage_id: str = \"\",\n+ temp_dir: str | None = None,\n ) -> pd.DataFrame:\n \"\"\"Return the coverage data (i.e., the weather forecast data).\n \n@@ -163,6 +166,7 @@ class WeatherForecast(ABC):\n raises an error if specified. Defaults to \"P1D\" for time-aggregated indicators such\n as TOTAL_PRECIPITATION.\n coverage_id: An id of a coverage, use get_capabilities() to get them.\n+ temp_dir (str | None): Directory to store the temporary file. Defaults to None.\n \n Returns:\n pd.DataFrame: The complete run for the specified execution.\n@@ -192,6 +196,7 @@ class WeatherForecast(ABC):\n forecast_horizon=forecast_horizon,\n lat=lat,\n long=long,\n+ temp_dir=temp_dir,\n )\n for forecast_horizon in forecast_horizons\n for pressure in pressures\n@@ -403,7 +408,11 @@ class WeatherForecast(ABC):\n response = self._client.get(url, params=params)\n return xmltodict.parse(response.text)\n \n- def _grib_bytes_to_df(self, grib_str: bytes) -> pd.DataFrame:\n+ def _grib_bytes_to_df(\n+ self,\n+ grib_str: bytes,\n+ temp_dir: str | None = None,\n+ ) -> pd.DataFrame:\n \"\"\"(Protected)\n Converts GRIB data (in binary format) into a pandas DataFrame.\n \n@@ -413,6 +422,7 @@ class WeatherForecast(ABC):\n \n Args:\n grib_str (bytes): Binary GRIB data as a byte string.\n+ temp_dir (str | None): Directory to store the temporary file. Defaults to None.\n \n Returns:\n pd.DataFrame: A pandas DataFrame containing the extracted GRIB data,\n@@ -427,8 +437,18 @@ class WeatherForecast(ABC):\n - The temporary file used for parsing is automatically deleted after use.\n - Ensure the input GRIB data is valid and encoded in a binary format.\n \"\"\"\n+ created_temp_dir = False\n+\n+ if temp_dir:\n+ if not os.path.exists(temp_dir):\n+ os.makedirs(temp_dir)\n+ created_temp_dir = True\n+ temp_subdir = os.path.join(temp_dir, \"temp_grib\")\n+ os.makedirs(temp_subdir, exist_ok=True)\n+ else:\n+ temp_subdir = tempfile.mkdtemp()\n \n- with tempfile.NamedTemporaryFile() as temp_file:\n+ with tempfile.NamedTemporaryFile(dir=temp_subdir, delete=False) as temp_file:\n # Write the GRIB binary data to the temporary file\n temp_file.write(grib_str)\n temp_file.flush() # Ensure the data is written to disk\n@@ -439,6 +459,11 @@ class WeatherForecast(ABC):\n # Convert the Dataset to a pandas DataFrame\n df = ds.to_dataframe().reset_index()\n \n+ if created_temp_dir and temp_dir is not None:\n+ shutil.rmtree(temp_dir)\n+ else:\n+ shutil.rmtree(temp_subdir)\n+\n return df\n \n def _get_data_single_forecast(\n@@ -449,6 +474,7 @@ class WeatherForecast(ABC):\n height: int | None,\n lat: tuple,\n long: tuple,\n+ temp_dir: str | None = None,\n ) -> pd.DataFrame:\n \"\"\"(Protected)\n Return the forecast's data for a given time and indicator.\n@@ -460,6 +486,7 @@ class WeatherForecast(ABC):\n forecast_horizon (int): the forecast horizon in hours (how many hours ahead)\n lat (tuple): minimum and maximum latitude\n long (tuple): minimum and maximum longitude\n+ temp_dir (str | None): Directory to store the temporary file. Defaults to None.\n \n Returns:\n pd.DataFrame: The forecast for the specified time.\n@@ -474,7 +501,7 @@ class WeatherForecast(ABC):\n long=long,\n )\n \n- df: pd.DataFrame = self._grib_bytes_to_df(grib_binary)\n+ df: pd.DataFrame = self._grib_bytes_to_df(grib_binary, temp_dir=temp_dir)\n \n # Drop and rename columns\n df.drop(columns=[\"surface\", \"valid_time\"], errors=\"ignore\", inplace=True)\n@@ -521,10 +548,7 @@ class WeatherForecast(ABC):\n long: tuple = (-12, 16),\n ) -> bytes:\n \"\"\"(Protected)\n- Retrieves raster data for a specified model prediction and saves it to a file.\n-\n- If no `filepath` is provided, the file is saved to a default cache directory under\n- the current working directory.\n+ Retrieves data for a specified model prediction.\n \n Args:\n coverage_id (str): The coverage ID to retrieve. Use `get_coverage` to list available coverage IDs.\n@@ -537,10 +561,6 @@ class WeatherForecast(ABC):\n Defaults to (37.5, 55.4), covering the latitudes of France.\n long (tuple[float, float], optional): Tuple specifying the minimum and maximum longitudes.\n Defaults to (-12, 16), covering the longitudes of France.\n- file_format (str, optional): The format of the raster file. Supported formats are \"grib\" and \"tiff\".\n- Defaults to \"grib\".\n- filepath (Path, optional): The file path where the raster file will be saved. If not specified,\n- the file is saved to a cache directory.\n \n Returns:\n Path: The file path to the saved raster data.\n@@ -605,6 +625,7 @@ class WeatherForecast(ABC):\n lat: tuple = FRANCE_METRO_LATITUDES,\n long: tuple = FRANCE_METRO_LONGITUDES,\n forecast_horizons: list[int] | None = None,\n+ temp_dir: str | None = None,\n ) -> pd.DataFrame:\n \"\"\"\n Get a combined DataFrame of coverage data for multiple indicators and different runs.\n@@ -624,6 +645,7 @@ class WeatherForecast(ABC):\n lat (tuple): The latitude range as (min_latitude, max_latitude). Defaults to FRANCE_METRO_LATITUDES.\n long (tuple): The longitude range as (min_longitude, max_longitude). Defaults to FRANCE_METRO_LONGITUDES.\n forecast_horizons (list[int] | None): A list of forecast horizon values in hours. Defaults to None.\n+ temp_dir (str | None): Directory to store the temporary file. Defaults to None.\n \n Returns:\n pd.DataFrame: A combined DataFrame containing coverage data for all specified runs and indicators.\n@@ -643,6 +665,7 @@ class WeatherForecast(ABC):\n pressures=pressures,\n intervals=intervals,\n forecast_horizons=forecast_horizons,\n+ temp_dir=temp_dir,\n )\n for run in runs\n ]\n@@ -658,6 +681,7 @@ class WeatherForecast(ABC):\n lat: tuple = FRANCE_METRO_LATITUDES,\n long: tuple = FRANCE_METRO_LONGITUDES,\n forecast_horizons: list[int] | None = None,\n+ temp_dir: str | None = None,\n ) -> pd.DataFrame:\n \"\"\"(Protected)\n Get a combined DataFrame of coverage data for a given run considering a list of indicators.\n@@ -677,6 +701,7 @@ class WeatherForecast(ABC):\n lat (tuple): The latitude range as (min_latitude, max_latitude). Defaults to FRANCE_METRO_LATITUDES.\n long (tuple): The longitude range as (min_longitude, max_longitude). Defaults to FRANCE_METRO_LONGITUDES.\n forecast_horizons (list[int] | None): A list of forecast horizon values in hours. Defaults to None.\n+ temp_dir (str | None): Directory to store the temporary file. Defaults to None.\n \n Returns:\n pd.DataFrame: A combined DataFrame containing coverage data for all specified runs and indicators.\n@@ -737,6 +762,7 @@ class WeatherForecast(ABC):\n heights=[height] if height is not None else [],\n pressures=[pressure] if pressure is not None else [],\n forecast_horizons=forecast_horizons,\n+ temp_dir=temp_dir,\n )\n for coverage_id, height, pressure in zip(coverage_ids, heights, pressures)\n ]\n", "test_patch": "diff --git a/tests/test_forecasts.py b/tests/test_forecasts.py\nindex fbe8f43..ef45f32 100644\n--- a/tests/test_forecasts.py\n+++ b/tests/test_forecasts.py\n@@ -235,7 +235,13 @@ class TestAromeForecast(unittest.TestCase):\n )\n \n mock_get_data_single_forecast.assert_called_once_with(\n- coverage_id=\"toto\", height=2, pressure=None, forecast_horizon=0, lat=(37.5, 55.4), long=(-12, 16)\n+ coverage_id=\"toto\",\n+ height=2,\n+ pressure=None,\n+ forecast_horizon=0,\n+ lat=(37.5, 55.4),\n+ long=(-12, 16),\n+ temp_dir=None,\n )\n \n @patch(\"meteole._arome.AromeForecast.get_coverage_description\")\n", "FAIL_TO_PASS": ["tests/test_forecasts.py::TestAromeForecast::test_get_coverage"]}], "all_FAIL_TO_PASS": ["tests/test_forecasts.py::TestAromeForecast::test_get_coverage"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Domain-Connect__domainconnect_python-5_x1", "level": 1, "source": "swerebench", "repo": "Domain-Connect/domainconnect_python", "image": "swerebench/sweb.eval.x86_64.domain-connect_1776_domainconnect_python-5:latest", "base_commit": "23f91c72851c6303c876bd1d6957c2236ac0e1cc", "num_bugs": 1, "bugs": [{"instance_id": "Domain-Connect__domainconnect_python-5", "base_commit": "23f91c72851c6303c876bd1d6957c2236ac0e1cc", "gold_patch": "diff --git a/README.md b/README.md\nindex 4e0bd1c..c96f770 100644\n--- a/README.md\n+++ b/README.md\n@@ -145,5 +145,6 @@ dc = DomainConnect(\n ## CHANGELOG\n | version | date | changes |\n | ------- | -----------| ------ |\n+| 0.0.7 | 2019-10-29 | Bugfix: error when setting up .app domain |\n | 0.0.6 | 2019-07-05 | UPDATE: moved from pycrypto to cryptography (due to know security issues) |\n | 0.0.5 | 2019-03-12 | NEW FEATURE: url signing capability added |\ndiff --git a/domainconnect/domainconnect.py b/domainconnect/domainconnect.py\nindex 1effe31..a66214f 100644\n--- a/domainconnect/domainconnect.py\n+++ b/domainconnect/domainconnect.py\n@@ -13,7 +13,7 @@ import time\n from six.moves import urllib\n from dns.exception import Timeout\n from dns.resolver import Resolver, NXDOMAIN, YXDOMAIN, NoAnswer, NoNameservers\n-from publicsuffix import PublicSuffixList\n+from publicsuffixlist import PublicSuffixList\n import webbrowser\n from .network import get_json, get_http, http_request_json, NetworkContext\n \n@@ -195,7 +195,7 @@ class DomainConnect:\n \n @staticmethod\n def identify_domain_root(domain):\n- return psl.get_public_suffix(domain)\n+ return psl.privatesuffix(domain)\n \n def _identify_domain_connect_api(self, domain_root):\n # noinspection PyBroadException\ndiff --git a/requirements.txt b/requirements.txt\nindex b933b75..e291b06 100644\n--- a/requirements.txt\n+++ b/requirements.txt\n@@ -1,11 +1,11 @@\n-asn1crypto==0.24.0\n-cffi==1.12.3\n-cryptography==2.7\n+asn1crypto==1.2.0\n+cffi==1.13.1\n+cryptography==2.8\n dnspython==1.16.0\n-future==0.17.1\n+future==0.18.1\n linecache2==1.0.0\n publicsuffix==1.1.0\n-publicsuffixlist==0.6.5\n+publicsuffixlist==0.6.11\n pybase64==0.5.0\n pycparser==2.19\n six==1.12.0\ndiff --git a/setup.py b/setup.py\nindex 6d4f36b..b95416c 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -3,7 +3,7 @@\n from setuptools import setup\n \n setup(name='domain_connect',\n- version='0.0.6',\n+ version='0.0.7',\n description='Python client library for Domain Connect protocol. See: https://domainconnect.org',\n long_description_content_type=\"text/markdown\",\n long_description=open('README.md').read(),\n@@ -19,11 +19,11 @@ setup(name='domain_connect',\n 'domainconnect',\n ],\n install_requires=[\n- 'dnspython >= 1.15.0',\n+ 'dnspython >= 1.16.0',\n 'publicsuffix >= 1.1.0',\n- 'publicsuffixlist >= 0.6.1',\n- 'six >= 1.11.0',\n- 'future >= 0.16.0',\n- 'cryptography >= 2.7'\n+ 'publicsuffixlist >= 0.6.11',\n+ 'six >= 1.12.0',\n+ 'future >= 0.18.1',\n+ 'cryptography >= 2.8'\n ],\n )\n", "test_patch": "diff --git a/domainconnect/tests/test_domainConnect.py b/domainconnect/tests/test_domainConnect.py\nindex 0d1022e..d610471 100644\n--- a/domainconnect/tests/test_domainConnect.py\n+++ b/domainconnect/tests/test_domainConnect.py\n@@ -185,6 +185,44 @@ class TestDomainConnect(TestCase):\n assert (res.urlAPI == config['API_URL']), 'urlAPI not correct: {}'.format(res.urlAPI)\n assert (res.providerName == config['PROVIDER_ID']), 'providerName not correct: {}'.format(res.providerName)\n \n+ domainroottests = [\n+ ('test.com', 'test.com', ''),\n+ ('subdomain.test.com', 'test.com', 'subdomain'),\n+ ('sub.subdomain.test.com', 'test.com', 'sub.subdomain'),\n+ ('test.co.uk', 'test.co.uk', ''),\n+ ('subdomain.test.co.uk', 'test.co.uk', 'subdomain'),\n+ ('sub.subdomain.test.co.uk', 'test.co.uk', 'sub.subdomain'),\n+ ('test.uk', 'test.uk', ''),\n+ ('subdomain.test.uk', 'test.uk', 'subdomain'),\n+ ('sub.subdomain.test.uk', 'test.uk', 'sub.subdomain'),\n+ ('test.com.de', 'test.com.de', ''),\n+ ('subdomain.test.com.de', 'test.com.de', 'subdomain'),\n+ ('sub.subdomain.test.com.de', 'test.com.de', 'sub.subdomain'),\n+ ('test.poznan.pl', 'test.poznan.pl', ''),\n+ ('subdomain.test.poznan.pl', 'test.poznan.pl', 'subdomain'),\n+ ('sub.subdomain.test.poznan.pl', 'test.poznan.pl', 'sub.subdomain'),\n+ ('get.app', 'get.app', ''),\n+ ('subdomain.get.app', 'get.app', 'subdomain'),\n+ ('sub.subdomain.get.app', 'get.app', 'sub.subdomain'),\n+ ('get.unkownnewtld', 'get.unkownnewtld', ''),\n+ ('subdomain.get.unkownnewtld', 'get.unkownnewtld', 'subdomain'),\n+ ('sub.subdomain.get.unkownnewtld', 'get.unkownnewtld', 'sub.subdomain'),\n+ ]\n+\n+ def test_get_domain_root(self):\n+ for i in TestDomainConnect.domainroottests:\n+ with self.subTest(i=i):\n+ self._test_get_domain_root(i)\n+\n+ @staticmethod\n+ def _test_get_domain_root(config):\n+ dc = DomainConnect()\n+ domain_root = dc.identify_domain_root(config[0]);\n+ assert domain_root is not None, \"No domain root found\"\n+ assert domain_root == config[1], \"Wrong domain root found. Expected {}, Found {}\".format(config[1], domain_root)\n+ assert '{}{}{}'.format(config[2], '' if config[2] == '' else '.', domain_root) == config[0], \"Domain root + subdomain != domain\"\n+\n+\n def test_get_domain_connect_template_async_url(self):\n for i in configs:\n with self.subTest(i=i):\n", "FAIL_TO_PASS": ["domainconnect/tests/test_domainConnect.py::TestDomainConnect::test_get_domain_root"]}], "all_FAIL_TO_PASS": ["domainconnect/tests/test_domainConnect.py::TestDomainConnect::test_get_domain_root"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "DataBiosphere__toil-4805_x1", "level": 1, "source": "swerebench", "repo": "DataBiosphere/toil", "image": "swerebench/sweb.eval.x86_64.databiosphere_1776_toil-4805:latest", "base_commit": "6558c7f97fb37c6ef6f469c7ae614109050322f4", "num_bugs": 1, "bugs": [{"instance_id": "DataBiosphere__toil-4805", "base_commit": "6558c7f97fb37c6ef6f469c7ae614109050322f4", "gold_patch": "diff --git a/src/toil/options/common.py b/src/toil/options/common.py\nindex 61086f3d..5c041f3b 100644\n--- a/src/toil/options/common.py\n+++ b/src/toil/options/common.py\n@@ -733,4 +733,4 @@ def add_base_toil_options(parser: ArgumentParser, jobstore_as_flag: bool = False\n \n # dest is set to enableCaching to not conflict with the current --caching destination\n caching.add_argument('--disableCaching', dest='enableCaching', action='store_false', help=SUPPRESS)\n- caching.set_defaults(disableCaching=None)\n+ caching.set_defaults(enableCaching=None)\n", "test_patch": "diff --git a/src/toil/test/options/__init__.py b/src/toil/test/options/__init__.py\nnew file mode 100644\nindex 00000000..471fe7cd\n--- /dev/null\n+++ b/src/toil/test/options/__init__.py\n@@ -0,0 +1,13 @@\n+# Copyright (C) 2015-2021 Regents of the University of California\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\ndiff --git a/src/toil/test/options/options.py b/src/toil/test/options/options.py\nnew file mode 100644\nindex 00000000..c3c30749\n--- /dev/null\n+++ b/src/toil/test/options/options.py\n@@ -0,0 +1,37 @@\n+from configargparse import ArgParser\n+\n+from toil.common import addOptions, Toil\n+from toil.test import ToilTest\n+\n+\n+class OptionsTest(ToilTest):\n+ \"\"\"\n+ Class to test functionality of all Toil options\n+ \"\"\"\n+ def test_default_caching_slurm(self):\n+ \"\"\"\n+ Test to ensure that caching will be set to false when running on Slurm\n+ :return:\n+ \"\"\"\n+ parser = ArgParser()\n+ addOptions(parser, jobstore_as_flag=True, wdl=False, cwl=False)\n+ test_args = [\"--jobstore=example-jobstore\", \"--batchSystem=slurm\"]\n+ options = parser.parse_args(test_args)\n+ with Toil(options) as toil:\n+ caching_value = toil.config.caching\n+ self.assertEqual(caching_value, False)\n+\n+ def test_caching_option_priority(self):\n+ \"\"\"\n+ Test to ensure that the --caching option takes priority over the default_caching() return value\n+ :return:\n+ \"\"\"\n+ parser = ArgParser()\n+ addOptions(parser, jobstore_as_flag=True, wdl=False, cwl=False)\n+ # the kubernetes batchsystem (and I think all batchsystems including singlemachine) return False\n+ # for default_caching\n+ test_args = [\"--jobstore=example-jobstore\", \"--batchSystem=kubernetes\", \"--caching=True\"]\n+ options = parser.parse_args(test_args)\n+ with Toil(options) as toil:\n+ caching_value = toil.config.caching\n+ self.assertEqual(caching_value, True)\n", "FAIL_TO_PASS": ["src/toil/test/options/options.py::OptionsTest::test_default_caching_slurm"]}], "all_FAIL_TO_PASS": ["src/toil/test/options/options.py::OptionsTest::test_default_caching_slurm"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "CodeForPhilly__chime-418_x1", "level": 1, "source": "swerebench", "repo": "CodeForPhilly/chime", "image": "swerebench/sweb.eval.x86_64.codeforphilly_1776_chime-418:latest", "base_commit": "e6ff8aaa0be2be7c27ec9b98611147650d414270", "num_bugs": 1, "bugs": [{"instance_id": "CodeForPhilly__chime-418", "base_commit": "e6ff8aaa0be2be7c27ec9b98611147650d414270", "gold_patch": "diff --git a/src/penn_chime/models.py b/src/penn_chime/models.py\nindex da7311f..6582b1c 100644\n--- a/src/penn_chime/models.py\n+++ b/src/penn_chime/models.py\n@@ -9,7 +9,7 @@ from __future__ import annotations\n from datetime import date, datetime, timedelta\n from logging import INFO, basicConfig, getLogger\n from sys import stdout\n-from typing import Dict, Generator, Tuple, Sequence,Optional\n+from typing import Dict, Generator, Tuple, Sequence, Optional\n \n import numpy as np\n import pandas as pd\n@@ -66,14 +66,13 @@ class SimSirModel:\n intrinsic_growth_rate = get_growth_rate(p.doubling_time)\n \n self.beta = get_beta(intrinsic_growth_rate, gamma, self.susceptible, 0.0)\n+ self.beta_t = get_beta(intrinsic_growth_rate, self.gamma, self.susceptible, p.relative_contact_rate)\n \n self.i_day = 0 # seed to the full length\n- self.beta_t = self.beta\n- self.run_projection(p)\n+ self.run_projection(p, [(self.beta, p.n_days)])\n self.i_day = i_day = int(get_argmin_ds(self.census_df, p.current_hospitalized))\n \n- self.beta_t = get_beta(intrinsic_growth_rate, self.gamma, self.susceptible, p.relative_contact_rate)\n- self.run_projection(p)\n+ self.run_projection(p, self.gen_policy(p))\n \n logger.info('Set i_day = %s', i_day)\n p.date_first_hospitalized = p.current_date - timedelta(days=i_day)\n@@ -100,7 +99,7 @@ class SimSirModel:\n self.beta = get_beta(intrinsic_growth_rate, self.gamma, self.susceptible, 0.0)\n self.beta_t = get_beta(intrinsic_growth_rate, self.gamma, self.susceptible, p.relative_contact_rate)\n \n- self.run_projection(p)\n+ self.run_projection(p, self.gen_policy(p))\n loss = self.get_loss()\n losses[i] = loss\n \n@@ -109,7 +108,7 @@ class SimSirModel:\n intrinsic_growth_rate = get_growth_rate(p.doubling_time)\n self.beta = get_beta(intrinsic_growth_rate, self.gamma, self.susceptible, 0.0)\n self.beta_t = get_beta(intrinsic_growth_rate, self.gamma, self.susceptible, p.relative_contact_rate)\n- self.run_projection(p)\n+ self.run_projection(p, self.gen_policy(p))\n \n self.population = p.population\n else:\n@@ -146,18 +145,35 @@ class SimSirModel:\n self.daily_growth_rate = get_growth_rate(p.doubling_time)\n self.daily_growth_rate_t = get_growth_rate(self.doubling_time_t)\n \n- def run_projection(self, p):\n+ def gen_policy(self, p: Parameters) -> Sequence[Tuple[float, int]]:\n+ if p.mitigation_date is not None:\n+ mitigation_day = -(p.current_date - p.mitigation_date).days\n+ else:\n+ mitigation_day = 0\n+\n+ total_days = self.i_day + p.n_days\n+\n+ if mitigation_day < -self.i_day:\n+ mitigation_day = -self.i_day\n+\n+ pre_mitigation_days = self.i_day + mitigation_day\n+ post_mitigation_days = total_days - pre_mitigation_days\n+\n+ return [\n+ (self.beta, pre_mitigation_days),\n+ (self.beta_t, post_mitigation_days),\n+ ]\n+\n+ def run_projection(self, p: Parameters, policy: Sequence[Tuple[float, int]]):\n self.raw_df = sim_sir_df(\n self.susceptible,\n self.infected,\n p.recovered,\n self.gamma,\n -self.i_day,\n- self.beta,\n- self.i_day,\n- self.beta_t,\n- p.n_days\n+ policy\n )\n+\n self.dispositions_df = build_dispositions_df(self.raw_df, self.rates, p.market_share, p.current_date)\n self.admits_df = build_admits_df(self.dispositions_df)\n self.census_df = build_census_df(self.admits_df, self.days)\n@@ -221,7 +237,7 @@ def sir(\n \n \n def gen_sir(\n- s: float, i: float, r: float, gamma: float, i_day: int, *args\n+ s: float, i: float, r: float, gamma: float, i_day: int, policies: Sequence[Tuple[float, int]]\n ) -> Generator[Tuple[int, float, float, float], None, None]:\n \"\"\"Simulate SIR model forward in time yielding tuples.\n Parameter order has changed to allow multiple (beta, n_days)\n@@ -230,8 +246,7 @@ def gen_sir(\n s, i, r = (float(v) for v in (s, i, r))\n n = s + i + r\n d = i_day\n- while args:\n- beta, n_days, *args = args\n+ for beta, n_days in policies:\n for _ in range(n_days):\n yield d, s, i, r\n s, i, r = sir(s, i, r, beta, gamma, n)\n@@ -241,11 +256,11 @@ def gen_sir(\n \n def sim_sir_df(\n s: float, i: float, r: float,\n- gamma: float, i_day: int, *args\n+ gamma: float, i_day: int, policies: Sequence[Tuple[float, int]]\n ) -> pd.DataFrame:\n \"\"\"Simulate the SIR model forward in time.\"\"\"\n return pd.DataFrame(\n- data=gen_sir(s, i, r, gamma, i_day, *args),\n+ data=gen_sir(s, i, r, gamma, i_day, policies),\n columns=(\"day\", \"susceptible\", \"infected\", \"recovered\"),\n )\n \ndiff --git a/src/penn_chime/parameters.py b/src/penn_chime/parameters.py\nindex d9da047..d6c03a0 100644\n--- a/src/penn_chime/parameters.py\n+++ b/src/penn_chime/parameters.py\n@@ -55,6 +55,7 @@ class Parameters:\n hospitalized: Disposition,\n icu: Disposition,\n relative_contact_rate: float,\n+ mitigation_date: Optional[date] = None,\n ventilated: Disposition,\n current_date: date = date.today(),\n date_first_hospitalized: Optional[date] = None,\n@@ -68,7 +69,6 @@ class Parameters:\n region: Optional[Regions] = None,\n ):\n self.current_hospitalized = Positive(value=current_hospitalized)\n- self.relative_contact_rate = Rate(value=relative_contact_rate)\n \n Rate(value=hospitalized.rate), Rate(value=icu.rate), Rate(value=ventilated.rate)\n StrictlyPositive(value=hospitalized.days), StrictlyPositive(value=icu.days),\n@@ -92,6 +92,9 @@ class Parameters:\n self.date_first_hospitalized = OptionalDate(value=date_first_hospitalized)\n self.doubling_time = OptionalStrictlyPositive(value=doubling_time)\n \n+ self.relative_contact_rate = Rate(value=relative_contact_rate)\n+ self.mitigation_date = OptionalDate(value=mitigation_date)\n+\n self.infectious_days = StrictlyPositive(value=infectious_days)\n self.market_share = Rate(value=market_share)\n self.max_y_axis = OptionalStrictlyPositive(value=max_y_axis)\ndiff --git a/src/penn_chime/presentation.py b/src/penn_chime/presentation.py\nindex 6492e1b..0f50f42 100644\n--- a/src/penn_chime/presentation.py\n+++ b/src/penn_chime/presentation.py\n@@ -11,6 +11,7 @@ from .constants import (\n CHANGE_DATE,\n DATE_FORMAT,\n DOCS_URL,\n+ EPSILON,\n FLOAT_INPUT_MIN,\n FLOAT_INPUT_STEP,\n )\n@@ -207,6 +208,10 @@ def display_sidebar(st, d: Parameters) -> Parameters:\n st_obj, \"Date of first hospitalized case - Enter this date to have chime estimate the initial doubling time\",\n value=d.date_first_hospitalized,\n )\n+ mitigation_date_input = DateInput(\n+ st_obj, \"Date of social distancing measures effect (may be delayed from implementation)\",\n+ value=d.mitigation_date\n+ )\n relative_contact_pct_input = PercentInput(\n st_obj,\n \"Social distancing (% reduction in social contact going forward)\",\n@@ -312,7 +317,15 @@ def display_sidebar(st, d: Parameters) -> Parameters:\n doubling_time = doubling_time_input()\n date_first_hospitalized = None\n \n- relative_contact_rate = relative_contact_pct_input()\n+ if st.sidebar.checkbox(\n+ \"Social distancing measures have been implemented\",\n+ value=(d.relative_contact_rate > EPSILON)\n+ ):\n+ mitigation_date = mitigation_date_input()\n+ relative_contact_rate = relative_contact_pct_input()\n+ else:\n+ mitigation_date = None\n+ relative_contact_rate = EPSILON\n \n st.sidebar.markdown(\n \"### Severity Parameters [\u2139]({docs_url}/what-is-chime/parameters#severity-parameters)\".format(\n@@ -346,6 +359,7 @@ def display_sidebar(st, d: Parameters) -> Parameters:\n hospitalized=Disposition(hospitalized_rate, hospitalized_days),\n icu=Disposition(icu_rate, icu_days),\n relative_contact_rate=relative_contact_rate,\n+ mitigation_date=mitigation_date,\n ventilated=Disposition(ventilated_rate, ventilated_days),\n current_date=current_date,\n date_first_hospitalized=date_first_hospitalized,\ndiff --git a/src/penn_chime/settings.py b/src/penn_chime/settings.py\nindex 0bd1298..a9ccb34 100644\n--- a/src/penn_chime/settings.py\n+++ b/src/penn_chime/settings.py\n@@ -16,6 +16,7 @@ def get_defaults():\n infectious_days=14,\n market_share=0.15,\n n_days=100,\n+ mitigation_date=date.today(),\n relative_contact_rate=0.3,\n ventilated=Disposition(0.005, 10),\n )\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex e822d91..b7cf01f 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -51,6 +51,7 @@ def DEFAULTS():\n doubling_time=4.0,\n n_days=60,\n market_share=0.15,\n+ mitigation_date=datetime(year=2020, month=3, day=28),\n relative_contact_rate=0.3,\n hospitalized=Disposition(0.025, 7),\n icu=Disposition(0.0075, 9),\n@@ -65,6 +66,7 @@ def param():\n current_hospitalized=100,\n doubling_time=6.0,\n market_share=0.05,\n+ mitigation_date=datetime(year=2020, month=3, day=28),\n relative_contact_rate=0.15,\n population=500000,\n hospitalized=Disposition(0.05, 7),\n@@ -81,6 +83,7 @@ def halving_param():\n current_hospitalized=100,\n doubling_time=6.0,\n market_share=0.05,\n+ mitigation_date=datetime(year=2020, month=3, day=28),\n relative_contact_rate=0.7,\n population=500000,\n hospitalized=Disposition(0.05, 7),\ndiff --git a/tests/penn_chime/test_models.py b/tests/penn_chime/test_models.py\nindex a8c4129..d5e6de2 100644\n--- a/tests/penn_chime/test_models.py\n+++ b/tests/penn_chime/test_models.py\n@@ -3,11 +3,13 @@ from datetime import date\n import pytest\n import pandas as pd\n import numpy as np\n+from datetime import timedelta\n \n from src.penn_chime.models import (\n sir,\n sim_sir_df,\n get_growth_rate,\n+ SimSirModel,\n )\n \n from src.penn_chime.constants import EPSILON\n@@ -64,7 +66,7 @@ def test_sim_sir():\n Rounding to move fast past decimal place issues\n \"\"\"\n raw_df = sim_sir_df(\n- 5, 6, 7, 0.1, 0, 0.1, 40, # s # i # r # gamma # i_day # beta1 # n_days1\n+ 5, 6, 7, 0.1, 0, [(0.1, 40)], # s # i # r # gamma # i_day # beta1 # n_days1\n )\n \n first = raw_df.iloc[0, :]\n@@ -100,6 +102,20 @@ def test_model(model, param):\n assert model.r_t == 2.307298374881539\n assert model.r_naught == 2.7144686763312222\n assert model.doubling_time_t == 7.764405988534983\n+ assert model.i_day == 43\n+\n+\n+def test_model_first_hosp_fit(param):\n+ param.date_first_hospitalized = param.current_date - timedelta(days=43)\n+ param.doubling_time = None\n+\n+ my_model = SimSirModel(param)\n+\n+ assert my_model.intrinsic_growth_rate == 0.12246204830937302\n+ assert abs(my_model.beta - 4.21501347256401e-07) < EPSILON\n+ assert my_model.r_t == 2.307298374881539\n+ assert my_model.r_naught == 2.7144686763312222\n+ assert my_model.doubling_time_t == 7.764405988534983\n \n \n def test_model_raw_start(model, param):\n", "FAIL_TO_PASS": ["[", "[100%]", "tests/penn_chime/test_models.py::test_sim_sir", "tests/penn_chime/test_models.py::test_model", "tests/penn_chime/test_models.py::test_model_first_hosp_fit", "tests/penn_chime/test_models.py::test_model_raw_start", "tests/penn_chime/test_models.py::test_model_conservation", "tests/penn_chime/test_models.py::test_model_raw_end", "tests/penn_chime/test_models.py::test_model_monotonicity", "tests/penn_chime/test_models.py::test_model_cumulative_census"]}], "all_FAIL_TO_PASS": ["[", "[100%]", "tests/penn_chime/test_models.py::test_sim_sir", "tests/penn_chime/test_models.py::test_model", "tests/penn_chime/test_models.py::test_model_first_hosp_fit", "tests/penn_chime/test_models.py::test_model_raw_start", "tests/penn_chime/test_models.py::test_model_conservation", "tests/penn_chime/test_models.py::test_model_raw_end", "tests/penn_chime/test_models.py::test_model_monotonicity", "tests/penn_chime/test_models.py::test_model_cumulative_census"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Point72__ccflow-24_x1", "level": 1, "source": "swerebench", "repo": "Point72/ccflow", "image": "swerebench/sweb.eval.x86_64.point72_1776_ccflow-24:latest", "base_commit": "67f4b6dcbb387e2e486e408806789d94c9b02886", "num_bugs": 1, "bugs": [{"instance_id": "Point72__ccflow-24", "base_commit": "67f4b6dcbb387e2e486e408806789d94c9b02886", "gold_patch": "diff --git a/ccflow/callable.py b/ccflow/callable.py\nindex 24c84d4..0af31bd 100644\n--- a/ccflow/callable.py\n+++ b/ccflow/callable.py\n@@ -147,7 +147,11 @@ class _CallableModel(BaseModel, abc.ABC):\n \n @abc.abstractmethod\n def __call__(self, context: ContextType) -> ResultType:\n- \"\"\"This method produces the result. Implementations should be decorated with Flow.call.\"\"\"\n+ \"\"\"This method produces the result for the given context.\n+\n+ Instead of passing the context, one can pass an object that pydantic will try to validate as the context.\n+ Additionally, if kwargs are passed instead of the context, it will use these to construct the context.\n+ \"\"\"\n \n @abc.abstractmethod\n def __deps__(\n@@ -234,7 +238,7 @@ class FlowOptions(BaseModel):\n return self._get_evaluator_from_options(options)\n \n def __call__(self, fn):\n- def wrapper(model, context=Signature.empty):\n+ def wrapper(model, context=Signature.empty, **kwargs):\n # TODO: Let ModelEvaluationContext handle this type checking\n if not isinstance(model, CallableModel):\n raise TypeError(\"Can only decorate methods on CallableModels with the flow decorator\")\n@@ -245,7 +249,15 @@ class FlowOptions(BaseModel):\n if context is Signature.empty:\n context = _cached_signature(fn).parameters[\"context\"].default\n if context is Signature.empty:\n- raise TypeError(f\"{fn.__name__}() missing 1 required positional argument: 'context'\")\n+ if kwargs:\n+ context = kwargs\n+ else:\n+ raise TypeError(\n+ f\"{fn.__name__}() missing 1 required positional argument: 'context' of type {model.context_type}, or kwargs to construct it\"\n+ )\n+ elif kwargs: # Kwargs passed in as well as context. Not allowed\n+ raise TypeError(f\"{fn.__name__}() was passed a context and got an unexpected keyword argument '{next(iter(kwargs.keys()))}'\")\n+\n # Type coercion on input TODO: Move to ModelEvaluationContext\n if not isinstance(context, model.context_type):\n context = model.context_type.model_validate(context)\n", "test_patch": "diff --git a/ccflow/tests/test_callable.py b/ccflow/tests/test_callable.py\nindex 56e1f55..43539ef 100644\n--- a/ccflow/tests/test_callable.py\n+++ b/ccflow/tests/test_callable.py\n@@ -198,6 +198,22 @@ class TestCallableModel(TestCase):\n self.assertIn(\"type_\", out)\n self.assertNotIn(\"context_type\", out)\n \n+ def test_signature(self):\n+ m = MyCallable(i=5)\n+ context = MyContext(a=\"foo\")\n+ target = m(context)\n+ self.assertEqual(m(context=context), m(context))\n+ # Validate from dict\n+ self.assertEqual(m(dict(a=\"foo\")), target)\n+ self.assertEqual(m(context=dict(a=\"foo\")), target)\n+ # Kwargs passed in\n+ self.assertEqual(m(a=\"foo\"), target)\n+ # No argument\n+ self.assertRaises(TypeError, m)\n+ # context and kwargs\n+ self.assertRaises(TypeError, m, context, a=\"foo\")\n+ self.assertRaises(TypeError, m, context=context, a=\"foo\")\n+\n def test_inheritance(self):\n m = MyCallableChild(i=5)\n self.assertEqual(m(MyContext(a=\"foo\")), MyResult(x=5, y=\"foo\"))\n", "FAIL_TO_PASS": ["ccflow/tests/test_callable.py::TestCallableModel::test_signature"]}], "all_FAIL_TO_PASS": ["ccflow/tests/test_callable.py::TestCallableModel::test_signature"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Nike-Inc__gimme-aws-creds-464_x1", "level": 1, "source": "swerebench", "repo": "Nike-Inc/gimme-aws-creds", "image": "swerebench/sweb.eval.x86_64.nike-inc_1776_gimme-aws-creds-464:latest", "base_commit": "763ae83ca4f5338ffdaeb788b4ac83542d72df6d", "num_bugs": 1, "bugs": [{"instance_id": "Nike-Inc__gimme-aws-creds-464", "base_commit": "763ae83ca4f5338ffdaeb788b4ac83542d72df6d", "gold_patch": "diff --git a/gimme_aws_creds/config.py b/gimme_aws_creds/config.py\nindex fe541d3..b5a881b 100644\n--- a/gimme_aws_creds/config.py\n+++ b/gimme_aws_creds/config.py\n@@ -201,23 +201,22 @@ class Config(object):\n profile_config[key] = True\n elif profile_config[key] == 'False':\n profile_config[key] = False\n- \n- # Empty string in force_classic should be handled as True - this makes sure that migrating from Classic to OIE is seamless\n- if profile_config.get('force_classic') == '' or profile_config.get('force_classic') is None:\n- profile_config['force_classic'] = True\n \n if \"inherits\" in profile_config.keys() and include_inherits:\n self.ui.message(\"Using inherited config: \" + profile_config[\"inherits\"])\n if profile_config[\"inherits\"] not in config:\n raise errors.GimmeAWSCredsError(self.conf_profile + \" inherits from \" + profile_config[\"inherits\"] + \", but could not find \" + profile_config[\"inherits\"])\n- combined_config = {\n+ profile_config = {\n **self._handle_config(config, dict(config[profile_config[\"inherits\"]])),\n **profile_config,\n }\n- del combined_config[\"inherits\"]\n- return combined_config\n- else:\n- return profile_config\n+ del profile_config[\"inherits\"]\n+\n+ # Empty string in force_classic should be handled as True - this makes sure that migrating from Classic to OIE is seamless\n+ if profile_config.get('force_classic') == '' or profile_config.get('force_classic') is None:\n+ profile_config['force_classic'] = True\n+\n+ return profile_config\n \n def get_config_dict(self, include_inherits = True):\n \"\"\"returns the conf dict from the okta config file\"\"\"\n", "test_patch": "diff --git a/tests/test_config.py b/tests/test_config.py\nindex fc1390f..d327c85 100644\n--- a/tests/test_config.py\n+++ b/tests/test_config.py\n@@ -122,6 +122,35 @@ aws_rolename = myrole\n \"force_classic\": True\n })\n \n+ def test_read_nested_config_inherited_no_force_classic(self):\n+ \"\"\"Test to make sure getting config works when inherited\"\"\"\n+ test_ui = MockUserInterface(argv = [\n+ \"--profile\",\n+ \"myprofile\",\n+ ])\n+ with open(test_ui.HOME + \"/.okta_aws_login_config\", \"w\") as config_file:\n+ config_file.write(\"\"\"\n+[mybase-level1]\n+client_id = bar\n+[mybase-level2]\n+inherits = mybase-level1\n+aws_appname = baz\n+force_classic = False\n+[myprofile]\n+inherits = mybase-level2\n+client_id = foo\n+aws_rolename = myrole\n+\"\"\")\n+ config = Config(gac_ui=test_ui, create_config=False)\n+ config.conf_profile = \"myprofile\"\n+ profile_config = config.get_config_dict()\n+ self.assertEqual(profile_config, {\n+ \"client_id\": \"foo\",\n+ \"aws_appname\": \"baz\",\n+ \"aws_rolename\": \"myrole\",\n+ \"force_classic\": False\n+ })\n+\n def test_fail_if_profile_not_found(self):\n \"\"\"Test to make sure missing Default fails properly\"\"\"\n test_ui = MockUserInterface(argv=[])\n", "FAIL_TO_PASS": ["tests/test_config.py::TestConfig::test_read_nested_config_inherited_no_force_classic"]}], "all_FAIL_TO_PASS": ["tests/test_config.py::TestConfig::test_read_nested_config_inherited_no_force_classic"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Chilipp__autodocsumm-101_x1", "level": 1, "source": "swerebench", "repo": "Chilipp/autodocsumm", "image": "swerebench/sweb.eval.x86_64.chilipp_1776_autodocsumm-101:latest", "base_commit": "354e67b443fe212401b1fc0f9e2f0d669c5852c4", "num_bugs": 1, "bugs": [{"instance_id": "Chilipp__autodocsumm-101", "base_commit": "354e67b443fe212401b1fc0f9e2f0d669c5852c4", "gold_patch": "diff --git a/autodocsumm/__init__.py b/autodocsumm/__init__.py\nindex 5808308..9727ec1 100755\n--- a/autodocsumm/__init__.py\n+++ b/autodocsumm/__init__.py\n@@ -414,7 +414,11 @@ class AutoSummClassDocumenter(ClassDocumenter, AutosummaryDocumenter):\n def add_content(self, *args, **kwargs):\n super().add_content(*args, **kwargs)\n \n- self.add_autosummary(relative_ref_paths=True)\n+ # If the class is already documented under another name, Sphinx\n+ # documents it as data/attribute. In this case, we do not want to\n+ # generate an autosummary of the class for the attribute (see #69).\n+ if not self.doc_as_attr:\n+ self.add_autosummary(relative_ref_paths=True)\n \n \n class CallableDataDocumenter(DataDocumenter):\n", "test_patch": "diff --git a/tests/test-root/dummy.py b/tests/test-root/dummy.py\nindex 36be801..f980498 100644\n--- a/tests/test-root/dummy.py\n+++ b/tests/test-root/dummy.py\n@@ -84,6 +84,14 @@ class TestClassWithInlineAutoClassSumm:\n pass\n \n \n+class TestClassWithRefToOtherClass:\n+ \"\"\"Class test for the autodocsummary when a class attribute is a reference\n+ to another class. No autosummary of the class should be generated for\n+ the attribute. See also issue #69\"\"\"\n+\n+ foo = TestClass\n+\n+\n #: data to be skipped\n large_data = 'Should also be skipped'\n \ndiff --git a/tests/test-root/test_class_with_ref_to_other_class.rst b/tests/test-root/test_class_with_ref_to_other_class.rst\nnew file mode 100644\nindex 0000000..4cbb5cf\n--- /dev/null\n+++ b/tests/test-root/test_class_with_ref_to_other_class.rst\n@@ -0,0 +1,6 @@\n+Autoclasssumm of Dummy Class\n+============================\n+\n+.. autoclass:: dummy.TestClassWithRefToOtherClass\n+ :members:\n+ :autosummary:\ndiff --git a/tests/test_autodocsumm.py b/tests/test_autodocsumm.py\nindex 1fdcb59..fd16399 100644\n--- a/tests/test_autodocsumm.py\n+++ b/tests/test_autodocsumm.py\n@@ -322,6 +322,22 @@ class TestAutosummaryDocumenter:\n \n assert '()' not in html\n \n+ def test_class_no_summary_for_reference_to_class(self, app):\n+ # see also: issue #69\n+ app.build()\n+\n+ html = get_html(app, 'test_class_with_ref_to_other_class.html')\n+\n+ # assert that the class itself has an autosummary that contains its\n+ # attributes\n+ assert in_autosummary(\"foo\", html)\n+\n+ # Assert that there is no autosummary of the attribute that is an alias\n+ # of another class. This autosummary would contain attrs/methods/...\n+ # of the referenced class.\n+ assert not in_autosummary(\"test_method\", html)\n+ assert not in_autosummary(\"test_attr\", html)\n+\n def test_inherited(self, app):\n app.build()\n html = get_html(app, 'test_inherited.html')\n", "FAIL_TO_PASS": ["tests/test_autodocsumm.py::TestAutosummaryDocumenter::test_class_no_summary_for_reference_to_class"]}], "all_FAIL_TO_PASS": ["tests/test_autodocsumm.py::TestAutosummaryDocumenter::test_class_no_summary_for_reference_to_class"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "LSSTDESC__sacc-79_x1", "level": 1, "source": "swerebench", "repo": "LSSTDESC/sacc", "image": "swerebench/sweb.eval.x86_64.lsstdesc_1776_sacc-79:latest", "base_commit": "64e6fae3f7bad5151815000ba49aa7f8f6585a5f", "num_bugs": 1, "bugs": [{"instance_id": "LSSTDESC__sacc-79", "base_commit": "64e6fae3f7bad5151815000ba49aa7f8f6585a5f", "gold_patch": "diff --git a/sacc/sacc.py b/sacc/sacc.py\nindex fcf963d..1cebbba 100644\n--- a/sacc/sacc.py\n+++ b/sacc/sacc.py\n@@ -198,7 +198,7 @@ class Sacc:\n d = DataPoint(data_type, tracers, value, **tags)\n self.data.append(d)\n \n- def add_covariance(self, covariance):\n+ def add_covariance(self, covariance, overwrite=False):\n \"\"\"\n Once you have finished adding data points, add a covariance\n for the entire set.\n@@ -208,11 +208,19 @@ class Sacc:\n covariance: array or list\n 2x2 numpy array containing the covariance of the added data points\n OR a list of blocks\n+ overwrite: bool\n+ If True, it overwrites the stored covariance matrix with the given\n+ one.\n \n Returns\n -------\n None\n \"\"\"\n+ if self.has_covariance() and not overwrite:\n+ raise RuntimeError(\"This sacc file already contains a covariance\"\n+ \"matrix. Use overwrite=True if you want to \"\n+ \"replace it for the new one\")\n+\n if isinstance(covariance, BaseCovariance):\n cov = covariance\n else:\n", "test_patch": "diff --git a/test/test_sacc2.py b/test/test_sacc2.py\nindex 771d6c6..3d79d3f 100644\n--- a/test/test_sacc2.py\n+++ b/test/test_sacc2.py\n@@ -66,6 +66,18 @@ def get_filled_sacc():\n return s\n \n \n+def test_add_covariance():\n+ s = get_filled_sacc()\n+ cov = np.ones((s.mean.size, s.mean.size))\n+ s.add_covariance(cov)\n+\n+ with pytest.raises(RuntimeError):\n+ s.add_covariance(cov)\n+\n+ s.add_covariance(0 * cov, overwrite=True)\n+ assert np.all(s.covariance.covmat == 0 * cov)\n+\n+\n def test_quantity_warning():\n s = sacc.Sacc()\n with pytest.warns(UserWarning):\n", "FAIL_TO_PASS": ["test/test_sacc2.py::test_add_covariance"]}], "all_FAIL_TO_PASS": ["test/test_sacc2.py::test_add_covariance"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "All-Hands-AI__openhands-resolver-123_x1", "level": 1, "source": "swerebench", "repo": "All-Hands-AI/openhands-resolver", "image": "swerebench/sweb.eval.x86_64.all-hands-ai_1776_openhands-resolver-123:latest", "base_commit": "84ccb9b29d786c3cb16f100b31ee456ddc622fd0", "num_bugs": 1, "bugs": [{"instance_id": "All-Hands-AI__openhands-resolver-123", "base_commit": "84ccb9b29d786c3cb16f100b31ee456ddc622fd0", "gold_patch": "diff --git a/openhands_resolver/send_pull_request.py b/openhands_resolver/send_pull_request.py\nindex dd227b7..3d06d3e 100644\n--- a/openhands_resolver/send_pull_request.py\n+++ b/openhands_resolver/send_pull_request.py\n@@ -139,6 +139,11 @@ def make_commit(repo_dir: str, issue: GithubIssue) -> None:\n raise RuntimeError(\"Failed to commit changes\")\n \n \n+\n+def branch_exists(base_url: str, branch_name: str, headers: dict) -> bool:\n+ response = requests.get(f\"{base_url}/branches/{branch_name}\", headers=headers)\n+ return response.status_code == 200\n+\n def send_pull_request(\n github_issue: GithubIssue,\n github_token: str,\n@@ -158,15 +163,21 @@ def send_pull_request(\n }\n base_url = f\"https://api.github.com/repos/{github_issue.owner}/{github_issue.repo}\"\n \n- # Create a new branch\n- branch_name = f\"openhands-fix-issue-{github_issue.number}\"\n+ # Create a new branch with a unique name\n+ base_branch_name = f\"openhands-fix-issue-{github_issue.number}\"\n+ branch_name = base_branch_name\n+ attempt = 1\n+\n+ while branch_exists(base_url, branch_name, headers):\n+ attempt += 1\n+ branch_name = f\"{base_branch_name}-try{attempt}\"\n \n # Get the default branch\n response = requests.get(f\"{base_url}\", headers=headers)\n response.raise_for_status()\n default_branch = response.json()[\"default_branch\"]\n \n- # Push changes to the new branch (using git command, as before)\n+ # Create and checkout the new branch\n result = subprocess.run(\n f\"git -C {patch_dir} checkout -b {branch_name}\",\n shell=True,\n", "test_patch": "diff --git a/tests/test_send_pull_request.py b/tests/test_send_pull_request.py\nindex b67edd5..fb2f393 100644\n--- a/tests/test_send_pull_request.py\n+++ b/tests/test_send_pull_request.py\n@@ -213,7 +213,10 @@ def test_send_pull_request(\n repo_path = os.path.join(mock_output_dir, \"repo\")\n \n # Mock API responses\n- mock_get.return_value = MagicMock(json=lambda: {\"default_branch\": \"main\"})\n+ mock_get.side_effect = [\n+ MagicMock(status_code=404), # Branch doesn't exist\n+ MagicMock(json=lambda: {\"default_branch\": \"main\"})\n+ ]\n mock_post.return_value.json.return_value = {\n \"html_url\": \"https://github.com/test-owner/test-repo/pull/1\"\n }\n@@ -234,7 +237,7 @@ def test_send_pull_request(\n )\n \n # Assert API calls\n- assert mock_get.call_count == 1\n+ assert mock_get.call_count == 2\n \n # Check branch creation and push\n assert mock_run.call_count == 2\n@@ -521,6 +524,58 @@ def test_process_all_successful_issues(\n # Add more assertions as needed to verify the behavior of the function\n \n \n+\n+@patch('requests.get')\n+@patch('subprocess.run')\n+def test_send_pull_request_branch_naming(mock_run, mock_get, mock_github_issue, mock_output_dir):\n+ repo_path = os.path.join(mock_output_dir, \"repo\")\n+\n+ # Mock API responses\n+ mock_get.side_effect = [\n+ MagicMock(status_code=200), # First branch exists\n+ MagicMock(status_code=200), # Second branch exists\n+ MagicMock(status_code=404), # Third branch doesn't exist\n+ MagicMock(json=lambda: {\"default_branch\": \"main\"}), # Get default branch\n+ ]\n+\n+ # Mock subprocess.run calls\n+ mock_run.side_effect = [\n+ MagicMock(returncode=0), # git checkout -b\n+ MagicMock(returncode=0), # git push\n+ ]\n+\n+ # Call the function\n+ result = send_pull_request(\n+ github_issue=mock_github_issue,\n+ github_token=\"test-token\",\n+ github_username=\"test-user\",\n+ patch_dir=repo_path,\n+ pr_type=\"branch\",\n+ )\n+\n+ # Assert API calls\n+ assert mock_get.call_count == 4\n+\n+ # Check branch creation and push\n+ assert mock_run.call_count == 2\n+ checkout_call, push_call = mock_run.call_args_list\n+\n+ assert checkout_call == call(\n+ f\"git -C {repo_path} checkout -b openhands-fix-issue-42-try3\",\n+ shell=True,\n+ capture_output=True,\n+ text=True,\n+ )\n+ assert push_call == call(\n+ f\"git -C {repo_path} push https://test-user:test-token@github.com/test-owner/test-repo.git openhands-fix-issue-42-try3\",\n+ shell=True,\n+ capture_output=True,\n+ text=True,\n+ )\n+\n+ # Check the result\n+ assert result == \"https://github.com/test-owner/test-repo/compare/openhands-fix-issue-42-try3?expand=1\"\n+\n @patch('openhands_resolver.send_pull_request.argparse.ArgumentParser')\n @patch('openhands_resolver.send_pull_request.process_all_successful_issues')\n @patch('openhands_resolver.send_pull_request.process_single_issue')\n@@ -575,3 +630,4 @@ def test_main(mock_getenv, mock_path_exists, mock_load_single_resolver_output,\n mock_args.issue_number = 'invalid'\n with pytest.raises(ValueError):\n main()\n+\n", "FAIL_TO_PASS": ["tests/test_send_pull_request.py::test_send_pull_request[branch]", "tests/test_send_pull_request.py::test_send_pull_request[draft]", "tests/test_send_pull_request.py::test_send_pull_request[ready]", "tests/test_send_pull_request.py::test_send_pull_request_branch_naming"]}], "all_FAIL_TO_PASS": ["tests/test_send_pull_request.py::test_send_pull_request[branch]", "tests/test_send_pull_request.py::test_send_pull_request[draft]", "tests/test_send_pull_request.py::test_send_pull_request[ready]", "tests/test_send_pull_request.py::test_send_pull_request_branch_naming"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "RedHatInsights__insights-core-4219_x1", "level": 1, "source": "swerebench", "repo": "RedHatInsights/insights-core", "image": "swerebench/sweb.eval.x86_64.redhatinsights_1776_insights-core-4219:latest", "base_commit": "fc8b6397611e78363f264892ac2ed7eb01c7e6be", "num_bugs": 1, "bugs": [{"instance_id": "RedHatInsights__insights-core-4219", "base_commit": "fc8b6397611e78363f264892ac2ed7eb01c7e6be", "gold_patch": "diff --git a/insights/combiners/lspci.py b/insights/combiners/lspci.py\nindex 42d28acc..6dc9bb33 100644\n--- a/insights/combiners/lspci.py\n+++ b/insights/combiners/lspci.py\n@@ -122,8 +122,8 @@ class LsPci(list):\n if lspci_vmmkn:\n for dev in lspci_vmmkn:\n # use the local copy to prevent from writing back to the parser\n- dev = dev.copy()\n- if lspci_k and dev['Slot'] in lspci_k:\n+ dev_t = dev.copy()\n+ if lspci_k and (dev['Slot'] in lspci_k.data or '0000:' + dev['Slot'] in lspci_k.data):\n # use the local copy to prevent from writing back to the parser\n dev_k = [v for v in lspci_k.data.values() if v['Slot'].endswith(dev['Slot'])][0].copy()\n # Since the 'lspci -k' is a more common command than the\n@@ -133,8 +133,9 @@ class LsPci(list):\n # dev_k.pop('Slot') if 'Slot' in dev_k else None\n dev_k.pop('Kernel driver in use') if 'Kernel driver in use' in dev_k else None\n dev_k.pop('Kernel modules') if 'Kernel modules' in dev_k else None\n- dev.update(dev_k)\n- self.append(dev)\n+ dev_t.update(dev_k)\n+\n+ self.append(dev_t)\n self._pci_dev_list = (lspci_k if lspci_k else lspci_vmmkn).pci_dev_list\n else:\n for dev in lspci_k.data.values():\n", "test_patch": "diff --git a/insights/tests/combiners/test_lspci.py b/insights/tests/combiners/test_lspci.py\nindex 7bc5feac..32e2c4a4 100644\n--- a/insights/tests/combiners/test_lspci.py\n+++ b/insights/tests/combiners/test_lspci.py\n@@ -166,6 +166,69 @@ Module: mlx5_core\n NUMANode: 0\n \"\"\"\n \n+LSPCI_K_3 = \"\"\"\n+pcilib: Error reading /sys/bus/pci/devices/0000:00:0c.0/label: Operation not permitted\n+pcilib: Error reading /sys/bus/pci/devices/0000:00:0e.0/label: Operation not permitted\n+00:00.0 System peripheral: Intel Corporation Ice Lake Memory Map/VT-d (rev 20)\n+\tSubsystem: Dell Device 0b73\n+bb:00.0 Processing accelerators: Habana Labs Ltd. Gaudi2 AI Training Accelerator (rev 01)\n+\tSubsystem: Habana Labs Ltd. Gaudi2 AI Training Accelerator\n+\tKernel driver in use: habanalabs\n+\tKernel modules: habanalabs\n+cb:00.0 Processing accelerators: Habana Labs Ltd. Gaudi2 AI Training Accelerator (rev 01)\n+\tSubsystem: Habana Labs Ltd. Gaudi2 AI Training Accelerator\n+\tKernel driver in use: habanalabs\n+\tKernel modules: habanalabs\n+db:00.0 Processing accelerators: Habana Labs Ltd. Gaudi2 AI Training Accelerator (rev 01)\n+\tSubsystem: Habana Labs Ltd. Gaudi2 AI Training Accelerator\n+\tKernel driver in use: habanalabs\n+\tKernel modules: habanalabs\n+\"\"\".strip() # noqa\n+\n+LSPCI_V_3 = \"\"\"\n+Slot:\t00:00.0\n+Class:\t0880\n+Vendor:\t8086\n+Device:\t09a2\n+SVendor:\t1028\n+SDevice:\t0b73\n+Rev:\t20\n+NUMANode:\t0\n+\n+Slot:\tbb:00.0\n+Class:\t1200\n+Vendor:\t1da3\n+Device:\t1020\n+SVendor:\t1da3\n+SDevice:\t1020\n+Rev:\t01\n+Driver:\thabanalabs\n+Module:\thabanalabs\n+NUMANode:\t1\n+\n+Slot:\tcb:00.0\n+Class:\t1200\n+Vendor:\t1da3\n+Device:\t1020\n+SVendor:\t1da3\n+SDevice:\t1020\n+Rev:\t01\n+Driver:\thabanalabs\n+Module:\thabanalabs\n+NUMANode:\t1\n+\n+Slot:\tdb:00.0\n+Class:\t1200\n+Vendor:\t1da3\n+Device:\t1020\n+SVendor:\t1da3\n+SDevice:\t1020\n+Rev:\t01\n+Driver:\thabanalabs\n+Module:\thabanalabs\n+NUMANode:\t1\n+\"\"\".strip() # noqa\n+\n \n def test_lspci_k():\n lspci_k = LsPciParser(context_wrap(LSPCI_K))\n@@ -271,6 +334,55 @@ def test_lspci_both_long_slot():\n 'PhySlot', 'NUMANode'])\n \n \n+def test_lspci_both_2():\n+ lspci_vmmkn = LsPciVmmkn(context_wrap(LSPCI_V_3))\n+ lspci_k = LsPciParser(context_wrap(LSPCI_K_3))\n+ lspci = LsPci(lspci_k, lspci_vmmkn)\n+ assert sorted(lspci.pci_dev_list) == ['00:00.0', 'bb:00.0', 'cb:00.0', 'db:00.0']\n+ assert lspci.search(Slot='bb:00.0') == [{\n+ 'Slot': 'bb:00.0',\n+ 'Module': ['habanalabs', ],\n+ 'Driver': 'habanalabs',\n+ 'Class': '1200',\n+ 'Vendor': '1da3',\n+ 'Device': '1020',\n+ 'Rev': '01',\n+ 'Dev_Details': 'Processing accelerators: Habana Labs Ltd. Gaudi2 AI Training Accelerator (rev 01)',\n+ 'SVendor': '1da3',\n+ 'SDevice': '1020',\n+ 'Subsystem': 'Habana Labs Ltd. Gaudi2 AI Training Accelerator',\n+ 'NUMANode': '1',\n+ }, ]\n+ assert lspci.search(Slot='cb:00.0') == [{\n+ 'Slot': 'cb:00.0',\n+ 'Module': ['habanalabs', ],\n+ 'Driver': 'habanalabs',\n+ 'Class': '1200',\n+ 'Vendor': '1da3',\n+ 'Device': '1020',\n+ 'Rev': '01',\n+ 'Dev_Details': 'Processing accelerators: Habana Labs Ltd. Gaudi2 AI Training Accelerator (rev 01)',\n+ 'SVendor': '1da3',\n+ 'SDevice': '1020',\n+ 'Subsystem': 'Habana Labs Ltd. Gaudi2 AI Training Accelerator',\n+ 'NUMANode': '1',\n+ }, ]\n+ assert lspci.search(Slot='db:00.0') == [{\n+ 'Slot': 'db:00.0',\n+ 'Module': ['habanalabs', ],\n+ 'Driver': 'habanalabs',\n+ 'Class': '1200',\n+ 'Vendor': '1da3',\n+ 'Device': '1020',\n+ 'Rev': '01',\n+ 'Dev_Details': 'Processing accelerators: Habana Labs Ltd. Gaudi2 AI Training Accelerator (rev 01)',\n+ 'SVendor': '1da3',\n+ 'SDevice': '1020',\n+ 'Subsystem': 'Habana Labs Ltd. Gaudi2 AI Training Accelerator',\n+ 'NUMANode': '1',\n+ }, ]\n+\n+\n def test_doc_examples():\n lspci_vmmkn = LsPciVmmkn(context_wrap(LSPCI_VMMKN))\n lspci_k = LsPciParser(context_wrap(LSPCI_K))\n", "FAIL_TO_PASS": ["insights/tests/combiners/test_lspci.py::test_lspci_both_2"]}], "all_FAIL_TO_PASS": ["insights/tests/combiners/test_lspci.py::test_lspci_both_2"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "RockefellerArchiveCenter__rac_aspace-60_x1", "level": 1, "source": "swerebench", "repo": "RockefellerArchiveCenter/rac_aspace", "image": "swerebench/sweb.eval.x86_64.rockefellerarchivecenter_1776_rac_aspace-60:latest", "base_commit": "f83aff9df6f1812ef3a531db594ed560fc6734a6", "num_bugs": 1, "bugs": [{"instance_id": "RockefellerArchiveCenter__rac_aspace-60", "base_commit": "f83aff9df6f1812ef3a531db594ed560fc6734a6", "gold_patch": "diff --git a/fixtures/archival_object.json b/fixtures/archival_object.json\nnew file mode 100644\nindex 0000000..26f2d42\n--- /dev/null\n+++ b/fixtures/archival_object.json\n@@ -0,0 +1,145 @@\n+{\n+ \"lock_version\": 3,\n+ \"title\": \"kmtests\",\n+ \"publish\": true,\n+ \"restrictions\": false,\n+ \"created_by\": \"k.martin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-09T16:25:14Z\",\n+ \"system_mtime\": \"2020-03-19T13:07:13Z\",\n+ \"user_mtime\": \"2020-03-19T13:07:13Z\",\n+ \"suppressed\": false,\n+ \"is_slug_auto\": false,\n+ \"id_0\": \"1\",\n+ \"id_1\": \"2\",\n+ \"id_2\": \"3\",\n+ \"id_3\": \"4\",\n+ \"language\": \"ang\",\n+ \"level\": \"collection\",\n+ \"jsonmodel_type\": \"resource\",\n+ \"external_ids\": [],\n+ \"subjects\": [],\n+ \"linked_events\": [],\n+ \"extents\": [\n+ {\n+ \"lock_version\": 0,\n+ \"number\": \"1\",\n+ \"created_by\": \"admin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-19T13:07:40Z\",\n+ \"system_mtime\": \"2020-03-19T13:07:40Z\",\n+ \"user_mtime\": \"2020-03-19T13:07:40Z\",\n+ \"portion\": \"whole\",\n+ \"extent_type\": \"Cubic Feet\",\n+ \"jsonmodel_type\": \"extent\"\n+ }\n+ ],\n+ \"dates\": [\n+ {\n+ \"lock_version\": 0,\n+ \"begin\": \"1990\",\n+ \"end\": \"2000\",\n+ \"created_by\": \"admin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-19T13:07:40Z\",\n+ \"system_mtime\": \"2020-03-19T13:07:40Z\",\n+ \"user_mtime\": \"2020-03-19T13:07:40Z\",\n+ \"date_type\": \"bulk\",\n+ \"label\": \"creation\",\n+ \"era\": \"ce\",\n+ \"calendar\": \"gregorian\",\n+ \"jsonmodel_type\": \"date\"\n+ }\n+ ],\n+ \"external_documents\": [],\n+ \"rights_statements\": [\n+ {\n+ \"lock_version\": 0,\n+ \"identifier\": \"e5dc6d09b9fe8640c05fe3de2926868c\",\n+ \"created_by\": \"admin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-19T13:07:41Z\",\n+ \"system_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"user_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"start_date\": \"2020-02-01\",\n+ \"end_date\": \"2090-05-06\",\n+ \"rights_type\": \"copyright\",\n+ \"status\": \"copyrighted\",\n+ \"jurisdiction\": \"US\",\n+ \"jsonmodel_type\": \"rights_statement\",\n+ \"external_documents\": [],\n+ \"acts\": [\n+ {\n+ \"start_date\": \"2020-01-01\",\n+ \"end_date\": \"2090-12-31\",\n+ \"created_by\": \"admin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-19T13:07:41Z\",\n+ \"system_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"user_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"act_type\": \"use\",\n+ \"restriction\": \"disallow\",\n+ \"jsonmodel_type\": \"rights_statement_act\",\n+ \"notes\": []\n+ }\n+ ],\n+ \"linked_agents\": [],\n+ \"notes\": []\n+ }\n+ ],\n+ \"linked_agents\": [],\n+ \"revision_statements\": [],\n+ \"instances\": [\n+ {\n+ \"lock_version\": 0,\n+ \"created_by\": \"admin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-19T13:07:41Z\",\n+ \"system_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"user_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"instance_type\": \"mixed materials\",\n+ \"jsonmodel_type\": \"instance\",\n+ \"is_representative\": false,\n+ \"sub_container\": {\n+ \"lock_version\": 0,\n+ \"created_by\": \"admin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-19T13:07:41Z\",\n+ \"system_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"user_mtime\": \"2020-03-19T13:07:41Z\",\n+ \"jsonmodel_type\": \"sub_container\",\n+ \"top_container\": {\n+ \"ref\": \"/repositories/2/top_containers/191155\"\n+ }\n+ }\n+ }\n+ ],\n+ \"deaccessions\": [],\n+ \"related_accessions\": [],\n+ \"classifications\": [],\n+ \"notes\": [\n+ {\n+ \"jsonmodel_type\": \"note_multipart\",\n+ \"persistent_id\": \"7e39d839488e068c65f822e52f5ffa01\",\n+ \"type\": \"accessrestrict\",\n+ \"rights_restriction\": {\n+ \"local_access_restriction_type\": []\n+ },\n+ \"subnotes\": [\n+ {\n+ \"jsonmodel_type\": \"note_text\",\n+ \"content\": \"materials are restricted\",\n+ \"publish\": true\n+ }\n+ ],\n+ \"publish\": true\n+ }\n+ ],\n+ \"uri\": \"/repositories/2/resources/13064\",\n+ \"repository\": {\n+ \"ref\": \"/repositories/2\"\n+ },\n+ \"tree\": {\n+ \"ref\": \"/repositories/2/resources/13064/tree\"\n+ }\n+}\ndiff --git a/fixtures/date_expression.json b/fixtures/date_expression.json\nnew file mode 100644\nindex 0000000..66e7b43\n--- /dev/null\n+++ b/fixtures/date_expression.json\n@@ -0,0 +1,14 @@\n+{\n+ \"lock_version\": 0,\n+ \"expression\": \"1905-1980\",\n+ \"begin\": \"1905\",\n+ \"end\": \"1980\",\n+ \"created_by\": \"greg\",\n+ \"last_modified_by\": \"greg\",\n+ \"create_time\": \"2017-08-08T21:11:46Z\",\n+ \"system_mtime\": \"2017-08-08T21:11:46Z\",\n+ \"user_mtime\": \"2017-08-08T21:11:46Z\",\n+ \"date_type\": \"inclusive\",\n+ \"label\": \"creation\",\n+ \"jsonmodel_type\": \"date\"\n+}\ndiff --git a/fixtures/date_no_expression.json b/fixtures/date_no_expression.json\nnew file mode 100644\nindex 0000000..a2db572\n--- /dev/null\n+++ b/fixtures/date_no_expression.json\n@@ -0,0 +1,13 @@\n+{\n+ \"lock_version\": 0,\n+ \"begin\": \"1905\",\n+ \"end\": \"1980\",\n+ \"created_by\": \"greg\",\n+ \"last_modified_by\": \"greg\",\n+ \"create_time\": \"2017-08-08T21:11:46Z\",\n+ \"system_mtime\": \"2017-08-08T21:11:46Z\",\n+ \"user_mtime\": \"2017-08-08T21:11:46Z\",\n+ \"date_type\": \"inclusive\",\n+ \"label\": \"creation\",\n+ \"jsonmodel_type\": \"date\"\n+}\ndiff --git a/fixtures/note_multi.json b/fixtures/note_multi.json\nnew file mode 100644\nindex 0000000..4488f58\n--- /dev/null\n+++ b/fixtures/note_multi.json\n@@ -0,0 +1,17 @@\n+{\n+ \"jsonmodel_type\": \"note_multipart\",\n+ \"persistent_id\": \"d08e4b20fceb371af437d3e2a23dda6f\",\n+ \"label\": \"Access\",\n+ \"type\": \"accessrestrict\",\n+ \"rights_restriction\": {\n+ \"local_access_restriction_type\": []\n+ },\n+ \"subnotes\": [\n+ {\n+ \"jsonmodel_type\": \"note_text\",\n+ \"content\": \"materials are restricted\",\n+ \"publish\": true\n+ }\n+ ],\n+ \"publish\": true\n+}\ndiff --git a/fixtures/note_single.json b/fixtures/note_single.json\nnew file mode 100644\nindex 0000000..406ab14\n--- /dev/null\n+++ b/fixtures/note_single.json\n@@ -0,0 +1,9 @@\n+{\n+ \"jsonmodel_type\": \"note_singlepart\",\n+ \"persistent_id\": \"ec9e58a73212a0b4782e512339a3fa83\",\n+ \"type\": \"abstract\",\n+ \"content\": [\n+ \"New York Mets\"\n+ ],\n+ \"publish\": true\n+}\ndiff --git a/fixtures/top_container.json b/fixtures/top_container.json\nnew file mode 100644\nindex 0000000..b64a04f\n--- /dev/null\n+++ b/fixtures/top_container.json\n@@ -0,0 +1,39 @@\n+{\n+ \"lock_version\": 2,\n+ \"indicator\": \"1\",\n+ \"created_by\": \"admin\",\n+ \"last_modified_by\": \"admin\",\n+ \"create_time\": \"2020-03-19T13:07:07Z\",\n+ \"system_mtime\": \"2020-03-19T13:14:45Z\",\n+ \"user_mtime\": \"2020-03-19T13:14:44Z\",\n+ \"created_for_collection\": \"/repositories/2/resources/13064\",\n+ \"type\": \"box\",\n+ \"jsonmodel_type\": \"top_container\",\n+ \"active_restrictions\": [],\n+ \"container_locations\": [\n+ {\n+ \"jsonmodel_type\": \"container_location\",\n+ \"status\": \"current\",\n+ \"start_date\": \"2020-03-19\",\n+ \"system_mtime\": \"2020-03-19 13:14:44 UTC\",\n+ \"user_mtime\": \"2020-03-19 13:14:44 UTC\",\n+ \"ref\": \"/locations/7799\"\n+ }\n+ ],\n+ \"series\": [],\n+ \"collection\": [\n+ {\n+ \"ref\": \"/repositories/2/resources/13064\",\n+ \"identifier\": \"1\",\n+ \"display_string\": \"kmtests\"\n+ }\n+ ],\n+ \"uri\": \"/repositories/2/top_containers/191155\",\n+ \"repository\": {\n+ \"ref\": \"/repositories/2\"\n+ },\n+ \"restricted\": false,\n+ \"is_linked_to_published_record\": true,\n+ \"display_string\": \"Box 1\",\n+ \"long_display_string\": \"1, Box 1\"\n+}\ndiff --git a/rac_aspace/data_helpers.py b/rac_aspace/data_helpers.py\nindex e53a24a..c062b01 100644\n--- a/rac_aspace/data_helpers.py\n+++ b/rac_aspace/data_helpers.py\n@@ -43,11 +43,13 @@ def get_note_text(note):\n return content\n \n if note.jsonmodel_type == \"note_singlepart\":\n- content = note.source.content.strip(\"]['\").split(', ')\n+ content = note.content\n elif note.jsonmodel_type == \"note_index\":\n- content = note.source.items.strip(\"]['\").split(', ')\n+ content = note.items\n else:\n- content = (parse_subnote(sn) for sn in note.subnotes)\n+ subnote_content_list = list(parse_subnote(sn) for sn in note.subnotes)\n+ content = [\n+ c for subnote_content in subnote_content_list for c in subnote_content]\n return content\n \n \n@@ -65,7 +67,8 @@ def text_in_note(note, query_string):\n CONFIDENCE_RATIO = 97\n \"\"\"int: Minimum confidence ratio to match against.\"\"\"\n note_content = get_note_text(note)\n- ratio = fuzz.token_sort_ratio(note_content.lower(), query_string.lower())\n+ ratio = fuzz.token_sort_ratio(\n+ \" \".join([n.lower() for n in note_content]), query_string.lower())\n return (True if ratio > CONFIDENCE_RATIO else False)\n \n \n@@ -110,7 +113,7 @@ def format_container(top_container):\n Returns:\n str: a concatenation of top container type and indicator.\n \"\"\"\n- return \"{0} {1}\".format(top_container.container_type,\n+ return \"{0} {1}\".format(top_container.type,\n top_container.indicator)\n \n \n@@ -126,7 +129,7 @@ def format_resource_id(resource, separator=\":\"):\n str: a concatenated four-part ID for the resource record.\n \"\"\"\n resource_id = []\n- for x in range(3):\n+ for x in range(4):\n try:\n resource_id.append(getattr(resource, \"id_{0}\".format(x)))\n except AttributeError:\n@@ -175,17 +178,20 @@ def get_expression(date):\n Concatenates start and end dates if no date expression exists.\n \n Args:\n- date (dict): an ArchivesSpace date object.\n+ date (obj): an ArchivesSpace date object\n \n Returns:\n str: a date expression for the date object.\n \"\"\"\n- if date.expression:\n- return date.expression\n- if date.date_end:\n- return \"{0} - {1}\".format(date.date_start, date.date_end)\n- else:\n- return date.date_start\n+ date_json = date.json()\n+ try:\n+ expression = date_json[\"expression\"]\n+ except KeyError:\n+ if date_json.get(\"end\"):\n+ expression = \"{0}-{1}\".format(date_json[\"begin\"], date_json[\"end\"])\n+ else:\n+ expression = date_json[\"begin\"]\n+ return expression\n \n \n def associated_objects(top_container):\n@@ -235,10 +241,10 @@ def is_restricted(archival_object):\n \"\"\"\n query_string = \"materials are restricted\"\n for note in archival_object.notes:\n- if note.jsonmodel_type == 'accessrestrict':\n+ if note.type == 'accessrestrict':\n if text_in_note(note, query_string):\n return True\n- for rights_statement in archival_object.rights_statement:\n+ for rights_statement in archival_object.rights_statements:\n if indicates_restriction(rights_statement):\n return True\n return False\n", "test_patch": "diff --git a/tests/test_data_helpers.py b/tests/test_data_helpers.py\nindex 8ea489c..0caa5a2 100644\n--- a/tests/test_data_helpers.py\n+++ b/tests/test_data_helpers.py\n@@ -1,16 +1,170 @@\n \"\"\"\n Unit tests for Data Helpers\n \"\"\"\n+import json\n+import os\n import unittest\n \n+from asnake.jsonmodel import wrap_json_object\n from rac_aspace import data_helpers\n \n \n class TestDataHelpers(unittest.TestCase):\n+ \"\"\"\n+ Tests the data helper functions.\n+ \"\"\"\n \n- def test_helpers(self):\n+ def test_get_note_text(self):\n+ \"\"\"\n+ Checks whether the returned note text matches the selected query string.\n+\n+ Args:\n+ note (dict): an ArchivesSpace note object\n+\n+ Returns:\n+ bool: True if the content matches the supplied text.\n+ \"\"\"\n+ with open(os.path.join(\"fixtures\", \"note_multi.json\"), \"r\") as json_file:\n+ data = json.load(json_file)\n+ note = wrap_json_object(data)\n+ result = data_helpers.get_note_text(note)\n+ self.assertTrue(result, list)\n+ self.assertEqual(result, [\"materials are restricted\"])\n+\n+ def test_text_in_note(self):\n+ \"\"\"\n+ Checks whether the query string and note content are close to a match.\n+\n+ Args:\n+ note (dict): an ArchivesSpace note object\n+\n+ query_string (str): a string object used to check against note content\n+\n+ Returns:\n+ bool: True if the sort ratio is greater than or equal to 97.\n+ \"\"\"\n+ query_string = \"New York Mets\"\n+ with open(os.path.join(\"fixtures\", \"note_single.json\"), \"r\") as json_file:\n+ data = json.load(json_file)\n+ note = wrap_json_object(data)\n+ result = data_helpers.text_in_note(note, query_string)\n+ self.assertTrue(result)\n+\n+ # def test_get_locations(self):\n+ \"\"\"\n+ Data helper as written won't work without AS calls. Container and Location\n+ information are in different objects, not just Archival Objects.\n+ \"\"\"\n+ # \"\"\"\n+ # Checks whether the function returns a list and if it is empty.\n+ # Need to write a way to get the archival_object information from AS.\n+\n+ # Args:\n+ # archival_object (dict): an ArchivesSpace archival object\n+\n+ # Returns:\n+ # bool: Boolean. True if locations exists and is not empty.\n+ # bool: Boolean. True if locations is a list. False if any other data type.\n+ # \"\"\"\n+ # with open(os.path.join(\"fixtures\", \"archival_object.json\"), \"r\") as json_file:\n+ # data = json.load(json_file)\n+ # archival_object = wrap_json_object(data)\n+ # locations = get_locations(archival_object)\n+ # self.assertNotEqual(\n+ # locations, False,\n+ # \"Get locatins returned an error: {}\".format(locations)\n+ # )\n+ # self.assertIsInstance(locations, list)\n+\n+ def test_format_location(self):\n pass\n \n+ def test_format_container(self):\n+ \"\"\"\n+ Checks whether the function returns a string as expected.\n+\n+ Args:\n+ top_container (dict): an archivespace top container\n+\n+ Returns:\n+ bool: Boolean. True if the top_container string matches expected output and type.\n+ \"\"\"\n+ with open(os.path.join(\"fixtures\", \"top_container.json\"), \"r\") as json_file:\n+ data = json.load(json_file)\n+ top_container = wrap_json_object(data)\n+ result = data_helpers.format_container(top_container)\n+ self.assertEqual(result, 'box 1')\n+ self.assertIsInstance(result, str)\n+\n+ def test_format_resource_id(self):\n+ \"\"\"\n+ Checks whether the function returns a concatenated string as expected.\n+\n+ Args:\n+ resource (dict): an ArchivesSpace object.\n+\n+ separator (str): a string separator that will be added in between each section.\n+\n+ Returns:\n+ bool: Boolean. True if the top_container string matches expected output and type.\n+ \"\"\"\n+ separator = \":\"\n+ with open(os.path.join(\"fixtures\", \"archival_object.json\"), \"r\") as json_file:\n+ data = json.load(json_file)\n+ resource = wrap_json_object(data)\n+ result = data_helpers.format_resource_id(resource, separator)\n+ self.assertIsInstance(result, str)\n+ self.assertEqual(result, '1:2:3:4')\n+\n+ def test_closest_value(self):\n+ pass\n+\n+ def test_get_orphans(self):\n+ pass\n+\n+ def test_get_expression(self):\n+ \"\"\"\n+ Tests whether the date expression function works as intended.\n+\n+ Args:\n+ date (dict): an ArchivesSpace date object\n+\n+ Returns:\n+ bool: Returns true if the function creates the expected string output.\n+ \"\"\"\n+ files = ['date_expression.json', 'date_no_expression.json']\n+ for f in files:\n+ with open(os.path.join(\"fixtures\", f), \"r\") as json_file:\n+ data = json.load(json_file)\n+ date = wrap_json_object(data)\n+ result = data_helpers.get_expression(date)\n+ self.assertTrue(result, \"1905-1980\")\n+\n+ def test_associated_objects(self):\n+ pass\n+\n+ def test_indicates_restriction(self):\n+ pass\n+\n+ def test_is_restricted(self):\n+ \"\"\"\n+ Tests whether the function can find restrictions in an AS archival object.\n+\n+ Args:\n+ archival_object (dict): and ArchivesSpace archival object\n+\n+ Returns:\n+ bool: Returns true when finding a restriction in a note or rights statement.\n+ \"\"\"\n+ with open(os.path.join(\"fixtures\", \"archival_object.json\"), \"r\") as json_file:\n+ data = json.load(json_file)\n+ archival_object = wrap_json_object(data)\n+ result = data_helpers.is_restricted(archival_object)\n+ self.assertEqual(result, True)\n+ \"\"\"\n+ Cannot currently test the restrictions portion because data helper is unwritten\n+ \"\"\"\n+\n def test_strip_html_tags(self):\n input = \"

Title

This is some text! It is wrapped in a variety of html tags, which should all be stripped & not returned.

\"\n expected = \"TitleThis is some text! It is wrapped in a variety of html tags, which should all be stripped & not returned.\"\ndiff --git a/tests/test_serializers.py b/tests/test_serializers.py\nindex 90c7b97..4a831fa 100644\n--- a/tests/test_serializers.py\n+++ b/tests/test_serializers.py\n@@ -34,7 +34,8 @@ class TestSerializers(unittest.TestCase):\n reader = csv.reader(\n out_file, delimiter=serializer.delimiter)\n out_data = [r for r in reader]\n- self.assertEqual(out_data[0], [\"column1\", \"column2\"])\n+ self.assertEqual(set(out_data[0]), set(\n+ [\"column1\", \"column2\"]))\n self.assertEqual(len(out_data), len(data) + 1)\n remove(expected_filepath)\n \n", "FAIL_TO_PASS": ["tests/test_data_helpers.py::TestDataHelpers::test_format_container", "tests/test_data_helpers.py::TestDataHelpers::test_format_resource_id", "tests/test_data_helpers.py::TestDataHelpers::test_get_expression", "tests/test_data_helpers.py::TestDataHelpers::test_get_note_text", "tests/test_data_helpers.py::TestDataHelpers::test_is_restricted", "tests/test_data_helpers.py::TestDataHelpers::test_text_in_note"]}], "all_FAIL_TO_PASS": ["tests/test_data_helpers.py::TestDataHelpers::test_format_container", "tests/test_data_helpers.py::TestDataHelpers::test_format_resource_id", "tests/test_data_helpers.py::TestDataHelpers::test_get_expression", "tests/test_data_helpers.py::TestDataHelpers::test_get_note_text", "tests/test_data_helpers.py::TestDataHelpers::test_is_restricted", "tests/test_data_helpers.py::TestDataHelpers::test_text_in_note"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PMEAL__porespy-465_x1", "level": 1, "source": "swerebench", "repo": "PMEAL/porespy", "image": "swerebench/sweb.eval.x86_64.pmeal_1776_porespy-465:latest", "base_commit": "51276c464ccaf8feea1cb246c6178a81af3b51dc", "num_bugs": 1, "bugs": [{"instance_id": "PMEAL__porespy-465", "base_commit": "51276c464ccaf8feea1cb246c6178a81af3b51dc", "gold_patch": "diff --git a/porespy/filters/_snows.py b/porespy/filters/_snows.py\nindex 346716570..aa17cb1a8 100644\n--- a/porespy/filters/_snows.py\n+++ b/porespy/filters/_snows.py\n@@ -350,7 +350,7 @@ def trim_saddle_points(peaks, dt, max_iters=10):\n return peaks\n \n \n-def trim_nearby_peaks(peaks, dt):\n+def trim_nearby_peaks(peaks, dt, f=1.0):\n r\"\"\"\n Finds pairs of peaks that are nearer to each other than to the solid\n phase, and removes the peak that is closer to the solid.\n@@ -363,6 +363,9 @@ def trim_nearby_peaks(peaks, dt):\n dt : ND-array\n The distance transform of the pore space for which the true peaks\n are sought.\n+ f : scalar\n+ Controls how close peaks must be before they are considered near to each\n+ other. Sets of peaks are tagged as near if ``d_neighbor < f * d_solid``.\n \n Returns\n -------\n@@ -399,7 +402,7 @@ def trim_nearby_peaks(peaks, dt):\n dist_to_neighbor = temp[0][:, 1]\n del temp, tree # Free-up memory\n dist_to_solid = dt[tuple(crds.T)] # Get distance to solid for each peak\n- hits = np.where(dist_to_neighbor < dist_to_solid)[0]\n+ hits = np.where(dist_to_neighbor < f * dist_to_solid)[0]\n # Drop peak that is closer to the solid than it's neighbor\n drop_peaks = []\n for peak in hits:\n@@ -415,7 +418,6 @@ def trim_nearby_peaks(peaks, dt):\n return peaks > 0\n \n \n-\n def _estimate_overlap(im, mode='dt', zoom=0.25):\n logger.trace('Calculating overlap thickness')\n if mode == 'watershed':\n", "test_patch": "diff --git a/test/unit/test_filters.py b/test/unit/test_filters.py\nindex d3d44a028..9f3c2b50d 100644\n--- a/test/unit/test_filters.py\n+++ b/test/unit/test_filters.py\n@@ -5,6 +5,7 @@ import porespy as ps\n import scipy.ndimage as spim\n from skimage.morphology import disk, ball, skeletonize_3d\n from skimage.util import random_noise\n+from scipy.stats import norm\n \n \n class FilterTest():\n@@ -476,6 +477,21 @@ class FilterTest():\n p2 = (im[0, ...]).sum()\n np.testing.assert_approx_equal(np.around(p1 / p2, decimals=1), 1)\n \n+ def test_trim_nearby_peaks_threshold(self):\n+ np.random.seed(10)\n+ dist = norm(loc=7, scale=5)\n+ im = ps.generators.polydisperse_spheres([100, 100, 100],\n+ porosity=0.8, dist=dist)\n+ im_dt = edt(im)\n+ im_dt = im_dt\n+ dt = spim.gaussian_filter(input=im_dt, sigma=0.4)\n+ peaks = ps.filters.find_peaks(dt=dt)\n+ peaks_far = ps.filters.trim_nearby_peaks(peaks=peaks, dt=dt)\n+ peaks_close = ps.filters.trim_nearby_peaks(peaks=peaks, dt=dt, f=0.3)\n+ num_peaks_after_far_trim = spim.label(peaks_far)[1]\n+ num_peaks_after_close_trim = spim.label(peaks_close)[1]\n+ assert num_peaks_after_far_trim <= num_peaks_after_close_trim\n+\n \n if __name__ == '__main__':\n t = FilterTest()\n", "FAIL_TO_PASS": ["test/unit/test_filters.py::FilterTest::test_trim_nearby_peaks_threshold"]}], "all_FAIL_TO_PASS": ["test/unit/test_filters.py::FilterTest::test_trim_nearby_peaks_threshold"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "RobinL__fuzzymatcher-50_x1", "level": 1, "source": "swerebench", "repo": "RobinL/fuzzymatcher", "image": "swerebench/sweb.eval.x86_64.robinl_1776_fuzzymatcher-50:latest", "base_commit": "5f0b19d50d5dcbcd930f9634d2bf429007b5efcc", "num_bugs": 1, "bugs": [{"instance_id": "RobinL__fuzzymatcher-50", "base_commit": "5f0b19d50d5dcbcd930f9634d2bf429007b5efcc", "gold_patch": "diff --git a/fuzzymatcher/data_getter_sqlite.py b/fuzzymatcher/data_getter_sqlite.py\nindex c54eec8..e97808e 100644\n--- a/fuzzymatcher/data_getter_sqlite.py\n+++ b/fuzzymatcher/data_getter_sqlite.py\n@@ -177,10 +177,21 @@ class DataGetter:\n \"\"\"\n \n # This fails if the special tokens 'and' or 'or' are in fts string! See issue 35!\n- tokens_to_remove = [\"AND\", \"OR\"]\n- tokens = [t for t in tokens if t not in tokens_to_remove]\n+ tokens_to_escape = [\"AND\", \"OR\", \"NEAR\"]\n+\n+ def escape_token(t):\n+ # return t\n+ if t in tokens_to_escape:\n+ return '\"' + t + '\"'\n+ else:\n+ return t\n+\n+\n+ tokens = [escape_token(t) for t in tokens]\n+\n fts_string = \" \".join(tokens)\n \n+\n if misspelling:\n table_name = \"_concat_all_alternatives\"\n else:\n@@ -188,6 +199,7 @@ class DataGetter:\n \n sql = get_records_sql.format(table_name, fts_string, self.return_records_limit)\n \n+\n cur = self.con.cursor()\n cur.execute(sql)\n results = cur.fetchall()\n", "test_patch": "diff --git a/tests/data/left_token_escape.csv b/tests/data/left_token_escape.csv\nnew file mode 100644\nindex 0000000..6da12f6\n--- /dev/null\n+++ b/tests/data/left_token_escape.csv\n@@ -0,0 +1,5 @@\n+id,fname,mname,lname,dob,another_field\n+1,or,or and,and,20/05/1980,other data\n+2,or,or,or smith or,15/06/1990,more data\n+3,near,and,near,20/05/1960,another thing\n+\ndiff --git a/tests/data/right_token_escape.csv b/tests/data/right_token_escape.csv\nnew file mode 100644\nindex 0000000..1b3232b\n--- /dev/null\n+++ b/tests/data/right_token_escape.csv\n@@ -0,0 +1,4 @@\n+id,name,middlename,surname,date,other\n+1,or,or,or smith or,15/06/1990,more data\n+2,near,and,near,20/05/1960,another thing\n+3,or,or and,and,20/05/1980,other data\n\\ No newline at end of file\ndiff --git a/tests/test_misc.py b/tests/test_misc.py\nindex cbb1668..2377c62 100644\n--- a/tests/test_misc.py\n+++ b/tests/test_misc.py\n@@ -17,4 +17,31 @@ class TestNulls(unittest.TestCase):\n \n on = [\"first_name\", \"surname\", \"dob\", \"city\"]\n \n- flj = link_table(df_left, df_right, on, on)\n\\ No newline at end of file\n+ flj = link_table(df_left, df_right, on, on)\n+\n+\n+class TestNulls(unittest.TestCase):\n+ \"\"\"\n+ Test what happens when the user provides input data with\n+ fts4 match expression keyworks like AND, OR, NEAR\n+ \"\"\"\n+\n+ def test_nulls_no_errors(self):\n+ \"\"\"\n+\n+ \"\"\"\n+\n+\n+ df_left = pd.read_csv(\"tests/data/left_token_escape.csv\")\n+ df_right = pd.read_csv(\"tests/data/right_token_escape.csv\")\n+\n+ # Columns to match on from df_left\n+ left_on = [\"fname\", \"mname\", \"lname\"]\n+\n+ # Columns to match on from df_right\n+ right_on = [\"name\", \"middlename\", \"surname\"]\n+\n+ on = [\"first_name\", \"surname\", ]\n+\n+ flj = link_table(df_left, df_right, left_on, right_on,\n+ left_id_col=\"id\", right_id_col=\"id\")\n", "FAIL_TO_PASS": ["tests/test_misc.py::TestNulls::test_nulls_no_errors"]}], "all_FAIL_TO_PASS": ["tests/test_misc.py::TestNulls::test_nulls_no_errors"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PyCQA__pyflakes-275_x1", "level": 1, "source": "swerebench", "repo": "PyCQA/pyflakes", "image": "swerebench/sweb.eval.x86_64.pycqa_1776_pyflakes-275:latest", "base_commit": "1af4f14ad4675bf5c61c47bbb7c2421b50d1cba4", "num_bugs": 1, "bugs": [{"instance_id": "PyCQA__pyflakes-275", "base_commit": "1af4f14ad4675bf5c61c47bbb7c2421b50d1cba4", "gold_patch": "diff --git a/README.rst b/README.rst\nindex e84d334..aeb15f9 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -72,7 +72,7 @@ rebase your commits for you.\n \n All changes should include tests and pass flake8_.\n \n-.. image:: https://api.travis-ci.org/PyCQA/pyflakes.svg\n+.. image:: https://api.travis-ci.org/PyCQA/pyflakes.svg?branch=master\n :target: https://travis-ci.org/PyCQA/pyflakes\n :alt: Build status\n \ndiff --git a/pyflakes/api.py b/pyflakes/api.py\nindex a535bff..e30f920 100644\n--- a/pyflakes/api.py\n+++ b/pyflakes/api.py\n@@ -5,6 +5,7 @@ from __future__ import with_statement\n \n import sys\n import os\n+import re\n import _ast\n \n from pyflakes import checker, __version__\n@@ -13,6 +14,9 @@ from pyflakes import reporter as modReporter\n __all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']\n \n \n+PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\\bpython[23]?\\b\\s*$')\n+\n+\n def check(codeString, filename, reporter=None):\n \"\"\"\n Check the Python source given by C{codeString} for flakes.\n@@ -108,6 +112,25 @@ def checkPath(filename, reporter=None):\n return check(codestr, filename, reporter)\n \n \n+def isPythonFile(filename):\n+ \"\"\"Return True if filename points to a Python file.\"\"\"\n+ if filename.endswith('.py'):\n+ return True\n+\n+ max_bytes = 128\n+\n+ try:\n+ with open(filename, 'rb') as f:\n+ text = f.read(max_bytes)\n+ if not text:\n+ return False\n+ except IOError:\n+ return False\n+\n+ first_line = text.splitlines()[0]\n+ return PYTHON_SHEBANG_REGEX.match(first_line)\n+\n+\n def iterSourceCode(paths):\n \"\"\"\n Iterate over all Python source files in C{paths}.\n@@ -120,8 +143,9 @@ def iterSourceCode(paths):\n if os.path.isdir(path):\n for dirpath, dirnames, filenames in os.walk(path):\n for filename in filenames:\n- if filename.endswith('.py'):\n- yield os.path.join(dirpath, filename)\n+ full_path = os.path.join(dirpath, filename)\n+ if isPythonFile(full_path):\n+ yield full_path\n else:\n yield path\n \n", "test_patch": "diff --git a/pyflakes/test/test_api.py b/pyflakes/test/test_api.py\nindex 51b0027..a1e0be2 100644\n--- a/pyflakes/test/test_api.py\n+++ b/pyflakes/test/test_api.py\n@@ -187,6 +187,22 @@ class TestIterSourceCode(TestCase):\n sorted(iterSourceCode([self.tempdir])),\n sorted([apath, bpath, cpath]))\n \n+ def test_shebang(self):\n+ \"\"\"\n+ Find Python files that don't end with `.py`, but contain a Python\n+ shebang.\n+ \"\"\"\n+ apath = os.path.join(self.tempdir, 'a')\n+ fd = open(apath, 'w')\n+ fd.write('#!/usr/bin/env python\\n')\n+ fd.close()\n+\n+ self.makeEmptyFile('b')\n+\n+ self.assertEqual(\n+ list(iterSourceCode([self.tempdir])),\n+ list([apath]))\n+\n def test_multipleDirectories(self):\n \"\"\"\n L{iterSourceCode} can be given multiple directories. It will recurse\n", "FAIL_TO_PASS": ["pyflakes/test/test_api.py::TestIterSourceCode::test_shebang"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_api.py::TestIterSourceCode::test_shebang"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Erotemic__ubelt-64_x1", "level": 1, "source": "swerebench", "repo": "Erotemic/ubelt", "image": "swerebench/sweb.eval.x86_64.erotemic_1776_ubelt-64:latest", "base_commit": "89085f148ace79aa0dfdc17383423e3dfe138017", "num_bugs": 1, "bugs": [{"instance_id": "Erotemic__ubelt-64", "base_commit": "89085f148ace79aa0dfdc17383423e3dfe138017", "gold_patch": "diff --git a/ubelt/util_path.py b/ubelt/util_path.py\nindex c028ba2..5241209 100644\n--- a/ubelt/util_path.py\n+++ b/ubelt/util_path.py\n@@ -291,9 +291,9 @@ def ensuredir(dpath, mode=0o1777, verbose=None, recreate=False):\n >>> assert exists(dpath)\n >>> os.rmdir(dpath)\n \"\"\"\n- if verbose is None: # nocover\n+ if verbose is None:\n verbose = 0\n- if isinstance(dpath, (list, tuple)): # nocover\n+ if isinstance(dpath, (list, tuple)):\n dpath = join(*dpath)\n \n if recreate:\n@@ -301,15 +301,15 @@ def ensuredir(dpath, mode=0o1777, verbose=None, recreate=False):\n ub.delete(dpath, verbose=verbose)\n \n if not exists(dpath):\n- if verbose: # nocover\n- print('Ensuring new directory (%r)' % dpath)\n+ if verbose:\n+ print('Ensuring directory (creating {!r})'.format(dpath))\n if sys.version_info.major == 2: # nocover\n os.makedirs(normpath(dpath), mode=mode)\n else:\n os.makedirs(normpath(dpath), mode=mode, exist_ok=True)\n else:\n- if verbose: # nocover\n- print('Ensuring existing directory (%r)' % dpath)\n+ if verbose:\n+ print('Ensuring directory (existing {!r})'.format(dpath))\n return dpath\n \n \n", "test_patch": "diff --git a/tests/test_path.py b/tests/test_path.py\nindex 49ea0c8..fafadd2 100644\n--- a/tests/test_path.py\n+++ b/tests/test_path.py\n@@ -55,8 +55,31 @@ def test_augpath_dpath():\n \n \n def test_ensuredir_recreate():\n- ub.ensuredir('foo', recreate=True)\n- ub.ensuredir('foo/bar')\n- assert exists('foo/bar')\n- ub.ensuredir('foo', recreate=True)\n- assert not exists('foo/bar')\n+ base = ub.ensure_app_cache_dir('ubelt/tests')\n+ folder = join(base, 'foo')\n+ member = join(folder, 'bar')\n+ ub.ensuredir(folder, recreate=True)\n+ ub.ensuredir(member)\n+ assert exists(member)\n+ ub.ensuredir(folder, recreate=True)\n+ assert not exists(member)\n+\n+\n+def test_ensuredir_verbosity():\n+ base = ub.ensure_app_cache_dir('ubelt/tests')\n+\n+ with ub.CaptureStdout() as cap:\n+ ub.ensuredir(join(base, 'foo'), verbose=0)\n+ assert cap.text == ''\n+ # None defaults to verbose=0\n+ with ub.CaptureStdout() as cap:\n+ ub.ensuredir((base, 'foo'), verbose=None)\n+ assert cap.text == ''\n+\n+ ub.delete(join(base, 'foo'))\n+ with ub.CaptureStdout() as cap:\n+ ub.ensuredir(join(base, 'foo'), verbose=1)\n+ assert 'creating' in cap.text\n+ with ub.CaptureStdout() as cap:\n+ ub.ensuredir(join(base, 'foo'), verbose=1)\n+ assert 'existing' in cap.text\n", "FAIL_TO_PASS": ["tests/test_path.py::test_ensuredir_verbosity"]}], "all_FAIL_TO_PASS": ["tests/test_path.py::test_ensuredir_verbosity"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Colin-b__keepachangelog-8_x1", "level": 1, "source": "swerebench", "repo": "Colin-b/keepachangelog", "image": "swerebench/sweb.eval.x86_64.colin-b_1776_keepachangelog-8:latest", "base_commit": "998fd84a568be62fb333422dbe8202200cf17bba", "num_bugs": 1, "bugs": [{"instance_id": "Colin-b__keepachangelog-8", "base_commit": "998fd84a568be62fb333422dbe8202200cf17bba", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex d694d84..6f721e2 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n ## [Unreleased]\n \n+## [0.3.0] - 2020-03-01\n+### Changed\n+- Information is now stored without star, space or caret at start or end of line.\n+\n ## [0.2.0] - 2020-02-24\n ### Added\n - It is now possible to retrieve \"Unreleased\" information thanks to the `show_unreleased` parameter. (Thanks [Alessandro Ogier](https://github.com/aogier))\n@@ -18,7 +22,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n ### Added\n - Initial release.\n \n-[Unreleased]: https://github.com/Colin-b/keepachangelog/compare/v0.2.0...HEAD\n+[Unreleased]: https://github.com/Colin-b/keepachangelog/compare/v0.3.0...HEAD\n+[0.3.0]: https://github.com/Colin-b/keepachangelog/compare/v0.2.0...v0.3.0\n [0.2.0]: https://github.com/Colin-b/keepachangelog/compare/v0.1.0...v0.2.0\n [0.1.0]: https://github.com/Colin-b/keepachangelog/compare/v0.0.1...v0.1.0\n [0.0.1]: https://github.com/Colin-b/keepachangelog/releases/tag/v0.0.1\ndiff --git a/README.md b/README.md\nindex ba23a57..491adfb 100644\n--- a/README.md\n+++ b/README.md\n@@ -5,7 +5,7 @@\n \"Build\n \"Coverage\"\n \"Code\n-\"Number\n+\"Number\n \"Number\n

\n \n@@ -23,26 +23,26 @@ changes = keepachangelog.to_dict(\"path/to/CHANGELOG.md\")\n changes = {\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\n@@ -65,14 +65,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n ### Added\n - Enhancement 1\n-- sub enhancement 1\n-- sub enhancement 2\n+ - sub enhancement 1\n+ - sub enhancement 2\n - Enhancement 2\n \n ### Fixed\n - Bug fix 1\n-- sub bug 1\n-- sub bug 2\n+ - sub bug 1\n+ - sub bug 2\n - Bug fix 2\n \n ### Security\n@@ -90,15 +90,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n ## [1.1.0] - 2018-05-31\n ### Changed\n - Enhancement 1 (1.1.0)\n-- sub enhancement 1\n-- sub enhancement 2\n+ - sub enhancement 1\n+ - sub enhancement 2\n - Enhancement 2 (1.1.0)\n \n ## [1.0.1] - 2018-05-31\n ### Fixed\n - Bug fix 1 (1.0.1)\n-- sub bug 1\n-- sub bug 2\n+ - sub bug 1\n+ - sub bug 2\n - Bug fix 2 (1.0.1)\n \n ## [1.0.0] - 2017-04-10\ndiff --git a/keepachangelog/_changelog.py b/keepachangelog/_changelog.py\nindex 759a625..b813beb 100644\n--- a/keepachangelog/_changelog.py\n+++ b/keepachangelog/_changelog.py\n@@ -47,7 +47,7 @@ def is_information(line: str) -> bool:\n \n \n def add_information(category: List[str], line: str):\n- category.append(line)\n+ category.append(line.strip(\" *-\"))\n \n \n def to_dict(changelog_path: str, *, show_unreleased: bool = False) -> Dict[str, dict]:\ndiff --git a/keepachangelog/version.py b/keepachangelog/version.py\nindex 03431df..e2e359f 100644\n--- a/keepachangelog/version.py\n+++ b/keepachangelog/version.py\n@@ -3,4 +3,4 @@\n # Major should be incremented in case there is a breaking change. (eg: 2.5.8 -> 3.0.0)\n # Minor should be incremented in case there is an enhancement. (eg: 2.5.8 -> 2.6.0)\n # Patch should be incremented in case there is a bug fix. (eg: 2.5.8 -> 2.5.9)\n-__version__ = \"0.2.0\"\n+__version__ = \"0.3.0\"\n", "test_patch": "diff --git a/tests/test_changelog.py b/tests/test_changelog.py\nindex 34e6bbb..798fbaa 100644\n--- a/tests/test_changelog.py\n+++ b/tests/test_changelog.py\n@@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n ## [Unreleased]\n+\n+## [1.2.0] - 2018-06-01\n ### Changed\n - Release note 1.\n - Release note 2.\n@@ -76,28 +78,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n def test_changelog_with_versions_and_all_categories(changelog):\n assert keepachangelog.to_dict(changelog) == {\n+ \"1.2.0\": {\n+ \"added\": [\n+ \"Enhancement 1\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2\",\n+ ],\n+ \"changed\": [\"Release note 1.\", \"Release note 2.\"],\n+ \"deprecated\": [\"Deprecated feature 1\", \"Future removal 2\"],\n+ \"fixed\": [\"Bug fix 1\", \"sub bug 1\", \"sub bug 2\", \"Bug fix 2\"],\n+ \"release_date\": \"2018-06-01\",\n+ \"removed\": [\"Deprecated feature 2\", \"Future removal 1\"],\n+ \"security\": [\"Known issue 1\", \"Known issue 2\"],\n+ \"version\": \"1.2.0\",\n+ },\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\ndiff --git a/tests/test_changelog_no_added.py b/tests/test_changelog_no_added.py\nindex 69d09de..05726ac 100644\n--- a/tests/test_changelog_no_added.py\n+++ b/tests/test_changelog_no_added.py\n@@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n ## [Unreleased]\n+\n+## [1.2.0] - 2018-06-01\n ### Changed\n - Release note 1.\n - Release note 2.\n@@ -65,28 +67,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n def test_changelog_with_versions_and_no_added(changelog):\n assert keepachangelog.to_dict(changelog) == {\n+ \"1.2.0\": {\n+ \"changed\": [\"Release note 1.\", \"Release note 2.\"],\n+ \"deprecated\": [\"Deprecated feature 1\", \"Future removal 2\"],\n+ \"fixed\": [\"Bug fix 1\", \"sub bug 1\", \"sub bug 2\", \"Bug fix 2\"],\n+ \"release_date\": \"2018-06-01\",\n+ \"removed\": [\"Deprecated feature 2\", \"Future removal 1\"],\n+ \"security\": [\"Known issue 1\", \"Known issue 2\"],\n+ \"version\": \"1.2.0\",\n+ },\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\ndiff --git a/tests/test_changelog_no_changed.py b/tests/test_changelog_no_changed.py\nindex 4d19407..2a77605 100644\n--- a/tests/test_changelog_no_changed.py\n+++ b/tests/test_changelog_no_changed.py\n@@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n ## [Unreleased]\n+\n+## [1.2.0] - 2018-06-01\n ### Added\n - Enhancement 1\n - sub enhancement 1\n@@ -62,19 +64,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n def test_changelog_with_versions_and_no_changed(changelog):\n assert keepachangelog.to_dict(changelog) == {\n+ \"1.2.0\": {\n+ \"added\": [\n+ \"Enhancement 1\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2\",\n+ ],\n+ \"deprecated\": [\"Deprecated feature 1\", \"Future removal 2\"],\n+ \"fixed\": [\"Bug fix 1\", \"sub bug 1\", \"sub bug 2\", \"Bug fix 2\"],\n+ \"release_date\": \"2018-06-01\",\n+ \"removed\": [\"Deprecated feature 2\", \"Future removal 1\"],\n+ \"security\": [\"Known issue 1\", \"Known issue 2\"],\n+ \"version\": \"1.2.0\",\n+ },\n \"1.1.0\": {\"release_date\": \"2018-05-31\", \"version\": \"1.1.0\"},\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\ndiff --git a/tests/test_changelog_no_deprecated.py b/tests/test_changelog_no_deprecated.py\nindex 119b723..fb1f27e 100644\n--- a/tests/test_changelog_no_deprecated.py\n+++ b/tests/test_changelog_no_deprecated.py\n@@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n ## [Unreleased]\n+\n+## [1.2.0] - 2018-06-01\n ### Changed\n - Release note 1.\n - Release note 2.\n@@ -64,22 +66,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n def test_changelog_with_versions_and_no_deprecated(changelog):\n assert keepachangelog.to_dict(changelog) == {\n+ \"1.2.0\": {\n+ \"added\": [\n+ \"Enhancement 1\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2\",\n+ ],\n+ \"changed\": [\"Release note 1.\", \"Release note 2.\"],\n+ \"fixed\": [\"Bug fix 1\", \"sub bug 1\", \"sub bug 2\", \"Bug fix 2\"],\n+ \"release_date\": \"2018-06-01\",\n+ \"removed\": [\"Deprecated feature 2\", \"Future removal 1\"],\n+ \"security\": [\"Known issue 1\", \"Known issue 2\"],\n+ \"version\": \"1.2.0\",\n+ },\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\ndiff --git a/tests/test_changelog_no_fixed.py b/tests/test_changelog_no_fixed.py\nindex 162168a..cae056e 100644\n--- a/tests/test_changelog_no_fixed.py\n+++ b/tests/test_changelog_no_fixed.py\n@@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n ## [Unreleased]\n+\n+## [1.2.0] - 2018-06-01\n ### Changed\n - Release note 1.\n - Release note 2.\n@@ -28,12 +30,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n - sub enhancement 2\n - Enhancement 2\n \n-### Fixed\n-- Bug fix 1\n-- sub bug 1\n-- sub bug 2\n-- Bug fix 2\n-\n ### Security\n - Known issue 1\n - Known issue 2\n@@ -71,28 +67,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n def test_changelog_with_versions_and_no_fixed(changelog):\n assert keepachangelog.to_dict(changelog) == {\n+ \"1.2.0\": {\n+ \"added\": [\n+ \"Enhancement 1\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2\",\n+ ],\n+ \"changed\": [\"Release note 1.\", \"Release note 2.\"],\n+ \"deprecated\": [\"Deprecated feature 1\", \"Future removal 2\"],\n+ \"release_date\": \"2018-06-01\",\n+ \"removed\": [\"Deprecated feature 2\", \"Future removal 1\"],\n+ \"security\": [\"Known issue 1\", \"Known issue 2\"],\n+ \"version\": \"1.2.0\",\n+ },\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\ndiff --git a/tests/test_changelog_no_removed.py b/tests/test_changelog_no_removed.py\nindex 21c0698..dc97af2 100644\n--- a/tests/test_changelog_no_removed.py\n+++ b/tests/test_changelog_no_removed.py\n@@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n ## [Unreleased]\n+\n+## [1.2.0] - 2018-06-01\n ### Changed\n - Release note 1.\n - Release note 2.\n@@ -67,28 +69,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n def test_changelog_with_versions_and_no_removed(changelog):\n assert keepachangelog.to_dict(changelog) == {\n+ \"1.2.0\": {\n+ \"added\": [\n+ \"Enhancement 1\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2\",\n+ ],\n+ \"changed\": [\"Release note 1.\", \"Release note 2.\"],\n+ \"deprecated\": [\"Deprecated feature 1\", \"Future removal 2\"],\n+ \"fixed\": [\"Bug fix 1\", \"sub bug 1\", \"sub bug 2\", \"Bug fix 2\"],\n+ \"release_date\": \"2018-06-01\",\n+ \"security\": [\"Known issue 1\", \"Known issue 2\"],\n+ \"version\": \"1.2.0\",\n+ },\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\ndiff --git a/tests/test_changelog_no_security.py b/tests/test_changelog_no_security.py\nindex 8ba1022..8724509 100644\n--- a/tests/test_changelog_no_security.py\n+++ b/tests/test_changelog_no_security.py\n@@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n ## [Unreleased]\n+\n+## [1.2.0] - 2018-06-01\n ### Changed\n - Release note 1.\n - Release note 2.\n@@ -34,10 +36,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n - sub bug 2\n - Bug fix 2\n \n-### Security\n-- Known issue 1\n-- Known issue 2\n-\n ### Deprecated\n - Deprecated feature 1\n - Future removal 2\n@@ -71,28 +69,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n def test_changelog_with_versions_and_no_security(changelog):\n assert keepachangelog.to_dict(changelog) == {\n+ \"1.2.0\": {\n+ \"added\": [\n+ \"Enhancement 1\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2\",\n+ ],\n+ \"changed\": [\"Release note 1.\", \"Release note 2.\"],\n+ \"deprecated\": [\"Deprecated feature 1\", \"Future removal 2\"],\n+ \"fixed\": [\"Bug fix 1\", \"sub bug 1\", \"sub bug 2\", \"Bug fix 2\"],\n+ \"release_date\": \"2018-06-01\",\n+ \"removed\": [\"Deprecated feature 2\", \"Future removal 1\"],\n+ \"version\": \"1.2.0\",\n+ },\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\ndiff --git a/tests/test_changelog_unreleased.py b/tests/test_changelog_unreleased.py\nindex 4eb19b5..bf6d2be 100644\n--- a/tests/test_changelog_unreleased.py\n+++ b/tests/test_changelog_unreleased.py\n@@ -19,32 +19,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n \n ## [Unreleased]\n ### Changed\n-- Release note 1.\n-- Release note 2.\n+- Release note 1. \n+* Release note 2.\n \n ### Added\n - Enhancement 1\n-- sub enhancement 1\n-- sub enhancement 2\n+ - sub enhancement 1 \n+ * sub enhancement 2\n - Enhancement 2\n \n ### Fixed\n - Bug fix 1\n-- sub bug 1\n-- sub bug 2\n+ - sub bug 1\n+ * sub bug 2\n - Bug fix 2\n \n ### Security\n-- Known issue 1\n+* Known issue 1\n - Known issue 2\n \n ### Deprecated\n-- Deprecated feature 1\n-- Future removal 2\n+- Deprecated feature 1 \n+* Future removal 2\n \n ### Removed\n - Deprecated feature 2\n-- Future removal 1\n+* Future removal 1 \n \n ## [1.1.0] - 2018-05-31\n ### Changed\n@@ -79,41 +79,41 @@ def test_changelog_with_versions_and_all_categories(changelog):\n \"Unreleased\": {\n \"version\": \"Unreleased\",\n \"release_date\": None,\n- \"changed\": [\"- Release note 1.\", \"- Release note 2.\"],\n+ \"changed\": [\"Release note 1.\", \"Release note 2.\"],\n \"added\": [\n- \"- Enhancement 1\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2\",\n+ \"Enhancement 1\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2\",\n ],\n- \"fixed\": [\"- Bug fix 1\", \"- sub bug 1\", \"- sub bug 2\", \"- Bug fix 2\"],\n- \"security\": [\"- Known issue 1\", \"- Known issue 2\"],\n- \"deprecated\": [\"- Deprecated feature 1\", \"- Future removal 2\"],\n- \"removed\": [\"- Deprecated feature 2\", \"- Future removal 1\"],\n+ \"fixed\": [\"Bug fix 1\", \"sub bug 1\", \"sub bug 2\", \"Bug fix 2\"],\n+ \"security\": [\"Known issue 1\", \"Known issue 2\"],\n+ \"deprecated\": [\"Deprecated feature 1\", \"Future removal 2\"],\n+ \"removed\": [\"Deprecated feature 2\", \"Future removal 1\"],\n },\n \"1.1.0\": {\n \"version\": \"1.1.0\",\n \"release_date\": \"2018-05-31\",\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n },\n \"1.0.1\": {\n \"version\": \"1.0.1\",\n \"release_date\": \"2018-05-31\",\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n },\n \"1.0.0\": {\n \"version\": \"1.0.0\",\n \"release_date\": \"2017-04-10\",\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n },\n }\ndiff --git a/tests/test_starlette.py b/tests/test_starlette.py\nindex eb8fb7d..f6f21b6 100644\n--- a/tests/test_starlette.py\n+++ b/tests/test_starlette.py\n@@ -79,26 +79,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n assert response.json() == {\n \"1.1.0\": {\n \"changed\": [\n- \"- Enhancement 1 (1.1.0)\",\n- \"- sub enhancement 1\",\n- \"- sub enhancement 2\",\n- \"- Enhancement 2 (1.1.0)\",\n+ \"Enhancement 1 (1.1.0)\",\n+ \"sub enhancement 1\",\n+ \"sub enhancement 2\",\n+ \"Enhancement 2 (1.1.0)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.1.0\",\n },\n \"1.0.1\": {\n \"fixed\": [\n- \"- Bug fix 1 (1.0.1)\",\n- \"- sub bug 1\",\n- \"- sub bug 2\",\n- \"- Bug fix 2 (1.0.1)\",\n+ \"Bug fix 1 (1.0.1)\",\n+ \"sub bug 1\",\n+ \"sub bug 2\",\n+ \"Bug fix 2 (1.0.1)\",\n ],\n \"release_date\": \"2018-05-31\",\n \"version\": \"1.0.1\",\n },\n \"1.0.0\": {\n- \"deprecated\": [\"- Known issue 1 (1.0.0)\", \"- Known issue 2 (1.0.0)\"],\n+ \"deprecated\": [\"Known issue 1 (1.0.0)\", \"Known issue 2 (1.0.0)\"],\n \"release_date\": \"2017-04-10\",\n \"version\": \"1.0.0\",\n },\n", "FAIL_TO_PASS": ["tests/test_changelog.py::test_changelog_with_versions_and_all_categories", "tests/test_changelog_no_added.py::test_changelog_with_versions_and_no_added", "tests/test_changelog_no_changed.py::test_changelog_with_versions_and_no_changed", "tests/test_changelog_no_deprecated.py::test_changelog_with_versions_and_no_deprecated", "tests/test_changelog_no_fixed.py::test_changelog_with_versions_and_no_fixed", "tests/test_changelog_no_removed.py::test_changelog_with_versions_and_no_removed", "tests/test_changelog_no_security.py::test_changelog_with_versions_and_no_security", "tests/test_changelog_unreleased.py::test_changelog_with_versions_and_all_categories", "tests/test_starlette.py::test_changelog_endpoint_with_file"]}], "all_FAIL_TO_PASS": ["tests/test_changelog.py::test_changelog_with_versions_and_all_categories", "tests/test_changelog_no_added.py::test_changelog_with_versions_and_no_added", "tests/test_changelog_no_changed.py::test_changelog_with_versions_and_no_changed", "tests/test_changelog_no_deprecated.py::test_changelog_with_versions_and_no_deprecated", "tests/test_changelog_no_fixed.py::test_changelog_with_versions_and_no_fixed", "tests/test_changelog_no_removed.py::test_changelog_with_versions_and_no_removed", "tests/test_changelog_no_security.py::test_changelog_with_versions_and_no_security", "tests/test_changelog_unreleased.py::test_changelog_with_versions_and_all_categories", "tests/test_starlette.py::test_changelog_endpoint_with_file"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Justintime50__github-archive-33_x1", "level": 1, "source": "swerebench", "repo": "Justintime50/github-archive", "image": "swerebench/sweb.eval.x86_64.justintime50_1776_github-archive-33:latest", "base_commit": "63e8730ff7eb0aeae2d94cbed9b239e38068c520", "num_bugs": 1, "bugs": [{"instance_id": "Justintime50__github-archive-33", "base_commit": "63e8730ff7eb0aeae2d94cbed9b239e38068c520", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex bff191d..cf5782d 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -15,6 +15,7 @@\n * Added the `--threads` flag which can specify the number of concurrent threads to run at once (closes #22)\n * Adds a new `--view` flag which allows you to \"dry run\" the application, seeing the entire list of repos and gists based on the input provided (closes #25)\n * Adds a new `--stars` flag which you can pass a comma separated list of users to and GitHub Archive will retrieve all of their starred repos which you can then view, clone, or pull (closes #26)\n+* Adds a new `--forks` flag which will include forks for whatever lists and operations you provide (closes #17))\n \n ### Fixes\n \ndiff --git a/README_v4.md b/README_v4.md\nindex d8e6d5b..29b3bda 100644\n--- a/README_v4.md\n+++ b/README_v4.md\n@@ -72,6 +72,7 @@ Options:\n -v, --view Pass this flag to view git assets (dry run).\n -c, --clone Pass this flag to clone git assets.\n -p, --pull Pass this flag to pull git assets.\n+ -f, --forks Pass this flag to include forked git assets.\n -u USERS, --users USERS\n Pass a comma separated list of users to get repos for.\n -o ORGS, --orgs ORGS Pass a comma separated list of orgs to get repos for.\ndiff --git a/github_archive/archive.py b/github_archive/archive.py\nindex 828bac9..ae3bbae 100644\n--- a/github_archive/archive.py\n+++ b/github_archive/archive.py\n@@ -28,6 +28,7 @@ class GithubArchive:\n view=False,\n clone=False,\n pull=False,\n+ forks=False,\n users=None,\n orgs=None,\n gists=None,\n@@ -41,6 +42,7 @@ class GithubArchive:\n self.view = view\n self.clone = clone\n self.pull = pull\n+ self.forks = forks\n self.users = users.lower().split(',') if users else ''\n self.orgs = orgs.lower().split(',') if orgs else ''\n self.gists = gists.lower().split(',') if gists else ''\n@@ -64,7 +66,7 @@ class GithubArchive:\n # Personal (includes personal authenticated items)\n if self.token and self.authenticated_user_in_users and self.users:\n LOGGER.info('# Making API call to GitHub for personal repos...\\n')\n- personal_repos = self.get_personal_repos()\n+ personal_repos = self.get_all_git_assets(PERSONAL_CONTEXT)\n \n if self.view:\n LOGGER.info('# Viewing user repos...\\n')\n@@ -80,7 +82,7 @@ class GithubArchive:\n # repos for the `users` logic.\n self.users.remove(self.authenticated_username)\n \n- # Users (can include personal non-authenticated items)\n+ # Users (can include personal non-authenticated items, excludes personal authenticated calls)\n if self.users and len(self.users) > 0:\n LOGGER.info('# Making API calls to GitHub for user repos...\\n')\n user_repos = self.get_all_git_assets(USER_CONTEXT)\n@@ -167,44 +169,41 @@ class GithubArchive:\n def authenticated_user_in_users(self):\n return self.authenticated_user.login.lower() in self.users\n \n- def get_personal_repos(self):\n- \"\"\"Retrieve all repos of the authenticated user.\"\"\"\n- repos = self.authenticated_user.get_repos()\n- LOGGER.debug('Personal repos retrieved!')\n-\n- return repos\n-\n def get_all_git_assets(self, context):\n \"\"\"Retrieve a list of lists via API of git assets (repos, gists) of the\n specified owner(s) (users, orgs). Return a sorted, flat, sorted list of git assets.\n \"\"\"\n- get_user_repos = lambda item: self.github_instance.get_user(item).get_repos() # noqa\n- get_org_repos = lambda item: self.github_instance.get_organization(item).get_repos() # noqa\n- get_user_gists = lambda item: self.github_instance.get_user(item).get_gists() # noqa\n- get_starred_repos = lambda item: self.github_instance.get_user(item).get_starred() # noqa\n+ get_org_repos = lambda owner: self.github_instance.get_organization(owner).get_repos() # noqa\n+ get_personal_repos = lambda owner: self.authenticated_user.get_repos(affiliation='owner') # noqa\n+ get_starred_repos = lambda owner: self.github_instance.get_user(owner).get_starred() # noqa\n+ get_user_gists = lambda owner: self.github_instance.get_user(owner).get_gists() # noqa\n+ get_user_repos = lambda owner: self.github_instance.get_user(owner).get_repos() # noqa\n \n context_manager = {\n- USER_CONTEXT: [self.users, get_user_repos, 'repos'],\n- ORG_CONTEXT: [self.orgs, get_org_repos, 'repos'],\n GIST_CONTEXT: [self.gists, get_user_gists, 'gists'],\n+ ORG_CONTEXT: [self.orgs, get_org_repos, 'repos'],\n+ PERSONAL_CONTEXT: [self.users, get_personal_repos, 'repos'],\n STAR_CONTEXT: [self.stars, get_starred_repos, 'starred repos'],\n+ USER_CONTEXT: [self.users, get_user_repos, 'repos'],\n }\n \n all_git_assets = []\n- cli_list = context_manager[context][0]\n+ owner_list = context_manager[context][0]\n git_asset_string = context_manager[context][2]\n \n- for item in cli_list:\n- formatted_item_name = item.strip()\n- git_assets = sorted(context_manager[context][1](item), key=lambda item: item.name)\n- all_git_assets.append(git_assets)\n- LOGGER.debug(f'{formatted_item_name} {git_asset_string} retrieved!')\n+ for owner in owner_list:\n+ formatted_owner_name = owner.strip()\n+ git_assets = context_manager[context][1](owner)\n+ LOGGER.debug(f'{formatted_owner_name} {git_asset_string} retrieved!')\n \n- flattened_git_asset_list = [\n- git_asset for sublist_git_assets in all_git_assets for git_asset in sublist_git_assets\n- ]\n+ for item in git_assets:\n+ if self.forks or (self.forks is False and item.fork is False):\n+ all_git_assets.append(item)\n+ else:\n+ # Do not include this forked asset\n+ pass\n \n- final_sorted_list = sorted(flattened_git_asset_list, key=lambda item: item.owner.login)\n+ final_sorted_list = sorted(all_git_assets, key=lambda item: item.owner.login)\n \n return final_sorted_list\n \n@@ -215,29 +214,18 @@ class GithubArchive:\n \n for repo in repos:\n repo_owner_username = repo.owner.login.lower()\n- # We check the owner name here to ensure that we only iterate\n- # through the user's personal repos which will exclude orgs.\n- #\n- # This is important because PyGithub will include a user's org repos\n- # in the list of repos for an authenticated user out of the box.\n- #\n- # Instead, the user can pass the \"--clone_orgs\" or \"--pull_orgs\"\n- # flags to allow for more granular control over which repos they get.\n- if self.token and repo_owner_username != self.authenticated_username and context == PERSONAL_CONTEXT:\n- continue\n- else:\n- repo_path = os.path.join(self.location, 'repos', repo_owner_username, repo.name)\n- repo_thread = Thread(\n- target=self.archive_repo,\n- args=(\n- thread_limiter,\n- repo,\n- repo_path,\n- operation,\n- ),\n- )\n- thread_list.append(repo_thread)\n- repo_thread.start()\n+ repo_path = os.path.join(self.location, 'repos', repo_owner_username, repo.name)\n+ repo_thread = Thread(\n+ target=self.archive_repo,\n+ args=(\n+ thread_limiter,\n+ repo,\n+ repo_path,\n+ operation,\n+ ),\n+ )\n+ thread_list.append(repo_thread)\n+ repo_thread.start()\n for thread in thread_list:\n thread.join()\n \ndiff --git a/github_archive/cli.py b/github_archive/cli.py\nindex 334cae4..503a10b 100644\n--- a/github_archive/cli.py\n+++ b/github_archive/cli.py\n@@ -35,6 +35,14 @@ class GithubArchiveCli:\n default=False,\n help='Pass this flag to pull git assets.',\n )\n+ parser.add_argument(\n+ '-f',\n+ '--forks',\n+ action='store_true',\n+ required=False,\n+ default=False,\n+ help='Pass this flag to include forked git assets.',\n+ )\n parser.add_argument(\n '-u',\n '--users',\n@@ -109,6 +117,7 @@ class GithubArchiveCli:\n view=self.view,\n clone=self.clone,\n pull=self.pull,\n+ forks=self.forks,\n users=self.users,\n orgs=self.orgs,\n gists=self.gists,\n", "test_patch": "diff --git a/test/unit/test_archive.py b/test/unit/test_archive.py\nindex 7d4cabd..f157af0 100644\n--- a/test/unit/test_archive.py\n+++ b/test/unit/test_archive.py\n@@ -28,8 +28,8 @@ def mock_thread_limiter():\n @mock.patch('github_archive.archive.Github.get_user')\n @mock.patch('github_archive.archive.GithubArchive.authenticated_user_in_users', return_value=True)\n @mock.patch('github_archive.archive.GithubArchive.view_repos')\n-@mock.patch('github_archive.archive.GithubArchive.get_personal_repos')\n-def test_run_token_view(mock_get_personal_repos, mock_view_repos, mock_authed_user_in_users, mock_get_user):\n+@mock.patch('github_archive.archive.GithubArchive.get_all_git_assets')\n+def test_run_token_view(mock_get_all_git_assets, mock_view_repos, mock_authed_user_in_users, mock_get_user):\n github_archive = GithubArchive(\n token='123',\n users='justintime50',\n@@ -39,7 +39,7 @@ def test_run_token_view(mock_get_personal_repos, mock_view_repos, mock_authed_us\n github_archive.authenticated_username = 'justintime50'\n github_archive.run()\n \n- mock_get_personal_repos.assert_called_once()\n+ mock_get_all_git_assets.assert_called_once()\n mock_view_repos.assert_called_once()\n assert github_archive.users == [] # Assert the authed user gets removed from list\n \n@@ -47,9 +47,9 @@ def test_run_token_view(mock_get_personal_repos, mock_view_repos, mock_authed_us\n @mock.patch('github_archive.archive.Github.get_user')\n @mock.patch('github_archive.archive.GithubArchive.authenticated_user_in_users', return_value=True)\n @mock.patch('github_archive.archive.GithubArchive.iterate_repos_to_archive')\n-@mock.patch('github_archive.archive.GithubArchive.get_personal_repos')\n+@mock.patch('github_archive.archive.GithubArchive.get_all_git_assets')\n def test_run_token_clone(\n- mock_get_personal_repos, mock_iterate_repos_to_archive, mock_authed_user_in_users, mock_get_user\n+ mock_get_all_git_assets, mock_iterate_repos_to_archive, mock_authed_user_in_users, mock_get_user\n ):\n github_archive = GithubArchive(\n token='123',\n@@ -60,7 +60,7 @@ def test_run_token_clone(\n github_archive.authenticated_username = 'justintime50'\n github_archive.run()\n \n- mock_get_personal_repos.assert_called_once()\n+ mock_get_all_git_assets.assert_called_once()\n mock_iterate_repos_to_archive.assert_called_once()\n assert github_archive.users == [] # Assert the authed user gets removed from list\n \n@@ -68,9 +68,9 @@ def test_run_token_clone(\n @mock.patch('github_archive.archive.Github.get_user')\n @mock.patch('github_archive.archive.GithubArchive.authenticated_user_in_users', return_value=True)\n @mock.patch('github_archive.archive.GithubArchive.iterate_repos_to_archive')\n-@mock.patch('github_archive.archive.GithubArchive.get_personal_repos')\n+@mock.patch('github_archive.archive.GithubArchive.get_all_git_assets')\n def test_run_token_pull(\n- mock_get_personal_repos, mock_iterate_repos_to_archive, mock_authed_user_in_users, mock_get_user\n+ mock_get_all_git_assets, mock_iterate_repos_to_archive, mock_authed_user_in_users, mock_get_user\n ):\n github_archive = GithubArchive(\n token='123',\n@@ -81,7 +81,7 @@ def test_run_token_pull(\n github_archive.authenticated_username = 'justintime50'\n github_archive.run()\n \n- mock_get_personal_repos.assert_called_once()\n+ mock_get_all_git_assets.assert_called_once()\n mock_iterate_repos_to_archive.assert_called_once()\n assert github_archive.users == [] # Assert the authed user gets removed from list\n \n@@ -275,11 +275,10 @@ def test_authenticated_user_in_users(mock_get_user):\n \n \n @mock.patch('github_archive.archive.Github.get_user')\n-def test_get_personal_repos(mock_get_user):\n+def test_get_all_git_assets(mock_get_user):\n GithubArchive(\n- token='123',\n users='justintime50',\n- ).get_personal_repos()\n+ ).get_all_git_assets(USER_CONTEXT)\n \n mock_get_user.assert_called_once()\n \n@@ -334,7 +333,7 @@ def test_iterate_repos_not_matching_authed_username(mock_archive_repo, mock_gith\n users='mock_username',\n ).iterate_repos_to_archive(repos, PERSONAL_CONTEXT, CLONE_OPERATION)\n \n- mock_archive_repo.assert_called()\n+ mock_archive_repo.assert_called_once()\n \n \n @mock.patch('github_archive.archive.Github')\n@@ -343,10 +342,10 @@ def test_iterate_repos_matching_authed_username(mock_archive_repo, mock_github_i\n repos = [mock_git_asset]\n GithubArchive(\n token='123',\n- users='mock_username',\n+ users='mock_username', # matches the username of the git asset\n ).iterate_repos_to_archive(repos, PERSONAL_CONTEXT, CLONE_OPERATION)\n \n- mock_archive_repo.assert_not_called()\n+ mock_archive_repo.assert_called_once()\n \n \n @mock.patch('github_archive.archive.Github')\n", "FAIL_TO_PASS": ["test/unit/test_archive.py::test_run_token_view", "test/unit/test_archive.py::test_run_token_clone", "test/unit/test_archive.py::test_run_token_pull", "test/unit/test_archive.py::test_iterate_repos_matching_authed_username"]}], "all_FAIL_TO_PASS": ["test/unit/test_archive.py::test_run_token_view", "test/unit/test_archive.py::test_run_token_clone", "test/unit/test_archive.py::test_run_token_pull", "test/unit/test_archive.py::test_iterate_repos_matching_authed_username"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Materials-Consortia__optimade-python-tools-1001_x1", "level": 1, "source": "swerebench", "repo": "Materials-Consortia/optimade-python-tools", "image": "swerebench/sweb.eval.x86_64.materials-consortia_1776_optimade-python-tools-1001:latest", "base_commit": "03b60f9f313db87daf5b76192a426588072a79e2", "num_bugs": 1, "bugs": [{"instance_id": "Materials-Consortia__optimade-python-tools-1001", "base_commit": "03b60f9f313db87daf5b76192a426588072a79e2", "gold_patch": "diff --git a/optimade/models/structures.py b/optimade/models/structures.py\nindex 62a39f46..1ef9ae57 100644\n--- a/optimade/models/structures.py\n+++ b/optimade/models/structures.py\n@@ -872,7 +872,8 @@ The properties of the species are found in the property `species`.\n return v\n \n elements = tuple(re.findall(r\"[A-Z][a-z]*\", v))\n- numbers = [int(n.strip()) for n in re.split(r\"[A-Z][a-z]*\", v) if n.strip()]\n+ numbers = re.split(r\"[A-Z][a-z]*\", v)[1:]\n+ numbers = [int(i) if i else 1 for i in numbers]\n \n expected_labels = ANONYMOUS_ELEMENTS[: len(elements)]\n expected_numbers = sorted(numbers, reverse=True)\n", "test_patch": "diff --git a/tests/models/test_structures.py b/tests/models/test_structures.py\nindex 09e9a626..e1401e55 100644\n--- a/tests/models/test_structures.py\n+++ b/tests/models/test_structures.py\n@@ -103,8 +103,8 @@ deformities = (\n \"'chemical_formula_anonymous' A2B90 has wrong order: elements with highest proportion should appear first: [2, 90] vs expected [90, 2]\",\n ),\n (\n- {\"chemical_formula_anonymous\": \"A2B10\"},\n- \"'chemical_formula_anonymous' A2B10 has wrong order: elements with highest proportion should appear first: [2, 10] vs expected [10, 2]\",\n+ {\"chemical_formula_anonymous\": \"AB10\"},\n+ \"'chemical_formula_anonymous' AB10 has wrong order: elements with highest proportion should appear first: [1, 10] vs expected [10, 1]\",\n ),\n (\n {\"chemical_formula_hill\": \"SiGe\"},\n", "FAIL_TO_PASS": ["tests/models/test_structures.py::test_structure_fatal_deformities[deformity8]"]}], "all_FAIL_TO_PASS": ["tests/models/test_structures.py::test_structure_fatal_deformities[deformity8]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Deltares__pyflwdir-18_x1", "level": 1, "source": "swerebench", "repo": "Deltares/pyflwdir", "image": "swerebench/sweb.eval.x86_64.deltares_1776_pyflwdir-18:latest", "base_commit": "90be06f24c7d7ce9bbeeccf19b1452d5be8859d2", "num_bugs": 1, "bugs": [{"instance_id": "Deltares__pyflwdir-18", "base_commit": "90be06f24c7d7ce9bbeeccf19b1452d5be8859d2", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex c0327c7..f240f71 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -2,6 +2,16 @@\n Change Log\n ###########\n \n+Unreleased\n+********************\n+\n+Improved\n+---------\n+* prioritize non-boundary cells with same elevation over boundary cells in dem.fill_depressions, #17\n+\n+Bugfix\n+------\n+\n \n 0.5.3 (18-Nov-2021)\n ********************\ndiff --git a/pyflwdir/dem.py b/pyflwdir/dem.py\nindex 0d6876e..cb77f81 100644\n--- a/pyflwdir/dem.py\n+++ b/pyflwdir/dem.py\n@@ -76,25 +76,27 @@ def fill_depressions(\n # initiate queue\n if idxs_pit is None: # with edge cells\n queued = gis_utils.get_edge(~done, structure=struct)\n- else: # with user difinfed outlet cells\n+ else: # with user defined outlet cells\n queued = np.array([bool(0) for s in range(elevtn.size)]).reshape((nrow, ncol))\n for idx in idxs_pit:\n queued.flat[idx] = True\n- q = [(elevtn[0, 0], np.uint32(0), np.uint32(0)) for _ in range(0)]\n+ # queue contains (elevation, boundary, row, col)\n+ # boundary is included to favor non-boundary cells over boundary cells with same elevation\n+ q = [(elevtn[0, 0], np.uint8(1), np.uint32(0), np.uint32(0)) for _ in range(0)]\n heapq.heapify(q)\n for r, c in zip(*np.where(queued)):\n- heapq.heappush(q, (elevtn[r, c], np.uint32(r), np.uint32(c)))\n+ heapq.heappush(q, (elevtn[r, c], np.uint8(1), np.uint32(r), np.uint32(c)))\n # restrict queue to global edge mimimum (single outlet)\n if outlets == \"min\":\n q = [heapq.heappop(q)]\n queued[:, :] = False\n- queued[q[0][1], q[0][2]] = True\n+ queued[q[0][-2], q[0][-1]] = True\n \n # loop over cells and neighbors with ascending cell elevation.\n drs, dcs = np.where(struct)\n drs, dcs = drs - 1, dcs - 1\n while len(q) > 0:\n- z0, r0, c0 = heapq.heappop(q)\n+ z0, _, r0, c0 = heapq.heappop(q)\n for dr, dc in zip(drs, dcs):\n r = r0 + dr\n c = c0 + dc\n@@ -104,7 +106,7 @@ def fill_depressions(\n dz = z0 - z1 # local depression if dz > 0\n if max_depth >= 0: # if positive max_depth: don't fill when dz > max_depth\n if dz >= max_depth:\n- heapq.heappush(q, (z1, np.uint32(r), np.uint32(c)))\n+ heapq.heappush(q, (z1, np.uint8(0), np.uint32(r), np.uint32(c)))\n queued[r, c] = True\n for dr, dc in zip(drs, dcs): # (re)visit neighbors\n done[r + dr, c + dc] = False\n@@ -116,7 +118,7 @@ def fill_depressions(\n delv[r, c] = dz\n z1 += dz\n if ~queued[r, c]: # add to queue\n- heapq.heappush(q, (z1, np.uint32(r), np.uint32(c)))\n+ heapq.heappush(q, (z1, np.uint8(0), np.uint32(r), np.uint32(c)))\n queued[r, c] = True\n done[r, c] = True\n d8[r, c] = core_d8._us[dr + 1, dc + 1]\n", "test_patch": "diff --git a/tests/test_dem.py b/tests/test_dem.py\nindex 8d7449a..39ec1d4 100644\n--- a/tests/test_dem.py\n+++ b/tests/test_dem.py\n@@ -24,12 +24,13 @@ def test_from_dem():\n )\n # NOTE: compared to paper same a_filled, but difference\n # in flowdir because row instead of col first ..\n+ # and priority of non-boundary cells with same elevation\n d8 = np.array(\n [\n [2, 2, 4, 8, 1, 0, 16],\n [1, 1, 2, 2, 128, 64, 32],\n [128, 128, 1, 1, 2, 2, 4],\n- [64, 128, 128, 128, 1, 1, 0],\n+ [128, 128, 128, 128, 1, 1, 0],\n [64, 128, 64, 32, 128, 128, 64],\n ],\n dtype=np.uint8,\n", "FAIL_TO_PASS": ["tests/test_dem.py::test_from_dem"]}], "all_FAIL_TO_PASS": ["tests/test_dem.py::test_from_dem"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "JelleZijlstra__ast_decompiler-34_x1", "level": 1, "source": "swerebench", "repo": "JelleZijlstra/ast_decompiler", "image": "swerebench/sweb.eval.x86_64.jellezijlstra_1776_ast_decompiler-34:latest", "base_commit": "f347ea7ddf9162d5b0e89edec73b4af0fa5fc9f7", "num_bugs": 1, "bugs": [{"instance_id": "JelleZijlstra__ast_decompiler-34", "base_commit": "f347ea7ddf9162d5b0e89edec73b4af0fa5fc9f7", "gold_patch": "diff --git a/CHANGELOG b/CHANGELOG\nindex 62b8063..3d37564 100644\n--- a/CHANGELOG\n+++ b/CHANGELOG\n@@ -1,4 +1,5 @@\n unreleased\n+- Preserve literal newlines in docstrings\n - Fix decompilation of complex infinity\n - Add support for Python 3.10 pattern matching\n - Fix incorrect decompilation of lambdas in comprehension guards on Python 3.9 and higher\ndiff --git a/ast_decompiler/decompiler.py b/ast_decompiler/decompiler.py\nindex d21c412..e642df8 100644\n--- a/ast_decompiler/decompiler.py\n+++ b/ast_decompiler/decompiler.py\n@@ -834,13 +834,21 @@ class Decompiler(ast.NodeVisitor):\n def write_string(self, string_value: str, kind: Optional[str] = None) -> None:\n if kind is not None:\n self.write(kind)\n+ if isinstance(self.get_parent_node(), ast.Expr) and '\"\"\"' not in string_value:\n+ self.write('\"\"\"')\n+ s = string_value.encode(\"unicode-escape\").decode(\"ascii\")\n+ s = s.replace(\"\\\\n\", \"\\n\").replace(\"\\\\r\", \"\\r\")\n+ self.write(s)\n+ self.write('\"\"\"')\n+ return\n if self.has_parent_of_type(ast.FormattedValue):\n delimiter = '\"'\n else:\n delimiter = \"'\"\n self.write(delimiter)\n s = string_value.encode(\"unicode-escape\").decode(\"ascii\")\n- self.write(s.replace(delimiter, \"\\\\\" + delimiter))\n+ s = s.replace(delimiter, \"\\\\\" + delimiter)\n+ self.write(s)\n self.write(delimiter)\n \n def visit_FormattedValue(self, node: ast.FormattedValue) -> None:\n", "test_patch": "diff --git a/tests/test_basic.py b/tests/test_basic.py\nindex 5b39dbc..72a8ecb 100644\n--- a/tests/test_basic.py\n+++ b/tests/test_basic.py\n@@ -1,6 +1,6 @@\n import ast\n from ast_decompiler import decompile\n-from .tests import check, only_on_version\n+from .tests import assert_decompiles, check, only_on_version\n \n \n def test_non_module() -> None:\n@@ -380,6 +380,24 @@ def test_Str() -> None:\n b'foo'\n \"\"\"\n )\n+ check('\"a\\\\nb\"')\n+ assert_decompiles(\n+ '''def f():\n+ \"\"\"Doc.\n+\n+ String.\n+\n+ \"\"\"\n+''',\n+ '''\n+def f():\n+ \"\"\"Doc.\n+\n+ String.\n+\n+ \"\"\"\n+''',\n+ )\n \n \n def test_Attribute() -> None:\n", "FAIL_TO_PASS": ["tests/test_basic.py::test_Str"]}], "all_FAIL_TO_PASS": ["tests/test_basic.py::test_Str"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Abjad__abjad-ext-nauert-24_x1", "level": 1, "source": "swerebench", "repo": "Abjad/abjad-ext-nauert", "image": "swerebench/sweb.eval.x86_64.abjad_1776_abjad-ext-nauert-24:latest", "base_commit": "520f389f06e21ee0a094016b4f1e2b0cb58263c1", "num_bugs": 1, "bugs": [{"instance_id": "Abjad__abjad-ext-nauert-24", "base_commit": "520f389f06e21ee0a094016b4f1e2b0cb58263c1", "gold_patch": "diff --git a/abjadext/nauert/gracehandlers.py b/abjadext/nauert/gracehandlers.py\nindex 8813e0f..a2dbdd3 100644\n--- a/abjadext/nauert/gracehandlers.py\n+++ b/abjadext/nauert/gracehandlers.py\n@@ -199,8 +199,8 @@ class ConcatenatingGraceHandler(GraceHandler):\n \n .. container:: example\n \n- When ``replace_rest_with_final_grace_note`` is set to ``False`` (the\n- default behaviour), grace notes are allowed to be attached to a rest.\n+ When ``replace_rest_with_final_grace_note`` is set to ``False``, grace\n+ notes are allowed to be attached to a rest.\n \n >>> quantizer = nauert.Quantizer()\n >>> durations = [1000, 1, 999, 1000]\n@@ -208,7 +208,9 @@ class ConcatenatingGraceHandler(GraceHandler):\n >>> q_event_sequence = nauert.QEventSequence.from_millisecond_pitch_pairs(\n ... tuple(zip(durations, pitches))\n ... )\n- >>> grace_handler = nauert.ConcatenatingGraceHandler()\n+ >>> grace_handler = nauert.ConcatenatingGraceHandler(\n+ ... replace_rest_with_final_grace_note=False\n+ ... )\n >>> result = quantizer(q_event_sequence, grace_handler=grace_handler)\n >>> abjad.show(result) # doctest: +SKIP\n \n@@ -233,13 +235,11 @@ class ConcatenatingGraceHandler(GraceHandler):\n \n .. container:: example\n \n- When ``replace_rest_with_final_grace_note`` is set to ``True``, any\n- rest with grace notes attached to it is replaced by the last pitched\n- grace note in the grace container.\n+ When ``replace_rest_with_final_grace_note`` is set to ``True`` (the\n+ default behavior), any rest with grace notes attached to it is replaced\n+ by the last pitched grace note in the grace container.\n \n- >>> grace_handler = nauert.ConcatenatingGraceHandler(\n- ... replace_rest_with_final_grace_note=True\n- ... )\n+ >>> grace_handler = nauert.ConcatenatingGraceHandler()\n >>> result = quantizer(q_event_sequence, grace_handler=grace_handler)\n >>> abjad.show(result) # doctest: +SKIP\n \n@@ -274,7 +274,7 @@ class ConcatenatingGraceHandler(GraceHandler):\n self,\n discard_grace_rest=True,\n grace_duration=None,\n- replace_rest_with_final_grace_note=False,\n+ replace_rest_with_final_grace_note=True,\n ):\n self._discard_grace_rest = discard_grace_rest\n if grace_duration is None:\n", "test_patch": "diff --git a/tests/test_ConcatenatingGraceHandler___call__.py b/tests/test_ConcatenatingGraceHandler___call__.py\nindex 75fa793..11424af 100644\n--- a/tests/test_ConcatenatingGraceHandler___call__.py\n+++ b/tests/test_ConcatenatingGraceHandler___call__.py\n@@ -58,7 +58,9 @@ def test_ConcatenatingGraceHandler___call___02():\n \n \n def test_ConcatenatingGraceHandler___call___03():\n- grace_handler = nauert.ConcatenatingGraceHandler()\n+ grace_handler = nauert.ConcatenatingGraceHandler(\n+ replace_rest_with_final_grace_note=False\n+ )\n quantizer = nauert.Quantizer()\n durations = [1000, 1, 999, 1000]\n pitches = [0, 0, None, 0]\ndiff --git a/tests/test_ConcatenatingGraceHandler___init__.py b/tests/test_ConcatenatingGraceHandler___init__.py\nindex 8466a64..2b14614 100644\n--- a/tests/test_ConcatenatingGraceHandler___init__.py\n+++ b/tests/test_ConcatenatingGraceHandler___init__.py\n@@ -12,14 +12,14 @@ def test_ConcatenatingGraceHandler___init___02():\n grace_handler = nauert.ConcatenatingGraceHandler(discard_grace_rest=False)\n assert grace_handler.grace_duration == abjad.Duration(1, 16)\n assert grace_handler.discard_grace_rest is False\n- assert grace_handler.replace_rest_with_final_grace_note is False\n+ assert grace_handler.replace_rest_with_final_grace_note is True\n \n \n def test_ConcatenatingGraceHandler___init___03():\n grace_handler = nauert.ConcatenatingGraceHandler(grace_duration=(1, 32))\n assert grace_handler.grace_duration == abjad.Duration(1, 32)\n assert grace_handler.discard_grace_rest is True\n- assert grace_handler.replace_rest_with_final_grace_note is False\n+ assert grace_handler.replace_rest_with_final_grace_note is True\n \n \n def test_ConcatenatingGraceHandler___init___04():\n", "FAIL_TO_PASS": ["tests/test_ConcatenatingGraceHandler___init__.py::test_ConcatenatingGraceHandler___init___02", "tests/test_ConcatenatingGraceHandler___init__.py::test_ConcatenatingGraceHandler___init___03"]}], "all_FAIL_TO_PASS": ["tests/test_ConcatenatingGraceHandler___init__.py::test_ConcatenatingGraceHandler___init___02", "tests/test_ConcatenatingGraceHandler___init__.py::test_ConcatenatingGraceHandler___init___03"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NOhs__dkey-18_x1", "level": 1, "source": "swerebench", "repo": "NOhs/dkey", "image": "swerebench/sweb.eval.x86_64.nohs_1776_dkey-18:latest", "base_commit": "098cecbe1c1ed8cca92029dbd90f77cc6c0d7673", "num_bugs": 1, "bugs": [{"instance_id": "NOhs__dkey-18", "base_commit": "098cecbe1c1ed8cca92029dbd90f77cc6c0d7673", "gold_patch": "diff --git a/dkey/__init__.py b/dkey/__init__.py\nindex 266df21..f71a87d 100644\n--- a/dkey/__init__.py\n+++ b/dkey/__init__.py\n@@ -10,6 +10,20 @@ dkey\n ====\n Function to generate deprecated keys.\n \n+__version__\n+===========\n+A string indicating which version of dkey is currently used.\n+\n+version_info\n+============\n+A tuple containing the currently used version.\n+\n \"\"\"\n from ._dkey import deprecate_keys as deprecate_keys\n from ._dkey import dkey as dkey\n+\n+from pbr.version import VersionInfo\n+\n+_v = VersionInfo('mgen').semantic_version()\n+__version__ = _v.release_string()\n+version_info = _v.version_tuple()\n", "test_patch": "diff --git a/tests/test_dkey.py b/tests/test_dkey.py\nindex fa6ae8d..3105fd0 100644\n--- a/tests/test_dkey.py\n+++ b/tests/test_dkey.py\n@@ -6,6 +6,12 @@ from contextlib import contextmanager\n \n from dkey import deprecate_keys, dkey\n \n+class version_test_case(unittest.TestCase):\n+ def test_version_string_available(self):\n+ import dkey as dk\n+ self.assertTrue(hasattr(dk, '__version__'))\n+ self.assertTrue(hasattr(dk, 'version_info'))\n+\n class dkey_test_case(unittest.TestCase):\n def test_number_of_keys_incorrect(self):\n with self.assertRaises(ValueError):\n", "FAIL_TO_PASS": ["tests/test_dkey.py::version_test_case::test_version_string_available"]}], "all_FAIL_TO_PASS": ["tests/test_dkey.py::version_test_case::test_version_string_available"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MicroPyramid__forex-python-27_x1", "level": 1, "source": "swerebench", "repo": "MicroPyramid/forex-python", "image": "swerebench/sweb.eval.x86_64.micropyramid_1776_forex-python-27:latest", "base_commit": "1ebd8dda32503ca63d52b8a55f5647804fd1d1dd", "num_bugs": 1, "bugs": [{"instance_id": "MicroPyramid__forex-python-27", "base_commit": "1ebd8dda32503ca63d52b8a55f5647804fd1d1dd", "gold_patch": "diff --git a/forex_python/converter.py b/forex_python/converter.py\nindex bcc8348..316f0cf 100644\n--- a/forex_python/converter.py\n+++ b/forex_python/converter.py\n@@ -56,6 +56,8 @@ class CurrencyRates(Common):\n raise RatesNotAvailableError(\"Currency Rates Source Not Ready\")\n \n def get_rate(self, base_cur, dest_cur, date_obj=None):\n+ if base_cur == dest_cur:\n+ return 1.\n date_str = self._get_date_string(date_obj)\n payload = {'base': base_cur, 'symbols': dest_cur}\n source_url = self._source_url() + date_str\n", "test_patch": "diff --git a/tests/test.py b/tests/test.py\nindex 040ed75..2501aa9 100644\n--- a/tests/test.py\n+++ b/tests/test.py\n@@ -50,6 +50,11 @@ class TestGetRate(TestCase):\n \n # check if return value is float\n self.assertTrue(isinstance(rate, float))\n+ \n+ def test_get_rate_with_valid_codes_same_currency(self):\n+ rate = get_rate('USD', 'USD')\n+ # rate should be 1.\n+ self.assertEqual(1., rate)\n \n def test_get_rate_with_date(self):\n date_obj = datetime.datetime.strptime('2010-05-10', \"%Y-%m-%d\").date()\n", "FAIL_TO_PASS": ["tests/test.py::TestGetRate::test_get_rate_with_valid_codes_same_currency"]}], "all_FAIL_TO_PASS": ["tests/test.py::TestGetRate::test_get_rate_with_valid_codes_same_currency"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NCAS-CMS__cf-python-284_x1", "level": 1, "source": "swerebench", "repo": "NCAS-CMS/cf-python", "image": "swerebench/sweb.eval.x86_64.ncas-cms_1776_cf-python-284:latest", "base_commit": "6475a87cb462763722ce1143b704392e040d58b7", "num_bugs": 1, "bugs": [{"instance_id": "NCAS-CMS__cf-python-284", "base_commit": "6475a87cb462763722ce1143b704392e040d58b7", "gold_patch": "diff --git a/Changelog.rst b/Changelog.rst\nindex 807c8ffd0..0ef1437a7 100644\n--- a/Changelog.rst\n+++ b/Changelog.rst\n@@ -1,3 +1,13 @@\n+version NEXT\n+------------\n+\n+**????-??-??**\n+\n+* Fix `cf.aggregate` failures when using the ``dimension`` keyword\n+ parameter (https://github.com/NCAS-CMS/cf-python/issues/283)\n+\n+----\n+\n version 3.11.0\n --------------\n \ndiff --git a/cf/aggregate.py b/cf/aggregate.py\nindex 1a3bcd712..39d3a2c10 100644\n--- a/cf/aggregate.py\n+++ b/cf/aggregate.py\n@@ -138,6 +138,7 @@ class _Meta:\n relaxed_identities=False,\n ncvar_identities=False,\n field_identity=None,\n+ copy=True,\n ):\n \"\"\"**initialization**\n \n@@ -163,7 +164,8 @@ class _Meta:\n dimension: (sequence of) `str`, optional\n See the `aggregate` function for details.\n \n- **Examples:**\n+ copy: `bool` optional\n+ See the `aggregate` function for details.\n \n \"\"\"\n self._bool = False\n@@ -245,6 +247,7 @@ class _Meta:\n # Promote selected properties to 1-d, size 1 auxiliary\n # coordinates\n # ------------------------------------------------------------\n+ _copy = copy\n for prop in dimension:\n value = f.get_property(prop, None)\n if value is None:\n@@ -258,10 +261,19 @@ class _Meta:\n aux_coord.nc_set_variable(prop)\n aux_coord.id = prop\n \n+ if _copy:\n+ # Copy the field, as we're about to change it.\n+ f = f.copy()\n+ self.field = f\n+ _copy = False\n+\n axis = f.set_construct(DomainAxis(1))\n f.set_construct(aux_coord, axes=[axis], copy=False)\n \n- f.del_property(prop) # dch COPY issue?\n+ f.del_property(prop)\n+\n+ if dimension:\n+ construct_axes = f.constructs.data_axes()\n \n self.units = self.canonical_units(\n f, self.identity, relaxed_units=relaxed_units\n@@ -1725,6 +1737,7 @@ def aggregate(\n ncvar_identities=ncvar_identities,\n field_identity=field_identity,\n respect_valid=respect_valid,\n+ copy=copy,\n )\n \n if not meta:\n", "test_patch": "diff --git a/cf/test/test_aggregate.py b/cf/test/test_aggregate.py\nindex 7ce83601d..2679eb97a 100644\n--- a/cf/test/test_aggregate.py\n+++ b/cf/test/test_aggregate.py\n@@ -255,6 +255,22 @@ class aggregateTest(unittest.TestCase):\n \n self.assertEqual(len(x), 1, x)\n \n+ def test_aggregate_dimension(self):\n+ \"\"\"Test the promotion of property to axis.\"\"\"\n+ f = cf.example_field(0)\n+ g = f.copy()\n+\n+ f.set_property(\"sim\", \"r1i1p1f1\")\n+ g.set_property(\"sim\", \"r2i1p1f1\")\n+\n+ self.assertFalse(len(f.auxiliary_coordinates()))\n+\n+ a = cf.aggregate([f, g], dimension=\"sim\")\n+ self.assertEqual(len(a), 1)\n+\n+ a = a[0]\n+ self.assertEqual(len(a.auxiliary_coordinates()), 1)\n+\n \n if __name__ == \"__main__\":\n print(\"Run date:\", datetime.datetime.now())\n", "FAIL_TO_PASS": ["cf/test/test_aggregate.py::aggregateTest::test_aggregate_dimension"]}], "all_FAIL_TO_PASS": ["cf/test/test_aggregate.py::aggregateTest::test_aggregate_dimension"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "RPing__influx-prompt-17_x1", "level": 1, "source": "swerebench", "repo": "RPing/influx-prompt", "image": "swerebench/sweb.eval.x86_64.rping_1776_influx-prompt-17:latest", "base_commit": "4650137ccfaf665816622a332574bd192ce8147c", "num_bugs": 1, "bugs": [{"instance_id": "RPing__influx-prompt-17", "base_commit": "4650137ccfaf665816622a332574bd192ce8147c", "gold_patch": "diff --git a/influx_prompt/main.py b/influx_prompt/main.py\nindex 302b02b..4e95b6f 100644\n--- a/influx_prompt/main.py\n+++ b/influx_prompt/main.py\n@@ -34,17 +34,17 @@ class InfluxPrompt(object):\n ('blue', 'o'),\n ('indigo', 'm'),\n ('purple', 'e'),\n- ('', '!')\n+ ('', '! ')\n ]), end='')\n print_formatted_text(FormattedText([\n- ('', 'Any issue please post to '),\n+ ('', 'Open an issue here: '),\n ('ansibrightgreen', 'https://github.com/RPing/influx-prompt/issues'),\n ]))\n if self.args['database'] is None:\n print_formatted_text(FormattedText([\n ('ansibrightyellow', '[Warning] '),\n ]), end='')\n- print('You havn\\'t set database. '\n+ print('You haven\\'t set database. '\n 'use \"use \" to specify database.')\n \n session = PromptSession(\ndiff --git a/influx_prompt/tabular.py b/influx_prompt/tabular.py\nindex 149f2fc..aadfcd9 100644\n--- a/influx_prompt/tabular.py\n+++ b/influx_prompt/tabular.py\n@@ -20,9 +20,9 @@ def json_to_tabular_result(j):\n series_list = rr.series.r(default=None)\n \n for series in series_list:\n- name = series['name']\n- columns = series['columns']\n- values = series['values']\n+ name = series.get('name')\n+ columns = series.get('columns')\n+ values = series.get('values', [])\n \n column_amount = len(columns)\n longest_value_len = [0] * column_amount\n", "test_patch": "diff --git a/tests/test_tabular.py b/tests/test_tabular.py\nindex 74445c8..57d4bae 100644\n--- a/tests/test_tabular.py\n+++ b/tests/test_tabular.py\n@@ -16,6 +16,41 @@ def test_error_in_json():\n ]\n \n \n+def test_no_value_key():\n+ j = {\n+ 'results': [{\n+ 'statement_id': 0,\n+ 'series': [\n+ {'name': '_internal', 'columns': ['name', 'query']},\n+ {'name': 'NOAA_water_database', 'columns': ['name', 'query']},\n+ ]\n+ }]\n+ }\n+ result = json_to_tabular_result(j)\n+ assert result == [\n+ ('', 'name: '),\n+ ('ansibrightgreen', '_internal'),\n+ ('', '\\n'),\n+ ('orange', 'name '),\n+ ('orange', 'query '),\n+ ('', '\\n'),\n+ ('orange', '--- '),\n+ ('orange', '--- '),\n+ ('', '\\n'),\n+ ('', '\\n'),\n+ ('', 'name: '),\n+ ('ansibrightgreen', 'NOAA_water_database'),\n+ ('', '\\n'),\n+ ('orange', 'name '),\n+ ('orange', 'query '),\n+ ('', '\\n'),\n+ ('orange', '--- '),\n+ ('orange', '--- '),\n+ ('', '\\n'),\n+ ('', '\\n'),\n+ ]\n+\n+\n def test_ordinary_json():\n j = {\n 'results': [{\n", "FAIL_TO_PASS": ["tests/test_tabular.py::test_no_value_key"]}], "all_FAIL_TO_PASS": ["tests/test_tabular.py::test_no_value_key"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "IMMM-SFA__population_gravity-19_x1", "level": 1, "source": "swerebench", "repo": "IMMM-SFA/population_gravity", "image": "swerebench/sweb.eval.x86_64.immm-sfa_1776_population_gravity-19:latest", "base_commit": "b9ecb72688ad72394ef8c7e604758c10a2de7d28", "num_bugs": 1, "bugs": [{"instance_id": "IMMM-SFA__population_gravity-19", "base_commit": "b9ecb72688ad72394ef8c7e604758c10a2de7d28", "gold_patch": "diff --git a/README.md b/README.md\nindex e9c3adf..f489290 100755\n--- a/README.md\n+++ b/README.md\n@@ -63,6 +63,7 @@ See examples below for how to pass into the `Model` class\n | `calibration_urban_year_two_raster` | string | Only used for running calibration. Full path with file name and extension to a raster containing urban population counts for each 1 km grid cell for year two of the calibration. |\n | `calibration_rural_year_one_raster` | string | Only used for running calibration. Full path with file name and extension to a raster containing rural population counts for each 1 km grid cell for year one of the calibration. |\n | `calibration_rural_year_two_raster` | string | Only used for running calibration. Full path with file name and extension to a raster containing rural population counts for each 1 km grid cell for year two of the calibration. |\n+| `kernel_distance_meters` | float | Distance kernel in meters; default 100,000 meters. |\n \n ### Variable arguments\n Users can update variable argument values after model initialization; this includes updating values between time steps (see **Example 3**). The following are variable arguments:\n@@ -72,6 +73,7 @@ Users can update variable argument values after model initialization; this inclu\n - `beta_rural`\n - `urban_pop_proj_n`\n - `rural_pop_proj_n`\n+- `kernel_distance_meters`\n \n ### YAML configuration file option (e.g., config.yml)\n Arguments can be passed into the `Model` class using a YAML configuration file as well (see **Example 1**):\n@@ -89,6 +91,7 @@ alpha_urban: 2.0\n alpha_rural: 0.08\n beta_urban: 1.78\n beta_rural: 1.42\n+kernel_distance_meters: 100000\n scenario: 'SSP2'\n state_name: 'vermont'\n historic_base_year: 2010\n@@ -137,6 +140,7 @@ run = Model(grid_coordinates_file='>> stats.set('example_metric.set', \"value_1\", tags=['environement:dev'])\n+ \"\"\"\n+ if not self._disabled:\n+ self._metric_aggregator.add_point(metric_name, tags, timestamp or time(), value, Set,\n+ sample_rate=sample_rate, host=host)\n+\n def increment(self, metric_name, value=1, timestamp=None, tags=None, sample_rate=1, host=None):\n \"\"\"\n Increment the counter by the given ``value``. Optionally, specify a list of\n@@ -285,13 +298,16 @@ class ThreadStats(object):\n finally:\n stats.histogram('user.query.time', time.time() - start)\n \"\"\"\n+\n def wrapper(func):\n @wraps(func)\n def wrapped(*args, **kwargs):\n with self.timer(metric_name, sample_rate, tags, host):\n result = func(*args, **kwargs)\n return result\n+\n return wrapped\n+\n return wrapper\n \n def flush(self, timestamp=None):\ndiff --git a/datadog/threadstats/metrics.py b/datadog/threadstats/metrics.py\nindex 00ff71e..fe3a0b7 100644\n--- a/datadog/threadstats/metrics.py\n+++ b/datadog/threadstats/metrics.py\n@@ -28,6 +28,25 @@ class Metric(object):\n raise NotImplementedError()\n \n \n+class Set(Metric):\n+ \"\"\" A set metric. \"\"\"\n+\n+ stats_tag = 'g'\n+\n+ def __init__(self, name, tags, host):\n+ self.name = name\n+ self.tags = tags\n+ self.host = host\n+ self.set = set()\n+\n+ def add_point(self, value):\n+ self.set.add(value)\n+\n+ def flush(self, timestamp, interval):\n+ return [(timestamp, len(self.set), self.name, self.tags,\n+ self.host, MetricType.Gauge, interval)]\n+\n+\n class Gauge(Metric):\n \"\"\" A gauge metric. \"\"\"\n \n", "test_patch": "diff --git a/tests/unit/threadstats/test_threadstats.py b/tests/unit/threadstats/test_threadstats.py\nindex 918a3b2..40c74a4 100644\n--- a/tests/unit/threadstats/test_threadstats.py\n+++ b/tests/unit/threadstats/test_threadstats.py\n@@ -25,10 +25,6 @@ logger = logging.getLogger('dd.datadogpy')\n logger.setLevel(logging.ERROR)\n \n \n-def assert_equal(a, b):\n- assert a == b\n-\n-\n class MemoryReporter(object):\n \"\"\"\n A reporting class that reports to memory for testing.\n@@ -127,21 +123,21 @@ class TestUnitThreadStats(unittest.TestCase):\n \"\"\"docstring\"\"\"\n return (a, b, c, d)\n \n- assert_equal(func.__name__, 'func')\n- assert_equal(func.__doc__, 'docstring')\n+ assert func.__name__ == 'func'\n+ assert func.__doc__ == 'docstring'\n \n result = func(1, 2, d=3)\n # Assert it handles args and kwargs correctly.\n- assert_equal(result, (1, 2, 1, 3))\n+ assert result == (1, 2, 1, 3)\n time.sleep(1) # Argh. I hate this.\n dog.flush()\n metrics = self.sort_metrics(reporter.metrics)\n- assert_equal(len(metrics), 8)\n+ assert len(metrics) == 8\n (_, _, _, _, avg, count, max_, min_) = metrics\n- assert_equal(avg['metric'], 'timed.test.avg')\n- assert_equal(count['metric'], 'timed.test.count')\n- assert_equal(max_['metric'], 'timed.test.max')\n- assert_equal(min_['metric'], 'timed.test.min')\n+ assert avg['metric'] == 'timed.test.avg'\n+ assert count['metric'] == 'timed.test.count'\n+ assert max_['metric'] == 'timed.test.max'\n+ assert min_['metric'] == 'timed.test.min'\n \n def test_event(self):\n dog = ThreadStats()\n@@ -159,10 +155,10 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event1, event2 = reporter.events\n- assert_equal(event1['title'], event1_title)\n- assert_equal(event1['text'], event1_text)\n- assert_equal(event2['title'], event2_title)\n- assert_equal(event2['text'], event2_text)\n+ assert event1['title'] == event1_title\n+ assert event1['text'] == event1_text\n+ assert event2['title'] == event2_title\n+ assert event2['text'] == event2_text\n \n # Test more parameters\n reporter.events = []\n@@ -175,11 +171,11 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event, = reporter.events\n- assert_equal(event['title'], event1_title)\n- assert_equal(event['text'], event1_text)\n- assert_equal(event['priority'], event1_priority)\n- assert_equal(event['date_happened'], event1_date_happened)\n- assert_equal(event['tags'], [event1_tag])\n+ assert event['title'] == event1_title\n+ assert event['text'] == event1_text\n+ assert event['priority'] == event1_priority\n+ assert event['date_happened'] == event1_date_happened\n+ assert event['tags'] == [event1_tag]\n \n def test_event_constant_tags(self):\n constant_tag = 'type:constant'\n@@ -198,13 +194,13 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event1, event2 = reporter.events\n- assert_equal(event1['title'], event1_title)\n- assert_equal(event1['text'], event1_text)\n- assert_equal(event1['tags'], [constant_tag])\n- assert_equal(event2['title'], event2_title)\n- assert_equal(event2['text'], event2_text)\n- assert_equal(event2['text'], event2_text)\n- assert_equal(event2['tags'], [constant_tag])\n+ assert event1['title'] == event1_title\n+ assert event1['text'] == event1_text\n+ assert event1['tags'] == [constant_tag]\n+ assert event2['title'] == event2_title\n+ assert event2['text'] == event2_text\n+ assert event2['text'] == event2_text\n+ assert event2['tags'] == [constant_tag]\n \n # Test more parameters\n reporter.events = []\n@@ -217,11 +213,11 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event, = reporter.events\n- assert_equal(event['title'], event1_title)\n- assert_equal(event['text'], event1_text)\n- assert_equal(event['priority'], event1_priority)\n- assert_equal(event['date_happened'], event1_date_happened)\n- assert_equal(event['tags'], [event1_tag, constant_tag])\n+ assert event['title'] == event1_title\n+ assert event['text'] == event1_text\n+ assert event['priority'] == event1_priority\n+ assert event['date_happened'] == event1_date_happened\n+ assert event['tags'] == [event1_tag, constant_tag]\n \n def test_histogram(self):\n dog = ThreadStats()\n@@ -245,55 +241,55 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and ensure they roll up properly.\n dog.flush(120.0)\n metrics = self.sort_metrics(reporter.metrics)\n- assert_equal(len(metrics), 24)\n+ assert len(metrics) == 24\n \n # Test histograms elsewhere.\n (h1751, h1851, h1951, h1991, h1avg1, h1cnt1, h1max1, h1min1,\n _, _, _, _, h2avg1, h2cnt1, h2max1, h2min1,\n h1752, _, _, h1992, h1avg2, h1cnt2, h1max2, h1min2) = metrics\n \n- assert_equal(h1avg1['metric'], 'histogram.1.avg')\n- assert_equal(h1avg1['points'][0][0], 100.0)\n- assert_equal(h1avg1['points'][0][1], 35)\n- assert_equal(h1cnt1['metric'], 'histogram.1.count')\n- assert_equal(h1cnt1['points'][0][0], 100.0)\n- assert_equal(h1cnt1['points'][0][1], 0.4)\n- assert_equal(h1min1['metric'], 'histogram.1.min')\n- assert_equal(h1min1['points'][0][1], 20)\n- assert_equal(h1max1['metric'], 'histogram.1.max')\n- assert_equal(h1max1['points'][0][1], 50)\n- assert_equal(h1751['metric'], 'histogram.1.75percentile')\n- assert_equal(h1751['points'][0][1], 40)\n- assert_equal(h1991['metric'], 'histogram.1.99percentile')\n- assert_equal(h1991['points'][0][1], 50)\n-\n- assert_equal(h1avg2['metric'], 'histogram.1.avg')\n- assert_equal(h1avg2['points'][0][0], 110.0)\n- assert_equal(h1avg2['points'][0][1], 40)\n- assert_equal(h1cnt2['metric'], 'histogram.1.count')\n- assert_equal(h1cnt2['points'][0][0], 110.0)\n- assert_equal(h1cnt2['points'][0][1], 0.3)\n- assert_equal(h1752['metric'], 'histogram.1.75percentile')\n- assert_equal(h1752['points'][0][0], 110.0)\n- assert_equal(h1752['points'][0][1], 40.0)\n- assert_equal(h1992['metric'], 'histogram.1.99percentile')\n- assert_equal(h1992['points'][0][0], 110.0)\n- assert_equal(h1992['points'][0][1], 50.0)\n-\n- assert_equal(h2avg1['metric'], 'histogram.2.avg')\n- assert_equal(h2avg1['points'][0][0], 100.0)\n- assert_equal(h2avg1['points'][0][1], 40)\n- assert_equal(h2cnt1['metric'], 'histogram.2.count')\n- assert_equal(h2cnt1['points'][0][0], 100.0)\n- assert_equal(h2cnt1['points'][0][1], 0.1)\n+ assert h1avg1['metric'] == 'histogram.1.avg'\n+ assert h1avg1['points'][0][0] == 100.0\n+ assert h1avg1['points'][0][1] == 35\n+ assert h1cnt1['metric'] == 'histogram.1.count'\n+ assert h1cnt1['points'][0][0] == 100.0\n+ assert h1cnt1['points'][0][1] == 0.4\n+ assert h1min1['metric'] == 'histogram.1.min'\n+ assert h1min1['points'][0][1] == 20\n+ assert h1max1['metric'] == 'histogram.1.max'\n+ assert h1max1['points'][0][1] == 50\n+ assert h1751['metric'] == 'histogram.1.75percentile'\n+ assert h1751['points'][0][1] == 40\n+ assert h1991['metric'] == 'histogram.1.99percentile'\n+ assert h1991['points'][0][1] == 50\n+\n+ assert h1avg2['metric'] == 'histogram.1.avg'\n+ assert h1avg2['points'][0][0] == 110.0\n+ assert h1avg2['points'][0][1] == 40\n+ assert h1cnt2['metric'] == 'histogram.1.count'\n+ assert h1cnt2['points'][0][0] == 110.0\n+ assert h1cnt2['points'][0][1] == 0.3\n+ assert h1752['metric'] == 'histogram.1.75percentile'\n+ assert h1752['points'][0][0] == 110.0\n+ assert h1752['points'][0][1] == 40.0\n+ assert h1992['metric'] == 'histogram.1.99percentile'\n+ assert h1992['points'][0][0] == 110.0\n+ assert h1992['points'][0][1] == 50.0\n+\n+ assert h2avg1['metric'] == 'histogram.2.avg'\n+ assert h2avg1['points'][0][0] == 100.0\n+ assert h2avg1['points'][0][1] == 40\n+ assert h2cnt1['metric'] == 'histogram.2.count'\n+ assert h2cnt1['points'][0][0] == 100.0\n+ assert h2cnt1['points'][0][1] == 0.1\n \n # Flush again ensure they're gone.\n dog.reporter.metrics = []\n dog.flush(140.0)\n- assert_equal(len(dog.reporter.metrics), 8)\n+ assert len(dog.reporter.metrics) == 8\n dog.reporter.metrics = []\n dog.flush(200.0)\n- assert_equal(len(dog.reporter.metrics), 0)\n+ assert len(dog.reporter.metrics) == 0\n \n def test_histogram_percentiles(self):\n dog = ThreadStats()\n@@ -312,10 +308,10 @@ class TestUnitThreadStats(unittest.TestCase):\n def assert_almost_equal(i, j, e=1):\n # Floating point math?\n assert abs(i - j) <= e, \"%s %s %s\" % (i, j, e)\n- assert_equal(len(metrics), 8)\n+ assert len(metrics) == 8\n p75, p85, p95, p99, _, _, _, _ = self.sort_metrics(metrics)\n- assert_equal(p75['metric'], 'percentiles.75percentile')\n- assert_equal(p75['points'][0][0], 1000.0)\n+ assert p75['metric'] == 'percentiles.75percentile'\n+ assert p75['points'][0][0] == 1000.0\n assert_almost_equal(p75['points'][0][1], 75, 8)\n assert_almost_equal(p85['points'][0][1], 85, 8)\n assert_almost_equal(p95['points'][0][1], 95, 8)\n@@ -335,23 +331,61 @@ class TestUnitThreadStats(unittest.TestCase):\n \n # Assert they've been properly flushed.\n metrics = self.sort_metrics(reporter.metrics)\n- assert_equal(len(metrics), 2)\n+ assert len(metrics) == 2\n \n (first, second) = metrics\n- assert_equal(first['metric'], 'test.gauge.1')\n- assert_equal(first['points'][0][0], 100.0)\n- assert_equal(first['points'][0][1], 22)\n- assert_equal(second['metric'], 'test.gauge.2')\n+ assert first['metric'] == 'test.gauge.1'\n+ assert first['points'][0][0] == 100.0\n+ assert first['points'][0][1] == 22\n+ assert second['metric'] == 'test.gauge.2'\n \n # Flush again and make sure we're progressing.\n reporter.metrics = []\n dog.flush(130.0)\n- assert_equal(len(reporter.metrics), 1)\n+ assert len(reporter.metrics) == 1\n+\n+ # Finally, make sure we've flushed all metrics.\n+ reporter.metrics = []\n+ dog.flush(150.0)\n+ assert len(reporter.metrics) == 0\n+\n+ def test_set(self):\n+ # Create some fake metrics.\n+ dog = ThreadStats()\n+ dog.start(roll_up_interval=10, flush_in_thread=False)\n+ reporter = dog.reporter = MemoryReporter()\n+\n+ dog.set('test.set.1', \"a string\", 100.0)\n+ dog.set('test.set.1', frozenset(), 105.0)\n+ dog.set('test.set.2', 30, 115.0)\n+ dog.set('test.set.3', 30, 125.0)\n+ dog.flush(120.0)\n+\n+ # Assert they've been properly flushed.\n+ metrics = self.sort_metrics(reporter.metrics)\n+ assert len(metrics) == 2\n+\n+ (first, second) = metrics\n+ assert first['metric'] == 'test.set.1'\n+ assert first['points'][0][0] == 100.0\n+ assert first['points'][0][1] == 2\n+ assert second['metric'] == 'test.set.2'\n+ assert second['points'][0][0] == 110.0\n+ assert second['points'][0][1] == 1\n+\n+ # Flush again and make sure we're progressing.\n+ reporter.metrics = []\n+ dog.flush(130.0)\n+ metrics = self.sort_metrics(reporter.metrics)\n+ assert len(metrics) == 1\n+ assert metrics[0]['metric'] == 'test.set.3'\n+ assert metrics[0]['points'][0][0] == 120.0\n+ assert metrics[0]['points'][0][1] == 1\n \n # Finally, make sure we've flushed all metrics.\n reporter.metrics = []\n dog.flush(150.0)\n- assert_equal(len(reporter.metrics), 0)\n+ assert len(reporter.metrics) == 0\n \n def test_counter(self):\n # Create some fake metrics.\n@@ -367,12 +401,12 @@ class TestUnitThreadStats(unittest.TestCase):\n \n # Assert they've been properly flushed.\n metrics = self.sort_metrics(reporter.metrics)\n- assert_equal(len(metrics), 2)\n+ assert len(metrics) == 2\n (first, second) = metrics\n- assert_equal(first['metric'], 'test.counter.1')\n- assert_equal(first['points'][0][0], 1000.0)\n- assert_equal(first['points'][0][1], 0.3)\n- assert_equal(second['metric'], 'test.counter.2')\n+ assert first['metric'] == 'test.counter.1'\n+ assert first['points'][0][0] == 1000.0\n+ assert first['points'][0][1] == 0.3\n+ assert second['metric'] == 'test.counter.2'\n \n # Test decrement\n dog.increment('test.counter.1', value=10, timestamp=1000.0)\n@@ -381,22 +415,22 @@ class TestUnitThreadStats(unittest.TestCase):\n dog.flush(1021.0)\n \n metrics = self.sort_metrics(reporter.metrics)\n- assert_equal(len(metrics), 1)\n+ assert len(metrics) == 1\n first, = metrics\n- assert_equal(first['metric'], 'test.counter.1')\n- assert_equal(first['points'][0][0], 1000.0)\n- assert_equal(first['points'][0][1], 0.8)\n- assert_equal(second['metric'], 'test.counter.2')\n+ assert first['metric'] == 'test.counter.1'\n+ assert first['points'][0][0] == 1000.0\n+ assert first['points'][0][1] == 0.8\n+ assert second['metric'] == 'test.counter.2'\n \n # Flush again and make sure we're progressing.\n reporter.metrics = []\n dog.flush(1030.0)\n- assert_equal(len(reporter.metrics), 1)\n+ assert len(reporter.metrics) == 1\n \n # Finally, make sure we've flushed all metrics.\n reporter.metrics = []\n dog.flush(1050.0)\n- assert_equal(len(reporter.metrics), 0)\n+ assert len(reporter.metrics) == 0\n \n def test_distribution(self):\n # Create some fake metrics.\n@@ -412,23 +446,23 @@ class TestUnitThreadStats(unittest.TestCase):\n \n # Assert they've been properly flushed.\n dists = self.sort_metrics(reporter.distributions)\n- assert_equal(len(dists), 2)\n+ assert len(dists) == 2\n \n (first, second) = dists\n- assert_equal(first['metric'], 'test.dist.1')\n- assert_equal(first['points'][0][0], 100.0)\n- assert_equal(first['points'][0][1], [20, 22])\n- assert_equal(second['metric'], 'test.dist.2')\n+ assert first['metric'] == 'test.dist.1'\n+ assert first['points'][0][0] == 100.0\n+ assert first['points'][0][1] == [20, 22]\n+ assert second['metric'] == 'test.dist.2'\n \n # Flush again and make sure we're progressing.\n reporter.distributions = []\n dog.flush(130.0)\n- assert_equal(len(reporter.distributions), 1)\n+ assert len(reporter.distributions) == 1\n \n # Finally, make sure we've flushed all metrics.\n reporter.distributions = []\n dog.flush(150.0)\n- assert_equal(len(reporter.distributions), 0)\n+ assert len(reporter.distributions) == 0\n \n def test_default_host_and_device(self):\n dog = ThreadStats()\n@@ -447,8 +481,8 @@ class TestUnitThreadStats(unittest.TestCase):\n dog.gauge('my.gauge', 1, 100.0, host='host')\n dog.flush(1000)\n metric = reporter.metrics[0]\n- assert_equal(metric['device'], 'dev')\n- assert_equal(metric['host'], 'host')\n+ assert metric['device'] == 'dev'\n+ assert metric['host'] == 'host'\n \n def test_tags(self):\n dog = ThreadStats()\n@@ -467,24 +501,28 @@ class TestUnitThreadStats(unittest.TestCase):\n dog.flush(200.0)\n \n metrics = self.sort_metrics(reporter.metrics)\n- assert_equal(len(metrics), 6)\n+ assert len(metrics) == 6\n \n [c1, c2, c3, g1, g2, g3] = metrics\n- (assert_equal(c['metric'], 'counter') for c in [c1, c2, c3])\n- assert_equal(c1['tags'], None)\n- assert_equal(c1['points'][0][1], 0.1)\n- assert_equal(c2['tags'], ['env:production', 'db'])\n- assert_equal(c2['points'][0][1], 0.1)\n- assert_equal(c3['tags'], ['env:staging'])\n- assert_equal(c3['points'][0][1], 0.1)\n-\n- (assert_equal(c['metric'], 'gauge') for c in [g1, g2, g3])\n- assert_equal(g1['tags'], None)\n- assert_equal(g1['points'][0][1], 10)\n- assert_equal(g2['tags'], ['env:production', 'db'])\n- assert_equal(g2['points'][0][1], 15)\n- assert_equal(g3['tags'], ['env:staging'])\n- assert_equal(g3['points'][0][1], 20)\n+ assert c1['metric'] == 'counter'\n+ assert c2['metric'] == 'counter'\n+ assert c3['metric'] == 'counter'\n+ assert c1['tags'] is None\n+ assert c1['points'][0][1] == 0.1\n+ assert c2['tags'] == ['env:production', 'db']\n+ assert c2['points'][0][1] == 0.1\n+ assert c3['tags'] == ['env:staging']\n+ assert c3['points'][0][1] == 0.1\n+\n+ assert g1['metric'] == 'gauge'\n+ assert g2['metric'] == 'gauge'\n+ assert g3['metric'] == 'gauge'\n+ assert g1['tags'] is None\n+ assert g1['points'][0][1] == 10\n+ assert g2['tags'] == ['env:production', 'db']\n+ assert g2['points'][0][1] == 15\n+ assert g3['tags'] == ['env:staging']\n+ assert g3['points'][0][1] == 20\n \n def test_constant_tags(self):\n \"\"\"\n@@ -579,27 +617,31 @@ class TestUnitThreadStats(unittest.TestCase):\n dog.flush(200.0)\n \n metrics = self.sort_metrics(reporter.metrics)\n- assert_equal(len(metrics), 6)\n+ assert len(metrics) == 6\n \n [c1, c2, c3, g1, g2, g3] = metrics\n- (assert_equal(c['metric'], 'counter') for c in [c1, c2, c3])\n- assert_equal(c1['host'], None)\n- assert_equal(c1['tags'], None)\n- assert_equal(c1['points'][0][1], 0.2)\n- assert_equal(c2['host'], 'test')\n- assert_equal(c2['tags'], None)\n- assert_equal(c2['points'][0][1], 0.1)\n- assert_equal(c3['host'], 'test')\n- assert_equal(c3['tags'], ['tag'])\n- assert_equal(c3['points'][0][1], 0.2)\n-\n- (assert_equal(g['metric'], 'gauge') for g in [g1, g2, g3])\n- assert_equal(g1['host'], None)\n- assert_equal(g1['points'][0][1], 10)\n- assert_equal(g2['host'], '')\n- assert_equal(g2['points'][0][1], 12)\n- assert_equal(g3['host'], 'test')\n- assert_equal(g3['points'][0][1], 15)\n+ assert c1['metric'] == 'counter'\n+ assert c2['metric'] == 'counter'\n+ assert c3['metric'] == 'counter'\n+ assert c1['host'] is None\n+ assert c1['tags'] is None\n+ assert c1['points'][0][1] == 0.2\n+ assert c2['host'] == 'test'\n+ assert c2['tags'] is None\n+ assert c2['points'][0][1] == 0.1\n+ assert c3['host'] == 'test'\n+ assert c3['tags'] == ['tag']\n+ assert c3['points'][0][1] == 0.2\n+\n+ assert g1['metric'] == 'gauge'\n+ assert g2['metric'] == 'gauge'\n+ assert g3['metric'] == 'gauge'\n+ assert g1['host'] is None\n+ assert g1['points'][0][1] == 10\n+ assert g2['host'] == ''\n+ assert g2['points'][0][1] == 12\n+ assert g3['host'] == 'test'\n+ assert g3['points'][0][1] == 15\n \n # Ensure histograms work as well.\n @dog.timed('timed', host='test')\n@@ -658,13 +700,13 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event1, event2 = reporter.events\n- assert_equal(event1['title'], event1_title)\n- assert_equal(event1['text'], event1_text)\n- assert_equal(event1['tags'], test_tags)\n- assert_equal(event2['title'], event2_title)\n- assert_equal(event2['text'], event2_text)\n- assert_equal(event2['text'], event2_text)\n- assert_equal(event2['tags'], test_tags)\n+ assert event1['title'] == event1_title\n+ assert event1['text'] == event1_text\n+ assert event1['tags'] == test_tags\n+ assert event2['title'] == event2_title\n+ assert event2['text'] == event2_text\n+ assert event2['text'] == event2_text\n+ assert event2['tags'] == test_tags\n \n # Test more parameters\n reporter.events = []\n@@ -677,11 +719,11 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event, = reporter.events\n- assert_equal(event['title'], event1_title)\n- assert_equal(event['text'], event1_text)\n- assert_equal(event['priority'], event1_priority)\n- assert_equal(event['date_happened'], event1_date_happened)\n- assert_equal(event['tags'], [event1_tag] + test_tags)\n+ assert event['title'] == event1_title\n+ assert event['text'] == event1_text\n+ assert event['priority'] == event1_priority\n+ assert event['date_happened'] == event1_date_happened\n+ assert event['tags'] == [event1_tag] + test_tags\n dog.start(flush_interval=1, roll_up_interval=1)\n \n def test_tags_from_environment_and_constant(self):\n@@ -704,13 +746,13 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event1, event2 = reporter.events\n- assert_equal(event1['title'], event1_title)\n- assert_equal(event1['text'], event1_text)\n- assert_equal(event1['tags'], constant_tags + test_tags)\n- assert_equal(event2['title'], event2_title)\n- assert_equal(event2['text'], event2_text)\n- assert_equal(event2['text'], event2_text)\n- assert_equal(event2['tags'], constant_tags + test_tags)\n+ assert event1['title'] == event1_title\n+ assert event1['text'] == event1_text\n+ assert event1['tags'] == constant_tags + test_tags\n+ assert event2['title'] == event2_title\n+ assert event2['text'] == event2_text\n+ assert event2['text'] == event2_text\n+ assert event2['tags'] == constant_tags + test_tags\n \n # Test more parameters\n reporter.events = []\n@@ -723,11 +765,11 @@ class TestUnitThreadStats(unittest.TestCase):\n # Flush and test\n dog.flush()\n event, = reporter.events\n- assert_equal(event['title'], event1_title)\n- assert_equal(event['text'], event1_text)\n- assert_equal(event['priority'], event1_priority)\n- assert_equal(event['date_happened'], event1_date_happened)\n- assert_equal(event['tags'], [event1_tag] + constant_tags + test_tags)\n+ assert event['title'] == event1_title\n+ assert event['text'] == event1_text\n+ assert event['priority'] == event1_priority\n+ assert event['date_happened'] == event1_date_happened\n+ assert event['tags'] == [event1_tag] + constant_tags + test_tags\n dog.start(flush_interval=1, roll_up_interval=1)\n \n def test_metric_type(self):\n@@ -748,16 +790,16 @@ class TestUnitThreadStats(unittest.TestCase):\n (first, second, p75, p85, p95, p99, avg, cnt, max_, min_) = self.sort_metrics(reporter.metrics)\n \n # Assert Metric type\n- assert_equal(first['type'], 'rate')\n- assert_equal(second['type'], 'gauge')\n- assert_equal(p75['type'], 'gauge')\n- assert_equal(p85['type'], 'gauge')\n- assert_equal(p95['type'], 'gauge')\n- assert_equal(p99['type'], 'gauge')\n- assert_equal(avg['type'], 'gauge')\n- assert_equal(cnt['type'], 'rate')\n- assert_equal(max_['type'], 'gauge')\n- assert_equal(min_['type'], 'gauge')\n+ assert first['type'] == 'rate'\n+ assert second['type'] == 'gauge'\n+ assert p75['type'] == 'gauge'\n+ assert p85['type'] == 'gauge'\n+ assert p95['type'] == 'gauge'\n+ assert p99['type'] == 'gauge'\n+ assert avg['type'] == 'gauge'\n+ assert cnt['type'] == 'rate'\n+ assert max_['type'] == 'gauge'\n+ assert min_['type'] == 'gauge'\n \n # Test lambda_wrapper (uses ThreadStats under the hood)\n def test_basic_lambda_decorator(self):\n@@ -769,9 +811,9 @@ class TestUnitThreadStats(unittest.TestCase):\n _lambda_stats.reporter = self.reporter\n basic_wrapped_function()\n \n- assert_equal(_lambda_stats.reporter.dist_flush_counter, 1)\n+ assert _lambda_stats.reporter.dist_flush_counter == 1\n dists = self.sort_metrics(_lambda_stats.reporter.distributions)\n- assert_equal(len(dists), 1)\n+ assert len(dists) == 1\n \n def test_embedded_lambda_decorator(self):\n \"\"\"\n@@ -789,7 +831,7 @@ class TestUnitThreadStats(unittest.TestCase):\n \n _lambda_stats.reporter = self.reporter\n wrapped_function_2()\n- assert_equal(_lambda_stats.reporter.dist_flush_counter, 1)\n+ assert _lambda_stats.reporter.dist_flush_counter == 1\n \n dists = self.sort_metrics(_lambda_stats.reporter.distributions)\n- assert_equal(len(dists), 2)\n+ assert len(dists) == 2\n", "FAIL_TO_PASS": ["tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_set"]}], "all_FAIL_TO_PASS": ["tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_set"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "3YOURMIND__django-migration-linter-113_x1", "level": 1, "source": "swerebench", "repo": "3YOURMIND/django-migration-linter", "image": "swerebench/sweb.eval.x86_64.3yourmind_1776_django-migration-linter-113:latest", "base_commit": "799957a5564e8ca1ea20d7cf643abbc21db4e40f", "num_bugs": 1, "bugs": [{"instance_id": "3YOURMIND__django-migration-linter-113", "base_commit": "799957a5564e8ca1ea20d7cf643abbc21db4e40f", "gold_patch": "diff --git a/django_migration_linter/migration_linter.py b/django_migration_linter/migration_linter.py\nindex 31f8fea..c5ea333 100644\n--- a/django_migration_linter/migration_linter.py\n+++ b/django_migration_linter/migration_linter.py\n@@ -289,8 +289,13 @@ class MigrationLinter(object):\n \n @classmethod\n def read_migrations_list(cls, migrations_file_path):\n+ \"\"\"\n+ Returning an empty list is different from returning None here.\n+ None: no file was specified and we should consider all migrations\n+ Empty list: no migration found in the file and we should consider no migration\n+ \"\"\"\n if not migrations_file_path:\n- return []\n+ return None\n \n migrations = []\n try:\n@@ -300,7 +305,14 @@ class MigrationLinter(object):\n app_label, name = split_migration_path(line)\n migrations.append((app_label, name))\n except IOError:\n- logger.warning(\"Migrations list path not found %s\", migrations_file_path)\n+ logger.exception(\"Migrations list path not found %s\", migrations_file_path)\n+ raise Exception(\"Error while reading migrations list file\")\n+\n+ if not migrations:\n+ logger.info(\n+ \"No valid migration paths found in the migrations file %s\",\n+ migrations_file_path,\n+ )\n return migrations\n \n def _gather_migrations_git(self, git_commit_id, migrations_list=None):\n@@ -315,7 +327,7 @@ class MigrationLinter(object):\n # Only gather lines that include added migrations\n if self.is_migration_file(line):\n app_label, name = split_migration_path(line)\n- if not migrations_list or (app_label, name) in migrations_list:\n+ if migrations_list is None or (app_label, name) in migrations_list:\n migration = self.migration_loader.disk_migrations[app_label, name]\n migrations.append(migration)\n diff_process.wait()\n@@ -334,7 +346,7 @@ class MigrationLinter(object):\n migration,\n ) in self.migration_loader.disk_migrations.items():\n if app_label not in DJANGO_APPS_WITH_MIGRATIONS: # Prune Django apps\n- if not migrations_list or (app_label, name) in migrations_list:\n+ if migrations_list is None or (app_label, name) in migrations_list:\n yield migration\n \n def should_ignore_migration(self, app_label, migration_name, operations=()):\n", "test_patch": "diff --git a/tests/unit/test_linter.py b/tests/unit/test_linter.py\nindex 392a43c..d086fbe 100644\n--- a/tests/unit/test_linter.py\n+++ b/tests/unit/test_linter.py\n@@ -88,8 +88,12 @@ class LinterFunctionsTestCase(unittest.TestCase):\n \n def test_read_migrations_unknown_file(self):\n file_path = \"unknown_file\"\n- migration_list = MigrationLinter.read_migrations_list(file_path)\n- self.assertEqual([], migration_list)\n+ with self.assertRaises(Exception):\n+ MigrationLinter.read_migrations_list(file_path)\n+\n+ def test_read_migrations_no_file(self):\n+ migration_list = MigrationLinter.read_migrations_list(None)\n+ self.assertIsNone(migration_list)\n \n def test_read_migrations_empty_file(self):\n with tempfile.NamedTemporaryFile() as tmp:\n", "FAIL_TO_PASS": ["tests/unit/test_linter.py::LinterFunctionsTestCase::test_read_migrations_no_file", "tests/unit/test_linter.py::LinterFunctionsTestCase::test_read_migrations_unknown_file"]}], "all_FAIL_TO_PASS": ["tests/unit/test_linter.py::LinterFunctionsTestCase::test_read_migrations_no_file", "tests/unit/test_linter.py::LinterFunctionsTestCase::test_read_migrations_unknown_file"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "CSCfi__swift-browser-ui-20_x1", "level": 1, "source": "swerebench", "repo": "CSCfi/swift-browser-ui", "image": "swerebench/sweb.eval.x86_64.cscfi_1776_swift-browser-ui-20:latest", "base_commit": "316d76f77f93701289188d0d461d4fc30fdccf96", "num_bugs": 1, "bugs": [{"instance_id": "CSCfi__swift-browser-ui-20", "base_commit": "316d76f77f93701289188d0d461d4fc30fdccf96", "gold_patch": "diff --git a/swift_browser_ui/middlewares.py b/swift_browser_ui/middlewares.py\nindex 3a857ab8..3f08bf77 100644\n--- a/swift_browser_ui/middlewares.py\n+++ b/swift_browser_ui/middlewares.py\n@@ -5,41 +5,40 @@ from aiohttp import web\n from .settings import setd\n \n \n+def return_error_response(error_code):\n+ \"\"\"Return the correct error page with correct status code.\"\"\"\n+ with open(\n+ setd[\"static_directory\"] + \"/\" + str(error_code) + \".html\"\n+ ) as resp:\n+ return web.Response(\n+ body=\"\".join(resp.readlines()),\n+ status=error_code,\n+ content_type=\"text/html\",\n+ headers={\n+ \"Cache-Control\": \"no-cache, no-store, must-revalidate\",\n+ \"Pragma\": \"no-cache\",\n+ \"Expires\": \"0\"\n+ }\n+ )\n+\n+\n @web.middleware\n async def error_middleware(request, handler):\n \"\"\"Return the correct HTTP Error page.\"\"\"\n try:\n response = await handler(request)\n if response.status == 401:\n- return web.FileResponse(\n- setd[\"static_directory\"] + \"/401.html\",\n- status=401\n- )\n+ return return_error_response(401)\n if response.status == 403:\n- return web.FileResponse(\n- setd[\"static_directory\"] + \"/403.html\",\n- status=403\n- )\n+ return return_error_response(403)\n if response.status == 404:\n- return web.FileResponse(\n- setd[\"static_directory\"] + \"/404.html\",\n- status=404\n- )\n+ return return_error_response(404)\n return response\n except web.HTTPException as ex:\n if ex.status == 401:\n- return web.FileResponse(\n- setd[\"static_directory\"] + \"/401.html\",\n- status=401\n- )\n+ return return_error_response(401)\n if ex.status == 403:\n- return web.FileResponse(\n- setd[\"static_directory\"] + \"/403.html\",\n- status=403\n- )\n+ return return_error_response(403)\n if ex.status == 404:\n- return web.FileResponse(\n- setd[\"static_directory\"] + \"/404.html\",\n- status=404\n- )\n+ return return_error_response(404)\n raise\ndiff --git a/tox.ini b/tox.ini\nindex ab953fc3..d983294d 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -16,7 +16,7 @@ deps =\n pydocstyle==3.0.0\n flake8\n flake8-docstrings\n-commands = flake8 .\n+commands = flake8 swift_browser_ui tests ui_tests\n \n [testenv:docs]\n ; skip_install = true\n", "test_patch": "diff --git a/tests/test_middlewares.py b/tests/test_middlewares.py\nindex 84bad576..3c54417d 100644\n--- a/tests/test_middlewares.py\n+++ b/tests/test_middlewares.py\n@@ -52,37 +52,37 @@ class MiddlewareTestClass(asynctest.TestCase):\n \"\"\"Test 401 middleware when the 401 status is returned.\"\"\"\n resp = await error_middleware(None, return_401_handler)\n self.assertEqual(resp.status, 401)\n- self.assertIsInstance(resp, FileResponse)\n+ self.assertIsInstance(resp, Response)\n \n async def test_401_exception(self):\n \"\"\"Test 401 middleware when the 401 status is risen.\"\"\"\n resp = await error_middleware(True, return_401_handler)\n self.assertEqual(resp.status, 401)\n- self.assertIsInstance(resp, FileResponse)\n+ self.assertIsInstance(resp, Response)\n \n async def test_403_return(self):\n \"\"\"Test 403 middleware when the 403 status is returned.\"\"\"\n resp = await error_middleware(None, return_403_handler)\n self.assertEqual(resp.status, 403)\n- self.assertIsInstance(resp, FileResponse)\n+ self.assertIsInstance(resp, Response)\n \n async def test_403_exception(self):\n \"\"\"Test 403 middleware when the 403 status is risen.\"\"\"\n resp = await error_middleware(True, return_403_handler)\n self.assertEqual(resp.status, 403)\n- self.assertIsInstance(resp, FileResponse)\n+ self.assertIsInstance(resp, Response)\n \n async def test_404_return(self):\n \"\"\"Test 404 middleware when the 404 status is returned.\"\"\"\n resp = await error_middleware(None, return_404_handler)\n self.assertEqual(resp.status, 404)\n- self.assertIsInstance(resp, FileResponse)\n+ self.assertIsInstance(resp, Response)\n \n async def test_404_exception(self):\n \"\"\"Test 404 middlewrae when the 404 status is risen.\"\"\"\n resp = await error_middleware(True, return_404_handler)\n self.assertEqual(resp.status, 404)\n- self.assertIsInstance(resp, FileResponse)\n+ self.assertIsInstance(resp, Response)\n \n async def test_error_middleware_no_error(self):\n \"\"\"Test the general error middleware with correct status.\"\"\"\n", "FAIL_TO_PASS": ["tests/test_middlewares.py::MiddlewareTestClass::test_401_exception", "tests/test_middlewares.py::MiddlewareTestClass::test_401_return", "tests/test_middlewares.py::MiddlewareTestClass::test_403_exception", "tests/test_middlewares.py::MiddlewareTestClass::test_403_return", "tests/test_middlewares.py::MiddlewareTestClass::test_404_exception", "tests/test_middlewares.py::MiddlewareTestClass::test_404_return"]}], "all_FAIL_TO_PASS": ["tests/test_middlewares.py::MiddlewareTestClass::test_401_exception", "tests/test_middlewares.py::MiddlewareTestClass::test_401_return", "tests/test_middlewares.py::MiddlewareTestClass::test_403_exception", "tests/test_middlewares.py::MiddlewareTestClass::test_403_return", "tests/test_middlewares.py::MiddlewareTestClass::test_404_exception", "tests/test_middlewares.py::MiddlewareTestClass::test_404_return"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ClimateImpactLab__impactlab-tools-450_x1", "level": 1, "source": "swerebench", "repo": "ClimateImpactLab/impactlab-tools", "image": "swerebench/sweb.eval.x86_64.climateimpactlab_1776_impactlab-tools-450:latest", "base_commit": "a56fa03cfe65515c324bfebda79e7906e20ac87d", "num_bugs": 1, "bugs": [{"instance_id": "ClimateImpactLab__impactlab-tools-450", "base_commit": "a56fa03cfe65515c324bfebda79e7906e20ac87d", "gold_patch": "diff --git a/impactlab_tools/utils/configdict.py b/impactlab_tools/utils/configdict.py\nindex cb9e5ec..135dfde 100644\n--- a/impactlab_tools/utils/configdict.py\n+++ b/impactlab_tools/utils/configdict.py\n@@ -10,15 +10,19 @@ except ImportError:\n import collections as collections_abc\n \n \n-def gather_configtree(d):\n+def gather_configtree(d, parse_lists=False):\n \"\"\"Chains nested-dicts into a connected tree of ConfigDict(s)\n \n Parameters\n ----------\n- d : dict\n+ d : dict or MutableMapping\n Cast to :py:class:`ConfigDict`. Nested dicts within are also\n recursively cast and assigned parents, reflecting their nested\n structure.\n+ parse_lists : bool, optional\n+ If `d` or its children contain a list of dicts, do you want to convert\n+ these listed dicts to ConfDicts and assign them parents. This is\n+ slow. Note this only parses lists, strictly, not all Sequences.\n \n Returns\n -------\n@@ -47,8 +51,17 @@ def gather_configtree(d):\n for k, v in out.data.items():\n # Replace nested maps with new ConfigDicts\n if isinstance(v, collections_abc.MutableMapping):\n- out.data[k] = gather_configtree(v)\n+ out.data[k] = gather_configtree(v, parse_lists=parse_lists)\n out.data[k].parent = out\n+\n+ # If list has mappings, replace mappings with new ConfigDicts\n+ if parse_lists and isinstance(v, list):\n+ for idx, item in enumerate(v):\n+ if isinstance(item, collections_abc.MutableMapping):\n+ cd = gather_configtree(item, parse_lists=parse_lists)\n+ cd.parent = out\n+ out.data[k][idx] = cd\n+\n return out\n \n \n@@ -138,7 +151,7 @@ class ConfigDict(UserDict, object):\n if isinstance(key, str):\n return key.lower().replace('_', '-')\n \n- def accessed_all_keys(self, search='local'):\n+ def accessed_all_keys(self, search='local', parse_lists=False):\n \"\"\"Were all the keys used in the config tree?\n \n Parameters\n@@ -156,6 +169,11 @@ class ConfigDict(UserDict, object):\n ``\"children\"``\n Recursively check keys in children, moving down the tree, after\n checking local keys.\n+ parse_lists : bool, optional\n+ If True when `search` is \"children\", check if self or its children\n+ contain a list and check the list for ConfDicts and whether they\n+ used their keys. This is slow. Note this only parses lists,\n+ strictly, not all Sequences.\n \n Returns\n -------\n@@ -215,17 +233,33 @@ class ConfigDict(UserDict, object):\n # Recursively check parents keys, if any haven't been used,\n # immediately return False.\n if self.parent is not None:\n- parent_used = self.parent.accessed_all_keys(search=search)\n+ parent_used = self.parent.accessed_all_keys(\n+ search=search,\n+ parse_lists=parse_lists,\n+ )\n if parent_used is False:\n return False\n+\n elif search == 'children':\n # Recursively check children keys, if any haven't been used,\n # immediately return False.\n for k, v in self.data.items():\n- # Assuming its faster to ask for forgiveness than to check\n- # with `isinstance()` or `hasattr()q...\n+ if parse_lists and isinstance(v, list):\n+ for item in v:\n+ try:\n+ child_used = item.accessed_all_keys(\n+ search=search,\n+ parse_lists=parse_lists,\n+ )\n+ if child_used is False:\n+ return False\n+ except AttributeError:\n+ continue\n+ continue\n+\n try:\n- child_used = v.accessed_all_keys(search=search)\n+ child_used = v.accessed_all_keys(search=search,\n+ parse_lists=parse_lists)\n if child_used is False:\n return False\n except AttributeError:\n", "test_patch": "diff --git a/tests/utils/test_configdict.py b/tests/utils/test_configdict.py\nindex 1d299f0..c26edb8 100644\n--- a/tests/utils/test_configdict.py\n+++ b/tests/utils/test_configdict.py\n@@ -8,6 +8,18 @@ def simple_nested_tree():\n return {'a': 1, 'b': {'a': 2}, 'c': 3, 'd-4': 4, 'e_5': 5, 'F': 6}\n \n \n+def test_gather_configtree_nested_lists():\n+ \"\"\"Test gather_configtree() \"parse_lists\" option\"\"\"\n+ d = {'a': 1, 'c': [2, {'x': 'foo', 'y': {'z': 'bar'}}]}\n+ conf = gather_configtree(d, parse_lists=True)\n+ assert conf['c'][1]['y']['a'] == conf['a']\n+\n+ assert conf.accessed_all_keys(search='children', parse_lists=True) is False\n+ conf['c'][1]['x']\n+ conf['c'][1]['y']['z']\n+ assert conf.accessed_all_keys(search='children', parse_lists=True) is True\n+\n+\n def test_configdict_climbs_tree(simple_nested_tree):\n conf = gather_configtree(simple_nested_tree)\n assert conf['b']['c'] == 3\n@@ -105,24 +117,6 @@ def test_configdict_key_access_stack_nested(simple_nested_tree):\n assert top_keys == ['b', 'f']\n \n \n-def test_configdict_accessed_all_keys_local(simple_nested_tree):\n- root_conf = gather_configtree(simple_nested_tree)\n- child_conf = root_conf['b']\n-\n- root_conf['a']\n- root_conf['c']\n- root_conf['d-4']\n- root_conf['e-5']\n-\n- assert root_conf.accessed_all_keys(search='local') is False\n-\n- root_conf['f']\n-\n- assert root_conf.accessed_all_keys(search='local') is True\n-\n- assert child_conf.accessed_all_keys(search='local') is False\n-\n-\n def test_configdict_accessed_all_keys_local(simple_nested_tree):\n kwargs = {'search': 'local'}\n root_conf = gather_configtree(simple_nested_tree)\n", "FAIL_TO_PASS": ["tests/utils/test_configdict.py::test_gather_configtree_nested_lists"]}], "all_FAIL_TO_PASS": ["tests/utils/test_configdict.py::test_gather_configtree_nested_lists"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "OpenMDAO__dymos-1018_x1", "level": 1, "source": "swerebench", "repo": "OpenMDAO/dymos", "image": "swerebench/sweb.eval.x86_64.openmdao_1776_dymos-1018:latest", "base_commit": "37bb5dd5e11467af36d0364d771ed7be4dbc18cc", "num_bugs": 1, "bugs": [{"instance_id": "OpenMDAO__dymos-1018", "base_commit": "37bb5dd5e11467af36d0364d771ed7be4dbc18cc", "gold_patch": "diff --git a/dymos/utils/introspection.py b/dymos/utils/introspection.py\nindex 73497d24..775fa29b 100644\n--- a/dymos/utils/introspection.py\n+++ b/dymos/utils/introspection.py\n@@ -227,7 +227,10 @@ def _configure_constraint_introspection(phase):\n \n con['shape'] = control_shape\n con['units'] = control_units if con['units'] is None else con['units']\n- con['constraint_path'] = f'timeseries.{prefix}{var}'\n+ if birkhoff and constraint_type in ('initial', 'final'):\n+ con['constraint_path'] = f'boundary_vals.{var}'\n+ else:\n+ con['constraint_path'] = f'timeseries.{prefix}{var}'\n \n elif var_type in ['indep_polynomial_control', 'input_polynomial_control']:\n prefix = 'polynomial_controls:' if phase.timeseries_options['use_prefix'] else ''\n@@ -235,7 +238,10 @@ def _configure_constraint_introspection(phase):\n control_units = phase.polynomial_control_options[var]['units']\n con['shape'] = control_shape\n con['units'] = control_units if con['units'] is None else con['units']\n- con['constraint_path'] = f'timeseries.{prefix}{var}'\n+ if birkhoff and constraint_type in ('initial', 'final'):\n+ con['constraint_path'] = f'boundary_vals.{var}'\n+ else:\n+ con['constraint_path'] = f'timeseries.{prefix}{var}'\n \n elif var_type == 'control_rate':\n prefix = 'control_rates:' if phase.timeseries_options['use_prefix'] else ''\n@@ -245,7 +251,10 @@ def _configure_constraint_introspection(phase):\n con['shape'] = control_shape\n con['units'] = get_rate_units(control_units, time_units, deriv=1) \\\n if con['units'] is None else con['units']\n- con['constraint_path'] = f'timeseries.{prefix}{var}'\n+ if birkhoff and constraint_type in ('initial', 'final'):\n+ con['constraint_path'] = f'boundary_vals.{var}'\n+ else:\n+ con['constraint_path'] = f'timeseries.{prefix}{var}'\n \n elif var_type == 'control_rate2':\n prefix = 'control_rates:' if phase.timeseries_options['use_prefix'] else ''\n@@ -255,7 +264,10 @@ def _configure_constraint_introspection(phase):\n con['shape'] = control_shape\n con['units'] = get_rate_units(control_units, time_units, deriv=2) \\\n if con['units'] is None else con['units']\n- con['constraint_path'] = f'timeseries.{prefix}{var}'\n+ if birkhoff and constraint_type in ('initial', 'final'):\n+ con['constraint_path'] = f'boundary_vals.{var}'\n+ else:\n+ con['constraint_path'] = f'timeseries.{prefix}{var}'\n \n elif var_type == 'polynomial_control_rate':\n prefix = 'polynomial_control_rates:' if phase.timeseries_options['use_prefix'] else ''\n@@ -265,7 +277,10 @@ def _configure_constraint_introspection(phase):\n con['shape'] = control_shape\n con['units'] = get_rate_units(control_units, time_units, deriv=1) \\\n if con['units'] is None else con['units']\n- con['constraint_path'] = f'timeseries.{prefix}{var}'\n+ if birkhoff and constraint_type in ('initial', 'final'):\n+ con['constraint_path'] = f'boundary_vals.{var}'\n+ else:\n+ con['constraint_path'] = f'timeseries.{prefix}{var}'\n \n elif var_type == 'polynomial_control_rate2':\n prefix = 'polynomial_control_rates:' if phase.timeseries_options['use_prefix'] else ''\n@@ -275,7 +290,10 @@ def _configure_constraint_introspection(phase):\n con['shape'] = control_shape\n con['units'] = get_rate_units(control_units, time_units, deriv=2) \\\n if con['units'] is None else con['units']\n- con['constraint_path'] = f'timeseries.{prefix}{var}'\n+ if birkhoff and constraint_type in ('initial', 'final'):\n+ con['constraint_path'] = f'boundary_vals.{var}'\n+ else:\n+ con['constraint_path'] = f'timeseries.{prefix}{var}'\n \n elif var_type == 'timeseries_exec_comp_output':\n con['shape'] = (1,)\n@@ -290,7 +308,11 @@ def _configure_constraint_introspection(phase):\n \n con['shape'] = meta['shape']\n con['units'] = meta['units']\n- con['constraint_path'] = f'timeseries.{con[\"constraint_name\"]}'\n+\n+ if birkhoff and constraint_type in ('initial', 'final'):\n+ con['constraint_path'] = f'boundary_vals.{var}'\n+ else:\n+ con['constraint_path'] = f'timeseries.{con[\"constraint_name\"]}'\n \n \n def configure_controls_introspection(control_options, ode, time_units='s'):\n", "test_patch": "diff --git a/dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py b/dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py\nnew file mode 100644\nindex 00000000..f47c5cfe\n--- /dev/null\n+++ b/dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py\n@@ -0,0 +1,251 @@\n+import unittest\n+\n+import openmdao.api as om\n+import dymos as dm\n+\n+from openmdao.utils.assert_utils import assert_near_equal\n+from openmdao.utils.testing_utils import use_tempdirs\n+from dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE\n+\n+\n+@use_tempdirs\n+class TestBrachistochroneBirkhoffConstraints(unittest.TestCase):\n+\n+ def test_brachistochrone_control_prefix(self):\n+\n+ p = om.Problem(model=om.Group())\n+\n+ p.driver = om.ScipyOptimizeDriver()\n+ p.driver.options['optimizer'] = 'SLSQP'\n+ p.driver.declare_coloring(tol=1.0E-12)\n+\n+ grid = dm.BirkhoffGrid(num_segments=1, nodes_per_seg=25, grid_type='lgl')\n+ tx = dm.Birkhoff(grid=grid)\n+\n+ traj = dm.Trajectory()\n+ phase = dm.Phase(ode_class=BrachistochroneODE, transcription=tx)\n+ phase.timeseries_options['use_prefix'] = True\n+ p.model.add_subsystem('traj', traj)\n+ traj.add_phase('phase0', phase)\n+\n+ phase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n+\n+ phase.add_state('x', fix_initial=True, fix_final=False)\n+ phase.add_state('y', fix_initial=True, fix_final=False)\n+\n+ # Note that by omitting the targets here Dymos will automatically attempt to connect\n+ # to a top-level input named 'v' in the ODE, and connect to nothing if it's not found.\n+ phase.add_state('v', fix_initial=True, fix_final=False)\n+\n+ phase.add_control('theta',\n+ continuity=True, rate_continuity=True,\n+ units='deg')\n+\n+ phase.add_parameter('g', targets=['g'], units='m/s**2')\n+\n+ phase.add_path_constraint('theta', lower=0.01, upper=179.9)\n+ phase.add_boundary_constraint('theta', loc='final', lower=0.01, upper=179.9)\n+\n+ phase.add_boundary_constraint('x', loc='final', equals=10)\n+ phase.add_boundary_constraint('y', loc='final', equals=5)\n+ # Minimize time at the end of the phase\n+ phase.add_objective('time_phase', loc='final', scaler=10)\n+\n+ p.set_solver_print(0)\n+\n+ p.setup()\n+\n+ p['traj.phase0.t_initial'] = 0.0\n+ p['traj.phase0.t_duration'] = 1.5\n+\n+ p['traj.phase0.initial_states:x'] = 0.0\n+ p['traj.phase0.initial_states:y'] = 10.0\n+ p['traj.phase0.initial_states:v'] = 0.0\n+\n+ p['traj.phase0.states:x'] = phase.interp('x', [0, 10])\n+ p['traj.phase0.states:y'] = phase.interp('y', [10, 5])\n+ p['traj.phase0.states:v'] = phase.interp('v', [0, 9.9])\n+ p['traj.phase0.controls:theta'] = phase.interp('theta', [5, 100])\n+ p['traj.phase0.parameters:g'] = 9.80665\n+\n+ p.run_driver()\n+ assert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-4)\n+\n+ def test_brachistochrone_control_no_prefix(self):\n+\n+ p = om.Problem(model=om.Group())\n+\n+ p.driver = om.ScipyOptimizeDriver()\n+ p.driver.options['optimizer'] = 'SLSQP'\n+ p.driver.declare_coloring(tol=1.0E-12)\n+\n+ grid = dm.BirkhoffGrid(num_segments=1, nodes_per_seg=25, grid_type='lgl')\n+ tx = dm.Birkhoff(grid=grid)\n+\n+ traj = dm.Trajectory()\n+ phase = dm.Phase(ode_class=BrachistochroneODE, transcription=tx)\n+ phase.timeseries_options['use_prefix'] = False\n+ p.model.add_subsystem('traj', traj)\n+ traj.add_phase('phase0', phase)\n+\n+ phase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n+\n+ phase.add_state('x', fix_initial=True, fix_final=False)\n+ phase.add_state('y', fix_initial=True, fix_final=False)\n+\n+ # Note that by omitting the targets here Dymos will automatically attempt to connect\n+ # to a top-level input named 'v' in the ODE, and connect to nothing if it's not found.\n+ phase.add_state('v', fix_initial=True, fix_final=False)\n+\n+ phase.add_control('theta',\n+ continuity=True, rate_continuity=True,\n+ units='deg')\n+\n+ phase.add_parameter('g', targets=['g'], units='m/s**2')\n+\n+ phase.add_path_constraint('theta', lower=0.01, upper=179.9)\n+ phase.add_boundary_constraint('theta', loc='final', lower=0.01, upper=179.9)\n+\n+ phase.add_boundary_constraint('x', loc='final', equals=10)\n+ phase.add_boundary_constraint('y', loc='final', equals=5)\n+ # Minimize time at the end of the phase\n+ phase.add_objective('time_phase', loc='final', scaler=10)\n+\n+ p.set_solver_print(0)\n+\n+ p.setup()\n+\n+ p['traj.phase0.t_initial'] = 0.0\n+ p['traj.phase0.t_duration'] = 1.5\n+\n+ p['traj.phase0.initial_states:x'] = 0.0\n+ p['traj.phase0.initial_states:y'] = 10.0\n+ p['traj.phase0.initial_states:v'] = 0.0\n+\n+ p['traj.phase0.states:x'] = phase.interp('x', [0, 10])\n+ p['traj.phase0.states:y'] = phase.interp('y', [10, 5])\n+ p['traj.phase0.states:v'] = phase.interp('v', [0, 9.9])\n+ p['traj.phase0.controls:theta'] = phase.interp('theta', [5, 100])\n+ p['traj.phase0.parameters:g'] = 9.80665\n+\n+ p.run_driver()\n+ assert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-4)\n+\n+ def test_brachistochrone_ode_prefix(self):\n+\n+ p = om.Problem(model=om.Group())\n+\n+ p.driver = om.ScipyOptimizeDriver()\n+ p.driver.options['optimizer'] = 'SLSQP'\n+ p.driver.declare_coloring(tol=1.0E-12)\n+\n+ grid = dm.BirkhoffGrid(num_segments=1, nodes_per_seg=25, grid_type='lgl')\n+ tx = dm.Birkhoff(grid=grid)\n+\n+ traj = dm.Trajectory()\n+ phase = dm.Phase(ode_class=BrachistochroneODE, transcription=tx)\n+ phase.timeseries_options['use_prefix'] = True\n+ p.model.add_subsystem('traj', traj)\n+ traj.add_phase('phase0', phase)\n+\n+ phase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n+\n+ phase.add_state('x', fix_initial=True, fix_final=False)\n+ phase.add_state('y', fix_initial=True, fix_final=False)\n+\n+ # Note that by omitting the targets here Dymos will automatically attempt to connect\n+ # to a top-level input named 'v' in the ODE, and connect to nothing if it's not found.\n+ phase.add_state('v', fix_initial=True, fix_final=False)\n+\n+ phase.add_control('theta',\n+ continuity=True, rate_continuity=True,\n+ units='deg', lower=0.01, upper=179.9)\n+\n+ phase.add_parameter('g', targets=['g'], units='m/s**2')\n+\n+ phase.add_boundary_constraint('x', loc='final', equals=10)\n+ phase.add_boundary_constraint('y', loc='final', equals=5)\n+ phase.add_boundary_constraint('check', loc='final', lower=-50, upper=50)\n+ phase.add_path_constraint('check', upper=100, lower=-100)\n+ # Minimize time at the end of the phase\n+ phase.add_objective('time_phase', loc='final', scaler=10)\n+\n+ p.set_solver_print(0)\n+\n+ p.setup()\n+\n+ p['traj.phase0.t_initial'] = 0.0\n+ p['traj.phase0.t_duration'] = 1.5\n+\n+ p['traj.phase0.initial_states:x'] = 0.0\n+ p['traj.phase0.initial_states:y'] = 10.0\n+ p['traj.phase0.initial_states:v'] = 0.0\n+\n+ p['traj.phase0.states:x'] = phase.interp('x', [0, 10])\n+ p['traj.phase0.states:y'] = phase.interp('y', [10, 5])\n+ p['traj.phase0.states:v'] = phase.interp('v', [0, 9.9])\n+ p['traj.phase0.controls:theta'] = phase.interp('theta', [5, 100])\n+ p['traj.phase0.parameters:g'] = 9.80665\n+\n+ p.run_driver()\n+ assert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-4)\n+\n+ def test_brachistochrone_ode_no_prefix(self):\n+\n+ p = om.Problem(model=om.Group())\n+\n+ p.driver = om.ScipyOptimizeDriver()\n+ p.driver.options['optimizer'] = 'SLSQP'\n+ p.driver.declare_coloring(tol=1.0E-12)\n+\n+ grid = dm.BirkhoffGrid(num_segments=1, nodes_per_seg=25, grid_type='lgl')\n+ tx = dm.Birkhoff(grid=grid)\n+\n+ traj = dm.Trajectory()\n+ phase = dm.Phase(ode_class=BrachistochroneODE, transcription=tx)\n+ phase.timeseries_options['use_prefix'] = False\n+ p.model.add_subsystem('traj', traj)\n+ traj.add_phase('phase0', phase)\n+\n+ phase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n+\n+ phase.add_state('x', fix_initial=True, fix_final=False)\n+ phase.add_state('y', fix_initial=True, fix_final=False)\n+\n+ # Note that by omitting the targets here Dymos will automatically attempt to connect\n+ # to a top-level input named 'v' in the ODE, and connect to nothing if it's not found.\n+ phase.add_state('v', fix_initial=True, fix_final=False)\n+\n+ phase.add_control('theta',\n+ continuity=True, rate_continuity=True,\n+ units='deg', lower=0.01, upper=179.9)\n+\n+ phase.add_parameter('g', targets=['g'], units='m/s**2')\n+\n+ phase.add_boundary_constraint('x', loc='final', equals=10)\n+ phase.add_boundary_constraint('y', loc='final', equals=5)\n+ phase.add_boundary_constraint('check', loc='final', lower=-50, upper=50)\n+ phase.add_path_constraint('check', upper=100, lower=-100)\n+\n+ # Minimize time at the end of the phase\n+ phase.add_objective('time_phase', loc='final', scaler=10)\n+\n+ p.set_solver_print(0)\n+\n+ p.setup()\n+\n+ p['traj.phase0.t_initial'] = 0.0\n+ p['traj.phase0.t_duration'] = 1.5\n+\n+ p['traj.phase0.initial_states:x'] = 0.0\n+ p['traj.phase0.initial_states:y'] = 10.0\n+ p['traj.phase0.initial_states:v'] = 0.0\n+\n+ p['traj.phase0.states:x'] = phase.interp('x', [0, 10])\n+ p['traj.phase0.states:y'] = phase.interp('y', [10, 5])\n+ p['traj.phase0.states:v'] = phase.interp('v', [0, 9.9])\n+ p['traj.phase0.controls:theta'] = phase.interp('theta', [5, 100])\n+ p['traj.phase0.parameters:g'] = 9.80665\n+\n+ p.run_driver()\n+ assert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-4)\n", "FAIL_TO_PASS": ["dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_control_no_prefix", "dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_control_prefix", "dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_ode_no_prefix", "dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_ode_prefix"]}], "all_FAIL_TO_PASS": ["dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_control_no_prefix", "dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_control_prefix", "dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_ode_no_prefix", "dymos/examples/brachistochrone/test/test_brachistochrone_birkhoff_constraints.py::TestBrachistochroneBirkhoffConstraints::test_brachistochrone_ode_prefix"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aws__chalice-1526_x2", "level": 2, "source": "swerebench", "repo": "aws/chalice", "image": "swerebench/sweb.eval.x86_64.aws_1776_chalice-1526:latest", "base_commit": "30d8b3eeba95d0bcbba8d21221158a9171fbec57", "num_bugs": 2, "bugs": [{"instance_id": "aws__chalice-1526", "base_commit": "30d8b3eeba95d0bcbba8d21221158a9171fbec57", "gold_patch": "diff --git a/.changes/next-release/21697515329-bugfix-Blueprints-30428.json b/.changes/next-release/21697515329-bugfix-Blueprints-30428.json\nnew file mode 100644\nindex 0000000..9cb3fe4\n--- /dev/null\n+++ b/.changes/next-release/21697515329-bugfix-Blueprints-30428.json\n@@ -0,0 +1,5 @@\n+{\n+ \"type\": \"bugfix\",\n+ \"category\": \"Blueprints\",\n+ \"description\": \"Preserve docstring in blueprints (#1525)\"\n+}\ndiff --git a/chalice/app.py b/chalice/app.py\nindex 6ae3359..b75bf09 100644\n--- a/chalice/app.py\n+++ b/chalice/app.py\n@@ -1776,6 +1776,7 @@ class Blueprint(DecoratorAPI):\n # Blueprint.register() and provide an app object. Once\n # we have access to an app, we can call the actual _wrap_handler\n # which will have access to middleware.\n+ @functools.wraps(user_handler)\n def _defer_wrap_handler(app):\n # pylint: disable=protected-access\n return app._wrap_handler(handler_type, handler_name,\n", "test_patch": "diff --git a/tests/unit/test_app.py b/tests/unit/test_app.py\nindex c7ae84d..9853101 100644\n--- a/tests/unit/test_app.py\n+++ b/tests/unit/test_app.py\n@@ -2015,6 +2015,27 @@ def test_can_combine_multiple_blueprints_in_single_app():\n assert sorted(list(myapp.routes)) == ['/bar', '/foo']\n \n \n+def test_doc_saved_on_route():\n+ myapp = app.Chalice('myapp')\n+\n+ @myapp.route('/')\n+ def index():\n+ \"\"\"My index docstring.\"\"\"\n+ pass\n+\n+ assert index.__doc__ == 'My index docstring.'\n+\n+\n+def test_blueprint_docstring_is_preserved():\n+ foo = app.Blueprint('foo')\n+\n+ @foo.route('/foo')\n+ def first():\n+ \"\"\"Blueprint docstring.\"\"\"\n+\n+ assert first.__doc__ == 'Blueprint docstring.'\n+\n+\n def test_can_mount_apis_at_url_prefix():\n myapp = app.Chalice('myapp')\n foo = app.Blueprint('foo')\n", "FAIL_TO_PASS": ["tests/unit/test_app.py::test_blueprint_docstring_is_preserved"]}, {"instance_id": "aws__chalice-1530", "base_commit": "96c8bded3e0936df42d49eb9fb3b2226e60848d2", "gold_patch": "diff --git a/.changes/next-release/51581685415-enhancement-Binary-64168.json b/.changes/next-release/51581685415-enhancement-Binary-64168.json\nnew file mode 100644\nindex 0000000..a40e212\n--- /dev/null\n+++ b/.changes/next-release/51581685415-enhancement-Binary-64168.json\n@@ -0,0 +1,5 @@\n+{\n+ \"type\": \"enhancement\",\n+ \"category\": \"Binary\",\n+ \"description\": \"Support returning native python types when using `*/*` for binary types (#1501)\"\n+}\ndiff --git a/chalice/app.py b/chalice/app.py\nindex b75bf09..d2bfe20 100644\n--- a/chalice/app.py\n+++ b/chalice/app.py\n@@ -494,12 +494,17 @@ class Response(object):\n body = response_dict['body']\n \n if _matches_content_type(content_type, binary_types):\n- if _matches_content_type(content_type, ['application/json']):\n+ if _matches_content_type(content_type, ['application/json']) or \\\n+ not content_type:\n # There's a special case when a user configures\n # ``application/json`` as a binary type. The default\n # json serialization results in a string type, but for binary\n # content types we need a type bytes(). So we need to special\n # case this scenario and encode the JSON body to bytes().\n+ #\n+ # If a user does not provide a content type header, which can\n+ # happen if they return a python type instead of a ``Response``\n+ # type, then we assume the content is application/json.\n body = body if isinstance(body, bytes) \\\n else body.encode('utf-8')\n body = self._base64encode(body)\n", "test_patch": "diff --git a/tests/unit/test_app.py b/tests/unit/test_app.py\nindex 9853101..bdec020 100644\n--- a/tests/unit/test_app.py\n+++ b/tests/unit/test_app.py\n@@ -415,6 +415,44 @@ def test_can_encode_binary_json(sample_app):\n assert encoded_response['body'] == 'eyJmb28iOiJiYXIifQ=='\n \n \n+def test_wildcard_accepts_with_native_python_types_serializes_json(\n+ sample_app, create_event):\n+ sample_app.api.binary_types = ['*/*']\n+\n+ @sample_app.route('/py-dict')\n+ def py_dict():\n+ return {'foo': 'bar'}\n+\n+ event = create_event('/py-dict', 'GET', {})\n+ event['headers']['Accept'] = '*/*'\n+ response = sample_app(event, context=None)\n+ # In this case, they've return a native python dict type, which should\n+ # be serialized to JSON and returned back to the user as JSON. Because\n+ # we also have ``*/*`` as a binary type, we'll return the response\n+ # as a binary response type.\n+ assert base64.b64decode(response['body']) == b'{\"foo\":\"bar\"}'\n+ assert response['isBase64Encoded']\n+\n+\n+def test_wildcard_accepts_with_response_class(\n+ sample_app, create_event):\n+ sample_app.api.binary_types = ['*/*']\n+\n+ @sample_app.route('/py-dict')\n+ def py_dict():\n+ return Response(body=json.dumps({'foo': 'bar'}).encode('utf-8'),\n+ headers={'Content-Type': 'application/json'},\n+ status_code=200)\n+\n+ event = create_event('/py-dict', 'GET', {})\n+ event['headers']['Accept'] = '*/*'\n+ response = sample_app(event, context=None)\n+ # Because our binary types is '*/*' we should be returning this\n+ # content as binary.\n+ assert base64.b64decode(response['body']) == b'{\"foo\": \"bar\"}'\n+ assert response['isBase64Encoded']\n+\n+\n def test_can_parse_route_view_args():\n entry = app.RouteEntry(lambda: {\"foo\": \"bar\"}, 'view-name',\n '/foo/{bar}/baz/{qux}', method='GET')\n", "FAIL_TO_PASS": ["tests/unit/test_app.py::test_wildcard_accepts_with_native_python_types_serializes_json"]}], "all_FAIL_TO_PASS": ["tests/unit/test_app.py::test_blueprint_docstring_is_preserved", "tests/unit/test_app.py::test_wildcard_accepts_with_native_python_types_serializes_json"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "bluesky__bluesky-darkframes-21_x2", "level": 2, "source": "swerebench", "repo": "bluesky/bluesky-darkframes", "image": "swerebench/sweb.eval.x86_64.bluesky_1776_bluesky-darkframes-21:latest", "base_commit": "3cf9c7e8ab62474932b7541ef1c13fa66183c14b", "num_bugs": 2, "bugs": [{"instance_id": "bluesky__bluesky-darkframes-21", "base_commit": "3cf9c7e8ab62474932b7541ef1c13fa66183c14b", "gold_patch": "diff --git a/.flake8 b/.flake8\nindex 5e2e49c..97bf913 100644\n--- a/.flake8\n+++ b/.flake8\n@@ -1,2 +1,10 @@\n [flake8]\n-exclude = .git,__pycache__,build,dist,versioneer.py,bluesky_darkframes/_version.py,docs/source/conf.py\n+exclude =\n+ .git,\n+ __pycache__,\n+ build,\n+ dist,\n+ versioneer.py,\n+ bluesky_darkframes/_version.py,\n+ docs/source/conf.py\n+max-line-length = 115\ndiff --git a/.travis.yml b/.travis.yml\nindex acc748e..f1cc1e3 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -24,7 +24,7 @@ script:\n - coverage run -m pytest # Run the tests and check for test coverage.\n - coverage report -m # Generate test coverage report.\n - codecov # Upload the report to codecov.\n- - flake8 --max-line-length=115 # Enforce code style (but relax line length limit a bit).\n+ - flake8 # Enforce code style.\n - make -C docs html # Build the documentation.\n - set -e\n - pip install doctr\ndiff --git a/bluesky_darkframes/__init__.py b/bluesky_darkframes/__init__.py\nindex de2f5fa..ddb3fac 100644\n--- a/bluesky_darkframes/__init__.py\n+++ b/bluesky_darkframes/__init__.py\n@@ -2,6 +2,7 @@ import collections\n import copy\n import logging\n import time\n+import uuid\n \n import event_model\n from frozendict import frozendict\n@@ -33,8 +34,8 @@ class SnapshotDevice(Device):\n self._describe_configuration = device.describe_configuration()\n self._read = device.read()\n self._read_configuration = device.read_configuration()\n- self._read_attrs = list(device.read())\n- self._configuration_attrs = list(device.read_configuration())\n+ self._read_attrs = list(self._read)\n+ self._configuration_attrs = list(self._read_configuration)\n self._asset_docs_cache = list(device.collect_asset_docs())\n self._assets_collected = False\n \n@@ -65,10 +66,59 @@ class SnapshotDevice(Device):\n if self._assets_collected:\n yield from []\n else:\n+ self._assets_collected = True\n yield from self._asset_docs_cache\n \n def stage(self):\n self._assets_collected = False\n+ return super().stage()\n+\n+ def unstage(self):\n+ self._remake_docs()\n+ return super().unstage()\n+\n+ def _remake_docs(self):\n+ \"\"\"\n+ Avoid re-emitting documents with the same unique identifiers.\n+\n+ - Make shallow copies of Resource and Datum docs with new unique identifiers.\n+ - Update the return value of read() with the new datum_ids.\n+ \"\"\"\n+ resources = {} # map old uid to new uid\n+ new_asset_docs_cache = []\n+ for name, doc in self._asset_docs_cache:\n+ if name == 'resource':\n+ new_uid = str(uuid.uuid4())\n+ resources[doc['uid']] = new_uid\n+ new_doc = doc.copy()\n+ new_doc['uid'] = new_uid\n+ new_asset_docs_cache.append((name, new_doc))\n+ elif name == 'datum':\n+ new_doc = doc.copy()\n+ old_resource_uid = doc['resource']\n+ new_resource_uid = resources[old_resource_uid]\n+ new_doc['resource'] = new_resource_uid\n+ # Some existing code in other libraries looks for the\n+ # {resource_uid}/{integer} pattern in Event documents and uses that\n+ # to take a fast path. The changes to Datum proposed in\n+ # https://github.com/bluesky/event-model/issues/156\n+ # would make this less fragile.\n+ old_datum_id = doc['datum_id']\n+ if old_datum_id.startswith(f\"{old_resource_uid}/\"):\n+ _, suffix = old_datum_id.split('/', 1)\n+ new_datum_id = f\"{new_resource_uid}/{suffix}\"\n+ else:\n+ new_datum_id = str(uuid.uuid4())\n+ new_doc['datum_id'] = new_datum_id\n+ new_asset_docs_cache.append((name, new_doc))\n+ # Update the return value of read() to replace the old datum_id\n+ # with the new one.\n+ for k, v in list(self._read.items()):\n+ if v['value'] == old_datum_id:\n+ self._read[k]['value'] = new_datum_id\n+ else:\n+ raise BlueskyDarkframesValueError(f\"Unexpected name {name}\")\n+ self._asset_docs_cache = new_asset_docs_cache\n \n \n class _SnapshotShell:\n@@ -177,7 +227,7 @@ class DarkFramePreprocessor:\n \n def _evict_old_entries(self):\n now = time.monotonic()\n- for key, (creation_time, snapshot) in list(self._cache.items()):\n+ for key, (creation_time, _snapshot) in list(self._cache.items()):\n if now - creation_time > self.max_age:\n logger.debug(\"Evicted old snapshot for state %r\", key)\n # Too old. Evict from cache.\ndiff --git a/docs/source/usage.rst b/docs/source/usage.rst\nindex 22012a8..7071e1a 100644\n--- a/docs/source/usage.rst\n+++ b/docs/source/usage.rst\n@@ -106,11 +106,17 @@ for whether/how dark frames can be reused.)\n shutter = Shutter(name='shutter', value='open')\n \n def dark_plan(detector):\n+ # Restage to ensure that dark frames goes into a separate file.\n+ yield from bps.unstage(detector)\n+ yield from bps.stage(detector)\n yield from bps.mv(shutter, 'closed')\n yield from bps.trigger(detector, group='darkframe-trigger')\n yield from bps.wait('darkframe-trigger')\n snapshot = bluesky_darkframes.SnapshotDevice(detector)\n yield from bps.mv(shutter, 'open')\n+ # Restage.\n+ yield from bps.unstage(detector)\n+ yield from bps.stage(detector)\n return snapshot\n \n This is boilerplate bluesky and databroker setup not specificially related to\n@@ -237,7 +243,7 @@ Here we use a :class:`event_model.RunRouter`.\n .. jupyter-execute::\n \n from bluesky_darkframes import DarkSubtraction\n- from event_model import RunRouter, Filler\n+ from event_model import RunRouter\n from suitcase.tiff_series import Serializer\n \n def factory(name, doc):\n@@ -246,23 +252,16 @@ Here we use a :class:`event_model.RunRouter`.\n # and then tearing it down when we're done with this run.\n subtractor = DarkSubtraction('det_image')\n serializer = Serializer('live_exported_files/')\n- filler = Filler(db.reg.handler_reg, inplace=False)\n-\n- # Here we push the run 'start' doc through.\n- subtractor(name, doc)\n- serializer(name, doc)\n- filler(name, doc)\n \n # And by returning this function below, we are routing all other\n # documents *for this run* through here.\n- def fill_subtract_and_serialize(name, doc):\n- name, doc = filler(name, doc)\n+ def subtract_and_serialize(name, doc):\n name, doc = subtractor(name, doc)\n serializer(name, doc)\n \n- return [fill_subtract_and_serialize], []\n+ return [subtract_and_serialize], []\n \n- rr = RunRouter([factory])\n+ rr = RunRouter([factory], db.reg.handler_reg)\n RE.subscribe(rr);\n \n Now take some data.\ndiff --git a/requirements.txt b/requirements.txt\nindex 325ece9..accc8c1 100644\n--- a/requirements.txt\n+++ b/requirements.txt\n@@ -1,4 +1,4 @@\n bluesky\n-event-model >=1.13.2\n+event-model >=1.14.0\n frozendict\n numpy\n", "test_patch": "diff --git a/bluesky_darkframes/tests/tests.py b/bluesky_darkframes/tests/tests.py\nindex 590334c..98ddcbb 100644\n--- a/bluesky_darkframes/tests/tests.py\n+++ b/bluesky_darkframes/tests/tests.py\n@@ -5,7 +5,7 @@ import bluesky.plan_stubs as bps\n import bluesky_darkframes\n import bluesky_darkframes.sim\n from bluesky.plans import count\n-from event_model import RunRouter, Filler\n+from event_model import RunRouter\n from ophyd.sim import NumpySeqHandler\n import pytest\n from suitcase.tiff_series import Serializer\n@@ -18,11 +18,15 @@ shutter = bluesky_darkframes.sim.Shutter(name='shutter', value='open')\n \n \n def dark_plan(detector):\n+ yield from bps.unstage(detector)\n yield from bps.mv(shutter, 'closed')\n+ yield from bps.stage(detector)\n yield from bps.trigger(detector, group='darkframe-trigger')\n yield from bps.wait('darkframe-trigger')\n snapshot = bluesky_darkframes.SnapshotDevice(detector)\n+ yield from bps.unstage(detector)\n yield from bps.mv(shutter, 'open')\n+ yield from bps.stage(detector)\n return snapshot\n \n \n@@ -179,6 +183,37 @@ def test_limit(RE):\n previous_state = state\n \n \n+def test_non_colliding_uids(RE):\n+ \"\"\"\n+ Tests that when the same Snapshot is used multiple times it issues distinct\n+ Resource and Datum documents with non-colliding uids.\n+ \"\"\"\n+\n+ class LocalException(Exception):\n+ ...\n+\n+ cache = set()\n+\n+ def check_uniqueness(name, doc):\n+ if name == 'datum':\n+ key = (name, doc['datum_id'])\n+ else:\n+ key = (name, doc['uid'])\n+ if key in cache:\n+ raise LocalException(f\"Collision {key}\")\n+ cache.add(key)\n+\n+ RE.subscribe(check_uniqueness)\n+\n+ dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n+ dark_plan=dark_plan, detector=det, max_age=100)\n+ RE.preprocessors.append(dark_frame_preprocessor)\n+\n+ RE(count([det]), check_uniqueness)\n+ RE(count([det]), check_uniqueness)\n+ RE(count([det]), check_uniqueness)\n+\n+\n @pytest.mark.parametrize('pedestal', [None, 0, 100])\n def test_streaming_export(RE, tmp_path, pedestal):\n \"\"\"\n@@ -193,23 +228,16 @@ def test_streaming_export(RE, tmp_path, pedestal):\n kwargs['pedestal'] = pedestal\n subtractor = bluesky_darkframes.DarkSubtraction('det_image', **kwargs)\n serializer = Serializer(tmp_path)\n- filler = Filler({'NPY_SEQ': NumpySeqHandler}, inplace=False)\n-\n- # Here we push the run 'start' doc through.\n- subtractor(name, doc)\n- serializer(name, doc)\n- filler(name, doc)\n \n # And by returning this function below, we are routing all other\n # documents *for this run* through here.\n- def fill_subtract_and_serialize(name, doc):\n- name, doc = filler(name, doc)\n+ def subtract_and_serialize(name, doc):\n name, doc = subtractor(name, doc)\n serializer(name, doc)\n \n- return [fill_subtract_and_serialize], []\n+ return [subtract_and_serialize], []\n \n- rr = RunRouter([factory])\n+ rr = RunRouter([factory], {'NPY_SEQ': NumpySeqHandler})\n RE.subscribe(rr)\n \n dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n@@ -232,23 +260,16 @@ def test_no_dark_frames(RE, tmp_path):\n # and then tearing it down when we're done with this run.\n subtractor = bluesky_darkframes.DarkSubtraction('det_image')\n serializer = Serializer(tmp_path)\n- filler = Filler({'NPY_SEQ': NumpySeqHandler}, inplace=False)\n-\n- # Here we push the run 'start' doc through.\n- subtractor(name, doc)\n- serializer(name, doc)\n- filler(name, doc)\n \n # And by returning this function below, we are routing all other\n # documents *for this run* through here.\n- def fill_subtract_and_serialize(name, doc):\n- name, doc = filler(name, doc)\n+ def subtract_and_serialize(name, doc):\n name, doc = subtractor(name, doc)\n serializer(name, doc)\n \n- return [fill_subtract_and_serialize], []\n+ return [subtract_and_serialize], []\n \n- rr = RunRouter([factory])\n+ rr = RunRouter([factory], {'NPY_SEQ': NumpySeqHandler})\n RE.subscribe(rr)\n \n # We intentionally 'forget' to set up a dark_frame_preprocessor for this\n", "FAIL_TO_PASS": ["bluesky_darkframes/tests/tests.py::test_non_colliding_uids[False]", "bluesky_darkframes/tests/tests.py::test_non_colliding_uids[True]"]}, {"instance_id": "bluesky__bluesky-darkframes-24", "base_commit": "53808f1f4450c3e1ec65aa4c6f8e9a91949d602a", "gold_patch": "diff --git a/bluesky_darkframes/__init__.py b/bluesky_darkframes/__init__.py\nindex ddb3fac..6603ab1 100644\n--- a/bluesky_darkframes/__init__.py\n+++ b/bluesky_darkframes/__init__.py\n@@ -8,6 +8,7 @@ import event_model\n from frozendict import frozendict\n import bluesky.preprocessors\n import bluesky.plan_stubs as bps\n+from bluesky.utils import short_uid\n import numpy\n from ophyd import Device\n \n@@ -138,6 +139,9 @@ class _SnapshotShell:\n return getattr(self.__snapshot, key)\n \n \n+GROUP_PREFIX = 'bluesky-darkframes-trigger'\n+\n+\n class DarkFramePreprocessor:\n \"\"\"\n A plan preprocessor that ensures each Run records a dark frame.\n@@ -312,18 +316,29 @@ class DarkFramePreprocessor:\n # bluesky will always see the \"Device\" self._current_snapshot\n # here, and it will be satisfied.\n yield from bps.stage(self._current_snapshot)\n- yield from bps.trigger_and_read([self._current_snapshot],\n- name=self.stream_name)\n+ yield from trigger_and_read(\n+ [self._current_snapshot],\n+ name=self.stream_name,\n+ group=short_uid(GROUP_PREFIX))\n yield from bps.unstage(self._current_snapshot)\n self._latch = False\n if msg is not None:\n return (yield msg)\n \n def maybe_insert_dark_frame(msg):\n- if msg.command == 'trigger' and msg.obj is self.detector and not self._latch:\n+ # * Is this a 'trigger' message?\n+ # * Does it refer to the detector that this preprocessor cares about?\n+ # * Is it *not* from another DarkFramePreprocessor. (There can be\n+ # multiple nested DarkFramePreprocessors watching the same detector\n+ # by applying different dark_plans / recording Events in different\n+ # streams.)\n+ if (msg.command == 'trigger'\n+ and msg.obj is self.detector\n+ and not msg.kwargs['group'].startswith(GROUP_PREFIX)\n+ and not self._latch):\n force_read = self._force_read_before_next_event\n self._force_read_before_next_event = False\n- self._latch = True\n+ self._latch = True # prevents infinite recursion\n return insert_dark_frame(force_read=force_read, msg=msg), None\n elif msg.command == 'open_run':\n # Make sure we get a new Event because we have just started a\n@@ -486,3 +501,56 @@ class NoDarkFrame(RuntimeError, BlueskyDarkframesException):\n \n class NoMatchingSnapshot(KeyError, BlueskyDarkframesException):\n ...\n+\n+\n+# Vendored from bluesky.plan_stubs, added `group` parameter\n+\n+\n+def trigger_and_read(devices, name='primary', group=None):\n+ \"\"\"\n+ Trigger and read a list of detectors and bundle readings into one Event.\n+\n+ Parameters\n+ ----------\n+ devices : iterable\n+ devices to trigger (if they have a trigger method) and then read\n+ name : string, optional\n+ event stream name, a convenient human-friendly identifier; default\n+ name is 'primary'\n+ group : string (or any hashable object), optional\n+ identifier used by 'trigger' and 'wait'\n+\n+ Yields\n+ ------\n+ msg : Msg\n+ messages to 'trigger', 'wait' and 'read'\n+ \"\"\"\n+ # If devices is empty, don't emit 'create'/'save' messages.\n+ if not devices:\n+ yield from bps.null()\n+ devices = bps.separate_devices(devices) # remove redundant entries\n+ rewindable = bps.all_safe_rewind(devices) # if devices can be re-triggered\n+\n+ def inner_trigger_and_read():\n+ nonlocal group\n+ if group is None:\n+ group = short_uid('trigger')\n+ no_wait = True\n+ for obj in devices:\n+ if hasattr(obj, 'trigger'):\n+ no_wait = False\n+ yield from bps.trigger(obj, group=group)\n+ # Skip 'wait' if none of the devices implemented a trigger method.\n+ if not no_wait:\n+ yield from bps.wait(group=group)\n+ yield from bps.create(name)\n+ ret = {} # collect and return readings to give plan access to them\n+ for obj in devices:\n+ reading = (yield from bps.read(obj))\n+ if reading is not None:\n+ ret.update(reading)\n+ yield from bps.save()\n+ return ret\n+ from bluesky.preprocessors import rewindable_wrapper\n+ return (yield from rewindable_wrapper(inner_trigger_and_read(),\n+ rewindable))\ndiff --git a/docs/source/usage.rst b/docs/source/usage.rst\nindex 7071e1a..cb89373 100644\n--- a/docs/source/usage.rst\n+++ b/docs/source/usage.rst\n@@ -110,8 +110,10 @@ for whether/how dark frames can be reused.)\n yield from bps.unstage(detector)\n yield from bps.stage(detector)\n yield from bps.mv(shutter, 'closed')\n- yield from bps.trigger(detector, group='darkframe-trigger')\n- yield from bps.wait('darkframe-trigger')\n+ # The `group` parameter passed to trigger MUST start with\n+ # bluesky-darkframes-trigger.\n+ yield from bps.trigger(detector, group='bluesky-darkframes-trigger')\n+ yield from bps.wait('bluesky-darkframes-trigger')\n snapshot = bluesky_darkframes.SnapshotDevice(detector)\n yield from bps.mv(shutter, 'open')\n # Restage.\n", "test_patch": "diff --git a/bluesky_darkframes/tests/tests.py b/bluesky_darkframes/tests/tests.py\nindex 98ddcbb..31bf2ea 100644\n--- a/bluesky_darkframes/tests/tests.py\n+++ b/bluesky_darkframes/tests/tests.py\n@@ -21,7 +21,7 @@ def dark_plan(detector):\n yield from bps.unstage(detector)\n yield from bps.mv(shutter, 'closed')\n yield from bps.stage(detector)\n- yield from bps.trigger(detector, group='darkframe-trigger')\n+ yield from bps.trigger(detector, group='bluesky-darkframes-trigger')\n yield from bps.wait('darkframe-trigger')\n snapshot = bluesky_darkframes.SnapshotDevice(detector)\n yield from bps.unstage(detector)\n@@ -277,3 +277,19 @@ def test_no_dark_frames(RE, tmp_path):\n \n with pytest.raises(bluesky_darkframes.NoDarkFrame):\n RE(count([det]))\n+\n+\n+def test_nested_preprocessors(RE):\n+ N = 3\n+ for i in range(N):\n+ dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n+ dark_plan=dark_plan, detector=det, max_age=0,\n+ stream_name=f'dark_{i}')\n+ RE.preprocessors.append(dark_frame_preprocessor)\n+\n+ def verify_event_count(name, doc):\n+ if name == 'stop':\n+ for i in range(N):\n+ assert doc['num_events'][f'dark_{i}'] == 3\n+\n+ RE(count([det], 3), verify_event_count)\n", "FAIL_TO_PASS": ["bluesky_darkframes/tests/tests.py::test_nested_preprocessors[False]", "bluesky_darkframes/tests/tests.py::test_nested_preprocessors[True]"]}], "all_FAIL_TO_PASS": ["bluesky_darkframes/tests/tests.py::test_non_colliding_uids[False]", "bluesky_darkframes/tests/tests.py::test_non_colliding_uids[True]", "bluesky_darkframes/tests/tests.py::test_nested_preprocessors[False]", "bluesky_darkframes/tests/tests.py::test_nested_preprocessors[True]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "AI4S2S__lilio-49_x2", "level": 2, "source": "swerebench", "repo": "AI4S2S/lilio", "image": "swerebench/sweb.eval.x86_64.ai4s2s_1776_lilio-49:latest", "base_commit": "329a736d26915944744a4235c11497718e0d7832", "num_bugs": 2, "bugs": [{"instance_id": "AI4S2S__lilio-49", "base_commit": "329a736d26915944744a4235c11497718e0d7832", "gold_patch": "diff --git a/lilio/__init__.py b/lilio/__init__.py\nindex f00a7de..ef989aa 100644\n--- a/lilio/__init__.py\n+++ b/lilio/__init__.py\n@@ -62,8 +62,8 @@ Example:\n \"\"\"\n \n import logging\n-from . import calendar_shifter\n-from . import traintest\n+from lilio import calendar_shifter\n+from lilio import traintest\n from .calendar import Calendar\n from .calendar import Interval\n from .calendar_shorthands import daily_calendar\ndiff --git a/lilio/_attrs.py b/lilio/_attrs.py\nnew file mode 100644\nindex 0000000..155ae00\n--- /dev/null\n+++ b/lilio/_attrs.py\n@@ -0,0 +1,52 @@\n+from datetime import datetime\n+from datetime import timezone\n+from typing import Union\n+import xarray as xr\n+import lilio\n+from lilio.calendar import Calendar\n+\n+\n+def add_attrs(data: Union[xr.DataArray, xr.Dataset], calendar: Calendar) -> None:\n+ \"\"\"Update resampled xarray data with the Calendar's attributes and provenance.\"\"\"\n+ history = (\n+ f\"{datetime.now(timezone.utc):%Y-%m-%d %H:%M:%S %Z} - \"\n+ \"Resampled with a Lilio calendar. \"\n+ \"See: https://github.com/AI4S2S/lilio\\n\"\n+ )\n+ if \"history\" in data.attrs.keys():\n+ history += data.attrs[\"history\"]\n+\n+ data.attrs = {\n+ **data.attrs, # Keep original attrs. Conflicts will be overwritten attrs below:\n+ \"lilio_version\": lilio.__version__,\n+ \"lilio_calendar_anchor_date\": calendar.anchor,\n+ \"lilio_calendar_code\": str(calendar),\n+ \"history\": history,\n+ }\n+\n+ data[\"anchor_year\"].attrs = {\n+ \"name\": \"anchor year\",\n+ \"units\": \"year\",\n+ \"description\": (\n+ \"The anchor date is the start of the period you want to forecast, and is \"\n+ \"an abstract date and does not include a year. \"\n+ \"Anchor years are used to create a full date with the anchor date \"\n+ f\"(here: {calendar.anchor}).\"\n+ ),\n+ }\n+ data[\"i_interval\"].attrs = {\n+ \"name\": \"interval index\",\n+ \"units\": \"-\",\n+ \"description\": (\n+ \"The index of each Lilio Calendar interval. Positive values denote \"\n+ \"intervals after the anchor date (targets), while negative values \"\n+ \"represent intervals before the anchor date (precursors).\"\n+ ),\n+ }\n+ data[\"is_target\"].attrs = {\n+ \"name\": \"Target flag\",\n+ \"description\": (\n+ \"Denotes if an interval was marked as a target interval in the\"\n+ \" Lilio Calendar.\"\n+ ),\n+ }\ndiff --git a/lilio/calendar.py b/lilio/calendar.py\nindex 95279cc..0b32e06 100644\n--- a/lilio/calendar.py\n+++ b/lilio/calendar.py\n@@ -10,8 +10,8 @@ from typing import Union\n import pandas as pd\n import xarray as xr\n from pandas.tseries.offsets import DateOffset\n-from . import _plot\n-from . import utils\n+from lilio import _plot\n+from lilio import utils\n \n \n _MappingYears = Tuple[Literal[\"years\"], int, int]\ndiff --git a/lilio/calendar_shifter.py b/lilio/calendar_shifter.py\nindex e7fce9c..ce30769 100644\n--- a/lilio/calendar_shifter.py\n+++ b/lilio/calendar_shifter.py\n@@ -4,8 +4,8 @@ from typing import Dict\n from typing import List\n from typing import Union\n import xarray as xr\n-from . import calendar\n-from . import utils\n+from lilio import calendar\n+from lilio import utils\n from .resampling import resample\n \n \ndiff --git a/lilio/resampling.py b/lilio/resampling.py\nindex f3a449c..2d29ce0 100644\n--- a/lilio/resampling.py\n+++ b/lilio/resampling.py\n@@ -7,8 +7,9 @@ from typing import overload\n import numpy as np\n import pandas as pd\n import xarray as xr\n+from lilio import utils\n+from lilio._attrs import add_attrs\n from lilio.calendar import Calendar\n-from . import utils\n \n \n # List of numpy statistical methods, with a single input argument and a single output.\n@@ -356,5 +357,11 @@ def resample(\n resampled_data = _mark_target_period(resampled_data)\n \n if isinstance(input_data, xr.DataArray):\n- return resampled_data[da_name]\n+ resampled_dataarray = resampled_data[da_name]\n+ resampled_dataarray.attrs = input_data.attrs\n+ add_attrs(resampled_dataarray, calendar)\n+ return resampled_dataarray\n+ if isinstance(input_data, xr.Dataset):\n+ resampled_data.attrs = input_data.attrs\n+ add_attrs(resampled_data, calendar)\n return resampled_data\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 52b93b5..7ae6b05 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -128,7 +128,7 @@ select = [\n \"F\", # pyflakes\n \"B\", # flake8-bugbear\n \"D\", # pydocstyle\n- \"C\", # mccabe complexity\n+ \"C90\", # mccabe complexity\n # \"I\", # isort (autosort not working correctly, disabled for now).\n \"N\", # PEP8-naming\n \"UP\", # pyupgrade (upgrade syntax to current syntax)\n@@ -140,12 +140,13 @@ extend-select = [\n \"D401\", # First line should be in imperative mood\n \"D400\", # First line should end in a period.\n \"D404\", # First word of the docstring should not be 'This'\n+ \"TID252\", # No relative imports (not pep8 compliant)\n ]\n ignore = [\n \"PLR2004\", # magic value used in comparsion (i.e. `if ndays == 28: month_is_feb`).\n ]\n # Allow autofix for all enabled rules (when `--fix`) is provided.\n-fixable = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"]\n+fixable = [\"A\", \"B\", \"C90\", \"D\", \"E\", \"F\", \"TID252\"]\n unfixable = []\n line-length = 88\n exclude = [\"docs\", \"build\"]\n", "test_patch": "diff --git a/tests/test_resample.py b/tests/test_resample.py\nindex 59fed6b..b50380f 100644\n--- a/tests/test_resample.py\n+++ b/tests/test_resample.py\n@@ -209,6 +209,45 @@ class TestResample:\n with pytest.warns(UserWarning):\n resample(cal, dataset)\n \n+ def test_dataset_attrs(self, dummy_calendar, dummy_dataset):\n+ dataset, _ = dummy_dataset\n+ dataset.attrs = {\"history\": \"test_history\", \"other_attrs\": \"abc\"}\n+ cal = dummy_calendar.map_years(2020, 2025)\n+ resampled = resample(cal, dataset)\n+\n+ expected_attrs = [\n+ \"lilio_version\",\n+ \"lilio_calendar_anchor_date\",\n+ \"lilio_calendar_code\",\n+ ]\n+\n+ assert \"test_history\" in resampled.attrs[\"history\"]\n+ assert \"other_attrs\" in resampled.attrs.keys()\n+ for att in expected_attrs:\n+ assert att in resampled.attrs.keys()\n+\n+ def test_dataarray_attrs(self, dummy_calendar, dummy_dataarray):\n+ \"\"\"This is a copy of the previous test, but with dataarray input.\n+\n+ Sadly, fixtures aren't compatible with parameterize. Refactoring the fixtures\n+ could solve this.\n+ \"\"\"\n+ dataarray, _ = dummy_dataarray\n+ dataarray.attrs = {\"history\": \"test_history\", \"other_attrs\": \"abc\"}\n+ cal = dummy_calendar.map_years(2020, 2025)\n+ resampled = resample(cal, dataarray)\n+\n+ expected_attrs = [\n+ \"lilio_version\",\n+ \"lilio_calendar_anchor_date\",\n+ \"lilio_calendar_code\",\n+ ]\n+\n+ assert \"test_history\" in resampled.attrs[\"history\"]\n+ assert \"other_attrs\" in resampled.attrs.keys()\n+ for att in expected_attrs:\n+ assert att in resampled.attrs.keys()\n+\n \n TOO_LOW_FREQ_ERR = r\".*lower time resolution than the calendar.*\"\n TOO_LOW_FREQ_WARN = r\".*input data frequency is very close to the Calendar's freq.*\"\n", "FAIL_TO_PASS": ["tests/test_resample.py::TestResample::test_dataset_attrs[20151020]", "tests/test_resample.py::TestResample::test_dataset_attrs[20191015]", "tests/test_resample.py::TestResample::test_dataarray_attrs[20151020]", "tests/test_resample.py::TestResample::test_dataarray_attrs[20191015]"]}, {"instance_id": "AI4S2S__lilio-58", "base_commit": "416ea560d41b57502cf204fbf4e65e79c21373bf", "gold_patch": "diff --git a/lilio/calendar.py b/lilio/calendar.py\nindex c288ebb..93ee1db 100644\n--- a/lilio/calendar.py\n+++ b/lilio/calendar.py\n@@ -206,10 +206,15 @@ class Calendar:\n self._set_mapping(mapping)\n \n @property\n- def n_targets(self):\n+ def n_targets(self) -> int:\n \"\"\"Return the number of targets.\"\"\"\n return len(self.targets)\n \n+ @property\n+ def n_precursors(self) -> int:\n+ \"\"\"Return the number of precursors.\"\"\"\n+ return len(self.precursors)\n+\n @property\n def anchor(self):\n \"\"\"Return the anchor.\"\"\"\ndiff --git a/lilio/resampling.py b/lilio/resampling.py\nindex b426dbd..aa729d5 100644\n--- a/lilio/resampling.py\n+++ b/lilio/resampling.py\n@@ -335,6 +335,8 @@ def resample(\n \"\"\"\n if calendar.mapping is None:\n raise ValueError(\"Generate a calendar map before calling resample\")\n+ if calendar.n_targets + calendar.n_precursors == 0:\n+ raise ValueError(\"The calendar has no intervals: resampling is not possible.\")\n \n if isinstance(how, str):\n _check_valid_resampling_methods(how)\n", "test_patch": "diff --git a/tests/test_resample.py b/tests/test_resample.py\nindex c39bd68..b68441f 100644\n--- a/tests/test_resample.py\n+++ b/tests/test_resample.py\n@@ -326,6 +326,24 @@ class TestResampleChecks:\n with pytest.raises(ValueError, match=r\".*reserved names..*\"):\n resample(cal, dummy_dataframe.rename(columns={\"data1\": \"anchor_year\"}))\n \n+ def test_empty_calendar(self, dummy_dataframe):\n+ cal = Calendar(anchor=\"Jan\")\n+ cal.map_to_data(dummy_dataframe)\n+ with pytest.raises(ValueError, match=r\".*calendar has no intervals.*\"):\n+ resample(cal, dummy_dataframe)\n+\n+ def test_single_target(self, dummy_dataframe):\n+ cal = Calendar(anchor=\"Jan\")\n+ cal.add_intervals(\"target\", length=\"7d\")\n+ cal.map_to_data(dummy_dataframe)\n+ resample(cal, dummy_dataframe)\n+\n+ def test_single_precursor(self, dummy_dataframe):\n+ cal = Calendar(anchor=\"Jan\")\n+ cal.add_intervals(\"precursor\", length=\"7d\")\n+ cal.map_to_data(dummy_dataframe)\n+ resample(cal, dummy_dataframe)\n+\n \n class TestResampleMethods:\n \"\"\"Test alternative resampling methods.\n", "FAIL_TO_PASS": ["tests/test_resample.py::TestResampleChecks::test_empty_calendar"]}], "all_FAIL_TO_PASS": ["tests/test_resample.py::TestResample::test_dataset_attrs[20151020]", "tests/test_resample.py::TestResample::test_dataset_attrs[20191015]", "tests/test_resample.py::TestResample::test_dataarray_attrs[20151020]", "tests/test_resample.py::TestResample::test_dataarray_attrs[20191015]", "tests/test_resample.py::TestResampleChecks::test_empty_calendar"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "iterative__dvc-767_x2", "level": 2, "source": "swerebench", "repo": "iterative/dvc", "image": "swerebench/sweb.eval.x86_64.iterative_1776_dvc-767:latest", "base_commit": "582cb9e0641528168bcacb002ff43f5736920a00", "num_bugs": 2, "bugs": [{"instance_id": "iterative__dvc-767", "base_commit": "582cb9e0641528168bcacb002ff43f5736920a00", "gold_patch": "diff --git a/dvc/cli.py b/dvc/cli.py\nindex 2ba52bb3f..b40c51ed1 100644\n--- a/dvc/cli.py\n+++ b/dvc/cli.py\n@@ -226,6 +226,17 @@ def parse_args(argv=None):\n 'remove',\n parents=[parent_parser],\n help='Remove outputs of DVC file.')\n+ remove_parser_group = remove_parser.add_mutually_exclusive_group()\n+ remove_parser_group.add_argument('-o',\n+ '--outs',\n+ action='store_true',\n+ default=True,\n+ help='Only remove DVC file outputs.')\n+ remove_parser_group.add_argument('-p',\n+ '--purge',\n+ action='store_true',\n+ default=False,\n+ help='Remove DVC file and all its outputs')\n remove_parser.add_argument('targets',\n nargs='+',\n help='DVC files.')\ndiff --git a/dvc/command/remove.py b/dvc/command/remove.py\nindex 228e3a365..aea78dfdb 100644\n--- a/dvc/command/remove.py\n+++ b/dvc/command/remove.py\n@@ -4,9 +4,10 @@ from dvc.command.common.base import CmdBase\n \n class CmdRemove(CmdBase):\n def run(self):\n+ outs_only = not self.args.purge\n for target in self.args.targets:\n try:\n- self.project.remove(target)\n+ self.project.remove(target, outs_only=outs_only)\n except DvcException as ex:\n self.project.logger.error('Failed to remove {}', ex)\n return 1\ndiff --git a/dvc/project.py b/dvc/project.py\nindex c6f3ae832..05a6c3d36 100644\n--- a/dvc/project.py\n+++ b/dvc/project.py\n@@ -123,13 +123,15 @@ class Project(object):\n stage.dump()\n return stage\n \n- def remove(self, target):\n+ def remove(self, target, outs_only=False):\n if not Stage.is_stage_file(target):\n raise StageNotFoundError(target)\n \n stage = Stage.load(self, target)\n- for out in stage.outs:\n- out.remove()\n+ if outs_only:\n+ stage.remove_outs()\n+ else:\n+ stage.remove()\n \n return stage\n \n", "test_patch": "diff --git a/tests/test_remove.py b/tests/test_remove.py\nindex b6503feab..7ae68f6ee 100644\n--- a/tests/test_remove.py\n+++ b/tests/test_remove.py\n@@ -11,11 +11,17 @@ from tests.basic_env import TestDvc\n class TestRemove(TestDvc):\n def test(self):\n stage = self.dvc.add(self.FOO)\n- stage_removed = self.dvc.remove(stage.path)\n+ stage_removed = self.dvc.remove(stage.path, outs_only=True)\n+\n+ self.assertIsInstance(stage_removed, Stage)\n+ self.assertEqual(stage.path, stage_removed.path)\n+ self.assertFalse(os.path.isfile(self.FOO))\n \n+ stage_removed = self.dvc.remove(stage.path)\n self.assertIsInstance(stage_removed, Stage)\n self.assertEqual(stage.path, stage_removed.path)\n self.assertFalse(os.path.isfile(self.FOO))\n+ self.assertFalse(os.path.exists(stage.path))\n \n \n class TestRemoveNonExistentFile(TestDvc):\n@@ -30,7 +36,7 @@ class TestRemoveDirectory(TestDvc):\n stage_removed = self.dvc.remove(stage_add.path)\n self.assertEqual(stage_add.path, stage_removed.path)\n self.assertFalse(os.path.exists(self.DATA_DIR))\n- self.assertTrue(os.path.exists(stage_removed.path))\n+ self.assertFalse(os.path.exists(stage_removed.path))\n \n \n class TestCmdRemove(TestDvc):\n", "FAIL_TO_PASS": ["tests/test_remove.py::TestRemove::test", "tests/test_remove.py::TestRemoveDirectory::test"]}, {"instance_id": "iterative__dvc-777", "base_commit": "5ea2fd8367b678b38ef699b479f385e401dbaf85", "gold_patch": "diff --git a/dvc/dependency/base.py b/dvc/dependency/base.py\nindex 246bc75b0..525e40209 100644\n--- a/dvc/dependency/base.py\n+++ b/dvc/dependency/base.py\n@@ -11,11 +11,6 @@ class DependencyError(DvcException):\n super(DependencyError, self).__init__('Dependency \\'{}\\' error: {}'.format(path, msg))\n \n \n-class DependencyOutsideOfRepoError(DependencyError):\n- def __init__(self, path):\n- super(DependencyOutsideOfRepoError, self).__init__(path, 'outside of repository')\n-\n-\n class DependencyDoesNotExistError(DependencyError):\n def __init__(self, path):\n super(DependencyDoesNotExistError, self).__init__(path, 'does not exist')\ndiff --git a/dvc/dependency/local.py b/dvc/dependency/local.py\nindex 4fdb3e8fa..081ae81e6 100644\n--- a/dvc/dependency/local.py\n+++ b/dvc/dependency/local.py\n@@ -3,6 +3,11 @@ import schema\n import posixpath\n import ntpath\n \n+try:\n+ from urlparse import urlparse\n+except ImportError:\n+ from urllib.parse import urlparse\n+\n from dvc.dependency.base import *\n from dvc.logger import Logger\n from dvc.utils import remove\n@@ -20,12 +25,17 @@ class DependencyLOCAL(DependencyBase):\n def __init__(self, stage, path, info=None, remote=None):\n self.stage = stage\n self.project = stage.project\n+ self.info = info\n+ self.remote = remote if remote != None else RemoteLOCAL(stage.project, {})\n+\n+ if remote:\n+ path = os.path.join(remote.prefix, urlparse(path).path.lstrip('/'))\n+\n if not os.path.isabs(path):\n- path = self.unixpath(path)\n+ path = self.ospath(path)\n path = os.path.join(stage.cwd, path)\n self.path = os.path.normpath(path)\n- self.info = info\n- self.remote = remote if remote != None else RemoteLOCAL(stage.project, {})\n+\n self.path_info = {'scheme': 'local',\n 'path': self.path}\n \n@@ -54,12 +64,23 @@ class DependencyLOCAL(DependencyBase):\n \n self.info = self.remote.save_info(self.path_info)\n \n+ def ospath(self, path):\n+ if os.name == 'nt':\n+ return self.ntpath(path)\n+ return self.unixpath(path)\n+\n @staticmethod\n def unixpath(path):\n assert not ntpath.isabs(path)\n assert not posixpath.isabs(path)\n return path.replace('\\\\', '/')\n \n+ @staticmethod\n+ def ntpath(path):\n+ assert not ntpath.isabs(path)\n+ assert not posixpath.isabs(path)\n+ return path.replace('/', '\\\\')\n+\n def dumpd(self):\n if self.path.startswith(self.stage.project.root_dir):\n path = self.unixpath(os.path.relpath(self.path, self.stage.cwd))\ndiff --git a/dvc/output/local.py b/dvc/output/local.py\nindex e36ec20e0..53e62e31f 100644\n--- a/dvc/output/local.py\n+++ b/dvc/output/local.py\n@@ -66,10 +66,16 @@ class OutputLOCAL(DependencyLOCAL):\n self.project.logger.debug(msg.format(self.rel_path))\n return\n \n- if self.project.scm.is_tracked(self.path):\n- raise OutputAlreadyTrackedError(self.rel_path)\n+ if self.path.startswith(self.project.root_dir):\n+ if self.project.scm.is_tracked(self.path):\n+ raise OutputAlreadyTrackedError(self.rel_path)\n+\n+ if self.use_cache:\n+ self.project.scm.ignore(self.path)\n \n self.info = self.project.cache.local.save(self.path_info)\n \n- def remove(self):\n+ def remove(self, ignore_remove=False):\n self.remote.remove(self.path_info)\n+ if ignore_remove and self.use_cache:\n+ self.project.scm.ignore_remove(self.path)\ndiff --git a/dvc/remote/local.py b/dvc/remote/local.py\nindex a30d625b1..38901c215 100644\n--- a/dvc/remote/local.py\n+++ b/dvc/remote/local.py\n@@ -35,6 +35,10 @@ class RemoteLOCAL(RemoteBase):\n \n self.state = State(self.cache_dir)\n \n+ @property\n+ def prefix(self):\n+ return self.cache_dir\n+\n def all(self):\n clist = []\n for entry in os.listdir(self.cache_dir):\ndiff --git a/dvc/stage.py b/dvc/stage.py\nindex d1f658526..231677923 100644\n--- a/dvc/stage.py\n+++ b/dvc/stage.py\n@@ -115,14 +115,12 @@ class Stage(object):\n \n return ret\n \n- def remove_outs(self):\n+ def remove_outs(self, ignore_remove=False):\n for out in self.outs:\n- out.remove()\n- if out.use_cache:\n- self.project.scm.ignore_remove(out.path)\n+ out.remove(ignore_remove=ignore_remove)\n \n def remove(self):\n- self.remove_outs()\n+ self.remove_outs(ignore_remove=True)\n os.unlink(self.path)\n \n def reproduce(self, force=False):\n@@ -131,7 +129,7 @@ class Stage(object):\n \n if self.cmd:\n # Removing outputs only if we actually have command to reproduce\n- self.remove_outs()\n+ self.remove_outs(ignore_remove=False)\n \n self.run()\n \n@@ -223,8 +221,6 @@ class Stage(object):\n \n for out in self.outs:\n out.save()\n- if out.use_cache and out.path_info['scheme'] == 'local':\n- self.project.scm.ignore(out.path)\n \n def run(self):\n if not self.is_data_source:\n", "test_patch": "diff --git a/tests/test_repro.py b/tests/test_repro.py\nindex cfc823dca..ff55fc1c0 100644\n--- a/tests/test_repro.py\n+++ b/tests/test_repro.py\n@@ -3,6 +3,7 @@ import yaml\n import stat\n import shutil\n import filecmp\n+import tempfile\n from subprocess import Popen, PIPE\n \n import boto3\n@@ -222,31 +223,47 @@ class TestReproExternalBase(TestDvc):\n def should_test(self):\n return False\n \n+ @property\n+ def cache_scheme(self):\n+ return self.scheme\n+\n+ @property\n+ def scheme(self):\n+ return None\n+\n+ @property\n+ def scheme_sep(self):\n+ return '://'\n+\n+ @property\n+ def sep(self):\n+ return '/'\n+\n def test(self):\n if not self.should_test():\n return\n \n- cache = self.scheme + '://' + self.bucket + '/' + str(uuid.uuid4())\n+ cache = self.scheme + self.scheme_sep + self.bucket + self.sep + str(uuid.uuid4())\n \n- ret = main(['config', 'cache.' + self.scheme, 'myrepo'])\n+ ret = main(['config', 'cache.' + self.cache_scheme, 'myrepo'])\n self.assertEqual(ret, 0)\n ret = main(['remote', 'add', 'myrepo', cache])\n self.assertEqual(ret, 0)\n \n remote_name = 'myremote'\n remote_key = str(uuid.uuid4())\n- remote = self.scheme + '://' + self.bucket + '/' + remote_key\n+ remote = self.scheme + self.scheme_sep + self.bucket + self.sep + remote_key\n \n ret = main(['remote', 'add', remote_name, remote])\n self.assertEqual(ret, 0)\n \n self.dvc = Project('.')\n \n- foo_key = remote_key + '/' + self.FOO\n- bar_key = remote_key + '/' + self.BAR\n+ foo_key = remote_key + self.sep + self.FOO\n+ bar_key = remote_key + self.sep + self.BAR\n \n- foo_path = self.scheme + '://' + self.bucket + '/' + foo_key\n- bar_path = self.scheme + '://' + self.bucket + '/' + bar_key\n+ foo_path = self.scheme + self.scheme_sep + self.bucket + self.sep + foo_key\n+ bar_path = self.scheme + self.scheme_sep + self.bucket + self.sep + bar_key\n \n # Using both plain and remote notation\n out_foo_path = 'remote://' + remote_name + '/' + self.FOO\n@@ -351,6 +368,51 @@ class TestReproExternalHDFS(TestReproExternalBase):\n self.assertEqual(p.returncode, 0)\n \n \n+class TestReproExternalLOCAL(TestReproExternalBase):\n+ def setUp(self):\n+ super(TestReproExternalLOCAL, self).setUp()\n+ self.tmpdir = tempfile.mkdtemp()\n+\n+ def should_test(self):\n+ return True\n+\n+ @property\n+ def cache_scheme(self):\n+ return 'local'\n+\n+ @property\n+ def scheme(self):\n+ return ''\n+\n+ @property\n+ def scheme_sep(self):\n+ return ''\n+\n+ @property\n+ def sep(self):\n+ return os.sep\n+\n+ @property\n+ def bucket(self):\n+ return self.tmpdir\n+\n+ @property\n+ def cmd(self):\n+ if os.name == 'nt':\n+ return 'copy'\n+ return 'cp'\n+\n+ def write(self, bucket, key, body):\n+ path = os.path.join(bucket, key)\n+ dname = os.path.dirname(path)\n+\n+ if not os.path.exists(dname):\n+ os.makedirs(dname)\n+\n+ with open(path, 'w+') as fd:\n+ fd.write(body)\n+\n+\n class TestReproShell(TestDvc):\n def test(self):\n if os.name == 'nt':\n", "FAIL_TO_PASS": ["tests/test_repro.py::TestReproExternalLOCAL::test"]}], "all_FAIL_TO_PASS": ["tests/test_remove.py::TestRemove::test", "tests/test_remove.py::TestRemoveDirectory::test", "tests/test_repro.py::TestReproExternalLOCAL::test"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getsentry__responses-614_x2", "level": 2, "source": "swerebench", "repo": "getsentry/responses", "image": "swerebench/sweb.eval.x86_64.getsentry_1776_responses-614:latest", "base_commit": "b30c13fe1c9a2e60e7e2de7a92322b4d4ad57562", "num_bugs": 2, "bugs": [{"instance_id": "getsentry__responses-614", "base_commit": "b30c13fe1c9a2e60e7e2de7a92322b4d4ad57562", "gold_patch": "diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml\nindex 13e14df..f8566ec 100644\n--- a/.github/workflows/build.yml\n+++ b/.github/workflows/build.yml\n@@ -20,7 +20,7 @@ jobs:\n - run: |\n pip install wheel\n python setup.py bdist_wheel sdist --formats=gztar\n- - uses: actions/upload-artifact@v2\n+ - uses: actions/upload-artifact@v3.1.1\n with:\n name: ${{ github.sha }}\n path: dist/*\ndiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml\nindex 236a25d..f638173 100644\n--- a/.github/workflows/ci.yml\n+++ b/.github/workflows/ci.yml\n@@ -21,7 +21,7 @@ jobs:\n \n - uses: actions/setup-python@v4\n with:\n- python-version: 3.8\n+ python-version: '3.10'\n \n - name: Install dependencies\n run: |\ndiff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml\nindex 0fb53d7..20e0535 100644\n--- a/.pre-commit-config.yaml\n+++ b/.pre-commit-config.yaml\n@@ -1,11 +1,11 @@\n repos:\n - repo: https://github.com/psf/black\n- rev: 22.3.0\n+ rev: 22.12.0\n hooks:\n - id: black\n args: [--line-length=88, --safe]\n - repo: https://github.com/pre-commit/pre-commit-hooks\n- rev: v4.1.0\n+ rev: v4.4.0\n hooks:\n - id: check-case-conflict\n - id: check-merge-conflict\n@@ -15,13 +15,13 @@ repos:\n - id: debug-statements\n - id: requirements-txt-fixer\n - repo: https://github.com/pycqa/isort\n- rev: 5.10.1\n+ rev: 5.11.4\n hooks:\n - id: isort\n name: isort (python)\n args: ['--force-single-line-imports', '--profile', 'black']\n - repo: https://github.com/pycqa/flake8\n- rev: 4.0.1\n+ rev: 6.0.0\n hooks:\n - id: flake8\n args: [ '--max-line-length', '100', '--max-doc-length', '120' ]\ndiff --git a/CHANGES b/CHANGES\nindex fa3e8cc..5542677 100644\n--- a/CHANGES\n+++ b/CHANGES\n@@ -2,8 +2,9 @@\n ------\n \n * Add Python 3.11 support\n-* Fix type annotations of `CallList`.\n+* Fix type annotations of `CallList`. See #593\n * Replaced toml with tomli and tomli-w.\n+* `request` object is attached to any custom exception provided as `Response` `body` argument. See #588\n \n 0.22.0\n ------\ndiff --git a/README.rst b/README.rst\nindex 6610e7e..0e4eec5 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -505,6 +505,8 @@ Request Keyword Arguments Matcher\n To validate request arguments use the ``matchers.request_kwargs_matcher`` function to match\n against the request kwargs.\n \n+Only following arguments are supported: ``timeout``, ``verify``, ``proxies``, ``stream``, ``cert``.\n+\n Note, only arguments provided to ``matchers.request_kwargs_matcher`` will be validated.\n \n .. code-block:: python\ndiff --git a/responses/__init__.py b/responses/__init__.py\nindex 0969312..514392b 100644\n--- a/responses/__init__.py\n+++ b/responses/__init__.py\n@@ -569,6 +569,7 @@ class Response(BaseResponse):\n \n def get_response(self, request: \"PreparedRequest\") -> HTTPResponse:\n if self.body and isinstance(self.body, Exception):\n+ setattr(self.body, \"request\", request)\n raise self.body\n \n headers = self.get_headers()\n", "test_patch": "diff --git a/responses/tests/test_responses.py b/responses/tests/test_responses.py\nindex 53924df..e8197a3 100644\n--- a/responses/tests/test_responses.py\n+++ b/responses/tests/test_responses.py\n@@ -2494,3 +2494,20 @@ class TestMaxRetry:\n \n run()\n assert_reset()\n+\n+\n+def test_request_object_attached_to_exception():\n+ \"\"\"Validate that we attach `request` object to custom exception supplied as body\"\"\"\n+\n+ @responses.activate\n+ def run():\n+ url = \"https://httpbin.org/delay/2\"\n+ responses.get(url, body=requests.ReadTimeout())\n+\n+ try:\n+ requests.get(url, timeout=1)\n+ except requests.ReadTimeout as exc:\n+ assert type(exc.request) == requests.models.PreparedRequest\n+\n+ run()\n+ assert_reset()\n", "FAIL_TO_PASS": ["responses/tests/test_responses.py::test_request_object_attached_to_exception"]}, {"instance_id": "getsentry__responses-622", "base_commit": "faf6dd9afa209e9b3c6b8254ed853ff4067519a1", "gold_patch": "diff --git a/CHANGES b/CHANGES\nindex 5542677..325a044 100644\n--- a/CHANGES\n+++ b/CHANGES\n@@ -5,6 +5,7 @@\n * Fix type annotations of `CallList`. See #593\n * Replaced toml with tomli and tomli-w.\n * `request` object is attached to any custom exception provided as `Response` `body` argument. See #588\n+* Fixed mocked responses leaking between tests when `assert_all_requests_are_fired` and a request was not fired.\n \n 0.22.0\n ------\ndiff --git a/responses/__init__.py b/responses/__init__.py\nindex 937b5c7..a24e12c 100644\n--- a/responses/__init__.py\n+++ b/responses/__init__.py\n@@ -924,8 +924,10 @@ class RequestsMock(object):\n \n def __exit__(self, type: Any, value: Any, traceback: Any) -> bool:\n success = type is None\n- self.stop(allow_assert=success)\n- self.reset()\n+ try:\n+ self.stop(allow_assert=success)\n+ finally:\n+ self.reset()\n return success\n \n @overload\n", "test_patch": "diff --git a/responses/tests/test_responses.py b/responses/tests/test_responses.py\nindex e8197a3..90c1d65 100644\n--- a/responses/tests/test_responses.py\n+++ b/responses/tests/test_responses.py\n@@ -1133,6 +1133,28 @@ def test_assert_all_requests_are_fired():\n assert_reset()\n \n \n+def test_assert_all_requests_fired_multiple():\n+ @responses.activate(assert_all_requests_are_fired=True)\n+ def test_some_function():\n+ # Not all mocks are called so we'll get an AssertionError\n+ responses.add(responses.GET, \"http://other_url\", json={})\n+ responses.add(responses.GET, \"http://some_api\", json={})\n+ requests.get(\"http://some_api\")\n+\n+ @responses.activate(assert_all_requests_are_fired=True)\n+ def test_some_second_function():\n+ # This should pass as mocks should be reset.\n+ responses.add(responses.GET, \"http://some_api\", json={})\n+ requests.get(\"http://some_api\")\n+\n+ with pytest.raises(AssertionError):\n+ test_some_function()\n+ assert_reset()\n+\n+ test_some_second_function()\n+ assert_reset()\n+\n+\n def test_allow_redirects_samehost():\n redirecting_url = \"http://example.com\"\n final_url_path = \"/1\"\n", "FAIL_TO_PASS": ["responses/tests/test_responses.py::test_assert_all_requests_fired_multiple", "responses/tests/test_responses.py::test_allow_redirects_samehost"]}], "all_FAIL_TO_PASS": ["responses/tests/test_responses.py::test_request_object_attached_to_exception", "responses/tests/test_responses.py::test_assert_all_requests_fired_multiple", "responses/tests/test_responses.py::test_allow_redirects_samehost"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "bvanelli__actualpy-108_x2", "level": 2, "source": "swerebench", "repo": "bvanelli/actualpy", "image": "swerebench/sweb.eval.x86_64.bvanelli_1776_actualpy-108:latest", "base_commit": "d2f2878016e5ac7b8aaac65bba42eb44af1a5808", "num_bugs": 2, "bugs": [{"instance_id": "bvanelli__actualpy-108", "base_commit": "d2f2878016e5ac7b8aaac65bba42eb44af1a5808", "gold_patch": "diff --git a/actual/__init__.py b/actual/__init__.py\nindex 89544e1..8bc9879 100644\n--- a/actual/__init__.py\n+++ b/actual/__init__.py\n@@ -37,9 +37,11 @@ from actual.exceptions import (\n from actual.migrations import js_migration_statements\n from actual.protobuf_models import HULC_Client, Message, SyncRequest\n from actual.queries import (\n+ create_transaction,\n get_account,\n get_accounts,\n get_or_create_clock,\n+ get_or_create_payee,\n get_ruleset,\n get_transactions,\n reconcile_transaction,\n@@ -469,7 +471,9 @@ class Actual(ActualServer):\n transactions = get_transactions(self.session, is_parent=True)\n ruleset.run(transactions)\n \n- def _run_bank_sync_account(self, acct: Accounts, start_date: datetime.date) -> List[Transactions]:\n+ def _run_bank_sync_account(\n+ self, acct: Accounts, start_date: datetime.date, is_first_sync: bool\n+ ) -> List[Transactions]:\n sync_method = acct.account_sync_source\n account_id = acct.account_id\n requisition_id = acct.bank.bank_id if sync_method == \"goCardless\" else None\n@@ -500,6 +504,20 @@ class Actual(ActualServer):\n )\n if reconciled.changed():\n imported_transactions.append(reconciled)\n+ if is_first_sync:\n+ current_balance = acct.balance\n+ # actual uses 'startingBalance', that already comes in cents and should be enough for our purposes\n+ # https://github.com/actualbudget/actual/blob/f09f4af667ddd57e031dcdb0d428ae935aa2afad/packages/loot-core/src/server/accounts/sync.ts#L740-L752\n+ expected_balance = new_transactions_data.data.balance\n+ balance_to_use = expected_balance - current_balance\n+ if balance_to_use:\n+ payee = None if acct.offbudget else get_or_create_payee(self.session, \"Starting Balance\")\n+ # get date from the oldest transaction. There seems to be a bug here, and it gets the youngest transaction.\n+ oldest_date = new_transactions[-1].date if new_transactions else datetime.date.today()\n+ reconciled_transaction = create_transaction(\n+ self.session, oldest_date, acct, payee, amount=balance_to_use\n+ )\n+ imported_transactions.insert(0, reconciled_transaction)\n return imported_transactions\n \n def run_bank_sync(\n@@ -509,6 +527,10 @@ class Actual(ActualServer):\n Runs the bank synchronization for the selected account. If missing, all accounts are synchronized. If a\n start_date is provided, is used as a reference, otherwise, the last timestamp of each account will be used. If\n the account does not have any transaction, the last 90 days are considered instead.\n+\n+ If the `start_date` is not provided and the account does not have any transaction, a reconcile transaction will\n+ be generated to match the expected balance of the account. This would correct the account balance with the\n+ remote one.\n \"\"\"\n # if no account is provided, sync all of them, otherwise just the account provided\n if account is None:\n@@ -518,7 +540,8 @@ class Actual(ActualServer):\n accounts = [account]\n imported_transactions = []\n \n- default_start_date = start_date\n+ default_start_date: datetime.date = start_date\n+ is_first_sync: bool = False\n for acct in accounts:\n sync_method = acct.account_sync_source\n account_id = acct.account_id\n@@ -532,7 +555,8 @@ class Actual(ActualServer):\n if all_transactions:\n default_start_date = all_transactions[0].get_date()\n else:\n+ is_first_sync = True\n default_start_date = datetime.date.today() - datetime.timedelta(days=90)\n- transactions = self._run_bank_sync_account(acct, default_start_date)\n+ transactions = self._run_bank_sync_account(acct, default_start_date, is_first_sync)\n imported_transactions.extend(transactions)\n return imported_transactions\ndiff --git a/actual/api/bank_sync.py b/actual/api/bank_sync.py\nindex afd7e87..2a4f645 100644\n--- a/actual/api/bank_sync.py\n+++ b/actual/api/bank_sync.py\n@@ -65,16 +65,16 @@ class Balance(BaseModel):\n \n class TransactionItem(BaseModel):\n transaction_id: str = Field(..., alias=\"transactionId\")\n- booking_date: str = Field(..., alias=\"bookingDate\")\n booked: bool = True\n- value_date: str = Field(..., alias=\"valueDate\")\n transaction_amount: BankSyncAmount = Field(..., alias=\"transactionAmount\")\n # this field will come as either debtorName or creditorName, depending on if it's a debt or credit\n payee: str = Field(None, validation_alias=AliasChoices(\"debtorName\", \"creditorName\"))\n payee_account: Optional[DebtorAccount] = Field(\n None, validation_alias=AliasChoices(\"debtorAccount\", \"creditorAccount\")\n )\n- date: datetime.date\n+ # 'bookingDate' and 'valueDate' can be null or not existing in some goCardless data. Actual does not use them.\n+ # Therefore, we just use them as fallbacks for the date, that should theoretically always exist.\n+ date: datetime.date = Field(..., validation_alias=AliasChoices(\"date\", \"bookingDate\", \"valueDate\"))\n remittance_information_unstructured: str = Field(None, alias=\"remittanceInformationUnstructured\")\n remittance_information_unstructured_array: List[str] = Field(\n default_factory=list, alias=\"remittanceInformationUnstructuredArray\"\n@@ -97,7 +97,7 @@ class TransactionItem(BaseModel):\n notes = self.remittance_information_unstructured or \", \".join(\n self.remittance_information_unstructured_array or []\n )\n- return notes.strip()\n+ return notes.strip().replace(\"#\", \"##\")\n \n \n class Transactions(BaseModel):\n@@ -118,6 +118,10 @@ class BankSyncTransactionData(BaseModel):\n iban: Optional[str] = None\n institution_id: Optional[str] = Field(None, alias=\"institutionId\")\n \n+ @property\n+ def balance(self) -> decimal.Decimal:\n+ return decimal.Decimal(self.starting_balance) / 100\n+\n \n class BankSyncErrorData(BaseModel):\n error_type: str\ndiff --git a/actual/queries.py b/actual/queries.py\nindex 7d95459..a4843f8 100644\n--- a/actual/queries.py\n+++ b/actual/queries.py\n@@ -605,7 +605,8 @@ def get_budgets(\n :param month: month to get budgets for, as a date for that month. Use `datetime.date.today()` if you want the budget\n for current month\n :param category: category to filter for the budget. By default, the query looks for all budgets.\n- :return: list of budgets\n+ :return: list of budgets. It's important to note that budgets will only exist if they are actively set beforehand.\n+ When the frontend shows a budget as 0.00, it might not be returned by this method.\n \"\"\"\n table = _get_budget_table(s)\n query = select(table).options(joinedload(table.category))\n@@ -630,7 +631,8 @@ def get_budget(\n :param month: month to get budgets for, as a date for that month. Use `datetime.date.today()` if you want the budget\n for current month.\n :param category: category to filter for the budget.\n- :return: return budget matching the month and category. If not found, returns `None`.\n+ :return: returns the budget matching the month and category. If not found, returns `None`. If the budget is not\n+ set via frontend, it will show as 0.00, but this function will still return `None`.\n \"\"\"\n budgets = get_budgets(s, month, category)\n return budgets[0] if budgets else None\n", "test_patch": "diff --git a/tests/test_bank_sync.py b/tests/test_bank_sync.py\nindex 094c5d8..4daffa8 100644\n--- a/tests/test_bank_sync.py\n+++ b/tests/test_bank_sync.py\n@@ -17,11 +17,11 @@ response = {\n \"balanceType\": \"expected\",\n \"lastChangeDateTime\": \"2024-06-13T14:56:06.092039915Z\",\n \"referenceDate\": \"2024-06-13\",\n- \"balanceAmount\": {\"amount\": \"0.00\", \"currency\": \"EUR\"},\n+ \"balanceAmount\": {\"amount\": \"1.49\", \"currency\": \"EUR\"},\n }\n ],\n \"institutionId\": \"My Bank\",\n- \"startingBalance\": 0,\n+ \"startingBalance\": 149,\n \"transactions\": {\n \"all\": [\n {\n@@ -72,23 +72,35 @@ def create_accounts(session, protocol: str):\n return bank\n \n \n-@pytest.fixture\n-def set_mocks(mocker):\n- # call for validate\n+def generate_bank_sync_data(mocker, starting_balance: int = None):\n+ response_full = copy.deepcopy(response)\n+ if starting_balance:\n+ response_full[\"startingBalance\"] = starting_balance\n response_empty = copy.deepcopy(response)\n response_empty[\"transactions\"][\"all\"] = []\n mocker.patch.object(Session, \"get\").return_value = RequestsMock({\"status\": \"ok\", \"data\": {\"validated\": True}})\n main_mock = mocker.patch.object(Session, \"post\")\n main_mock.side_effect = [\n RequestsMock({\"status\": \"ok\", \"data\": {\"configured\": True}}),\n- RequestsMock({\"status\": \"ok\", \"data\": response}),\n+ RequestsMock({\"status\": \"ok\", \"data\": response_full}),\n RequestsMock({\"status\": \"ok\", \"data\": {\"configured\": True}}), # in case it gets called again\n RequestsMock({\"status\": \"ok\", \"data\": response_empty}),\n ]\n return main_mock\n \n \n-def test_full_bank_sync_go_cardless(session, set_mocks):\n+@pytest.fixture\n+def bank_sync_data_match(mocker):\n+ # call for validate\n+ return generate_bank_sync_data(mocker)\n+\n+\n+@pytest.fixture\n+def bank_sync_data_no_match(mocker):\n+ return generate_bank_sync_data(mocker, 2500)\n+\n+\n+def test_full_bank_sync_go_cardless(session, bank_sync_data_match):\n with Actual(token=\"foo\") as actual:\n actual._session = session\n create_accounts(session, \"goCardless\")\n@@ -114,10 +126,10 @@ def test_full_bank_sync_go_cardless(session, set_mocks):\n new_imported_transactions = actual.run_bank_sync()\n assert new_imported_transactions == []\n # assert that the call date is correctly set\n- assert set_mocks.call_args_list[3][1][\"json\"][\"startDate\"] == \"2024-06-13\"\n+ assert bank_sync_data_match.call_args_list[3][1][\"json\"][\"startDate\"] == \"2024-06-13\"\n \n \n-def test_full_bank_sync_go_simplefin(session, set_mocks):\n+def test_full_bank_sync_go_simplefin(session, bank_sync_data_match):\n with Actual(token=\"foo\") as actual:\n actual._session = session\n create_accounts(session, \"simplefin\")\n@@ -138,6 +150,19 @@ def test_full_bank_sync_go_simplefin(session, set_mocks):\n assert imported_transactions[1].notes == \"Payment\"\n \n \n+def test_bank_sync_with_starting_balance(session, bank_sync_data_no_match):\n+ with Actual(token=\"foo\") as actual:\n+ actual._session = session\n+ create_accounts(session, \"simplefin\")\n+ # now try to run the bank sync\n+ imported_transactions = actual.run_bank_sync(\"Bank\")\n+ assert len(imported_transactions) == 3\n+ # first transaction should be the amount\n+ assert imported_transactions[0].get_date() == datetime.date(2024, 6, 13)\n+ # final amount is 2500 - (926 - 777) = 2351\n+ assert imported_transactions[0].get_amount() == decimal.Decimal(\"23.51\")\n+\n+\n def test_bank_sync_unconfigured(mocker, session):\n mocker.patch.object(Session, \"get\").return_value = RequestsMock({\"status\": \"ok\", \"data\": {\"validated\": True}})\n main_mock = mocker.patch.object(Session, \"post\")\n", "FAIL_TO_PASS": ["tests/test_bank_sync.py::test_bank_sync_with_starting_balance"]}, {"instance_id": "bvanelli__actualpy-117", "base_commit": "6f124f780a0c517e5cd84dac5af4208073b8056b", "gold_patch": "diff --git a/actual/__init__.py b/actual/__init__.py\nindex 8bc9879..27b4068 100644\n--- a/actual/__init__.py\n+++ b/actual/__init__.py\n@@ -489,6 +489,8 @@ class Actual(ActualServer):\n new_transactions = new_transactions_data.data.transactions.all\n imported_transactions = []\n for transaction in new_transactions:\n+ if not transaction.booked:\n+ continue\n payee = transaction.imported_payee or \"\" if sync_method == \"goCardless\" else transaction.notes\n reconciled = reconcile_transaction(\n self.session,\ndiff --git a/actual/api/bank_sync.py b/actual/api/bank_sync.py\nindex 2a4f645..37e3c31 100644\n--- a/actual/api/bank_sync.py\n+++ b/actual/api/bank_sync.py\n@@ -46,13 +46,21 @@ class DebtorAccount(BaseModel):\n \n \n class BalanceType(enum.Enum):\n+ # See https://developer.gocardless.com/bank-account-data/balance#balance_type for full documentation\n+ CLOSING_AVAILABLE = \"closingAvailable\"\n CLOSING_BOOKED = \"closingBooked\"\n+ CLOSING_CLEARED = \"closingCleared\"\n EXPECTED = \"expected\"\n FORWARD_AVAILABLE = \"forwardAvailable\"\n INTERIM_AVAILABLE = \"interimAvailable\"\n+ INTERIM_CLEARED = \"interimCleared\"\n+ INFORMATION = \"information\"\n INTERIM_BOOKED = \"interimBooked\"\n NON_INVOICED = \"nonInvoiced\"\n OPENING_BOOKED = \"openingBooked\"\n+ OPENING_AVAILABLE = \"openingAvailable\"\n+ OPENING_CLEARED = \"openingCleared\"\n+ PREVIOUSLY_CLOSED_BOOKED = \"previouslyClosedBooked\"\n \n \n class Balance(BaseModel):\n@@ -64,16 +72,18 @@ class Balance(BaseModel):\n \n \n class TransactionItem(BaseModel):\n- transaction_id: str = Field(..., alias=\"transactionId\")\n- booked: bool = True\n+ transaction_id: Optional[str] = Field(None, alias=\"transactionId\")\n+ booked: Optional[bool] = False\n transaction_amount: BankSyncAmount = Field(..., alias=\"transactionAmount\")\n # this field will come as either debtorName or creditorName, depending on if it's a debt or credit\n- payee: str = Field(None, validation_alias=AliasChoices(\"debtorName\", \"creditorName\"))\n+ # The field might not exist, therefore is set as optional with a default\n+ payee: Optional[str] = Field(None, validation_alias=AliasChoices(\"debtorName\", \"creditorName\"))\n payee_account: Optional[DebtorAccount] = Field(\n None, validation_alias=AliasChoices(\"debtorAccount\", \"creditorAccount\")\n )\n # 'bookingDate' and 'valueDate' can be null or not existing in some goCardless data. Actual does not use them.\n # Therefore, we just use them as fallbacks for the date, that should theoretically always exist.\n+ # if the 'bookingDate' does not exist, the 'valueDate' will according to the docs\n date: datetime.date = Field(..., validation_alias=AliasChoices(\"date\", \"bookingDate\", \"valueDate\"))\n remittance_information_unstructured: str = Field(None, alias=\"remittanceInformationUnstructured\")\n remittance_information_unstructured_array: List[str] = Field(\n", "test_patch": "diff --git a/tests/test_bank_sync.py b/tests/test_bank_sync.py\nindex 4daffa8..23597b3 100644\n--- a/tests/test_bank_sync.py\n+++ b/tests/test_bank_sync.py\n@@ -32,6 +32,7 @@ response = {\n \"transactionAmount\": {\"amount\": \"9.26\", \"currency\": \"EUR\"},\n \"debtorName\": \"John Doe\",\n \"remittanceInformationUnstructured\": \"Transferring Money\",\n+ \"booked\": True,\n },\n # some have creditor name\n {\n@@ -48,6 +49,13 @@ response = {\n \"remittanceInformationUnstructuredArray\": [\"Payment\"],\n \"bankTransactionCode\": \"FOO-BAR\",\n \"internalTransactionId\": \"6118268af4dc45039a7ca21b0fdcbe96\",\n+ \"booked\": True,\n+ },\n+ # ignored since booked is set to false, but all required fields are also missing\n+ {\n+ \"date\": \"2024-06-13\",\n+ \"transactionAmount\": {\"amount\": \"-7.77\", \"currency\": \"EUR\"},\n+ \"booked\": False,\n },\n ],\n \"booked\": [],\n", "FAIL_TO_PASS": ["tests/test_bank_sync.py::test_full_bank_sync_go_cardless", "tests/test_bank_sync.py::test_full_bank_sync_go_simplefin", "tests/test_bank_sync.py::test_bank_sync_with_starting_balance"]}], "all_FAIL_TO_PASS": ["tests/test_bank_sync.py::test_bank_sync_with_starting_balance", "tests/test_bank_sync.py::test_full_bank_sync_go_cardless", "tests/test_bank_sync.py::test_full_bank_sync_go_simplefin", "tests/test_bank_sync.py::test_bank_sync_with_starting_balance"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "capsulecorplab__mindgraph-22_x2", "level": 2, "source": "swerebench", "repo": "capsulecorplab/mindgraph", "image": "swerebench/sweb.eval.x86_64.capsulecorplab_1776_mindgraph-22:latest", "base_commit": "cfc9443eda343310c5f2cadb91f61e1849990a05", "num_bugs": 2, "bugs": [{"instance_id": "capsulecorplab__mindgraph-22", "base_commit": "cfc9443eda343310c5f2cadb91f61e1849990a05", "gold_patch": "diff --git a/README.md b/README.md\nindex c80ec3f..644f1cd 100644\n--- a/README.md\n+++ b/README.md\n@@ -20,14 +20,14 @@ $ pip install git+https://github.com/capsulecorplab/mindgraph.git\n ```\n >>> import mindgraph as mg\n \n->>> graph = mg.Graph('learn all the things')\n->>> thing1 = graph.append('1st thing')\n->>> thing2 = graph.append('2nd thing')\n->>> thing3 = graph.append('3rd thing')\n+>>> project = mg.Project('learn all the things')\n+>>> thing1 = project.append('1st thing')\n+>>> thing2 = project.append('2nd thing')\n+>>> thing3 = project.append('3rd thing')\n \n->>> graph.remove(2)\n+>>> project.remove(2)\n \n->>> thing1 = graph[0]\n+>>> thing1 = project[0]\n >>> thing1_1 = thing1.append('thing within a thing')\n >>> thing1_2 = thing1.append('thing blocking a thing')\n >>> thing1_1.blockedby(thing1_2)\n@@ -36,7 +36,7 @@ $ pip install git+https://github.com/capsulecorplab/mindgraph.git\n >>> thing2_2 = thing2.append('another thing blocking a thing')\n >>> thing2_2.blocking(thing2_1)\n \n->>> print(graph)\n+>>> print(project)\n learn all the things:\n - 1st thing:\n - thing within a thing\n@@ -46,11 +46,11 @@ learn all the things:\n - another thing blocking a thing\n ```\n \n-`Graph` objects can be exported to, and imported from, a yaml file for storage:\n+Projects can be exported to, or imported from, a yaml file for external storage:\n \n ```\n->>> graph.to_yaml('mygraph.yaml')\n->>> graph2 = mg.read_yaml('mygraph.yaml')\n+>>> project.to_yaml('myproject.yaml')\n+>>> revivedproject = mg.read_yaml('myproject.yaml')\n ```\n \n ## Contribute\ndiff --git a/mindgraph/graph.py b/mindgraph/graph.py\nindex d7b1769..be55272 100644\n--- a/mindgraph/graph.py\n+++ b/mindgraph/graph.py\n@@ -4,109 +4,106 @@ from typing import (Any, Callable, Generator, Iterator, List, Optional, Set,\n from yaml import dump, load\n \n \n-class Node(object):\n- \"\"\"node class\"\"\"\n+class Task(object):\n+ \"\"\"Task class\"\"\"\n \n- def __init__(self, name: str = '', weight: int = 1) -> None:\n- self._dependencies = list() # type: List[Node]\n- self._threads = list() # type: List[Node]\n+ def __init__(self, name: str = '', priority: int = 1) -> None:\n+ self._blockers = list() # type: List[Task]\n+ self._subtasks = list() # type: List[Task]\n self._name = '' # type: str\n- self._weight = weight # type: int\n+ self._priority = priority # type: int\n if type(name) is str:\n self._name = name\n else:\n raise TypeError\n \n- def append(self, newnode) -> \"Node\":\n- \"\"\" Creates a new Node and appends it to threads \"\"\"\n- if type(newnode) is str:\n- newnode = Node(newnode)\n- elif type(newnode) is not Node:\n+ def append(self, newtask) -> \"Task\":\n+ \"\"\" Creates a new Task and appends it to subtasks \"\"\"\n+ if type(newtask) is str:\n+ newtask = Task(newtask)\n+ elif type(newtask) is not Task:\n raise TypeError\n- self._threads.append(newnode)\n- return newnode\n+ self._subtasks.append(newtask)\n+ return newtask\n \n- def pop(self, index: int) -> \"Node\":\n- \"\"\" Pops the Node from threads[index] \"\"\"\n- return self._threads.pop(index)\n+ def pop(self, index: int) -> \"Task\":\n+ \"\"\" Pops the Task from subtasks[index] \"\"\"\n+ return self._subtasks.pop(index)\n \n- def blockedby(self, node: \"Node\") -> None:\n- \"\"\" Adds a Node to the dependenceis list \"\"\"\n- if type(node) is Node:\n- self._dependencies.append(node)\n+ def blockedby(self, task: \"Task\") -> None:\n+ \"\"\" Adds a task to the subtasks list \"\"\"\n+ if type(task) is Task:\n+ self._blockers.append(task)\n return None\n else:\n raise TypeError\n \n- def blocking(self, node: \"Node\") -> None:\n- \"\"\" Adds this Node to another node's dependencies list \"\"\"\n- if type(node) is Node:\n- node._dependencies.append(self)\n+ def blocking(self, task: \"Task\") -> None:\n+ \"\"\" Adds this task to another task's blockers list \"\"\"\n+ if type(task) is Task:\n+ task._blockers.append(self)\n return None\n else:\n raise TypeError\n \n- def __getitem__(self, key: int) -> \"Node\":\n- return self._threads[key]\n+ def __getitem__(self, key: int) -> \"Task\":\n+ return self._subtasks[key]\n \n def __repr__(self) -> str:\n- return '\\n'.join(self.format_tree())\n+ return '\\n'.join(self._format_tree())\n \n- def format_tree(self: \"Node\", depth: int = 0) -> Iterator[str]:\n- \"\"\"Format node and dependents in tree format, emitting lines\n-\n- Assumes no cycles in graph\n- \"\"\"\n+ def _format_tree(self: \"Task\", depth: int = 0) -> Iterator[str]:\n+ \"\"\"Generates task and subtasks into a string formatted tree\"\"\"\n indent = ' ' * depth\n bullet = '- ' if depth != 0 else ''\n- suffix = ':' if self.threads else ''\n+ suffix = ':' if self.subtasks else ''\n line = '{indent}{bullet}{self.name}{suffix}'.format(**locals())\n \n yield line\n- for n in self.threads:\n- yield from n.format_tree(depth+1)\n+ for n in self.subtasks:\n+ yield from n._format_tree(depth+1)\n \n def _postorder(self,\n depth: int = 0,\n- visited: Set[\"Node\"] = None,\n- node_key: Callable[[\"Node\"], Any]=None,\n- ) -> Generator[Tuple[int, \"Node\"], None, Set[\"Node\"]]:\n- \"\"\"Post-order traversal of graph rooted at node\"\"\"\n+ visited: Set[\"Task\"] = None,\n+ taskkey: Callable[[\"Task\"], Any]=None,\n+ ) -> Generator[Tuple[int, \"Task\"], None, Set[\"Task\"]]:\n+ \"\"\"Post-order traversal of Project rooted at Task\"\"\"\n if visited is None:\n visited = set()\n \n- children = self._threads\n- if node_key is not None:\n- children = sorted(self._threads, key=node_key)\n+ children = self._subtasks\n+ if taskkey is not None:\n+ children = sorted(self._subtasks, key=taskkey)\n \n for child in children:\n if child not in visited:\n visited = yield from child._postorder(depth+1,\n visited,\n- node_key)\n+ taskkey)\n \n yield (depth, self)\n visited.add(self)\n \n return visited\n \n- def todo(self) -> Iterator[\"Node\"]:\n- \"\"\"Generate nodes in todo order\n+ def todo(self) -> Iterator[\"Task\"]:\n+ \"\"\"Generate Tasks in todo order\n \n- Nodes are scheduled by weight and to resolve blocking tasks\n+ Tasks are scheduled by priority and to resolve blocking tasks\n \"\"\"\n- # sorts by weight (2 before 1), then alphabetical\n- def node_key(node):\n- return (-node.weight, node.name)\n- return (x[1] for x in self._postorder(node_key=node_key))\n+ # sorts by priority (2 before 1), then alphabetical\n+ def taskkey(Task):\n+ return (-Task.priority, Task.name)\n+ return (x[1] for x in self._postorder(taskkey=taskkey))\n \n def __str__(self) -> str:\n return dump(load(str(self.__repr__())), default_flow_style=False)\n \n @property\n- def dependencies(self) -> List[\"Node\"]:\n- \"\"\" dependencies getter \"\"\"\n- return self._dependencies\n+ def blockers(self) -> List[\"Task\"]:\n+ \"\"\" blockers getter \"\"\"\n+ return self._blockers\n \n @property\n def name(self) -> str:\n@@ -119,38 +116,37 @@ class Node(object):\n self._name = name\n \n @property\n- def threads(self) -> List[\"Node\"]:\n- \"\"\" threads getter \"\"\"\n- return self._threads\n+ def subtasks(self) -> List[\"Task\"]:\n+ \"\"\" subtasks getter \"\"\"\n+ return self._subtasks\n \n @property\n- def weight(self) -> int:\n- \"\"\" weight getter \"\"\"\n- return self._weight\n-\n- @weight.setter\n- def weight(self, value: int) -> None:\n- \"\"\" weight setter \"\"\"\n- self._weight = value\n-\n+ def priority(self) -> int:\n+ \"\"\" priority getter \"\"\"\n+ return self._priority\n \n-class Graph(Node):\n- \"\"\"A Graph model of the mind\"\"\"\n-\n- def __init__(self, name=None) -> None:\n- Node.__init__(self, name)\n+ @priority.setter\n+ def priority(self, value: int) -> None:\n+ \"\"\" priority setter \"\"\"\n+ self._priority = value\n \n def to_yaml(self, filename=None) -> None:\n- \"\"\" Write this Graph to a yaml file \"\"\"\n+ \"\"\" Write this Project to a yaml file \"\"\"\n with open(filename, 'w') as f:\n f.write(dump(self))\n \n \n-def read_yaml(filename: str = \"\") -> Graph:\n- \"\"\" Load a Graph from a yaml file \"\"\"\n+class Project(object):\n+ \"\"\"Returns a task representing the root of your project\"\"\"\n+ def __new__(cls, name: str=None) -> Task:\n+ return Task(name)\n+\n+\n+def read_yaml(filename: str = \"\") -> Task:\n+ \"\"\" Load a project from a yaml file \"\"\"\n with open(filename, 'r') as f:\n rv = load(f.read())\n- if type(rv) is Graph:\n+ if type(rv) is Task:\n return rv\n else:\n raise TypeError(type(rv))\n", "test_patch": "diff --git a/test/test_mindgraph.py b/test/test_mindgraph.py\nindex 1fc5c76..3a375fa 100644\n--- a/test/test_mindgraph.py\n+++ b/test/test_mindgraph.py\n@@ -11,25 +11,25 @@ from mindgraph import *\n \n \n @pytest.fixture(scope=\"module\")\n-def graph():\n- graph = Graph('learn all the things')\n- return graph\n+def project():\n+ project = Project('learn all the things')\n+ return project\n \n \n @pytest.fixture\n-def task_graph():\n- # setup example graph from issue #14\n- g = Graph('build a thing')\n+def task_project():\n+ # setup example project from issue #14\n+ g = Project('build a thing')\n \n t1 = g.append('task 1')\n- t1.weight = 3\n+ t1.priority = 3\n t11 = t1.append('task 1.1')\n t12 = t1.append('task 1.2')\n t13 = t1.append('task 1.3')\n- t13.weight = 3\n+ t13.priority = 3\n \n t2 = g.append('task 2')\n- t2.weight = 2\n+ t2.priority = 2\n t21 = t2.append('task 2.1')\n t22 = t2.append('task 2.2')\n t221 = t22.append('task 2.2.1')\n@@ -39,111 +39,123 @@ def task_graph():\n t31 = t3.append('task 3.1')\n t32 = t3.append('task 3.2')\n \n- t32.threads.append(t22)\n- t12.threads.append(t22)\n+ t32.subtasks.append(t22)\n+ t12.subtasks.append(t22)\n return g\n \n \n-def test_todo_high_weights_win(task_graph):\n- \"\"\"High weights are scheduled before low weights\"\"\"\n- todo = [n.name for n in task_graph.todo()]\n+def test_todo_high_priorities_win(task_project):\n+ \"\"\"High priorities are scheduled before low priorities\"\"\"\n+ todo = [n.name for n in task_project.todo()]\n assert todo.index('task 1') < todo.index('task 2')\n assert todo.index('task 1') < todo.index('task 3')\n assert todo.index('task 1.3') < todo.index('task 1.1')\n \n \n-def test_todo_blocking_tasks_win(task_graph):\n+def test_todo_blocking_tasks_win(task_project):\n \"\"\"Blocking tasks are scheduled before blocked tasks\"\"\"\n- todo = [n.name for n in task_graph.todo()]\n+ todo = [n.name for n in task_project.todo()]\n assert todo.index('task 2.2') < todo.index('task 3.2')\n assert todo.index('task 2.2') < todo.index('task 1.2')\n assert todo.index('task 1.1') < todo.index('task 1.2')\n \n \n-def test_postorder_default_weights_ignored(task_graph):\n- \"\"\"Post-order traversal ignores node weights by default\"\"\"\n- po = [n.name for _, n in task_graph._postorder()]\n+def test_postorder_default_priorities_ignored(task_project):\n+ \"\"\"Post-order traversal ignores task priorities by default\"\"\"\n+ po = [n.name for _, n in task_project._postorder()]\n assert po.index('task 1.1') < po.index('task 1.3')\n \n \n-def test_node_init_typeerror():\n+def test_task_init_typeerror():\n with pytest.raises(TypeError) as info:\n- node = Node(47)\n+ task = Task(47)\n assert \"\" in str(info.value)\n \n \n-def test_node_append_node():\n- rootNode = Node('root node')\n- subNode1 = rootNode.append(Node('sub node'))\n- subNode2 = rootNode.append(Node('sub node 2'))\n- assert rootNode[0] is subNode1\n- assert rootNode[1] is subNode2\n+def test_task_append_task():\n+ rootTask = Task('root task')\n+ subTask1 = rootTask.append(Task('sub task'))\n+ subTask2 = rootTask.append(Task('sub task 2'))\n+ assert rootTask[0] is subTask1\n+ assert rootTask[1] is subTask2\n \n \n-def test_node_append(graph):\n- thing1 = graph.append('1st thing')\n- thing2 = graph.append('2nd thing')\n- thing3 = graph.append('3rd thing')\n+def test_task_append(project):\n+ thing1 = project.append('1st thing')\n+ thing2 = project.append('2nd thing')\n+ thing3 = project.append('3rd thing')\n \n- assert thing1 is graph[0]\n- assert thing2 is graph[1]\n- assert thing3 is graph[2]\n+ assert thing1 is project[0]\n+ assert thing2 is project[1]\n+ assert thing3 is project[2]\n \n assert thing1.name == '1st thing'\n assert thing2.name == '2nd thing'\n assert thing3.name == '3rd thing'\n \n \n-def test_node_pop(graph):\n- assert graph[2].name == '3rd thing'\n- graph.pop(2)\n+def test_task_pop(project):\n+ assert project[2].name == '3rd thing'\n+ project.pop(2)\n with pytest.raises(IndexError) as info:\n- thing3 = graph[2]\n+ thing3 = project[2]\n assert \"\" in str(info.value)\n \n \n-def test_node_pop_fail1(graph):\n+def test_task_pop_fail1(project):\n with pytest.raises(IndexError):\n- graph.pop(20000)\n+ project.pop(20000)\n \n \n-def test_node_append_TypeError():\n+def test_task_append_TypeError():\n with pytest.raises(TypeError) as info:\n- node = Node('mynode')\n- node.append(47)\n+ task = Task('mytask')\n+ task.append(47)\n assert \"\" in str(info.value)\n \n \n-def test_blockedby(graph):\n- thing1 = graph[0]\n+def test_blockedby(project):\n+ thing1 = project[0]\n thing1_1 = thing1.append('thing within a thing')\n thing1_2 = thing1.append('thing blocking a thing')\n thing1_1.blockedby(thing1_2)\n- assert thing1_1.dependencies[0].name == 'thing blocking a thing'\n+ assert thing1_1.blockers[0].name == 'thing blocking a thing'\n \n \n-def test_blocking(graph):\n- thing2 = graph[1]\n+def test_blockedby_TypeError():\n+ with pytest.raises(TypeError):\n+ task = Task('mytask')\n+ task.blockedby(47)\n+\n+\n+def test_blocking(project):\n+ thing2 = project[1]\n thing2_1 = thing2.append('another thing within a thing')\n thing2_2 = thing2.append('another thing blocking a thing')\n thing2_2.blocking(thing2_1)\n- assert thing2_1.dependencies[0].name == 'another thing blocking a thing'\n+ assert thing2_1.blockers[0].name == 'another thing blocking a thing'\n+\n+\n+def test_blocking_TypeError():\n+ with pytest.raises(TypeError):\n+ task = Task('mytask')\n+ task.blocking(47)\n \n \n-def test_repr(graph):\n- assert graph.name == 'learn all the things'\n+def test_repr(project):\n+ assert project.name == 'learn all the things'\n \n- thing1 = graph[0]\n- thing2 = graph[1]\n+ thing1 = project[0]\n+ thing2 = project[1]\n \n with pytest.raises(IndexError) as info:\n- thing3 = graph[2]\n+ thing3 = project[2]\n assert \"\" in str(info.value)\n \n assert thing1.name == '1st thing'\n assert thing2.name == '2nd thing'\n \n- assert str(graph) == \"\".join([\n+ assert str(project) == \"\".join([\n \"learn all the things:\\n\",\n \"- 1st thing:\\n\",\n \" - thing within a thing\\n\",\n@@ -154,14 +166,14 @@ def test_repr(graph):\n ])\n \n \n-def test_deep_repr(graph):\n+def test_deep_repr(project):\n \n- thing2_1 = graph[1][0]\n+ thing2_1 = project[1][0]\n assert thing2_1.name == 'another thing within a thing'\n \n thing2_1.append('super deep thing')\n \n- assert str(graph) == \"\".join([\n+ assert str(project) == \"\".join([\n \"learn all the things:\\n\",\n \"- 1st thing:\\n\",\n \" - thing within a thing\\n\",\n@@ -175,42 +187,42 @@ def test_deep_repr(graph):\n thing2_1.pop(0)\n \n \n-def test_weight_getter_setter():\n- node = Node('myNode')\n- default_weight = node.weight\n- node.weight = 5\n+def test_priority_getter_setter():\n+ task = Task('myTask')\n+ default_priority = task.priority\n+ task.priority = 5\n \n- assert default_weight == 1\n- assert node.weight == 5\n+ assert default_priority == 1\n+ assert task.priority == 5\n \n \n def test_name_getter_setter():\n- node = Node()\n- default_name = node.name\n- node.name = 'a new name'\n+ task = Task()\n+ default_name = task.name\n+ task.name = 'a new name'\n \n assert default_name == ''\n- assert node.name == 'a new name'\n+ assert task.name == 'a new name'\n \n \n-def test_to_yaml(graph):\n- assert graph.name == 'learn all the things'\n- assert graph[0].name == '1st thing'\n- graph.to_yaml('mindgraph.yaml')\n- graph2 = read_yaml('mindgraph.yaml')\n- test_repr(graph2)\n- assert repr(graph) == repr(graph2)\n- os.remove('mindgraph.yaml')\n+def test_to_yaml(project):\n+ assert project.name == 'learn all the things'\n+ assert project[0].name == '1st thing'\n+ project.to_yaml('project.yaml')\n+ project2 = read_yaml('project.yaml')\n+ test_repr(project2)\n+ assert repr(project) == repr(project2)\n+ os.remove('project.yaml')\n \n \n def test_to_yaml_TypeError():\n- not_a_graph = yaml.dump(\"not a graph\")\n- with open('not_a_graph.yaml', 'w') as f:\n- f.write(not_a_graph)\n+ not_a_project = yaml.dump(\"not a project\")\n+ with open('not_a_project.yaml', 'w') as f:\n+ f.write(not_a_project)\n with pytest.raises(TypeError) as info:\n- read_yaml('not_a_graph.yaml')\n+ read_yaml('not_a_project.yaml')\n assert \"\" in str(info.value)\n- os.remove('not_a_graph.yaml')\n+ os.remove('not_a_project.yaml')\n \n \n def test_parser():\n", "FAIL_TO_PASS": ["test/test_mindgraph.py::test_todo_high_priorities_win", "test/test_mindgraph.py::test_todo_blocking_tasks_win", "test/test_mindgraph.py::test_postorder_default_priorities_ignored", "test/test_mindgraph.py::test_task_init_typeerror", "test/test_mindgraph.py::test_task_append_task", "test/test_mindgraph.py::test_task_append", "test/test_mindgraph.py::test_task_pop", "test/test_mindgraph.py::test_task_pop_fail1", "test/test_mindgraph.py::test_task_append_TypeError", "test/test_mindgraph.py::test_blockedby", "test/test_mindgraph.py::test_blockedby_TypeError", "test/test_mindgraph.py::test_blocking", "test/test_mindgraph.py::test_blocking_TypeError", "test/test_mindgraph.py::test_priority_getter_setter", "test/test_mindgraph.py::test_name_getter_setter"]}, {"instance_id": "capsulecorplab__mindgraph-23", "base_commit": "aa05682130d34c308f699936d16299b5029d26ab", "gold_patch": "diff --git a/mindgraph/graph.py b/mindgraph/graph.py\nindex be55272..c1dc475 100644\n--- a/mindgraph/graph.py\n+++ b/mindgraph/graph.py\n@@ -1,6 +1,6 @@\n # -*- coding: utf-8 -*-\n-from typing import (Any, Callable, Generator, Iterator, List, Optional, Set,\n- Tuple)\n+from typing import Any, Callable, Iterator, List, Set, Tuple\n+\n from yaml import dump, load\n \n \n@@ -67,34 +67,36 @@ class Task(object):\n depth: int = 0,\n visited: Set[\"Task\"] = None,\n taskkey: Callable[[\"Task\"], Any]=None,\n- ) -> Generator[Tuple[int, \"Task\"], None, Set[\"Task\"]]:\n+ ) -> Iterator[Tuple[int, \"Task\"]]:\n \"\"\"Post-order traversal of Project rooted at Task\"\"\"\n+ from itertools import chain\n+\n if visited is None:\n visited = set()\n \n- children = self._subtasks\n- if taskkey is not None:\n- children = sorted(self._subtasks, key=taskkey)\n+ if taskkey is None:\n+ blockers = self.blockers\n+ subtasks = self.subtasks\n+ else:\n+ blockers = sorted(self.blockers, key=taskkey)\n+ subtasks = sorted(self.subtasks, key=taskkey)\n \n- for child in children:\n- if child not in visited:\n- visited = yield from child._postorder(depth+1,\n- visited,\n- taskkey)\n+ for node in chain(blockers, subtasks):\n+ if node in visited:\n+ continue\n+ yield from node._postorder(depth+1, visited, taskkey)\n \n yield (depth, self)\n visited.add(self)\n \n- return visited\n-\n def todo(self) -> Iterator[\"Task\"]:\n \"\"\"Generate Tasks in todo order\n \n Tasks are scheduled by priority and to resolve blocking tasks\n \"\"\"\n # sorts by priority (2 before 1), then alphabetical\n- def taskkey(Task):\n- return (-Task.priority, Task.name)\n+ def taskkey(task):\n+ return (-task.priority, task.name)\n return (x[1] for x in self._postorder(taskkey=taskkey))\n \n def __str__(self) -> str:\n", "test_patch": "diff --git a/test/test_mindgraph.py b/test/test_mindgraph.py\nindex 3a375fa..368b7a3 100644\n--- a/test/test_mindgraph.py\n+++ b/test/test_mindgraph.py\n@@ -1,10 +1,10 @@\n import os\n-from random import choice\n import string\n from argparse import Namespace\n+from random import choice\n+from unittest.mock import mock_open, patch\n \n import pytest\n-from unittest.mock import mock_open, patch\n import yaml\n \n from mindgraph import *\n@@ -39,8 +39,8 @@ def task_project():\n t31 = t3.append('task 3.1')\n t32 = t3.append('task 3.2')\n \n- t32.subtasks.append(t22)\n- t12.subtasks.append(t22)\n+ t32.blockedby(t22)\n+ t12.blockedby(t22)\n return g\n \n \n", "FAIL_TO_PASS": ["test/test_mindgraph.py::test_todo_blocking_tasks_win"]}], "all_FAIL_TO_PASS": ["test/test_mindgraph.py::test_todo_high_priorities_win", "test/test_mindgraph.py::test_todo_blocking_tasks_win", "test/test_mindgraph.py::test_postorder_default_priorities_ignored", "test/test_mindgraph.py::test_task_init_typeerror", "test/test_mindgraph.py::test_task_append_task", "test/test_mindgraph.py::test_task_append", "test/test_mindgraph.py::test_task_pop", "test/test_mindgraph.py::test_task_pop_fail1", "test/test_mindgraph.py::test_task_append_TypeError", "test/test_mindgraph.py::test_blockedby", "test/test_mindgraph.py::test_blockedby_TypeError", "test/test_mindgraph.py::test_blocking", "test/test_mindgraph.py::test_blocking_TypeError", "test/test_mindgraph.py::test_priority_getter_setter", "test/test_mindgraph.py::test_name_getter_setter", "test/test_mindgraph.py::test_todo_blocking_tasks_win"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "fabfuel__ecs-deploy-79_x2", "level": 2, "source": "swerebench", "repo": "fabfuel/ecs-deploy", "image": "swerebench/sweb.eval.x86_64.fabfuel_1776_ecs-deploy-79:latest", "base_commit": "f489ac92fe2cf9ead5bedac68e852fadc6d68778", "num_bugs": 2, "bugs": [{"instance_id": "fabfuel__ecs-deploy-79", "base_commit": "f489ac92fe2cf9ead5bedac68e852fadc6d68778", "gold_patch": "diff --git a/README.rst b/README.rst\nindex a5e3451..c6602be 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -162,6 +162,16 @@ This will modify the definition **of two containers**.\n The **webserver**'s environment variable `SOME_VARIABLE` will be set to \"SOME_VALUE\" and the variable `OTHER_VARIABLE` to \"OTHER_VALUE\".\n The **app**'s environment variable `APP_VARIABLE` will be set to \"APP_VALUE\".\n \n+\n+Set environment variables exclusively, remove all other pre-existing environment variables\n+==========================================================================================\n+To reset all existing environment variables of a task definition, use the flag ``--exclusive-env`` ::\n+\n+ $ ecs deploy my-cluster my-service -e webserver SOME_VARIABLE SOME_VALUE --exclusive-env\n+\n+This will remove **all other** existing environment variables of **all containers** of the task definition, except for the variable `SOME_VARIABLE` with the value \"SOME_VALUE\" in the webserver container.\n+\n+\n Set a secret environment variable from the AWS Parameter Store\n ==============================================================\n \n@@ -178,6 +188,16 @@ You can also specify the full arn of the parameter::\n \n This will modify the **webserver** container definition and add or overwrite the environment variable `SOME_SECRET` with the value of the `KEY_OF_SECRET_IN_PARAMETER_STORE` in the AWS Parameter Store of the AWS Systems Manager.\n \n+\n+Set secrets exclusively, remove all other pre-existing secret environment variables\n+===================================================================================\n+To reset all existing secrets (secret environment variables) of a task definition, use the flag ``--exclusive-secrets`` ::\n+\n+ $ ecs deploy my-cluster my-service -s webserver NEW_SECRET KEY_OF_SECRET_IN_PARAMETER_STORE --exclusive-secret\n+\n+This will remove **all other** existing secret environment variables of **all containers** of the task definition, except for the new secret variable `NEW_SECRET` with the value coming from the AWS Parameter Store with the name \"KEY_OF_SECRET_IN_PARAMETER_STORE\" in the webserver container.\n+\n+\n Modify a command\n ================\n To change the command of a specific container, run the following command::\ndiff --git a/ecs_deploy/cli.py b/ecs_deploy/cli.py\nindex 3b9e9d9..45cdfee 100644\n--- a/ecs_deploy/cli.py\n+++ b/ecs_deploy/cli.py\n@@ -46,7 +46,9 @@ def get_client(access_key_id, secret_access_key, region, profile):\n @click.option('--diff/--no-diff', default=True, help='Print which values were changed in the task definition (default: --diff)')\n @click.option('--deregister/--no-deregister', default=True, help='Deregister or keep the old task definition (default: --deregister)')\n @click.option('--rollback/--no-rollback', default=False, help='Rollback to previous revision, if deployment failed (default: --no-rollback)')\n-def deploy(cluster, service, tag, image, command, env, secret, role, task, region, access_key_id, secret_access_key, profile, timeout, newrelic_apikey, newrelic_appid, comment, user, ignore_warnings, diff, deregister, rollback):\n+@click.option('--exclusive-env', is_flag=True, default=False, help='Set the given environment variables exclusively and remove all other pre-existing env variables from all containers')\n+@click.option('--exclusive-secrets', is_flag=True, default=False, help='Set the given secrets exclusively and remove all other pre-existing secrets from all containers')\n+def deploy(cluster, service, tag, image, command, env, secret, role, task, region, access_key_id, secret_access_key, profile, timeout, newrelic_apikey, newrelic_appid, comment, user, ignore_warnings, diff, deregister, rollback, exclusive_env, exclusive_secrets):\n \"\"\"\n Redeploy or modify a service.\n \n@@ -66,8 +68,8 @@ def deploy(cluster, service, tag, image, command, env, secret, role, task, regio\n td = get_task_definition(deployment, task)\n td.set_images(tag, **{key: value for (key, value) in image})\n td.set_commands(**{key: value for (key, value) in command})\n- td.set_environment(env)\n- td.set_secrets(secret)\n+ td.set_environment(env, exclusive_env)\n+ td.set_secrets(secret, exclusive_secrets)\n td.set_role_arn(role)\n \n if diff:\ndiff --git a/ecs_deploy/ecs.py b/ecs_deploy/ecs.py\nindex 74cf19a..9136bdd 100644\n--- a/ecs_deploy/ecs.py\n+++ b/ecs_deploy/ecs.py\n@@ -241,7 +241,7 @@ class EcsTaskDefinition(object):\n self._diff.append(diff)\n container[u'command'] = new_command.split(\" \")\n \n- def set_environment(self, environment_list):\n+ def set_environment(self, environment_list, exclusive=False):\n environment = {}\n \n for env in environment_list:\n@@ -253,14 +253,25 @@ class EcsTaskDefinition(object):\n if container[u'name'] in environment:\n self.apply_container_environment(\n container=container,\n- new_environment=environment[container[u'name']]\n+ new_environment=environment[container[u'name']],\n+ exclusive=exclusive,\n+ )\n+ elif exclusive is True:\n+ self.apply_container_environment(\n+ container=container,\n+ new_environment={},\n+ exclusive=exclusive,\n )\n \n- def apply_container_environment(self, container, new_environment):\n+ def apply_container_environment(self, container, new_environment, exclusive=False):\n environment = container.get('environment', {})\n old_environment = {env['name']: env['value'] for env in environment}\n- merged = old_environment.copy()\n- merged.update(new_environment)\n+\n+ if exclusive is True:\n+ merged = new_environment\n+ else:\n+ merged = old_environment.copy()\n+ merged.update(new_environment)\n \n if old_environment == merged:\n return\n@@ -277,7 +288,7 @@ class EcsTaskDefinition(object):\n {\"name\": e, \"value\": merged[e]} for e in merged\n ]\n \n- def set_secrets(self, secrets_list):\n+ def set_secrets(self, secrets_list, exclusive=False):\n secrets = {}\n \n for secret in secrets_list:\n@@ -289,14 +300,25 @@ class EcsTaskDefinition(object):\n if container[u'name'] in secrets:\n self.apply_container_secrets(\n container=container,\n- new_secrets=secrets[container[u'name']]\n+ new_secrets=secrets[container[u'name']],\n+ exclusive=exclusive,\n+ )\n+ elif exclusive is True:\n+ self.apply_container_secrets(\n+ container=container,\n+ new_secrets={},\n+ exclusive=exclusive,\n )\n \n- def apply_container_secrets(self, container, new_secrets):\n+ def apply_container_secrets(self, container, new_secrets, exclusive=False):\n secrets = container.get('secrets', {})\n old_secrets = {secret['name']: secret['valueFrom'] for secret in secrets}\n- merged = old_secrets.copy()\n- merged.update(new_secrets)\n+\n+ if exclusive is True:\n+ merged = new_secrets\n+ else:\n+ merged = old_secrets.copy()\n+ merged.update(new_secrets)\n \n if old_secrets == merged:\n return\n@@ -369,23 +391,33 @@ class EcsTaskDefinitionDiff(object):\n @staticmethod\n def _get_environment_diffs(container, env, old_env):\n msg = u'Changed environment \"%s\" of container \"%s\" to: \"%s\"'\n+ msg_removed = u'Removed environment \"%s\" of container \"%s\"'\n diffs = []\n for name, value in env.items():\n old_value = old_env.get(name)\n if value != old_value or not old_value:\n message = msg % (name, container, value)\n diffs.append(message)\n+ for old_name in old_env.keys():\n+ if old_name not in env.keys():\n+ message = msg_removed % (old_name, container)\n+ diffs.append(message)\n return diffs\n \n @staticmethod\n def _get_secrets_diffs(container, secrets, old_secrets):\n msg = u'Changed secret \"%s\" of container \"%s\" to: \"%s\"'\n+ msg_removed = u'Removed secret \"%s\" of container \"%s\"'\n diffs = []\n for name, value in secrets.items():\n old_value = old_secrets.get(name)\n if value != old_value or not old_value:\n message = msg % (name, container, value)\n diffs.append(message)\n+ for old_name in old_secrets.keys():\n+ if old_name not in secrets.keys():\n+ message = msg_removed % (old_name, container)\n+ diffs.append(message)\n return diffs\n \n \n", "test_patch": "diff --git a/tests/test_cli.py b/tests/test_cli.py\nindex 8922286..79150b1 100644\n--- a/tests/test_cli.py\n+++ b/tests/test_cli.py\n@@ -253,6 +253,52 @@ def test_deploy_empty_environment_variable_again(get_client, runner):\n assert u'Deployment successful' in result.output\n \n \n+@patch('ecs_deploy.cli.get_client')\n+def test_deploy_exclusive_environment(get_client, runner):\n+ get_client.return_value = EcsTestClient('acces_key', 'secret_key')\n+ result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '-e', 'webserver', 'new-env', 'new-value', '--exclusive-env'))\n+\n+ assert result.exit_code == 0\n+ assert not result.exception\n+\n+ assert u\"Deploying based on task definition: test-task:1\" in result.output\n+ assert u\"Updating task definition\" in result.output\n+ assert u'Changed environment \"new-env\" of container \"webserver\" to: \"new-value\"' in result.output\n+\n+ assert u'Removed environment \"foo\" of container \"webserver\"' in result.output\n+ assert u'Removed environment \"lorem\" of container \"webserver\"' in result.output\n+\n+ assert u'Removed secret' not in result.output\n+\n+ assert u'Successfully created revision: 2' in result.output\n+ assert u'Successfully deregistered revision: 1' in result.output\n+ assert u'Successfully changed task definition to: test-task:2' in result.output\n+ assert u'Deployment successful' in result.output\n+\n+\n+@patch('ecs_deploy.cli.get_client')\n+def test_deploy_exclusive_secret(get_client, runner):\n+ get_client.return_value = EcsTestClient('acces_key', 'secret_key')\n+ result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '-s', 'webserver', 'new-secret', 'new-place', '--exclusive-secrets'))\n+\n+ assert result.exit_code == 0\n+ assert not result.exception\n+\n+ assert u\"Deploying based on task definition: test-task:1\" in result.output\n+ assert u\"Updating task definition\" in result.output\n+ assert u'Changed secret \"new-secret\" of container \"webserver\" to: \"new-place\"' in result.output\n+\n+ assert u'Removed secret \"baz\" of container \"webserver\"' in result.output\n+ assert u'Removed secret \"dolor\" of container \"webserver\"' in result.output\n+\n+ assert u'Removed environment' not in result.output\n+\n+ assert u'Successfully created revision: 2' in result.output\n+ assert u'Successfully deregistered revision: 1' in result.output\n+ assert u'Successfully changed task definition to: test-task:2' in result.output\n+ assert u'Deployment successful' in result.output\n+\n+\n @patch('ecs_deploy.cli.get_client')\n def test_deploy_one_new_secret_variable(get_client, runner):\n get_client.return_value = EcsTestClient('acces_key', 'secret_key')\ndiff --git a/tests/test_ecs.py b/tests/test_ecs.py\nindex 6634188..c93372b 100644\n--- a/tests/test_ecs.py\n+++ b/tests/test_ecs.py\n@@ -28,7 +28,7 @@ TASK_DEFINITION_CONTAINERS_1 = [\n {u'name': u'webserver', u'image': u'webserver:123', u'command': u'run',\n u'environment': ({\"name\": \"foo\", \"value\": \"bar\"}, {\"name\": \"lorem\", \"value\": \"ipsum\"}, {\"name\": \"empty\", \"value\": \"\"}),\n u'secrets': ({\"name\": \"baz\", \"valueFrom\": \"qux\"}, {\"name\": \"dolor\", \"valueFrom\": \"sit\"})},\n- {u'name': u'application', u'image': u'application:123', u'command': u'run'}\n+ {u'name': u'application', u'image': u'application:123', u'command': u'run', u'environment': ()}\n ]\n TASK_DEFINITION_FAMILY_2 = u'test-task'\n TASK_DEFINITION_REVISION_2 = 2\n@@ -39,7 +39,7 @@ TASK_DEFINITION_CONTAINERS_2 = [\n {u'name': u'webserver', u'image': u'webserver:123', u'command': u'run',\n u'environment': ({\"name\": \"foo\", \"value\": \"bar\"}, {\"name\": \"lorem\", \"value\": \"ipsum\"}, {\"name\": \"empty\", \"value\": \"\"}),\n u'secrets': ({\"name\": \"baz\", \"valueFrom\": \"qux\"}, {\"name\": \"dolor\", \"valueFrom\": \"sit\"})},\n- {u'name': u'application', u'image': u'application:123', u'command': u'run'}\n+ {u'name': u'application', u'image': u'application:123', u'command': u'run', u'environment': ()}\n ]\n \n PAYLOAD_TASK_DEFINITION_1 = {\n@@ -310,12 +310,40 @@ def test_task_set_image(task_definition):\n \n \n def test_task_set_environment(task_definition):\n+ assert len(task_definition.containers[0]['environment']) == 3\n+\n task_definition.set_environment(((u'webserver', u'foo', u'baz'), (u'webserver', u'some-name', u'some-value')))\n \n+ assert len(task_definition.containers[0]['environment']) == 4\n+\n assert {'name': 'lorem', 'value': 'ipsum'} in task_definition.containers[0]['environment']\n assert {'name': 'foo', 'value': 'baz'} in task_definition.containers[0]['environment']\n assert {'name': 'some-name', 'value': 'some-value'} in task_definition.containers[0]['environment']\n \n+\n+def test_task_set_environment_exclusively(task_definition):\n+ assert len(task_definition.containers[0]['environment']) == 3\n+ assert len(task_definition.containers[1]['environment']) == 0\n+\n+ task_definition.set_environment(((u'application', u'foo', u'baz'), (u'application', u'new-var', u'new-value')), exclusive=True)\n+\n+ assert len(task_definition.containers[0]['environment']) == 0\n+ assert len(task_definition.containers[1]['environment']) == 2\n+\n+ assert task_definition.containers[0]['environment'] == []\n+ assert {'name': 'foo', 'value': 'baz'} in task_definition.containers[1]['environment']\n+ assert {'name': 'new-var', 'value': 'new-value'} in task_definition.containers[1]['environment']\n+\n+\n+def test_task_set_secrets_exclusively(task_definition):\n+ assert len(task_definition.containers[0]['secrets']) == 2\n+\n+ task_definition.set_secrets(((u'webserver', u'new-secret', u'another-place'), ), exclusive=True)\n+\n+ assert len(task_definition.containers[0]['secrets']) == 1\n+ assert {'name': 'new-secret', 'valueFrom': 'another-place'} in task_definition.containers[0]['secrets']\n+\n+\n def test_task_set_secrets(task_definition):\n task_definition.set_secrets(((u'webserver', u'foo', u'baz'), (u'webserver', u'some-name', u'some-value')))\n \n@@ -323,6 +351,7 @@ def test_task_set_secrets(task_definition):\n assert {'name': 'foo', 'valueFrom': 'baz'} in task_definition.containers[0]['secrets']\n assert {'name': 'some-name', 'valueFrom': 'some-value'} in task_definition.containers[0]['secrets']\n \n+\n def test_task_set_image_for_unknown_container(task_definition):\n with pytest.raises(UnknownContainerError):\n task_definition.set_images(foobar=u'new-image:123')\n@@ -336,6 +365,7 @@ def test_task_set_command(task_definition):\n if container[u'name'] == u'application':\n assert container[u'command'] == [u'run-application']\n \n+\n def test_task_set_command_with_multiple_arguments(task_definition):\n task_definition.set_commands(webserver=u'run-webserver arg1 arg2', application=u'run-application arg1 arg2')\n for container in task_definition.containers:\n", "FAIL_TO_PASS": ["tests/test_cli.py::test_deploy_exclusive_environment", "tests/test_cli.py::test_deploy_exclusive_secret", "tests/test_ecs.py::test_task_set_environment_exclusively", "tests/test_ecs.py::test_task_set_secrets_exclusively"]}, {"instance_id": "fabfuel__ecs-deploy-81", "base_commit": "5a098eb69b19476f7befcb8b1a58213238b648d7", "gold_patch": "diff --git a/README.rst b/README.rst\nindex c6602be..ccbd4a7 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -238,6 +238,13 @@ To ignore these warnings, you can run the deployment with the flag ``--ignore-wa\n In that case, the warning is printed, but the script continues and waits for a successful\n deployment until it times out.\n \n+Deployment timeout\n+==================\n+The deploy and scale actions allow defining a timeout (in seconds) via the ``--timeout`` parameter.\n+This instructs ecs-deploy to wait for ECS to finish the deployment for the given number of seconds.\n+\n+To run a deployment without waiting for the successful or failed result at all, set ``--timeout`` to the value of ``-1``.\n+\n Scaling\n -------\n \ndiff --git a/ecs_deploy/cli.py b/ecs_deploy/cli.py\nindex 45cdfee..869a0bc 100644\n--- a/ecs_deploy/cli.py\n+++ b/ecs_deploy/cli.py\n@@ -37,7 +37,7 @@ def get_client(access_key_id, secret_access_key, region, profile):\n @click.option('--access-key-id', required=False, help='AWS access key id')\n @click.option('--secret-access-key', required=False, help='AWS secret access key')\n @click.option('--profile', required=False, help='AWS configuration profile name')\n-@click.option('--timeout', required=False, default=300, type=int, help='Amount of seconds to wait for deployment before command fails (default: 300)')\n+@click.option('--timeout', required=False, default=300, type=int, help='Amount of seconds to wait for deployment before command fails (default: 300). To disable timeout (fire and forget) set to -1')\n @click.option('--ignore-warnings', is_flag=True, help='Do not fail deployment on warnings (port already in use or insufficient memory/CPU)')\n @click.option('--newrelic-apikey', required=False, help='New Relic API Key for recording the deployment')\n @click.option('--newrelic-appid', required=False, help='New Relic App ID for recording the deployment')\n@@ -113,7 +113,7 @@ def deploy(cluster, service, tag, image, command, env, secret, role, task, regio\n @click.option('--access-key-id', help='AWS access key id')\n @click.option('--secret-access-key', help='AWS secret access key')\n @click.option('--profile', help='AWS configuration profile name')\n-@click.option('--timeout', default=300, type=int, help='AWS configuration profile')\n+@click.option('--timeout', default=300, type=int, help='Amount of seconds to wait for deployment before command fails (default: 300). To disable timeout (fire and forget) set to -1')\n @click.option('--ignore-warnings', is_flag=True, help='Do not fail deployment on warnings (port already in use or insufficient memory/CPU)')\n def scale(cluster, service, desired_count, access_key_id, secret_access_key, region, profile, timeout, ignore_warnings):\n \"\"\"\n@@ -202,10 +202,15 @@ def run(cluster, task, count, command, env, secret, region, access_key_id, secre\n def wait_for_finish(action, timeout, title, success_message, failure_message,\n ignore_warnings):\n click.secho(title, nl=False)\n- waiting = True\n waiting_timeout = datetime.now() + timedelta(seconds=timeout)\n service = action.get_service()\n inspected_until = None\n+\n+ if timeout == -1:\n+ waiting = False\n+ else:\n+ waiting = True\n+\n while waiting and datetime.now() < waiting_timeout:\n click.secho('.', nl=False)\n service = action.get_service()\n", "test_patch": "diff --git a/tests/test_cli.py b/tests/test_cli.py\nindex 043a894..d29f1de 100644\n--- a/tests/test_cli.py\n+++ b/tests/test_cli.py\n@@ -1,3 +1,5 @@\n+from datetime import datetime\n+\n import pytest\n from click.testing import CliRunner\n from mock.mock import patch\n@@ -484,6 +486,30 @@ def test_deploy_with_timeout(get_client, runner):\n u\"https://github.com/fabfuel/ecs-deploy#timeout\" in result.output\n \n \n+@patch('ecs_deploy.cli.get_client')\n+def test_deploy_with_wait_within_timeout(get_client, runner):\n+ get_client.return_value = EcsTestClient('acces_key', 'secret_key', wait=2)\n+ result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '--timeout', '10'))\n+ assert result.exit_code == 0\n+ assert u'Deploying new task definition...' in result.output\n+\n+\n+@patch('ecs_deploy.cli.get_client')\n+def test_deploy_without_timeout(get_client, runner):\n+ get_client.return_value = EcsTestClient('acces_key', 'secret_key', wait=2)\n+\n+ start_time = datetime.now()\n+ result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '--timeout', '-1'))\n+ end_time = datetime.now()\n+\n+ assert result.exit_code == 0\n+\n+ # assert task is not waiting for deployment\n+ assert u'Deploying new task definition\\n' in result.output\n+ assert u'...' not in result.output\n+ assert (end_time - start_time).total_seconds() < 1\n+\n+\n @patch('ecs_deploy.cli.get_client')\n def test_deploy_unknown_task_definition_arn(get_client, runner):\n get_client.return_value = EcsTestClient('acces_key', 'secret_key')\n", "FAIL_TO_PASS": ["tests/test_cli.py::test_deploy_without_timeout"]}], "all_FAIL_TO_PASS": ["tests/test_cli.py::test_deploy_exclusive_environment", "tests/test_cli.py::test_deploy_exclusive_secret", "tests/test_ecs.py::test_task_set_environment_exclusively", "tests/test_ecs.py::test_task_set_secrets_exclusively", "tests/test_cli.py::test_deploy_without_timeout"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "camptocamp__python-geoservercloud-51_x2", "level": 2, "source": "swerebench", "repo": "camptocamp/python-geoservercloud", "image": "swerebench/sweb.eval.x86_64.camptocamp_1776_python-geoservercloud-51:latest", "base_commit": "77747913c8a6342d35b1471a3b987c12b1e171f0", "num_bugs": 2, "bugs": [{"instance_id": "camptocamp__python-geoservercloud-51", "base_commit": "77747913c8a6342d35b1471a3b987c12b1e171f0", "gold_patch": "diff --git a/geoservercloud/models/featuretype.py b/geoservercloud/models/featuretype.py\nindex ea35a47..2b761d4 100644\n--- a/geoservercloud/models/featuretype.py\n+++ b/geoservercloud/models/featuretype.py\n@@ -140,6 +140,8 @@ class FeatureType(EntityModel):\n projection_policy=feature_type[\"projectionPolicy\"],\n service_configuration=feature_type[\"serviceConfiguration\"],\n advertised=feature_type.get(\"advertised\"),\n+ native_bounding_box=feature_type.get(\"nativeBoundingBox\"),\n+ lat_lon_bounding_box=feature_type.get(\"latLonBoundingBox\"),\n encode_measures=feature_type.get(\"encodeMeasures\"),\n forced_decimals=feature_type.get(\"forcedDecimals\"),\n simple_conversion_enabled=feature_type.get(\"simpleConversionEnabled\"),\n", "test_patch": "diff --git a/tests/models/test_featuretype.py b/tests/models/test_featuretype.py\nindex 1a7364e..100a112 100644\n--- a/tests/models/test_featuretype.py\n+++ b/tests/models/test_featuretype.py\n@@ -134,7 +134,21 @@ def test_featuretype_from_get_response_payload():\n \"enabled\": True,\n \"advertised\": True,\n \"projectionPolicy\": \"FORCE_DECLARED\",\n- \"srs\": \"EPSG:4326\",\n+ \"srs\": \"EPSG:2056\",\n+ \"nativeBoundingBox\": {\n+ \"minx\": 2485014.052451379,\n+ \"maxx\": 2837016.9329778464,\n+ \"miny\": 1074188.6943776933,\n+ \"maxy\": 1299782.763494124,\n+ \"crs\": {\"@class\": \"projected\", \"$\": \"EPSG:2056\"},\n+ },\n+ \"latLonBoundingBox\": {\n+ \"minx\": 5.902662003204146,\n+ \"maxx\": 10.603307860867739,\n+ \"miny\": 45.7779277267225,\n+ \"maxy\": 47.8485348773655,\n+ \"crs\": \"EPSG:4326\",\n+ },\n \"title\": \"Test Title\",\n \"abstract\": \"Test Abstract\",\n \"keywords\": {\"string\": [\"keyword1\", \"keyword2\"]},\n@@ -176,7 +190,21 @@ def test_featuretype_from_get_response_payload():\n assert feature_type.native_name == \"test_native_name\"\n assert feature_type.store_name == \"test_store\"\n assert feature_type.workspace_name == \"test_workspace\"\n- assert feature_type.srs == \"EPSG:4326\"\n+ assert feature_type.srs == \"EPSG:2056\"\n+ assert feature_type.native_bounding_box == {\n+ \"minx\": 2485014.052451379,\n+ \"maxx\": 2837016.9329778464,\n+ \"miny\": 1074188.6943776933,\n+ \"maxy\": 1299782.763494124,\n+ \"crs\": {\"@class\": \"projected\", \"$\": \"EPSG:2056\"},\n+ }\n+ assert feature_type.lat_lon_bounding_box == {\n+ \"minx\": 5.902662003204146,\n+ \"maxx\": 10.603307860867739,\n+ \"miny\": 45.7779277267225,\n+ \"maxy\": 47.8485348773655,\n+ \"crs\": \"EPSG:4326\",\n+ }\n assert feature_type.title.asdict()[\"title\"] == \"Test Title\"\n assert feature_type.abstract.asdict()[\"abstract\"] == \"Test Abstract\"\n assert feature_type.keywords == [\"keyword1\", \"keyword2\"]\n", "FAIL_TO_PASS": ["tests/models/test_featuretype.py::test_featuretype_from_get_response_payload"]}, {"instance_id": "camptocamp__python-geoservercloud-52", "base_commit": "3df141679ce7f33851294ff1348fa113ec62d304", "gold_patch": "diff --git a/geoservercloud/models/featuretype.py b/geoservercloud/models/featuretype.py\nindex 2b761d4..d117d47 100644\n--- a/geoservercloud/models/featuretype.py\n+++ b/geoservercloud/models/featuretype.py\n@@ -41,7 +41,7 @@ class FeatureType(EntityModel):\n namespace_name: str | None = None,\n title: dict[str, str] | str | None = None,\n abstract: dict[str, str] | str | None = None,\n- keywords: list[str] | None = [],\n+ keywords: list[str] | None = None,\n native_bounding_box: dict[str, Any] | None = None,\n lat_lon_bounding_box: dict[str, Any] | None = None,\n attributes: list[dict[str, Any]] | None = None,\n@@ -130,7 +130,6 @@ class FeatureType(EntityModel):\n title=title,\n abstract=abstract,\n srs=feature_type[\"srs\"],\n- keywords=feature_type[\"keywords\"][\"string\"],\n attributes=feature_type[\"attributes\"][\"attribute\"],\n metadata_links=metadata_links,\n enabled=feature_type[\"enabled\"],\n@@ -142,6 +141,7 @@ class FeatureType(EntityModel):\n advertised=feature_type.get(\"advertised\"),\n native_bounding_box=feature_type.get(\"nativeBoundingBox\"),\n lat_lon_bounding_box=feature_type.get(\"latLonBoundingBox\"),\n+ keywords=feature_type.get(\"keywords\", {}).get(\"string\", []),\n encode_measures=feature_type.get(\"encodeMeasures\"),\n forced_decimals=feature_type.get(\"forcedDecimals\"),\n simple_conversion_enabled=feature_type.get(\"simpleConversionEnabled\"),\n@@ -194,8 +194,10 @@ class FeatureType(EntityModel):\n \n def post_payload(self) -> dict[str, Any]:\n content = self.asdict()\n- content[\"attributes\"] = {\"attribute\": self.attributes}\n- content[\"keywords\"] = {\"string\": self.keywords}\n+ if self.attributes is not None:\n+ content[\"attributes\"] = {\"attribute\": self.attributes}\n+ if self.keywords is not None:\n+ content[\"keywords\"] = {\"string\": self.keywords}\n return {\"featureType\": content}\n \n def put_payload(self) -> dict[str, Any]:\n", "test_patch": "diff --git a/tests/models/test_featuretype.py b/tests/models/test_featuretype.py\nindex 100a112..b1ce5f3 100644\n--- a/tests/models/test_featuretype.py\n+++ b/tests/models/test_featuretype.py\n@@ -252,3 +252,29 @@ def test_featuretype_repr():\n expected_repr = json.dumps(feature_type.post_payload(), indent=4)\n \n assert repr(feature_type) == expected_repr\n+\n+\n+def test_featuretype_create_no_keyword():\n+ feature_type = FeatureType(\n+ namespace_name=\"test_namespace\",\n+ workspace_name=\"test_workspace\",\n+ store_name=\"test_store\",\n+ name=\"test_name\",\n+ native_name=\"test_native_name\",\n+ keywords=None,\n+ )\n+\n+ assert feature_type.post_payload()[\"featureType\"].get(\"keywords\") is None\n+\n+ feature_type = FeatureType(\n+ namespace_name=\"test_namespace\",\n+ workspace_name=\"test_workspace\",\n+ store_name=\"test_store\",\n+ name=\"test_name\",\n+ native_name=\"test_native_name\",\n+ keywords=[],\n+ )\n+\n+ assert (\n+ feature_type.post_payload()[\"featureType\"].get(\"keywords\").get(\"string\") == []\n+ )\n", "FAIL_TO_PASS": ["tests/models/test_featuretype.py::test_featuretype_create_no_keyword"]}], "all_FAIL_TO_PASS": ["tests/models/test_featuretype.py::test_featuretype_from_get_response_payload", "tests/models/test_featuretype.py::test_featuretype_create_no_keyword"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "iterative__dvc-4196_x2", "level": 2, "source": "swerebench", "repo": "iterative/dvc", "image": "swerebench/sweb.eval.x86_64.iterative_1776_dvc-4196:latest", "base_commit": "71c478755399b049101ab9400e7f48dda2a47597", "num_bugs": 2, "bugs": [{"instance_id": "iterative__dvc-4196", "base_commit": "71c478755399b049101ab9400e7f48dda2a47597", "gold_patch": "diff --git a/dvc/command/checkout.py b/dvc/command/checkout.py\nindex ecc750e62..3752342e1 100644\n--- a/dvc/command/checkout.py\n+++ b/dvc/command/checkout.py\n@@ -112,7 +112,9 @@ def add_parser(subparsers, parent_parser):\n checkout_parser.add_argument(\n \"targets\",\n nargs=\"*\",\n- help=\"DVC-files to checkout. Optional. \"\n- \"(Finds all DVC-files in the workspace by default.)\",\n+ help=(\n+ \"Limit command scope to these tracked files/directories, \"\n+ \".dvc files, or stage names.\"\n+ ),\n ).complete = completion.DVC_FILE\n checkout_parser.set_defaults(func=CmdCheckout)\ndiff --git a/dvc/command/data_sync.py b/dvc/command/data_sync.py\nindex 3701c59d9..5b931177e 100644\n--- a/dvc/command/data_sync.py\n+++ b/dvc/command/data_sync.py\n@@ -103,8 +103,10 @@ def shared_parent_parser():\n parent_parser.add_argument(\n \"targets\",\n nargs=\"*\",\n- help=\"Limit command scope to these DVC-files. \"\n- \"Using -R, directories to search DVC-files in can also be given.\",\n+ help=(\n+ \"Limit command scope to these tracked files/directories, \"\n+ \".dvc files, or stage names.\"\n+ ),\n ).complete = completion.DVC_FILE\n \n return parent_parser\ndiff --git a/dvc/dvcfile.py b/dvc/dvcfile.py\nindex 8269edaa8..5b0f2f38c 100644\n--- a/dvc/dvcfile.py\n+++ b/dvc/dvcfile.py\n@@ -233,7 +233,11 @@ class PipelineFile(FileMixin):\n \n logger.debug(\"Removing '%s' from '%s'\", stage.name, self.path)\n del d[\"stages\"][stage.name]\n- dump_yaml(self.path, d)\n+\n+ if d[\"stages\"]:\n+ dump_yaml(self.path, d)\n+ else:\n+ super().remove()\n \n \n class Lockfile(FileMixin):\n@@ -286,7 +290,10 @@ class Lockfile(FileMixin):\n logger.debug(\"Removing '%s' from '%s'\", stage.name, self.path)\n del d[stage.name]\n \n- dump_yaml(self.path, d)\n+ if d:\n+ dump_yaml(self.path, d)\n+ else:\n+ self.remove()\n \n \n class Dvcfile:\ndiff --git a/dvc/version.py b/dvc/version.py\nindex 8a041adb4..158982c60 100644\n--- a/dvc/version.py\n+++ b/dvc/version.py\n@@ -6,7 +6,7 @@\n import os\n import subprocess\n \n-_BASE_VERSION = \"1.1.9\"\n+_BASE_VERSION = \"1.1.10\"\n \n \n def _generate_version(base_version):\n", "test_patch": "diff --git a/tests/func/test_dvcfile.py b/tests/func/test_dvcfile.py\nindex 8c7978d64..5ba42a093 100644\n--- a/tests/func/test_dvcfile.py\n+++ b/tests/func/test_dvcfile.py\n@@ -285,6 +285,23 @@ def test_remove_stage_preserves_comment(tmp_dir, dvc, run_copy):\n )\n \n \n+def test_remove_stage_removes_dvcfiles_if_no_stages_left(\n+ tmp_dir, dvc, run_copy\n+):\n+ tmp_dir.gen(\"foo\", \"foo\")\n+ run_copy(\"foo\", \"bar\", name=\"run_copy\")\n+\n+ dvc_file = Dvcfile(dvc, PIPELINE_FILE)\n+\n+ assert dvc_file.exists()\n+ assert (tmp_dir / PIPELINE_LOCK).exists()\n+ assert (tmp_dir / \"foo\").exists()\n+\n+ dvc_file.remove_stage(dvc_file.stages[\"run_copy\"])\n+ assert not dvc_file.exists()\n+ assert not (tmp_dir / PIPELINE_LOCK).exists()\n+\n+\n def test_dvcfile_dump_preserves_meta(tmp_dir, dvc, run_copy):\n tmp_dir.gen(\"foo\", \"foo\")\n stage = run_copy(\"foo\", \"bar\", name=\"run_copy\")\n", "FAIL_TO_PASS": ["tests/func/test_dvcfile.py::test_remove_stage_removes_dvcfiles_if_no_stages_left"]}, {"instance_id": "iterative__dvc-4204", "base_commit": "c1b04b88fac76ed49b9591288f885e38a9cfe48c", "gold_patch": "diff --git a/dvc/external_repo.py b/dvc/external_repo.py\nindex 5f2232147..809d04b9c 100644\n--- a/dvc/external_repo.py\n+++ b/dvc/external_repo.py\n@@ -72,6 +72,9 @@ class BaseExternalRepo:\n \n _local_cache = None\n \n+ def __str__(self):\n+ return self.url\n+\n @property\n def local_cache(self):\n if hasattr(self, \"cache\"):\ndiff --git a/dvc/repo/tree.py b/dvc/repo/tree.py\nindex 1b12ad68e..1639d144a 100644\n--- a/dvc/repo/tree.py\n+++ b/dvc/repo/tree.py\n@@ -44,6 +44,7 @@ class DvcTree(BaseTree): # pylint:disable=abstract-method\n return outs\n \n def _get_granular_checksum(self, path, out, remote=None):\n+ assert isinstance(path, PathInfo)\n if not self.fetch and not self.stream:\n raise FileNotFoundError\n dir_cache = out.get_dir_cache(remote=remote)\n@@ -128,7 +129,7 @@ class DvcTree(BaseTree): # pylint:disable=abstract-method\n # for dir checksum, we need to check if this is a file inside the\n # directory\n try:\n- self._get_granular_checksum(path, out)\n+ self._get_granular_checksum(path_info, out)\n return False\n except FileNotFoundError:\n return True\n", "test_patch": "diff --git a/tests/func/test_ls.py b/tests/func/test_ls.py\nindex 14d57acf1..85dd9eb1b 100644\n--- a/tests/func/test_ls.py\n+++ b/tests/func/test_ls.py\n@@ -472,3 +472,33 @@ def test_ls_granular(erepo_dir):\n {\"isout\": False, \"isdir\": False, \"isexec\": False, \"path\": \"2\"},\n {\"isout\": False, \"isdir\": True, \"isexec\": False, \"path\": \"subdir\"},\n ]\n+\n+\n+@pytest.mark.parametrize(\"use_scm\", [True, False])\n+def test_ls_target(erepo_dir, use_scm):\n+ with erepo_dir.chdir():\n+ gen = erepo_dir.scm_gen if use_scm else erepo_dir.dvc_gen\n+ gen(\n+ {\n+ \"dir\": {\n+ \"1\": \"1\",\n+ \"2\": \"2\",\n+ \"subdir\": {\"foo\": \"foo\", \"bar\": \"bar\"},\n+ }\n+ },\n+ commit=\"create dir\",\n+ )\n+\n+ def _ls(path):\n+ return Repo.ls(os.fspath(erepo_dir), path)\n+\n+ assert _ls(os.path.join(\"dir\", \"1\")) == [\n+ {\"isout\": False, \"isdir\": False, \"isexec\": False, \"path\": \"1\"}\n+ ]\n+ assert _ls(os.path.join(\"dir\", \"subdir\", \"foo\")) == [\n+ {\"isout\": False, \"isdir\": False, \"isexec\": False, \"path\": \"foo\"}\n+ ]\n+ assert _ls(os.path.join(\"dir\", \"subdir\")) == [\n+ {\"isdir\": False, \"isexec\": 0, \"isout\": False, \"path\": \"bar\"},\n+ {\"isdir\": False, \"isexec\": 0, \"isout\": False, \"path\": \"foo\"},\n+ ]\ndiff --git a/tests/func/test_tree.py b/tests/func/test_tree.py\nindex ebfd9aea6..8cb49d10d 100644\n--- a/tests/func/test_tree.py\n+++ b/tests/func/test_tree.py\n@@ -211,7 +211,7 @@ def test_repotree_cache_save(tmp_dir, dvc, scm, erepo_dir, local_cloud):\n # into dvc.cache, not fetched or streamed from a remote\n tree = RepoTree(erepo_dir.dvc, stream=True)\n expected = [\n- tree.get_file_hash(erepo_dir / path)\n+ tree.get_file_hash(PathInfo(erepo_dir / path))\n for path in (\"dir/bar\", \"dir/subdir/foo\")\n ]\n \n", "FAIL_TO_PASS": ["tests/func/test_ls.py::test_ls_target[False]"]}], "all_FAIL_TO_PASS": ["tests/func/test_dvcfile.py::test_remove_stage_removes_dvcfiles_if_no_stages_left", "tests/func/test_ls.py::test_ls_target[False]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jamesoff__simplemonitor-539_x2", "level": 2, "source": "swerebench", "repo": "jamesoff/simplemonitor", "image": "swerebench/sweb.eval.x86_64.jamesoff_1776_simplemonitor-539:latest", "base_commit": "d1204fb82128ffd2b64ecc88ac429966a29e338b", "num_bugs": 2, "bugs": [{"instance_id": "jamesoff__simplemonitor-539", "base_commit": "d1204fb82128ffd2b64ecc88ac429966a29e338b", "gold_patch": "diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml\nindex 05a5247..b08fa7b 100644\n--- a/.github/workflows/main.yml\n+++ b/.github/workflows/main.yml\n@@ -38,3 +38,4 @@ jobs:\n run: make network-test\n - name: Upload to codecov\n run: pipenv run codecov --token=\"${{ secrets.CODECOV_TOKEN }}\"\n+ - uses: codecov/codecov-action@v1\ndiff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml\nindex 6345ace..980bf96 100644\n--- a/.github/workflows/windows.yml\n+++ b/.github/workflows/windows.yml\n@@ -32,5 +32,4 @@ jobs:\n run: make integration-tests\n - name: Unit tests\n run: make unit-test\n- - name: Upload to codecov\n- run: pipenv run codecov\n+ - uses: codecov/codecov-action@v1\ndiff --git a/docs/alerting.md b/docs/alerting.md\nindex 5f8005f..5448953 100644\n--- a/docs/alerting.md\n+++ b/docs/alerting.md\n@@ -37,6 +37,7 @@ The section name should be the name of your alerter. This is the name you should\n | ooh_success | makes an alerter trigger its success action even if out-of-hours (0 or 1) | no | 0 |\n | groups | comma-separated list of group names this alerter will fire for. See the `group` setting for monitors | no | `default` |\n | only_failures | set to 1 to only fire this alerters for failure notifications (or catchups), not recoveries | no | 0 |\n+| tz | timezone to use in alert messages | no | UTC |\n \n The *limit* uses the virtual fail count of a monitor, which means if a monitor has a tolerance of 3 and the alerter has a limit of 2, the monitor must fail 5 times before an alert is sent.\n \ndiff --git a/simplemonitor/Alerters/alerter.py b/simplemonitor/Alerters/alerter.py\nindex 34373af..4d0a3b7 100644\n--- a/simplemonitor/Alerters/alerter.py\n+++ b/simplemonitor/Alerters/alerter.py\n@@ -158,6 +158,7 @@ class Alerter:\n self._only_failures = self.get_config_option(\n \"only_failures\", required_type=bool, default=False\n )\n+ self._tz = cast(str, self.get_config_option(\"tz\", default=\"UTC\"))\n \n if self._ooh_failures is None:\n self._ooh_failures = []\n@@ -311,9 +312,8 @@ class Alerter:\n else:\n return \"unknowned\"\n \n- @staticmethod\n def build_message(\n- length: AlertLength, alert_type: AlertType, monitor: Monitor\n+ self, length: AlertLength, alert_type: AlertType, monitor: Monitor\n ) -> str:\n \"\"\"Create a message for an Alerter to send.\"\"\"\n if monitor.state() == MonitorState.FAILED:\n@@ -336,7 +336,7 @@ class Alerter:\n alert_type=alert_type.value,\n alert_verb=Alerter._get_verb(alert_type),\n downtime=downtime,\n- failure_time=format_datetime(monitor.first_failure_time()),\n+ failure_time=format_datetime(monitor.first_failure_time(), self._tz),\n monitor=monitor,\n result=monitor.get_result(),\n )\n@@ -384,13 +384,13 @@ class Alerter:\n alert_type=alert_type,\n monitor=monitor,\n alert_verb=Alerter._get_verb(alert_type),\n- failure_time=format_datetime(monitor.first_failure_time()),\n+ failure_time=format_datetime(monitor.first_failure_time(), self._tz),\n downtime=downtime,\n result=monitor.get_result(),\n host=host,\n desc=monitor.describe(),\n vfc=monitor.virtual_fail_count(),\n- recovered_time=format_datetime(monitor.last_update),\n+ recovered_time=format_datetime(monitor.last_update, self._tz),\n )\n message = textwrap.dedent(message)\n else:\n", "test_patch": "diff --git a/tests/test_alerter.py b/tests/test_alerter.py\nindex 3da5bda..f568b9d 100644\n--- a/tests/test_alerter.py\n+++ b/tests/test_alerter.py\n@@ -297,12 +297,17 @@ class TestAlerter(unittest.TestCase):\n \n \n class TestMessageBuilding(unittest.TestCase):\n+ def setUp(self):\n+ self.test_alerter = alerter.Alerter()\n+ self.freeze_time_value = \"2020-03-10 09:00\"\n+ self.expected_time_string = \"2020-03-10 09:00:00+00:00\"\n+\n def test_notification_format_failure(self):\n m = monitor.MonitorFail(\"test\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n m.run_test()\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.NOTIFICATION, alerter.AlertType.FAILURE, m\n ),\n \"Monitor test failed\",\n@@ -310,11 +315,11 @@ class TestMessageBuilding(unittest.TestCase):\n \n def test_notification_format_success(self):\n m = monitor.MonitorNull(\"winning\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n for _ in range(0, 6):\n m.run_test()\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.NOTIFICATION, alerter.AlertType.SUCCESS, m\n ),\n \"Monitor winning succeeded\",\n@@ -322,20 +327,21 @@ class TestMessageBuilding(unittest.TestCase):\n \n def test_oneline_format_failure(self):\n m = monitor.MonitorFail(\"test\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n m.run_test()\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.ONELINE, alerter.AlertType.FAILURE, m\n ),\n- \"failure: test failed on {hostname} at 2020-03-10 09:00:00+00:00 (0+00:00:00): This monitor always fails.\".format(\n- hostname=util.short_hostname()\n+ \"failure: test failed on {hostname} at {expected_time} (0+00:00:00): This monitor always fails.\".format(\n+ hostname=util.short_hostname(),\n+ expected_time=self.expected_time_string,\n ),\n )\n \n def test_oneline_format_success(self):\n m = monitor.MonitorNull(\"winning\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n for _ in range(0, 6):\n m.run_test()\n m.last_result = \"a \" * 80\n@@ -345,32 +351,33 @@ class TestMessageBuilding(unittest.TestCase):\n )\n + \"a \" * 80\n )\n- output = alerter.Alerter.build_message(\n+ output = self.test_alerter.build_message(\n alerter.AlertLength.ONELINE, alerter.AlertType.SUCCESS, m\n )\n self.assertEqual(desired, output)\n \n def test_sms_format_failure(self):\n m = monitor.MonitorFail(\"test\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n m.run_test()\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.SMS, alerter.AlertType.FAILURE, m\n ),\n- \"failure: test failed on {hostname} at 2020-03-10 09:00:00+00:00 (0+00:00:00): This monitor always fails.\".format(\n- hostname=util.short_hostname()\n+ \"failure: test failed on {hostname} at {expected_time} (0+00:00:00): This monitor always fails.\".format(\n+ hostname=util.short_hostname(),\n+ expected_time=self.expected_time_string,\n ),\n )\n \n def test_sms_format_success(self):\n m = monitor.MonitorNull(\"winning\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n for _ in range(0, 6):\n m.run_test()\n m.last_result = \"a \" * 80\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.SMS, alerter.AlertType.SUCCESS, m\n ),\n \"success: winning succeeded on {hostname} at (0+00:00:00): a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a...\".format(\n@@ -380,69 +387,79 @@ class TestMessageBuilding(unittest.TestCase):\n \n def test_full_format_failure(self):\n m = monitor.MonitorFail(\"test\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n m.run_test()\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.FULL, alerter.AlertType.FAILURE, m\n ),\n textwrap.dedent(\n \"\"\"\n Monitor test on {hostname} failed!\n- Failed at: 2020-03-10 09:00:00+00:00 (down 0+00:00:00)\n+ Failed at: {expected_time} (down 0+00:00:00)\n Virtual failure count: 1\n Additional info: This monitor always fails.\n Description: A monitor which always fails.\n \"\"\".format(\n- hostname=util.short_hostname()\n+ hostname=util.short_hostname(),\n+ expected_time=self.expected_time_string,\n )\n ),\n )\n \n def test_full_format_failure_docs(self):\n m = monitor.MonitorFail(\"test\", {\"failure_doc\": \"whoops\"})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n m.run_test()\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.FULL, alerter.AlertType.FAILURE, m\n ),\n textwrap.dedent(\n \"\"\"\n Monitor test on {hostname} failed!\n- Failed at: 2020-03-10 09:00:00+00:00 (down 0+00:00:00)\n+ Failed at: {expected_time} (down 0+00:00:00)\n Virtual failure count: 1\n Additional info: This monitor always fails.\n Description: A monitor which always fails.\n Documentation: whoops\n \"\"\".format(\n- hostname=util.short_hostname()\n+ hostname=util.short_hostname(),\n+ expected_time=self.expected_time_string,\n )\n ),\n )\n \n def test_full_format_success(self):\n m = monitor.MonitorNull(\"winning\", {})\n- with freeze_time(\"2020-03-10 09:00\"):\n+ with freeze_time(self.freeze_time_value):\n for _ in range(0, 6):\n m.run_test()\n self.assertEqual(\n- alerter.Alerter.build_message(\n+ self.test_alerter.build_message(\n alerter.AlertLength.FULL, alerter.AlertType.SUCCESS, m\n ),\n textwrap.dedent(\n \"\"\"\n Monitor winning on {hostname} succeeded!\n- Recovered at: 2020-03-10 09:00:00+00:00\n+ Recovered at: {expected_time}\n Additional info: \n Description: (Monitor did not write an auto-biography.)\n \"\"\".format( # noqa: W291\n- hostname=util.short_hostname()\n+ hostname=util.short_hostname(),\n+ expected_time=self.expected_time_string,\n )\n ),\n )\n \n \n+class TestMessageBuildingTZ(TestMessageBuilding):\n+ def setUp(self):\n+ super().setUp()\n+ self.test_alerter._tz = \"Europe/Warsaw\"\n+ self.expected_time_string = \"2020-03-10 10:00:00+01:00\"\n+\n+\n class TestSNSAlerter(unittest.TestCase):\n def test_config(self):\n with self.assertRaises(util.AlerterConfigurationError):\n", "FAIL_TO_PASS": ["tests/test_alerter.py::TestMessageBuildingTZ::test_full_format_failure", "tests/test_alerter.py::TestMessageBuildingTZ::test_full_format_failure_docs", "tests/test_alerter.py::TestMessageBuildingTZ::test_full_format_success", "tests/test_alerter.py::TestMessageBuildingTZ::test_oneline_format_failure", "tests/test_alerter.py::TestMessageBuildingTZ::test_sms_format_failure"]}, {"instance_id": "jamesoff__simplemonitor-605", "base_commit": "a285fb62030d9d275c4117361b8eb4290e5aa0ae", "gold_patch": "diff --git a/docs/alerting.md b/docs/alerting.md\nindex 5448953..dc9af21 100644\n--- a/docs/alerting.md\n+++ b/docs/alerting.md\n@@ -50,6 +50,7 @@ All alerters accept time period configuration. By default, an alerter is active\n | day | Which days an alerter can operate on. This is a comma-separated list of integers. 0 is Monday and 6 is Sunday. | no | (all days)|\n | times_type | Set to one of always, only, or not. \u201cOnly\u201d means that the limits define the period that an alerter can operate. \u201cNot\u201d means that the limits define the period during which it will not operate. | no | always |\n | time_lower and time_upper| If *times_type* is only or not, these two settings define the time limits. time_lower must always be the lower time. The time format is hh:mm using 24-hour clock. Both are required if times_type is anything other than always. | when *times_type* is not `always` | |\n+| times_tz | the timezone you want time_lower and time_upper interpreted as | no | local |\n | delay | If any kind of time/day restriction applies, the alerter will notify you of any monitors that failed while they were unable to alert you and are still failed. If a monitor fails and recovers during the restricted period, no catch-up alert is generated. Set to 1 to enable. | no | 0 |\n \n Here\u2019s a quick example of setting time periods (some other configuration values omitted):\ndiff --git a/simplemonitor/Alerters/alerter.py b/simplemonitor/Alerters/alerter.py\nindex 4d0a3b7..35ec7f3 100644\n--- a/simplemonitor/Alerters/alerter.py\n+++ b/simplemonitor/Alerters/alerter.py\n@@ -52,7 +52,7 @@ class Alerter:\n \"\"\"BaseClass for Alerters\"\"\"\n \n alerter_type = \"unknown\"\n- _dependencies = None # type: List[str]\n+ _dependencies = None # type: Optional[List[str]]\n hostname = gethostname()\n available = False\n \n@@ -159,6 +159,7 @@ class Alerter:\n \"only_failures\", required_type=bool, default=False\n )\n self._tz = cast(str, self.get_config_option(\"tz\", default=\"UTC\"))\n+ self._times_tz = cast(str, self.get_config_option(\"times_tz\", default=\"local\"))\n \n if self._ooh_failures is None:\n self._ooh_failures = []\n@@ -175,7 +176,9 @@ class Alerter:\n \n If a monitor we depend on fails, it means we can't reach the database,\n so we shouldn't bother trying to write to it.\"\"\"\n- return self._dependencies\n+ if self._dependencies is not None:\n+ return self._dependencies\n+ return []\n \n @dependencies.setter\n def dependencies(self, dependency_list: List[str]) -> None:\n@@ -197,6 +200,8 @@ class Alerter:\n \n def check_dependencies(self, failed_list: List[str]) -> bool:\n \"\"\"Check if anything we depend on has failed.\"\"\"\n+ if self._dependencies is None or len(self._dependencies) == 0:\n+ return True\n for dependency in failed_list:\n if dependency in self._dependencies:\n self.available = False\n@@ -275,7 +280,7 @@ class Alerter:\n \n def _allowed_today(self) -> bool:\n \"\"\"Check if today is an allowed day for an alert.\"\"\"\n- if arrow.now().weekday() not in self._days:\n+ if arrow.now(self._times_tz).weekday() not in self._days:\n self.alerter_logger.debug(\"not allowed to alert today\")\n return False\n return True\n@@ -285,12 +290,12 @@ class Alerter:\n if self._times_type == AlertTimeFilter.ALWAYS:\n return True\n if self._time_info[0] is not None and self._time_info[1] is not None:\n- now = arrow.now().time()\n- in_time_range = (now > self._time_info[0]) and (now < self._time_info[1])\n+ now = arrow.now(self._times_tz).time()\n+ in_time_range = self._time_info[0] <= now < self._time_info[1]\n if self._times_type == AlertTimeFilter.ONLY:\n self.alerter_logger.debug(\"in_time_range: %s\", in_time_range)\n return in_time_range\n- elif self._times_type == AlertTimeFilter.NOT:\n+ if self._times_type == AlertTimeFilter.NOT:\n self.alerter_logger.debug(\n \"in_time_range: %s (inverting due to AlertTimeFilter.NOT)\",\n in_time_range,\n@@ -305,12 +310,11 @@ class Alerter:\n def _get_verb(alert_type: AlertType) -> str:\n if alert_type == AlertType.CATCHUP:\n return \"failed earlier\"\n- elif alert_type == AlertType.FAILURE:\n+ if alert_type == AlertType.FAILURE:\n return \"failed\"\n- elif alert_type == AlertType.SUCCESS:\n+ if alert_type == AlertType.SUCCESS:\n return \"succeeded\"\n- else:\n- return \"unknowned\"\n+ return \"unknowned\"\n \n def build_message(\n self, length: AlertLength, alert_type: AlertType, monitor: Monitor\n", "test_patch": "diff --git a/tests/test_alerter.py b/tests/test_alerter.py\nindex f568b9d..1d8d025 100644\n--- a/tests/test_alerter.py\n+++ b/tests/test_alerter.py\n@@ -152,11 +152,25 @@ class TestAlerter(unittest.TestCase):\n a = alerter.Alerter({\"days\": \"0,2,3,4,5,6\"})\n self.assertFalse(a._allowed_today())\n \n+ @freeze_time(\n+ \"2020-03-09 22:00:00+00:00\"\n+ ) # a Monday, but the TZ will push to Tuesday\n+ def test_not_allowed_today_tz(self):\n+ a = alerter.Alerter({\"days\": \"0,2,3,4,5,6\", \"times_tz\": \"+05:00\"})\n+ self.assertFalse(a._allowed_today())\n+\n @freeze_time(\"2020-03-10\")\n def test_allowed_today(self):\n a = alerter.Alerter({\"days\": \"1\"})\n self.assertTrue(a._allowed_today())\n \n+ @freeze_time(\n+ \"2020-03-09 22:00:00+00:00\"\n+ ) # a Monday, but the TZ will push to Tuesday\n+ def test_allowed_today_tz(self):\n+ a = alerter.Alerter({\"days\": \"1\", \"times_tz\": \"+05:00\"})\n+ self.assertTrue(a._allowed_today())\n+\n @freeze_time(\"2020-03-10\")\n def test_allowed_default(self):\n a = alerter.Alerter({})\n@@ -178,6 +192,22 @@ class TestAlerter(unittest.TestCase):\n with freeze_time(\"12:00\", tz_offset=-self.utcoffset):\n self.assertFalse(a._allowed_time())\n \n+ def test_allowed_only_tz(self):\n+ a = alerter.Alerter(\n+ {\n+ \"times_type\": \"only\",\n+ \"time_lower\": \"15:00\",\n+ \"time_upper\": \"16:00\",\n+ \"times_tz\": \"+05:00\",\n+ }\n+ )\n+ with freeze_time(\"09:00\"):\n+ self.assertFalse(a._allowed_time())\n+ with freeze_time(\"10:30\"):\n+ self.assertTrue(a._allowed_time())\n+ with freeze_time(\"12:00\"):\n+ self.assertFalse(a._allowed_time())\n+\n def test_allowed_not(self):\n a = alerter.Alerter(\n {\"times_type\": \"not\", \"time_lower\": \"10:00\", \"time_upper\": \"11:00\"}\n@@ -189,6 +219,22 @@ class TestAlerter(unittest.TestCase):\n with freeze_time(\"12:00\", tz_offset=-self.utcoffset):\n self.assertTrue(a._allowed_time())\n \n+ def test_allowed_not_tz(self):\n+ a = alerter.Alerter(\n+ {\n+ \"times_type\": \"not\",\n+ \"time_lower\": \"15:00\",\n+ \"time_upper\": \"16:00\",\n+ \"times_tz\": \"+05:00\",\n+ }\n+ )\n+ with freeze_time(\"09:00\"):\n+ self.assertTrue(a._allowed_time())\n+ with freeze_time(\"10:30\"):\n+ self.assertFalse(a._allowed_time())\n+ with freeze_time(\"12:00\"):\n+ self.assertTrue(a._allowed_time())\n+\n def test_should_not_alert_ooh(self):\n config = {\"times_type\": \"only\", \"time_lower\": \"10:00\", \"time_upper\": \"11:00\"}\n a = alerter.Alerter(config)\n", "FAIL_TO_PASS": ["tests/test_alerter.py::TestAlerter::test_allowed_not_tz", "tests/test_alerter.py::TestAlerter::test_allowed_only_tz", "tests/test_alerter.py::TestAlerter::test_allowed_today_tz", "tests/test_alerter.py::TestAlerter::test_not_allowed_today_tz"]}], "all_FAIL_TO_PASS": ["tests/test_alerter.py::TestMessageBuildingTZ::test_full_format_failure", "tests/test_alerter.py::TestMessageBuildingTZ::test_full_format_failure_docs", "tests/test_alerter.py::TestMessageBuildingTZ::test_full_format_success", "tests/test_alerter.py::TestMessageBuildingTZ::test_oneline_format_failure", "tests/test_alerter.py::TestMessageBuildingTZ::test_sms_format_failure", "tests/test_alerter.py::TestAlerter::test_allowed_not_tz", "tests/test_alerter.py::TestAlerter::test_allowed_only_tz", "tests/test_alerter.py::TestAlerter::test_allowed_today_tz", "tests/test_alerter.py::TestAlerter::test_not_allowed_today_tz"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "hylang__hy-2514_x2", "level": 2, "source": "swerebench", "repo": "hylang/hy", "image": "swerebench/sweb.eval.x86_64.hylang_1776_hy-2514:latest", "base_commit": "902233d854d765058927402d60f1ee8bef02daf8", "num_bugs": 2, "bugs": [{"instance_id": "hylang__hy-2514", "base_commit": "902233d854d765058927402d60f1ee8bef02daf8", "gold_patch": "diff --git a/NEWS.rst b/NEWS.rst\nindex 4b3e7082..969f8aad 100644\n--- a/NEWS.rst\n+++ b/NEWS.rst\n@@ -34,6 +34,7 @@ Misc. Improvements\n ------------------------------\n * Some syntax errors raised by core macros now have more informative\n messages.\n+* Logical operators now compile to simpler Python code in some cases.\n \n Bug Fixes\n ------------------------------\ndiff --git a/hy/core/result_macros.py b/hy/core/result_macros.py\nindex 81c24ffe..9ed6c65e 100644\n--- a/hy/core/result_macros.py\n+++ b/hy/core/result_macros.py\n@@ -256,48 +256,66 @@ def compile_unary_operator(compiler, expr, root, arg):\n def compile_logical_or_and_and_operator(compiler, expr, operator, args):\n ops = {\"and\": (ast.And, True), \"or\": (ast.Or, None)}\n opnode, default = ops[operator]\n- osym = expr[0]\n if len(args) == 0:\n- return asty.Constant(osym, value=default)\n- elif len(args) == 1:\n- return compiler.compile(args[0])\n- ret = Result()\n- values = list(map(compiler.compile, args))\n- if any(value.stmts for value in values):\n- # Compile it to an if...else sequence\n- var = compiler.get_anon_var()\n- name = asty.Name(osym, id=var, ctx=ast.Store())\n- expr_name = asty.Name(osym, id=var, ctx=ast.Load())\n- temp_variables = [name, expr_name]\n-\n- def make_assign(value, node=None):\n- positioned_name = asty.Name(node or osym, id=var, ctx=ast.Store())\n- temp_variables.append(positioned_name)\n- return asty.Assign(node or osym, targets=[positioned_name], value=value)\n-\n- current = root = []\n- for i, value in enumerate(values):\n- if value.stmts:\n- node = value.stmts[0]\n- current.extend(value.stmts)\n+ return asty.Constant(expr[0], value=default)\n+\n+ ret = None\n+ var = None # A temporary variable for assigning results to\n+ assignment = None # The current assignment to `var`\n+ stmts = None # The current statement list\n+\n+ def put(node, value):\n+ # Save the result of the operation so far to `var`.\n+ nonlocal var, assignment\n+ if var is None:\n+ var = compiler.get_anon_var()\n+ name = asty.Name(node, id=var, ctx=ast.Store())\n+ ret.temp_variables.append(name)\n+ return (assignment := asty.Assign(node, targets=[name], value=value))\n+\n+ def get(node):\n+ # Get the value of `var`, creating it if necessary.\n+ if var is None:\n+ stmts.append(put(node, ret.force_expr))\n+ name = asty.Name(node, id=var, ctx=ast.Load())\n+ ret.temp_variables.append(name)\n+ return name\n+\n+ for value in map(compiler.compile, args):\n+ if ret is None:\n+ # This is the first iteration. Don't actually introduce a\n+ # `BoolOp` yet; the unary case doesn't need it.\n+ ret = value\n+ stmts = ret.stmts\n+ elif value.stmts:\n+ # Save the result of the statements to the temporary\n+ # variable. Use an `if` statement to implement\n+ # short-circuiting from this point.\n+ node = value.stmts[0]\n+ cond = get(node)\n+ if operator == \"or\":\n+ # Negate the conditional.\n+ cond = asty.UnaryOp(node, op=ast.Not(), operand=cond)\n+ branch = asty.If(node, test=cond, body=value.stmts, orelse=[])\n+ stmts.append(branch)\n+ stmts = branch.body\n+ stmts.append(put(node, value.force_expr))\n+ else:\n+ # Add this value to the current `BoolOp`, or create a new\n+ # one if we don't have one.\n+ value = value.force_expr\n+ def enbool(expr):\n+ if isinstance(expr, ast.BoolOp):\n+ expr.values.append(value)\n+ return expr\n+ return asty.BoolOp(expr, op=opnode(), values=[expr, value])\n+ if assignment:\n+ assignment.value = enbool(assignment.value)\n else:\n- node = value.expr\n- current.append(make_assign(value.force_expr, value.force_expr))\n- if i == len(values) - 1:\n- # Skip a redundant 'if'.\n- break\n- if operator == \"and\":\n- cond = expr_name\n- elif operator == \"or\":\n- cond = asty.UnaryOp(node, op=ast.Not(), operand=expr_name)\n- current.append(asty.If(node, test=cond, body=[], orelse=[]))\n- current = current[-1].body\n- ret = sum(root, ret)\n- ret += Result(expr=expr_name, temp_variables=temp_variables)\n- else:\n- ret += asty.BoolOp(\n- osym, op=opnode(), values=[value.force_expr for value in values]\n- )\n+ ret.expr = enbool(ret.expr)\n+\n+ if var:\n+ ret.expr = get(expr)\n return ret\n \n \n", "test_patch": "diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py\nindex 27cf3505..001c2e55 100644\n--- a/tests/compilers/test_ast.py\n+++ b/tests/compilers/test_ast.py\n@@ -449,6 +449,15 @@ def test_literal_newlines():\n assert s(\"#[[\\rhello\\rworld]]\") == \"hello\\nworld\"\n \n \n+def test_linear_boolop():\n+ \"\"\"Operations like `(and 1 2 3)` should use only one `BoolOp`,\n+ instead of an equivalent nested sequence of `BoolOp`s.\"\"\"\n+ for op in (\"and\", \"or\"):\n+ node = can_compile(f'({op} 1 2.0 True \"hi\" 5)').body[0].value\n+ assert len(node.values) == 5\n+ assert all(isinstance(v, ast.Constant) for v in node.values)\n+\n+\n def test_compile_error():\n \"\"\"Ensure we get compile error in tricky cases\"\"\"\n with pytest.raises(HyLanguageError) as excinfo:\ndiff --git a/tests/compilers/test_compiler.py b/tests/compilers/test_compiler.py\nindex 64fd2a01..4269fe0d 100644\n--- a/tests/compilers/test_compiler.py\n+++ b/tests/compilers/test_compiler.py\n@@ -3,6 +3,8 @@ import types\n \n from hy import compiler\n from hy.models import Expression, Integer, List, Symbol\n+from hy.reader import read_many\n+from hy.compiler import hy_compile\n \n \n def make_expression(*args):\n@@ -14,6 +16,10 @@ def make_expression(*args):\n return h.replace(h)\n \n \n+def hy2py(s):\n+ return ast.unparse(hy_compile(read_many(s), \"test\", import_stdlib=False))\n+\n+\n def test_compiler_bare_names():\n \"\"\"\n Check that the compiler doesn't drop bare names from code branches\n@@ -58,3 +64,15 @@ def test_compiler_yield_return():\n assert isinstance(body[0].value, ast.Yield)\n assert isinstance(body[1], ast.Return)\n assert isinstance(body[1].value, ast.BinOp)\n+\n+\n+# https://github.com/hylang/hy/issues/854\n+def test_compact_logic():\n+ \"\"\"\n+ Check that we don't generate multiple unnecessary if-statements\n+ when compiling the short-circuiting operators.\n+ \"\"\"\n+ py = hy2py(\"(and 1 2 3 (do (setv x 4) x) 5 6)\")\n+ assert py.count(\"if\") == 1\n+ py = hy2py(\"(or 1 2 3 (do (setv x 4) x) 5 6 (do (setv y 7)))\")\n+ assert py.count(\"if\") == 2\n", "FAIL_TO_PASS": ["tests/compilers/test_compiler.py::test_compact_logic"]}, {"instance_id": "hylang__hy-2522", "base_commit": "fa639893e5b56e3f3cc9f6ed46fd654dfaf35754", "gold_patch": "diff --git a/NEWS.rst b/NEWS.rst\nindex 61d9a3fb..d167fe40 100644\n--- a/NEWS.rst\n+++ b/NEWS.rst\n@@ -50,6 +50,8 @@ Bug Fixes\n * Fixed incomplete recognition of macro calls with a unary dotted\n head like `((. defn) f [])`.\n * `~@ #*` now produces a syntax error instead of a nonsensical result.\n+* Fixed parsing of infinite and NaN imaginary literals with an\n+ uppercase \"J\".\n * Fixed `hy.eval` failing on `defreader` or `require` forms that\n install a new reader.\n * `require` now warns when you shadow a core macro, like `defmacro`\ndiff --git a/docs/syntax.rst b/docs/syntax.rst\nindex 1a55eb7a..54188fda 100644\n--- a/docs/syntax.rst\n+++ b/docs/syntax.rst\n@@ -152,7 +152,8 @@ few extensions:\n interpreted in octal like they do in C. For octal, use the prefix ``0o``, as\n in Python.\n - ``NaN``, ``Inf``, and ``-Inf`` are understood as literals. Each produces a\n- :class:`Float `.\n+ :class:`Float `. These are case-sensitive, unlike other uses\n+ of letters in numeric literals (``1E2``, ``0XFF``, ``5J``, etc.).\n - Hy allows complex literals as understood by the constructor for\n :class:`complex`, such as ``5+4j``. (This is also legal Python, but Hy reads\n it as a single :class:`Complex `, and doesn't otherwise\ndiff --git a/hy/models.py b/hy/models.py\nindex 3ce3a74e..23ccb6c5 100644\n--- a/hy/models.py\n+++ b/hy/models.py\n@@ -361,7 +361,7 @@ class Complex(Object, complex):\n if isinstance(real, str):\n value = super().__new__(cls, strip_digit_separators(real))\n p1, _, p2 = real.lstrip(\"+-\").replace(\"-\", \"+\").partition(\"+\")\n- check_inf_nan_cap(p1, value.imag if \"j\" in p1 else value.real)\n+ check_inf_nan_cap(p1, value.imag if \"j\" in p1.lower() else value.real)\n if p2:\n check_inf_nan_cap(p2, value.imag)\n return value\n", "test_patch": "diff --git a/tests/test_reader.py b/tests/test_reader.py\nindex 6127a11c..3ae60daf 100644\n--- a/tests/test_reader.py\n+++ b/tests/test_reader.py\n@@ -225,9 +225,13 @@ def test_lex_expression_complex():\n def f(x):\n return [Expression([Symbol(\"foo\"), x])]\n \n+ assert t(\"2j\") == f(Complex(2.0j))\n+ assert t(\"2J\") == f(Complex(2.0j))\n assert t(\"2.j\") == f(Complex(2.0j))\n+ assert t(\"2.J\") == f(Complex(2.0j))\n assert t(\"-0.5j\") == f(Complex(-0.5j))\n assert t(\"1.e7j\") == f(Complex(1e7j))\n+ assert t(\"1.e7J\") == f(Complex(1e7j))\n assert t(\"j\") == f(Symbol(\"j\"))\n assert t(\"J\") == f(Symbol(\"J\"))\n assert isnan(t(\"NaNj\")[0][1].imag)\n@@ -236,6 +240,13 @@ def test_lex_expression_complex():\n assert t(\"Inf-Infj\") == f(Complex(complex(float(\"inf\"), float(\"-inf\"))))\n assert t(\"Inf-INFj\") == f(Symbol(\"Inf-INFj\"))\n \n+ # https://github.com/hylang/hy/issues/2521\n+ assert isnan(t(\"NaNJ\")[0][1].imag)\n+ assert t(\"nanJ\") == f(Symbol(\"nanJ\"))\n+ assert t(\"InfJ\") == f(Complex(complex(0, float(\"inf\"))))\n+ assert t(\"iNfJ\") == f(Symbol(\"iNfJ\"))\n+ assert t(\"Inf-INFJ\") == f(Symbol(\"Inf-INFJ\"))\n+\n \n def test_lex_digit_separators():\n \n", "FAIL_TO_PASS": ["tests/test_reader.py::test_lex_expression_complex"]}], "all_FAIL_TO_PASS": ["tests/compilers/test_compiler.py::test_compact_logic", "tests/test_reader.py::test_lex_expression_complex"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "duo-labs__py_webauthn-120_x2", "level": 2, "source": "swerebench", "repo": "duo-labs/py_webauthn", "image": "swerebench/sweb.eval.x86_64.duo-labs_1776_py_webauthn-120:latest", "base_commit": "381aad2548a884b54bc928dd3fbc37dbe68514c9", "num_bugs": 2, "bugs": [{"instance_id": "duo-labs__py_webauthn-120", "base_commit": "381aad2548a884b54bc928dd3fbc37dbe68514c9", "gold_patch": "diff --git a/webauthn/helpers/structs.py b/webauthn/helpers/structs.py\nindex 9ae33bc..74274ab 100644\n--- a/webauthn/helpers/structs.py\n+++ b/webauthn/helpers/structs.py\n@@ -44,6 +44,7 @@ class BytesLike(bytes):\n - https://github.com/duo-labs/py_webauthn/issues/110\n - https://github.com/duo-labs/py_webauthn/issues/113\n \"\"\"\n+\n @classmethod\n def __get_validators__(cls):\n yield cls.validate\n@@ -52,6 +53,8 @@ class BytesLike(bytes):\n def validate(cls, v):\n if isinstance(v, bytes):\n return v\n+ elif isinstance(v, memoryview):\n+ return v.tobytes()\n else:\n return strict_bytes_validator(v)\n \n", "test_patch": "diff --git a/tests/test_bytes_subclass_support.py b/tests/test_bytes_subclass_support.py\nindex c6c9783..3fe50d6 100644\n--- a/tests/test_bytes_subclass_support.py\n+++ b/tests/test_bytes_subclass_support.py\n@@ -7,19 +7,19 @@ from webauthn.helpers.structs import (\n )\n \n \n-class CustomBytes(bytes):\n- def __new__(cls, data: str):\n- data_bytes = base64url_to_bytes(data)\n- self = bytes.__new__(cls, memoryview(data_bytes).tobytes())\n- return self\n-\n-\n class TestWebAuthnBytesSubclassSupport(TestCase):\n def test_handles_bytes_subclasses(self) -> None:\n \"\"\"\n Ensure the library can support being used in projects that might work with values that are\n subclasses of `bytes`. Let's embrace Python's duck-typing, not shy away from it\n \"\"\"\n+\n+ class CustomBytes(bytes):\n+ def __new__(cls, data: str):\n+ data_bytes = base64url_to_bytes(data)\n+ self = bytes.__new__(cls, memoryview(data_bytes).tobytes())\n+ return self\n+\n verification = verify_authentication_response(\n credential=AuthenticationCredential(\n id=\"fq9Nj0nS24B5y6Pkw_h3-9GEAEA3-0LBPxE2zvTdLjDqtSeCSNYFe9VMRueSpAZxT3YDc6L1lWXdQNwI-sVNYrefEcRR1Nsb_0jpHE955WEtFud2xxZg3MvoLMxHLet63i5tajd1fHtP7I-00D6cehM8ZWlLp2T3s9lfZgVIFcA\",\n@@ -50,3 +50,43 @@ class TestWebAuthnBytesSubclassSupport(TestCase):\n )\n \n assert verification.new_sign_count == 7\n+\n+ def test_handles_memoryviews(self) -> None:\n+ \"\"\"\n+ Ensure support for libraries that leverage memoryviews\n+ \"\"\"\n+\n+ def base64url_to_memoryview(data: str) -> memoryview:\n+ data_bytes = base64url_to_bytes(data)\n+ return memoryview(data_bytes)\n+\n+ verification = verify_authentication_response(\n+ credential=AuthenticationCredential(\n+ id=\"fq9Nj0nS24B5y6Pkw_h3-9GEAEA3-0LBPxE2zvTdLjDqtSeCSNYFe9VMRueSpAZxT3YDc6L1lWXdQNwI-sVNYrefEcRR1Nsb_0jpHE955WEtFud2xxZg3MvoLMxHLet63i5tajd1fHtP7I-00D6cehM8ZWlLp2T3s9lfZgVIFcA\",\n+ raw_id=base64url_to_memoryview(\n+ \"fq9Nj0nS24B5y6Pkw_h3-9GEAEA3-0LBPxE2zvTdLjDqtSeCSNYFe9VMRueSpAZxT3YDc6L1lWXdQNwI-sVNYrefEcRR1Nsb_0jpHE955WEtFud2xxZg3MvoLMxHLet63i5tajd1fHtP7I-00D6cehM8ZWlLp2T3s9lfZgVIFcA\"\n+ ),\n+ response=AuthenticatorAssertionResponse(\n+ authenticator_data=base64url_to_memoryview(\n+ \"SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MBAAAABw\"\n+ ),\n+ client_data_json=base64url_to_memoryview(\n+ \"eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZVo0ZWVBM080ank1Rkl6cURhU0o2SkROR3UwYkJjNXpJMURqUV9rTHNvMVdOcWtHNms1bUNZZjFkdFFoVlVpQldaV2xaa3pSNU1GZWVXQ3BKUlVOWHciLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9\"\n+ ),\n+ signature=base64url_to_memoryview(\n+ \"RRWV8mYDRvK7YdQgdtZD4pJ2dh1D_IWZ_D6jsZo6FHJBoenbj0CVT5nA20vUzlRhN4R6dOEUHmUwP1F8eRBhBg\"\n+ ),\n+ ),\n+ ),\n+ expected_challenge=base64url_to_memoryview(\n+ \"eZ4eeA3O4jy5FIzqDaSJ6JDNGu0bBc5zI1DjQ_kLso1WNqkG6k5mCYf1dtQhVUiBWZWlZkzR5MFeeWCpJRUNXw\"\n+ ),\n+ expected_rp_id=\"localhost\",\n+ expected_origin=\"http://localhost:5000\",\n+ credential_public_key=base64url_to_memoryview(\n+ \"pAEBAycgBiFYIMz6_SUFLiDid2Yhlq0YboyJ-CDrIrNpkPUGmJp4D3Dp\"\n+ ),\n+ credential_current_sign_count=3,\n+ )\n+\n+ assert verification.new_sign_count == 7\n", "FAIL_TO_PASS": ["tests/test_bytes_subclass_support.py::TestWebAuthnBytesSubclassSupport::test_handles_memoryviews"]}, {"instance_id": "duo-labs__py_webauthn-129", "base_commit": "81f7d86d0c8d8eb6b7fa0fddcd704a658d0a9b85", "gold_patch": "diff --git a/webauthn/helpers/structs.py b/webauthn/helpers/structs.py\nindex 74274ab..16800c4 100644\n--- a/webauthn/helpers/structs.py\n+++ b/webauthn/helpers/structs.py\n@@ -74,6 +74,7 @@ class AuthenticatorTransport(str, Enum):\n `NFC`: Near Field Communication\n `BLE`: Bluetooth Low Energy\n `INTERNAL`: Direct connection (read: a platform authenticator)\n+ `CABLE`: Cloud Assisted Bluetooth Low Energy\n \n https://www.w3.org/TR/webauthn-2/#enum-transport\n \"\"\"\n@@ -82,6 +83,7 @@ class AuthenticatorTransport(str, Enum):\n NFC = \"nfc\"\n BLE = \"ble\"\n INTERNAL = \"internal\"\n+ CABLE = \"cable\"\n \n \n class AuthenticatorAttachment(str, Enum):\n@@ -221,7 +223,7 @@ class PublicKeyCredentialRpEntity(WebAuthnBaseModel):\n \n Attributes:\n `name`: A user-readable name for the Relying Party\n- `id`: A unique, constant value assigned to the Relying Party. Authenticators use this value to associate a credential with a particular Relying Party user\n+ (optional) `id`: A unique, constant value assigned to the Relying Party. Authenticators use this value to associate a credential with a particular Relying Party user\n \n https://www.w3.org/TR/webauthn-2/#dictdef-publickeycredentialrpentity\n \"\"\"\n@@ -373,7 +375,7 @@ class RegistrationCredential(WebAuthnBaseModel):\n `raw_id`: A byte sequence representing the credential's unique identifier\n `response`: The authenticator's attesation data\n `type`: The literal string `\"public-key\"`\n- `transports`: The authenticator's supported methods of communication with a client/browser\n+ (optional) `transports`: The authenticator's supported methods of communication with a client/browser\n \n https://www.w3.org/TR/webauthn-2/#publickeycredential\n \"\"\"\n", "test_patch": "diff --git a/tests/test_verify_registration_response.py b/tests/test_verify_registration_response.py\nindex 60b7077..d9a0115 100644\n--- a/tests/test_verify_registration_response.py\n+++ b/tests/test_verify_registration_response.py\n@@ -166,3 +166,35 @@ class TestVerifyRegistrationResponse(TestCase):\n AttestationFormat.PACKED: [globalsign_r2]\n },\n )\n+\n+ def test_verifies_registration_over_cable(self) -> None:\n+ credential = RegistrationCredential.parse_raw(\n+ \"\"\"{\n+ \"id\": \"9y1xA8Tmg1FEmT-c7_fvWZ_uoTuoih3OvR45_oAK-cwHWhAbXrl2q62iLVTjiyEZ7O7n-CROOY494k7Q3xrs_w\",\n+ \"rawId\": \"9y1xA8Tmg1FEmT-c7_fvWZ_uoTuoih3OvR45_oAK-cwHWhAbXrl2q62iLVTjiyEZ7O7n-CROOY494k7Q3xrs_w\",\n+ \"response\": {\n+ \"attestationObject\": \"o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjESZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NFAAAAFwAAAAAAAAAAAAAAAAAAAAAAQPctcQPE5oNRRJk_nO_371mf7qE7qIodzr0eOf6ACvnMB1oQG165dqutoi1U44shGezu5_gkTjmOPeJO0N8a7P-lAQIDJiABIVggSFbUJF-42Ug3pdM8rDRFu_N5oiVEysPDB6n66r_7dZAiWCDUVnB39FlGypL-qAoIO9xWHtJygo2jfDmHl-_eKFRLDA\",\n+ \"clientDataJSON\": \"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiVHdON240V1R5R0tMYzRaWS1xR3NGcUtuSE00bmdscXN5VjBJQ0psTjJUTzlYaVJ5RnRya2FEd1V2c3FsLWdrTEpYUDZmbkYxTWxyWjUzTW00UjdDdnciLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9\"\n+ },\n+ \"type\": \"public-key\",\n+ \"clientExtensionResults\": {},\n+ \"transports\": [\n+ \"cable\"\n+ ]\n+ }\"\"\"\n+ )\n+\n+ challenge = base64url_to_bytes(\n+ \"TwN7n4WTyGKLc4ZY-qGsFqKnHM4nglqsyV0ICJlN2TO9XiRyFtrkaDwUvsql-gkLJXP6fnF1MlrZ53Mm4R7Cvw\"\n+ )\n+ rp_id = \"localhost\"\n+ expected_origin = \"http://localhost:5000\"\n+\n+ verification = verify_registration_response(\n+ credential=credential,\n+ expected_challenge=challenge,\n+ expected_origin=expected_origin,\n+ expected_rp_id=rp_id,\n+ )\n+\n+ assert verification.fmt == AttestationFormat.NONE\n", "FAIL_TO_PASS": ["tests/test_verify_registration_response.py::TestVerifyRegistrationResponse::test_verifies_registration_over_cable"]}], "all_FAIL_TO_PASS": ["tests/test_bytes_subclass_support.py::TestWebAuthnBytesSubclassSupport::test_handles_memoryviews", "tests/test_verify_registration_response.py::TestVerifyRegistrationResponse::test_verifies_registration_over_cable"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "dwavesystems__dwave-cloud-client-650_x2", "level": 2, "source": "swerebench", "repo": "dwavesystems/dwave-cloud-client", "image": "swerebench/sweb.eval.x86_64.dwavesystems_1776_dwave-cloud-client-650:latest", "base_commit": "87123208854c4c292501233dc9bde2f176d5412a", "num_bugs": 2, "bugs": [{"instance_id": "dwavesystems__dwave-cloud-client-650", "base_commit": "87123208854c4c292501233dc9bde2f176d5412a", "gold_patch": "diff --git a/dwave/cloud/api/client.py b/dwave/cloud/api/client.py\nindex 3b19f3b..366bd31 100644\n--- a/dwave/cloud/api/client.py\n+++ b/dwave/cloud/api/client.py\n@@ -19,12 +19,12 @@ import hashlib\n import logging\n import os\n from collections import deque, namedtuple\n-from typing import Callable, Mapping, Optional, TypedDict, Union, TYPE_CHECKING\n+from typing import Callable, Mapping, Optional, Tuple, TypedDict, Union, TYPE_CHECKING\n \n import requests\n import urllib3\n+import werkzeug\n from packaging.specifiers import SpecifierSet\n-from werkzeug.http import parse_options_header, dump_options_header\n \n import dwave.cloud.config # don't use `from` to break circular import (config <> api.constants)\n from dwave.cloud.api import constants, exceptions\n@@ -189,7 +189,7 @@ class VersionedAPISession(LoggingSession):\n else:\n return\n \n- media_type, params = parse_options_header(content_type)\n+ media_type, params = werkzeug.http.parse_options_header(content_type)\n \n if media_type != self._media_type:\n raise exceptions.ResourceBadResponseError(\n@@ -220,7 +220,7 @@ class VersionedAPISession(LoggingSession):\n params['version'] = self._ask_version\n \n headers = {} if headers is None else headers.copy()\n- headers['Accept'] = dump_options_header(self._media_type, params)\n+ headers['Accept'] = werkzeug.http.dump_options_header(self._media_type, params)\n \n response = super().request(*args, headers=headers, **kwargs)\n \n@@ -285,7 +285,7 @@ class CachingSession(VersionedAPISession):\n \n class CacheConfig(TypedDict, total=False):\n enabled: bool\n- maxage: float\n+ maxage: int\n store: Union[Mapping, Callable[[], Mapping]]\n \n # default cache config\n@@ -315,7 +315,10 @@ class CachingSession(VersionedAPISession):\n logger.debug(\"[%s] cache disabled.\", type(self).__name__)\n return\n \n- self._maxage = config['maxage']\n+ if not isinstance(_maxage := config.get('maxage'), int) or _maxage < 0:\n+ raise ValueError(\"A non-negative integer required for 'maxage'.\")\n+ self._maxage = _maxage\n+\n self._store = config['store']\n if callable(self._store):\n self._store = self._store()\n@@ -326,6 +329,67 @@ class CachingSession(VersionedAPISession):\n if hasattr(self._store, 'directory'):\n logger.debug(\"cache.store.directory=%r\", self._store.directory)\n \n+ def _parse_cache_control(\n+ self,\n+ cache_control: Optional[str] = None,\n+ ) -> Tuple[bool, Optional[int]]:\n+ # parse Cache-Control header field (if present) and derive a suitable max-age value\n+ # returns: (cache?, maxage)\n+\n+ # note:\n+ # - we always revalidate after expiry, so we can ignore `must-revalidate`\n+ # - and we never transform the response, so safe to ignore `no-transform`\n+ # - our cache is private (for a single user), so we can ignore `private`,\n+ # `public` and `s-maxage` directives\n+\n+ cc = werkzeug.http.parse_cache_control_header(\n+ cache_control, cls=werkzeug.datastructures.ResponseCacheControl)\n+\n+ if cc.no_cache:\n+ # cache, but always validate\n+ return (True, 0)\n+\n+ if cc.no_store:\n+ # skip cache\n+ return (False, 0)\n+\n+ # cache for up to max_age\n+ return (True, cc.max_age)\n+\n+ def _update_cache(\n+ self,\n+ response: requests.Response,\n+ key_meta: str,\n+ key_data: Optional[str] = None,\n+ only_meta: bool = False\n+ ) -> bool:\n+ # update cache from response according to cache-control\n+ # returns: updated?\n+\n+ # etag and cache-control are present in 304 if they're in 200 response\n+ # see: https://datatracker.ietf.org/doc/html/rfc9110#name-304-not-modified\n+ etag = response.headers.get('ETag')\n+ cache_control = response.headers.get('Cache-Control')\n+\n+ use_cache, maxage = self._parse_cache_control(cache_control)\n+ if use_cache:\n+ meta = dict(created=epochnow(), maxage=maxage, etag=etag)\n+ self._store[key_meta] = meta\n+ if not only_meta:\n+ self._store[key_data] = response.content\n+\n+ logger.debug(\"response cached for maxage=%r\", maxage)\n+ return True\n+\n+ else:\n+ if key_meta in self._store:\n+ del self._store[key_meta]\n+ if key_data in self._store:\n+ del self._store[key_data]\n+\n+ logger.debug(\"response caching skipped at server's request\")\n+ return False\n+\n def request(self, method, url, *,\n params: Optional[dict] = None,\n headers: Optional[dict] = None,\n@@ -335,10 +399,10 @@ class CachingSession(VersionedAPISession):\n # read CachingSession-specific params\n refresh = kwargs.pop('refresh_', False)\n no_cache = kwargs.pop('no_cache_', False)\n- suggested_maxage = kwargs.pop('maxage_', self._maxage)\n+ default_maxage = kwargs.pop('maxage_', self._maxage)\n \n if not self._cache_enabled or no_cache or method.lower() != 'get':\n- # completely bypass cache lookup and conditional request\n+ # completely bypass cache lookup and validation\n return super().request(method, url, params=params, headers=headers, **kwargs)\n \n key = (method,\n@@ -357,8 +421,14 @@ class CachingSession(VersionedAPISession):\n return res\n \n if not refresh and (meta := self._store.get(key_meta)):\n- maxage = meta.get('maxage', suggested_maxage) or 0\n-\n+ # respect max-age from response cache-control\n+ maxage = meta.get('maxage')\n+ if maxage is None:\n+ # but if cache-control was absent, client gets do decide\n+ maxage = default_maxage\n+\n+ # note: by deferring this lookup, we could save a few ms in case\n+ # when upstream content was modified (but that doesn't happen often)\n content = self._store.get(key_data)\n \n if epochnow() - meta['created'] < maxage:\n@@ -372,26 +442,21 @@ class CachingSession(VersionedAPISession):\n res = super().request(method, url, params=params, headers=headers, **kwargs)\n \n if res.status_code == requests.codes['not_modified']:\n+ # see 4.3.4. in rfc9111 (http caching)\n+ # we know SAPI only uses weak validators\n logger.debug('resource \"not modified\", using cached value')\n- meta['created'] = epochnow()\n- self._store[key_meta] = meta\n+ self._update_cache(res, key_meta=key_meta, only_meta=True)\n return make_response(content)\n \n else:\n logger.debug('resource modified, updating cache')\n- meta = dict(created=epochnow(),\n- etag=res.headers.get('etag'))\n- self._store[key_meta] = meta\n- self._store[key_data] = res.content\n+ self._update_cache(res, key_meta=key_meta, key_data=key_data)\n return res\n \n else:\n logger.debug('cache miss, updating cache')\n res = super().request(method, url, params=params, headers=headers, **kwargs)\n- meta = dict(created=epochnow(),\n- etag=res.headers.get('etag'))\n- self._store[key_meta] = meta\n- self._store[key_data] = res.content\n+ self._update_cache(res, key_meta=key_meta, key_data=key_data)\n return res\n \n \ndiff --git a/dwave/cloud/client/base.py b/dwave/cloud/client/base.py\nindex 4bc4ef6..47c9871 100644\n--- a/dwave/cloud/client/base.py\n+++ b/dwave/cloud/client/base.py\n@@ -343,7 +343,7 @@ class Client(object):\n # Downloaded solver definition cache config\n _DEFAULT_SOLVERS_CACHE_CONFIG = dict(\n enabled=True,\n- maxage=900, # 15 min heuristic maxage (TODO: API cache-control to override it)\n+ maxage=3600, # 1 hour heuristic maxage (cache-control in response overrides it)\n )\n \n # Downloaded region metadata cache maxage [sec]\ndiff --git a/releasenotes/notes/respect-cache-control-in-api-response-27dbd1a7f300648d.yaml b/releasenotes/notes/respect-cache-control-in-api-response-27dbd1a7f300648d.yaml\nnew file mode 100644\nindex 0000000..50fbb35\n--- /dev/null\n+++ b/releasenotes/notes/respect-cache-control-in-api-response-27dbd1a7f300648d.yaml\n@@ -0,0 +1,9 @@\n+---\n+features:\n+ - |\n+ Parse ``Cache-Control`` header field if present in API response, and use it\n+ to guide local caching policy.\n+\n+ This means ``dwave.cloud.api.DWaveAPIClient`` and ``dwave.cloud.api.resource``\n+ classes now respect origin server response caching policy.\n+ See `#646 `_.\n", "test_patch": "diff --git a/tests/api/test_api_clients.py b/tests/api/test_api_clients.py\nindex ed670ad..1f9a0d0 100644\n--- a/tests/api/test_api_clients.py\n+++ b/tests/api/test_api_clients.py\n@@ -13,6 +13,7 @@\n # limitations under the License.\n \n import json\n+import time\n import uuid\n import unittest\n \n@@ -354,7 +355,7 @@ class TestResponseCaching(unittest.TestCase):\n self.assertIsInstance(client.session._store, dict)\n \n @requests_mock.Mocker()\n- def test_caching(self, m):\n+ def test_caching_no_cache_control(self, m):\n endpoint = 'https://mock'\n \n path_a = 'path-a'\n@@ -369,11 +370,15 @@ class TestResponseCaching(unittest.TestCase):\n \n # mock: resource not modified\n m.get(f\"{endpoint}/{path_a}\", json=data_a, headers={'ETag': etag_a})\n- m.get(f\"{endpoint}/{path_a}\", request_headers={'If-None-Match': etag_a}, status_code=304)\n+ m.get(f\"{endpoint}/{path_a}\",\n+ request_headers={'If-None-Match': etag_a}, status_code=304,\n+ headers={'ETag': etag_a})\n \n # mock: resource modified between requests\n m.get(f\"{endpoint}/{path_b}\", json=data_b, headers={'ETag': etag_b})\n- m.get(f\"{endpoint}/{path_b}\", request_headers={'If-None-Match': etag_b}, json=data_bb, headers={'ETag': etag_bb})\n+ m.get(f\"{endpoint}/{path_b}\",\n+ request_headers={'If-None-Match': etag_b}, json=data_bb,\n+ headers={'ETag': etag_bb})\n \n store = {}\n \n@@ -433,3 +438,121 @@ class TestResponseCaching(unittest.TestCase):\n self.assertEqual(r.json(), data_a)\n \n self.assertTrue(m.called)\n+\n+ @requests_mock.Mocker()\n+ def test_cache_control_maxage(self, m):\n+ # verify max-age from cache-control header is respected\n+\n+ endpoint = 'https://mock'\n+\n+ path = 'path'\n+ etag = 'etag'\n+ data = {\"a\": 1}\n+\n+ maxage = 10\n+\n+ # mock: resource not modified\n+ m.get(f\"{endpoint}/{path}\", json=data,\n+ headers={'ETag': etag, 'Cache-Control': f'public, max-age={maxage}'})\n+ m.get(f\"{endpoint}/{path}\",\n+ request_headers={'If-None-Match': etag}, status_code=304,\n+ headers={'ETag': etag, 'Cache-Control': f'public, max-age={maxage}'})\n+\n+ store = {}\n+\n+ with DWaveAPIClient(endpoint=endpoint, cache=dict(store=store), history_size=1) as client:\n+\n+ with self.subTest(\"cache miss\"):\n+ self.assertEqual(len(store), 0)\n+\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+ self.assertEqual(len(store), 2) # data + meta\n+\n+ with self.subTest(\"cache hit\"):\n+ m.reset_mock()\n+\n+ with unittest.mock.patch('dwave.cloud.api.client.epochnow',\n+ lambda: time.time() + maxage - 1):\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ # if mock not called, data came from cache\n+ self.assertFalse(m.called)\n+\n+ with self.subTest(\"cache expired, validated\"):\n+ m.reset_mock()\n+\n+ with unittest.mock.patch('dwave.cloud.api.client.epochnow',\n+ lambda: time.time() + maxage + 1):\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+ self.assertEqual(client.session.history[-1].response.status_code, 304)\n+\n+ @requests_mock.Mocker()\n+ def test_cache_control_no_store(self, m):\n+ # verify we don't cache when server forbids caching\n+\n+ endpoint = 'https://mock'\n+\n+ path = 'path'\n+ etag = 'etag'\n+ data = {\"a\": 1}\n+\n+ m.get(f\"{endpoint}/{path}\", json=data,\n+ headers={'ETag': etag, 'Cache-Control': 'no-store'})\n+\n+ store = {}\n+\n+ with DWaveAPIClient(endpoint=endpoint, cache=dict(store=store)) as client:\n+\n+ with self.subTest(\"cache miss\"):\n+ self.assertEqual(len(store), 0)\n+\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+ self.assertEqual(len(store), 0)\n+\n+ @requests_mock.Mocker()\n+ def test_cache_control_no_cache(self, m):\n+ # verify we cache but always validate when cache-control is no-cache\n+\n+ endpoint = 'https://mock'\n+\n+ path = 'path'\n+ etag = 'etag'\n+ data = {\"a\": 1}\n+\n+ m.get(f\"{endpoint}/{path}\", json=data,\n+ headers={'ETag': etag, 'Cache-Control': f'no-cache, max-age=100'})\n+ m.get(f\"{endpoint}/{path}\",\n+ request_headers={'If-None-Match': etag}, status_code=304,\n+ headers={'ETag': etag, 'Cache-Control': f'no-cache, max-age=100'})\n+\n+ store = {}\n+\n+ with DWaveAPIClient(endpoint=endpoint, cache=dict(store=store), history_size=1) as client:\n+\n+ with self.subTest(\"cache miss\"):\n+ self.assertEqual(len(store), 0)\n+\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+ self.assertEqual(len(store), 2)\n+\n+ with self.subTest(\"cache validated\"):\n+ m.reset_mock()\n+\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+ self.assertEqual(client.session.history[-1].response.status_code, 304)\n", "FAIL_TO_PASS": ["tests/api/test_api_clients.py::TestResponseCaching::test_cache_control_maxage", "tests/api/test_api_clients.py::TestResponseCaching::test_cache_control_no_store"]}, {"instance_id": "dwavesystems__dwave-cloud-client-651", "base_commit": "1f590ecc41eef194096f54022475a3bcd762ac8e", "gold_patch": "diff --git a/dwave/cloud/api/client.py b/dwave/cloud/api/client.py\nindex 366bd31..8160531 100644\n--- a/dwave/cloud/api/client.py\n+++ b/dwave/cloud/api/client.py\n@@ -17,7 +17,9 @@ from __future__ import annotations\n import io\n import hashlib\n import logging\n+import numbers\n import os\n+import warnings\n from collections import deque, namedtuple\n from typing import Callable, Mapping, Optional, Tuple, TypedDict, Union, TYPE_CHECKING\n \n@@ -285,7 +287,7 @@ class CachingSession(VersionedAPISession):\n \n class CacheConfig(TypedDict, total=False):\n enabled: bool\n- maxage: int\n+ maxage: float\n store: Union[Mapping, Callable[[], Mapping]]\n \n # default cache config\n@@ -315,8 +317,9 @@ class CachingSession(VersionedAPISession):\n logger.debug(\"[%s] cache disabled.\", type(self).__name__)\n return\n \n- if not isinstance(_maxage := config.get('maxage'), int) or _maxage < 0:\n- raise ValueError(\"A non-negative integer required for 'maxage'.\")\n+ _maxage = config.get('maxage')\n+ if not isinstance(_maxage, numbers.Real) or _maxage < 0:\n+ raise ValueError(\"A non-negative real value required for 'maxage'.\")\n self._maxage = _maxage\n \n self._store = config['store']\n@@ -399,7 +402,14 @@ class CachingSession(VersionedAPISession):\n # read CachingSession-specific params\n refresh = kwargs.pop('refresh_', False)\n no_cache = kwargs.pop('no_cache_', False)\n- default_maxage = kwargs.pop('maxage_', self._maxage)\n+ default_maxage = kwargs.pop('maxage_', None)\n+ if default_maxage is None:\n+ default_maxage = self._maxage\n+ elif not isinstance(default_maxage, numbers.Real) or default_maxage < 0:\n+ warnings.warn(\n+ f\"non-negative real value required for 'maxage_'; ignoring {default_maxage}\",\n+ UserWarning, stacklevel=2)\n+ default_maxage = self._maxage\n \n if not self._cache_enabled or no_cache or method.lower() != 'get':\n # completely bypass cache lookup and validation\n@@ -435,9 +445,10 @@ class CachingSession(VersionedAPISession):\n logger.debug('cache hit within maxage')\n return make_response(content)\n \n- # conditional request\n- headers = {} if headers is None else headers.copy()\n- headers['If-None-Match'] = meta['etag']\n+ # validate with conditional request if possible\n+ if etag := meta.get('etag'):\n+ headers = {} if headers is None else headers.copy()\n+ headers['If-None-Match'] = etag\n \n res = super().request(method, url, params=params, headers=headers, **kwargs)\n \ndiff --git a/dwave/cloud/api/resources.py b/dwave/cloud/api/resources.py\nindex a0487d7..921d43f 100644\n--- a/dwave/cloud/api/resources.py\n+++ b/dwave/cloud/api/resources.py\n@@ -106,16 +106,16 @@ class Regions(ResourceBase):\n client_class = MetadataAPIClient\n \n @accepts(media_type='application/vnd.dwave.metadata.regions+json', version='~=1.0')\n- def list_regions(self) -> List[models.Region]:\n+ def list_regions(self, **kwargs) -> List[models.Region]:\n path = ''\n- response = self.session.get(path)\n+ response = self.session.get(path, **kwargs)\n regions = response.json()\n return TypeAdapter(List[models.Region]).validate_python(regions)\n \n @accepts(media_type='application/vnd.dwave.metadata.region+json', version='~=1.0')\n- def get_region(self, code: str) -> models.Region:\n+ def get_region(self, code: str, **kwargs) -> models.Region:\n path = '{}'.format(code)\n- response = self.session.get(path)\n+ response = self.session.get(path, **kwargs)\n region = response.json()\n return TypeAdapter(models.Region).validate_python(region)\n \ndiff --git a/dwave/cloud/client/base.py b/dwave/cloud/client/base.py\nindex 4aefa9d..7c64164 100644\n--- a/dwave/cloud/client/base.py\n+++ b/dwave/cloud/client/base.py\n@@ -629,9 +629,13 @@ class Client(object):\n self._poll_workers, self._load_workers):\n worker.join()\n \n- # Close the main thread's session\n+ # Close the main thread's sessions\n self.session.close()\n \n+ solvers_session = getattr(self, '_solvers_session', None)\n+ if solvers_session:\n+ solvers_session.close()\n+\n def __enter__(self):\n \"\"\"Let connections be used in with blocks.\"\"\"\n return self\ndiff --git a/dwave/cloud/regions.py b/dwave/cloud/regions.py\nindex 5e49ae4..3aa10ab 100644\n--- a/dwave/cloud/regions.py\n+++ b/dwave/cloud/regions.py\n@@ -14,37 +14,35 @@\n \n import logging\n import re\n-from functools import partial\n-from typing import Any, Dict, List, Optional, Union\n+from typing import Dict, List, Optional, Union\n from urllib.parse import urlsplit\n \n-from pydantic import TypeAdapter\n-\n from dwave.cloud import api\n from dwave.cloud.api.constants import (\n DEFAULT_REGION, DEFAULT_SOLVER_API_ENDPOINT, DEFAULT_LEAP_API_ENDPOINT,\n DEFAULT_METADATA_API_ENDPOINT)\n from dwave.cloud.config.models import ClientConfig, validate_config_v1\n-from dwave.cloud.utils.decorators import cached\n \n __all__ = ['get_regions']\n \n logger = logging.getLogger(__name__)\n \n-_REGIONS_CACHE_MAXAGE = 7 * 86400 # 7 days\n+_DEFAULT_REGIONS_CACHE_CONFIG = dict(\n+ enabled=True,\n+ maxage=7 * 86400 # 7 days\n+)\n \n \n-@cached.ondisk(maxage=_REGIONS_CACHE_MAXAGE, key='cache_key', bucket='regions')\n-def _fetch_available_regions(cache_key: Any, config: ClientConfig) -> Dict[str, str]:\n+def _fetch_available_regions(config: ClientConfig, **kwargs) -> Dict[str, str]:\n logger.debug(\"Fetching available regions from the Metadata API at %r\",\n config.metadata_api_endpoint)\n \n- with api.Regions.from_config(config) as regions:\n- regions = regions.list_regions()\n- data = TypeAdapter(Any).dump_python(regions)\n+ with api.Regions.from_config(\n+ config, cache=_DEFAULT_REGIONS_CACHE_CONFIG) as regions:\n+ regions = regions.list_regions(**kwargs)\n \n- logger.debug(\"Received region metadata: %r\", data)\n- return data\n+ logger.debug(\"Received region metadata: %r\", regions)\n+ return regions\n \n \n def get_regions(config: Optional[Union[ClientConfig, str, dict]] = None,\n@@ -66,7 +64,8 @@ def get_regions(config: Optional[Union[ClientConfig, str, dict]] = None,\n refresh:\n Force regions cache refresh.\n maxage:\n- Maximum allowed age, in seconds, of cached regions metadata.\n+ Default maximum allowed age, in seconds, of cached regions metadata.\n+ Overridden by Metadata API cache control.\n no_cache:\n Do not use cache.\n \n@@ -77,6 +76,10 @@ def get_regions(config: Optional[Union[ClientConfig, str, dict]] = None,\n .. versionadded:: 0.11.0\n Added :func:`.get_regions`.\n \n+ .. versionchanged:: 0.12.2\n+ ``maxage`` parameter is now just a default value for the maximum allowed\n+ cache age, and it's typically overridden by regions API's cache control.\n+\n \"\"\"\n if isinstance(config, str):\n config = ClientConfig(metadata_api_endpoint=config)\n@@ -87,27 +90,15 @@ def get_regions(config: Optional[Union[ClientConfig, str, dict]] = None,\n elif not isinstance(config, ClientConfig):\n raise TypeError(f\"'config' type {type(config).__name__!r} not supported\")\n \n- # make sure we don't cache by noise in config\n- cache_key = (config.metadata_api_endpoint, config.cert, config.headers,\n- config.proxy, config.permissive_ssl,\n- config.request_retry, config.request_timeout)\n-\n- fetch = partial(_fetch_available_regions,\n- cache_key=cache_key, config=config, refresh_=refresh, maxage_=maxage)\n-\n- if no_cache:\n- fetch = cached.disabled()(fetch)\n-\n try:\n- obj = fetch()\n- except api.exceptions.RequestError as exc:\n+ return _fetch_available_regions(\n+ config=config, refresh_=refresh, maxage_=maxage, no_cache_=no_cache)\n+\n+ except api.exceptions.RequestError:\n logger.debug(\"Metadata API unavailable\", exc_info=True)\n raise ValueError(\n f\"Metadata API unavailable at {config.metadata_api_endpoint!r}\")\n \n- regions = TypeAdapter(List[api.models.Region]).validate_python(obj)\n- return regions\n-\n \n def _infer_leap_api_endpoint(solver_api_endpoint: str,\n region_code: Optional[str] = None) -> str:\ndiff --git a/releasenotes/notes/get_regions-use-cachingsession-8fd9d84b1bbaa53d.yaml b/releasenotes/notes/get_regions-use-cachingsession-8fd9d84b1bbaa53d.yaml\nnew file mode 100644\nindex 0000000..2cf7096\n--- /dev/null\n+++ b/releasenotes/notes/get_regions-use-cachingsession-8fd9d84b1bbaa53d.yaml\n@@ -0,0 +1,6 @@\n+---\n+features:\n+ - |\n+ Enable regions metadata API cache control in ``dwave.cloud.regions.get_regions()``\n+ by switching to ``api.Regions`` built-in caching session.\n+ See `#647 `_.\n", "test_patch": "diff --git a/tests/api/test_api_clients.py b/tests/api/test_api_clients.py\nindex 1f9a0d0..a1df6aa 100644\n--- a/tests/api/test_api_clients.py\n+++ b/tests/api/test_api_clients.py\n@@ -20,6 +20,7 @@ import unittest\n import diskcache\n import requests\n import requests_mock\n+from parameterized import parameterized\n \n from dwave.cloud.api import exceptions, constants\n from dwave.cloud.api.client import (\n@@ -354,8 +355,28 @@ class TestResponseCaching(unittest.TestCase):\n self.assertEqual(client.session._maxage, 5)\n self.assertIsInstance(client.session._store, dict)\n \n+ @parameterized.expand([\n+ (None, ),\n+ (2j, ),\n+ (-1.0, ),\n+ ])\n+ def test_invalid_maxage(self, maxage):\n+ with self.assertRaises(ValueError):\n+ DWaveAPIClient(\n+ endpoint='https://mock', cache=dict(maxage=maxage, store={}))\n+\n+ @parameterized.expand([\n+ (0, ),\n+ (1, ),\n+ (2.0, ),\n+ ])\n+ def test_valid_maxage(self, maxage):\n+ with DWaveAPIClient(endpoint='https://mock',\n+ cache=dict(maxage=maxage, store={})) as client:\n+ self.assertEqual(client.session._maxage, maxage)\n+\n @requests_mock.Mocker()\n- def test_caching_no_cache_control(self, m):\n+ def test_conditional_requests_with_no_cache_control(self, m):\n endpoint = 'https://mock'\n \n path_a = 'path-a'\n@@ -556,3 +577,68 @@ class TestResponseCaching(unittest.TestCase):\n \n self.assertTrue(m.called)\n self.assertEqual(client.session.history[-1].response.status_code, 304)\n+\n+ @requests_mock.Mocker()\n+ def test_time_based_validation_only(self, m):\n+ # when etag is not available, cache validation is based on time/maxage\n+\n+ endpoint = 'https://mock'\n+ path = 'path'\n+ data = {\"a\": 1}\n+\n+ m.get(f\"{endpoint}/{path}\", json=data)\n+\n+ store = {}\n+ maxage = 10\n+\n+ with DWaveAPIClient(endpoint=endpoint,\n+ cache=dict(store=store, maxage=maxage)) as client:\n+\n+ with self.subTest(\"cache miss\"):\n+ self.assertEqual(len(store), 0)\n+\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+ self.assertEqual(len(store), 2) # data + meta\n+\n+ with self.subTest(\"cache hit\"):\n+ m.reset_mock()\n+\n+ with unittest.mock.patch('dwave.cloud.api.client.epochnow',\n+ lambda: time.time() + maxage - 1):\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ # if mock not called, data came from cache\n+ self.assertFalse(m.called)\n+\n+ with self.subTest(\"cache expired\"):\n+ m.reset_mock()\n+\n+ with unittest.mock.patch('dwave.cloud.api.client.epochnow',\n+ lambda: time.time() + maxage + 1):\n+ r = client.session.get(path)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+\n+ with self.subTest(\"ignored maxage=None\"):\n+ m.reset_mock()\n+ store.clear()\n+\n+ r = client.session.get(path, maxage_=None)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\n+\n+ with self.subTest(\"warn about invalid maxage\"):\n+ m.reset_mock()\n+ store.clear()\n+\n+ with self.assertWarns(UserWarning):\n+ r = client.session.get(path, maxage_=-1)\n+ self.assertEqual(r.json(), data)\n+\n+ self.assertTrue(m.called)\ndiff --git a/tests/test_regions.py b/tests/test_regions.py\nindex b6af53d..6e084be 100644\n--- a/tests/test_regions.py\n+++ b/tests/test_regions.py\n@@ -13,11 +13,12 @@\n # limitations under the License.\n \n import unittest\n-from secrets import token_hex\n from unittest import mock\n-import contextlib\n+from typing import List\n \n+import requests_mock\n from parameterized import parameterized\n+from pydantic import TypeAdapter\n \n from dwave.cloud.api.models import Region\n from dwave.cloud.api import constants\n@@ -63,50 +64,29 @@ class GetRegionsInit(unittest.TestCase):\n class GetRegionsFunctionality(unittest.TestCase):\n \n def test_config(self):\n- mock_regions = [\n- Region(code='A', name='Region A', endpoint='http://a/'),\n- Region(code='B', name='Region B', endpoint='http://b/'),\n- ]\n- # use a random mock metadata api to avoid cache contamination with mock data\n- # XXX: alternatively, we flush the cache after this test\n- mock_metadata_api_endpoint = f'https://example.com/meta/{token_hex(8)}/'\n-\n- # mock `api.Regions.from_config().list_regions()` call\n- @contextlib.contextmanager\n- def mock_regions_from_config(*args, **kwargs):\n- class mock_regions_obj:\n- def list_regions(_):\n- return mock_regions\n- yield mock_regions_obj()\n+ # get_regions() caching params are passed down to CachingSession\n \n- with mock.patch(\"dwave.cloud.regions.api.Regions.from_config\",\n- side_effect=mock_regions_from_config) as m:\n+ with mock.patch(\"dwave.cloud.regions.api.Regions.from_config\") as m:\n+ ls = m.return_value.__enter__.return_value.list_regions\n \n with self.subTest('default call'):\n- ret = get_regions(mock_metadata_api_endpoint)\n- m.assert_called()\n- self.assertEqual(ret, mock_regions)\n-\n- with self.subTest('caching'):\n- m.reset_mock()\n- ret = get_regions(mock_metadata_api_endpoint)\n- m.assert_not_called()\n- self.assertEqual(ret, mock_regions)\n+ get_regions()\n+ ls.assert_called()\n \n with self.subTest('cache refresh'):\n m.reset_mock()\n- ret = get_regions(mock_metadata_api_endpoint, refresh=True)\n- m.assert_called()\n+ get_regions(refresh=True)\n+ self.assertTrue(ls.call_args.kwargs.get('refresh_'))\n \n- with self.subTest('cache refresh'):\n+ with self.subTest('cache maxage'):\n m.reset_mock()\n- ret = get_regions(mock_metadata_api_endpoint, maxage=0)\n- m.assert_called()\n+ get_regions(maxage=0)\n+ self.assertEqual(ls.call_args.kwargs.get('maxage_'), 0)\n \n with self.subTest('cache bypass'):\n m.reset_mock()\n- ret = get_regions(mock_metadata_api_endpoint, no_cache=True)\n- m.assert_called()\n+ get_regions(no_cache=True)\n+ self.assertTrue(ls.call_args.kwargs.get('no_cache_'))\n \n @mock.patch(\"dwave.cloud.regions._fetch_available_regions\",\n side_effect=ResourceAccessForbiddenError)\n@@ -114,6 +94,23 @@ class GetRegionsFunctionality(unittest.TestCase):\n with self.assertRaises(ValueError):\n get_regions()\n \n+ @requests_mock.Mocker()\n+ def test_end_to_end_mocked(self, m):\n+\n+ mock_endpoint = 'https://mock'\n+\n+ mock_regions = [\n+ Region(code='A', name='Region A', endpoint='http://a/'),\n+ Region(code='B', name='Region B', endpoint='http://b/'),\n+ ]\n+ mock_json = TypeAdapter(List[Region]).dump_python(mock_regions)\n+\n+ m.get(f\"{mock_endpoint}/regions/\", json=mock_json,\n+ headers={'Content-Type': 'application/vnd.dwave.metadata.regions+json; version=1.0'})\n+\n+ regions = get_regions(mock_endpoint)\n+ self.assertEqual(regions, mock_regions)\n+\n \n class ResolveEndpointsMocked(unittest.TestCase):\n \n", "FAIL_TO_PASS": ["tests/api/test_api_clients.py::TestResponseCaching::test_time_based_validation_only", "tests/api/test_api_clients.py::TestResponseCaching::test_valid_maxage_2", "tests/test_regions.py::GetRegionsFunctionality::test_config"]}], "all_FAIL_TO_PASS": ["tests/api/test_api_clients.py::TestResponseCaching::test_cache_control_maxage", "tests/api/test_api_clients.py::TestResponseCaching::test_cache_control_no_store", "tests/api/test_api_clients.py::TestResponseCaching::test_time_based_validation_only", "tests/api/test_api_clients.py::TestResponseCaching::test_valid_maxage_2", "tests/test_regions.py::GetRegionsFunctionality::test_config"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aio-libs__yarl-1414_x2", "level": 2, "source": "swerebench", "repo": "aio-libs/yarl", "image": "swerebench/sweb.eval.x86_64.aio-libs_1776_yarl-1414:latest", "base_commit": "d6a65ebad5d5f0866446c4a6670ac485a7f0e07f", "num_bugs": 2, "bugs": [{"instance_id": "aio-libs__yarl-1414", "base_commit": "d6a65ebad5d5f0866446c4a6670ac485a7f0e07f", "gold_patch": "diff --git a/CHANGES/1414.feature.rst b/CHANGES/1414.feature.rst\nnew file mode 100644\nindex 0000000..e34d624\n--- /dev/null\n+++ b/CHANGES/1414.feature.rst\n@@ -0,0 +1,2 @@\n+Make error messages include details of incorrect type when ``port`` is not int in :py:meth:`~yarl.URL.build`.\n+-- by :user:`Cycloctane`.\ndiff --git a/yarl/_url.py b/yarl/_url.py\nindex b69149b..6e8f02e 100644\n--- a/yarl/_url.py\n+++ b/yarl/_url.py\n@@ -349,7 +349,7 @@ class URL:\n 'Can\\'t mix \"authority\" with \"user\", \"password\", \"host\" or \"port\".'\n )\n if port is not None and not isinstance(port, int):\n- raise TypeError(\"The port is required to be int.\")\n+ raise TypeError(f\"The port is required to be int, got {type(port)!r}.\")\n if port and not host:\n raise ValueError('Can\\'t build URL with \"port\" but without \"host\".')\n if query and query_string:\n", "test_patch": "diff --git a/tests/test_url_build.py b/tests/test_url_build.py\nindex a5339dd..43f1383 100644\n--- a/tests/test_url_build.py\n+++ b/tests/test_url_build.py\n@@ -66,7 +66,7 @@ def test_build_with_scheme_and_host():\n id=\"port-only\",\n ),\n pytest.param(\n- \"\", TypeError, r\"^The port is required to be int\\.$\", id=\"port-str\"\n+ \"\", TypeError, r\"^The port is required to be int, got .*\\.$\", id=\"port-str\"\n ),\n ],\n )\n", "FAIL_TO_PASS": ["tests/test_url_build.py::test_build_with_port[port-str]"]}, {"instance_id": "aio-libs__yarl-1421", "base_commit": "2b94725e90bb4406cc88fda10375c80d673300df", "gold_patch": "diff --git a/CHANGES/111.feature.rst b/CHANGES/111.feature.rst\nnew file mode 120000\nindex 0000000..96c7efc\n--- /dev/null\n+++ b/CHANGES/111.feature.rst\n@@ -0,0 +1,1 @@\n+1421.feature.rst\n\\ No newline at end of file\ndiff --git a/CHANGES/1421.feature.rst b/CHANGES/1421.feature.rst\nnew file mode 100644\nindex 0000000..bb8f7de\n--- /dev/null\n+++ b/CHANGES/1421.feature.rst\n@@ -0,0 +1,1 @@\n+Added ``keep_query`` and ``keep_fragment`` flags in the :py:meth:`yarl.URL.with_path`, :py:meth:`yarl.URL.with_name` and :py:meth:`yarl.URL.with_suffix` methods, allowing users to optionally retain the query string and fragment in the resulting URL when replacing the path -- by :user:`paul-nameless`.\ndiff --git a/docs/api.rst b/docs/api.rst\nindex f9698fb..69417bd 100644\n--- a/docs/api.rst\n+++ b/docs/api.rst\n@@ -652,10 +652,16 @@ section generates a new :class:`URL` instance.\n >>> URL('http://example.com:8888').with_port(None)\n URL('http://example.com')\n \n-.. method:: URL.with_path(path)\n+.. method:: URL.with_path(path, *, keep_query=False, keep_fragment=False)\n \n Return a new URL with *path* replaced, encode *path* if needed.\n \n+ If ``keep_query=True`` or ``keep_fragment=True`` it retains the existing query or fragment in the URL.\n+\n+ .. versionchanged:: 1.18\n+\n+ Added *keep_query* and *keep_fragment* parameters.\n+\n .. doctest::\n \n >>> URL('http://example.com/').with_path('/path/to')\n@@ -857,13 +863,19 @@ section generates a new :class:`URL` instance.\n >>> URL('http://example.com/path#frag').with_fragment(None)\n URL('http://example.com/path')\n \n-.. method:: URL.with_name(name)\n+.. method:: URL.with_name(name, *, keep_query=False, keep_fragment=False)\n \n Return a new URL with *name* (last part of *path*) replaced and\n cleaned up *query* and *fragment* parts.\n \n Name is encoded if needed.\n \n+ If ``keep_query=True`` or ``keep_fragment=True`` it retains the existing query or fragment in the URL.\n+\n+ .. versionchanged:: 1.18\n+\n+ Added *keep_query* and *keep_fragment* parameters.\n+\n .. doctest::\n \n >>> URL('http://example.com/path/to?arg#frag').with_name('new')\n@@ -871,13 +883,19 @@ section generates a new :class:`URL` instance.\n >>> URL('http://example.com/path/to').with_name(\"\u0456\u043c'\u044f\")\n URL('http://example.com/path/%D1%96%D0%BC%27%D1%8F')\n \n-.. method:: URL.with_suffix(suffix)\n+.. method:: URL.with_suffix(suffix, *, keep_query=False, keep_fragment=False)\n \n Return a new URL with *suffix* (file extension of *name*) replaced and\n cleaned up *query* and *fragment* parts.\n \n Name is encoded if needed.\n \n+ If ``keep_query=True`` or ``keep_fragment=True`` it retains the existing query or fragment in the URL.\n+\n+ .. versionchanged:: 1.18\n+\n+ Added *keep_query* and *keep_fragment* parameters.\n+\n .. doctest::\n \n >>> URL('http://example.com/path/to?arg#frag').with_suffix('.doc')\ndiff --git a/yarl/_url.py b/yarl/_url.py\nindex d20a610..4bf3c2d 100644\n--- a/yarl/_url.py\n+++ b/yarl/_url.py\n@@ -1114,7 +1114,14 @@ class URL:\n self._scheme, netloc, self._path, self._query, self._fragment\n )\n \n- def with_path(self, path: str, *, encoded: bool = False) -> \"URL\":\n+ def with_path(\n+ self,\n+ path: str,\n+ *,\n+ encoded: bool = False,\n+ keep_query: bool = False,\n+ keep_fragment: bool = False,\n+ ) -> \"URL\":\n \"\"\"Return a new URL with path replaced.\"\"\"\n netloc = self._netloc\n if not encoded:\n@@ -1123,7 +1130,9 @@ class URL:\n path = normalize_path(path) if \".\" in path else path\n if path and path[0] != \"/\":\n path = f\"/{path}\"\n- return self._from_parts(self._scheme, netloc, path, \"\", \"\")\n+ query = self._query if keep_query else \"\"\n+ fragment = self._fragment if keep_fragment else \"\"\n+ return self._from_parts(self._scheme, netloc, path, query, fragment)\n \n @overload\n def with_query(self, query: Query) -> \"URL\": ...\n@@ -1271,7 +1280,13 @@ class URL:\n self._scheme, self._netloc, self._path, self._query, raw_fragment\n )\n \n- def with_name(self, name: str) -> \"URL\":\n+ def with_name(\n+ self,\n+ name: str,\n+ *,\n+ keep_query: bool = False,\n+ keep_fragment: bool = False,\n+ ) -> \"URL\":\n \"\"\"Return a new URL with name (last part of path) replaced.\n \n Query and fragment parts are cleaned up.\n@@ -1298,9 +1313,18 @@ class URL:\n parts[-1] = name\n if parts[0] == \"/\":\n parts[0] = \"\" # replace leading '/'\n- return self._from_parts(self._scheme, netloc, \"/\".join(parts), \"\", \"\")\n \n- def with_suffix(self, suffix: str) -> \"URL\":\n+ query = self._query if keep_query else \"\"\n+ fragment = self._fragment if keep_fragment else \"\"\n+ return self._from_parts(self._scheme, netloc, \"/\".join(parts), query, fragment)\n+\n+ def with_suffix(\n+ self,\n+ suffix: str,\n+ *,\n+ keep_query: bool = False,\n+ keep_fragment: bool = False,\n+ ) -> \"URL\":\n \"\"\"Return a new URL with suffix (file extension of name) replaced.\n \n Query and fragment parts are cleaned up.\n@@ -1316,7 +1340,8 @@ class URL:\n raise ValueError(f\"{self!r} has an empty name\")\n old_suffix = self.raw_suffix\n name = name + suffix if not old_suffix else name[: -len(old_suffix)] + suffix\n- return self.with_name(name)\n+\n+ return self.with_name(name, keep_query=keep_query, keep_fragment=keep_fragment)\n \n def join(self, url: \"URL\") -> \"URL\":\n \"\"\"Join URLs\n", "test_patch": "diff --git a/tests/test_url.py b/tests/test_url.py\nindex 0a8ed90..da68c2f 100644\n--- a/tests/test_url.py\n+++ b/tests/test_url.py\n@@ -10,7 +10,7 @@ _WHATWG_C0_CONTROL_OR_SPACE = (\n \"\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f \"\n )\n _VERTICAL_COLON = \"\\ufe13\" # normalizes to \":\"\n-_FULL_WITH_NUMBER_SIGN = \"\\uFF03\" # normalizes to \"#\"\n+_FULL_WITH_NUMBER_SIGN = \"\\uff03\" # normalizes to \"#\"\n _ACCOUNT_OF = \"\\u2100\" # normalizes to \"a/c\"\n \n \n@@ -1240,6 +1240,47 @@ def test_with_path_fragment():\n assert str(url.with_path(\"/test\")) == \"http://example.com/test\"\n \n \n+@pytest.mark.parametrize(\n+ (\"original_url\", \"keep_query\", \"keep_fragment\", \"expected_url\"),\n+ [\n+ pytest.param(\n+ \"http://example.com?a=b#frag\",\n+ True,\n+ False,\n+ \"http://example.com/test?a=b\",\n+ id=\"query-only\",\n+ ),\n+ pytest.param(\n+ \"http://example.com?a=b#frag\",\n+ False,\n+ True,\n+ \"http://example.com/test#frag\",\n+ id=\"fragment-only\",\n+ ),\n+ pytest.param(\n+ \"http://example.com?a=b#frag\",\n+ True,\n+ True,\n+ \"http://example.com/test?a=b#frag\",\n+ id=\"all\",\n+ ),\n+ pytest.param(\n+ \"http://example.com?a=b#frag\",\n+ False,\n+ False,\n+ \"http://example.com/test\",\n+ id=\"none\",\n+ ),\n+ ],\n+)\n+def test_with_path_keep_query_keep_fragment_flags(\n+ original_url, keep_query, keep_fragment, expected_url\n+):\n+ url = URL(original_url)\n+ url2 = url.with_path(\"/test\", keep_query=keep_query, keep_fragment=keep_fragment)\n+ assert str(url2) == expected_url\n+\n+\n def test_with_path_empty():\n url = URL(\"http://example.com/test\")\n assert str(url.with_path(\"\")) == \"http://example.com\"\n@@ -1319,6 +1360,47 @@ def test_with_name():\n assert url2.path == \"/a/c\"\n \n \n+@pytest.mark.parametrize(\n+ (\"original_url\", \"keep_query\", \"keep_fragment\", \"expected_url\"),\n+ [\n+ pytest.param(\n+ \"http://example.com/path/to?a=b#frag\",\n+ True,\n+ False,\n+ \"http://example.com/path/newname?a=b\",\n+ id=\"query-only\",\n+ ),\n+ pytest.param(\n+ \"http://example.com/path/to?a=b#frag\",\n+ False,\n+ True,\n+ \"http://example.com/path/newname#frag\",\n+ id=\"fragment-only\",\n+ ),\n+ pytest.param(\n+ \"http://example.com/path/to?a=b#frag\",\n+ True,\n+ True,\n+ \"http://example.com/path/newname?a=b#frag\",\n+ id=\"all\",\n+ ),\n+ pytest.param(\n+ \"http://example.com/path/to?a=b#frag\",\n+ False,\n+ False,\n+ \"http://example.com/path/newname\",\n+ id=\"none\",\n+ ),\n+ ],\n+)\n+def test_with_name_keep_query_keep_fragment_flags(\n+ original_url, keep_query, keep_fragment, expected_url\n+):\n+ url = URL(original_url)\n+ url2 = url.with_name(\"newname\", keep_query=keep_query, keep_fragment=keep_fragment)\n+ assert str(url2) == expected_url\n+\n+\n def test_with_name_for_naked_path():\n url = URL(\"http://example.com\")\n url2 = url.with_name(\"a\")\n@@ -1409,6 +1491,47 @@ def test_with_suffix():\n assert url2.path == \"/a/b.c\"\n \n \n+@pytest.mark.parametrize(\n+ (\"original_url\", \"keep_query\", \"keep_fragment\", \"expected_url\"),\n+ [\n+ pytest.param(\n+ \"http://example.com/path/to.txt?a=b#frag\",\n+ True,\n+ False,\n+ \"http://example.com/path/to.md?a=b\",\n+ id=\"query-only\",\n+ ),\n+ pytest.param(\n+ \"http://example.com/path/to.txt?a=b#frag\",\n+ False,\n+ True,\n+ \"http://example.com/path/to.md#frag\",\n+ id=\"fragment-only\",\n+ ),\n+ pytest.param(\n+ \"http://example.com/path/to.txt?a=b#frag\",\n+ True,\n+ True,\n+ \"http://example.com/path/to.md?a=b#frag\",\n+ id=\"all\",\n+ ),\n+ pytest.param(\n+ \"http://example.com/path/to.txt?a=b#frag\",\n+ False,\n+ False,\n+ \"http://example.com/path/to.md\",\n+ id=\"none\",\n+ ),\n+ ],\n+)\n+def test_with_suffix_keep_query_keep_fragment_flags(\n+ original_url, keep_query, keep_fragment, expected_url\n+):\n+ url = URL(original_url)\n+ url2 = url.with_suffix(\".md\", keep_query=keep_query, keep_fragment=keep_fragment)\n+ assert str(url2) == expected_url\n+\n+\n def test_with_suffix_for_naked_path():\n url = URL(\"http://example.com\")\n with pytest.raises(ValueError) as excinfo:\n", "FAIL_TO_PASS": ["tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[none]", "tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[all]", "tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[query-only]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[query-only]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[query-only]", "tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[fragment-only]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[fragment-only]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[none]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[all]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[fragment-only]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[all]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[none]"]}], "all_FAIL_TO_PASS": ["tests/test_url_build.py::test_build_with_port[port-str]", "tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[none]", "tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[all]", "tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[query-only]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[query-only]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[query-only]", "tests/test_url.py::test_with_name_keep_query_keep_fragment_flags[fragment-only]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[fragment-only]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[none]", "tests/test_url.py::test_with_path_keep_query_keep_fragment_flags[all]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[fragment-only]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[all]", "tests/test_url.py::test_with_suffix_keep_query_keep_fragment_flags[none]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aws__chalice-1537_x2", "level": 2, "source": "swerebench", "repo": "aws/chalice", "image": "swerebench/sweb.eval.x86_64.aws_1776_chalice-1537:latest", "base_commit": "54f70f1140967bf0f441fe092e5a06364affdda3", "num_bugs": 2, "bugs": [{"instance_id": "aws__chalice-1537", "base_commit": "54f70f1140967bf0f441fe092e5a06364affdda3", "gold_patch": "diff --git a/.changes/next-release/28759404254-bugfix-Blueprints-51536.json b/.changes/next-release/28759404254-bugfix-Blueprints-51536.json\nnew file mode 100644\nindex 0000000..ebb1743\n--- /dev/null\n+++ b/.changes/next-release/28759404254-bugfix-Blueprints-51536.json\n@@ -0,0 +1,5 @@\n+{\n+ \"type\": \"bugfix\",\n+ \"category\": \"Blueprints\",\n+ \"description\": \"Fix regression when invoking Lambda functions from blueprints (#1535)\"\n+}\ndiff --git a/chalice/app.py b/chalice/app.py\nindex a9506a9..08671a6 100644\n--- a/chalice/app.py\n+++ b/chalice/app.py\n@@ -769,27 +769,7 @@ class DecoratorAPI(object):\n return _register_handler\n \n def _wrap_handler(self, handler_type, handler_name, user_handler):\n- event_classes = {\n- 'on_s3_event': S3Event,\n- 'on_sns_message': SNSEvent,\n- 'on_sqs_message': SQSEvent,\n- 'on_cw_event': CloudWatchEvent,\n- 'on_kinesis_record': KinesisEvent,\n- 'on_dynamodb_record': DynamoDBEvent,\n- 'schedule': CloudWatchEvent,\n- 'lambda_function': LambdaFunctionEvent,\n- }\n- middleware_mapping = {\n- 'on_s3_event': 's3',\n- 'on_sns_message': 'sns',\n- 'on_sqs_message': 'sqs',\n- 'on_cw_event': 'cloudwatch',\n- 'on_kinesis_record': 'kinesis',\n- 'on_dynamodb_record': 'dynamodb',\n- 'schedule': 'scheduled',\n- 'lambda_function': 'pure_lambda',\n- }\n- if handler_type in event_classes:\n+ if handler_type in _EVENT_CLASSES:\n if handler_type == 'lambda_function':\n # We have to wrap existing @app.lambda_function()\n # handlers for backwards compat reasons so we can\n@@ -799,9 +779,9 @@ class DecoratorAPI(object):\n # here.\n user_handler = PureLambdaWrapper(user_handler)\n return EventSourceHandler(\n- user_handler, event_classes[handler_type],\n+ user_handler, _EVENT_CLASSES[handler_type],\n middleware_handlers=self._get_middleware_handlers(\n- event_type=middleware_mapping[handler_type],\n+ event_type=_MIDDLEWARE_MAPPING[handler_type],\n )\n )\n \n@@ -1506,6 +1486,14 @@ class EventSourceHandler(BaseLambdaHandler):\n self._middleware_handlers = middleware_handlers\n self.handler = None\n \n+ @property\n+ def middleware_handlers(self):\n+ return self._middleware_handlers\n+\n+ @middleware_handlers.setter\n+ def middleware_handlers(self, value):\n+ self._middleware_handlers = value\n+\n def __call__(self, event, context):\n event_obj = self.event_class(event, context)\n if self.handler is None:\n@@ -1906,17 +1894,6 @@ class Blueprint(DecoratorAPI):\n # these methods are not public in the sense that we don't want users to\n # call them, they're available for blueprints to use in order to avoid\n # boilerplate code.\n- def _wrap_handler(self, handler_type, handler_name, user_handler):\n- # This deferred wrap handler will be called when we call\n- # Blueprint.register() and provide an app object. Once\n- # we have access to an app, we can call the actual _wrap_handler\n- # which will have access to middleware.\n- @functools.wraps(user_handler)\n- def _defer_wrap_handler(app):\n- # pylint: disable=protected-access\n- return app._wrap_handler(handler_type, handler_name,\n- user_handler)\n- return _defer_wrap_handler\n \n def register_middleware(self, func, event_type='all'):\n self._deferred_registrations.append(\n@@ -1932,18 +1909,22 @@ class Blueprint(DecoratorAPI):\n # we have to duplicate either the methods or the params in this\n # class. We're using _register_handler as a tradeoff for cutting\n # down on the duplication.\n- self._deferred_registrations.append(\n+ def _register_blueprint_handler(app, options):\n+ if handler_type in _EVENT_CLASSES:\n+ # pylint: disable=protected-access\n+ wrapped_handler.middleware_handlers = \\\n+ app._get_middleware_handlers(\n+ _MIDDLEWARE_MAPPING[handler_type])\n # pylint: disable=protected-access\n- lambda app, options: app._register_handler(\n- handler_type, name, user_handler, wrapped_handler(app),\n+ app._register_handler(\n+ handler_type, name, user_handler, wrapped_handler,\n kwargs, options\n )\n- )\n+ self._deferred_registrations.append(_register_blueprint_handler)\n \n def _get_middleware_handlers(self, event_type):\n- raise RuntimeError(\"Blueprints are unable to retrieve middleware \"\n- \"handlers, must be registered to an app using \"\n- \"register_blueprint()\")\n+ # This will get filled in later during the registration process.\n+ return []\n \n \n # This class is used to convert any existing/3rd party decorators\n@@ -1977,3 +1958,27 @@ class ConvertToMiddleware(object):\n if isinstance(event, Request):\n return event.to_original_event(), event.lambda_context\n return event.to_dict(), event.context\n+\n+\n+_EVENT_CLASSES = {\n+ 'on_s3_event': S3Event,\n+ 'on_sns_message': SNSEvent,\n+ 'on_sqs_message': SQSEvent,\n+ 'on_cw_event': CloudWatchEvent,\n+ 'on_kinesis_record': KinesisEvent,\n+ 'on_dynamodb_record': DynamoDBEvent,\n+ 'schedule': CloudWatchEvent,\n+ 'lambda_function': LambdaFunctionEvent,\n+}\n+\n+\n+_MIDDLEWARE_MAPPING = {\n+ 'on_s3_event': 's3',\n+ 'on_sns_message': 'sns',\n+ 'on_sqs_message': 'sqs',\n+ 'on_cw_event': 'cloudwatch',\n+ 'on_kinesis_record': 'kinesis',\n+ 'on_dynamodb_record': 'dynamodb',\n+ 'schedule': 'scheduled',\n+ 'lambda_function': 'pure_lambda',\n+}\n", "test_patch": "diff --git a/tests/unit/test_app.py b/tests/unit/test_app.py\nindex bf5d5b4..8a2a261 100644\n--- a/tests/unit/test_app.py\n+++ b/tests/unit/test_app.py\n@@ -2185,6 +2185,23 @@ def test_can_combine_multiple_blueprints_in_single_app():\n assert sorted(list(myapp.routes)) == ['/bar', '/foo']\n \n \n+def test_can_preserve_signature_on_blueprint():\n+ myapp = app.Chalice('myapp')\n+ foo = app.Blueprint('foo')\n+\n+ @foo.lambda_function()\n+ def first(event, context):\n+ return {'foo': 'bar'}\n+\n+ myapp.register_blueprint(foo)\n+\n+ # The handler string given to a blueprint\n+ # is the \"module.function_name\" so we have\n+ # to ensure we can continue to invoke the\n+ # function with its expected signature.\n+ assert first({}, None) == {'foo': 'bar'}\n+\n+\n def test_doc_saved_on_route():\n myapp = app.Chalice('myapp')\n \n", "FAIL_TO_PASS": ["tests/unit/test_app.py::test_can_preserve_signature_on_blueprint"]}, {"instance_id": "aws__chalice-1539", "base_commit": "98932be51160a2c079b48be7bbed2afd67ef1261", "gold_patch": "diff --git a/.changes/next-release/30774531330-bugfix-Websocket-824.json b/.changes/next-release/30774531330-bugfix-Websocket-824.json\nnew file mode 100644\nindex 0000000..b7ad7dd\n--- /dev/null\n+++ b/.changes/next-release/30774531330-bugfix-Websocket-824.json\n@@ -0,0 +1,5 @@\n+{\n+ \"type\": \"bugfix\",\n+ \"category\": \"Websocket\",\n+ \"description\": \"Fix websocket client configuration when using a custom domain (#1503)\"\n+}\ndiff --git a/chalice/app.py b/chalice/app.py\nindex 8dad18f..959bb98 100644\n--- a/chalice/app.py\n+++ b/chalice/app.py\n@@ -579,11 +579,15 @@ class APIGateway(object):\n \n class WebsocketAPI(object):\n _WEBSOCKET_ENDPOINT_TEMPLATE = 'https://{domain_name}/{stage}'\n+ _REGION_ENV_VARS = ['AWS_REGION', 'AWS_DEFAULT_REGION']\n \n- def __init__(self):\n+ def __init__(self, env=None):\n self.session = None\n self._endpoint = None\n self._client = None\n+ if env is None:\n+ env = os.environ\n+ self._env = env\n \n def configure(self, domain_name, stage):\n if self._endpoint is not None:\n@@ -593,6 +597,37 @@ class WebsocketAPI(object):\n stage=stage,\n )\n \n+ def configure_from_api_id(self, api_id, stage):\n+ if self._endpoint is not None:\n+ return\n+ region_name = self._get_region()\n+ domain_name = '{api_id}.execute-api.{region}.amazonaws.com'.format(\n+ api_id=api_id, region=region_name)\n+ self.configure(domain_name, stage)\n+\n+ def _get_region(self):\n+ # Attempt to get the region so we can configure the\n+ # apigatewaymanagementapi client. We'll first try\n+ # retrieving this value from env vars because these should\n+ # always be set in the Lambda runtime environment.\n+ for varname in self._REGION_ENV_VARS:\n+ if varname in self._env:\n+ return self._env[varname]\n+ # As a last attempt we'll try to retrieve the region\n+ # from the currently configured region. If the session\n+ # isn't configured or we can't get the region, we have\n+ # no choice but to error out.\n+ if self.session is not None:\n+ region_name = self.session.region_name\n+ if region_name is not None:\n+ return region_name\n+ raise ValueError(\n+ \"Unable to retrieve the region name when configuring the \"\n+ \"websocket client. Either set the 'AWS_REGION' environment \"\n+ \"variable or assign 'app.websocket_api.session' to a boto3 \"\n+ \"session.\"\n+ )\n+\n def _get_client(self):\n if self.session is None:\n raise ValueError(\n@@ -1515,8 +1550,8 @@ class WebsocketEventSourceHandler(EventSourceHandler):\n self.handler = None\n \n def __call__(self, event, context):\n- self.websocket_api.configure(\n- event['requestContext']['domainName'],\n+ self.websocket_api.configure_from_api_id(\n+ event['requestContext']['apiId'],\n event['requestContext']['stage'],\n )\n super(WebsocketEventSourceHandler, self).__call__(event, context)\n", "test_patch": "diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py\nindex dbe77cd..e1e663f 100644\n--- a/tests/unit/conftest.py\n+++ b/tests/unit/conftest.py\n@@ -187,9 +187,10 @@ def create_websocket_event():\n return {\n 'requestContext': {\n 'routeKey': route_key,\n- 'domainName': 'abcd1234.us-west-2.amazonaws.com',\n+ 'domainName': 'abcd1234.execute-api.us-west-2.amazonaws.com',\n 'stage': 'api',\n 'connectionId': 'ABCD1234=',\n+ 'apiId': 'abcd1234',\n },\n 'body': body,\n }\ndiff --git a/tests/unit/test_app.py b/tests/unit/test_app.py\nindex 8a2a261..1c59ea7 100644\n--- a/tests/unit/test_app.py\n+++ b/tests/unit/test_app.py\n@@ -28,6 +28,7 @@ from chalice.app import (\n WebsocketDisconnectedError,\n WebsocketEventSourceHandler,\n ConvertToMiddleware,\n+ WebsocketAPI\n )\n from chalice import __version__ as chalice_version\n from chalice.deploy.validate import ExperimentalFeatureError\n@@ -139,9 +140,10 @@ class FakeClient(object):\n \n \n class FakeSession(object):\n- def __init__(self, client=None):\n+ def __init__(self, client=None, region_name='us-west-2'):\n self.calls = []\n self._client = client\n+ self.region_name = region_name\n \n def client(self, name, endpoint_url=None):\n self.calls.append((name, endpoint_url))\n@@ -2633,7 +2635,7 @@ def test_can_route_websocket_connect_message(sample_websocket_app,\n assert calls[0][0] == 'connect'\n event = calls[0][1]\n assert isinstance(event, WebsocketEvent)\n- assert event.domain_name == 'abcd1234.us-west-2.amazonaws.com'\n+ assert event.domain_name == 'abcd1234.execute-api.us-west-2.amazonaws.com'\n assert event.stage == 'api'\n assert event.connection_id == 'ABCD1234='\n \n@@ -2652,7 +2654,7 @@ def test_can_route_websocket_disconnect_message(sample_websocket_app,\n assert calls[0][0] == 'disconnect'\n event = calls[0][1]\n assert isinstance(event, WebsocketEvent)\n- assert event.domain_name == 'abcd1234.us-west-2.amazonaws.com'\n+ assert event.domain_name == 'abcd1234.execute-api.us-west-2.amazonaws.com'\n assert event.stage == 'api'\n assert event.connection_id == 'ABCD1234='\n \n@@ -2671,7 +2673,7 @@ def test_can_route_websocket_default_message(sample_websocket_app,\n assert calls[0][0] == 'default'\n event = calls[0][1]\n assert isinstance(event, WebsocketEvent)\n- assert event.domain_name == 'abcd1234.us-west-2.amazonaws.com'\n+ assert event.domain_name == 'abcd1234.execute-api.us-west-2.amazonaws.com'\n assert event.stage == 'api'\n assert event.connection_id == 'ABCD1234='\n assert event.body == 'foo bar'\n@@ -2688,7 +2690,44 @@ def test_can_configure_client_on_connect(sample_websocket_app,\n \n assert demo.websocket_api.session.calls == [\n ('apigatewaymanagementapi',\n- 'https://abcd1234.us-west-2.amazonaws.com/api'),\n+ 'https://abcd1234.execute-api.us-west-2.amazonaws.com/api'),\n+ ]\n+\n+\n+def test_uses_api_id_not_domain_name(sample_websocket_app,\n+ create_websocket_event):\n+ demo, calls = sample_websocket_app\n+ client = FakeClient()\n+ demo.websocket_api.session = FakeSession(client)\n+ event = create_websocket_event('$connect')\n+ # If you configure a custom domain name, we should still use the\n+ # original domainName generated from API gateway when configuring\n+ # the apigatewaymanagementapi client.\n+ event['requestContext']['domainName'] = 'api.custom-domain-name.com'\n+ handler = websocket_handler_for_route('$connect', demo)\n+ handler(event, context=None)\n+ assert demo.websocket_api.session.calls == [\n+ ('apigatewaymanagementapi',\n+ 'https://abcd1234.execute-api.us-west-2.amazonaws.com/api'),\n+ ]\n+\n+\n+def test_fallsback_to_session_if_needed(sample_websocket_app,\n+ create_websocket_event):\n+ demo, calls = sample_websocket_app\n+ client = FakeClient()\n+ demo.websocket_api = WebsocketAPI(env={})\n+ demo.websocket_api.session = FakeSession(client, region_name='us-east-2')\n+ event = create_websocket_event('$connect')\n+ # If you configure a custom domain name, we should still use the\n+ # original domainName generated from API gateway when configuring\n+ # the apigatewaymanagementapi client.\n+ event['requestContext']['domainName'] = 'api.custom-domain-name.com'\n+ handler = websocket_handler_for_route('$connect', demo)\n+ handler(event, context=None)\n+ assert demo.websocket_api.session.calls == [\n+ ('apigatewaymanagementapi',\n+ 'https://abcd1234.execute-api.us-east-2.amazonaws.com/api'),\n ]\n \n \n@@ -2703,7 +2742,7 @@ def test_can_configure_client_on_disconnect(sample_websocket_app,\n \n assert demo.websocket_api.session.calls == [\n ('apigatewaymanagementapi',\n- 'https://abcd1234.us-west-2.amazonaws.com/api'),\n+ 'https://abcd1234.execute-api.us-west-2.amazonaws.com/api'),\n ]\n \n \n@@ -2719,7 +2758,7 @@ def test_can_configure_client_on_message(sample_websocket_app,\n \n assert demo.websocket_api.session.calls == [\n ('apigatewaymanagementapi',\n- 'https://abcd1234.us-west-2.amazonaws.com/api'),\n+ 'https://abcd1234.execute-api.us-west-2.amazonaws.com/api'),\n ]\n \n \n@@ -2736,7 +2775,7 @@ def test_does_only_configure_client_once(sample_websocket_app,\n \n assert demo.websocket_api.session.calls == [\n ('apigatewaymanagementapi',\n- 'https://abcd1234.us-west-2.amazonaws.com/api'),\n+ 'https://abcd1234.execute-api.us-west-2.amazonaws.com/api'),\n ]\n \n \n@@ -3239,6 +3278,7 @@ class TestMiddleware:\n 'domainName': 'example.com',\n 'stage': 'dev',\n 'connectionId': 'abcd',\n+ 'apiId': 'abcd1234',\n },\n 'body': \"body\"\n }\n@@ -3325,6 +3365,7 @@ class TestMiddleware:\n 'domainName': 'example.com',\n 'stage': 'dev',\n 'connectionId': 'abcd',\n+ 'apiId': 'abcd1234',\n },\n 'body': \"body\"\n })\n", "FAIL_TO_PASS": ["tests/unit/test_app.py::test_uses_api_id_not_domain_name", "tests/unit/test_app.py::test_fallsback_to_session_if_needed"]}], "all_FAIL_TO_PASS": ["tests/unit/test_app.py::test_can_preserve_signature_on_blueprint", "tests/unit/test_app.py::test_uses_api_id_not_domain_name", "tests/unit/test_app.py::test_fallsback_to_session_if_needed"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "just-work__fffw-68_x2", "level": 2, "source": "swerebench", "repo": "just-work/fffw", "image": "swerebench/sweb.eval.x86_64.just-work_1776_fffw-68:latest", "base_commit": "ec1451b6347ac0c9a8da3947651d7b15ebf0212d", "num_bugs": 2, "bugs": [{"instance_id": "just-work__fffw-68", "base_commit": "ec1451b6347ac0c9a8da3947651d7b15ebf0212d", "gold_patch": "diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py\nindex ff1baa2..1ef1505 100644\n--- a/fffw/encoding/filters.py\n+++ b/fffw/encoding/filters.py\n@@ -3,7 +3,7 @@ from typing import Union, List, cast\n \n from fffw.graph import base\n from fffw.encoding import mixins\n-from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO\n+from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO, AudioMeta\n from fffw.graph.meta import StreamType, Device\n from fffw.wrapper.params import Params, param\n \n@@ -330,16 +330,26 @@ class Concat(Filter):\n duration = TS(0)\n scenes = []\n streams: List[str] = []\n+ samples = 0\n+ sampling_rate = None\n for meta in metadata:\n duration += meta.duration\n+ if isinstance(meta, AudioMeta):\n+ samples += meta.samples\n+ if sampling_rate is None:\n+ sampling_rate = meta.sampling_rate\n+ else:\n+ assert sampling_rate == meta.sampling_rate\n scenes.extend(meta.scenes)\n for stream in meta.streams:\n if not streams or streams[-1] != stream:\n # Add all streams for each concatenated metadata and remove\n # contiguous duplicates.\n streams.append(stream)\n- return replace(metadata[0], duration=duration,\n- scenes=scenes, streams=streams)\n+ kwargs = dict(duration=duration, scenes=scenes, streams=streams)\n+ if samples != 0:\n+ kwargs['samples'] = samples\n+ return replace(metadata[0], **kwargs)\n \n \n @dataclass\n", "test_patch": "diff --git a/tests/test_graph.py b/tests/test_graph.py\nindex 5e82f6e..905464c 100644\n--- a/tests/test_graph.py\n+++ b/tests/test_graph.py\n@@ -35,7 +35,10 @@ class FilterGraphTestCase(TestCase):\n par=1.0,\n duration=300.0,\n )\n- self.audio_metadata = audio_meta_data()\n+ self.audio_metadata = audio_meta_data(\n+ duration=200.0,\n+ sampling_rate=48000,\n+ samples_count=200*48000)\n \n self.source = inputs.Input(\n input_file='input.mp4',\n@@ -239,6 +242,25 @@ class FilterGraphTestCase(TestCase):\n self.assertEqual(self.video_metadata.duration + vs.meta.duration,\n vm.duration)\n \n+ def test_concat_audio_metadata(self):\n+ \"\"\"\n+ Concat filter sums samples count for audio streams.\n+ \"\"\"\n+ audio_meta = audio_meta_data(duration=1000.0, sampling_rate=48000,\n+ samples_count=48000 * 1000)\n+ a = inputs.Stream(AUDIO, meta=audio_meta)\n+ self.input_list.append(inputs.input_file('second.mp4', a))\n+ concat = a | Concat(AUDIO)\n+ self.source | concat\n+\n+ concat > self.output\n+\n+ am = cast(AudioMeta, self.output.codecs[-1].get_meta_data())\n+ self.assertEqual(self.audio_metadata.duration + audio_meta.duration,\n+ am.duration)\n+ self.assertEqual(self.audio_metadata.samples + audio_meta.samples,\n+ am.samples)\n+\n def test_trim_metadata(self):\n \"\"\"\n Trim filter sets start and changes stream duration.\n", "FAIL_TO_PASS": ["tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata"]}, {"instance_id": "just-work__fffw-70", "base_commit": "448ed0a0b1dee4640a86e0ecce056f5fb1505c3b", "gold_patch": "diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py\nindex 1ef1505..43ed444 100644\n--- a/fffw/encoding/filters.py\n+++ b/fffw/encoding/filters.py\n@@ -202,6 +202,10 @@ class Split(AutoFilter):\n return ''\n return str(self.output_count)\n \n+ def validate_edge_device(self, edge: base.Edge) -> None:\n+ # Any device is supported\n+ return\n+\n \n @dataclass\n class Trim(AutoFilter):\n@@ -351,6 +355,10 @@ class Concat(Filter):\n kwargs['samples'] = samples\n return replace(metadata[0], **kwargs)\n \n+ def validate_edge_device(self, edge: base.Edge) -> None:\n+ # Any device is supported\n+ return\n+\n \n @dataclass\n class Overlay(VideoFilter):\n", "test_patch": "diff --git a/tests/test_graph.py b/tests/test_graph.py\nindex 905464c..6b9bb4c 100644\n--- a/tests/test_graph.py\n+++ b/tests/test_graph.py\n@@ -305,3 +305,17 @@ class FilterGraphTestCase(TestCase):\n \n cuda = meta.Device(hardware='cuda', name='foo')\n self.source.video | Upload(device=cuda) | ScaleCuda(640, 360)\n+\n+ def test_concat_split_allows_any_hardware(self):\n+ \"\"\"\n+ Concat and split filters allow any hardware acceleration.\n+ \"\"\"\n+ try:\n+ cuda = meta.Device(hardware='cuda', name='foo')\n+ hw = self.source.video | Upload(device=cuda)\n+ split = hw | Split(VIDEO, output_count=2)\n+ concat = Concat(VIDEO, input_count=2)\n+ split | concat\n+ split | concat\n+ except ValueError: # pragma: no cover\n+ self.fail(\"hardware validation unexpectedly failed\")\n", "FAIL_TO_PASS": ["tests/test_graph.py::FilterGraphTestCase::test_concat_split_allows_any_hardware"]}], "all_FAIL_TO_PASS": ["tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata", "tests/test_graph.py::FilterGraphTestCase::test_concat_split_allows_any_hardware"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NREL__hescore-hpxml-113_x2", "level": 2, "source": "swerebench", "repo": "NREL/hescore-hpxml", "image": "swerebench/sweb.eval.x86_64.nrel_1776_hescore-hpxml-113:latest", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "num_bugs": 2, "bugs": [{"instance_id": "NREL__hescore-hpxml-113", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "gold_patch": "diff --git a/docs/source/translation/zone_window.rst b/docs/source/translation/zone_window.rst\nindex 480fe5db..5062926c 100644\n--- a/docs/source/translation/zone_window.rst\n+++ b/docs/source/translation/zone_window.rst\n@@ -13,17 +13,21 @@ assumed to mean the sum of the areas of the windows that the ``Window`` element\n represents. Each ``Window`` is then assigned to a side of the building in one of\n two ways:\n \n- #. By association with a particular wall.\n #. By inspecting the azimuth or orientation of the window.\n+ #. By association with a particular wall.\n \n-If an HPXML window has the ``AttachedToWall`` element, the id reference in that\n-element is used to find the associated wall and the side of the building that\n-the window faces is inferred from the :ref:`wall orientation `.\n-\n-If there is not an ``AttachedToWall`` element, the side is determined via the\n-``Azimuth`` or ``Orientation`` elements with preference given to the\n-``Azimuth`` if present. If the window falls between two sides of the house, the\n-window area is divided between the sides of the house evenly. \n+If there is an ``Orientation`` or ``Azimuth`` element, the side is determined\n+via the one of those elements with preference given to the ``Azimuth`` if\n+present. If the window falls between two sides of the house, the window area is\n+divided between the sides of the house evenly. \n+\n+If ``Orientation`` or ``Azimuth`` are missing and the HPXML window has the\n+``AttachedToWall`` element, the id reference in that element is used to find the\n+associated wall and the side of the building that the window faces is inferred\n+from the :ref:`wall orientation `. If the window is attached to\n+a foundation wall, the orientation/azimuth must be provided on the ``Window``\n+element because foundation walls do not have orientation or azimuth elements\n+available.\n \n The areas on each side of the house are summed and the :ref:`window-prop` are\n determined independently for each side of the house. Since HPXML requires that\ndiff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 55a58b86..102d0f48 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -1530,29 +1530,33 @@ class HPXMLtoHEScoreTranslator(object):\n \n # Window side\n window_sides = []\n- attached_to_wall_id = xpath(hpxmlwndw, 'h:AttachedToWall/@idref')\n- if attached_to_wall_id is not None:\n- # Give preference to the Attached to Wall element to determine the side of the house.\n- for side, walls in list(hpxmlwalls.items()):\n- for wall in walls:\n- if attached_to_wall_id == wall['id']:\n- window_sides.append(side)\n- break\n+ window_id = xpath(hpxmlwndw, 'h:SystemIdentifier/@id')\n+ try:\n+ # Get the aziumuth or orientation if they exist\n+ wndw_azimuth = self.get_nearest_azimuth(xpath(hpxmlwndw, 'h:Azimuth/text()'),\n+ xpath(hpxmlwndw, 'h:Orientation/text()'))\n+ except TranslationError:\n+ # The window doesn't have orientation/azimuth information, get from wall\n+ attached_to_wall_id = xpath(hpxmlwndw, 'h:AttachedToWall/@idref')\n+ if attached_to_wall_id is not None:\n+ for side, walls in list(hpxmlwalls.items()):\n+ for wall in walls:\n+ if attached_to_wall_id == wall['id']:\n+ window_sides.append(side)\n+ break\n+ if not window_sides:\n+ raise TranslationError('The Window[SystemIdentifier/@id=\"{}\"] has no Azimuth or Orientation, and the Window/AttachedToWall/@idref of \"{}\" didn\\'t reference a Wall element.'.format(window_id, attached_to_wall_id)) # noqa: E501\n+ else:\n+ raise TranslationError(\n+ 'Window[SystemIdentifier/@id=\"{}\"] doesn\\'t have Azimuth, Orientation, or AttachedToWall. At least one is required.'.format(window_id) # noqa: E501\n+ )\n else:\n- # If there's not Attached to Wall element, figure it out from the Azimuth/Orientation\n+ # Azimuth found, associate with a side\n try:\n- wndw_azimuth = self.get_nearest_azimuth(xpath(hpxmlwndw, 'h:Azimuth/text()'),\n- xpath(hpxmlwndw, 'h:Orientation/text()'))\n- except TranslationError:\n- # there's no directional information in the window\n- raise TranslationError(\n- 'All windows need to have either an AttachedToWall, Orientation, or Azimuth sub element.')\n- else:\n- try:\n- window_sides = [sidemap[wndw_azimuth]]\n- except KeyError:\n- # the direction of the window is between sides, split area\n- window_sides = [sidemap[unspin_azimuth(wndw_azimuth + x)] for x in (-45, 45)]\n+ window_sides = [sidemap[wndw_azimuth]]\n+ except KeyError:\n+ # the direction of the window is between sides, split area\n+ window_sides = [sidemap[unspin_azimuth(wndw_azimuth + x)] for x in (-45, 45)]\n \n # Assign properties and areas to the correct side of the house\n windowd['area'] /= float(len(window_sides))\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex 1f6fd6cb..31a901bc 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -333,9 +333,23 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el.getparent().remove(el)\n self.assertRaisesRegexp(\n TranslationError,\n- r'All windows need to have either an AttachedToWall, Orientation, or Azimuth sub element\\.',\n+ r'Window\\[SystemIdentifier/@id=\"\\w+\"\\] doesn\\'t have Azimuth, Orientation, or AttachedToWall. At least one is required.', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n+ def test_window_only_attached_to_foundation_wall(self):\n+ tr = self._load_xmlfile('house4')\n+ window_orientation = self.xpath('//h:Window[1]/h:Orientation')\n+ window = window_orientation.getparent()\n+ etree.SubElement(window, tr.addns('h:AttachedToWall'), attrib={'idref': 'crawlwall'})\n+ self._do_compare('house4')\n+\n+ window.remove(window_orientation)\n+ self.assertRaisesRegexp(\n+ TranslationError,\n+ r'The Window\\[SystemIdentifier/@id=\"\\w+\"\\] has no Azimuth or Orientation, and the .* didn\\'t reference a Wall element.', # noqa E501\n+ tr.hpxml_to_hescore_dict\n+ )\n+\n def test_window_attached_to_wall(self):\n filebase = 'house6'\n tr = self._load_xmlfile(filebase)\n", "FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_window_orientation", "tests/tests.py::TestOtherHouses::test_window_only_attached_to_foundation_wall"]}, {"instance_id": "NREL__hescore-hpxml-115", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "gold_patch": "diff --git a/docs/source/translation/hvac.rst b/docs/source/translation/hvac.rst\nindex ec1bc7e9..cdc7169f 100644\n--- a/docs/source/translation/hvac.rst\n+++ b/docs/source/translation/hvac.rst\n@@ -1,26 +1,35 @@\n HVAC Systems\n ############\n \n-HEScore allows the definition of up to two HVAC systems which can each include a heating system, cooling system, and duct system.\n-To determine which HPXML elements are associated, the ``DistributionSystem`` subelement of\n-``HeatingSystem``, ``CoolingSystem``, ``HeatPump`` is used to find the link to ``HVACDistributionSystem``.\n-Systems that share the same ``HVACDistributionSystem`` are determined to be the same HVAC system for HEScore.\n-\n-Sometimes an HVAC system will not share ducts, for instance a central air conditioner and boiler.\n-In that case, if each of those systems serve a fraction of the home's load within 5% of each other\n-they will be combined into the same HVAC system for HEScore.\n-If a ``HeatingSystem`` and ``CoolingSystem`` that are associated with the same ``HVACDistributionSystem`` serve differing\n-portions of the house's heating and cooling load, that weight is averaged to find the combined system weight.\n-\n-If either a heating or cooling system meets all of the load and two systems of the opposite (cooling or heating, respectively)\n-are required to meet the same fraction of the load, the larger system is split into two for input into HEScore.\n-\n-To determine the fraction of the home's heating and cooling load each system serves,\n-each HPXML heating or cooling system is required to have ``FloorAreaServed`` or, alternatively ``FracLoadServed``.\n-The two combined HVAC systems that serve the greatest portion of the house's load are sent to HEScore.\n-\n-For details about how each kind of ``HeatingSystem``, ``CoolingSystem``, ``HeatPump``, and ``HVACDistributionSystem``\n-are translated into HEScore inputs, see the appropriate subsection:\n+HEScore allows the definition of up to two HVAC systems which can each include a\n+heating system, cooling system, and duct system. To determine which HPXML\n+elements are associated, the ``DistributionSystem`` subelement of\n+``HeatingSystem``, ``CoolingSystem``, ``HeatPump`` is used to find the link to\n+``HVACDistributionSystem``. Systems that share the same\n+``HVACDistributionSystem`` are determined to be the same HVAC system for\n+HEScore.\n+\n+Sometimes an HVAC system will not share ducts, for instance a central air\n+conditioner and boiler. In that case, if each of those systems serve a fraction\n+of the home's load within 5% of each other they will be combined into the same\n+HVAC system for HEScore. If a ``HeatingSystem`` and ``CoolingSystem`` that are\n+associated with the same ``HVACDistributionSystem`` serve differing portions of\n+the house's heating and cooling load, that weight is averaged to find the\n+combined system weight.\n+\n+If either a heating or cooling system meets all of the load and two systems of\n+the opposite (cooling or heating, respectively) are required to meet the same\n+fraction of the load, the larger system is split into two for input into\n+HEScore.\n+\n+To determine the fraction of the home's heating and cooling load each system\n+serves, each HPXML heating and cooling system is required to have\n+``FloorAreaServed`` or, alternatively ``FracLoadServed``. The two combined HVAC\n+systems that serve the greatest portion of the house's load are sent to HEScore.\n+\n+For details about how each kind of ``HeatingSystem``, ``CoolingSystem``,\n+``HeatPump``, and ``HVACDistributionSystem`` are translated into HEScore inputs,\n+see the appropriate subsection:\n \n .. toctree::\n :maxdepth: 1\ndiff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 55a58b86..dc737aa9 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -688,7 +688,7 @@ class HPXMLtoHEScoreTranslator(object):\n bldg['zone']['window_construction_same'] = False\n bldg['zone']['zone_wall'] = self._get_building_zone_wall(b, bldg['about'])\n bldg['systems'] = OrderedDict()\n- bldg['systems']['hvac'] = self._get_hvac(b)\n+ bldg['systems']['hvac'] = self._get_hvac(b, bldg['about'])\n bldg['systems']['domestic_hot_water'] = self._get_systems_dhw(b)\n generation = self._get_generation(b)\n if generation:\n@@ -1678,7 +1678,7 @@ class HPXMLtoHEScoreTranslator(object):\n zone_window['solar_screen'] = max(list(window_sunscreen_areas.items()), key=lambda x: x[1])[0]\n return zone_wall\n \n- def _get_hvac(self, b):\n+ def _get_hvac(self, b, bldg_about):\n \n def _get_dict_of_hpxml_elements_by_id(xpathexpr):\n return_dict = {}\n@@ -1786,48 +1786,41 @@ class HPXMLtoHEScoreTranslator(object):\n distribution_systems[key] = self._get_hvac_distribution(el)\n \n # Determine the weighting factors\n- def _choose_weighting_factor(systems_dict):\n- weighting_factor_priority = ['_floorarea', '_fracload']\n- found_weighting_factor = False\n- for weighting_factor in weighting_factor_priority:\n- weighting_factor_list = [item[weighting_factor] for item in list(systems_dict.values())]\n- if None not in weighting_factor_list and len(weighting_factor_list) > 0:\n- found_weighting_factor = True\n- break\n- if not found_weighting_factor:\n- if len(systems_dict) == 1:\n- list(systems_dict.values())[0]['_fracload'] = 1.0\n- weighting_factor_list = [1.0]\n- weighting_factor = '_fracload'\n- else:\n- raise TranslationError(\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed.')\n- return weighting_factor, sum(weighting_factor_list)\n- if heating_systems:\n- heating_weighting_factor, heating_weight_sum = _choose_weighting_factor(heating_systems)\n- else:\n- heating_weight_sum = 0\n- heating_weighting_factor = None\n- if cooling_systems:\n- cooling_weighting_factor, cooling_weight_sum = _choose_weighting_factor(cooling_systems)\n- else:\n- cooling_weight_sum = 0\n- cooling_weighting_factor = None\n \n- if cooling_systems and heating_systems and heating_weighting_factor != cooling_weighting_factor:\n+ # If there's only one heating or cooling system and no weighting elements, fill it in.\n+ for heating_or_cooling_systems in (heating_systems, cooling_systems):\n+ if len(heating_or_cooling_systems) == 1:\n+ for key, hvac_sys in heating_or_cooling_systems.items():\n+ if hvac_sys.get('_floorarea') is None and hvac_sys.get('_fracload') is None:\n+ hvac_sys['_fracload'] = 1.0\n+ hvac_sys['_floorarea'] = bldg_about['conditioned_floor_area']\n+\n+ # Choose a weighting factor that all the heating and cooling systems use\n+ all_systems = []\n+ all_systems.extend(heating_systems.values())\n+ all_systems.extend(cooling_systems.values())\n+ found_weighting_factor = False\n+ for weighting_factor in ['_floorarea', '_fracload']:\n+ if None not in [x.get(weighting_factor) for x in all_systems]:\n+ found_weighting_factor = True\n+ break\n+ if not found_weighting_factor:\n raise TranslationError(\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed.')\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed.' # noqa: E501\n+ )\n \n- weight_sum = max(heating_weight_sum, cooling_weight_sum)\n- del heating_weight_sum\n- del cooling_weight_sum\n+ # Calculate the sum of the weights (total fraction or floor area)\n+ weight_sum = max(\n+ sum([x[weighting_factor] for x in heating_systems.values()]),\n+ sum([x[weighting_factor] for x in cooling_systems.values()])\n+ )\n \n # Ensure that heating and cooling systems attached to the same ducts are within 5% of each other\n # in terms of fraction of the load served.\n for duct_id, (htg_id, clg_id) in list(dist_heating_cooling_map.items()):\n try:\n- htg_weight = old_div(heating_systems[htg_id][heating_weighting_factor], weight_sum)\n- clg_weight = old_div(cooling_systems[clg_id][cooling_weighting_factor], weight_sum)\n+ htg_weight = old_div(heating_systems[htg_id][weighting_factor], weight_sum)\n+ clg_weight = old_div(cooling_systems[clg_id][weighting_factor], weight_sum)\n except KeyError:\n continue\n if abs(htg_weight - clg_weight) > 0.051:\n@@ -1859,9 +1852,9 @@ class HPXMLtoHEScoreTranslator(object):\n for dist_sys_id, (htg_sys_id, clg_sys_id) in list(dist_heating_cooling_map.items()):\n weights_to_average = []\n if htg_sys_id is not None:\n- weights_to_average.append(old_div(heating_systems[htg_sys_id][heating_weighting_factor], weight_sum))\n+ weights_to_average.append(old_div(heating_systems[htg_sys_id][weighting_factor], weight_sum))\n if clg_sys_id is not None:\n- weights_to_average.append(old_div(cooling_systems[clg_sys_id][cooling_weighting_factor], weight_sum))\n+ weights_to_average.append(old_div(cooling_systems[clg_sys_id][weighting_factor], weight_sum))\n avg_sys_weight = old_div(sum(weights_to_average), len(weights_to_average))\n hvac_systems_ids.add(IDsAndWeights(htg_sys_id, clg_sys_id, dist_sys_id, avg_sys_weight))\n \n@@ -1875,7 +1868,7 @@ class HPXMLtoHEScoreTranslator(object):\n heatpump_id,\n heatpump_id,\n None,\n- old_div(heating_systems[heatpump_id][heating_weighting_factor], weight_sum)))\n+ old_div(heating_systems[heatpump_id][weighting_factor], weight_sum)))\n \n # Add the singletons to the list\n for htg_sys_id in singleton_heating_systems:\n@@ -1883,13 +1876,13 @@ class HPXMLtoHEScoreTranslator(object):\n htg_sys_id,\n None,\n None,\n- old_div(heating_systems[htg_sys_id][heating_weighting_factor], weight_sum)))\n+ old_div(heating_systems[htg_sys_id][weighting_factor], weight_sum)))\n for clg_sys_id in singleton_cooling_systems:\n hvac_systems_ids.add(IDsAndWeights(\n None,\n clg_sys_id,\n None,\n- old_div(cooling_systems[clg_sys_id][cooling_weighting_factor], weight_sum)))\n+ old_div(cooling_systems[clg_sys_id][weighting_factor], weight_sum)))\n \n # Split and combine systems by fraction as needed #45\n singleton_heating_systems = []\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex 1f6fd6cb..a6cd505f 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -410,7 +410,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = self.xpath('//h:HeatPump[1]/h:FloorAreaServed')\n el.getparent().remove(el)\n self.assertRaisesRegexp(TranslationError,\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed',\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n def test_missing_cooling_weighting_factor(self):\n@@ -420,7 +420,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = self.xpath('//h:CoolingSystem[2]/h:FloorAreaServed')\n el.getparent().remove(el)\n self.assertRaisesRegexp(TranslationError,\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed',\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n def test_bad_duct_location(self):\n@@ -1179,7 +1179,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n aircond.insert(-1, el)\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 3213})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1229,7 +1229,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n tr.xpath(ducts2, 'h:SystemIdentifier').attrib['id'] = 'ducts2'\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1275,7 +1275,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n clgsys_floor_area_el.text = str(total_floor_area)\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1325,7 +1325,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n \n # Get HEScore inputs and sort by fraction\n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1348,7 +1348,21 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n frac_cool_load_served.text = '1.0'\n clg_sys_eff.addprevious(frac_cool_load_served)\n b = self.xpath('h:Building[1]')\n- tr._get_hvac(b)\n+ tr._get_hvac(b, {\"conditioned_floor_area\": 2400})\n+\n+ def test_different_weighting_factors(self):\n+ tr = self._load_xmlfile('hescore_min')\n+ htg_sys = self.xpath('//h:HeatingSystem')\n+ frac_heat_load_served = etree.SubElement(htg_sys, tr.addns('h:FractionHeatLoadServed'))\n+ frac_heat_load_served.text = '1.0'\n+ heating_floor_area_served = etree.SubElement(htg_sys, tr.addns('h:FloorAreaServed'))\n+ heating_floor_area_served.text = '2400'\n+ clg_sys_eff = self.xpath('//h:CoolingSystem/h:AnnualCoolingEfficiency')\n+ frac_cool_load_served = etree.Element(tr.addns('h:FractionCoolLoadServed'))\n+ frac_cool_load_served.text = '1.0'\n+ clg_sys_eff.addprevious(frac_cool_load_served)\n+ b = self.xpath('h:Building[1]')\n+ tr._get_hvac(b, {\"conditioned_floor_area\": 2400})\n \n \n class TestPhotovoltaics(unittest.TestCase, ComparatorBase):\n", "FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_cooling_weighting_factor", "tests/tests.py::TestOtherHouses::test_missing_heating_weighting_factor", "tests/tests.py::TestHVACFractions::test_allow_5pct_diff", "tests/tests.py::TestHVACFractions::test_boiler_roomac", "tests/tests.py::TestHVACFractions::test_different_weighting_factors", "tests/tests.py::TestHVACFractions::test_furnace_baseboard_centralac", "tests/tests.py::TestHVACFractions::test_furnace_heat_pump", "tests/tests.py::TestHVACFractions::test_wall_furnace_baseboard_centralac"]}], "all_FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_window_orientation", "tests/tests.py::TestOtherHouses::test_window_only_attached_to_foundation_wall", "tests/tests.py::TestOtherHouses::test_missing_cooling_weighting_factor", "tests/tests.py::TestOtherHouses::test_missing_heating_weighting_factor", "tests/tests.py::TestHVACFractions::test_allow_5pct_diff", "tests/tests.py::TestHVACFractions::test_boiler_roomac", "tests/tests.py::TestHVACFractions::test_different_weighting_factors", "tests/tests.py::TestHVACFractions::test_furnace_baseboard_centralac", "tests/tests.py::TestHVACFractions::test_furnace_heat_pump", "tests/tests.py::TestHVACFractions::test_wall_furnace_baseboard_centralac"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "encode__httpx-861_x2", "level": 2, "source": "swerebench", "repo": "encode/httpx", "image": "swerebench/sweb.eval.x86_64.encode_1776_httpx-861:latest", "base_commit": "43ec09c3cbb089edd2e83ccc717fb95beef0c189", "num_bugs": 2, "bugs": [{"instance_id": "encode__httpx-861", "base_commit": "43ec09c3cbb089edd2e83ccc717fb95beef0c189", "gold_patch": "diff --git a/httpx/_content_streams.py b/httpx/_content_streams.py\nindex 5f3237e..afffed3 100644\n--- a/httpx/_content_streams.py\n+++ b/httpx/_content_streams.py\n@@ -323,7 +323,7 @@ def encode(\n Handles encoding the given `data`, `files`, and `json`, returning\n a `ContentStream` implementation.\n \"\"\"\n- if data is None:\n+ if not data:\n if json is not None:\n return JSONStream(json=json)\n elif files:\n@@ -331,7 +331,7 @@ def encode(\n else:\n return ByteStream(body=b\"\")\n elif isinstance(data, dict):\n- if files is not None:\n+ if files:\n return MultipartStream(data=data, files=files, boundary=boundary)\n else:\n return URLEncodedStream(data=data)\n", "test_patch": "diff --git a/tests/test_content_streams.py b/tests/test_content_streams.py\nindex 6aa91f4..c5eb961 100644\n--- a/tests/test_content_streams.py\n+++ b/tests/test_content_streams.py\n@@ -189,6 +189,18 @@ async def test_multipart_data_and_files_content():\n )\n \n \n+@pytest.mark.asyncio\n+async def test_empty_request():\n+ stream = encode(data={}, files={})\n+ sync_content = b\"\".join([part for part in stream])\n+ async_content = b\"\".join([part async for part in stream])\n+\n+ assert stream.can_replay()\n+ assert stream.get_headers() == {}\n+ assert sync_content == b\"\"\n+ assert async_content == b\"\"\n+\n+\n def test_invalid_argument():\n with pytest.raises(TypeError):\n encode(123)\n", "FAIL_TO_PASS": ["tests/test_content_streams.py::test_empty_request"]}, {"instance_id": "encode__httpx-883", "base_commit": "21f533774f87292c2381376eb40f3216a48eee06", "gold_patch": "diff --git a/docs/api.md b/docs/api.md\nindex 3889d8c..c63d4ec 100644\n--- a/docs/api.md\n+++ b/docs/api.md\n@@ -38,6 +38,13 @@\n :docstring:\n :members: headers cookies params request get head options post put patch delete build_request send close\n \n+## `AsyncClient`\n+\n+::: httpx.AsyncClient\n+ :docstring:\n+ :members: headers cookies params request get head options post put patch delete build_request send\n+\n+\n ## `Response`\n \n *An HTTP response.*\ndiff --git a/httpx/_client.py b/httpx/_client.py\nindex 2a310e2..3976522 100644\n--- a/httpx/_client.py\n+++ b/httpx/_client.py\n@@ -426,7 +426,7 @@ class Client(BaseClient):\n request URLs.\n * **dispatch** - *(optional)* A dispatch class to use for sending requests\n over the network.\n- * **app** - *(optional)* An ASGI application to send requests to,\n+ * **app** - *(optional)* An WSGI application to send requests to,\n rather than sending actual network requests.\n * **trust_env** - *(optional)* Enables or disables usage of environment\n variables for configuration.\ndiff --git a/httpx/_content_streams.py b/httpx/_content_streams.py\nindex afffed3..dd6c51f 100644\n--- a/httpx/_content_streams.py\n+++ b/httpx/_content_streams.py\n@@ -71,8 +71,6 @@ class ByteStream(ContentStream):\n self.body = body.encode(\"utf-8\") if isinstance(body, str) else body\n \n def get_headers(self) -> typing.Dict[str, str]:\n- if not self.body:\n- return {}\n content_length = str(len(self.body))\n return {\"Content-Length\": content_length}\n \n", "test_patch": "diff --git a/tests/client/test_headers.py b/tests/client/test_headers.py\nindex 22b0ba1..5c4dbb4 100755\n--- a/tests/client/test_headers.py\n+++ b/tests/client/test_headers.py\n@@ -40,6 +40,7 @@ async def test_client_header():\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"connection\": \"keep-alive\",\n+ \"content-length\": \"0\",\n \"example-header\": \"example-value\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{__version__}\",\n@@ -61,6 +62,7 @@ async def test_header_merge():\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"connection\": \"keep-alive\",\n+ \"content-length\": \"0\",\n \"host\": \"example.org\",\n \"user-agent\": \"python-myclient/0.2.1\",\n \"x-auth-token\": \"FooBarBazToken\",\n@@ -82,6 +84,7 @@ async def test_header_merge_conflicting_headers():\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"connection\": \"keep-alive\",\n+ \"content-length\": \"0\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{__version__}\",\n \"x-auth-token\": \"BazToken\",\n@@ -105,6 +108,7 @@ async def test_header_update():\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"connection\": \"keep-alive\",\n+ \"content-length\": \"0\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{__version__}\",\n }\n@@ -117,6 +121,7 @@ async def test_header_update():\n \"accept-encoding\": \"gzip, deflate, br\",\n \"another-header\": \"AThing\",\n \"connection\": \"keep-alive\",\n+ \"content-length\": \"0\",\n \"host\": \"example.org\",\n \"user-agent\": \"python-myclient/0.2.1\",\n }\n@@ -147,6 +152,7 @@ async def test_host_with_auth_and_port_in_url():\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"connection\": \"keep-alive\",\n+ \"content-length\": \"0\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{__version__}\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n@@ -171,6 +177,7 @@ async def test_host_with_non_default_port_in_url():\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"connection\": \"keep-alive\",\n+ \"content-length\": \"0\",\n \"host\": \"example.org:123\",\n \"user-agent\": f\"python-httpx/{__version__}\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\ndiff --git a/tests/client/test_redirects.py b/tests/client/test_redirects.py\nindex 190ff09..63403a6 100644\n--- a/tests/client/test_redirects.py\n+++ b/tests/client/test_redirects.py\n@@ -279,7 +279,7 @@ async def test_body_redirect():\n response = await client.post(url, data=data)\n assert response.url == URL(\"https://example.org/redirect_body_target\")\n assert response.json()[\"body\"] == \"Example request body\"\n- assert \"content-length\" in response.json()[\"headers\"]\n+ assert response.json()[\"headers\"][\"content-length\"] == \"20\"\n \n \n @pytest.mark.usefixtures(\"async_environment\")\n@@ -293,7 +293,7 @@ async def test_no_body_redirect():\n response = await client.post(url, data=data)\n assert response.url == URL(\"https://example.org/redirect_body_target\")\n assert response.json()[\"body\"] == \"\"\n- assert \"content-length\" not in response.json()[\"headers\"]\n+ assert response.json()[\"headers\"][\"content-length\"] == \"0\"\n \n \n @pytest.mark.usefixtures(\"async_environment\")\ndiff --git a/tests/models/test_requests.py b/tests/models/test_requests.py\nindex c72e0af..0461394 100644\n--- a/tests/models/test_requests.py\n+++ b/tests/models/test_requests.py\n@@ -10,7 +10,7 @@ def test_request_repr():\n \n def test_no_content():\n request = httpx.Request(\"GET\", \"http://example.org\")\n- assert \"Content-Length\" not in request.headers\n+ assert request.headers[\"Content-Length\"] == \"0\"\n \n \n def test_content_length_header():\ndiff --git a/tests/test_content_streams.py b/tests/test_content_streams.py\nindex c5eb961..84999ef 100644\n--- a/tests/test_content_streams.py\n+++ b/tests/test_content_streams.py\n@@ -25,7 +25,9 @@ async def test_empty_content():\n async_content = b\"\".join([part async for part in stream])\n \n assert stream.can_replay()\n- assert stream.get_headers() == {}\n+ assert stream.get_headers() == {\n+ \"Content-Length\": \"0\",\n+ }\n assert sync_content == b\"\"\n assert async_content == b\"\"\n \n@@ -196,7 +198,9 @@ async def test_empty_request():\n async_content = b\"\".join([part async for part in stream])\n \n assert stream.can_replay()\n- assert stream.get_headers() == {}\n+ assert stream.get_headers() == {\n+ \"Content-Length\": \"0\",\n+ }\n assert sync_content == b\"\"\n assert async_content == b\"\"\n \n", "FAIL_TO_PASS": ["tests/client/test_headers.py::test_client_header", "tests/client/test_headers.py::test_header_merge", "tests/client/test_headers.py::test_header_merge_conflicting_headers", "tests/client/test_headers.py::test_header_update", "tests/client/test_headers.py::test_host_with_auth_and_port_in_url", "tests/client/test_headers.py::test_host_with_non_default_port_in_url", "tests/client/test_redirects.py::test_no_body_redirect[asyncio]", "tests/client/test_redirects.py::test_no_body_redirect[trio]", "tests/models/test_requests.py::test_no_content", "tests/test_content_streams.py::test_empty_content", "tests/test_content_streams.py::test_empty_request"]}], "all_FAIL_TO_PASS": ["tests/test_content_streams.py::test_empty_request", "tests/client/test_headers.py::test_client_header", "tests/client/test_headers.py::test_header_merge", "tests/client/test_headers.py::test_header_merge_conflicting_headers", "tests/client/test_headers.py::test_header_update", "tests/client/test_headers.py::test_host_with_auth_and_port_in_url", "tests/client/test_headers.py::test_host_with_non_default_port_in_url", "tests/client/test_redirects.py::test_no_body_redirect[asyncio]", "tests/client/test_redirects.py::test_no_body_redirect[trio]", "tests/models/test_requests.py::test_no_content", "tests/test_content_streams.py::test_empty_content", "tests/test_content_streams.py::test_empty_request"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "dlr-eoc__ukis-pysat-37_x2", "level": 2, "source": "swerebench", "repo": "dlr-eoc/ukis-pysat", "image": "swerebench/sweb.eval.x86_64.dlr-eoc_1776_ukis-pysat-37:latest", "base_commit": "5e8ae0f5aa92c083b20147b8ac794fa3ae97f321", "num_bugs": 2, "bugs": [{"instance_id": "dlr-eoc__ukis-pysat-37", "base_commit": "5e8ae0f5aa92c083b20147b8ac794fa3ae97f321", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 7d28bc2..ba1146c 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -20,7 +20,7 @@ Added\n *****\r\n - ``raster.Image()``: expanded test_arr to test AttributeError #31\r\n - ``raster.Image()``: optional dimorder for arr and according test #31\r\n-- dn2toa tests and testfiles #17\r\n+- `dn2toa` tests and testfiles #17\r\n - ``data.source()``: accept WKT string as AOI #26\r\n - ``data.source()``: check if an AOI string is a file or a WKT string #26\r\n \r\n@@ -31,6 +31,7 @@ Fixed\n Changed\r\n *******\r\n - ``raster.Image()``: changed ``dn2toa(platform, metadata, wavelengths)`` to ``dn2toa(platform, mtl_file, wavelengths)`` #17\r\n+- ``raster.Image()``: auto-update of in-memory `dataset` #35\r\n \r\n \r\n [0.3.0] (2020-05-26)\r\ndiff --git a/docs/conf.py b/docs/conf.py\nindex a33e834..367a590 100644\n--- a/docs/conf.py\n+++ b/docs/conf.py\n@@ -29,6 +29,7 @@ version = str(subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip())\n # -- General configuration ---------------------------------------------------\r\n \r\n master_doc = 'index'\r\n+autoclass_content = 'both'\r\n \r\n # Add any Sphinx extension module names here, as strings. They can be\r\n # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\r\ndiff --git a/ukis_pysat/raster.py b/ukis_pysat/raster.py\nindex 398e040..fa4d337 100644\n--- a/ukis_pysat/raster.py\n+++ b/ukis_pysat/raster.py\n@@ -29,6 +29,12 @@ logger = logging.getLogger(__name__)\n \r\n class Image:\r\n def __init__(self, path=None, dataset=None, arr=None, dimorder=\"first\"):\r\n+ \"\"\"\r\n+ :param path: str, path to raster (default: None)\r\n+ :param dataset: rasterio.io.DatasetReader (default: None)\r\n+ :param arr: np.ndarray (default: None)\r\n+ :param dimorder: order of channels or bands 'first' or 'last' (default: 'first)\r\n+ \"\"\"\r\n if path:\r\n if isinstance(path, str):\r\n self.dataset = rasterio.open(path)\r\n@@ -50,6 +56,7 @@ class Image:\n \r\n @property\r\n def arr(self):\r\n+ \"\"\"array property\"\"\"\r\n if self.dimorder == \"first\":\r\n return self.__arr\r\n elif self.dimorder == \"last\":\r\n@@ -67,12 +74,13 @@ class Image:\n return windows.bounds(valid_data_window, windows.transform(valid_data_window, self.transform))\r\n \r\n def mask_image(self, bbox, crop=True, pad=False, **kwargs):\r\n- \"\"\"\r\n- TODO https://github.com/mapbox/rasterio/issues/995\r\n+ \"\"\"Mask the area outside of the input shapes with no data.\r\n+\r\n :param bbox: bounding box of type tuple or Shapely Polygon\r\n :param crop: bool, see rasterio.mask. Optional, (default: True)\r\n :param pad: pads image, should only be used when bbox.bounds extent img.bounds, optional (default: False)\r\n \"\"\"\r\n+ # TODO https://github.com/mapbox/rasterio/issues/995\r\n if pad:\r\n self.dataset = self._pad_to_bbox(bbox, **kwargs).open()\r\n \r\n@@ -83,6 +91,9 @@ class Image:\n else:\r\n raise TypeError(f\"bbox must be of type tuple or Shapely Polygon\")\r\n \r\n+ # update for further processing\r\n+ self.dataset = self.__update_dataset().open()\r\n+\r\n def _pad_to_bbox(self, bbox, mode=\"constant\", constant_values=0):\r\n \"\"\"Buffers array with biggest difference to bbox and adjusts affine transform matrix. Can be used to fill\r\n array with nodata values before masking in case bbox only partially overlaps dataset bounds.\r\n@@ -90,7 +101,7 @@ class Image:\n :param bbox: bounding box of type tuple or Shapely Polygon\r\n :param mode: str, how to pad, see rasterio.pad. Optional (default: 'constant')\r\n :param constant_values: nodata value, padding should be filled with, optional (default: 0)\r\n- :return: open, buffered dataset in memory\r\n+ :return: closed, buffered dataset in memory\r\n \"\"\"\r\n if isinstance(bbox, polygon.Polygon):\r\n bbox = bbox.bounds\r\n@@ -117,6 +128,13 @@ class Image:\n \r\n self.__arr = destination\r\n \r\n+ return self.__update_dataset()\r\n+\r\n+ def __update_dataset(self):\r\n+ \"\"\"Update dataset without writing to file after it theoretically changed.\r\n+\r\n+ :return: closed dataset in memory\r\n+ \"\"\"\r\n mem_profile = self.dataset.meta\r\n mem_profile.update(\r\n {\"height\": self.__arr.shape[-2], \"width\": self.__arr.shape[-1], \"transform\": self.transform,}\r\n@@ -171,6 +189,7 @@ class Image:\n self.__arr = destination\r\n self.transform = transform\r\n self.crs = dst_crs\r\n+ self.dataset = self.__update_dataset().open()\r\n \r\n def dn2toa(self, platform, mtl_file=None, wavelengths=None):\r\n \"\"\"This method converts digital numbers to top of atmosphere reflectance, like described here:\r\n", "test_patch": "diff --git a/tests/test_raster.py b/tests/test_raster.py\nindex 0fbe9e1..ca6b7fb 100644\n--- a/tests/test_raster.py\n+++ b/tests/test_raster.py\n@@ -85,13 +85,17 @@ class DataTest(unittest.TestCase):\n img.mask_image(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n self.assertEqual(\r\n img.dataset.bounds,\r\n- BoundingBox(left=11.896863892, bottom=51.446545369, right=11.9578595, top=51.515176657,),\r\n+ BoundingBox(\r\n+ left=11.902702941366716, bottom=51.46639813686387, right=11.947798368783504, top=51.50098327545026,\r\n+ ),\r\n )\r\n \r\n img.mask_image((11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n self.assertEqual(\r\n img.dataset.bounds,\r\n- BoundingBox(left=11.896863892, bottom=51.446545369, right=11.9578595, top=51.515176657,),\r\n+ BoundingBox(\r\n+ left=11.902702941366716, bottom=51.46639813686387, right=11.947798368783504, top=51.50098327545026,\r\n+ ),\r\n )\r\n \r\n img.mask_image(\r\n@@ -100,7 +104,7 @@ class DataTest(unittest.TestCase):\n self.assertEqual(\r\n img.dataset.bounds,\r\n BoundingBox(\r\n- left=11.897762207287187, bottom=51.4614574027801, right=11.952739102863033, top=51.50592400953403,\r\n+ left=11.891923157920472, bottom=51.46639813686387, right=11.947798368783504, top=51.50098327545026\r\n ),\r\n )\r\n \r\n", "FAIL_TO_PASS": ["tests/test_raster.py::DataTest::test_mask_image"]}, {"instance_id": "dlr-eoc__ukis-pysat-38", "base_commit": "bd2e83a59621bb2552ece5278d5bce69919e10eb", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex ba1146c..9bbb7ca 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -31,6 +31,7 @@ Fixed\n Changed\r\n *******\r\n - ``raster.Image()``: changed ``dn2toa(platform, metadata, wavelengths)`` to ``dn2toa(platform, mtl_file, wavelengths)`` #17\r\n+- ``raster.Image()``: explicit dtype when writing, optional compression #32\r\n - ``raster.Image()``: auto-update of in-memory `dataset` #35\r\n \r\n \r\ndiff --git a/ukis_pysat/raster.py b/ukis_pysat/raster.py\nindex fa4d337..97fd77c 100644\n--- a/ukis_pysat/raster.py\n+++ b/ukis_pysat/raster.py\n@@ -9,6 +9,7 @@ try:\n import rasterio\r\n import rasterio.mask\r\n from rasterio import windows\r\n+ from rasterio.dtypes import get_minimum_dtype\r\n from rasterio.io import MemoryFile\r\n from rasterio.plot import reshape_as_image\r\n from rasterio.warp import calculate_default_transform, reproject\r\n@@ -360,13 +361,18 @@ class Image:\n self.da_arr = da.from_array(self.__arr, chunks=chunk_size)\r\n return self.da_arr\r\n \r\n- def write_to_file(self, path_to_file, dtype=rasterio.uint16, driver=\"GTiff\"):\r\n+ def write_to_file(self, path_to_file, dtype, driver=\"GTiff\", compress=None):\r\n \"\"\"\r\n Write a dataset to file.\r\n :param path_to_file: str, path to new file\r\n- :param dtype: datatype, optional (default: rasterio.uint16)\r\n+ :param dtype: datatype, like np.uint16, 'float32' or 'min' to use the minimum type to represent values\r\n+\r\n :param driver: str, optional (default: 'GTiff')\r\n+ :param compress: compression, e.g. 'lzw' (default: None)\r\n \"\"\"\r\n+ if dtype == 'min':\r\n+ dtype = get_minimum_dtype(self.__arr)\r\n+\r\n profile = self.dataset.meta\r\n profile.update(\r\n {\r\n@@ -379,6 +385,9 @@ class Image:\n }\r\n )\r\n \r\n+ if compress:\r\n+ profile.update({\"compress\": compress})\r\n+\r\n with rasterio.open(path_to_file, \"w\", **profile) as dst:\r\n dst.write(self.__arr.astype(dtype))\r\n \r\n", "test_patch": "diff --git a/tests/test_raster.py b/tests/test_raster.py\nindex ca6b7fb..42ee9d3 100644\n--- a/tests/test_raster.py\n+++ b/tests/test_raster.py\n@@ -5,8 +5,8 @@ import dask.array\n import numpy as np\r\n from rasterio import windows\r\n from rasterio.coords import BoundingBox\r\n-from shapely.geometry import box\r\n from rasterio.transform import from_bounds\r\n+from shapely.geometry import box\r\n \r\n from ukis_pysat.members import Platform\r\n from ukis_pysat.raster import Image\r\n@@ -187,13 +187,21 @@ class DataTest(unittest.TestCase):\n self.assertIsInstance(img.to_dask_array(chunk_size=(1, 10, 10)), dask.array.core.Array)\r\n \r\n def test_write_to_file(self):\r\n- img.write_to_file(r\"result.tif\")\r\n+ img.write_to_file(r\"result.tif\", np.uint16)\r\n img2 = Image(\"result.tif\")\r\n self.assertTrue(np.array_equal(img2.arr, img.arr))\r\n \r\n img2.close()\r\n os.remove(r\"result.tif\")\r\n \r\n+ img.write_to_file(r\"result.tif\", \"min\", compress=\"lzw\")\r\n+ img2 = Image(\"result.tif\")\r\n+ self.assertEqual(img2.arr.dtype, \"uint8\")\r\n+ self.assertEqual(img2.dataset.profile[\"compress\"], \"lzw\")\r\n+\r\n+ img2.close()\r\n+ os.remove(r\"result.tif\")\r\n+\r\n \r\n if __name__ == \"__main__\":\r\n unittest.main()\r\n", "FAIL_TO_PASS": ["tests/test_raster.py::DataTest::test_write_to_file"]}], "all_FAIL_TO_PASS": ["tests/test_raster.py::DataTest::test_mask_image", "tests/test_raster.py::DataTest::test_write_to_file"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "beetbox__beets-2775_x2", "level": 2, "source": "swerebench", "repo": "beetbox/beets", "image": "swerebench/sweb.eval.x86_64.beetbox_1776_beets-2775:latest", "base_commit": "721fedd7b9050ff0b6f17c33bdf00ea638484a03", "num_bugs": 2, "bugs": [{"instance_id": "beetbox__beets-2775", "base_commit": "721fedd7b9050ff0b6f17c33bdf00ea638484a03", "gold_patch": "diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py\nindex 5c484d2b3..b5ed4f358 100644\n--- a/beets/autotag/mb.py\n+++ b/beets/autotag/mb.py\n@@ -36,6 +36,9 @@ if util.SNI_SUPPORTED:\n else:\n BASE_URL = 'http://musicbrainz.org/'\n \n+NON_AUDIO_FORMATS = ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD',\n+ 'SVCD', 'UMD', 'VHS']\n+\n musicbrainzngs.set_useragent('beets', beets.__version__,\n 'http://beets.io/')\n \n@@ -275,6 +278,9 @@ def album_info(release):\n disctitle = medium.get('title')\n format = medium.get('format')\n \n+ if format in NON_AUDIO_FORMATS:\n+ continue\n+\n all_tracks = medium['track-list']\n if 'pregap' in medium:\n all_tracks.insert(0, medium['pregap'])\ndiff --git a/docs/changelog.rst b/docs/changelog.rst\nindex bd084a890..2a7349d65 100644\n--- a/docs/changelog.rst\n+++ b/docs/changelog.rst\n@@ -6,6 +6,9 @@ Changelog\n \n Changelog goes here!\n \n+Fixes:\n+* Non-audio media (DVD-Video, etc.) are now skipped by the autotagger. :bug:`2688`\n+\n \n 1.4.6 (December 21, 2017)\n -------------------------\n", "test_patch": "diff --git a/test/test_mb.py b/test/test_mb.py\nindex ca1bf2a1a..9c51d0fe3 100644\n--- a/test/test_mb.py\n+++ b/test/test_mb.py\n@@ -27,7 +27,7 @@ import mock\n \n class MBAlbumInfoTest(_common.TestCase):\n def _make_release(self, date_str='2009', tracks=None, track_length=None,\n- track_artist=False):\n+ track_artist=False, medium_format='FORMAT'):\n release = {\n 'title': 'ALBUM TITLE',\n 'id': 'ALBUM ID',\n@@ -90,7 +90,7 @@ class MBAlbumInfoTest(_common.TestCase):\n release['medium-list'].append({\n 'position': '1',\n 'track-list': track_list,\n- 'format': 'FORMAT',\n+ 'format': medium_format,\n 'title': 'MEDIUM TITLE',\n })\n return release\n@@ -324,6 +324,27 @@ class MBAlbumInfoTest(_common.TestCase):\n d = mb.album_info(release)\n self.assertEqual(d.data_source, 'MusicBrainz')\n \n+ def test_skip_non_audio_dvd(self):\n+ tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0),\n+ self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)]\n+ release = self._make_release(tracks=tracks, medium_format=\"DVD\")\n+ d = mb.album_info(release)\n+ self.assertEqual(len(d.tracks), 0)\n+\n+ def test_skip_non_audio_dvd_video(self):\n+ tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0),\n+ self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)]\n+ release = self._make_release(tracks=tracks, medium_format=\"DVD-Video\")\n+ d = mb.album_info(release)\n+ self.assertEqual(len(d.tracks), 0)\n+\n+ def test_no_skip_dvd_audio(self):\n+ tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0),\n+ self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)]\n+ release = self._make_release(tracks=tracks, medium_format=\"DVD-Audio\")\n+ d = mb.album_info(release)\n+ self.assertEqual(len(d.tracks), 2)\n+\n \n class ParseIDTest(_common.TestCase):\n def test_parse_id_correct(self):\n", "FAIL_TO_PASS": ["test/test_mb.py::MBAlbumInfoTest::test_skip_non_audio_dvd", "test/test_mb.py::MBAlbumInfoTest::test_skip_non_audio_dvd_video"]}, {"instance_id": "beetbox__beets-2776", "base_commit": "a5fc80ec50363c642b64b5621c705dfd1157c31c", "gold_patch": "diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py\nindex b5ed4f358..eb7c30808 100644\n--- a/beets/autotag/mb.py\n+++ b/beets/autotag/mb.py\n@@ -39,6 +39,8 @@ else:\n NON_AUDIO_FORMATS = ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD',\n 'SVCD', 'UMD', 'VHS']\n \n+SKIPPED_TRACKS = ['[data track]']\n+\n musicbrainzngs.set_useragent('beets', beets.__version__,\n 'http://beets.io/')\n \n@@ -286,6 +288,16 @@ def album_info(release):\n all_tracks.insert(0, medium['pregap'])\n \n for track in all_tracks:\n+\n+ if ('title' in track['recording'] and\n+ track['recording']['title'] in SKIPPED_TRACKS):\n+ continue\n+\n+ if ('video' in track['recording'] and\n+ track['recording']['video'] == 'true' and\n+ config['match']['ignore_video_tracks']):\n+ continue\n+\n # Basic information from the recording.\n index += 1\n ti = track_info(\ndiff --git a/beets/config_default.yaml b/beets/config_default.yaml\nindex 942459738..01c1e0f65 100644\n--- a/beets/config_default.yaml\n+++ b/beets/config_default.yaml\n@@ -126,5 +126,6 @@ match:\n original_year: no\n ignored: []\n required: []\n+ ignore_video_tracks: yes\n track_length_grace: 10\n track_length_max: 30\ndiff --git a/docs/changelog.rst b/docs/changelog.rst\nindex 2a7349d65..4ff54b222 100644\n--- a/docs/changelog.rst\n+++ b/docs/changelog.rst\n@@ -7,7 +7,10 @@ Changelog\n Changelog goes here!\n \n Fixes:\n+\n * Non-audio media (DVD-Video, etc.) are now skipped by the autotagger. :bug:`2688`\n+* Non-audio tracks (data tracks, video tracks, etc.) are now skipped by the\n+ autotagger. :bug:`1210`\n \n \n 1.4.6 (December 21, 2017)\ndiff --git a/docs/reference/config.rst b/docs/reference/config.rst\nindex 4015a4fc2..84f41a385 100644\n--- a/docs/reference/config.rst\n+++ b/docs/reference/config.rst\n@@ -774,6 +774,17 @@ want to enforce to the ``required`` setting::\n \n No tags are required by default.\n \n+.. _ignore_video_tracks:\n+\n+ignore_video_tracks\n+~~~~~~~~~~~~~~~~~~~\n+\n+By default, video tracks within a release will be ignored. If you want them to\n+be included (for example if you would like to track the audio-only versions of\n+the video tracks), set it to ``no``.\n+\n+Default: ``yes``.\n+\n .. _path-format-config:\n \n Path Format Configuration\n", "test_patch": "diff --git a/test/test_mb.py b/test/test_mb.py\nindex 9c51d0fe3..35f7c3aa2 100644\n--- a/test/test_mb.py\n+++ b/test/test_mb.py\n@@ -95,7 +95,7 @@ class MBAlbumInfoTest(_common.TestCase):\n })\n return release\n \n- def _make_track(self, title, tr_id, duration, artist=False):\n+ def _make_track(self, title, tr_id, duration, artist=False, video=False):\n track = {\n 'title': title,\n 'id': tr_id,\n@@ -113,6 +113,8 @@ class MBAlbumInfoTest(_common.TestCase):\n 'name': 'RECORDING ARTIST CREDIT',\n }\n ]\n+ if video:\n+ track['video'] = 'true'\n return track\n \n def test_parse_release_with_year(self):\n@@ -345,6 +347,41 @@ class MBAlbumInfoTest(_common.TestCase):\n d = mb.album_info(release)\n self.assertEqual(len(d.tracks), 2)\n \n+ def test_skip_data_track(self):\n+ tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0),\n+ self._make_track('[data track]', 'ID DATA TRACK',\n+ 100.0 * 1000.0),\n+ self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)]\n+ release = self._make_release(tracks=tracks)\n+ d = mb.album_info(release)\n+ self.assertEqual(len(d.tracks), 2)\n+ self.assertEqual(d.tracks[0].title, 'TITLE ONE')\n+ self.assertEqual(d.tracks[1].title, 'TITLE TWO')\n+\n+ def test_skip_video_tracks_by_default(self):\n+ tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0),\n+ self._make_track('TITLE VIDEO', 'ID VIDEO', 100.0 * 1000.0,\n+ False, True),\n+ self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)]\n+ release = self._make_release(tracks=tracks)\n+ d = mb.album_info(release)\n+ self.assertEqual(len(d.tracks), 2)\n+ self.assertEqual(d.tracks[0].title, 'TITLE ONE')\n+ self.assertEqual(d.tracks[1].title, 'TITLE TWO')\n+\n+ def test_no_skip_video_tracks_if_configured(self):\n+ config['match']['ignore_video_tracks'] = False\n+ tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0),\n+ self._make_track('TITLE VIDEO', 'ID VIDEO', 100.0 * 1000.0,\n+ False, True),\n+ self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)]\n+ release = self._make_release(tracks=tracks)\n+ d = mb.album_info(release)\n+ self.assertEqual(len(d.tracks), 3)\n+ self.assertEqual(d.tracks[0].title, 'TITLE ONE')\n+ self.assertEqual(d.tracks[1].title, 'TITLE VIDEO')\n+ self.assertEqual(d.tracks[2].title, 'TITLE TWO')\n+\n \n class ParseIDTest(_common.TestCase):\n def test_parse_id_correct(self):\n", "FAIL_TO_PASS": ["test/test_mb.py::MBAlbumInfoTest::test_skip_data_track", "test/test_mb.py::MBAlbumInfoTest::test_skip_video_tracks_by_default"]}], "all_FAIL_TO_PASS": ["test/test_mb.py::MBAlbumInfoTest::test_skip_non_audio_dvd", "test/test_mb.py::MBAlbumInfoTest::test_skip_non_audio_dvd_video", "test/test_mb.py::MBAlbumInfoTest::test_skip_data_track", "test/test_mb.py::MBAlbumInfoTest::test_skip_video_tracks_by_default"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Viatorus__quom-30_x2", "level": 2, "source": "swerebench", "repo": "Viatorus/quom", "image": "swerebench/sweb.eval.x86_64.viatorus_1776_quom-30:latest", "base_commit": "d9af2a6e7bf31b097f0ae4d35651235fa14d8cf6", "num_bugs": 2, "bugs": [{"instance_id": "Viatorus__quom-30", "base_commit": "d9af2a6e7bf31b097f0ae4d35651235fa14d8cf6", "gold_patch": "diff --git a/README.md b/README.md\nindex a993850..db84fbb 100644\n--- a/README.md\n+++ b/README.md\n@@ -42,6 +42,8 @@ optional arguments:\n --include_guard format, -g format\n Regex format of the include guard. Default: None\n --trim, -t Reduce continuous line breaks to one. Default: True\n+ --include_directory INCLUDE_DIRECTORY, -I INCLUDE_DIRECTORY\n+ Add include directories for header files.\n ```\n \n ## Simple example\ndiff --git a/examples/include_directory/README.md b/examples/include_directory/README.md\nnew file mode 100644\nindex 0000000..57599b5\n--- /dev/null\n+++ b/examples/include_directory/README.md\n@@ -0,0 +1,3 @@\n+```\n+quom libfoobar/foobar.hpp foobar_gen.hpp -s \"~> stitch <~\" -g FOOBAR_.+_HPP -I include/\n+```\ndiff --git a/examples/include_directory/foobar_gen.hpp b/examples/include_directory/foobar_gen.hpp\nnew file mode 100644\nindex 0000000..63c83dc\n--- /dev/null\n+++ b/examples/include_directory/foobar_gen.hpp\n@@ -0,0 +1,54 @@\n+#pragma once\n+\n+#ifndef FOOBAR_HPP\n+#define FOOBAR_HPP\n+\n+class Base {\n+public:\n+ Base();\n+};\n+\n+class Foo : Base {\n+public:\n+ Abc();\n+};\n+\n+#define none\n+\n+class Def : Base {\n+public:\n+ Def();\n+};\n+\n+void start() {\n+ Abc abc;\n+ Def def;\n+}\n+\n+#endif // FOOBAR_HPP\n+\n+#ifdef FOOBAR_MAIN\n+\n+#include \n+\n+/* hello */\n+Base::Base() {\n+ std::cout << \"Base constructed\" << std::endl;\n+}\n+\n+Abc::Abc() {\n+}\n+\n+void call();\n+\n+Def::Def() {\n+\tcall();\n+}\n+\n+#include \n+\n+void call() {\n+ std::cout << \"called\" << std::endl;\n+}\n+\n+#endif /* FOOBAR_MAIN */\ndiff --git a/examples/include_directory/include/libfoobar/bar.cpp b/examples/include_directory/include/libfoobar/bar.cpp\nnew file mode 100644\nindex 0000000..02b0beb\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/bar.cpp\n@@ -0,0 +1,7 @@\n+#include \"bar.hpp\"\n+\n+#include \"util.hpp\"\n+\n+Def::Def() {\n+\tcall();\n+}\n\\ No newline at end of file\ndiff --git a/examples/include_directory/include/libfoobar/bar.hpp b/examples/include_directory/include/libfoobar/bar.hpp\nnew file mode 100644\nindex 0000000..d6981b1\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/bar.hpp\n@@ -0,0 +1,13 @@\n+#pragma once\n+\n+#ifndef /*aha*/ FOOBAR_BAR_HPP\n+#define FOOBAR_BAR_HPP\n+\n+#include \"libfoobar/base.hpp\"\n+\n+class Def : Base {\n+public:\n+ Def();\n+};\n+\n+#endif //FOOBAR_BAR_HPP\ndiff --git a/examples/include_directory/include/libfoobar/base.cpp b/examples/include_directory/include/libfoobar/base.cpp\nnew file mode 100644\nindex 0000000..8e0cb0a\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/base.cpp\n@@ -0,0 +1,8 @@\n+#include \"base.hpp\"\n+\n+#include \n+\n+/* hello */\n+Base::Base() {\n+ std::cout << \"Base constructed\" << std::endl;\n+}\ndiff --git a/examples/include_directory/include/libfoobar/base.hpp b/examples/include_directory/include/libfoobar/base.hpp\nnew file mode 100644\nindex 0000000..8da5916\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/base.hpp\n@@ -0,0 +1,11 @@\n+#pragma once\n+\n+#ifndef FOOBAR_BASE_HPP\n+#define FOOBAR_BASE_HPP\n+\n+class Base {\n+public:\n+ Base();\n+};\n+\n+#endif // FOOBAR_BASE_HPP\ndiff --git a/examples/include_directory/include/libfoobar/foo.cpp b/examples/include_directory/include/libfoobar/foo.cpp\nnew file mode 100644\nindex 0000000..9b0746c\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/foo.cpp\n@@ -0,0 +1,4 @@\n+#include \"foo.hpp\"\n+\n+Abc::Abc() {\n+}\n\\ No newline at end of file\ndiff --git a/examples/include_directory/include/libfoobar/foo.hpp b/examples/include_directory/include/libfoobar/foo.hpp\nnew file mode 100644\nindex 0000000..f57d882\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/foo.hpp\n@@ -0,0 +1,14 @@\n+#pragma once\n+\n+#include \"libfoobar/base.hpp\"\n+\n+#/*123*/ifndef FOOBAR_FOO_HPP\n+#define /*123*/ FOOBAR_FOO_HPP\n+\n+class Foo : Base {\n+public:\n+ Abc();\n+};\n+\n+# /*123*/ endif /* FOOBAR_FOO_HPP */\n+#define none\ndiff --git a/examples/include_directory/include/libfoobar/foobar.hpp b/examples/include_directory/include/libfoobar/foobar.hpp\nnew file mode 100644\nindex 0000000..c8f9914\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/foobar.hpp\n@@ -0,0 +1,20 @@\n+#pragma once\n+\n+#ifndef FOOBAR_HPP\n+#define FOOBAR_HPP\n+\n+#include \"libfoobar/foo.hpp\"\n+#include \"libfoobar/bar.hpp\"\n+\n+void start() {\n+ Abc abc;\n+ Def def;\n+}\n+\n+#endif // FOOBAR_HPP\n+\n+#ifdef FOOBAR_MAIN\n+\n+// ~> stitch <~\n+\n+#endif /* FOOBAR_MAIN */\ndiff --git a/examples/include_directory/include/libfoobar/util.cpp b/examples/include_directory/include/libfoobar/util.cpp\nnew file mode 100644\nindex 0000000..94612f5\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/util.cpp\n@@ -0,0 +1,7 @@\n+#include \"util.hpp\"\n+\n+#include \n+\n+void call() {\n+ std::cout << \"called\" << std::endl;\n+}\n\\ No newline at end of file\ndiff --git a/examples/include_directory/include/libfoobar/util.hpp b/examples/include_directory/include/libfoobar/util.hpp\nnew file mode 100644\nindex 0000000..7a6dcf8\n--- /dev/null\n+++ b/examples/include_directory/include/libfoobar/util.hpp\n@@ -0,0 +1,8 @@\n+#pragma once\n+\n+#ifndef /*aha*/ FOOBAR_UTIL_HPP\n+#define FOOBAR_UTIL_HPP\n+\n+void call();\n+\n+#endif // FOOBAR_UTIL_HPP\ndiff --git a/quom/__main__.py b/quom/__main__.py\nindex 6140dd8..d717853 100644\n--- a/quom/__main__.py\n+++ b/quom/__main__.py\n@@ -1,5 +1,6 @@\n import argparse\n import sys\n+import traceback\n from pathlib import Path\n \n from .quom import Quom\n@@ -17,15 +18,13 @@ def main():\n help='Regex format of the include guard. Default: %(default)s')\n parser.add_argument('--trim', '-t', action='store_true', default=True,\n help='Reduce continuous line breaks to one. Default: %(default)s')\n+ parser.add_argument('--include_directory', '-I', type=Path, action='append', default=[],\n+ help='Add include directories for header files.')\n \n args = parser.parse_args()\n \n- try:\n- with args.output_path.open('w+') as file:\n- Quom(args.input_path, file, args.stitch, args.include_guard, args.trim)\n- except Exception as e:\n- print('Error: {}'.format(e), file=sys.stderr)\n- return 1\n+ with args.output_path.open('w+') as file:\n+ Quom(args.input_path, file, args.stitch, args.include_guard, args.trim, args.include_directory)\n \n \n if __name__ == '__main__':\ndiff --git a/quom/quom.py b/quom/quom.py\nindex 5bdf7f0..20bc83e 100644\n--- a/quom/quom.py\n+++ b/quom/quom.py\n@@ -28,25 +28,27 @@ def contains_only_whitespace_and_comment_tokens(tokens: List[Token]):\n \n class Quom:\n def __init__(self, src_file_path: Union[Path, str], dst: TextIO, stitch_format: str = None,\n- include_guard_format: str = None, trim: bool = True):\n+ include_guard_format: str = None, trim: bool = True,\n+ include_directories: List[Union[Path, str]] = None):\n self.__dst = dst\n self.__stitch_format = stitch_format\n self.__include_guard_format = re.compile('^{}$'.format(include_guard_format)) if include_guard_format else None\n self.__trim = trim\n+ self.__include_directories = [Path(x) for x in include_directories] if include_directories else []\n \n self.__processed_files = set()\n self.__source_files = Queue()\n- self.__cont_lb = CONTINUOUS_BREAK_REACHED\n+ self.__cont_lb = CONTINUOUS_LINE_BREAK_START\n self.__prev_token = EmptyToken()\n \n- self.__process_file(Path(src_file_path), False, True)\n+ self.__process_file(Path(), src_file_path, False, True)\n \n if not self.__source_files.empty():\n if stitch_format is not None:\n raise QuomError('Couldn\\'t stitch source files. The stitch location \"{}\" was not found.'\n .format(stitch_format))\n while not self.__source_files.empty():\n- self.__process_file(self.__source_files.get(), True)\n+ self.__process_file(Path(), self.__source_files.get(), True)\n # Write last token.\n self.__write_token(self.__prev_token, True)\n elif self.__cont_lb == CONTINUOUS_LINE_BREAK_START or not isinstance(self.__prev_token,\n@@ -54,18 +56,29 @@ class Quom:\n # Write last token, if not a continuous line break.\n self.__write_token(self.__prev_token, True)\n \n- def __process_file(self, file_path: Path, is_source_file: bool, is_main_header=False):\n+ def __process_file(self, relative_path: Path, include_path: Path, is_source_file: bool,\n+ is_main_header=False):\n+ # First check if file exists relative.\n+ file_path = relative_path / include_path\n+ if file_path.exists():\n+ with file_path.open() as file:\n+ tokens = tokenize(file.read())\n+ else:\n+ # Otherwise search in include directories.\n+ for include_directory in self.__include_directories:\n+ file_path = include_directory / include_path\n+ if file_path.exists():\n+ with file_path.open() as file:\n+ tokens = tokenize(file.read())\n+ break\n+ else:\n+ raise QuomError('Include not found: \\'{}\\''.format(include_path))\n+\n # Skip already processed files.\n if file_path in self.__processed_files:\n return\n self.__processed_files.add(file_path)\n \n- try:\n- with file_path.open() as file:\n- tokens = tokenize(file.read())\n- except FileNotFoundError:\n- raise QuomError('File not found: \\'{}\\''.format(file_path))\n-\n for token in tokens:\n # Find local includes.\n token = self.__scan_for_include(file_path, token, is_source_file)\n@@ -131,7 +144,7 @@ class Quom:\n if not isinstance(token, PreprocessorIncludeToken) or not token.is_local_include:\n return token\n \n- self.__process_file(file_path.parent / str(token.path), is_source_file)\n+ self.__process_file(file_path.parent, Path(str(token.path)), is_source_file)\n # Take include tokens line break token if any.\n token = token.preprocessor_tokens[-2]\n if isinstance(token, LinebreakWhitespaceToken):\n@@ -144,7 +157,7 @@ class Quom:\n return False\n \n while not self.__source_files.empty():\n- self.__process_file(self.__source_files.get(), True)\n+ self.__process_file(Path(), self.__source_files.get(), True)\n \n return True\n \n", "test_patch": "diff --git a/tests/test_quom/test_include_directory.py b/tests/test_quom/test_include_directory.py\nnew file mode 100644\nindex 0000000..1d8e572\n--- /dev/null\n+++ b/tests/test_quom/test_include_directory.py\n@@ -0,0 +1,115 @@\n+import os\n+from io import StringIO\n+from pathlib import Path\n+\n+import pytest\n+\n+from quom import Quom, QuomError\n+\n+FILE_MAIN_HPP = \"\"\"\n+int foo = 3;\n+\n+#include \"my_lib/core/core.hpp\"\n+#include \"my_other_lib/bar.hpp\"\n+\"\"\"\n+\n+FILE_CORE_HPP = \"\"\"\n+#pragma once\n+\n+#include \"my_lib/util/foo.hpp\"\n+\"\"\"\n+\n+FILE_CORE_CPP = \"\"\"\n+#include \"my_lib/core/core.hpp\"\n+\n+int i = 10;\n+\"\"\"\n+\n+FILE_FOO_HPP = \"\"\"\n+#pragma once\n+\n+int foo();\n+\"\"\"\n+\n+FILE_FOO_CPP = \"\"\"\n+#include \"foo.hpp\"\n+\n+int foo() { return 42; }\n+\"\"\"\n+\n+FILE_BAR_HPP = \"\"\"\n+#pragma once\n+\n+float bar();\n+\"\"\"\n+\n+FILE_INFO_HPP = \"\"\"\n+\n+float f = 0.42;\n+\n+\"\"\"\n+\n+FILE_BAR_CPP = \"\"\"\n+#include \"bar.hpp\"\n+\n+#include \"info.hpp\"\n+\n+float bar() { return f; }\n+\"\"\"\n+\n+RESULT = \"\"\"\n+int foo = 3;\n+\n+int foo();\n+\n+float bar();\n+\n+int foo() { return 42; }\n+\n+int i = 10;\n+\n+float f = 0.42;\n+\n+float bar() { return f; }\n+\"\"\"\n+\n+\n+def test_include_directory(fs):\n+ os.makedirs('include/my_lib/core')\n+ os.makedirs('include/my_lib/util')\n+ os.makedirs('include/my_other_lib/')\n+\n+ with open('include/my_lib/main.hpp', 'w+') as file:\n+ file.write(FILE_MAIN_HPP)\n+\n+ with open('include/my_lib/core/core.hpp', 'w+') as file:\n+ file.write(FILE_CORE_HPP)\n+\n+ with open('include/my_lib/core/core.cpp', 'w+') as file:\n+ file.write(FILE_CORE_CPP)\n+\n+ with open('include/my_lib/util/foo.hpp', 'w+') as file:\n+ file.write(FILE_FOO_HPP)\n+\n+ with open('include/my_lib/util/foo.cpp', 'w+') as file:\n+ file.write(FILE_FOO_CPP)\n+\n+ with open('include/my_other_lib/bar.hpp', 'w+') as file:\n+ file.write(FILE_BAR_HPP)\n+\n+ with open('include/my_other_lib/bar.cpp', 'w+') as file:\n+ file.write(FILE_BAR_CPP)\n+\n+ with open('include/my_other_lib/info.hpp', 'w+') as file:\n+ file.write(FILE_INFO_HPP)\n+\n+ dst = StringIO()\n+\n+ with pytest.raises(QuomError):\n+ Quom(Path('include/my_lib/main.hpp'), dst)\n+\n+ dst = StringIO()\n+\n+ Quom(Path('include/my_lib/main.hpp'), dst, include_directories=['include/'])\n+\n+ assert dst.getvalue() == RESULT\n", "FAIL_TO_PASS": ["tests/test_quom/test_include_directory.py::test_include_directory"]}, {"instance_id": "Viatorus__quom-34", "base_commit": "b4bb7665357892411081b86b7c33c0ffc18d2f1b", "gold_patch": "diff --git a/README.md b/README.md\nindex db84fbb..4486b8c 100644\n--- a/README.md\n+++ b/README.md\n@@ -44,6 +44,10 @@ optional arguments:\n --trim, -t Reduce continuous line breaks to one. Default: True\n --include_directory INCLUDE_DIRECTORY, -I INCLUDE_DIRECTORY\n Add include directories for header files.\n+ --source_directory SOURCE_DIRECTORY, -S SOURCE_DIRECTORY\n+ Set the source directories for source files.\n+ Use ./ in front of a path to mark as relative to the header file.\n+\n ```\n \n ## Simple example\ndiff --git a/quom/__main__.py b/quom/__main__.py\nindex d717853..ed25d0b 100644\n--- a/quom/__main__.py\n+++ b/quom/__main__.py\n@@ -1,12 +1,12 @@\n import argparse\n import sys\n-import traceback\n from pathlib import Path\n+from typing import List\n \n from .quom import Quom\n \n \n-def main():\n+def main(args: List[str]):\n parser = argparse.ArgumentParser(prog='quom', description='Single header generator for C/C++ libraries.')\n parser.add_argument('input_path', metavar='input', type=Path, help='Input file path of the main file.')\n parser.add_argument('output_path', metavar='output', type=Path,\n@@ -20,12 +20,33 @@ def main():\n help='Reduce continuous line breaks to one. Default: %(default)s')\n parser.add_argument('--include_directory', '-I', type=Path, action='append', default=[],\n help='Add include directories for header files.')\n+ parser.add_argument('--source_directory', '-S', type=str, action='append', default=['.'],\n+ help='Set the source directories for source files. '\n+ 'Use ./ in front of a path to mark as relative to the header file.')\n \n- args = parser.parse_args()\n+ args = parser.parse_args(args)\n+\n+ # Transform source directories to distingue between:\n+ # - relative from header file (starting with dot)\n+ # - relative from workdir\n+ # - absolute path\n+ relative_source_directories = []\n+ source_directories = []\n+ for src in args.source_directory:\n+ path = Path(src)\n+ if src == '.' or src.startswith('./'):\n+ relative_source_directories.append(path)\n+ else:\n+ source_directories.append(path.resolve())\n \n with args.output_path.open('w+') as file:\n- Quom(args.input_path, file, args.stitch, args.include_guard, args.trim, args.include_directory)\n+ Quom(args.input_path, file, args.stitch, args.include_guard, args.trim, args.include_directory,\n+ relative_source_directories, source_directories)\n+\n+\n+def run():\n+ main(sys.argv[1:])\n \n \n if __name__ == '__main__':\n- sys.exit(main())\n+ run()\ndiff --git a/quom/quom.py b/quom/quom.py\nindex 20bc83e..d366219 100644\n--- a/quom/quom.py\n+++ b/quom/quom.py\n@@ -1,3 +1,4 @@\n+import os\n import re\n from pathlib import Path\n from queue import Queue\n@@ -29,12 +30,17 @@ def contains_only_whitespace_and_comment_tokens(tokens: List[Token]):\n class Quom:\n def __init__(self, src_file_path: Union[Path, str], dst: TextIO, stitch_format: str = None,\n include_guard_format: str = None, trim: bool = True,\n- include_directories: List[Union[Path, str]] = None):\n+ include_directories: List[Union[Path, str]] = None,\n+ relative_source_directories: List[Union[Path]] = None,\n+ source_directories: List[Union[Path]] = None):\n self.__dst = dst\n self.__stitch_format = stitch_format\n self.__include_guard_format = re.compile('^{}$'.format(include_guard_format)) if include_guard_format else None\n self.__trim = trim\n self.__include_directories = [Path(x) for x in include_directories] if include_directories else []\n+ self.__relative_source_directories = relative_source_directories if relative_source_directories else [] \\\n+ if source_directories else [Path('.')]\n+ self.__source_directories = source_directories if source_directories else [Path('.')]\n \n self.__processed_files = set()\n self.__source_files = Queue()\n@@ -87,7 +93,9 @@ class Quom:\n \n self.__write_token(token, is_main_header)\n \n- self.__find_possible_source_file(file_path)\n+ file_path = self.__find_possible_source_file(file_path)\n+ if file_path:\n+ self.__source_files.put(file_path)\n \n def __write_token(self, token: Token, is_main_header: bool):\n if isinstance(token, StartToken) or isinstance(token, EndToken):\n@@ -129,16 +137,21 @@ class Quom:\n contains_only_whitespace_and_comment_tokens(token.preprocessor_arguments[i + 1:]):\n return True\n \n- def __find_possible_source_file(self, header_file_path: Path):\n+ def __find_possible_source_file(self, header_file_path: Path) -> Union[Path, None]:\n if header_file_path.suffix in ['.c', '.cpp', '.cxx', '.cc', '.c++', '.cp', '.C']:\n return\n \n # Checks if a equivalent compilation unit exits.\n for extension in ['.c', '.cpp', '.cxx', '.cc', '.c++', '.cp', '.C']:\n- file_path = header_file_path.with_suffix(extension)\n- if file_path.exists():\n- self.__source_files.put(file_path)\n- break\n+ for src_dir in self.__relative_source_directories:\n+ file_path = (header_file_path.parent / src_dir / header_file_path.name).with_suffix(extension)\n+ if file_path.exists():\n+ return file_path\n+ for src_dir in self.__source_directories:\n+ file_path = (src_dir / header_file_path.name).with_suffix(extension).resolve()\n+ if file_path.exists():\n+ return file_path\n+ return None\n \n def __scan_for_include(self, file_path: Path, token: Token, is_source_file: bool) -> Union[Token, None]:\n if not isinstance(token, PreprocessorIncludeToken) or not token.is_local_include:\n", "test_patch": "diff --git a/tests/test_quom/test_normal.py b/tests/test_quom/test_normal.py\nindex f0928dd..38d53f0 100644\n--- a/tests/test_quom/test_normal.py\n+++ b/tests/test_quom/test_normal.py\n@@ -4,6 +4,7 @@ from pathlib import Path\n import pytest\n \n from quom import Quom, QuomError\n+from quom.__main__ import main\n \n FILE_MAIN_HPP = \"\"\"\\\n #pragma once\n@@ -247,3 +248,13 @@ def test_with_missing_source_file(fs):\n Quom(Path('main.hpp'), dst)\n \n assert dst.getvalue() == RESULT_NORMAL_WITHOUT_SOURCES\n+\n+\n+def test_main(fs):\n+ init()\n+\n+ main(['main.hpp', 'result.hpp'])\n+ assert Path('result.hpp').read_text() == RESULT_NORMAL\n+\n+ main(['main.hpp', 'result.hpp', '-S', '.'])\n+ assert Path('result.hpp').read_text() == RESULT_NORMAL\ndiff --git a/tests/test_quom/test_source_directory.py b/tests/test_quom/test_source_directory.py\nnew file mode 100644\nindex 0000000..790d417\n--- /dev/null\n+++ b/tests/test_quom/test_source_directory.py\n@@ -0,0 +1,62 @@\n+import os\n+from io import StringIO\n+from pathlib import Path\n+\n+from quom import Quom\n+from quom.__main__ import main\n+\n+FILE_MAIN_HPP = \"\"\"\n+int foo = 3;\n+\n+int foo();\n+\"\"\"\n+\n+FILE_MAIN_CPP = \"\"\"\n+int foo() { return 42; }\n+\"\"\"\n+\n+RESULT = \"\"\"\n+int foo = 3;\n+\n+int foo();\n+\n+int foo() { return 42; }\n+\"\"\"\n+\n+\n+def test_source_directory(fs):\n+ os.makedirs('project/')\n+ os.chdir('project/')\n+ os.makedirs('include/')\n+ os.makedirs('src/')\n+\n+ with open('include/main.hpp', 'w+') as file:\n+ file.write(FILE_MAIN_HPP)\n+\n+ with open('src/main.cpp', 'w+') as file:\n+ file.write(FILE_MAIN_CPP)\n+\n+ dst = StringIO()\n+ Quom(Path('include/main.hpp'), dst)\n+ assert dst.getvalue() != RESULT\n+\n+ dst = StringIO()\n+ Quom(Path('include/main.hpp'), dst, relative_source_directories=[Path('../src')])\n+ assert dst.getvalue() == RESULT\n+\n+ dst = StringIO()\n+ Quom(Path('include/main.hpp'), dst, source_directories=[Path('src').resolve()])\n+ assert dst.getvalue() == RESULT\n+\n+ dst = StringIO()\n+ Quom(Path('include/main.hpp'), dst, source_directories=[Path('/project/src')])\n+ assert dst.getvalue() == RESULT\n+\n+ main(['include/main.hpp', 'result.hpp', '-S', './../src'])\n+ assert Path('result.hpp').read_text() == RESULT\n+\n+ main(['include/main.hpp', 'result.hpp', '-S', 'src'])\n+ assert Path('result.hpp').read_text() == RESULT\n+\n+ main(['include/main.hpp', 'result.hpp', '-S', '/project/src'])\n+ assert Path('result.hpp').read_text() == RESULT\n", "FAIL_TO_PASS": ["tests/test_quom/test_normal.py::test_main", "tests/test_quom/test_source_directory.py::test_source_directory"]}], "all_FAIL_TO_PASS": ["tests/test_quom/test_include_directory.py::test_include_directory", "tests/test_quom/test_normal.py::test_main", "tests/test_quom/test_source_directory.py::test_source_directory"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "di__vladiate-40_x2", "level": 2, "source": "swerebench", "repo": "di/vladiate", "image": "swerebench/sweb.eval.x86_64.di_1776_vladiate-40:latest", "base_commit": "577cfae7c7835e89e592af7cd024d6e9de084ed1", "num_bugs": 2, "bugs": [{"instance_id": "di__vladiate-40", "base_commit": "577cfae7c7835e89e592af7cd024d6e9de084ed1", "gold_patch": "diff --git a/setup.py b/setup.py\nindex 8de8422..62b35f8 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -4,7 +4,7 @@ import sys\n from setuptools import setup, find_packages\n from setuptools.command.test import test as TestCommand\n \n-__version__ = '0.0.16'\n+__version__ = '0.0.17'\n \n \n class PyTest(TestCommand):\ndiff --git a/tox.ini b/tox.ini\nindex 4b85cd7..80f6311 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -4,13 +4,29 @@\n # and then run \"tox\" from this directory.\n \n [tox]\n-envlist = py27, py35\n+envlist = begin,py{27,35,36},lint,end\n+\n+[testenv:py27]\n+basepython = python2.7\n+\n+[testenv:py35]\n+basepython = python3.5\n+\n+[testenv:py36]\n+basepython = python3.6\n+\n+[testenv:lint]\n+commands = flake8\n \n [testenv]\n-commands = coverage erase\n- coverage run --source=vladiate setup.py test\n- coverage combine\n- coverage report --include=*\n+commands = coverage run --source=vladiate setup.py test\n deps =\n pytest\n coverage\n+ flake8\n+\n+[testenv:begin]\n+commands = coverage erase\n+\n+[testenv:end]\n+commands = coverage report -m --include=*\ndiff --git a/vladiate/validators.py b/vladiate/validators.py\nindex bbbb18c..a425c2c 100644\n--- a/vladiate/validators.py\n+++ b/vladiate/validators.py\n@@ -185,16 +185,16 @@ class NotEmptyValidator(Validator):\n \n def __init__(self):\n self.fail_count = 0\n+ self.failed = False\n \n def validate(self, field, row={}):\n if field == '':\n+ self.failed = True\n raise ValidationException(\"Row has emtpy field in column\")\n \n @property\n def bad(self):\n- # Return an empty set to conform to the protocol. The 'bad' fields\n- # would all be empty strings anyways\n- return set()\n+ return self.failed\n \n \n class Ignore(Validator):\ndiff --git a/vladiate/vlad.py b/vladiate/vlad.py\nindex b0eb438..0233152 100644\n--- a/vladiate/vlad.py\n+++ b/vladiate/vlad.py\n@@ -41,14 +41,24 @@ class Vlad(object):\n \" {} failed {} time(s) ({:.1%}) on field: '{}'\".format(\n validator.__class__.__name__, validator.fail_count,\n validator.fail_count / self.line_count, field_name))\n- invalid = list(validator.bad)\n- shown = [\"'{}'\".format(field) for field in invalid[:99]]\n- hidden = [\"'{}'\".format(field) for field in invalid[99:]]\n- self.logger.error(\n- \" Invalid fields: [{}]\".format(\", \".join(shown)))\n- if hidden:\n+ try:\n+ # If self.bad is iterable, it contains the fields which\n+ # caused it to fail\n+ invalid = list(validator.bad)\n+ shown = [\n+ \"'{}'\".format(field) for field in invalid[:99]\n+ ]\n+ hidden = [\n+ \"'{}'\".format(field)\n+ for field in invalid[99:]\n+ ]\n self.logger.error(\n- \" ({} more suppressed)\".format(len(hidden)))\n+ \" Invalid fields: [{}]\".format(\", \".join(shown)))\n+ if hidden:\n+ self.logger.error(\n+ \" ({} more suppressed)\".format(len(hidden)))\n+ except TypeError:\n+ pass\n \n def _log_missing_validators(self):\n self.logger.error(\" Missing validators for:\")\n", "test_patch": "diff --git a/vladiate/test/test_validators.py b/vladiate/test/test_validators.py\nindex 66d431d..7b80686 100644\n--- a/vladiate/test/test_validators.py\n+++ b/vladiate/test/test_validators.py\n@@ -196,7 +196,7 @@ def test_non_empty_validator_fails():\n with pytest.raises(ValidationException):\n validator.validate(\"\")\n \n- assert validator.bad == set()\n+ assert validator.bad is True\n \n \n def test_ignore_validator():\ndiff --git a/vladiate/test/test_vlads.py b/vladiate/test/test_vlads.py\nindex fd55f94..4b077ae 100644\n--- a/vladiate/test/test_vlads.py\n+++ b/vladiate/test/test_vlads.py\n@@ -3,7 +3,8 @@ import pytest\n from ..vlad import Vlad\n from ..inputs import LocalFile, String\n from ..validators import (\n- EmptyValidator, FloatValidator, SetValidator, UniqueValidator\n+ EmptyValidator, FloatValidator, NotEmptyValidator, SetValidator,\n+ UniqueValidator,\n )\n \n \n@@ -144,3 +145,21 @@ def test_ignore_missing_validators():\n \n assert vlad.validate()\n assert vlad.missing_validators == {'Column B'}\n+\n+\n+def test_when_bad_is_non_iterable():\n+ source = String('Column A,Column B\\n,foo')\n+\n+ class TestVlad(Vlad):\n+ validators = {\n+ 'Column A': [NotEmptyValidator()],\n+ 'Column B': [NotEmptyValidator()],\n+ }\n+\n+ vlad = TestVlad(source=source)\n+\n+ assert not vlad.validate()\n+ assert vlad.validators['Column A'][0].fail_count == 1\n+ assert vlad.validators['Column A'][0].bad\n+ assert vlad.validators['Column B'][0].fail_count == 0\n+ assert not vlad.validators['Column B'][0].bad\n", "FAIL_TO_PASS": ["vladiate/test/test_validators.py::test_non_empty_validator_fails", "vladiate/test/test_vlads.py::test_when_bad_is_non_iterable"]}, {"instance_id": "di__vladiate-42", "base_commit": "81892a0a29bd668bc12c72e17b3f2f62f7ed0377", "gold_patch": "diff --git a/README.rst b/README.rst\nindex f36c851..77af67e 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -236,6 +236,8 @@ Vladiate comes with a few common validators built-in:\n \n :``unique_with=[]``:\n List of field names to make the primary field unique with.\n+ :``empty_ok=False``:\n+ Specify whether a field which is an empty string should be ignored.\n \n *class* ``RegexValidator``\n \n@@ -243,6 +245,8 @@ Vladiate comes with a few common validators built-in:\n \n :``pattern=r'di^'``:\n The regex pattern. Fails for all fields by default.\n+ :``empty_ok=False``:\n+ Specify whether a field which is an empty string should be ignored.\n \n *class* ``RangeValidator``\n \n@@ -253,6 +257,8 @@ Vladiate comes with a few common validators built-in:\n The low value of the range.\n :``high``:\n The high value of the range.\n+ :``empty_ok=False``:\n+ Specify whether a field which is an empty string should be ignored.\n \n *class* ``EmptyValidator``\n \ndiff --git a/setup.py b/setup.py\nindex 62b35f8..b5c8c72 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -4,7 +4,7 @@ import sys\n from setuptools import setup, find_packages\n from setuptools.command.test import test as TestCommand\n \n-__version__ = '0.0.17'\n+__version__ = '0.0.18'\n \n \n class PyTest(TestCommand):\ndiff --git a/vladiate/validators.py b/vladiate/validators.py\nindex a425c2c..72dccdb 100644\n--- a/vladiate/validators.py\n+++ b/vladiate/validators.py\n@@ -6,8 +6,9 @@ from vladiate.exceptions import ValidationException, BadValidatorException\n class Validator(object):\n ''' Generic Validator class '''\n \n- def __init__(self):\n+ def __init__(self, empty_ok=False):\n self.fail_count = 0\n+ self.empty_ok = empty_ok\n \n @property\n def bad(self):\n@@ -22,8 +23,8 @@ class Validator(object):\n class CastValidator(Validator):\n ''' Validates that a field can be cast to a float '''\n \n- def __init__(self):\n- super(CastValidator, self).__init__()\n+ def __init__(self, **kwargs):\n+ super(CastValidator, self).__init__(**kwargs)\n self.invalid_set = set([])\n \n def validate(self, field, row={}):\n@@ -42,29 +43,27 @@ class CastValidator(Validator):\n class FloatValidator(CastValidator):\n ''' Validates that a field can be cast to a float '''\n \n- def __init__(self, empty_ok=False):\n- super(FloatValidator, self).__init__()\n- self.empty_ok = empty_ok\n+ def __init__(self, **kwargs):\n+ super(FloatValidator, self).__init__(**kwargs)\n self.cast = float\n \n \n class IntValidator(CastValidator):\n ''' Validates that a field can be cast to an int '''\n \n- def __init__(self, empty_ok=False):\n- super(IntValidator, self).__init__()\n- self.empty_ok = empty_ok\n+ def __init__(self, **kwargs):\n+ super(IntValidator, self).__init__(**kwargs)\n self.cast = int\n \n \n class SetValidator(Validator):\n ''' Validates that a field is in the given set '''\n \n- def __init__(self, valid_set=[], empty_ok=False):\n- super(SetValidator, self).__init__()\n+ def __init__(self, valid_set=[], **kwargs):\n+ super(SetValidator, self).__init__(**kwargs)\n self.valid_set = set(valid_set)\n self.invalid_set = set([])\n- if empty_ok:\n+ if self.empty_ok:\n self.valid_set.add('')\n \n def validate(self, field, row={}):\n@@ -81,8 +80,8 @@ class SetValidator(Validator):\n class UniqueValidator(Validator):\n ''' Validates that a field is unique within the file '''\n \n- def __init__(self, unique_with=[]):\n- super(UniqueValidator, self).__init__()\n+ def __init__(self, unique_with=[], **kwargs):\n+ super(UniqueValidator, self).__init__(**kwargs)\n self.unique_values = set([])\n self.duplicates = set([])\n self.unique_with = unique_with\n@@ -119,10 +118,9 @@ class UniqueValidator(Validator):\n class RegexValidator(Validator):\n ''' Validates that a field matches a given regex '''\n \n- def __init__(self, pattern=r'di^', empty_ok=False):\n- super(RegexValidator, self).__init__()\n+ def __init__(self, pattern=r'di^', **kwargs):\n+ super(RegexValidator, self).__init__(**kwargs)\n self.regex = re.compile(pattern)\n- self.empty_ok = empty_ok\n self.failures = set([])\n \n def validate(self, field, row={}):\n@@ -137,13 +135,16 @@ class RegexValidator(Validator):\n \n \n class RangeValidator(Validator):\n- def __init__(self, low, high):\n+ def __init__(self, low, high, **kwargs):\n+ super(RangeValidator, self).__init__(**kwargs)\n self.fail_count = 0\n self.low = low\n self.high = high\n self.outside = set()\n \n def validate(self, field, row={}):\n+ if field == '' and self.empty_ok:\n+ return\n try:\n value = float(field)\n if not self.low <= value <= self.high:\n@@ -164,8 +165,8 @@ class RangeValidator(Validator):\n class EmptyValidator(Validator):\n ''' Validates that a field is always empty '''\n \n- def __init__(self):\n- super(EmptyValidator, self).__init__()\n+ def __init__(self, **kwargs):\n+ super(EmptyValidator, self).__init__(**kwargs)\n self.nonempty = set([])\n \n def validate(self, field, row={}):\n@@ -183,7 +184,8 @@ class EmptyValidator(Validator):\n class NotEmptyValidator(Validator):\n ''' Validates that a field is not empty '''\n \n- def __init__(self):\n+ def __init__(self, **kwargs):\n+ super(NotEmptyValidator, self).__init__(**kwargs)\n self.fail_count = 0\n self.failed = False\n \n", "test_patch": "diff --git a/vladiate/test/test_validators.py b/vladiate/test/test_validators.py\nindex 7b80686..369e9a4 100644\n--- a/vladiate/test/test_validators.py\n+++ b/vladiate/test/test_validators.py\n@@ -81,12 +81,6 @@ def test_set_validator_works(field_set, field):\n assert field in validator.valid_set\n \n \n-def test_set_validator_empty_ok():\n- validator = SetValidator(['foo'], empty_ok=True)\n- validator.validate('')\n- assert '' in validator.valid_set\n-\n-\n @pytest.mark.parametrize('field_set, field', [\n ([], 'bar'),\n (['foo'], 'bar'),\n@@ -139,10 +133,6 @@ def test_regex_validator_works(pattern, field):\n RegexValidator(pattern).validate(field)\n \n \n-def test_regex_validator_allows_empty():\n- RegexValidator(r'foo.*', empty_ok=True).validate('')\n-\n-\n @pytest.mark.parametrize('pattern, field', [\n (r'foo.*', 'afoo'),\n (r'^$', 'foo'),\n@@ -213,3 +203,16 @@ def test_base_class_raises():\n \n with pytest.raises(NotImplementedError):\n validator.validate(stub(), stub())\n+\n+\n+@pytest.mark.parametrize('validator_class,args', [\n+ (SetValidator, [['foo']]),\n+ (RegexValidator, [r'foo.*']),\n+ (IntValidator, []),\n+ (FloatValidator, []),\n+ (RangeValidator, [0, 42]),\n+ (UniqueValidator, []),\n+])\n+def test_all_validators_support_empty_ok(validator_class, args):\n+ validator = validator_class(*args, empty_ok=True)\n+ validator.validate('')\n", "FAIL_TO_PASS": ["vladiate/test/test_validators.py::test_all_validators_support_empty_ok[RangeValidator-args4]", "vladiate/test/test_validators.py::test_all_validators_support_empty_ok[UniqueValidator-args5]"]}], "all_FAIL_TO_PASS": ["vladiate/test/test_validators.py::test_non_empty_validator_fails", "vladiate/test/test_vlads.py::test_when_bad_is_non_iterable", "vladiate/test/test_validators.py::test_all_validators_support_empty_ok[RangeValidator-args4]", "vladiate/test/test_validators.py::test_all_validators_support_empty_ok[UniqueValidator-args5]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cocagne__pysrp-48_x2", "level": 2, "source": "swerebench", "repo": "cocagne/pysrp", "image": "swerebench/sweb.eval.x86_64.cocagne_1776_pysrp-48:latest", "base_commit": "1cfefbb64c4f39cde64695ac87e1a6a032e4eb1d", "num_bugs": 2, "bugs": [{"instance_id": "cocagne__pysrp-48", "base_commit": "1cfefbb64c4f39cde64695ac87e1a6a032e4eb1d", "gold_patch": "diff --git a/srp/_ctsrp.py b/srp/_ctsrp.py\nindex 7794bf1..9436728 100644\n--- a/srp/_ctsrp.py\n+++ b/srp/_ctsrp.py\n@@ -353,7 +353,7 @@ def get_ngk( hash_class, ng_type, n_hex, g_hex, ctx ):\n \n \n \n-def create_salted_verification_key( username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, salt_len=4 ):\n+def create_salted_verification_key( username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, salt_len=4, k_hex=None ):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n s = BN_new()\n@@ -386,7 +386,7 @@ def create_salted_verification_key( username, password, hash_alg=SHA1, ng_type=N\n \n \n class Verifier (object):\n- def __init__(self, username, bytes_s, bytes_v, bytes_A, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None):\n+ def __init__(self, username, bytes_s, bytes_v, bytes_A, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None, k_hex=None):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n if bytes_b and len(bytes_b) != 32:\n@@ -411,6 +411,8 @@ class Verifier (object):\n \n hash_class = _hash_map[ hash_alg ]\n N,g,k = get_ngk( hash_class, ng_type, n_hex, g_hex, self.ctx )\n+ if k_hex is not None:\n+ BN_hex2bn(k, k_hex)\n \n self.hash_class = hash_class\n self.N = N\n@@ -503,7 +505,7 @@ class Verifier (object):\n \n \n class User (object):\n- def __init__(self, username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_a=None, bytes_A=None):\n+ def __init__(self, username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_a=None, bytes_A=None, k_hex=None):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n if bytes_a and len(bytes_a) != 32:\n@@ -529,6 +531,8 @@ class User (object):\n \n hash_class = _hash_map[ hash_alg ]\n N,g,k = get_ngk( hash_class, ng_type, n_hex, g_hex, self.ctx )\n+ if k_hex is not None:\n+ BN_hex2bn(k, k_hex)\n \n self.hash_class = hash_class\n self.N = N\ndiff --git a/srp/_pysrp.py b/srp/_pysrp.py\nindex 6b773f1..d59f100 100644\n--- a/srp/_pysrp.py\n+++ b/srp/_pysrp.py\n@@ -180,7 +180,7 @@ def old_H( hash_class, s1, s2 = '', s3=''):\n \n def H( hash_class, *args, **kwargs ):\n width = kwargs.get('width', None)\n- \n+\n h = hash_class()\n \n for s in args:\n@@ -221,7 +221,7 @@ def gen_x( hash_class, salt, username, password ):\n \n \n \n-def create_salted_verification_key( username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, salt_len=4 ):\n+def create_salted_verification_key( username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, salt_len=4, k_hex=None ):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n hash_class = _hash_map[ hash_alg ]\n@@ -257,7 +257,7 @@ def calculate_H_AMK( hash_class, A, M, K ):\n \n class Verifier (object):\n \n- def __init__(self, username, bytes_s, bytes_v, bytes_A, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None):\n+ def __init__(self, username, bytes_s, bytes_v, bytes_A, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None, k_hex=None):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n if bytes_b and len(bytes_b) != 32:\n@@ -270,7 +270,10 @@ class Verifier (object):\n \n N,g = get_ng( ng_type, n_hex, g_hex )\n hash_class = _hash_map[ hash_alg ]\n- k = H( hash_class, N, g, width=len(long_to_bytes(N)) )\n+ if k_hex is None:\n+ k = H( hash_class, N, g, width=len(long_to_bytes(N)) )\n+ else:\n+ k = int(k_hex, 16)\n \n self.hash_class = hash_class\n self.N = N\n@@ -328,14 +331,17 @@ class Verifier (object):\n \n \n class User (object):\n- def __init__(self, username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_a=None, bytes_A=None):\n+ def __init__(self, username, password, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_a=None, bytes_A=None, k_hex=None):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n if bytes_a and len(bytes_a) != 32:\n raise ValueError(\"32 bytes required for bytes_a\")\n N,g = get_ng( ng_type, n_hex, g_hex )\n hash_class = _hash_map[ hash_alg ]\n- k = H( hash_class, N, g, width=len(long_to_bytes(N)) )\n+ if k_hex is None:\n+ k = H( hash_class, N, g, width=len(long_to_bytes(N)) )\n+ else:\n+ k = int(k_hex, 16)\n \n self.I = username\n self.p = password\n", "test_patch": "diff --git a/srp/test_srp.py b/srp/test_srp.py\nindex 3f1af68..b49aa78 100644\n--- a/srp/test_srp.py\n+++ b/srp/test_srp.py\n@@ -45,7 +45,7 @@ FBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73''')\n \n class SRPTests( unittest.TestCase ):\n \n- def doit(self, u_mod, v_mod, g_mod, hash_alg=srp.SHA1, ng_type=srp.NG_2048, n_hex='', g_hex=''):\n+ def doit(self, u_mod, v_mod, g_mod, hash_alg=srp.SHA1, ng_type=srp.NG_2048, n_hex='', g_hex='', k_hex=None):\n User = u_mod.User\n Verifier = v_mod.Verifier\n create_salted_verification_key = g_mod.create_salted_verification_key\n@@ -55,19 +55,19 @@ class SRPTests( unittest.TestCase ):\n \n _s, _v = create_salted_verification_key( username, password, hash_alg, ng_type, n_hex, g_hex )\n \n- usr = User( username, password, hash_alg, ng_type, n_hex, g_hex )\n+ usr = User( username, password, hash_alg, ng_type, n_hex, g_hex, None, None, k_hex )\n bytes_a = usr.get_ephemeral_secret()\n uname, A = usr.start_authentication()\n \n # Make sure a recreated User does all the same appropriate things\n- usr2 = User( username, password, hash_alg, ng_type, n_hex, g_hex, bytes_a )\n+ usr2 = User( username, password, hash_alg, ng_type, n_hex, g_hex, bytes_a, None, k_hex )\n self.assertEqual(bytes_a, usr2.get_ephemeral_secret())\n uname2, A2 = usr2.start_authentication()\n self.assertEqual(uname, uname2)\n self.assertEqual(A, A2)\n \n # username, A => server\n- svr = Verifier( uname, _s, _v, A, hash_alg, ng_type, n_hex, g_hex )\n+ svr = Verifier( uname, _s, _v, A, hash_alg, ng_type, n_hex, g_hex, None, k_hex )\n bytes_b = svr.get_ephemeral_secret()\n s,B = svr.get_challenge()\n \n@@ -80,7 +80,7 @@ class SRPTests( unittest.TestCase ):\n HAMK = svr.verify_session( M )\n \n # Make sure that a recreated Verifier will authenticate appropriately\n- svr2 = Verifier( uname, _s, _v, A, hash_alg, ng_type, n_hex, g_hex, bytes_b )\n+ svr2 = Verifier( uname, _s, _v, A, hash_alg, ng_type, n_hex, g_hex, bytes_b, k_hex )\n self.assertEqual(bytes_b, svr2.get_ephemeral_secret())\n HAMK2 = svr2.verify_session( M )\n self.assertEqual(HAMK, HAMK2)\n@@ -165,6 +165,8 @@ class SRPTests( unittest.TestCase ):\n usr = _ctsrp.User('test', 'test')\n self.assertTrue(not usr.authenticated())\n \n+ def test_custom_k(self):\n+ self.doit( _ctsrp, _pysrp, _ctsrp, k_hex=six.b('5'))\n \n #-----------------------------------------------------------------------------------\n # Performance Testing\n", "FAIL_TO_PASS": ["srp/test_srp.py::SRPTests::test_NG_8192", "srp/test_srp.py::SRPTests::test_NG_CUSTOM", "srp/test_srp.py::SRPTests::test_all1", "srp/test_srp.py::SRPTests::test_all2", "srp/test_srp.py::SRPTests::test_ctypes_defaults", "srp/test_srp.py::SRPTests::test_custom_k", "srp/test_srp.py::SRPTests::test_hash_SHA512", "srp/test_srp.py::SRPTests::test_mix1", "srp/test_srp.py::SRPTests::test_mix2", "srp/test_srp.py::SRPTests::test_mix3", "srp/test_srp.py::SRPTests::test_mix4", "srp/test_srp.py::SRPTests::test_pure_python_defaults"]}, {"instance_id": "cocagne__pysrp-51", "base_commit": "4dfb111fffd671b7d97d803309fda2904e3ca1c8", "gold_patch": "diff --git a/srp/_ctsrp.py b/srp/_ctsrp.py\nindex 9436728..98ae309 100644\n--- a/srp/_ctsrp.py\n+++ b/srp/_ctsrp.py\n@@ -386,12 +386,11 @@ def create_salted_verification_key( username, password, hash_alg=SHA1, ng_type=N\n \n \n class Verifier (object):\n- def __init__(self, username, bytes_s, bytes_v, bytes_A, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None, k_hex=None):\n+ def __init__(self, username, bytes_s, bytes_v, bytes_A=None, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None, k_hex=None):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n if bytes_b and len(bytes_b) != 32:\n raise ValueError(\"32 bytes required for bytes_b\")\n- self.A = BN_new()\n self.B = BN_new()\n self.K = None\n self.S = BN_new()\n@@ -421,14 +420,10 @@ class Verifier (object):\n \n bytes_to_bn( self.s, bytes_s )\n bytes_to_bn( self.v, bytes_v )\n- bytes_to_bn( self.A, bytes_A )\n-\n- # SRP-6a safety check\n- BN_mod(self.tmp1, self.A, N, self.ctx)\n+ if bytes_A:\n+ self._set_A(bytes_A)\n \n- if BN_is_zero(self.tmp1):\n- self.safety_failed = True\n- else:\n+ if not self.safety_failed:\n if bytes_b:\n bytes_to_bn( self.b, bytes_b )\n else:\n@@ -441,18 +436,6 @@ class Verifier (object):\n BN_add(self.B, self.tmp1, self.tmp2)\n BN_mod(self.B, self.B, N, self.ctx)\n \n- H_bn_bn(hash_class, self.u, self.A, self.B, width=BN_num_bytes(N))\n-\n- # S = (A *(v^u)) ^ b\n- BN_mod_exp(self.tmp1, self.v, self.u, N, self.ctx)\n- BN_mul(self.tmp2, self.A, self.tmp1, self.ctx)\n- BN_mod_exp(self.S, self.tmp2, self.b, N, self.ctx)\n-\n- self.K = hash_class( bn_to_bytes(self.S) ).digest()\n-\n- self.M = calculate_M( hash_class, N, g, self.I, self.s, self.A, self.B, self.K )\n- self.H_AMK = calculate_H_AMK( hash_class, self.A, self.M, self.K )\n-\n \n def __del__(self):\n if not hasattr(self, 'A'):\n@@ -496,12 +479,40 @@ class Verifier (object):\n return (bn_to_bytes(self.s), bn_to_bytes(self.B))\n \n \n- def verify_session(self, user_M):\n- if user_M == self.M:\n- self._authenticated = True\n- return self.H_AMK\n+ def verify_session(self, user_M, bytes_A=None):\n+ if bytes_A:\n+ self._set_A(bytes_A)\n+ if not hasattr(self, 'A'):\n+ raise ValueError(\"bytes_A must be provided through Verifier constructor or verify_session parameter.\")\n+ if not self.safety_failed:\n+ self._derive_H_AMK()\n+ if user_M == self.M:\n+ self._authenticated = True\n+ return self.H_AMK\n+\n+\n+ def _set_A(self, bytes_A):\n+ self.A = BN_new()\n+ bytes_to_bn( self.A, bytes_A )\n+\n+ # SRP-6a safety check\n+ BN_mod(self.tmp1, self.A, self.N, self.ctx)\n+\n+ if BN_is_zero(self.tmp1):\n+ self.safety_failed = True\n+\n+ def _derive_H_AMK(self):\n+ H_bn_bn(self.hash_class, self.u, self.A, self.B, width=BN_num_bytes(self.N))\n+\n+ # S = (A *(v^u)) ^ b\n+ BN_mod_exp(self.tmp1, self.v, self.u, self.N, self.ctx)\n+ BN_mul(self.tmp2, self.A, self.tmp1, self.ctx)\n+ BN_mod_exp(self.S, self.tmp2, self.b, self.N, self.ctx)\n \n+ self.K = self.hash_class( bn_to_bytes(self.S) ).digest()\n \n+ self.M = calculate_M( self.hash_class, self.N, self.g, self.I, self.s, self.A, self.B, self.K )\n+ self.H_AMK = calculate_H_AMK( self.hash_class, self.A, self.M, self.K )\n \n \n class User (object):\ndiff --git a/srp/_pysrp.py b/srp/_pysrp.py\nindex d59f100..854ef2f 100644\n--- a/srp/_pysrp.py\n+++ b/srp/_pysrp.py\n@@ -257,7 +257,7 @@ def calculate_H_AMK( hash_class, A, M, K ):\n \n class Verifier (object):\n \n- def __init__(self, username, bytes_s, bytes_v, bytes_A, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None, k_hex=None):\n+ def __init__(self, username, bytes_s, bytes_v, bytes_A=None, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None, bytes_b=None, k_hex=None):\n if ng_type == NG_CUSTOM and (n_hex is None or g_hex is None):\n raise ValueError(\"Both n_hex and g_hex are required when ng_type = NG_CUSTOM\")\n if bytes_b and len(bytes_b) != 32:\n@@ -268,6 +268,8 @@ class Verifier (object):\n self.K = None\n self._authenticated = False\n \n+ self.safety_failed = False\n+\n N,g = get_ng( ng_type, n_hex, g_hex )\n hash_class = _hash_map[ hash_alg ]\n if k_hex is None:\n@@ -280,23 +282,15 @@ class Verifier (object):\n self.g = g\n self.k = k\n \n- self.A = bytes_to_long(bytes_A)\n-\n- # SRP-6a safety check\n- self.safety_failed = self.A % N == 0\n+ if bytes_A:\n+ self._set_A(bytes_A)\n \n if not self.safety_failed:\n-\n if bytes_b:\n self.b = bytes_to_long(bytes_b)\n else:\n self.b = get_random_of_length( 32 )\n self.B = (k*self.v + pow(g, self.b, N)) % N\n- self.u = H(hash_class, self.A, self.B, width=len(long_to_bytes(N)))\n- self.S = pow(self.A*pow(self.v, self.u, N ), self.b, N)\n- self.K = hash_class( long_to_bytes(self.S) ).digest()\n- self.M = calculate_M( hash_class, N, g, self.I, self.s, self.A, self.B, self.K )\n- self.H_AMK = calculate_H_AMK( hash_class, self.A, self.M, self.K )\n \n \n def authenticated(self):\n@@ -322,10 +316,30 @@ class Verifier (object):\n return (long_to_bytes(self.s), long_to_bytes(self.B))\n \n # returns H_AMK on success, None on failure\n- def verify_session(self, user_M):\n- if not self.safety_failed and user_M == self.M:\n- self._authenticated = True\n- return self.H_AMK\n+ def verify_session(self, user_M, bytes_A=None):\n+ if bytes_A:\n+ self._set_A(bytes_A)\n+ if not hasattr(self, 'A'):\n+ raise ValueError(\"bytes_A must be provided through Verifier constructor or verify_session parameter.\")\n+ if not self.safety_failed:\n+ self._derive_H_AMK()\n+ if user_M == self.M:\n+ self._authenticated = True\n+ return self.H_AMK\n+\n+\n+ def _set_A(self, bytes_A):\n+ self.A = bytes_to_long(bytes_A)\n+ # SRP-6a safety check\n+ self.safety_failed = self.A % self.N == 0\n+\n+\n+ def _derive_H_AMK(self):\n+ self.u = H(self.hash_class, self.A, self.B, width=len(long_to_bytes(self.N)))\n+ self.S = pow(self.A*pow(self.v, self.u, self.N ), self.b, self.N)\n+ self.K = self.hash_class( long_to_bytes(self.S) ).digest()\n+ self.M = calculate_M( self.hash_class, self.N, self.g, self.I, self.s, self.A, self.B, self.K )\n+ self.H_AMK = calculate_H_AMK( self.hash_class, self.A, self.M, self.K )\n \n \n \ndiff --git a/srp/doc/srp.rst b/srp/doc/srp.rst\nindex b01ac62..fee30df 100644\n--- a/srp/doc/srp.rst\n+++ b/srp/doc/srp.rst\n@@ -141,7 +141,7 @@ user.\n The standard SRP 6 protocol allows only one password attempt per \n connection.\n \n-.. class:: Verifier( username, bytes_s, bytes_v, bytes_A[, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None] )\n+.. class:: Verifier( username, bytes_s, bytes_v[, bytes_A=None, hash_alg=SHA1, ng_type=NG_2048, n_hex=None, g_hex=None] )\n \n *username* Name of the remote user being authenticated.\n \n@@ -150,7 +150,10 @@ user.\n *bytes_v* Verification Key generated by :func:`create_salted_verification_key`.\n \n *bytes_A* Challenge from the remote user. Generated by\n- :meth:`User.start_authentication` \n+ :meth:`User.start_authentication`. Useful when user generates A\n+ before verifier generates B. If following RFC5054 section 2.2 where\n+ B is generated prior to A, then A can instead later be provided to\n+ Verifier via :func:`Verifier.verify_session`.\n \n *hash_alg*, *ng_type*, *n_hex*, *g_hex* Refer to the :ref:`constants` section.\n \n@@ -173,12 +176,13 @@ user.\n Return (bytes_s, bytes_B) on success or (None, None) if\n authentication has failed.\n \n- .. method:: Verifier.verify_session( user_M )\n+ .. method:: Verifier.verify_session( user_M[, user_A=None] )\n \n- Complete the :class:`Verifier` side of the authentication\n- process. If the authentication succeded the return result,\n- bytes_H_AMK should be returned to the remote user. On failure,\n- this method returns None.\n+ Complete the :class:`Verifier` side of the authentication process.\n+ If A was generated after B as in RFC5054 Section 2.2, then bytes_A\n+ can be provided here. If the authentication succeeded, bytes_H_AMK\n+ should be returned to the remote user. On failure, this method\n+ returns None.\n \n \n :class:`User` Objects\n@@ -350,13 +354,17 @@ M = H(H(N) xor H(g), H(I), s, A, B, K) Session key verifier\n The server stores the password verifier *v*. Authentication begins with a \n message from the client::\n \n- client -> server: I, A = g^a\n+ client -> server: I, [A = g^a]\n \n-The server replies with the verifier salt and challenge::\n+where public ephemeral key *A* may be provided at this point or later\n+as part of verification. The server replies with the verifier salt and\n+challenge::\n \n- server -> client: s, B = kv + g^b\n+ server -> client: s, B = kv + g^b, [N, g]\n \n-At this point, both the client and server calculate the shared session key::\n+where *N* and *g* may be provided by the server or hardcoded in the\n+user client. At this point, both the client and server calculate the\n+shared session key::\n \n client & server: u = H(A,B)\n \n@@ -372,13 +380,20 @@ At this point, both the client and server calculate the shared session key::\n Now both parties have a shared, strong session key *K*. To complete \n authentication they need to prove to each other that their keys match::\n \n- client -> server: M = H(H(N) xor H(g), H(I), s, A, B, K)\n+ client -> server: M = H(H(N) xor H(g), H(I), s, A, B, K), [A = g^a]\n server -> client: H(A, M, K)\n \n-SRP 6a requires the two parties to use the following safeguards:\n+Note that *A* is only provided here if it was not provided during the initial authentication request.\n+\n+SRP 6a requires the two parties to use the following safeguards (all of which this library automatically checks):\n \n 1. The client will abort if it recieves B == 0 (mod N) or u == 0\n 2. The server will abort if it detects A == 0 (mod N)\n 3. The client must show its proof of K first. If the server detects that this\n proof is incorrect it must abort without showing its own proof of K\n \n+Additionally, if the server provides N and g to the user, the user\n+should verify the safe prime bit length is as expected, that its\n+highest bit is 1 to ensure it is large, and that it is indeed a safe\n+prime with the expected generator. These N and g checks are not\n+currently provided by this library.\n", "test_patch": "diff --git a/srp/test_srp.py b/srp/test_srp.py\nindex b49aa78..165ef90 100644\n--- a/srp/test_srp.py\n+++ b/srp/test_srp.py\n@@ -85,12 +85,19 @@ class SRPTests( unittest.TestCase ):\n HAMK2 = svr2.verify_session( M )\n self.assertEqual(HAMK, HAMK2)\n \n+ # Make sure Verifier generating B before receiving A will not change authentication.\n+ svr3 = Verifier ( uname, _s, _v, None, hash_alg, ng_type, n_hex, g_hex, bytes_b, k_hex )\n+ self.assertEqual(bytes_b, svr3.get_ephemeral_secret())\n+ HAMK3 = svr3.verify_session( M, A )\n+ self.assertEqual(HAMK, HAMK3)\n+\n # HAMK => client\n usr.verify_session( HAMK )\n usr2.verify_session( HAMK )\n \n self.assertTrue( svr.authenticated() )\n self.assertTrue( svr2.authenticated() )\n+ self.assertTrue( svr3.authenticated() )\n \n self.assertTrue( usr.authenticated() )\n self.assertTrue( svr2.authenticated() )\n@@ -168,6 +175,16 @@ class SRPTests( unittest.TestCase ):\n def test_custom_k(self):\n self.doit( _ctsrp, _pysrp, _ctsrp, k_hex=six.b('5'))\n \n+ def test_verifier_requires_A(self):\n+ randbytes = _pysrp.long_to_bytes(_pysrp.get_random_of_length(32))\n+\n+ for mod in [_ctsrp, _pysrp]:\n+ svr = mod.Verifier('uname', randbytes, randbytes)\n+ with self.assertRaises(ValueError) as ctx:\n+ svr.verify_session(randbytes)\n+ self.assertIn('bytes_A', str(ctx.exception))\n+\n+\n #-----------------------------------------------------------------------------------\n # Performance Testing\n #\n", "FAIL_TO_PASS": ["srp/test_srp.py::SRPTests::test_NG_8192", "srp/test_srp.py::SRPTests::test_NG_CUSTOM", "srp/test_srp.py::SRPTests::test_all1", "srp/test_srp.py::SRPTests::test_all2", "srp/test_srp.py::SRPTests::test_ctypes_defaults", "srp/test_srp.py::SRPTests::test_custom_k", "srp/test_srp.py::SRPTests::test_hash_SHA512", "srp/test_srp.py::SRPTests::test_mix1", "srp/test_srp.py::SRPTests::test_mix2", "srp/test_srp.py::SRPTests::test_mix3", "srp/test_srp.py::SRPTests::test_mix4", "srp/test_srp.py::SRPTests::test_pure_python_defaults", "srp/test_srp.py::SRPTests::test_verifier_requires_A"]}], "all_FAIL_TO_PASS": ["srp/test_srp.py::SRPTests::test_NG_8192", "srp/test_srp.py::SRPTests::test_NG_CUSTOM", "srp/test_srp.py::SRPTests::test_all1", "srp/test_srp.py::SRPTests::test_all2", "srp/test_srp.py::SRPTests::test_ctypes_defaults", "srp/test_srp.py::SRPTests::test_custom_k", "srp/test_srp.py::SRPTests::test_hash_SHA512", "srp/test_srp.py::SRPTests::test_mix1", "srp/test_srp.py::SRPTests::test_mix2", "srp/test_srp.py::SRPTests::test_mix3", "srp/test_srp.py::SRPTests::test_mix4", "srp/test_srp.py::SRPTests::test_pure_python_defaults", "srp/test_srp.py::SRPTests::test_NG_8192", "srp/test_srp.py::SRPTests::test_NG_CUSTOM", "srp/test_srp.py::SRPTests::test_all1", "srp/test_srp.py::SRPTests::test_all2", "srp/test_srp.py::SRPTests::test_ctypes_defaults", "srp/test_srp.py::SRPTests::test_custom_k", "srp/test_srp.py::SRPTests::test_hash_SHA512", "srp/test_srp.py::SRPTests::test_mix1", "srp/test_srp.py::SRPTests::test_mix2", "srp/test_srp.py::SRPTests::test_mix3", "srp/test_srp.py::SRPTests::test_mix4", "srp/test_srp.py::SRPTests::test_pure_python_defaults", "srp/test_srp.py::SRPTests::test_verifier_requires_A"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "astanin__python-tabulate-139_x2", "level": 2, "source": "swerebench", "repo": "astanin/python-tabulate", "image": "swerebench/sweb.eval.x86_64.astanin_1776_python-tabulate-139:latest", "base_commit": "b2c26bcb70e497f674b38aa7e29de12c0123708a", "num_bugs": 2, "bugs": [{"instance_id": "astanin__python-tabulate-139", "base_commit": "b2c26bcb70e497f674b38aa7e29de12c0123708a", "gold_patch": "diff --git a/tabulate.py b/tabulate.py\nindex 0579fb3..0a23f3c 100644\n--- a/tabulate.py\n+++ b/tabulate.py\n@@ -1189,6 +1189,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex=\"default\"):\n headers = rows[0]\n headers = list(map(_text_type, headers)) # headers should be strings\n rows = rows[1:]\n+ elif headers == \"firstrow\":\n+ headers = []\n \n headers = list(map(_text_type, headers))\n rows = list(map(list, rows))\n", "test_patch": "diff --git a/test/test_output.py b/test/test_output.py\nindex eed4489..b751e5e 100644\n--- a/test/test_output.py\n+++ b/test/test_output.py\n@@ -1412,6 +1412,13 @@ def test_empty_data_without_headers():\n assert_equal(expected, result)\n \n \n+def test_empty_data_with_headers():\n+ \"Output: table with empty data and headers as firstrow\"\n+ expected = \"\"\n+ result = tabulate([], headers=\"firstrow\")\n+ assert_equal(expected, result)\n+\n+\n def test_floatfmt():\n \"Output: floating point format\"\n result = tabulate([[\"1.23456789\"], [1.0]], floatfmt=\".3f\", tablefmt=\"plain\")\n", "FAIL_TO_PASS": ["test/test_output.py::test_empty_data_with_headers"]}, {"instance_id": "astanin__python-tabulate-151", "base_commit": "792bfdd1557d99fda5bc99453ccb3b96889083a1", "gold_patch": "diff --git a/README.md b/README.md\nindex 7378a76..37fbdbe 100644\n--- a/README.md\n+++ b/README.md\n@@ -137,7 +137,15 @@ Supported table formats are:\n - \"simple\"\n - \"github\"\n - \"grid\"\n+- \"simple\\_grid\"\n+- \"rounded\\_grid\"\n+- \"double\\_grid\"\n - \"fancy\\_grid\"\n+- \"outline\"\n+- \"simple\\_outline\"\n+- \"rounded\\_outline\"\n+- \"double\\_outline\"\n+- \"fancy\\_outline\"\n - \"pipe\"\n - \"orgtbl\"\n - \"jira\"\n@@ -203,7 +211,47 @@ corresponds to the `pipe` format without alignment colons:\n | bacon | 0 |\n +--------+-------+\n \n-`fancy_grid` draws a grid using box-drawing characters:\n+`simple_grid` draws a grid using single-line box-drawing characters:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"simple_grid\"))\n+ \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n+ \u2502 item \u2502 qty \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 42 \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 eggs \u2502 451 \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 bacon \u2502 0 \u2502\n+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n+\n+`rounded_grid` draws a grid using single-line box-drawing characters with rounded corners:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"rounded_grid\"))\n+ \u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n+ \u2502 item \u2502 qty \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 42 \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 eggs \u2502 451 \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 bacon \u2502 0 \u2502\n+ \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n+\n+`double_grid` draws a grid using double-line box-drawing characters:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"double_grid\"))\n+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n+ \u2551 item \u2551 qty \u2551\n+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n+ \u2551 spam \u2551 42 \u2551\n+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n+ \u2551 eggs \u2551 451 \u2551\n+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n+ \u2551 bacon \u2551 0 \u2551\n+ \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n+\n+`fancy_grid` draws a grid using a mix of single and\n+ double-line box-drawing characters:\n \n >>> print(tabulate(table, headers, tablefmt=\"fancy_grid\"))\n \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555\n@@ -216,6 +264,61 @@ corresponds to the `pipe` format without alignment colons:\n \u2502 bacon \u2502 0 \u2502\n \u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\n \n+`outline` is the same as the `grid` format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"outline\"))\n+ +--------+-------+\n+ | item | qty |\n+ +========+=======+\n+ | spam | 42 |\n+ | eggs | 451 |\n+ | bacon | 0 |\n+ +--------+-------+\n+\n+`simple_outline` is the same as the `simple_grid` format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"simple_outline\"))\n+ \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n+ \u2502 item \u2502 qty \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 42 \u2502\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2502 bacon \u2502 0 \u2502\n+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n+\n+`rounded_outline` is the same as the `rounded_grid` format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"rounded_outline\"))\n+ \u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n+ \u2502 item \u2502 qty \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 42 \u2502\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2502 bacon \u2502 0 \u2502\n+ \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n+\n+`double_outline` is the same as the `double_grid` format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"double_outline\"))\n+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n+ \u2551 item \u2551 qty \u2551\n+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n+ \u2551 spam \u2551 42 \u2551\n+ \u2551 eggs \u2551 451 \u2551\n+ \u2551 bacon \u2551 0 \u2551\n+ \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n+\n+`fancy_outline` is the same as the `fancy_grid` format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate(table, headers, tablefmt=\"fancy_outline\"))\n+ \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555\n+ \u2502 item \u2502 qty \u2502\n+ \u255e\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561\n+ \u2502 spam \u2502 42 \u2502\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2502 bacon \u2502 0 \u2502\n+ \u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\n+\n `presto` is like tables formatted by Presto cli:\n \n >>> print(tabulate(table, headers, tablefmt=\"presto\"))\ndiff --git a/tabulate.py b/tabulate.py\nindex a0b2dc2..f23a1a8 100644\n--- a/tabulate.py\n+++ b/tabulate.py\n@@ -310,6 +310,36 @@ _table_formats = {\n padding=1,\n with_header_hide=None,\n ),\n+ \"simple_grid\": TableFormat(\n+ lineabove=Line(\"\u250c\", \"\u2500\", \"\u252c\", \"\u2510\"),\n+ linebelowheader=Line(\"\u251c\", \"\u2500\", \"\u253c\", \"\u2524\"),\n+ linebetweenrows=Line(\"\u251c\", \"\u2500\", \"\u253c\", \"\u2524\"),\n+ linebelow=Line(\"\u2514\", \"\u2500\", \"\u2534\", \"\u2518\"),\n+ headerrow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ datarow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ padding=1,\n+ with_header_hide=None,\n+ ),\n+ \"rounded_grid\": TableFormat(\n+ lineabove=Line(\"\u256d\", \"\u2500\", \"\u252c\", \"\u256e\"),\n+ linebelowheader=Line(\"\u251c\", \"\u2500\", \"\u253c\", \"\u2524\"),\n+ linebetweenrows=Line(\"\u251c\", \"\u2500\", \"\u253c\", \"\u2524\"),\n+ linebelow=Line(\"\u2570\", \"\u2500\", \"\u2534\", \"\u256f\"),\n+ headerrow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ datarow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ padding=1,\n+ with_header_hide=None,\n+ ),\n+ \"double_grid\": TableFormat(\n+ lineabove=Line(\"\u2554\", \"\u2550\", \"\u2566\", \"\u2557\"),\n+ linebelowheader=Line(\"\u2560\", \"\u2550\", \"\u256c\", \"\u2563\"),\n+ linebetweenrows=Line(\"\u2560\", \"\u2550\", \"\u256c\", \"\u2563\"),\n+ linebelow=Line(\"\u255a\", \"\u2550\", \"\u2569\", \"\u255d\"),\n+ headerrow=DataRow(\"\u2551\", \"\u2551\", \"\u2551\"),\n+ datarow=DataRow(\"\u2551\", \"\u2551\", \"\u2551\"),\n+ padding=1,\n+ with_header_hide=None,\n+ ),\n \"fancy_grid\": TableFormat(\n lineabove=Line(\"\u2552\", \"\u2550\", \"\u2564\", \"\u2555\"),\n linebelowheader=Line(\"\u255e\", \"\u2550\", \"\u256a\", \"\u2561\"),\n@@ -320,6 +350,46 @@ _table_formats = {\n padding=1,\n with_header_hide=None,\n ),\n+ \"outline\": TableFormat(\n+ lineabove=Line(\"+\", \"-\", \"+\", \"+\"),\n+ linebelowheader=Line(\"+\", \"=\", \"+\", \"+\"),\n+ linebetweenrows=None,\n+ linebelow=Line(\"+\", \"-\", \"+\", \"+\"),\n+ headerrow=DataRow(\"|\", \"|\", \"|\"),\n+ datarow=DataRow(\"|\", \"|\", \"|\"),\n+ padding=1,\n+ with_header_hide=None,\n+ ),\n+ \"simple_outline\": TableFormat(\n+ lineabove=Line(\"\u250c\", \"\u2500\", \"\u252c\", \"\u2510\"),\n+ linebelowheader=Line(\"\u251c\", \"\u2500\", \"\u253c\", \"\u2524\"),\n+ linebetweenrows=None,\n+ linebelow=Line(\"\u2514\", \"\u2500\", \"\u2534\", \"\u2518\"),\n+ headerrow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ datarow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ padding=1,\n+ with_header_hide=None,\n+ ),\n+ \"rounded_outline\": TableFormat(\n+ lineabove=Line(\"\u256d\", \"\u2500\", \"\u252c\", \"\u256e\"),\n+ linebelowheader=Line(\"\u251c\", \"\u2500\", \"\u253c\", \"\u2524\"),\n+ linebetweenrows=None,\n+ linebelow=Line(\"\u2570\", \"\u2500\", \"\u2534\", \"\u256f\"),\n+ headerrow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ datarow=DataRow(\"\u2502\", \"\u2502\", \"\u2502\"),\n+ padding=1,\n+ with_header_hide=None,\n+ ),\n+ \"double_outline\": TableFormat(\n+ lineabove=Line(\"\u2554\", \"\u2550\", \"\u2566\", \"\u2557\"),\n+ linebelowheader=Line(\"\u2560\", \"\u2550\", \"\u256c\", \"\u2563\"),\n+ linebetweenrows=None,\n+ linebelow=Line(\"\u255a\", \"\u2550\", \"\u2569\", \"\u255d\"),\n+ headerrow=DataRow(\"\u2551\", \"\u2551\", \"\u2551\"),\n+ datarow=DataRow(\"\u2551\", \"\u2551\", \"\u2551\"),\n+ padding=1,\n+ with_header_hide=None,\n+ ),\n \"fancy_outline\": TableFormat(\n lineabove=Line(\"\u2552\", \"\u2550\", \"\u2564\", \"\u2555\"),\n linebelowheader=Line(\"\u255e\", \"\u2550\", \"\u256a\", \"\u2561\"),\n@@ -537,6 +607,9 @@ multiline_formats = {\n \"plain\": \"plain\",\n \"simple\": \"simple\",\n \"grid\": \"grid\",\n+ \"simple_grid\": \"simple_grid\",\n+ \"rounded_grid\": \"rounded_grid\",\n+ \"double_grid\": \"double_grid\",\n \"fancy_grid\": \"fancy_grid\",\n \"pipe\": \"pipe\",\n \"orgtbl\": \"orgtbl\",\n@@ -1425,7 +1498,47 @@ def tabulate(\n | eggs | 451 |\n +------+----------+\n \n- \"fancy_grid\" draws a grid using box-drawing characters:\n+ \"simple_grid\" draws a grid using single-line box-drawing\n+ characters:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"simple_grid\"))\n+ \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n+ \u2502 strings \u2502 numbers \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 41.9999 \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n+\n+ \"rounded_grid\" draws a grid using single-line box-drawing\n+ characters with rounded corners:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"rounded_grid\"))\n+ \u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n+ \u2502 strings \u2502 numbers \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 41.9999 \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n+\n+ \"double_grid\" draws a grid using double-line box-drawing\n+ characters:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"double_grid\"))\n+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n+ \u2551 strings \u2551 numbers \u2551\n+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n+ \u2551 spam \u2551 41.9999 \u2551\n+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n+ \u2551 eggs \u2551 451 \u2551\n+ \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n+\n+ \"fancy_grid\" draws a grid using a mix of single and\n+ double-line box-drawing characters:\n \n >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n ... [\"strings\", \"numbers\"], \"fancy_grid\"))\n@@ -1437,6 +1550,67 @@ def tabulate(\n \u2502 eggs \u2502 451 \u2502\n \u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\n \n+ \"outline\" is the same as the \"grid\" format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"outline\"))\n+ +-----------+-----------+\n+ | strings | numbers |\n+ +===========+===========+\n+ | spam | 41.9999 |\n+ | eggs | 451 |\n+ +-----------+-----------+\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]], tablefmt=\"outline\"))\n+ +------+----------+\n+ | spam | 41.9999 |\n+ | eggs | 451 |\n+ +------+----------+\n+\n+ \"simple_outline\" is the same as the \"simple_grid\" format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"simple_outline\"))\n+ \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n+ \u2502 strings \u2502 numbers \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 41.9999 \u2502\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n+\n+ \"rounded_outline\" is the same as the \"rounded_grid\" format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"rounded_outline\"))\n+ \u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n+ \u2502 strings \u2502 numbers \u2502\n+ \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n+ \u2502 spam \u2502 41.9999 \u2502\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n+\n+ \"double_outline\" is the same as the \"double_grid\" format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"double_outline\"))\n+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n+ \u2551 strings \u2551 numbers \u2551\n+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n+ \u2551 spam \u2551 41.9999 \u2551\n+ \u2551 eggs \u2551 451 \u2551\n+ \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n+\n+ \"fancy_outline\" is the same as the \"fancy_grid\" format but doesn't draw lines between rows:\n+\n+ >>> print(tabulate([[\"spam\", 41.9999], [\"eggs\", \"451.0\"]],\n+ ... [\"strings\", \"numbers\"], \"fancy_outline\"))\n+ \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555\n+ \u2502 strings \u2502 numbers \u2502\n+ \u255e\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561\n+ \u2502 spam \u2502 41.9999 \u2502\n+ \u2502 eggs \u2502 451 \u2502\n+ \u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\n+\n \"pipe\" is like tables in PHP Markdown Extra extension or Pandoc\n pipe_tables:\n \n", "test_patch": "diff --git a/test/test_output.py b/test/test_output.py\nindex eed4489..ef27a91 100644\n--- a/test/test_output.py\n+++ b/test/test_output.py\n@@ -478,6 +478,411 @@ def test_grid_multiline_with_empty_cells_headerless():\n assert_equal(expected, result)\n \n \n+def test_simple_grid():\n+ \"Output: simple_grid with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 strings \u2502 numbers \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"simple_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_grid_wide_characters():\n+ \"Output: simple_grid with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_simple_grid_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 strings \u2502 \u914d\u5217 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"simple_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_grid_headerless():\n+ \"Output: simple_grid without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"simple_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_grid_multiline_headerless():\n+ \"Output: simple_grid with multiline cells without headers\"\n+ table = [[\"foo bar\\nbaz\\nbau\", \"hello\"], [\"\", \"multiline\\nworld\"]]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 foo bar \u2502 hello \u2502\",\n+ \"\u2502 baz \u2502 \u2502\",\n+ \"\u2502 bau \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 \u2502 multiline \u2502\",\n+ \"\u2502 \u2502 world \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(table, stralign=\"center\", tablefmt=\"simple_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_grid_multiline():\n+ \"Output: simple_grid with multiline cells with headers\"\n+ table = [[2, \"foo\\nbar\"]]\n+ headers = (\"more\\nspam \\x1b[31meggs\\x1b[0m\", \"more spam\\n& eggs\")\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 more \u2502 more spam \u2502\",\n+ \"\u2502 spam \\x1b[31meggs\\x1b[0m \u2502 & eggs \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 2 \u2502 foo \u2502\",\n+ \"\u2502 \u2502 bar \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(table, headers, tablefmt=\"simple_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_grid_multiline_with_empty_cells():\n+ \"Output: simple_grid with multiline cells and empty cells with headers\"\n+ table = [\n+ [\"hdr\", \"data\", \"fold\"],\n+ [\"1\", \"\", \"\"],\n+ [\"2\", \"very long data\", \"fold\\nthis\"],\n+ ]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 hdr \u2502 data \u2502 fold \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 1 \u2502 \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 2 \u2502 very long data \u2502 fold \u2502\",\n+ \"\u2502 \u2502 \u2502 this \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(table, headers=\"firstrow\", tablefmt=\"simple_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_grid_multiline_with_empty_cells_headerless():\n+ \"Output: simple_grid with multiline cells and empty cells without headers\"\n+ table = [[\"0\", \"\", \"\"], [\"1\", \"\", \"\"], [\"2\", \"very long data\", \"fold\\nthis\"]]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 0 \u2502 \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 1 \u2502 \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 2 \u2502 very long data \u2502 fold \u2502\",\n+ \"\u2502 \u2502 \u2502 this \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(table, tablefmt=\"simple_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_grid():\n+ \"Output: rounded_grid with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 strings \u2502 numbers \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"rounded_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_grid_wide_characters():\n+ \"Output: rounded_grid with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_rounded_grid_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 strings \u2502 \u914d\u5217 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"rounded_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_grid_headerless():\n+ \"Output: rounded_grid without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"rounded_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_grid_multiline_headerless():\n+ \"Output: rounded_grid with multiline cells without headers\"\n+ table = [[\"foo bar\\nbaz\\nbau\", \"hello\"], [\"\", \"multiline\\nworld\"]]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 foo bar \u2502 hello \u2502\",\n+ \"\u2502 baz \u2502 \u2502\",\n+ \"\u2502 bau \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 \u2502 multiline \u2502\",\n+ \"\u2502 \u2502 world \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(table, stralign=\"center\", tablefmt=\"rounded_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_grid_multiline():\n+ \"Output: rounded_grid with multiline cells with headers\"\n+ table = [[2, \"foo\\nbar\"]]\n+ headers = (\"more\\nspam \\x1b[31meggs\\x1b[0m\", \"more spam\\n& eggs\")\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 more \u2502 more spam \u2502\",\n+ \"\u2502 spam \\x1b[31meggs\\x1b[0m \u2502 & eggs \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 2 \u2502 foo \u2502\",\n+ \"\u2502 \u2502 bar \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(table, headers, tablefmt=\"rounded_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_grid_multiline_with_empty_cells():\n+ \"Output: rounded_grid with multiline cells and empty cells with headers\"\n+ table = [\n+ [\"hdr\", \"data\", \"fold\"],\n+ [\"1\", \"\", \"\"],\n+ [\"2\", \"very long data\", \"fold\\nthis\"],\n+ ]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 hdr \u2502 data \u2502 fold \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 1 \u2502 \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 2 \u2502 very long data \u2502 fold \u2502\",\n+ \"\u2502 \u2502 \u2502 this \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(table, headers=\"firstrow\", tablefmt=\"rounded_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_grid_multiline_with_empty_cells_headerless():\n+ \"Output: rounded_grid with multiline cells and empty cells without headers\"\n+ table = [[\"0\", \"\", \"\"], [\"1\", \"\", \"\"], [\"2\", \"very long data\", \"fold\\nthis\"]]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 0 \u2502 \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 1 \u2502 \u2502 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 2 \u2502 very long data \u2502 fold \u2502\",\n+ \"\u2502 \u2502 \u2502 this \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(table, tablefmt=\"rounded_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_grid():\n+ \"Output: double_grid with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 strings \u2551 numbers \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 spam \u2551 41.9999 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 eggs \u2551 451 \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"double_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_grid_wide_characters():\n+ \"Output: double_grid with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_double_grid_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 strings \u2551 \u914d\u5217 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 spam \u2551 41.9999 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 eggs \u2551 451 \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"double_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_grid_headerless():\n+ \"Output: double_grid without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 spam \u2551 41.9999 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 eggs \u2551 451 \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"double_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_grid_multiline_headerless():\n+ \"Output: double_grid with multiline cells without headers\"\n+ table = [[\"foo bar\\nbaz\\nbau\", \"hello\"], [\"\", \"multiline\\nworld\"]]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 foo bar \u2551 hello \u2551\",\n+ \"\u2551 baz \u2551 \u2551\",\n+ \"\u2551 bau \u2551 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 \u2551 multiline \u2551\",\n+ \"\u2551 \u2551 world \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(table, stralign=\"center\", tablefmt=\"double_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_grid_multiline():\n+ \"Output: double_grid with multiline cells with headers\"\n+ table = [[2, \"foo\\nbar\"]]\n+ headers = (\"more\\nspam \\x1b[31meggs\\x1b[0m\", \"more spam\\n& eggs\")\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 more \u2551 more spam \u2551\",\n+ \"\u2551 spam \\x1b[31meggs\\x1b[0m \u2551 & eggs \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 2 \u2551 foo \u2551\",\n+ \"\u2551 \u2551 bar \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(table, headers, tablefmt=\"double_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_grid_multiline_with_empty_cells():\n+ \"Output: double_grid with multiline cells and empty cells with headers\"\n+ table = [\n+ [\"hdr\", \"data\", \"fold\"],\n+ [\"1\", \"\", \"\"],\n+ [\"2\", \"very long data\", \"fold\\nthis\"],\n+ ]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 hdr \u2551 data \u2551 fold \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 1 \u2551 \u2551 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 2 \u2551 very long data \u2551 fold \u2551\",\n+ \"\u2551 \u2551 \u2551 this \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(table, headers=\"firstrow\", tablefmt=\"double_grid\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_grid_multiline_with_empty_cells_headerless():\n+ \"Output: double_grid with multiline cells and empty cells without headers\"\n+ table = [[\"0\", \"\", \"\"], [\"1\", \"\", \"\"], [\"2\", \"very long data\", \"fold\\nthis\"]]\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 0 \u2551 \u2551 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 1 \u2551 \u2551 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 2 \u2551 very long data \u2551 fold \u2551\",\n+ \"\u2551 \u2551 \u2551 this \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(table, tablefmt=\"double_grid\")\n+ assert_equal(expected, result)\n+\n+\n def test_fancy_grid():\n \"Output: fancy_grid with headers\"\n expected = \"\\n\".join(\n@@ -495,6 +900,29 @@ def test_fancy_grid():\n assert_equal(expected, result)\n \n \n+def test_fancy_grid_wide_characters():\n+ \"Output: fancy_grid with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_fancy_grid_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555\",\n+ \"\u2502 strings \u2502 \u914d\u5217 \u2502\",\n+ \"\u255e\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"fancy_grid\")\n+ assert_equal(expected, result)\n+\n+\n def test_fancy_grid_headerless():\n \"Output: fancy_grid without headers\"\n expected = \"\\n\".join(\n@@ -590,6 +1018,266 @@ def test_fancy_grid_multiline_with_empty_cells_headerless():\n assert_equal(expected, result)\n \n \n+def test_outline():\n+ \"Output: outline with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"+-----------+-----------+\",\n+ \"| strings | numbers |\",\n+ \"+===========+===========+\",\n+ \"| spam | 41.9999 |\",\n+ \"| eggs | 451 |\",\n+ \"+-----------+-----------+\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_outline_wide_characters():\n+ \"Output: outline with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_outline_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"+-----------+----------+\",\n+ \"| strings | \u914d\u5217 |\",\n+ \"+===========+==========+\",\n+ \"| spam | 41.9999 |\",\n+ \"| eggs | 451 |\",\n+ \"+-----------+----------+\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_outline_headerless():\n+ \"Output: outline without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"+------+----------+\",\n+ \"| spam | 41.9999 |\",\n+ \"| eggs | 451 |\",\n+ \"+------+----------+\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_outline():\n+ \"Output: simple_outline with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 strings \u2502 numbers \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"simple_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_outline_wide_characters():\n+ \"Output: simple_outline with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_simple_outline_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 strings \u2502 \u914d\u5217 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"simple_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_simple_outline_headerless():\n+ \"Output: simple_outline without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"simple_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_outline():\n+ \"Output: rounded_outline with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 strings \u2502 numbers \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"rounded_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_outline_wide_characters():\n+ \"Output: rounded_outline with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_rounded_outline_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 strings \u2502 \u914d\u5217 \u2502\",\n+ \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"rounded_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_rounded_outline_headerless():\n+ \"Output: rounded_outline without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"rounded_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_outline():\n+ \"Output: double_outline with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 strings \u2551 numbers \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 spam \u2551 41.9999 \u2551\",\n+ \"\u2551 eggs \u2551 451 \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"double_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_outline_wide_characters():\n+ \"Output: double_outline with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_double_outline_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 strings \u2551 \u914d\u5217 \u2551\",\n+ \"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\",\n+ \"\u2551 spam \u2551 41.9999 \u2551\",\n+ \"\u2551 eggs \u2551 451 \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"double_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_double_outline_headerless():\n+ \"Output: double_outline without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\",\n+ \"\u2551 spam \u2551 41.9999 \u2551\",\n+ \"\u2551 eggs \u2551 451 \u2551\",\n+ \"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"double_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_fancy_outline():\n+ \"Output: fancy_outline with headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555\",\n+ \"\u2502 strings \u2502 numbers \u2502\",\n+ \"\u255e\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\",\n+ ]\n+ )\n+ result = tabulate(_test_table, _test_table_headers, tablefmt=\"fancy_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_fancy_outline_wide_characters():\n+ \"Output: fancy_outline with wide characters in headers\"\n+ try:\n+ import wcwidth # noqa\n+ except ImportError:\n+ skip(\"test_fancy_outline_wide_characters is skipped\")\n+ headers = list(_test_table_headers)\n+ headers[1] = \"\u914d\u5217\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555\",\n+ \"\u2502 strings \u2502 \u914d\u5217 \u2502\",\n+ \"\u255e\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\",\n+ ]\n+ )\n+ result = tabulate(_test_table, headers, tablefmt=\"fancy_outline\")\n+ assert_equal(expected, result)\n+\n+\n+def test_fancy_outline_headerless():\n+ \"Output: fancy_outline without headers\"\n+ expected = \"\\n\".join(\n+ [\n+ \"\u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555\",\n+ \"\u2502 spam \u2502 41.9999 \u2502\",\n+ \"\u2502 eggs \u2502 451 \u2502\",\n+ \"\u2558\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255b\",\n+ ]\n+ )\n+ result = tabulate(_test_table, tablefmt=\"fancy_outline\")\n+ assert_equal(expected, result)\n+\n+\n def test_pipe():\n \"Output: pipe with headers\"\n expected = \"\\n\".join(\n", "FAIL_TO_PASS": ["test/test_output.py::test_simple_grid", "test/test_output.py::test_simple_grid_wide_characters", "test/test_output.py::test_simple_grid_headerless", "test/test_output.py::test_simple_grid_multiline_headerless", "test/test_output.py::test_simple_grid_multiline", "test/test_output.py::test_simple_grid_multiline_with_empty_cells", "test/test_output.py::test_simple_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_rounded_grid", "test/test_output.py::test_rounded_grid_wide_characters", "test/test_output.py::test_rounded_grid_headerless", "test/test_output.py::test_rounded_grid_multiline_headerless", "test/test_output.py::test_rounded_grid_multiline", "test/test_output.py::test_rounded_grid_multiline_with_empty_cells", "test/test_output.py::test_rounded_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_double_grid", "test/test_output.py::test_double_grid_wide_characters", "test/test_output.py::test_double_grid_headerless", "test/test_output.py::test_double_grid_multiline_headerless", "test/test_output.py::test_double_grid_multiline", "test/test_output.py::test_double_grid_multiline_with_empty_cells", "test/test_output.py::test_double_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_outline", "test/test_output.py::test_outline_wide_characters", "test/test_output.py::test_outline_headerless", "test/test_output.py::test_simple_outline", "test/test_output.py::test_simple_outline_wide_characters", "test/test_output.py::test_simple_outline_headerless", "test/test_output.py::test_rounded_outline", "test/test_output.py::test_rounded_outline_wide_characters", "test/test_output.py::test_rounded_outline_headerless", "test/test_output.py::test_double_outline", "test/test_output.py::test_double_outline_wide_characters", "test/test_output.py::test_double_outline_headerless"]}], "all_FAIL_TO_PASS": ["test/test_output.py::test_empty_data_with_headers", "test/test_output.py::test_simple_grid", "test/test_output.py::test_simple_grid_wide_characters", "test/test_output.py::test_simple_grid_headerless", "test/test_output.py::test_simple_grid_multiline_headerless", "test/test_output.py::test_simple_grid_multiline", "test/test_output.py::test_simple_grid_multiline_with_empty_cells", "test/test_output.py::test_simple_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_rounded_grid", "test/test_output.py::test_rounded_grid_wide_characters", "test/test_output.py::test_rounded_grid_headerless", "test/test_output.py::test_rounded_grid_multiline_headerless", "test/test_output.py::test_rounded_grid_multiline", "test/test_output.py::test_rounded_grid_multiline_with_empty_cells", "test/test_output.py::test_rounded_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_double_grid", "test/test_output.py::test_double_grid_wide_characters", "test/test_output.py::test_double_grid_headerless", "test/test_output.py::test_double_grid_multiline_headerless", "test/test_output.py::test_double_grid_multiline", "test/test_output.py::test_double_grid_multiline_with_empty_cells", "test/test_output.py::test_double_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_outline", "test/test_output.py::test_outline_wide_characters", "test/test_output.py::test_outline_headerless", "test/test_output.py::test_simple_outline", "test/test_output.py::test_simple_outline_wide_characters", "test/test_output.py::test_simple_outline_headerless", "test/test_output.py::test_rounded_outline", "test/test_output.py::test_rounded_outline_wide_characters", "test/test_output.py::test_rounded_outline_headerless", "test/test_output.py::test_double_outline", "test/test_output.py::test_double_outline_wide_characters", "test/test_output.py::test_double_outline_headerless"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jackdewinter__pymarkdown-1248_x2", "level": 2, "source": "swerebench", "repo": "jackdewinter/pymarkdown", "image": "swerebench/sweb.eval.x86_64.jackdewinter_1776_pymarkdown-1248:latest", "base_commit": "cee1f3f5575f73b671deb4374c6e7a263fa40df9", "num_bugs": 2, "bugs": [{"instance_id": "jackdewinter__pymarkdown-1248", "base_commit": "cee1f3f5575f73b671deb4374c6e7a263fa40df9", "gold_patch": "diff --git a/newdocs/src/changelog.md b/newdocs/src/changelog.md\nindex be928638..9acc115f 100644\n--- a/newdocs/src/changelog.md\n+++ b/newdocs/src/changelog.md\n@@ -23,6 +23,10 @@\n - [Issue 1245](https://github.com/jackdewinter/pymarkdown/issues/1245)\n - Handling leading spaces in `__fix_spacing` function now that data\n is present.\n+- [Issue 1247](https://github.com/jackdewinter/pymarkdown/issues/1247)\n+ - In 3+ drop cases with only lists and no block quotes, indent is\n+ not calculated properly on rehydrate. This in turn causes the\n+ fixed text to be wrong.\n \n \n ### Changed\ndiff --git a/publish/coverage.json b/publish/coverage.json\nindex 398dc062..11801c21 100644\n--- a/publish/coverage.json\n+++ b/publish/coverage.json\n@@ -2,12 +2,12 @@\n \"projectName\": \"pymarkdown\",\n \"reportSource\": \"pytest\",\n \"branchLevel\": {\n- \"totalMeasured\": 5393,\n- \"totalCovered\": 5392\n+ \"totalMeasured\": 5403,\n+ \"totalCovered\": 5401\n },\n \"lineLevel\": {\n- \"totalMeasured\": 21094,\n- \"totalCovered\": 21093\n+ \"totalMeasured\": 21123,\n+ \"totalCovered\": 21122\n }\n }\n \ndiff --git a/pymarkdown/plugins/rule_md_031.py b/pymarkdown/plugins/rule_md_031.py\nindex 07d958bc..c6ebf6fc 100644\n--- a/pymarkdown/plugins/rule_md_031.py\n+++ b/pymarkdown/plugins/rule_md_031.py\n@@ -56,6 +56,7 @@ class RuleMd031(RulePlugin):\n self.__removed_container_adjustments: Optional[\n List[PendingContainerAdjustment]\n ] = None\n+ self.__last_end_container_tokens: List[MarkdownToken] = []\n \n self.__leading_space_index_tracker = LeadingSpaceIndexTracker()\n \n@@ -513,17 +514,26 @@ class RuleMd031(RulePlugin):\n new_token.adjust_line_number(context, self.__fix_count)\n assert self.__last_token is not None\n if token.is_fenced_code_block and self.__last_token.is_list_end:\n+ end_container_index = len(self.__last_end_container_tokens) - 1\n+ while (\n+ end_container_index >= 0\n+ and self.__last_end_container_tokens[end_container_index].is_list_end\n+ ):\n+ end_container_index -= 1\n+ first_token = self.__last_end_container_tokens[end_container_index + 1]\n replacement_tokens: List[MarkdownToken] = [\n BlankLineMarkdownToken(\n extracted_whitespace=\"\",\n position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n column_delta=1,\n- ),\n- self.__last_token,\n- new_token,\n+ )\n ]\n+ replacement_tokens.extend(\n+ self.__last_end_container_tokens[end_container_index + 1 :]\n+ )\n+ replacement_tokens.append(new_token)\n self.register_replace_tokens_request(\n- context, self.__last_token, token, replacement_tokens\n+ context, first_token, token, replacement_tokens\n )\n elif did_special_list_fix:\n assert self.__last_token and self.__last_token.is_block_quote_end\n@@ -755,6 +765,11 @@ class RuleMd031(RulePlugin):\n ):\n self.__last_non_end_token = token\n \n+ if token.is_block_quote_end or token.is_list_end:\n+ self.__last_end_container_tokens.append(token)\n+ else:\n+ self.__last_end_container_tokens.clear()\n+\n self.__second_last_token = self.__last_token\n self.__last_token = token\n self.__removed_container_stack_token = None\ndiff --git a/pymarkdown/transform_markdown/transform_containers.py b/pymarkdown/transform_markdown/transform_containers.py\nindex 18b20bc9..f3d5eb56 100644\n--- a/pymarkdown/transform_markdown/transform_containers.py\n+++ b/pymarkdown/transform_markdown/transform_containers.py\n@@ -426,9 +426,55 @@ class TransformContainers:\n \n # pylint: enable=too-many-arguments, too-many-boolean-expressions\n \n+ @staticmethod\n+ def __abcd_final_list_second_half(\n+ removed_tokens: List[MarkdownToken],\n+ removed_token_indices: List[int],\n+ container_stack: List[MarkdownToken],\n+ possible_prefix: Optional[str],\n+ ) -> Optional[str]:\n+ container_stack_copy: List[MarkdownToken] = container_stack[:]\n+ container_stack_copy.extend(removed_tokens[::-1])\n+ is_only_list_starts_on_stack = not any(\n+ i.is_block_quote_start for i in container_stack_copy\n+ )\n+\n+ prefix = None\n+ if is_only_list_starts_on_stack and possible_prefix is not None:\n+ prefix = possible_prefix\n+ token_index = len(removed_tokens) - 1\n+ while token_index >= 0:\n+ list_token = cast(ListStartMarkdownToken, removed_tokens[token_index])\n+ assert list_token.leading_spaces is None\n+ assert removed_token_indices[token_index] == 0\n+ token_index -= 1\n+ del removed_tokens[0]\n+ del removed_token_indices[0]\n+\n+ list_token = cast(ListStartMarkdownToken, container_stack[-1])\n+ current_indent_level = list_token.indent_level if container_stack else 0\n+ prefix = \" \" * current_indent_level\n+ else:\n+ if removed_tokens[0].is_block_quote_start:\n+ removed_block_quote_token = cast(\n+ BlockQuoteMarkdownToken, removed_tokens[0]\n+ )\n+ assert removed_block_quote_token.bleading_spaces is not None\n+ split_bleading_spaces = removed_block_quote_token.bleading_spaces.split(\n+ \"\\n\"\n+ )\n+ assert removed_token_indices[0] < len(split_bleading_spaces)\n+ prefix = \"\" if possible_prefix is None else possible_prefix\n+ prefix = f\"{split_bleading_spaces[removed_token_indices[0]]}{prefix}\"\n+ del removed_tokens[0]\n+ del removed_token_indices[0]\n+ return prefix\n+\n @staticmethod\n def __abcd_final_list(\n- removed_tokens: List[MarkdownToken], removed_token_indices: List[int]\n+ removed_tokens: List[MarkdownToken],\n+ removed_token_indices: List[int],\n+ container_stack: List[MarkdownToken],\n ) -> Optional[str]:\n removed_list_token = cast(ListStartMarkdownToken, removed_tokens[0])\n assert removed_list_token.leading_spaces is not None\n@@ -437,26 +483,17 @@ class TransformContainers:\n # prefix is None for most cases\n possible_prefix = None\n if (\n- removed_token_indices[0] < len(split_leading_spaces)\n- and split_leading_spaces[removed_token_indices[0]]\n+ removed_token_indices[0]\n+ < len(split_leading_spaces)\n+ # and split_leading_spaces[removed_token_indices[0]]\n ):\n possible_prefix = split_leading_spaces[removed_token_indices[0]]\n del removed_tokens[0]\n del removed_token_indices[0]\n \n- prefix = None\n- if removed_tokens[0].is_block_quote_start:\n- removed_block_quote_token = cast(BlockQuoteMarkdownToken, removed_tokens[0])\n- assert removed_block_quote_token.bleading_spaces is not None\n- split_bleading_spaces = removed_block_quote_token.bleading_spaces.split(\n- \"\\n\"\n- )\n- assert removed_token_indices[0] < len(split_bleading_spaces)\n- prefix = \"\" if possible_prefix is None else possible_prefix\n- prefix = f\"{split_bleading_spaces[removed_token_indices[0]]}{prefix}\"\n- del removed_tokens[0]\n- del removed_token_indices[0]\n- return prefix\n+ return TransformContainers.__abcd_final_list_second_half(\n+ removed_tokens, removed_token_indices, container_stack, possible_prefix\n+ )\n \n @staticmethod\n def __abcd_final(\n@@ -506,7 +543,7 @@ class TransformContainers:\n del removed_token_indices[0]\n else:\n prefix = TransformContainers.__abcd_final_list(\n- removed_tokens, removed_token_indices\n+ removed_tokens, removed_token_indices, container_stack\n )\n return prefix\n \n", "test_patch": "diff --git a/publish/test-results.json b/publish/test-results.json\nindex 7e2b78aa..0fe7cc94 100644\n--- a/publish/test-results.json\n+++ b/publish/test-results.json\n@@ -1367,7 +1367,7 @@\n \"totalTests\": 653,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 62,\n+ \"skippedTests\": 61,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\n@@ -1620,7 +1620,7 @@\n },\n {\n \"name\": \"test.test_markdown_extra\",\n- \"totalTests\": 206,\n+ \"totalTests\": 210,\n \"failedTests\": 0,\n \"errorTests\": 0,\n \"skippedTests\": 3,\ndiff --git a/test/rules/test_md031.py b/test/rules/test_md031.py\nindex 435a4958..d1538cae 100644\n--- a/test/rules/test_md031.py\n+++ b/test/rules/test_md031.py\n@@ -30,6 +30,7 @@ The value for property 'plugins.md031.list_items' must be of type 'bool'.\"\"\",\n ),\n ]\n \n+skip_fix_bad_markdown = True\n skip_fix_asserts = True\n \n scanTests = [\n@@ -810,7 +811,7 @@ A code block\n This is a blank line and some text.\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n scan_expected_return_code=1,\n scan_expected_output=\"\"\"{temp_source_path}:3:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n {temp_source_path}:5:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n@@ -2188,7 +2189,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > > block 3\n > > > block 3\n > > > block 3\n@@ -2469,7 +2470,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + block 3\n > > block 3\n > > + block 3\n@@ -2652,7 +2653,7 @@ A code block\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > > fourth block 1\n > > > > fourth block 2\n@@ -2910,7 +2911,7 @@ A code block\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > + inner list 1\n > > > inner list 2\n@@ -2939,7 +2940,7 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > + inner list 1\n > > > inner list 2\n@@ -3130,7 +3131,7 @@ A code block\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n use_debug=True,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n@@ -3270,7 +3271,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3300,7 +3301,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3419,7 +3420,7 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -3537,7 +3538,7 @@ ______\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -4245,7 +4246,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > block 1\n > > > block 2\n@@ -4350,7 +4351,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4377,7 +4378,7 @@ A code block\n {temp_source_path}:6:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4480,7 +4481,7 @@ A code block\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4822,7 +4823,7 @@ A code block\n {temp_source_path}:8:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4853,7 +4854,7 @@ A code block\n {temp_source_path}:8:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4944,7 +4945,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5080,7 +5081,7 @@ A code block\n {temp_source_path}:7:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5109,7 +5110,7 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5200,7 +5201,7 @@ A code block\n {temp_source_path}:7:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5229,7 +5230,7 @@ A code block\n {temp_source_path}:7:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5317,7 +5318,7 @@ A code block\n {temp_source_path}:8:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5348,7 +5349,7 @@ A code block\n {temp_source_path}:8:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5647,7 +5648,7 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + list 1\n > > block 2\n > > block 3\n@@ -6312,7 +6313,7 @@ another list\n \"\"\",\n disable_rules=\"md032,md027,md007,md023\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6643,7 +6644,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6947,7 +6948,7 @@ another list\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -6976,7 +6977,7 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7064,7 +7065,7 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7095,7 +7096,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7347,7 +7348,7 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > + list 1\n > list 2\n@@ -7657,7 +7658,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -7688,7 +7689,7 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -8293,7 +8294,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > > block 1\n > > block 2\n@@ -8420,7 +8421,7 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8546,7 +8547,7 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8579,7 +8580,7 @@ another list\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8776,7 +8777,7 @@ another list\n another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050c2 test_extra_050c3\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\",\n source_file_contents=\"\"\"+ + + -----\n > block 1\n@@ -8866,7 +8867,7 @@ another list\n + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050c0 test_extra_050c1\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\",\n source_file_contents=\"\"\"+ + + -----\n > block 1\n@@ -8883,7 +8884,6 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n > block 1\n > block 2\ndiff --git a/test/test_markdown_extra.py b/test/test_markdown_extra.py\nindex 272eec4c..191c52c5 100644\n--- a/test/test_markdown_extra.py\n+++ b/test/test_markdown_extra.py\n@@ -9243,6 +9243,279 @@ list 2\n act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n \n \n+@pytest.mark.gfm\n+def test_extra_050c0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+ -----\n+ ```block\n+ A code block\n+ ```\n+ -----\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:: \\n \\n \\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[tbreak(4,3):-::-----]\",\n+ \"[fcode-block(5,3):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(8,3):-::-----]\",\n+ \"[para(9,3):]\",\n+ \"[text(9,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(10,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+another list
  • \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+ -----\n+\n+ ```block\n+ A code block\n+ ```\n+\n+ -----\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2::\\n \\n \\n \\n\\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[tbreak(4,3):-::-----]\",\n+ \"[BLANK(5,1):]\",\n+ \"[fcode-block(6,3):`:3:block:::::]\",\n+ \"[text(7,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(9,1):]\",\n+ \"[tbreak(10,3):-::-----]\",\n+ \"[para(11,3):]\",\n+ \"[text(11,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(12,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+

    another list

    \n+
  • \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c2():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+```block\n+A code block\n+```\n+-----\n+another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,1):`:3:block:::::]\",\n+ \"[text(5,1):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,1):-::-----]\",\n+ \"[para(8,1):]\",\n+ \"[text(8,1):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(9,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
  • \n+
\n+
A code block\n+
\n+
\n+

another list

\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c3():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+\n+```block\n+A code block\n+```\n+\n+-----\n+another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > \\n]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(4,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,1):`:3:block:::::]\",\n+ \"[text(6,1):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,1):]\",\n+ \"[tbreak(9,1):-::-----]\",\n+ \"[para(10,1):]\",\n+ \"[text(10,1):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(11,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
  • \n+
\n+
A code block\n+
\n+
\n+

another list

\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n @pytest.mark.gfm\n def test_extra_999():\n \"\"\"\n@@ -9270,9 +9543,9 @@ def test_extra_999():\n \n \n # Fix\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n \n # Bad fix\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n", "FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics]", "test/test_markdown_extra.py::test_extra_050c0", "test/test_markdown_extra.py::test_extra_050c1"]}, {"instance_id": "jackdewinter__pymarkdown-1251", "base_commit": "50a1e9487d32589015ec920edc987d5d3ba911f8", "gold_patch": "diff --git a/newdocs/src/changelog.md b/newdocs/src/changelog.md\nindex 9acc115f..a2a05616 100644\n--- a/newdocs/src/changelog.md\n+++ b/newdocs/src/changelog.md\n@@ -27,6 +27,9 @@\n - In 3+ drop cases with only lists and no block quotes, indent is\n not calculated properly on rehydrate. This in turn causes the\n fixed text to be wrong.\n+- [Issue 1250](https://github.com/jackdewinter/pymarkdown/issues/1250)\n+ - Batch of fixes for cases when Md031 is trying to properly space\n+ a fenced code block after dropping 2 containers.\n \n \n ### Changed\ndiff --git a/publish/coverage.json b/publish/coverage.json\nindex 11801c21..ef9a15f3 100644\n--- a/publish/coverage.json\n+++ b/publish/coverage.json\n@@ -2,12 +2,12 @@\n \"projectName\": \"pymarkdown\",\n \"reportSource\": \"pytest\",\n \"branchLevel\": {\n- \"totalMeasured\": 5403,\n- \"totalCovered\": 5401\n+ \"totalMeasured\": 5431,\n+ \"totalCovered\": 5428\n },\n \"lineLevel\": {\n- \"totalMeasured\": 21123,\n- \"totalCovered\": 21122\n+ \"totalMeasured\": 21194,\n+ \"totalCovered\": 21193\n }\n }\n \ndiff --git a/pymarkdown/plugins/rule_md_031.py b/pymarkdown/plugins/rule_md_031.py\nindex c6ebf6fc..715cf2ef 100644\n--- a/pymarkdown/plugins/rule_md_031.py\n+++ b/pymarkdown/plugins/rule_md_031.py\n@@ -35,6 +35,7 @@ class PendingContainerAdjustment:\n insert_index: int\n leading_space_to_insert: str\n do_insert: bool = True\n+ do_special: bool = False\n \n \n # pylint: disable=too-many-instance-attributes\n@@ -53,6 +54,9 @@ class RuleMd031(RulePlugin):\n self.__container_adjustments: List[List[PendingContainerAdjustment]] = []\n self.__fix_count = 0\n self.__removed_container_stack_token: Optional[MarkdownToken] = None\n+ self.__x1: List[MarkdownToken] = []\n+ self.__x2: List[List[PendingContainerAdjustment]] = []\n+ self.__x3: List[int] = []\n self.__removed_container_adjustments: Optional[\n List[PendingContainerAdjustment]\n ] = None\n@@ -103,6 +107,9 @@ class RuleMd031(RulePlugin):\n self.__leading_space_index_tracker.clear()\n self.__removed_container_adjustments = None\n self.__removed_container_stack_token = None\n+ self.__x1.clear()\n+ self.__x2.clear()\n+ self.__x3.clear()\n \n def __fix_spacing_special_case(\n self, context: PluginScanContext, token: MarkdownToken\n@@ -123,6 +130,7 @@ class RuleMd031(RulePlugin):\n self.register_replace_tokens_request(\n context, self.__last_token, token, replacement_tokens\n )\n+\n end_token = cast(EndMarkdownToken, self.__last_token)\n block_quote_start_token = cast(\n BlockQuoteMarkdownToken, end_token.start_markdown_token\n@@ -137,7 +145,9 @@ class RuleMd031(RulePlugin):\n )\n )\n \n- def __fix_spacing_block_quote(self, token: MarkdownToken) -> None:\n+ def __fix_spacing_block_quote(\n+ self, token: MarkdownToken, upgrade_kludge: bool\n+ ) -> None:\n leading_space_insert_index = self.__leading_space_index_tracker.get_tokens_block_quote_bleading_space_index(\n token\n )\n@@ -153,12 +163,23 @@ class RuleMd031(RulePlugin):\n )\n assert block_quote_token.bleading_spaces is not None\n split_leading_space = block_quote_token.bleading_spaces.split(\"\\n\")\n- former_item_leading_space = split_leading_space[\n- leading_space_insert_index\n- ].rstrip()\n+\n+ former_item_leading_space = split_leading_space[leading_space_insert_index]\n+ if (\n+ leading_space_insert_index == len(split_leading_space) - 1\n+ and not former_item_leading_space\n+ and leading_space_insert_index\n+ ):\n+ former_item_leading_space = split_leading_space[\n+ leading_space_insert_index - 1\n+ ]\n+ if not upgrade_kludge:\n+ former_item_leading_space = former_item_leading_space.rstrip()\n self.__container_adjustments[container_index].append(\n PendingContainerAdjustment(\n- leading_space_insert_index, former_item_leading_space\n+ leading_space_insert_index,\n+ former_item_leading_space,\n+ do_special=upgrade_kludge,\n )\n )\n \n@@ -464,13 +485,13 @@ class RuleMd031(RulePlugin):\n )\n \n def __fix_spacing_one_container(\n- self, context: PluginScanContext, token: MarkdownToken\n+ self, context: PluginScanContext, token: MarkdownToken, upgrade_kludge: bool\n ) -> bool:\n did_special_list_fix = False\n if self.__leading_space_index_tracker.get_container_stack_item(\n -1\n ).is_block_quote_start:\n- self.__fix_spacing_block_quote(token)\n+ self.__fix_spacing_block_quote(token, upgrade_kludge)\n else:\n did_special_list_fix = self.__fix_spacing_list(context, token)\n return did_special_list_fix\n@@ -497,15 +518,179 @@ class RuleMd031(RulePlugin):\n \"\\n\".join(split_spaces),\n )\n \n+ def __fix_spacing_with_fenced_and_list_end(\n+ self, context: PluginScanContext, token: MarkdownToken, new_token: MarkdownToken\n+ ) -> None:\n+ end_container_index = len(self.__last_end_container_tokens) - 1\n+ while (\n+ end_container_index >= 0\n+ and self.__last_end_container_tokens[end_container_index].is_list_end\n+ ):\n+ end_container_index -= 1\n+ first_token = self.__last_end_container_tokens[end_container_index + 1]\n+ replacement_tokens: List[MarkdownToken] = [\n+ BlankLineMarkdownToken(\n+ extracted_whitespace=\"\",\n+ position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n+ column_delta=1,\n+ )\n+ ]\n+ replacement_tokens.extend(\n+ self.__last_end_container_tokens[end_container_index + 1 :]\n+ )\n+ replacement_tokens.append(new_token)\n+ self.register_replace_tokens_request(\n+ context, first_token, token, replacement_tokens\n+ )\n+\n+ def __fix_spacing_with_special_list_fix(\n+ self, context: PluginScanContext, token: MarkdownToken, new_token: MarkdownToken\n+ ) -> None:\n+ assert self.__last_token and self.__last_token.is_block_quote_end\n+ new_end_token = cast(EndMarkdownToken, copy.copy(self.__last_token))\n+ new_end_token.set_extra_end_data(None)\n+ replacement_tokens = [\n+ BlankLineMarkdownToken(\n+ extracted_whitespace=\"\",\n+ position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n+ column_delta=1,\n+ ),\n+ new_end_token,\n+ new_token,\n+ ]\n+ self.register_replace_tokens_request(\n+ context, self.__last_token, token, replacement_tokens\n+ )\n+\n+ def __fix_spacing_with_else(\n+ self, context: PluginScanContext, token: MarkdownToken, new_token: MarkdownToken\n+ ) -> None:\n+ replacement_tokens = [\n+ BlankLineMarkdownToken(\n+ extracted_whitespace=\"\",\n+ position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n+ column_delta=1,\n+ ),\n+ new_token,\n+ ]\n+ self.register_replace_tokens_request(context, token, token, replacement_tokens)\n+\n+ def __calc_kludge_one(self, at_least_one_container: bool) -> bool:\n+ is_kludge_one = False\n+ if at_least_one_container:\n+ last_stack_token = (\n+ self.__leading_space_index_tracker.get_container_stack_item(-1)\n+ )\n+ if last_stack_token.is_list_start and self.__x1[-1].is_block_quote_start:\n+ is_kludge_one = not any(i.is_block_quote_start for i in self.__x1[:-1])\n+ return is_kludge_one\n+\n+ def __calc_2(self, context: PluginScanContext, did_process_removals: bool) -> bool:\n+\n+ # This will most likely need rewriting for deeper nestings.\n+ if (\n+ not did_process_removals\n+ and len(self.__x1) == 2\n+ and self.__x1[0].is_block_quote_start\n+ and self.__x1[1].is_list_start\n+ ):\n+ did_process_removals = self.__apply_tailing_block_quote_fix(0, context)\n+ return did_process_removals\n+\n+ def __calc_3(\n+ self,\n+ context: PluginScanContext,\n+ did_process_removals: bool,\n+ at_least_one_container: bool,\n+ upgrade_kludge: bool,\n+ ) -> Tuple[bool, bool]:\n+ # This will most likely need rewriting for deeper nestings.\n+ if not did_process_removals and at_least_one_container:\n+ last_stack_token_index = (\n+ self.__leading_space_index_tracker.get_container_stack_size() - 1\n+ )\n+ found_block_quote_token = None\n+ assert last_stack_token_index >= 0\n+ assert (\n+ token_at_index := self.__leading_space_index_tracker.get_container_stack_item(\n+ last_stack_token_index\n+ )\n+ ).is_block_quote_start\n+ found_block_quote_token = token_at_index\n+ # while last_stack_token_index >= 0:\n+ # if (\n+ # token_at_index := self.__leading_space_index_tracker.get_container_stack_item(\n+ # last_stack_token_index\n+ # )\n+ # ).is_block_quote_start:\n+ # found_block_quote_token = token_at_index\n+ # break\n+ # last_stack_token_index -= 1\n+ if (\n+ found_block_quote_token\n+ and len(self.__x1) == 2\n+ and self.__x1[0].is_list_start\n+ and self.__x1[1].is_block_quote_start\n+ ):\n+ did_process_removals = upgrade_kludge = (\n+ self.__apply_tailing_block_quote_fix(1, context)\n+ )\n+ return did_process_removals, upgrade_kludge\n+\n+ def __apply_tailing_block_quote_fix(\n+ self, modify_index: int, context: PluginScanContext\n+ ) -> bool:\n+\n+ assert self.__x1[modify_index].is_block_quote_start\n+ block_quote_token = cast(BlockQuoteMarkdownToken, self.__x1[modify_index])\n+ assert block_quote_token.bleading_spaces is not None\n+ split_spaces = block_quote_token.bleading_spaces.split(\"\\n\")\n+ assert self.__x3[modify_index] == len(split_spaces) - 1\n+ split_spaces[-1] = split_spaces[-1].rstrip()\n+ self.register_fix_token_request(\n+ context,\n+ self.__x1[modify_index],\n+ \"next_token\",\n+ \"bleading_spaces\",\n+ \"\\n\".join(split_spaces),\n+ )\n+ return True\n+\n def __fix_spacing(\n self, context: PluginScanContext, token: MarkdownToken, special_case: bool\n ) -> None:\n- did_special_list_fix = False\n if special_case:\n self.__fix_spacing_special_case(context, token)\n return\n- if self.__leading_space_index_tracker.in_at_least_one_container():\n- did_special_list_fix = self.__fix_spacing_one_container(context, token)\n+ at_least_one_container = (\n+ self.__leading_space_index_tracker.in_at_least_one_container()\n+ )\n+ upgrade_kludge = False\n+ if len(self.__x1) > 1:\n+ # These circumstances are already handled by the zero and single level removals.\n+ all_removals_are_block_quotes = all(\n+ f.is_block_quote_start for f in self.__x1\n+ )\n+ all_removals_are_lists = all(f.is_list_start for f in self.__x1)\n+ was_kludge_one = self.__calc_kludge_one(at_least_one_container)\n+ did_process_removals = (\n+ all_removals_are_block_quotes\n+ or all_removals_are_lists\n+ or was_kludge_one\n+ or not at_least_one_container\n+ )\n+\n+ did_process_removals = self.__calc_2(context, did_process_removals)\n+ did_process_removals, upgrade_kludge = self.__calc_3(\n+ context, did_process_removals, at_least_one_container, upgrade_kludge\n+ )\n+ # assert did_process_removals\n+\n+ did_special_list_fix = False\n+ if at_least_one_container:\n+ did_special_list_fix = self.__fix_spacing_one_container(\n+ context, token, upgrade_kludge\n+ )\n elif self.__removed_container_stack_token:\n self.__fix_spacing_removed_container(context, token)\n \n@@ -514,55 +699,11 @@ class RuleMd031(RulePlugin):\n new_token.adjust_line_number(context, self.__fix_count)\n assert self.__last_token is not None\n if token.is_fenced_code_block and self.__last_token.is_list_end:\n- end_container_index = len(self.__last_end_container_tokens) - 1\n- while (\n- end_container_index >= 0\n- and self.__last_end_container_tokens[end_container_index].is_list_end\n- ):\n- end_container_index -= 1\n- first_token = self.__last_end_container_tokens[end_container_index + 1]\n- replacement_tokens: List[MarkdownToken] = [\n- BlankLineMarkdownToken(\n- extracted_whitespace=\"\",\n- position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n- column_delta=1,\n- )\n- ]\n- replacement_tokens.extend(\n- self.__last_end_container_tokens[end_container_index + 1 :]\n- )\n- replacement_tokens.append(new_token)\n- self.register_replace_tokens_request(\n- context, first_token, token, replacement_tokens\n- )\n+ self.__fix_spacing_with_fenced_and_list_end(context, token, new_token)\n elif did_special_list_fix:\n- assert self.__last_token and self.__last_token.is_block_quote_end\n- new_end_token = cast(EndMarkdownToken, copy.copy(self.__last_token))\n- new_end_token.set_extra_end_data(None)\n- replacement_tokens = [\n- BlankLineMarkdownToken(\n- extracted_whitespace=\"\",\n- position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n- column_delta=1,\n- ),\n- new_end_token,\n- new_token,\n- ]\n- self.register_replace_tokens_request(\n- context, self.__last_token, token, replacement_tokens\n- )\n+ self.__fix_spacing_with_special_list_fix(context, token, new_token)\n else:\n- replacement_tokens = [\n- BlankLineMarkdownToken(\n- extracted_whitespace=\"\",\n- position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n- column_delta=1,\n- ),\n- new_token,\n- ]\n- self.register_replace_tokens_request(\n- context, token, token, replacement_tokens\n- )\n+ self.__fix_spacing_with_else(context, token, new_token)\n \n def __handle_fenced_code_block(\n self, context: PluginScanContext, token: MarkdownToken, special_case: bool\n@@ -677,7 +818,16 @@ class RuleMd031(RulePlugin):\n ), \"Pending containers means this should at least have a newline in it.\"\n split_spaces = list_token.leading_spaces.split(\"\\n\")\n \n+ for i, next_container_adjustment in enumerate(next_container_adjustment_list):\n+ if next_container_adjustment.do_special:\n+ split_spaces.insert(\n+ 0, next_container_adjustment.leading_space_to_insert\n+ )\n+ del next_container_adjustment_list[i]\n+ break\n+\n for next_container_adjustment in next_container_adjustment_list[::-1]:\n+ assert not next_container_adjustment.do_special\n if next_container_adjustment.do_insert:\n split_spaces.insert(\n next_container_adjustment.insert_index,\n@@ -706,10 +856,22 @@ class RuleMd031(RulePlugin):\n context, next_container_adjustment_list\n )\n \n+ if self.__leading_space_index_tracker.get_container_stack_item(\n+ -1\n+ ).is_block_quote_start:\n+ leading_space_insert_index = self.__leading_space_index_tracker.get_tokens_block_quote_bleading_space_index(\n+ token\n+ )\n+ else:\n+ leading_space_insert_index = -10\n+ self.__x3.append(leading_space_insert_index)\n+\n self.__removed_container_stack_token = (\n self.__leading_space_index_tracker.process_container_end(token)\n )\n+ self.__x1.append(self.__removed_container_stack_token)\n self.__removed_container_adjustments = self.__container_adjustments[-1]\n+ self.__x2.append(self.__removed_container_adjustments)\n del self.__container_adjustments[-1]\n \n def __calculate_special_case(\n@@ -773,7 +935,10 @@ class RuleMd031(RulePlugin):\n self.__second_last_token = self.__last_token\n self.__last_token = token\n self.__removed_container_stack_token = None\n+ self.__x1.clear()\n self.__removed_container_adjustments = None\n+ self.__x2.clear()\n+ self.__x3.clear()\n \n \n # pylint: enable=too-many-instance-attributes\n", "test_patch": "diff --git a/publish/test-results.json b/publish/test-results.json\nindex 0fe7cc94..979e1298 100644\n--- a/publish/test-results.json\n+++ b/publish/test-results.json\n@@ -1367,7 +1367,7 @@\n \"totalTests\": 653,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 61,\n+ \"skippedTests\": 59,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\n@@ -1620,7 +1620,7 @@\n },\n {\n \"name\": \"test.test_markdown_extra\",\n- \"totalTests\": 210,\n+ \"totalTests\": 220,\n \"failedTests\": 0,\n \"errorTests\": 0,\n \"skippedTests\": 3,\ndiff --git a/test/rules/test_md031.py b/test/rules/test_md031.py\nindex d1538cae..79045e92 100644\n--- a/test/rules/test_md031.py\n+++ b/test/rules/test_md031.py\n@@ -2174,7 +2174,7 @@ A code block\n > > ```\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050g0 test_extra_050g1\n \"bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\",\n source_file_contents=\"\"\"> > > block 3\n > > > block 3\n@@ -2189,6 +2189,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n+ use_fix_debug=True,\n mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > > block 3\n > > > block 3\n@@ -2455,7 +2456,7 @@ A code block\n > > --------\n \"\"\",\n ),\n- pluginRuleTest( # test_extra_049l0\n+ pluginRuleTest( # test_extra_049l0 test_extra_050h0 test_extra_050h1\n \"bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop\",\n source_file_contents=\"\"\"> > + block 3\n > > block 3\n@@ -2470,7 +2471,8 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=skip_fix_bad_markdown,\n+ # mark_fix_as_skipped=skip_fix_bad_markdown,\n+ # use_fix_debug=True,\n fix_expected_file_contents=\"\"\"> > + block 3\n > > block 3\n > > + block 3\n@@ -4465,7 +4467,7 @@ A code block\n > ----\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050e0 test_extra_050e1\n \"bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop\",\n source_file_contents=\"\"\"1. > + ----\n > > block 1\n@@ -4480,8 +4482,6 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- use_debug=True,\n- mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4689,7 +4689,7 @@ A code block\n > ----\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050f0 test_extra_050f1\n \"bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_triple_drop\",\n source_file_contents=\"\"\"1. > + ----\n > + list 1\n@@ -6932,7 +6932,7 @@ another list\n > + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050d0 test_extra_050d1\n \"bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\",\n source_file_contents=\"\"\"> + + -----\n > > block 1\ndiff --git a/test/test_markdown_extra.py b/test/test_markdown_extra.py\nindex 191c52c5..5095eb63 100644\n--- a/test/test_markdown_extra.py\n+++ b/test/test_markdown_extra.py\n@@ -9516,6 +9516,608 @@ block 2

\n act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n \n \n+@pytest.mark.gfm\n+def test_extra_050d0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> + + -----\n+> > block 1\n+> > block 2\n+> ```block\n+> A code block\n+> ```\n+> -----\n+> + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n> \\n> \\n> ]\",\n+ \"[ulist(1,3):+::4:: \\n \\n \\n]\",\n+ \"[ulist(1,5):+::6: :\\n\\n \u00fe]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7)::> > \\n> > \\n> ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::False]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,5):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,5):-::-----]\",\n+ \"[li(8,3):4::]\",\n+ \"[para(8,5):]\",\n+ \"[text(8,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(9,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
\n+
    \n+
  • \n+
      \n+
    • \n+
      \n+
      \n+

      block 1\n+block 2

      \n+
      \n+
    • \n+
    \n+
    A code block\n+
    \n+
    \n+
  • \n+
  • another list
  • \n+
\n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050d1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> + + -----\n+> > block 1\n+> > block 2\n+>\n+> ```block\n+> A code block\n+> ```\n+>\n+> -----\n+> + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n> \\n> \\n>\\n> \\n> ]\",\n+ \"[ulist(1,3):+::4:: \\n \\n\\n \\n]\",\n+ \"[ulist(1,5):+::6: :\\n\\n\\n ]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7)::> > \\n> > \\n>]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,2):]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,5):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,2):]\",\n+ \"[tbreak(9,5):-::-----]\",\n+ \"[li(10,3):4::]\",\n+ \"[para(10,5):]\",\n+ \"[text(10,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(11,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
\n+
    \n+
  • \n+
      \n+
    • \n+
      \n+
      \n+

      block 1\n+block 2

      \n+
      \n+
    • \n+
    \n+
    A code block\n+
    \n+
    \n+
  • \n+
  • \n+

    another list

    \n+
  • \n+
\n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050e0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > > block 1\n+ > > block 2\n+ > ```block\n+ > A code block\n+ > ```\n+ > ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3::\\n\\n\\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > \\n > \\n]\",\n+ \"[ulist(1,6):+::7::\\n\\n]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[block-quote(2,8)::> \\n > > \\n > ]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::False]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,6):`:3:block:::::]\",\n+ \"[text(5,6):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,6):-::----]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(8,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  1. \n+
    \n+
      \n+
    • \n+
      \n+
      \n+

      block 1\n+block 2

      \n+
      \n+
    • \n+
    \n+
    A code block\n+
    \n+
    \n+
    \n+
  2. \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=True)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050e1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > > block 1\n+ > > block 2\n+ >\n+ > ```block\n+ > A code block\n+ > ```\n+ >\n+ > ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3::\\n\\n\\n\\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > \\n > \\n >\\n > \\n]\",\n+ \"[ulist(1,6):+::7::\\n\\n\\n]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[block-quote(2,8)::> \\n > > \\n >]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,5):]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,6):`:3:block:::::]\",\n+ \"[text(6,6):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,5):]\",\n+ \"[tbreak(9,6):-::----]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(10,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  1. \n+
    \n+
      \n+
    • \n+
      \n+
      \n+

      block 1\n+block 2

      \n+
      \n+
    • \n+
    \n+
    A code block\n+
    \n+
    \n+
    \n+
  2. \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050f0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_triple_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > + list 1\n+ > list 2\n+ > + list 3\n+ ```block\n+ A code block\n+ ```\n+ ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3:: \\n \\n \\n \\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > ]\",\n+ \"[ulist(1,6):+::7:]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[ulist(2,8):+::9: : ]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,8):9: :]\",\n+ \"[para(4,10):]\",\n+ \"[text(4,10):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(5,4):`:3:block:::::]\",\n+ \"[text(6,4):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(8,4):-::----]\",\n+ \"[BLANK(9,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  1. \n+
    \n+
      \n+
    • \n+
      \n+
        \n+
      • list 1\n+list 2
      • \n+
      • list 3
      • \n+
      \n+
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+
  2. \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050f1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_triple_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > + list 1\n+ > list 2\n+ > + list 3\n+\n+ ```block\n+ A code block\n+ ```\n+\n+ ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3:: \\n \\n \\n\\n \\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > ]\",\n+ \"[ulist(1,6):+::7:]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[ulist(2,8):+::9: : \\n]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,8):9: :]\",\n+ \"[para(4,10):]\",\n+ \"[text(4,10):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(5,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(6,4):`:3:block:::::]\",\n+ \"[text(7,4):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(9,1):]\",\n+ \"[tbreak(10,4):-::----]\",\n+ \"[BLANK(11,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  1. \n+
    \n+
      \n+
    • \n+
      \n+
        \n+
      • list 1\n+list 2
      • \n+
      • list 3
      • \n+
      \n+
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+
  2. \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050g0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > > block 3\n+> > > block 3\n+> > > block 3\n+> ```block\n+> A code block\n+> ```\n+> text\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n]\",\n+ \"[block-quote(1,3)::]\",\n+ \"[block-quote(1,5)::> > > \\n> > > \\n> > > \\n> ]\",\n+ \"[para(1,7):\\n\\n]\",\n+ \"[text(1,7):block 3\\nblock 3\\nblock 3::\\n\\n]\",\n+ \"[end-para:::False]\",\n+ \"[end-block-quote::> :True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(4,3):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[para(7,3):]\",\n+ \"[text(7,3):text:]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(8,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
\n+
\n+
\n+

block 3\n+block 3\n+block 3

\n+
\n+
\n+
A code block\n+
\n+

text

\n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050g1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > > block 3\n+> > > block 3\n+> > > block 3\n+>\n+> ```block\n+> A code block\n+> ```\n+>\n+> text\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n>\\n> \\n]\",\n+ \"[block-quote(1,3)::]\",\n+ \"[block-quote(1,5)::> > > \\n> > > \\n> > > \\n>]\",\n+ \"[para(1,7):\\n\\n]\",\n+ \"[text(1,7):block 3\\nblock 3\\nblock 3::\\n\\n]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,2):]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(5,3):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,2):]\",\n+ \"[para(9,3):]\",\n+ \"[text(9,3):text:]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(10,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
\n+
\n+
\n+

block 3\n+block 3\n+block 3

\n+
\n+
\n+
A code block\n+
\n+

text

\n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050h0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > + block 3\n+> > block 3\n+> > + block 3\n+> ```block\n+> A code block\n+> ```\n+> --------\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n]\",\n+ \"[block-quote(1,3)::> > \\n> > \\n> > \\n> ]\",\n+ \"[ulist(1,5):+::6:: \\n]\",\n+ \"[para(1,7):\\n]\",\n+ \"[text(1,7):block 3\\nblock 3::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(3,5):6::]\",\n+ \"[para(3,7):]\",\n+ \"[text(3,7):block 3:]\",\n+ \"[end-para:::False]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(4,3):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,3):-::--------]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(8,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
\n+
\n+
    \n+
  • block 3\n+block 3
  • \n+
  • block 3
  • \n+
\n+
\n+
A code block\n+
\n+
\n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050h1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > + block 3\n+> > block 3\n+> > + block 3\n+>\n+> ```block\n+> A code block\n+> ```\n+>\n+> --------\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n>\\n> \\n]\",\n+ \"[block-quote(1,3)::> > \\n> > \\n> > \\n>]\",\n+ \"[ulist(1,5):+::6:: \\n]\",\n+ \"[para(1,7):\\n]\",\n+ \"[text(1,7):block 3\\nblock 3::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(3,5):6::]\",\n+ \"[para(3,7):]\",\n+ \"[text(3,7):block 3:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,2):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(5,3):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,2):]\",\n+ \"[tbreak(9,3):-::--------]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(10,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
\n+
\n+
    \n+
  • block 3\n+block 3
  • \n+
  • block 3
  • \n+
\n+
\n+
A code block\n+
\n+
\n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=True)\n+\n+\n @pytest.mark.gfm\n def test_extra_999():\n \"\"\"\n@@ -9545,9 +10147,12 @@ def test_extra_999():\n # Fix\n # bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n \n+# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n+# test_extra_050d0 test_extra_050d1\n+# - need to work with split lines\n+\n # Bad fix\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n-# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_triple_drop\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_triple_drop_with_thematics\n", "FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop]"]}], "all_FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics]", "test/test_markdown_extra.py::test_extra_050c0", "test/test_markdown_extra.py::test_extra_050c1", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "MaineKuehn__usim-81_x2", "level": 2, "source": "swerebench", "repo": "MaineKuehn/usim", "image": "swerebench/sweb.eval.x86_64.mainekuehn_1776_usim-81:latest", "base_commit": "c6f3502cfed08cfabe3c3f3f086c8ddab8323886", "num_bugs": 2, "bugs": [{"instance_id": "MaineKuehn__usim-81", "base_commit": "c6f3502cfed08cfabe3c3f3f086c8ddab8323886", "gold_patch": "diff --git a/docs/source/api/usim_resources.rst b/docs/source/api/usim_resources.rst\nindex 9d0366a..d2f0a71 100644\n--- a/docs/source/api/usim_resources.rst\n+++ b/docs/source/api/usim_resources.rst\n@@ -4,6 +4,10 @@ Resource Modelling\n Resource Containers\n -------------------\n \n+Resources support the comparison operations, such as ``==``, ``>=``, or ``<``.\n+This derives a :py:class:`~usim.Comparison` that triggers when the Resources'\n+levels reaches the desired value.\n+\n .. autoclass:: usim.Resources\n :members:\n \ndiff --git a/usim/_basics/resource.py b/usim/_basics/resource.py\nindex 429d7a1..7ec42e6 100644\n--- a/usim/_basics/resource.py\n+++ b/usim/_basics/resource.py\n@@ -1,4 +1,4 @@\n-from typing import TypeVar, Generic, Optional, Type\n+from typing import TypeVar, Generic, Optional, Type, Union, Dict\n \n from .._core.loop import __LOOP_STATE__\n from ._resource_level import __specialise__, ResourceLevels\n@@ -72,6 +72,36 @@ class BaseResources(Generic[T]):\n )\n return f'{self.__class__.__name__}({content})'\n \n+ def __eq__(self, other: Union[ResourceLevels[T], Dict[str, T]]):\n+ if isinstance(other, dict):\n+ other = self.resource_type(**other)\n+ return self._available == other\n+\n+ def __ne__(self, other: Union[ResourceLevels[T], Dict[str, T]]):\n+ if isinstance(other, dict):\n+ other = self.resource_type(**other)\n+ return self._available != other\n+\n+ def __gt__(self, other: Union[ResourceLevels[T], Dict[str, T]]):\n+ if isinstance(other, dict):\n+ other = self.resource_type(**other)\n+ return self._available > other\n+\n+ def __ge__(self, other: Union[ResourceLevels[T], Dict[str, T]]):\n+ if isinstance(other, dict):\n+ other = self.resource_type(**other)\n+ return self._available >= other\n+\n+ def __le__(self, other: Union[ResourceLevels[T], Dict[str, T]]):\n+ if isinstance(other, dict):\n+ other = self.resource_type(**other)\n+ return self._available <= other\n+\n+ def __lt__(self, other: Union[ResourceLevels[T], Dict[str, T]]):\n+ if isinstance(other, dict):\n+ other = self.resource_type(**other)\n+ return self._available < other\n+\n \n class BorrowedResources(BaseResources[T]):\n \"\"\"\n", "test_patch": "diff --git a/usim_pytest/test_types/test_resource.py b/usim_pytest/test_types/test_resource.py\nindex ba1aadd..6e08061 100644\n--- a/usim_pytest/test_types/test_resource.py\n+++ b/usim_pytest/test_types/test_resource.py\n@@ -187,6 +187,51 @@ class BaseResourceCase:\n async with resources.borrow(a=10, b=10):\n assert time == 10\n \n+ @via_usim\n+ async def test_compare(self):\n+ resources = self.resource_type(a=10, b=10)\n+\n+ async def borrow_shortly(resource: BaseResources, **amounts):\n+ async with resource.borrow(**amounts):\n+ pass\n+\n+ async with Scope() as scope:\n+ await (resources == {'a': 10, 'b': 10})\n+ scope.do(borrow_shortly(resources, a=5, b=5), after=10)\n+ await (resources == resources.resource_type(a=5, b=5))\n+ assert time.now == 10\n+ assert time.now == 10\n+ async with Scope() as scope:\n+ await (resources > {'a': 9, 'b': 9})\n+ scope.do(borrow_shortly(resources, a=5, b=5), after=10)\n+ await (resources > resources.resource_type(a=5, b=5))\n+ assert time.now == 10\n+ assert time.now == 20\n+ async with Scope() as scope:\n+ await (resources >= {'a': 10, 'b': 10})\n+ scope.do(borrow_shortly(resources, a=5, b=5), after=10)\n+ await (resources >= resources.resource_type(a=5, b=5))\n+ assert time.now == 20\n+ assert time.now == 30\n+ async with Scope() as scope:\n+ await (resources <= {'a': 10, 'b': 10})\n+ scope.do(borrow_shortly(resources, a=5, b=5), after=10)\n+ await (resources <= resources.resource_type(a=5, b=5))\n+ assert time.now == 40\n+ assert time.now == 40\n+ async with Scope() as scope:\n+ await (resources < {'a': 11, 'b': 11})\n+ scope.do(borrow_shortly(resources, a=5, b=5), after=10)\n+ await (resources < resources.resource_type(a=6, b=6))\n+ assert time.now == 50\n+ assert time.now == 50\n+ async with Scope() as scope:\n+ await (resources != {'a': 5, 'b': 5})\n+ scope.do(borrow_shortly(resources, a=5, b=5), after=10)\n+ await (resources != resources.resource_type(a=10, b=10))\n+ assert time.now == 60\n+ assert time.now == 60\n+\n \n class TestCapacity(BaseResourceCase):\n resource_type = Capacities\ndiff --git a/usim_pytest/utility.py b/usim_pytest/utility.py\nindex 9faff58..6f11d66 100644\n--- a/usim_pytest/utility.py\n+++ b/usim_pytest/utility.py\n@@ -74,7 +74,8 @@ def via_usim(test_case: Callable[..., Coroutine]):\n nonlocal test_completed\n await test_case(*args, **kwargs)\n test_completed = True\n- run(complete_test_case())\n+ result = run(complete_test_case())\n if not test_completed:\n raise UnfinishedTest(test_case)\n+ return result\n return run_test\n", "FAIL_TO_PASS": ["usim_pytest/test_types/test_resource.py::TestCapacity::test_compare", "usim_pytest/test_types/test_resource.py::TestResources::test_compare"]}, {"instance_id": "MaineKuehn__usim-85", "base_commit": "07263c93f55301530d98da915e7b9ccded8abd3e", "gold_patch": "diff --git a/docs/source/changes/85.early_task_cancellation.yaml b/docs/source/changes/85.early_task_cancellation.yaml\nnew file mode 100644\nindex 0000000..0a4219c\n--- /dev/null\n+++ b/docs/source/changes/85.early_task_cancellation.yaml\n@@ -0,0 +1,7 @@\n+category: fixed\n+summary: \"Cancelling a Task early no longer cancels its parent scope\"\n+description: |\n+ Cancelling a :py:class:`~usim.Task` was incorrectly flagged as a failure of the task.\n+ This caused the parent :py:class:`~usim.Scope` to abort as well.\n+pull requests:\n+- 85\ndiff --git a/docs/source/changes/85.scope_shutdown_suppression.yaml b/docs/source/changes/85.scope_shutdown_suppression.yaml\nnew file mode 100644\nindex 0000000..2bdff80\n--- /dev/null\n+++ b/docs/source/changes/85.scope_shutdown_suppression.yaml\n@@ -0,0 +1,11 @@\n+category: fixed\n+summary: \"Scopes no longer swallow exceptions during graceful shutdown\"\n+description: |\n+ When a :py:class:`~usim.Scope` received a signal during graceful shutdown,\n+ its fast shutdown path attempted to propagate the signal incorrectly.\n+ Such late signals as well as concurrent exceptions are now explicitly\n+ handled and propagated out of the scope as needed.\n+issues:\n+- 83\n+pull requests:\n+- 85\ndiff --git a/usim/_primitives/context.py b/usim/_primitives/context.py\nindex 4f2b65f..ae9a742 100644\n--- a/usim/_primitives/context.py\n+++ b/usim/_primitives/context.py\n@@ -1,7 +1,7 @@\n from typing import Coroutine, List, TypeVar, Any, Optional, Tuple\n \n from .._core.loop import __LOOP_STATE__, Interrupt as CoreInterrupt\n-from .notification import Notification, postpone\n+from .notification import Notification\n from .flag import Flag\n from .task import Task, TaskClosed, TaskCancelled, try_close\n from .concurrent_exception import Concurrent\n@@ -238,61 +238,32 @@ class Scope:\n return self\n \n async def __aexit__(self, exc_type, exc_val, exc_tb) -> bool:\n+ # there was no exception, we regularly exited the loop body\n+ # we wait for our children to finish or some interrupt to happen\n if exc_type is None:\n try:\n # inform everyone that we are shutting down\n # we may receive any shutdown signal here\n await self._body_done.set()\n+ await self._await_children()\n except BaseException as err:\n- exc_type, exc_val = type(err), err\n- else:\n- return await self._aexit_graceful()\n- self._body_done._value = True\n- self._body_done.__trigger__()\n- # there was an exception, we have to abandon the scope\n- return self._aexit_forceful(exc_type, exc_val)\n-\n- def _aexit_forceful(self, exc_type, exc_val) -> bool:\n- \"\"\"\n- Exit with exception\n-\n- This immediately closes all children without waiting for anything.\n- No further interrupts can occur during shutdown (this is a sync function).\n+ self._close_scope()\n+ if self._propagate_exceptions(type(err), err):\n+ raise\n+ return True\n+ # there was an exception, we have to abandon the scope fast\n+ # we do not want interrupts that conflict with our current exception\n+ else:\n+ self._body_done._value = True\n+ self._body_done.__trigger__()\n+ self._close_scope()\n+ return not self._propagate_exceptions(exc_type, exc_val)\n \n- If a fatal exception occurred in this scope or a child, the fatal\n- exception replaces all other exceptions in flight.\n- If the current exception is suppressed by the scope, any exceptions from\n- children are reraised as :py:exc:`~.Concurrent` errors.\n- \"\"\"\n- # we already handle an exception, suppress\n+ def _close_scope(self):\n+ \"\"\"Ultimately close the scope, its interrupts and all children\"\"\"\n self._disable_interrupts()\n- # reap all children now\n self._close_children()\n self._close_volatile()\n- return self._propagate_exceptions(exc_type, exc_val)\n-\n- async def _aexit_graceful(self) -> bool:\n- \"\"\"\n- Exit without exception\n-\n- This suspends the scope until all children have finished themselves.\n- If any children encountered an error, they are reraised as\n- :py:exc:`~.Concurrent` errors.\n-\n- If an error occurs while waiting for children to stop, a forceful\n- shutdown is performed instead.\n- \"\"\"\n- try:\n- await self._await_children()\n- # we must always postpone to receive signals, even if there are no children\n- await postpone()\n- except BaseException as err:\n- return self._aexit_forceful(type(err), err)\n- else:\n- # everybody is gone - we just handle the cleanup\n- self._disable_interrupts()\n- self._close_volatile()\n- return self._propagate_exceptions(None, None)\n \n def _collect_exceptions(self)\\\n -> Tuple[Optional[BaseException], Optional[Concurrent]]:\n@@ -322,25 +293,25 @@ class Scope:\n return None, exc\n return None, None\n \n- def _propagate_exceptions(self, exc_type, exc_val):\n+ def _propagate_exceptions(self, exc_type, exc_val) -> bool:\n if exc_type in self.PROMOTE_CONCURRENT:\n # we already have a privileged exception, there is nothing more important\n # propagate it\n- return False\n- elif self._is_suppressed(exc_val):\n+ return True\n+ elif self._is_suppressed(exc_val) or exc_type is None:\n # we do not have an exception to propagate, take whatever we can get\n privileged, concurrent = self._collect_exceptions()\n if privileged is not None or concurrent is not None:\n raise privileged or concurrent\n # we handled our own and there was nothing else to propagate\n- return True\n+ return False\n else:\n # we already have an exception to propagate, take only important ones\n privileged, _ = self._collect_exceptions()\n if privileged is not None:\n raise privileged\n # we still have our unhandled exception to propagate\n- return False\n+ return True\n \n def _is_suppressed(self, exc_val) -> bool:\n \"\"\"\ndiff --git a/usim/_primitives/task.py b/usim/_primitives/task.py\nindex 0bb4c2a..0028786 100644\n--- a/usim/_primitives/task.py\n+++ b/usim/_primitives/task.py\n@@ -118,7 +118,7 @@ class Task(Awaitable[RT]):\n # check for a pre-run cancellation\n if self._result is not None:\n try_close(self.payload)\n- self.parent.__child_finished__(self, failed=True)\n+ self.parent.__child_finished__(self, failed=False)\n return\n try:\n # We suspend the Task internally instead of waiting to start\n", "test_patch": "diff --git a/usim_pytest/test_types/test_scope.py b/usim_pytest/test_types/test_scope.py\nindex 58cfe58..6565ab3 100644\n--- a/usim_pytest/test_types/test_scope.py\n+++ b/usim_pytest/test_types/test_scope.py\n@@ -2,7 +2,7 @@ import inspect\n \n import pytest\n \n-from usim import Scope, time, instant, Concurrent\n+from usim import Scope, time, instant, eternity, Concurrent, TaskCancelled\n \n from ..utility import via_usim, assertion_mode\n \n@@ -164,6 +164,32 @@ class TestExceptions:\n except Concurrent[Concurrent[IndexError]]:\n assert False\n \n+ @via_usim\n+ async def test_fail_interrupt_shutdown(self):\n+ \"\"\"Interrupts during shutdown are not suppressed\"\"\"\n+ async def bare_scope():\n+ await instant # allow the task to postpone before we cancel it\n+ # a bare Scope postpones twice:\n+ # 1) signalling body done\n+ # 2) waiting for children (even if there are none)\n+ async with Scope():\n+ ...\n+ await eternity # receive late cancellations\n+\n+ async with Scope() as scope:\n+ # create *more* tasks than we expect postponements (3)\n+ # so that we cover every interrupt point in case the\n+ # implementation changes\n+ tasks = [scope.do(bare_scope()) for _ in range(5)]\n+ for task in tasks:\n+ assert not task.done\n+ task.cancel()\n+ await instant\n+\n+ for task in tasks:\n+ with pytest.raises(TaskCancelled):\n+ await task\n+\n \n class TestScoping:\n @via_usim\n", "FAIL_TO_PASS": ["usim_pytest/test_types/test_scope.py::TestExceptions::test_fail_interrupt_shutdown"]}], "all_FAIL_TO_PASS": ["usim_pytest/test_types/test_resource.py::TestCapacity::test_compare", "usim_pytest/test_types/test_resource.py::TestResources::test_compare", "usim_pytest/test_types/test_scope.py::TestExceptions::test_fail_interrupt_shutdown"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "deshima-dev__decode-14_x2", "level": 2, "source": "swerebench", "repo": "deshima-dev/decode", "image": "swerebench/sweb.eval.x86_64.deshima-dev_1776_decode-14:latest", "base_commit": "8b70f186b2c01c01fd48174753ea1b55a6e43248", "num_bugs": 2, "bugs": [{"instance_id": "deshima-dev__decode-14", "base_commit": "8b70f186b2c01c01fd48174753ea1b55a6e43248", "gold_patch": "diff --git a/decode/__init__.py b/decode/__init__.py\nindex 6147cd5..49c96c0 100644\n--- a/decode/__init__.py\n+++ b/decode/__init__.py\n@@ -1,5 +1,5 @@\n # flake8: noqa\n-__version__ = \"0.5.7\"\n+__version__ = \"0.5.8\"\n __author__ = \"DESHIMA software team\"\n \n \ndiff --git a/docs/conf.py b/docs/conf.py\nindex 8663081..f771c05 100644\n--- a/docs/conf.py\n+++ b/docs/conf.py\n@@ -23,7 +23,7 @@ copyright = \"2018-2020 DESHIMA software team\"\n author = \"DESHIMA software team\"\n \n # The full version, including alpha/beta/rc tags\n-release = \"0.5.7\"\n+release = \"0.5.8\"\n \n \n # -- General configuration ---------------------------------------------------\ndiff --git a/poetry.lock b/poetry.lock\nindex 8d859fb..7c17f47 100644\n--- a/poetry.lock\n+++ b/poetry.lock\n@@ -641,12 +641,12 @@ category = \"main\"\n description = \"Powerful data structures for data analysis, time series, and statistics\"\n name = \"pandas\"\n optional = false\n-python-versions = \">=3.6.1\"\n-version = \"1.1.0\"\n+python-versions = \">=3.5.3\"\n+version = \"0.25.3\"\n \n [package.dependencies]\n-numpy = \">=1.15.4\"\n-python-dateutil = \">=2.7.3\"\n+numpy = \">=1.13.3\"\n+python-dateutil = \">=2.6.1\"\n pytz = \">=2017.2\"\n \n [package.extras]\n@@ -739,8 +739,8 @@ category = \"dev\"\n description = \"Library for building powerful interactive command lines in Python\"\n name = \"prompt-toolkit\"\n optional = false\n-python-versions = \">=3.6.1\"\n-version = \"3.0.5\"\n+python-versions = \">=3.6\"\n+version = \"3.0.3\"\n \n [package.dependencies]\n wcwidth = \"*\"\n@@ -1218,9 +1218,9 @@ docs = [\"sphinx\", \"jaraco.packaging (>=3.2)\", \"rst.linker (>=1.9)\"]\n testing = [\"jaraco.itertools\", \"func-timeout\"]\n \n [metadata]\n-content-hash = \"d35b1da445ddf93fe990a18f7f5a8bf866481a8d382c4514b2165ec8ce882baf\"\n+content-hash = \"a67e790d31db8fea686f1cee4f90de67cfdb30f5024bfacb3930dc7b79c479fb\"\n lock-version = \"1.0\"\n-python-versions = \"^3.6.1\"\n+python-versions = \"^3.6\"\n \n [metadata.files]\n alabaster = [\n@@ -1594,22 +1594,25 @@ packaging = [\n {file = \"packaging-20.4.tar.gz\", hash = \"sha256:4357f74f47b9c12db93624a82154e9b120fa8293699949152b22065d556079f8\"},\n ]\n pandas = [\n- {file = \"pandas-1.1.0-cp36-cp36m-macosx_10_9_x86_64.whl\", hash = \"sha256:47a03bfef80d6812c91ed6fae43f04f2fa80a4e1b82b35aa4d9002e39529e0b8\"},\n- {file = \"pandas-1.1.0-cp36-cp36m-manylinux1_i686.whl\", hash = \"sha256:0210f8fe19c2667a3817adb6de2c4fd92b1b78e1975ca60c0efa908e0985cbdb\"},\n- {file = \"pandas-1.1.0-cp36-cp36m-manylinux1_x86_64.whl\", hash = \"sha256:35db623487f00d9392d8af44a24516d6cb9f274afaf73cfcfe180b9c54e007d2\"},\n- {file = \"pandas-1.1.0-cp36-cp36m-win32.whl\", hash = \"sha256:4d1a806252001c5db7caecbe1a26e49a6c23421d85a700960f6ba093112f54a1\"},\n- {file = \"pandas-1.1.0-cp36-cp36m-win_amd64.whl\", hash = \"sha256:9f61cca5262840ff46ef857d4f5f65679b82188709d0e5e086a9123791f721c8\"},\n- {file = \"pandas-1.1.0-cp37-cp37m-macosx_10_9_x86_64.whl\", hash = \"sha256:182a5aeae319df391c3df4740bb17d5300dcd78034b17732c12e62e6dd79e4a4\"},\n- {file = \"pandas-1.1.0-cp37-cp37m-manylinux1_i686.whl\", hash = \"sha256:40ec0a7f611a3d00d3c666c4cceb9aa3f5bf9fbd81392948a93663064f527203\"},\n- {file = \"pandas-1.1.0-cp37-cp37m-manylinux1_x86_64.whl\", hash = \"sha256:16504f915f1ae424052f1e9b7cd2d01786f098fbb00fa4e0f69d42b22952d798\"},\n- {file = \"pandas-1.1.0-cp37-cp37m-win32.whl\", hash = \"sha256:fc714895b6de6803ac9f661abb316853d0cd657f5d23985222255ad76ccedc25\"},\n- {file = \"pandas-1.1.0-cp37-cp37m-win_amd64.whl\", hash = \"sha256:a15835c8409d5edc50b4af93be3377b5dd3eb53517e7f785060df1f06f6da0e2\"},\n- {file = \"pandas-1.1.0-cp38-cp38-macosx_10_9_x86_64.whl\", hash = \"sha256:0bc440493cf9dc5b36d5d46bbd5508f6547ba68b02a28234cd8e81fdce42744d\"},\n- {file = \"pandas-1.1.0-cp38-cp38-manylinux1_i686.whl\", hash = \"sha256:4b21d46728f8a6be537716035b445e7ef3a75dbd30bd31aa1b251323219d853e\"},\n- {file = \"pandas-1.1.0-cp38-cp38-manylinux1_x86_64.whl\", hash = \"sha256:0227e3a6e3a22c0e283a5041f1e3064d78fbde811217668bb966ed05386d8a7e\"},\n- {file = \"pandas-1.1.0-cp38-cp38-win32.whl\", hash = \"sha256:ed60848caadeacecefd0b1de81b91beff23960032cded0ac1449242b506a3b3f\"},\n- {file = \"pandas-1.1.0-cp38-cp38-win_amd64.whl\", hash = \"sha256:60e20a4ab4d4fec253557d0fc9a4e4095c37b664f78c72af24860c8adcd07088\"},\n- {file = \"pandas-1.1.0.tar.gz\", hash = \"sha256:b39508562ad0bb3f384b0db24da7d68a2608b9ddc85b1d931ccaaa92d5e45273\"},\n+ {file = \"pandas-0.25.3-cp35-cp35m-macosx_10_6_intel.whl\", hash = \"sha256:df8864824b1fe488cf778c3650ee59c3a0d8f42e53707de167ba6b4f7d35f133\"},\n+ {file = \"pandas-0.25.3-cp35-cp35m-manylinux1_i686.whl\", hash = \"sha256:7458c48e3d15b8aaa7d575be60e1e4dd70348efcd9376656b72fecd55c59a4c3\"},\n+ {file = \"pandas-0.25.3-cp35-cp35m-manylinux1_x86_64.whl\", hash = \"sha256:61741f5aeb252f39c3031d11405305b6d10ce663c53bc3112705d7ad66c013d0\"},\n+ {file = \"pandas-0.25.3-cp35-cp35m-win32.whl\", hash = \"sha256:adc3d3a3f9e59a38d923e90e20c4922fc62d1e5a03d083440468c6d8f3f1ae0a\"},\n+ {file = \"pandas-0.25.3-cp35-cp35m-win_amd64.whl\", hash = \"sha256:975c461accd14e89d71772e89108a050fa824c0b87a67d34cedf245f6681fc17\"},\n+ {file = \"pandas-0.25.3-cp36-cp36m-macosx_10_9_x86_64.whl\", hash = \"sha256:ee50c2142cdcf41995655d499a157d0a812fce55c97d9aad13bc1eef837ed36c\"},\n+ {file = \"pandas-0.25.3-cp36-cp36m-manylinux1_i686.whl\", hash = \"sha256:4545467a637e0e1393f7d05d61dace89689ad6d6f66f267f86fff737b702cce9\"},\n+ {file = \"pandas-0.25.3-cp36-cp36m-manylinux1_x86_64.whl\", hash = \"sha256:bbe3eb765a0b1e578833d243e2814b60c825b7fdbf4cdfe8e8aae8a08ed56ecf\"},\n+ {file = \"pandas-0.25.3-cp36-cp36m-win32.whl\", hash = \"sha256:8153705d6545fd9eb6dd2bc79301bff08825d2e2f716d5dced48daafc2d0b81f\"},\n+ {file = \"pandas-0.25.3-cp36-cp36m-win_amd64.whl\", hash = \"sha256:26382aab9c119735908d94d2c5c08020a4a0a82969b7e5eefb92f902b3b30ad7\"},\n+ {file = \"pandas-0.25.3-cp37-cp37m-macosx_10_9_x86_64.whl\", hash = \"sha256:00dff3a8e337f5ed7ad295d98a31821d3d0fe7792da82d78d7fd79b89c03ea9d\"},\n+ {file = \"pandas-0.25.3-cp37-cp37m-manylinux1_x86_64.whl\", hash = \"sha256:e45055c30a608076e31a9fcd780a956ed3b1fa20db61561b8d88b79259f526f7\"},\n+ {file = \"pandas-0.25.3-cp37-cp37m-win32.whl\", hash = \"sha256:255920e63850dc512ce356233081098554d641ba99c3767dde9e9f35630f994b\"},\n+ {file = \"pandas-0.25.3-cp37-cp37m-win_amd64.whl\", hash = \"sha256:22361b1597c8c2ffd697aa9bf85423afa9e1fcfa6b1ea821054a244d5f24d75e\"},\n+ {file = \"pandas-0.25.3-cp38-cp38-macosx_10_9_x86_64.whl\", hash = \"sha256:9962957a27bfb70ab64103d0a7b42fa59c642fb4ed4cb75d0227b7bb9228535d\"},\n+ {file = \"pandas-0.25.3-cp38-cp38-manylinux1_x86_64.whl\", hash = \"sha256:78bf638993219311377ce9836b3dc05f627a666d0dbc8cec37c0ff3c9ada673b\"},\n+ {file = \"pandas-0.25.3-cp38-cp38-win32.whl\", hash = \"sha256:6a3ac2c87e4e32a969921d1428525f09462770c349147aa8e9ab95f88c71ec71\"},\n+ {file = \"pandas-0.25.3-cp38-cp38-win_amd64.whl\", hash = \"sha256:33970f4cacdd9a0ddb8f21e151bfb9f178afb7c36eb7c25b9094c02876f385c2\"},\n+ {file = \"pandas-0.25.3.tar.gz\", hash = \"sha256:52da74df8a9c9a103af0a72c9d5fdc8e0183a90884278db7f386b5692a2220a4\"},\n ]\n pandocfilters = [\n {file = \"pandocfilters-1.4.2.tar.gz\", hash = \"sha256:b3dd70e169bb5449e6bc6ff96aea89c5eea8c5f6ab5e207fc2f521a2cf4a0da9\"},\n@@ -1667,8 +1670,8 @@ prometheus-client = [\n {file = \"prometheus_client-0.8.0.tar.gz\", hash = \"sha256:c6e6b706833a6bd1fd51711299edee907857be10ece535126a158f911ee80915\"},\n ]\n prompt-toolkit = [\n- {file = \"prompt_toolkit-3.0.5-py3-none-any.whl\", hash = \"sha256:df7e9e63aea609b1da3a65641ceaf5bc7d05e0a04de5bd45d05dbeffbabf9e04\"},\n- {file = \"prompt_toolkit-3.0.5.tar.gz\", hash = \"sha256:563d1a4140b63ff9dd587bda9557cffb2fe73650205ab6f4383092fb882e7dc8\"},\n+ {file = \"prompt_toolkit-3.0.3-py3-none-any.whl\", hash = \"sha256:c93e53af97f630f12f5f62a3274e79527936ed466f038953dfa379d4941f651a\"},\n+ {file = \"prompt_toolkit-3.0.3.tar.gz\", hash = \"sha256:a402e9bf468b63314e37460b68ba68243d55b2f8c4d0192f85a019af3945050e\"},\n ]\n ptyprocess = [\n {file = \"ptyprocess-0.6.0-py2.py3-none-any.whl\", hash = \"sha256:d7cc528d76e76342423ca640335bd3633420dc1366f258cb31d05e865ef5ca1f\"},\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 38c6be0..b904170 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -1,6 +1,6 @@\n [tool.poetry]\n name = \"decode\"\n-version = \"0.5.7\"\n+version = \"0.5.8\"\n description = \"DESHIMA code for data analysis\"\n keywords = [\n \"astronomy\",\n@@ -19,7 +19,7 @@ homepage = \"https://github.com/deshima-dev/decode/\"\n documentation = \"https://deshima-dev.github.io/decode/\"\n \n [tool.poetry.dependencies]\n-python = \"^3.6.1\"\n+python = \"^3.6\"\n astropy = \"^4.0\"\n matplotlib = \"^3.2\"\n netcdf4 = \"^1.5\"\n", "test_patch": "diff --git a/tests/test_metadata.py b/tests/test_metadata.py\nindex bc800b2..c1ca6e6 100644\n--- a/tests/test_metadata.py\n+++ b/tests/test_metadata.py\n@@ -3,7 +3,7 @@ import decode as dc\n \n def test_version():\n \"\"\"Make sure the version is valid.\"\"\"\n- assert dc.__version__ == \"0.5.7\"\n+ assert dc.__version__ == \"0.5.8\"\n \n \n def test_author():\n", "FAIL_TO_PASS": ["tests/test_metadata.py::test_version"]}, {"instance_id": "deshima-dev__decode-16", "base_commit": "21c0888b2f7fa84eef7f8b30b5a553fc83a6867d", "gold_patch": "diff --git a/decode/__init__.py b/decode/__init__.py\nindex 49c96c0..4172dd8 100644\n--- a/decode/__init__.py\n+++ b/decode/__init__.py\n@@ -1,5 +1,5 @@\n # flake8: noqa\n-__version__ = \"0.5.8\"\n+__version__ = \"0.5.9\"\n __author__ = \"DESHIMA software team\"\n \n \ndiff --git a/docs/conf.py b/docs/conf.py\nindex f771c05..ae26901 100644\n--- a/docs/conf.py\n+++ b/docs/conf.py\n@@ -23,7 +23,7 @@ copyright = \"2018-2020 DESHIMA software team\"\n author = \"DESHIMA software team\"\n \n # The full version, including alpha/beta/rc tags\n-release = \"0.5.8\"\n+release = \"0.5.9\"\n \n \n # -- General configuration ---------------------------------------------------\ndiff --git a/poetry.lock b/poetry.lock\nindex 7c17f47..d7225fd 100644\n--- a/poetry.lock\n+++ b/poetry.lock\n@@ -594,7 +594,7 @@ description = \"A web-based notebook environment for interactive computing\"\n name = \"notebook\"\n optional = false\n python-versions = \">=3.5\"\n-version = \"6.1.0\"\n+version = \"6.1.1\"\n \n [package.dependencies]\n Send2Trash = \"*\"\n@@ -614,7 +614,7 @@ traitlets = \">=4.2.1\"\n \n [package.extras]\n docs = [\"sphinx\", \"nbsphinx\", \"sphinxcontrib-github-alt\"]\n-test = [\"nose\", \"coverage\", \"requests\", \"nose-warnings-filters\", \"nbval\", \"nose-exclude\", \"selenium\", \"pytest\", \"pytest-cov\", \"requests-unixsocket\", \"nose-exclude\"]\n+test = [\"nose\", \"coverage\", \"requests\", \"nose-warnings-filters\", \"nbval\", \"nose-exclude\", \"selenium\", \"pytest\", \"pytest-cov\", \"requests-unixsocket\"]\n \n [[package]]\n category = \"main\"\n@@ -882,8 +882,8 @@ category = \"main\"\n description = \"YAML parser and emitter for Python\"\n name = \"pyyaml\"\n optional = false\n-python-versions = \"*\"\n-version = \"3.13\"\n+python-versions = \">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*\"\n+version = \"5.3.1\"\n \n [[package]]\n category = \"dev\"\n@@ -1133,7 +1133,7 @@ description = \"Fast, Extensible Progress Meter\"\n name = \"tqdm\"\n optional = false\n python-versions = \">=2.6, !=3.0.*, !=3.1.*\"\n-version = \"4.48.1\"\n+version = \"4.48.2\"\n \n [package.extras]\n dev = [\"py-make (>=0.1.0)\", \"twine\", \"argopt\", \"pydoc-markdown\"]\n@@ -1218,7 +1218,7 @@ docs = [\"sphinx\", \"jaraco.packaging (>=3.2)\", \"rst.linker (>=1.9)\"]\n testing = [\"jaraco.itertools\", \"func-timeout\"]\n \n [metadata]\n-content-hash = \"a67e790d31db8fea686f1cee4f90de67cfdb30f5024bfacb3930dc7b79c479fb\"\n+content-hash = \"a2309c57a61600cf08051add6a11e3e1194a7b076fcfa9e08bc86d8e650b4f3e\"\n lock-version = \"1.0\"\n python-versions = \"^3.6\"\n \n@@ -1558,8 +1558,8 @@ netcdf4 = [\n {file = \"netCDF4-1.5.4.tar.gz\", hash = \"sha256:941de6f3623b6474ecb4d043be5990690f7af4cf0d593b31be912627fe5aad03\"},\n ]\n notebook = [\n- {file = \"notebook-6.1.0-py3-none-any.whl\", hash = \"sha256:d3b58a0106abbb7287fe680654665d29020a8203cb167c27ac0c37e940442836\"},\n- {file = \"notebook-6.1.0.tar.gz\", hash = \"sha256:0f44d22092896f68f7589bfdbfc912885993ddb1fd7d5779ddbbf0d8c6b73eef\"},\n+ {file = \"notebook-6.1.1-py3-none-any.whl\", hash = \"sha256:4cc4e44a43a83a7c2f5e85bfdbbfe1c68bed91b857741df9e593d213a6fc2d27\"},\n+ {file = \"notebook-6.1.1.tar.gz\", hash = \"sha256:42391d8f3b88676e774316527599e49c11f3a7e51c41035e9e44c1b58e1398d5\"},\n ]\n numpy = [\n {file = \"numpy-1.19.1-cp36-cp36m-macosx_10_9_x86_64.whl\", hash = \"sha256:b1cca51512299841bf69add3b75361779962f9cee7d9ee3bb446d5982e925b69\"},\n@@ -1743,17 +1743,17 @@ pywinpty = [\n {file = \"pywinpty-0.5.7.tar.gz\", hash = \"sha256:2d7e9c881638a72ffdca3f5417dd1563b60f603e1b43e5895674c2a1b01f95a0\"},\n ]\n pyyaml = [\n- {file = \"PyYAML-3.13-cp27-cp27m-win32.whl\", hash = \"sha256:d5eef459e30b09f5a098b9cea68bebfeb268697f78d647bd255a085371ac7f3f\"},\n- {file = \"PyYAML-3.13-cp27-cp27m-win_amd64.whl\", hash = \"sha256:e01d3203230e1786cd91ccfdc8f8454c8069c91bee3962ad93b87a4b2860f537\"},\n- {file = \"PyYAML-3.13-cp34-cp34m-win32.whl\", hash = \"sha256:558dd60b890ba8fd982e05941927a3911dc409a63dcb8b634feaa0cda69330d3\"},\n- {file = \"PyYAML-3.13-cp34-cp34m-win_amd64.whl\", hash = \"sha256:d46d7982b62e0729ad0175a9bc7e10a566fc07b224d2c79fafb5e032727eaa04\"},\n- {file = \"PyYAML-3.13-cp35-cp35m-win32.whl\", hash = \"sha256:a7c28b45d9f99102fa092bb213aa12e0aaf9a6a1f5e395d36166639c1f96c3a1\"},\n- {file = \"PyYAML-3.13-cp35-cp35m-win_amd64.whl\", hash = \"sha256:bc558586e6045763782014934bfaf39d48b8ae85a2713117d16c39864085c613\"},\n- {file = \"PyYAML-3.13-cp36-cp36m-win32.whl\", hash = \"sha256:40c71b8e076d0550b2e6380bada1f1cd1017b882f7e16f09a65be98e017f211a\"},\n- {file = \"PyYAML-3.13-cp36-cp36m-win_amd64.whl\", hash = \"sha256:3d7da3009c0f3e783b2c873687652d83b1bbfd5c88e9813fb7e5b03c0dd3108b\"},\n- {file = \"PyYAML-3.13-cp37-cp37m-win32.whl\", hash = \"sha256:e170a9e6fcfd19021dd29845af83bb79236068bf5fd4df3327c1be18182b2531\"},\n- {file = \"PyYAML-3.13-cp37-cp37m-win_amd64.whl\", hash = \"sha256:aa7dd4a6a427aed7df6fb7f08a580d68d9b118d90310374716ae90b710280af1\"},\n- {file = \"PyYAML-3.13.tar.gz\", hash = \"sha256:3ef3092145e9b70e3ddd2c7ad59bdd0252a94dfe3949721633e41344de00a6bf\"},\n+ {file = \"PyYAML-5.3.1-cp27-cp27m-win32.whl\", hash = \"sha256:74809a57b329d6cc0fdccee6318f44b9b8649961fa73144a98735b0aaf029f1f\"},\n+ {file = \"PyYAML-5.3.1-cp27-cp27m-win_amd64.whl\", hash = \"sha256:240097ff019d7c70a4922b6869d8a86407758333f02203e0fc6ff79c5dcede76\"},\n+ {file = \"PyYAML-5.3.1-cp35-cp35m-win32.whl\", hash = \"sha256:4f4b913ca1a7319b33cfb1369e91e50354d6f07a135f3b901aca02aa95940bd2\"},\n+ {file = \"PyYAML-5.3.1-cp35-cp35m-win_amd64.whl\", hash = \"sha256:cc8955cfbfc7a115fa81d85284ee61147059a753344bc51098f3ccd69b0d7e0c\"},\n+ {file = \"PyYAML-5.3.1-cp36-cp36m-win32.whl\", hash = \"sha256:7739fc0fa8205b3ee8808aea45e968bc90082c10aef6ea95e855e10abf4a37b2\"},\n+ {file = \"PyYAML-5.3.1-cp36-cp36m-win_amd64.whl\", hash = \"sha256:69f00dca373f240f842b2931fb2c7e14ddbacd1397d57157a9b005a6a9942648\"},\n+ {file = \"PyYAML-5.3.1-cp37-cp37m-win32.whl\", hash = \"sha256:d13155f591e6fcc1ec3b30685d50bf0711574e2c0dfffd7644babf8b5102ca1a\"},\n+ {file = \"PyYAML-5.3.1-cp37-cp37m-win_amd64.whl\", hash = \"sha256:73f099454b799e05e5ab51423c7bcf361c58d3206fa7b0d555426b1f4d9a3eaf\"},\n+ {file = \"PyYAML-5.3.1-cp38-cp38-win32.whl\", hash = \"sha256:06a0d7ba600ce0b2d2fe2e78453a470b5a6e000a985dd4a4e54e436cc36b0e97\"},\n+ {file = \"PyYAML-5.3.1-cp38-cp38-win_amd64.whl\", hash = \"sha256:95f71d2af0ff4227885f7a6605c37fd53d3a106fcab511b8860ecca9fcf400ee\"},\n+ {file = \"PyYAML-5.3.1.tar.gz\", hash = \"sha256:b8eac752c5e14d3eca0e6dd9199cd627518cb5ec06add0de9d32baeee6fe645d\"},\n ]\n pyzmq = [\n {file = \"pyzmq-19.0.2-cp27-cp27m-macosx_10_9_intel.whl\", hash = \"sha256:59f1e54627483dcf61c663941d94c4af9bf4163aec334171686cdaee67974fe5\"},\n@@ -1921,8 +1921,8 @@ tornado = [\n {file = \"tornado-6.0.4.tar.gz\", hash = \"sha256:0fe2d45ba43b00a41cd73f8be321a44936dc1aba233dee979f17a042b83eb6dc\"},\n ]\n tqdm = [\n- {file = \"tqdm-4.48.1-py2.py3-none-any.whl\", hash = \"sha256:44b896c38f70f91826a3f83a3195b23c0460322bfc729566ec8e4e89bb5ad713\"},\n- {file = \"tqdm-4.48.1.tar.gz\", hash = \"sha256:7b7dd59cd9f03b89365ba67eb8515f5d2803fd1eb707abdbb914691a3123d9df\"},\n+ {file = \"tqdm-4.48.2-py2.py3-none-any.whl\", hash = \"sha256:1a336d2b829be50e46b84668691e0a2719f26c97c62846298dd5ae2937e4d5cf\"},\n+ {file = \"tqdm-4.48.2.tar.gz\", hash = \"sha256:564d632ea2b9cb52979f7956e093e831c28d441c11751682f84c86fc46e4fd21\"},\n ]\n traitlets = [\n {file = \"traitlets-4.3.3-py2.py3-none-any.whl\", hash = \"sha256:70b4c6a1d9019d7b4f6846832288f86998aa3b9207c6821f3578a6a6a467fe44\"},\ndiff --git a/pyproject.toml b/pyproject.toml\nindex b904170..41c8ebc 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -1,6 +1,6 @@\n [tool.poetry]\n name = \"decode\"\n-version = \"0.5.8\"\n+version = \"0.5.9\"\n description = \"DESHIMA code for data analysis\"\n keywords = [\n \"astronomy\",\n@@ -24,7 +24,7 @@ astropy = \"^4.0\"\n matplotlib = \"^3.2\"\n netcdf4 = \"^1.5\"\n numpy = \"^1.18\"\n-pyyaml = \"^3.13\"\n+pyyaml = \"^5.3\"\n scikit-learn = \"^0.22\"\n scipy = \"^1.4\"\n tqdm = \"^4.41\"\n", "test_patch": "diff --git a/tests/test_metadata.py b/tests/test_metadata.py\nindex c1ca6e6..c739d42 100644\n--- a/tests/test_metadata.py\n+++ b/tests/test_metadata.py\n@@ -3,7 +3,7 @@ import decode as dc\n \n def test_version():\n \"\"\"Make sure the version is valid.\"\"\"\n- assert dc.__version__ == \"0.5.8\"\n+ assert dc.__version__ == \"0.5.9\"\n \n \n def test_author():\n", "FAIL_TO_PASS": ["tests/test_metadata.py::test_version"]}], "all_FAIL_TO_PASS": ["tests/test_metadata.py::test_version", "tests/test_metadata.py::test_version"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ifosch__accloudtant-82_x2", "level": 2, "source": "swerebench", "repo": "ifosch/accloudtant", "image": "swerebench/sweb.eval.x86_64.ifosch_1776_accloudtant-82:latest", "base_commit": "9dd6000060b4bddfa5366ef3102fe7d42371d514", "num_bugs": 2, "bugs": [{"instance_id": "ifosch__accloudtant-82", "base_commit": "9dd6000060b4bddfa5366ef3102fe7d42371d514", "gold_patch": "diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py\nindex 4e19b2d..2073f28 100644\n--- a/accloudtant/aws/instance.py\n+++ b/accloudtant/aws/instance.py\n@@ -62,7 +62,7 @@ class Instance(object):\n @property\n def name(self):\n names = [tag for tag in self.tags if tag['Key'] == 'Name']\n- if names is None:\n+ if len(names) == 0:\n return ''\n else:\n return names[0]['Value']\n", "test_patch": "diff --git a/tests/aws/test_instance.py b/tests/aws/test_instance.py\nindex d90e2c5..a016f7b 100644\n--- a/tests/aws/test_instance.py\n+++ b/tests/aws/test_instance.py\n@@ -73,6 +73,57 @@ def test_instance():\n assert(instance.best == 0.293)\n \n \n+def test_unnamed_instance():\n+ az = 'us-east-1b'\n+ region = 'us-east-1'\n+ instance_data = {\n+ 'id': 'i-1840273e',\n+ 'tags': [],\n+ 'instance_type': 'r2.8xlarge',\n+ 'placement': {\n+ 'AvailabilityZone': az,\n+ },\n+ 'state': {\n+ 'Name': 'running',\n+ },\n+ 'launch_time': datetime.datetime(\n+ 2015,\n+ 10,\n+ 22,\n+ 14,\n+ 15,\n+ 10,\n+ tzinfo=tzutc()\n+ ),\n+ 'console_output': {'Output': 'RHEL Linux', },\n+ }\n+\n+\n+ ec2_instance = MockEC2Instance(instance_data)\n+ instance = accloudtant.aws.instance.Instance(ec2_instance)\n+\n+ assert(instance.id == ec2_instance.id)\n+ assert(instance.reserved == 'No')\n+ assert(instance.name == '')\n+ assert(instance.size == ec2_instance.instance_type)\n+ assert(instance.availability_zone == az)\n+ assert(instance.region == region)\n+ assert(instance.operating_system == 'Red Hat Enterprise Linux')\n+ assert(instance.key == 'rhel')\n+ assert(instance.state == ec2_instance.state['Name'])\n+ assert(instance.current == 0.0)\n+ assert(instance.best == 0.0)\n+\n+ with pytest.raises(ValueError):\n+ instance.reserved = 'Maybe'\n+\n+ instance.current = 0.392\n+ instance.best = 0.293\n+\n+ assert(instance.current == 0.392)\n+ assert(instance.best == 0.293)\n+\n+\n def test_guess_os():\n instance_data_win = {\n 'id': 'i-912a4392',\n", "FAIL_TO_PASS": ["tests/aws/test_instance.py::test_unnamed_instance"]}, {"instance_id": "ifosch__accloudtant-88", "base_commit": "79e3cf915208ffd58a63412ffc87bd48f8bfb2dd", "gold_patch": "diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py\nindex d83c3dc..f360c03 100644\n--- a/accloudtant/aws/instance.py\n+++ b/accloudtant/aws/instance.py\n@@ -28,6 +28,9 @@ class Instance(object):\n 'best': 0.0,\n }\n \n+ def __repr__(self):\n+ return \"\".format(self.id)\n+\n @property\n def current(self):\n return self._prices['current']\ndiff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py\nindex 0bbbeb9..e8f2fc9 100644\n--- a/accloudtant/aws/reports.py\n+++ b/accloudtant/aws/reports.py\n@@ -25,9 +25,26 @@ class Reports(object):\n def __init__(self):\n ec2 = boto3.resource('ec2')\n ec2_client = boto3.client('ec2')\n+ instances_filters = [{\n+ 'Name': 'instance-state-name',\n+ 'Values': ['running', ],\n+ }, ]\n+ reserved_instances_filters = [{\n+ 'Name': 'state',\n+ 'Values': ['active', ],\n+ }, ]\n try:\n- self.instances = [Instance(i) for i in ec2.instances.all()]\n- self.reserved_instances = ec2_client.describe_reserved_instances()\n+ self.instances = [\n+ Instance(i)\n+ for i in ec2.instances.filter(Filters=instances_filters)\n+ ]\n+ # self.instances = [Instance(i) for i in ec2.instances.all()]\n+ self.reserved_instances = ec2_client.\\\n+ describe_reserved_instances(\n+ Filters=reserved_instances_filters\n+ )\n+ # self.reserved_instances = ec2_client\n+ # .describe_reserved_instances()\n except exceptions.NoCredentialsError:\n print(\"Error: no AWS credentials found\", file=sys.stderr)\n sys.exit(1)\n", "test_patch": "diff --git a/tests/aws/conftest.py b/tests/aws/conftest.py\nindex 0594830..5a97b58 100644\n--- a/tests/aws/conftest.py\n+++ b/tests/aws/conftest.py\n@@ -65,6 +65,14 @@ def ec2_resource():\n for instance in self.instances:\n yield MockEC2Instance(instance)\n \n+ def filter(self, Filters=None):\n+ if Filters is None:\n+ self.all()\n+ if Filters[0]['Name'] == 'instance-state-name':\n+ for instance in self.instances:\n+ if instance['state']['Name'] in Filters[0]['Values']:\n+ yield MockEC2Instance(instance)\n+\n class MockEC2Resource(object):\n def __init__(self, responses):\n self.responses = responses\n@@ -94,7 +102,19 @@ def ec2_client():\n def describe_instances(self):\n return self.instances\n \n- def describe_reserved_instances(self):\n+ def describe_reserved_instances(self, Filters=None):\n+ final_reserved = {'ReservedInstances': []}\n+ if Filters is None:\n+ final_reserved = self.reserved\n+ else:\n+ filter = Filters[0]\n+ if filter['Name'] == 'state':\n+ final_reserved['ReservedInstances'] = [\n+ reserved_instance\n+ for reserved_instance\n+ in self.reserved['ReservedInstances']\n+ if reserved_instance['State'] not in filter['Values']\n+ ]\n return self.reserved\n \n class MockEC2ClientCall(object):\ndiff --git a/tests/aws/report_running_expected.txt b/tests/aws/report_running_expected.txt\nnew file mode 100644\nindex 0000000..befecd0\n--- /dev/null\n+++ b/tests/aws/report_running_expected.txt\n@@ -0,0 +1,8 @@\n+Id Name Type AZ OS State Launch time Reserved Current hourly price Renewed hourly price\n+---------- --------- ---------- ---------- ------------------------ ------- ------------------- ---------- ---------------------- ----------------------\n+i-912a4392 web1 c3.8xlarge us-east-1c Windows running 2015-10-22 14:15:10 Yes 0.5121 0.3894\n+i-1840273e app1 r2.8xlarge us-east-1b Red Hat Enterprise Linux running 2015-10-22 14:15:10 Yes 0.3894 0.3794\n+i-9840273d app2 r2.8xlarge us-east-1c SUSE Linux running 2015-10-22 14:15:10 Yes 0.5225 0.389\n+i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379\n+i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379\n+i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No 0.767 0.3892\ndiff --git a/tests/aws/test_reports.py b/tests/aws/test_reports.py\nindex 35fd236..d0f6793 100644\n--- a/tests/aws/test_reports.py\n+++ b/tests/aws/test_reports.py\n@@ -17,6 +17,10 @@ from dateutil.tz import tzutc\n import accloudtant.aws.reports\n \n \n+def get_future_date(years=1):\n+ return datetime.datetime.now() + datetime.timedelta(years)\n+\n+\n def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n instances = {\n 'instances': [{\n@@ -232,16 +236,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- 494000,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320',\n@@ -266,16 +261,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- 494000,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233321',\n@@ -300,15 +286,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233322',\n@@ -333,15 +311,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320',\n@@ -421,7 +391,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n },\n },\n },\n- 'od': '0.767',\n+ 'od': '0.867',\n 'memoryGiB': '15',\n 'vCPU': '8',\n },\n@@ -618,7 +588,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n 'best': 0.3892,\n },\n }\n- expected = open('tests/aws/report_expected.txt', 'r').read()\n+ expected = open('tests/aws/report_running_expected.txt', 'r').read()\n \n monkeypatch.setattr('boto3.resource', ec2_resource)\n ec2_resource.set_responses(instances)\n@@ -634,6 +604,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n print(reports)\n out, err = capsys.readouterr()\n \n+ assert(len(reports.instances) == 6)\n for mock in instances['instances']:\n mock['current'] = instances_prices[mock['id']]['current']\n mock['best'] = instances_prices[mock['id']]['best']\n@@ -641,5 +612,4 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n if instance.id == mock['id']:\n assert(instance.current == mock['current'])\n assert(instance.best == mock['best'])\n- print(out)\n assert(out == expected)\n", "FAIL_TO_PASS": ["tests/aws/test_reports.py::test_reports"]}], "all_FAIL_TO_PASS": ["tests/aws/test_instance.py::test_unnamed_instance", "tests/aws/test_reports.py::test_reports"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "feder-observatory__stellarphot-298_x2", "level": 2, "source": "swerebench", "repo": "feder-observatory/stellarphot", "image": "swerebench/sweb.eval.x86_64.feder-observatory_1776_stellarphot-298:latest", "base_commit": "bd23f25fd68e88feac679c232514a8ecca43365a", "num_bugs": 2, "bugs": [{"instance_id": "feder-observatory__stellarphot-298", "base_commit": "bd23f25fd68e88feac679c232514a8ecca43365a", "gold_patch": "diff --git a/stellarphot/settings/models.py b/stellarphot/settings/models.py\nindex db043c2..d64f9aa 100644\n--- a/stellarphot/settings/models.py\n+++ b/stellarphot/settings/models.py\n@@ -252,23 +252,27 @@ class Camera(BaseModelWithTableRep):\n NonEmptyStr,\n Field(\n description=\"Name of the camera\",\n- examples=[\"SBIG ST-8300M\", \"ZWO ASI1600\"],\n+ examples=[\"SBIG FakeCam\", \"ZWO NadaCam\", \"CG16m\"],\n ),\n ]\n data_unit: UnitType = Field(\n- description=\"units of the data\", examples=[\"adu\", \"counts\", \"DN\", \"electrons\"]\n+ description=\"units of the data\", examples=[\"adu\", \"DN\", \"count\"]\n )\n gain: QuantityType = Field(\n description=\"unit should be consistent with data and read noise\",\n- examples=[\"1.0 electron / adu\"],\n+ examples=[\"1.5 electron / adu\", \"1.0 electron / DN\", \"1.0 photon / count\"],\n )\n read_noise: QuantityType = Field(\n description=\"unit should be consistent with dark current\",\n- examples=[\"10.0 electron\"],\n+ examples=[\"10.0 electron\", \"10.0 electron\", \"10.0 photon\"],\n )\n dark_current: QuantityType = Field(\n description=\"unit consistent with read noise, per unit time\",\n- examples=[\"0.01 electron / second\"],\n+ examples=[\n+ \"0.01 electron / second\",\n+ \"0.01 electron / second\",\n+ \"0.01 photon / second\",\n+ ],\n )\n pixel_scale: Annotated[\n QuantityType,\n@@ -279,7 +283,7 @@ class Camera(BaseModelWithTableRep):\n QuantityType,\n Field(\n description=\"maximum data value while performing photometry\",\n- examples=[\"50000 adu\"],\n+ examples=[\"50000 adu\", \"50000 DN\", \"50000 count\"],\n gt=0,\n ),\n ]\n@@ -505,10 +509,12 @@ class Observatory(BaseModelWithTableRep):\n above example, but the example is given in part to show how to use sexagesimal\n notation.\n \n-\n \"\"\"\n \n- name: Annotated[NonEmptyStr, Field(description=\"Name of the observatory\")]\n+ name: Annotated[\n+ NonEmptyStr,\n+ Field(description=\"Name of the observatory\", examples=[\"My Observatory\"]),\n+ ]\n latitude: Annotated[\n Latitude,\n _UnitQuantTypePydanticAnnotation,\n@@ -532,7 +538,6 @@ class Observatory(BaseModelWithTableRep):\n examples=[\n \"-96.7678\",\n \"-96d46m04.08s\",\n- \"263.2322\",\n \"263.2322 degree\",\n \"263d13m55.92s\",\n ],\n@@ -543,7 +548,7 @@ class Observatory(BaseModelWithTableRep):\n WithPhysicalType(\"length\"),\n Field(\n description=\"Elevation of the observatory\",\n- examples=[\"1000 m\", \"1 km\", \"3.241e-14 pc\"],\n+ examples=[\"1000 m\", \"1 km\", \"3.241e-14 pc\", \"1e12 nm\"],\n ),\n ]\n AAVSO_code: Annotated[str | None, Field(description=\"AAVSO code for observer\")] = (\n@@ -753,8 +758,12 @@ class PassbandMapEntry(BaseModel):\n \n \"\"\"\n \n- your_filter_name: Annotated[str, Field(description=\"Instrumental Filter Name\")]\n- aavso_filter_name: Annotated[AAVSOFilters, Field(title=\"AAVSO Filter Name\")]\n+ your_filter_name: Annotated[\n+ str, Field(description=\"Instrumental Filter Name\", examples=[\"Sloan r\"])\n+ ]\n+ aavso_filter_name: Annotated[\n+ AAVSOFilters, Field(title=\"AAVSO Filter Name\", default=\"SR\")\n+ ]\n \n \n class PassbandMap(BaseModelWithTableRep):\n", "test_patch": "diff --git a/stellarphot/settings/tests/test_models.py b/stellarphot/settings/tests/test_models.py\nindex a580347..85f599b 100644\n--- a/stellarphot/settings/tests/test_models.py\n+++ b/stellarphot/settings/tests/test_models.py\n@@ -1,8 +1,9 @@\n import json\n+import re\n \n import astropy.units as u\n import pytest\n-from astropy.coordinates import EarthLocation, SkyCoord\n+from astropy.coordinates import EarthLocation, Latitude, Longitude, SkyCoord\n from astropy.table import Table\n from astropy.time import Time\n from pydantic import ValidationError\n@@ -257,6 +258,83 @@ class TestModelsWithName:\n assert model(**settings).name == \"\u03c0\"\n \n \n+# Only include models here that have examples that should be tested\n+@pytest.mark.parametrize(\n+ \"model,settings\",\n+ [\n+ [Camera, TEST_CAMERA_VALUES.copy()],\n+ [Observatory, DEFAULT_OBSERVATORY_SETTINGS.copy()],\n+ ],\n+)\n+class TestModelExamples:\n+ \"\"\" \"\n+ Test that you can make a valid model from the examples. The assumption is that\n+ all of the first choices in the examples make a valid model, all of the second\n+ choices make a valid model, etc.\n+\n+ The purpose for including this test is that users may use the examples as guidance\n+ so we should make sure the guidance isn't nonsense.\n+ \"\"\"\n+\n+ def test_example(self, model, settings):\n+ # Get the model's fields so that we can get their examples. fields is dict\n+ # with the field names as keys and the field objects as values.\n+ fields = model.model_fields\n+\n+ examples = {k: f.examples for k, f in fields.items()}\n+ example_lengths = set(len(e) for e in examples.values() if e is not None)\n+\n+ # We can't handle more than two different example lengths in an unambiguous way,\n+ # so we raise an error if we have more than two.\n+ if len(example_lengths) > 2:\n+ raise ValueError(f\"Too many different example lengths for {model.__name__}\")\n+ elif min(example_lengths) > 1 and len(example_lengths) == 2:\n+ raise ValueError(\n+ \"Must have the same number of examples for all fields \"\n+ \"or one example for some fields and the same number for \"\n+ \"the rest.\"\n+ )\n+ max_len = max(example_lengths)\n+ for k in examples.keys():\n+ if examples[k] is None:\n+ examples[k] = [None] * max_len\n+ elif len(examples[k]) == 1:\n+ examples[k] = examples[k] * max_len\n+\n+ for i in range(max_len):\n+ settings = {k: examples[k][i] for k in examples.keys()}\n+\n+ mod = model(**settings)\n+\n+ # Really need to compare some fields as\n+ # latitude/longitude/quantities/numbers but don't want to hard code that\n+ # here.\n+ for k, v in settings.items():\n+ model_value = getattr(mod, k)\n+\n+ # For some foolish reason Observatory allows the latitude and longitude\n+ # to be entered as floats, which we assume are intended to have unit of\n+ # degrees. Test and handle that case...\n+ print(k, v)\n+ if k.lower() in [\"latitude\", \"longitude\"] and re.match(\n+ r\"[+-]?\\d+\\.\\d+$\", v\n+ ):\n+ v = v + \" degree\"\n+\n+ # Also, latitude and longitude are not Quantity, so handle that too\n+ if k == \"latitude\":\n+ v = Latitude(v)\n+ elif k == \"longitude\":\n+ v = Longitude(v)\n+\n+ if isinstance(model_value, u.Quantity):\n+ assert model_value == u.Quantity(v)\n+ elif isinstance(model_value, u.UnitBase):\n+ assert model_value == u.Unit(v)\n+ else:\n+ assert model_value == v\n+\n+\n def test_camera_unitscheck():\n # Check that the units are checked properly\n \n", "FAIL_TO_PASS": ["stellarphot/settings/tests/test_models.py::TestModelExamples::test_example[Camera-settings0]", "stellarphot/settings/tests/test_models.py::TestModelExamples::test_example[Observatory-settings1]"]}, {"instance_id": "feder-observatory__stellarphot-300", "base_commit": "bd23f25fd68e88feac679c232514a8ecca43365a", "gold_patch": "diff --git a/stellarphot/settings/models.py b/stellarphot/settings/models.py\nindex db043c2..09c9e8a 100644\n--- a/stellarphot/settings/models.py\n+++ b/stellarphot/settings/models.py\n@@ -7,7 +7,7 @@ from typing import Annotated, Any, Literal\n from astropy.coordinates import EarthLocation, Latitude, Longitude, SkyCoord\n from astropy.io.misc.yaml import AstropyDumper, AstropyLoader\n from astropy.time import Time\n-from astropy.units import Quantity, Unit\n+from astropy.units import Quantity, Unit, UnitConversionError\n from astropy.utils import lazyproperty\n from pydantic import (\n AfterValidator,\n@@ -294,15 +294,14 @@ class Camera(BaseModelWithTableRep):\n # Check that gain and read noise have compatible units, that is that\n # gain is read noise per data unit.\n gain = self.gain\n- if (\n- len(gain.unit.bases) != 2\n- or gain.unit.bases[0] != rn_unit\n- or gain.unit.bases[1] != self.data_unit\n- ):\n+\n+ try:\n+ gain.to(self.read_noise.unit / self.data_unit)\n+ except UnitConversionError as e:\n raise ValueError(\n f\"Gain units {gain.unit} are not compatible with \"\n f\"read noise units {rn_unit}.\"\n- )\n+ ) from e\n \n # Check that dark current and read noise have compatible units, that is\n # that dark current is read noise per second.\n", "test_patch": "diff --git a/stellarphot/settings/tests/test_models.py b/stellarphot/settings/tests/test_models.py\nindex a580347..577d5cd 100644\n--- a/stellarphot/settings/tests/test_models.py\n+++ b/stellarphot/settings/tests/test_models.py\n@@ -302,6 +302,21 @@ def test_camera_incompatible_gain_units():\n )\n \n \n+def test_camera_unitsless_gain():\n+ # Regression test for #299\n+ c = Camera(\n+ name=\"should_work\",\n+ data_unit=\"electron\",\n+ gain=\"1\",\n+ dark_current=\"0.01 electron / second\",\n+ read_noise=\"1.2 electron\",\n+ pixel_scale=\"0.55 arcsec / pix\",\n+ max_data_value=\"80000 electron\",\n+ )\n+\n+ assert c.gain == u.Quantity(1)\n+\n+\n def test_camera_incompatible_max_val_units():\n camera_for_test = TEST_CAMERA_VALUES.copy()\n # data unit is adu, not count\n", "FAIL_TO_PASS": ["stellarphot/settings/tests/test_models.py::test_camera_unitsless_gain"]}], "all_FAIL_TO_PASS": ["stellarphot/settings/tests/test_models.py::TestModelExamples::test_example[Camera-settings0]", "stellarphot/settings/tests/test_models.py::TestModelExamples::test_example[Observatory-settings1]", "stellarphot/settings/tests/test_models.py::test_camera_unitsless_gain"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ipython__ipython-14693_x2", "level": 2, "source": "swerebench", "repo": "ipython/ipython", "image": "swerebench/sweb.eval.x86_64.ipython_1776_ipython-14693:latest", "base_commit": "637e037d668db7aebe61ae04261ebfc5cb7f32c5", "num_bugs": 2, "bugs": [{"instance_id": "ipython__ipython-14693", "base_commit": "637e037d668db7aebe61ae04261ebfc5cb7f32c5", "gold_patch": "diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py\nindex 7387e212f..dd745249d 100644\n--- a/IPython/core/magics/execution.py\n+++ b/IPython/core/magics/execution.py\n@@ -977,7 +977,21 @@ def _run_with_debugger(\n break\n finally:\n sys.settrace(trace)\n- \n+\n+ # Perform proper cleanup of the session in case if\n+ # it exited with \"continue\" and not \"quit\" command\n+ if hasattr(deb, \"rcLines\"):\n+ # Run this code defensively in case if custom debugger\n+ # class does not implement rcLines, which although public\n+ # is an implementation detail of `pdb.Pdb` and not part of\n+ # the more generic basic debugger framework (`bdb.Bdb`).\n+ deb.set_quit()\n+ deb.rcLines.extend([\"q\"])\n+ try:\n+ deb.run(\"\", code_ns, local_ns)\n+ except StopIteration:\n+ # Stop iteration is raised on quit command\n+ pass\n \n except:\n etype, value, tb = sys.exc_info()\ndiff --git a/IPython/core/magics/script.py b/IPython/core/magics/script.py\nindex 0c405ef42..8abc22efe 100644\n--- a/IPython/core/magics/script.py\n+++ b/IPython/core/magics/script.py\n@@ -67,6 +67,10 @@ def script_args(f):\n return f\n \n \n+class RaiseAfterInterrupt(Exception):\n+ pass\n+\n+\n @magics_class\n class ScriptMagics(Magics):\n \"\"\"Magics for talking to scripts\n@@ -176,6 +180,10 @@ def shebang(self, line, cell):\n \n The rest of the cell is run by that program.\n \n+ .. versionchanged:: 9.0\n+ Interrupting the script executed without `--bg` will end in\n+ raising an exception (unless `--no-raise-error` is passed).\n+\n Examples\n --------\n ::\n@@ -292,20 +300,33 @@ async def _stream_communicate(process, cell):\n p.send_signal(signal.SIGINT)\n in_thread(asyncio.wait_for(p.wait(), timeout=0.1))\n if p.returncode is not None:\n- print(\"Process is interrupted.\")\n- return\n+ print(\"Process was interrupted.\")\n+ if args.raise_error:\n+ raise RaiseAfterInterrupt()\n+ else:\n+ return\n p.terminate()\n in_thread(asyncio.wait_for(p.wait(), timeout=0.1))\n if p.returncode is not None:\n- print(\"Process is terminated.\")\n- return\n+ print(\"Process was terminated.\")\n+ if args.raise_error:\n+ raise RaiseAfterInterrupt()\n+ else:\n+ return\n p.kill()\n- print(\"Process is killed.\")\n+ print(\"Process was killed.\")\n+ if args.raise_error:\n+ raise RaiseAfterInterrupt()\n+ except RaiseAfterInterrupt:\n+ pass\n except OSError:\n pass\n except Exception as e:\n print(\"Error while terminating subprocess (pid=%i): %s\" % (p.pid, e))\n- return\n+ if args.raise_error:\n+ raise CalledProcessError(p.returncode, cell) from None\n+ else:\n+ return\n \n if args.raise_error and p.returncode != 0:\n # If we get here and p.returncode is still None, we must have\n", "test_patch": "diff --git a/IPython/core/tests/test_magic.py b/IPython/core/tests/test_magic.py\nindex 036f250d3..a107da0c6 100644\n--- a/IPython/core/tests/test_magic.py\n+++ b/IPython/core/tests/test_magic.py\n@@ -6,12 +6,16 @@\n import os\n import re\n import shlex\n+import signal\n import sys\n import warnings\n from importlib import invalidate_caches\n from io import StringIO\n from pathlib import Path\n+from subprocess import CalledProcessError\n from textwrap import dedent\n+from time import sleep\n+from threading import Thread\n from unittest import TestCase, mock\n \n import pytest\n@@ -1121,6 +1125,36 @@ def test_script_config():\n assert \"whoda\" in sm.magics[\"cell\"]\n \n \n+def _interrupt_after_1s():\n+ sleep(1)\n+ signal.raise_signal(signal.SIGINT)\n+\n+\n+def test_script_raise_on_interrupt():\n+ ip = get_ipython()\n+\n+ with pytest.raises(CalledProcessError):\n+ thread = Thread(target=_interrupt_after_1s)\n+ thread.start()\n+ ip.run_cell_magic(\n+ \"script\", f\"{sys.executable}\", \"from time import sleep; sleep(2)\"\n+ )\n+ thread.join()\n+\n+\n+def test_script_do_not_raise_on_interrupt():\n+ ip = get_ipython()\n+\n+ thread = Thread(target=_interrupt_after_1s)\n+ thread.start()\n+ ip.run_cell_magic(\n+ \"script\",\n+ f\"--no-raise-error {sys.executable}\",\n+ \"from time import sleep; sleep(2)\",\n+ )\n+ thread.join()\n+\n+\n def test_script_out():\n ip = get_ipython()\n ip.run_cell_magic(\"script\", f\"--out output {sys.executable}\", \"print('hi')\")\n", "FAIL_TO_PASS": ["IPython/core/tests/test_magic.py::test_script_raise_on_interrupt"]}, {"instance_id": "ipython__ipython-14695", "base_commit": "b8220b5b975e3f4e19d078033aa1e68da28e2c9b", "gold_patch": "diff --git a/IPython/core/magics/script.py b/IPython/core/magics/script.py\nindex 8abc22efe..3bfc4d8d6 100644\n--- a/IPython/core/magics/script.py\n+++ b/IPython/core/magics/script.py\n@@ -220,7 +220,7 @@ def in_thread(coro):\n \n async def _readchunk(stream):\n try:\n- return await stream.readuntil(b\"\\n\")\n+ return await stream.read(100)\n except asyncio.exceptions.IncompleteReadError as e:\n return e.partial\n except asyncio.exceptions.LimitOverrunError as e:\n", "test_patch": "diff --git a/IPython/core/tests/test_magic.py b/IPython/core/tests/test_magic.py\nindex a107da0c6..4e167007c 100644\n--- a/IPython/core/tests/test_magic.py\n+++ b/IPython/core/tests/test_magic.py\n@@ -12,6 +12,8 @@\n from importlib import invalidate_caches\n from io import StringIO\n from pathlib import Path\n+from time import sleep\n+from threading import Thread\n from subprocess import CalledProcessError\n from textwrap import dedent\n from time import sleep\n@@ -1259,6 +1261,37 @@ def test_script_defaults():\n assert cmd in ip.magics_manager.magics[\"cell\"]\n \n \n+async def test_script_streams_continiously(capsys):\n+ ip = get_ipython()\n+ # Windows is slow to start up a thread on CI\n+ is_windows = os.name == \"nt\"\n+ step = 3 if is_windows else 1\n+ code = dedent(\n+ f\"\"\"\\\n+ import time\n+ for _ in range(3):\n+ time.sleep({step})\n+ print(\".\", flush=True, end=\"\")\n+ \"\"\"\n+ )\n+\n+ def print_numbers():\n+ for i in range(3):\n+ sleep(step)\n+ print(i, flush=True, end=\"\")\n+\n+ thread = Thread(target=print_numbers)\n+ thread.start()\n+ sleep(step / 2)\n+ ip.run_cell_magic(\"script\", f\"{sys.executable}\", code)\n+ thread.join()\n+\n+ captured = capsys.readouterr()\n+ # If the streaming was line-wise or broken\n+ # we would get `012...`\n+ assert captured.out == \"0.1.2.\"\n+\n+\n @magics_class\n class FooFoo(Magics):\n \"\"\"class with both %foo and %%foo magics\"\"\"\n", "FAIL_TO_PASS": ["IPython/core/tests/test_magic.py::test_script_streams_continiously"]}], "all_FAIL_TO_PASS": ["IPython/core/tests/test_magic.py::test_script_raise_on_interrupt", "IPython/core/tests/test_magic.py::test_script_streams_continiously"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "horejsek__python-fastjsonschema-88_x2", "level": 2, "source": "swerebench", "repo": "horejsek/python-fastjsonschema", "image": "swerebench/sweb.eval.x86_64.horejsek_1776_python-fastjsonschema-88:latest", "base_commit": "e845f622d6340703342a58318d94a295d86bbfaf", "num_bugs": 2, "bugs": [{"instance_id": "horejsek__python-fastjsonschema-88", "base_commit": "e845f622d6340703342a58318d94a295d86bbfaf", "gold_patch": "diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py\nindex 01cc07e..6c50a21 100644\n--- a/fastjsonschema/draft04.py\n+++ b/fastjsonschema/draft04.py\n@@ -11,7 +11,7 @@ JSON_TYPE_TO_PYTHON_TYPE = {\n 'number': 'int, float',\n 'integer': 'int',\n 'string': 'str',\n- 'array': 'list',\n+ 'array': 'list, tuple',\n 'object': 'dict',\n }\n \ndiff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py\nindex fc5b4b1..17cebd6 100644\n--- a/fastjsonschema/generator.py\n+++ b/fastjsonschema/generator.py\n@@ -281,7 +281,7 @@ class CodeGenerator:\n if variable_name in self._variables:\n return\n self._variables.add(variable_name)\n- self.l('{variable}_is_list = isinstance({variable}, list)')\n+ self.l('{variable}_is_list = isinstance({variable}, (list, tuple))')\n \n def create_variable_is_dict(self):\n \"\"\"\n", "test_patch": "diff --git a/tests/test_array.py b/tests/test_array.py\nindex 33f6a06..3d77435 100644\n--- a/tests/test_array.py\n+++ b/tests/test_array.py\n@@ -134,3 +134,35 @@ def test_different_items_without_additional_items(asserter, value, expected):\n ],\n 'additionalItems': False,\n }, value, expected)\n+\n+\n+@pytest.mark.parametrize('value, expected', [\n+ ((), ()),\n+ (('a',), ('a',)),\n+ (('a', 'b'), ('a', 'b')),\n+ (('a', 'b', 3), JsonSchemaException('data[2] must be string', value=3, name='data[2]',\n+ definition={'type': 'string'}, rule='type')),\n+])\n+def test_tuples_as_arrays(asserter, value, expected):\n+ asserter({\n+ '$schema': 'http://json-schema.org/draft-06/schema',\n+ 'type': 'array',\n+ 'items':\n+ {'type': 'string'},\n+\n+ }, value, expected)\n+\n+\n+@pytest.mark.parametrize('value, expected', [\n+ ({'a': [], 'b': ()}, {'a': [], 'b': ()}),\n+ ({'a': (1, 2), 'b': (3, 4)}, {'a': (1, 2), 'b': (3, 4)}),\n+])\n+def test_mixed_arrays(asserter, value, expected):\n+ asserter({\n+ 'type': 'object',\n+ 'properties': {\n+ 'a': {'type': 'array'},\n+ 'b': {'type': 'array'},\n+ },\n+ }, value, expected)\n+\ndiff --git a/tests/test_integration.py b/tests/test_integration.py\nindex 5ea2c08..27135f9 100644\n--- a/tests/test_integration.py\n+++ b/tests/test_integration.py\n@@ -52,6 +52,10 @@ definition = {\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'd': 'd'}, 42, 3],\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'abc', 'd': 'd'}, 42, 3],\n ),\n+ (\n+ (9, 'world', (1,), {'a': 'a', 'b': 'b', 'd': 'd'}, 42, 3),\n+ (9, 'world', (1,), {'a': 'a', 'b': 'b', 'c': 'abc', 'd': 'd'}, 42, 3),\n+ ),\n (\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'xy'}, 42, 3],\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'xy'}, 42, 3],\n", "FAIL_TO_PASS": ["tests/test_array.py::test_tuples_as_arrays[value0-expected0]", "tests/test_array.py::test_tuples_as_arrays[value1-expected1]", "tests/test_array.py::test_tuples_as_arrays[value2-expected2]", "tests/test_array.py::test_tuples_as_arrays[value3-expected3]", "tests/test_array.py::test_mixed_arrays[value0-expected0]", "tests/test_array.py::test_mixed_arrays[value1-expected1]", "tests/test_integration.py::test_integration[value2-expected2]"]}, {"instance_id": "horejsek__python-fastjsonschema-112", "base_commit": "4b0d76cb07d78f047813c6bcda01879ee0a0216c", "gold_patch": "diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py\nindex 5c40de7..b79b1f9 100644\n--- a/fastjsonschema/draft04.py\n+++ b/fastjsonschema/draft04.py\n@@ -349,8 +349,16 @@ class CodeGeneratorDraft04(CodeGenerator):\n \"\"\"\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n+ self.l(\n+ 'def fn(var): '\n+ 'return frozenset(dict((k, fn(v)) '\n+ 'for k, v in var.items()).items()) '\n+ 'if hasattr(var, \"items\") else tuple(fn(v) '\n+ 'for v in var) '\n+ 'if isinstance(var, (dict, list)) else str(var) '\n+ 'if isinstance(var, bool) else var')\n self.create_variable_with_length()\n- with self.l('if {variable}_len > len(set(str({variable}_x) for {variable}_x in {variable})):'):\n+ with self.l('if {variable}_len > len(set(fn({variable}_x) for {variable}_x in {variable})):'):\n self.exc('{name} must contain unique items', rule='uniqueItems')\n \n def generate_items(self):\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 756429e..de91132 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -13,6 +13,11 @@ from fastjsonschema import JsonSchemaException, compile\n from fastjsonschema.draft07 import CodeGeneratorDraft07\n \n \n+def pytest_configure(config):\n+ config.addinivalue_line(\"markers\", \"none\")\n+ config.addinivalue_line(\"markers\", \"benchmark\")\n+\n+\n @pytest.fixture\n def asserter():\n def f(definition, value, expected, formats={}):\ndiff --git a/tests/test_array.py b/tests/test_array.py\nindex 3d77435..19289ab 100644\n--- a/tests/test_array.py\n+++ b/tests/test_array.py\n@@ -51,6 +51,20 @@ def test_min_items(asserter, value, expected):\n ([1], [1]),\n ([1, 1], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n ([1, 2, 3], [1, 2, 3]),\n+ ([True, False], [True, False]),\n+ ([True, True], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ (['abc', 'bce', 'hhh'], ['abc', 'bce', 'hhh']),\n+ (['abc', 'abc'], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': 'a'}, {'b': 'b'}], [{'a': 'a'}, {'b': 'b'}]),\n+ ([{'a': 'a'}, {'a': 'a'}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': 'a', 'b': 'b'}, {'b': 'b', 'c': 'c'}], [{'a': 'a', 'b': 'b'}, {'b': 'b', 'c': 'c'}]),\n+ ([{'a': 'a', 'b': 'b'}, {'b': 'b', 'a': 'a'}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([1, '1'], [1, '1']),\n+ ([{'a': 'b'}, \"{'a': 'b'}\"], [{'a': 'b'}, \"{'a': 'b'}\"]),\n+ ([[1, 2], [2, 1]], [[1, 2], [2, 1]]),\n+ ([[1, 2], [1, 2]], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': {'b': {'c': [1, 2]}}}, {'a': {'b': {'c': [1, 2]}}}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': {'b': {'c': [2, 1]}}}, {'a': {'b': {'c': [1, 2]}}}], [{'a': {'b': {'c': [2, 1]}}}, {'a': {'b': {'c': [1, 2]}}}]),\n ])\n def test_unique_items(asserter, value, expected):\n asserter({\n", "FAIL_TO_PASS": ["tests/test_array.py::test_unique_items[value11-expected11]", "tests/test_array.py::test_unique_items[value12-expected12]", "tests/test_array.py::test_unique_items[value13-expected13]"]}], "all_FAIL_TO_PASS": ["tests/test_array.py::test_tuples_as_arrays[value0-expected0]", "tests/test_array.py::test_tuples_as_arrays[value1-expected1]", "tests/test_array.py::test_tuples_as_arrays[value2-expected2]", "tests/test_array.py::test_tuples_as_arrays[value3-expected3]", "tests/test_array.py::test_mixed_arrays[value0-expected0]", "tests/test_array.py::test_mixed_arrays[value1-expected1]", "tests/test_integration.py::test_integration[value2-expected2]", "tests/test_array.py::test_unique_items[value11-expected11]", "tests/test_array.py::test_unique_items[value12-expected12]", "tests/test_array.py::test_unique_items[value13-expected13]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ilevkivskyi__typing_inspect-74_x2", "level": 2, "source": "swerebench", "repo": "ilevkivskyi/typing_inspect", "image": "swerebench/sweb.eval.x86_64.ilevkivskyi_1776_typing_inspect-74:latest", "base_commit": "d1d46f4c2429dd0a60f902fa7b728d67bb2d1582", "num_bugs": 2, "bugs": [{"instance_id": "ilevkivskyi__typing_inspect-74", "base_commit": "d1d46f4c2429dd0a60f902fa7b728d67bb2d1582", "gold_patch": "diff --git a/typing_inspect.py b/typing_inspect.py\nindex c11b856..4c765e3 100644\n--- a/typing_inspect.py\n+++ b/typing_inspect.py\n@@ -467,7 +467,8 @@ def get_args(tp, evaluate=None):\n if NEW_TYPING:\n if evaluate is not None and not evaluate:\n raise ValueError('evaluate can only be True in Python >= 3.7')\n- if isinstance(tp, typingGenericAlias):\n+ # Note special aliases on Python 3.9 don't have __args__.\n+ if isinstance(tp, typingGenericAlias) and hasattr(tp, '__args__'):\n res = tp.__args__\n if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:\n res = (list(res[:-1]), res[-1])\n", "test_patch": "diff --git a/test_typing_inspect.py b/test_typing_inspect.py\nindex 58a03ee..7e9d432 100644\n--- a/test_typing_inspect.py\n+++ b/test_typing_inspect.py\n@@ -402,6 +402,8 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_args(list[int]), (int,))\n self.assertEqual(get_args(tuple[int, str]), (int, str))\n self.assertEqual(get_args(list[list[int]]), (list[int],))\n+ # This would return (~T,) before Python 3.9.\n+ self.assertEqual(get_args(List), ())\n \n def test_bound(self):\n T = TypeVar('T')\n", "FAIL_TO_PASS": ["test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated"]}, {"instance_id": "ilevkivskyi__typing_inspect-94", "base_commit": "b24da20b0f137e00cd8c511843ff52cb92dcf470", "gold_patch": "diff --git a/typing_inspect.py b/typing_inspect.py\nindex d786e96..0268b16 100644\n--- a/typing_inspect.py\n+++ b/typing_inspect.py\n@@ -408,7 +408,11 @@ def get_parameters(tp):\n else:\n return ()\n elif NEW_TYPING:\n- if (isinstance(tp, typingGenericAlias) or\n+ if (\n+ (\n+ isinstance(tp, typingGenericAlias) and\n+ hasattr(tp, '__parameters__')\n+ ) or\n isinstance(tp, type) and issubclass(tp, Generic) and\n tp is not Generic):\n return tp.__parameters__\n", "test_patch": "diff --git a/test_typing_inspect.py b/test_typing_inspect.py\nindex 9f6be56..eaea460 100644\n--- a/test_typing_inspect.py\n+++ b/test_typing_inspect.py\n@@ -14,6 +14,7 @@ from typing import (\n Union, Callable, Optional, TypeVar, Sequence, AnyStr, Mapping,\n MutableMapping, Iterable, Generic, List, Any, Dict, Tuple, NamedTuple,\n )\n+from typing import T as typing_T\n \n from mypy_extensions import TypedDict as METypedDict\n from typing_extensions import TypedDict as TETypedDict\n@@ -354,6 +355,10 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_parameters(Union), ())\n if not LEGACY_TYPING:\n self.assertEqual(get_parameters(List[int]), ())\n+ if PY39:\n+ self.assertEqual(get_parameters(List), ())\n+ else:\n+ self.assertEqual(get_parameters(List), (typing_T,))\n else:\n # in 3.5.3 a list has no __args__ and instead they are used in __parameters__\n # in 3.5.1 the behaviour is normal again.\n", "FAIL_TO_PASS": ["test_typing_inspect.py::GetUtilityTestCase::test_parameters"]}], "all_FAIL_TO_PASS": ["test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_parameters"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "kaste__mockito-python-34_x2", "level": 2, "source": "swerebench", "repo": "kaste/mockito-python", "image": "swerebench/sweb.eval.x86_64.kaste_1776_mockito-python-34:latest", "base_commit": "79ae4340635c8298a79b1d6afc8e6b0b5ce26f88", "num_bugs": 2, "bugs": [{"instance_id": "kaste__mockito-python-34", "base_commit": "79ae4340635c8298a79b1d6afc8e6b0b5ce26f88", "gold_patch": "diff --git a/mockito/mocking.py b/mockito/mocking.py\nindex 82be9b2..0955e19 100644\n--- a/mockito/mocking.py\n+++ b/mockito/mocking.py\n@@ -18,17 +18,14 @@\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n # THE SOFTWARE.\n \n-from collections import deque\n-import inspect\n import functools\n+import inspect\n import operator\n+from collections import deque\n \n-from . import invocation\n-from . import signature\n-from . import utils\n+from . import invocation, signature, utils\n from .mock_registry import mock_registry\n \n-\n __all__ = ['mock']\n \n __tracebackhide__ = operator.methodcaller(\n@@ -75,13 +72,24 @@ class Mock(object):\n # STUBBING\n \n def get_original_method(self, method_name):\n+ \"\"\"\n+ Looks up the original method on the `spec` object and returns it\n+ together with an indication of whether the method is found\n+ \"directly\" on the `spec` object.\n+\n+ This is used to decide whether the method should be stored as an\n+ original_method and should therefore be replaced when unstubbing.\n+ \"\"\"\n if self.spec is None:\n- return None\n+ return None, False\n \n try:\n- return self.spec.__dict__.get(method_name)\n- except AttributeError:\n- return getattr(self.spec, method_name, None)\n+ return self.spec.__dict__[method_name], True\n+ except (AttributeError, KeyError):\n+ # Classes with defined `__slots__` and then no `__dict__` are not\n+ # patchable but if we catch the `AttributeError` here, we get\n+ # the better error message for the user.\n+ return getattr(self.spec, method_name, None), False\n \n def set_method(self, method_name, new_method):\n setattr(self.mocked_obj, method_name, new_method)\n@@ -130,8 +138,14 @@ class Mock(object):\n try:\n self.original_methods[method_name]\n except KeyError:\n- original_method = self.get_original_method(method_name)\n- self.original_methods[method_name] = original_method\n+ original_method, was_in_spec = self.get_original_method(\n+ method_name)\n+ if was_in_spec:\n+ # This indicates the original method was found directly on\n+ # the spec object and should therefore be restored by unstub\n+ self.original_methods[method_name] = original_method\n+ else:\n+ self.original_methods[method_name] = None\n \n self.replace_method(method_name, original_method)\n \ndiff --git a/mockito/utils.py b/mockito/utils.py\nindex ed8e7c3..52e8be4 100644\n--- a/mockito/utils.py\n+++ b/mockito/utils.py\n@@ -14,10 +14,7 @@ def contains_strict(seq, element):\n \n \n def newmethod(fn, obj):\n- if PY3:\n- return types.MethodType(fn, obj)\n- else:\n- return types.MethodType(fn, obj, obj.__class__)\n+ return types.MethodType(fn, obj)\n \n \n def get_function_host(fn):\n", "test_patch": "diff --git a/tests/classmethods_test.py b/tests/classmethods_test.py\nindex 69d8cf7..0dc15bd 100644\n--- a/tests/classmethods_test.py\n+++ b/tests/classmethods_test.py\n@@ -18,10 +18,12 @@\n # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n # THE SOFTWARE.\n \n-from .test_base import TestBase\n-from mockito import when, unstub, verify\n+from mockito import unstub, verify, when\n from mockito.verification import VerificationError\n \n+from .test_base import TestBase\n+\n+\n class Dog:\n @classmethod\n def bark(cls):\n@@ -105,3 +107,122 @@ class ClassMethodsTest(TestBase):\n self.assertEqual(\"Cat foo\", Cat.meow(\"foo\"))\n \n \n+class Retriever:\n+ @classmethod\n+ def retrieve(cls, item):\n+ return item\n+\n+\n+class TrickDog(Dog, Retriever):\n+ pass\n+\n+\n+class InheritedClassMethodsTest(TestBase):\n+\n+ def tearDown(self):\n+ unstub()\n+\n+ def testUnstubs(self):\n+ when(TrickDog).bark().thenReturn(\"miau!\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"ball\")\n+ unstub()\n+ self.assertEqual(\"woof!\", TrickDog.bark())\n+ self.assertEqual(\"stick\", TrickDog.retrieve(\"stick\"))\n+\n+ def testStubs(self):\n+ self.assertEqual(\"woof!\", TrickDog.bark())\n+ self.assertEqual(\"stick\", TrickDog.retrieve(\"stick\"))\n+\n+ when(TrickDog).bark().thenReturn(\"miau!\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"ball\")\n+\n+ self.assertEqual(\"miau!\", TrickDog.bark())\n+ self.assertEqual(\"ball\", TrickDog.retrieve(\"stick\"))\n+\n+ def testVerifiesMultipleCallsOnClassmethod(self):\n+ when(TrickDog).bark().thenReturn(\"miau!\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"ball\")\n+\n+ TrickDog.bark()\n+ TrickDog.bark()\n+\n+ TrickDog.retrieve(\"stick\")\n+ TrickDog.retrieve(\"stick\")\n+\n+ verify(TrickDog, times=2).bark()\n+ verify(TrickDog, times=2).retrieve(\"stick\")\n+\n+ def testFailsVerificationOfMultipleCallsOnClassmethod(self):\n+ when(TrickDog).bark().thenReturn(\"miau!\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"bark\")\n+\n+ TrickDog.bark()\n+ TrickDog.retrieve(\"stick\")\n+\n+ self.assertRaises(VerificationError, verify(TrickDog, times=2).bark)\n+ self.assertRaises(VerificationError, verify(TrickDog,\n+ times=2).retrieve)\n+\n+ def testStubsAndVerifiesClassmethod(self):\n+ when(TrickDog).bark().thenReturn(\"miau!\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"ball\")\n+\n+ self.assertEqual(\"miau!\", TrickDog.bark())\n+ self.assertEqual(\"ball\", TrickDog.retrieve(\"stick\"))\n+\n+ verify(TrickDog).bark()\n+ verify(TrickDog).retrieve(\"stick\")\n+\n+ def testPreservesSuperClassClassMethodWhenStubbed(self):\n+ self.assertEqual(\"woof!\", Dog.bark())\n+ self.assertEqual(\"stick\", Retriever.retrieve(\"stick\"))\n+\n+ self.assertEqual(\"woof!\", TrickDog.bark())\n+ self.assertEqual(\"stick\", TrickDog.retrieve(\"stick\"))\n+\n+ when(TrickDog).bark().thenReturn(\"miau!\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"ball\")\n+\n+ self.assertEqual(\"miau!\", TrickDog.bark())\n+ self.assertEqual(\"ball\", TrickDog.retrieve(\"stick\"))\n+\n+ self.assertEqual(\"woof!\", Dog.bark())\n+ self.assertEqual(\"stick\", Retriever.retrieve(\"stick\"))\n+\n+ def testDoubleStubStubWorksAfterUnstub(self):\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"ball\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"cat\")\n+ unstub()\n+ self.assertEqual(\"stick\", TrickDog.retrieve(\"stick\"))\n+\n+ def testUnStubWorksOnClassAndSuperClass(self):\n+ self.assertEqual(\"stick\", Retriever.retrieve(\"stick\"))\n+ self.assertEqual(\"stick\", TrickDog.retrieve(\"stick\"))\n+\n+ when(Retriever).retrieve(\"stick\").thenReturn(\"ball\")\n+ self.assertEqual(\"ball\", Retriever.retrieve(\"stick\"))\n+ self.assertEqual(\"ball\", TrickDog.retrieve(\"stick\"))\n+\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"cat\")\n+ self.assertEqual(\"ball\", Retriever.retrieve(\"stick\"))\n+ self.assertEqual(\"cat\", TrickDog.retrieve(\"stick\"))\n+\n+ unstub(TrickDog)\n+ self.assertEqual(\"ball\", Retriever.retrieve(\"stick\"))\n+ self.assertEqual(\"ball\", TrickDog.retrieve(\"stick\"))\n+\n+ unstub(Retriever)\n+ self.assertEqual(\"stick\", Retriever.retrieve(\"stick\"))\n+ self.assertEqual(\"stick\", TrickDog.retrieve(\"stick\"))\n+\n+ def testReverseOrderWhenUnstubbing(self):\n+ when(Retriever).retrieve(\"stick\").thenReturn(\"ball\")\n+ when(TrickDog).retrieve(\"stick\").thenReturn(\"cat\")\n+\n+ unstub(Retriever)\n+ self.assertEqual(\"stick\", Retriever.retrieve(\"stick\"))\n+ self.assertEqual(\"cat\", TrickDog.retrieve(\"stick\"))\n+\n+ unstub(TrickDog)\n+ self.assertEqual(\"stick\", Retriever.retrieve(\"stick\"))\n+ self.assertEqual(\"stick\", TrickDog.retrieve(\"stick\"))\n", "FAIL_TO_PASS": ["tests/classmethods_test.py::InheritedClassMethodsTest::testFailsVerificationOfMultipleCallsOnClassmethod", "tests/classmethods_test.py::InheritedClassMethodsTest::testPreservesSuperClassClassMethodWhenStubbed", "tests/classmethods_test.py::InheritedClassMethodsTest::testReverseOrderWhenUnstubbing", "tests/classmethods_test.py::InheritedClassMethodsTest::testStubs", "tests/classmethods_test.py::InheritedClassMethodsTest::testStubsAndVerifiesClassmethod", "tests/classmethods_test.py::InheritedClassMethodsTest::testUnStubWorksOnClassAndSuperClass", "tests/classmethods_test.py::InheritedClassMethodsTest::testVerifiesMultipleCallsOnClassmethod"]}, {"instance_id": "kaste__mockito-python-54", "base_commit": "699294f903025623a241a0259cf4c770614c61f2", "gold_patch": "diff --git a/mockito/mocking.py b/mockito/mocking.py\nindex e52db5e..7ac5c8c 100644\n--- a/mockito/mocking.py\n+++ b/mockito/mocking.py\n@@ -180,8 +180,11 @@ class Mock(object):\n # the one on its class, so we delete as well.\n if (\n not original_method\n- or not inspect.isclass(self.mocked_obj)\n- and inspect.ismethod(original_method)\n+ or (\n+ inspect.ismethod(original_method)\n+ and not inspect.isclass(self.mocked_obj)\n+ and not inspect.ismodule(self.mocked_obj)\n+ )\n ):\n delattr(self.mocked_obj, method_name)\n else:\n", "test_patch": "diff --git a/tests/modulefunctions_test.py b/tests/modulefunctions_test.py\nindex 6d8728f..d1429e1 100644\n--- a/tests/modulefunctions_test.py\n+++ b/tests/modulefunctions_test.py\n@@ -98,3 +98,10 @@ class ModuleFunctionsTest(TestBase):\n from . import module\n when(module).Foo().thenReturn('mocked')\n assert module.Foo() == 'mocked'\n+\n+ def testUnstubFunctionOnModuleWhichIsActuallyAMethod_issue_53(self):\n+ import random\n+ when(random).randint(...).thenReturn(\"mocked\")\n+ assert random.randint(1, 10) == \"mocked\"\n+ unstub(random)\n+ assert random.randint(1, 10) != \"mocked\"\n", "FAIL_TO_PASS": ["tests/modulefunctions_test.py::ModuleFunctionsTest::testUnstubFunctionOnModuleWhichIsActuallyAMethod_issue_53"]}], "all_FAIL_TO_PASS": ["tests/classmethods_test.py::InheritedClassMethodsTest::testFailsVerificationOfMultipleCallsOnClassmethod", "tests/classmethods_test.py::InheritedClassMethodsTest::testPreservesSuperClassClassMethodWhenStubbed", "tests/classmethods_test.py::InheritedClassMethodsTest::testReverseOrderWhenUnstubbing", "tests/classmethods_test.py::InheritedClassMethodsTest::testStubs", "tests/classmethods_test.py::InheritedClassMethodsTest::testStubsAndVerifiesClassmethod", "tests/classmethods_test.py::InheritedClassMethodsTest::testUnStubWorksOnClassAndSuperClass", "tests/classmethods_test.py::InheritedClassMethodsTest::testVerifiesMultipleCallsOnClassmethod", "tests/modulefunctions_test.py::ModuleFunctionsTest::testUnstubFunctionOnModuleWhichIsActuallyAMethod_issue_53"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jpadilla__pyjwt-670_x2", "level": 2, "source": "swerebench", "repo": "jpadilla/pyjwt", "image": "swerebench/sweb.eval.x86_64.jpadilla_1776_pyjwt-670:latest", "base_commit": "db18661724305f7bc0663e738759222158900bb8", "num_bugs": 2, "bugs": [{"instance_id": "jpadilla__pyjwt-670", "base_commit": "db18661724305f7bc0663e738759222158900bb8", "gold_patch": "diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml\nindex 2c33e32..632d7f9 100644\n--- a/.pre-commit-config.yaml\n+++ b/.pre-commit-config.yaml\n@@ -1,6 +1,6 @@\n repos:\n - repo: https://github.com/psf/black\n- rev: 21.6b0\n+ rev: 21.7b0\n hooks:\n - id: black\n args: [\"--target-version=py36\"]\n@@ -18,7 +18,7 @@ repos:\n language_version: python3.8\n \n - repo: https://github.com/PyCQA/isort\n- rev: 5.8.0\n+ rev: 5.9.2\n hooks:\n - id: isort\n \ndiff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex b138569..763822a 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -13,6 +13,8 @@ Changed\n Fixed\n ~~~~~\n \n+- Fix aud validation to support {'aud': null} case. `#670 `__\n+\n Added\n ~~~~~\n \ndiff --git a/jwt/api_jwt.py b/jwt/api_jwt.py\nindex 70a5e53..55a8f29 100644\n--- a/jwt/api_jwt.py\n+++ b/jwt/api_jwt.py\n@@ -177,19 +177,18 @@ class PyJWT:\n raise ExpiredSignatureError(\"Signature has expired\")\n \n def _validate_aud(self, payload, audience):\n- if audience is None and \"aud\" not in payload:\n- return\n+ if audience is None:\n+ if \"aud\" not in payload or not payload[\"aud\"]:\n+ return\n+ # Application did not specify an audience, but\n+ # the token has the 'aud' claim\n+ raise InvalidAudienceError(\"Invalid audience\")\n \n- if audience is not None and \"aud\" not in payload:\n+ if \"aud\" not in payload or not payload[\"aud\"]:\n # Application specified an audience, but it could not be\n # verified since the token does not contain a claim.\n raise MissingRequiredClaimError(\"aud\")\n \n- if audience is None and \"aud\" in payload:\n- # Application did not specify an audience, but\n- # the token has the 'aud' claim\n- raise InvalidAudienceError(\"Invalid audience\")\n-\n audience_claims = payload[\"aud\"]\n \n if isinstance(audience_claims, str):\n", "test_patch": "diff --git a/tests/test_api_jwt.py b/tests/test_api_jwt.py\nindex 56de90c..1faa05f 100644\n--- a/tests/test_api_jwt.py\n+++ b/tests/test_api_jwt.py\n@@ -202,6 +202,16 @@ class TestJWT:\n with pytest.raises(DecodeError):\n jwt.decode(example_jwt, \"secret\", algorithms=[\"HS256\"])\n \n+ def test_decode_raises_exception_if_aud_is_none(self, jwt):\n+ # >>> jwt.encode({'aud': None}, 'secret')\n+ example_jwt = (\n+ \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.\"\n+ \"eyJhdWQiOm51bGx9.\"\n+ \"-Peqc-pTugGvrc5C8Bnl0-X1V_5fv-aVb_7y7nGBVvQ\"\n+ )\n+ decoded = jwt.decode(example_jwt, \"secret\", algorithms=[\"HS256\"])\n+ assert decoded[\"aud\"] is None\n+\n def test_encode_datetime(self, jwt):\n secret = \"secret\"\n current_datetime = datetime.utcnow()\n@@ -413,6 +423,15 @@ class TestJWT:\n \n assert exc.value.claim == \"aud\"\n \n+ def test_raise_exception_token_with_aud_none_and_without_audience(self, jwt):\n+ payload = {\"some\": \"payload\", \"aud\": None}\n+ token = jwt.encode(payload, \"secret\")\n+\n+ with pytest.raises(MissingRequiredClaimError) as exc:\n+ jwt.decode(token, \"secret\", audience=\"urn:me\", algorithms=[\"HS256\"])\n+\n+ assert exc.value.claim == \"aud\"\n+\n def test_check_issuer_when_valid(self, jwt):\n issuer = \"urn:foo\"\n payload = {\"some\": \"payload\", \"iss\": \"urn:foo\"}\n", "FAIL_TO_PASS": ["tests/test_api_jwt.py::TestJWT::test_decode_raises_exception_if_aud_is_none", "tests/test_api_jwt.py::TestJWT::test_raise_exception_token_with_aud_none_and_without_audience"]}, {"instance_id": "jpadilla__pyjwt-673", "base_commit": "c8ab900b831c4e859620c964d25737bf95d5eeb8", "gold_patch": "diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml\nindex 632d7f9..505e374 100644\n--- a/.pre-commit-config.yaml\n+++ b/.pre-commit-config.yaml\n@@ -18,7 +18,7 @@ repos:\n language_version: python3.8\n \n - repo: https://github.com/PyCQA/isort\n- rev: 5.9.2\n+ rev: 5.9.3\n hooks:\n - id: isort\n \ndiff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 763822a..b049e9e 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -13,6 +13,7 @@ Changed\n Fixed\n ~~~~~\n \n+- Prefer `headers[\"alg\"]` to `algorithm` in `jwt.encode()`. `#673 `__\n - Fix aud validation to support {'aud': null} case. `#670 `__\n \n Added\ndiff --git a/docs/api.rst b/docs/api.rst\nindex d23d4bd..f1720b9 100644\n--- a/docs/api.rst\n+++ b/docs/api.rst\n@@ -13,8 +13,9 @@ API Reference\n * for **asymmetric algorithms**: PEM-formatted private key, a multiline string\n * for **symmetric algorithms**: plain string, sufficiently long for security\n \n- :param str algorithm: algorithm to sign the token with, e.g. ``\"ES256\"``\n- :param dict headers: additional JWT header fields, e.g. ``dict(kid=\"my-key-id\")``\n+ :param str algorithm: algorithm to sign the token with, e.g. ``\"ES256\"``.\n+ If ``headers`` includes ``alg``, it will be preferred to this parameter.\n+ :param dict headers: additional JWT header fields, e.g. ``dict(kid=\"my-key-id\")``.\n :param json.JSONEncoder json_encoder: custom JSON encoder for ``payload`` and ``headers``\n :rtype: str\n :returns: a JSON Web Token\ndiff --git a/jwt/api_jws.py b/jwt/api_jws.py\nindex 6d13699..6cefb2c 100644\n--- a/jwt/api_jws.py\n+++ b/jwt/api_jws.py\n@@ -77,7 +77,7 @@ class PyJWS:\n self,\n payload: bytes,\n key: str,\n- algorithm: str = \"HS256\",\n+ algorithm: Optional[str] = \"HS256\",\n headers: Optional[Dict] = None,\n json_encoder: Optional[Type[json.JSONEncoder]] = None,\n ) -> str:\n@@ -86,6 +86,10 @@ class PyJWS:\n if algorithm is None:\n algorithm = \"none\"\n \n+ # Prefer headers[\"alg\"] if present to algorithm parameter.\n+ if headers and \"alg\" in headers and headers[\"alg\"]:\n+ algorithm = headers[\"alg\"]\n+\n if algorithm not in self._valid_algs:\n pass\n \ndiff --git a/jwt/api_jwt.py b/jwt/api_jwt.py\nindex 55a8f29..48a9316 100644\n--- a/jwt/api_jwt.py\n+++ b/jwt/api_jwt.py\n@@ -38,7 +38,7 @@ class PyJWT:\n self,\n payload: Dict[str, Any],\n key: str,\n- algorithm: str = \"HS256\",\n+ algorithm: Optional[str] = \"HS256\",\n headers: Optional[Dict] = None,\n json_encoder: Optional[Type[json.JSONEncoder]] = None,\n ) -> str:\n", "test_patch": "diff --git a/tests/test_api_jws.py b/tests/test_api_jws.py\nindex b731edc..fbeda02 100644\n--- a/tests/test_api_jws.py\n+++ b/tests/test_api_jws.py\n@@ -166,6 +166,32 @@ class TestJWS:\n exception = context.value\n assert str(exception) == \"Algorithm not supported\"\n \n+ def test_encode_with_headers_alg_none(self, jws, payload):\n+ msg = jws.encode(payload, key=None, headers={\"alg\": \"none\"})\n+ with pytest.raises(DecodeError) as context:\n+ jws.decode(msg, algorithms=[\"none\"])\n+ assert str(context.value) == \"Signature verification failed\"\n+\n+ @crypto_required\n+ def test_encode_with_headers_alg_es256(self, jws, payload):\n+ with open(key_path(\"testkey_ec.priv\"), \"rb\") as ec_priv_file:\n+ priv_key = load_pem_private_key(ec_priv_file.read(), password=None)\n+ with open(key_path(\"testkey_ec.pub\"), \"rb\") as ec_pub_file:\n+ pub_key = load_pem_public_key(ec_pub_file.read())\n+\n+ msg = jws.encode(payload, priv_key, headers={\"alg\": \"ES256\"})\n+ assert b\"hello world\" == jws.decode(msg, pub_key, algorithms=[\"ES256\"])\n+\n+ @crypto_required\n+ def test_encode_with_alg_hs256_and_headers_alg_es256(self, jws, payload):\n+ with open(key_path(\"testkey_ec.priv\"), \"rb\") as ec_priv_file:\n+ priv_key = load_pem_private_key(ec_priv_file.read(), password=None)\n+ with open(key_path(\"testkey_ec.pub\"), \"rb\") as ec_pub_file:\n+ pub_key = load_pem_public_key(ec_pub_file.read())\n+\n+ msg = jws.encode(payload, priv_key, algorithm=\"HS256\", headers={\"alg\": \"ES256\"})\n+ assert b\"hello world\" == jws.decode(msg, pub_key, algorithms=[\"ES256\"])\n+\n def test_decode_algorithm_param_should_be_case_sensitive(self, jws):\n example_jws = (\n \"eyJhbGciOiJoczI1NiIsInR5cCI6IkpXVCJ9\" # alg = hs256\n", "FAIL_TO_PASS": ["tests/test_api_jws.py::TestJWS::test_encode_with_headers_alg_none", "tests/test_api_jws.py::TestJWS::test_encode_with_headers_alg_es256", "tests/test_api_jws.py::TestJWS::test_encode_with_alg_hs256_and_headers_alg_es256"]}], "all_FAIL_TO_PASS": ["tests/test_api_jwt.py::TestJWT::test_decode_raises_exception_if_aud_is_none", "tests/test_api_jwt.py::TestJWT::test_raise_exception_token_with_aud_none_and_without_audience", "tests/test_api_jws.py::TestJWS::test_encode_with_headers_alg_none", "tests/test_api_jws.py::TestJWS::test_encode_with_headers_alg_es256", "tests/test_api_jws.py::TestJWS::test_encode_with_alg_hs256_and_headers_alg_es256"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jboss-dockerfiles__dogen-149_x2", "level": 2, "source": "swerebench", "repo": "jboss-dockerfiles/dogen", "image": "swerebench/sweb.eval.x86_64.jboss-dockerfiles_1776_dogen-149:latest", "base_commit": "a475173ce00b2d6686c601ffc46a8d2bc3ed0a7f", "num_bugs": 2, "bugs": [{"instance_id": "jboss-dockerfiles__dogen-149", "base_commit": "a475173ce00b2d6686c601ffc46a8d2bc3ed0a7f", "gold_patch": "diff --git a/dogen/generator.py b/dogen/generator.py\nindex 0562cd8..415dcb0 100644\n--- a/dogen/generator.py\n+++ b/dogen/generator.py\n@@ -313,9 +313,10 @@ class Generator(object):\n algorithms.append(supported_algorithm)\n \n try:\n- if os.path.exists(filename) and algorithms:\n- for algorithm in algorithms:\n- self.check_sum(filename, source[algorithm], algorithm)\n+ if os.path.exists(filename):\n+ if algorithms:\n+ for algorithm in algorithms:\n+ self.check_sum(filename, source[algorithm], algorithm)\n passed = True\n except Exception as e:\n self.log.debug(str(e))\n@@ -361,7 +362,7 @@ class Generator(object):\n else:\n if hint:\n self.log.info(hint)\n- self.log.info(\"Please download the '%s' artifact manually and save it as '%s'\" % (artifact, filename))\n+ self.log.info(\"Please download the '%s' artifact manually and save it as '%s'\" % (artifact, filename))\n raise Error(\"Artifact '%s' could not be fetched!\" % artifact)\n \n def check_sum(self, filename, checksum, algorithm):\n", "test_patch": "diff --git a/tests/test_unit_generate_handle_files.py b/tests/test_unit_generate_handle_files.py\nindex daf240a..e811ebb 100644\n--- a/tests/test_unit_generate_handle_files.py\n+++ b/tests/test_unit_generate_handle_files.py\n@@ -155,6 +155,17 @@ class TestHandleSources(unittest.TestCase):\n self.assertEquals(str(cm.exception), \"Could not download artifact from orignal location, reason: original\")\n mock_fetch_file.assert_has_calls([mock.call('http://cache/get?#algorithm#=#hash#', 'target/jboss-eap.zip'), mock.call('http://host.com/jboss-eap.zip', 'target/jboss-eap.zip')])\n \n+ @mock.patch('dogen.generator.Generator._fetch_file')\n+ def test_fetch_artifact_should_fail_with_nice_message_when_artifact_without_url_is_not_found_locally(self, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'jboss-eap.zip'}]}\n+\n+ with self.assertRaises(Error) as cm:\n+ self.generator.handle_sources()\n+\n+ self.assertEquals(str(cm.exception), \"Artifact 'jboss-eap.zip' could not be fetched!\")\n+ mock_fetch_file.assert_not_called()\n+ self.log.info.assert_any_call(\"Please download the 'jboss-eap.zip' artifact manually and save it as 'target/jboss-eap.zip'\")\n+\n @mock.patch('dogen.generator.Generator._fetch_file')\n def test_fetch_artifact_should_fetch_file_from_cache(self, mock_fetch_file):\n self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n@@ -169,7 +180,8 @@ class TestHandleSources(unittest.TestCase):\n mock_fetch_file.assert_called_with('http://cache/get?jboss-eap.zip', 'target/jboss-eap.zip')\n \n @mock.patch('dogen.generator.Generator._fetch_file')\n- def test_fetch_artifact_should_fetch_file(self, mock_fetch_file):\n+ @mock.patch('dogen.generator.os.path.exists', return_value=False)\n+ def test_fetch_artifact_should_fetch_file(self, mock_path_exists, mock_fetch_file):\n self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n self.generator.handle_sources()\n # No checksum provided and computed\n@@ -187,3 +199,12 @@ class TestHandleSources(unittest.TestCase):\n \n self.assertEquals(self.generator.cfg['artifacts'], {'jboss-eap.zip': None})\n mock_fetch_file.assert_has_calls([mock.call('http://cache/get?#algorithm#=#hash#', 'target/jboss-eap.zip'), mock.call('http://host.com/jboss-eap.zip', 'target/jboss-eap.zip')])\n+\n+ @mock.patch('dogen.generator.Generator._fetch_file')\n+ @mock.patch('dogen.generator.os.path.exists', return_value=True)\n+ def test_fetch_artifact_should_not_fetch_file_if_exists(self, mock_path_exists, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n+ self.generator.handle_sources()\n+ # No checksum provided and computed\n+ self.assertEquals(self.generator.cfg['artifacts'], {'jboss-eap.zip': None})\n+ mock_fetch_file.assert_not_called()\n", "FAIL_TO_PASS": ["tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_with_nice_message_when_artifact_without_url_is_not_found_locally", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_not_fetch_file_if_exists"]}, {"instance_id": "jboss-dockerfiles__dogen-196", "base_commit": "611898a32fca936d5a45368f049c1e3f74ea3c2f", "gold_patch": "diff --git a/dogen/generator.py b/dogen/generator.py\nindex 1106f49..3a13051 100644\n--- a/dogen/generator.py\n+++ b/dogen/generator.py\n@@ -232,13 +232,24 @@ class Generator(object):\n if not self.cfg.get('labels'):\n self.cfg['labels'] = []\n \n+ labels = {}\n+\n+ for label in self.cfg.get('labels'):\n+ labels[label['name']] = label['value']\n+\n # https://github.com/jboss-dockerfiles/dogen/issues/129\n # https://github.com/jboss-dockerfiles/dogen/issues/137\n for label in ['maintainer', 'description']:\n value = self.cfg.get(label)\n \n- if value:\n+ if value and not label in labels:\n self.cfg['labels'].append({'name': label, 'value': value})\n+ labels[label] = value\n+\n+ # https://github.com/jboss-dockerfiles/dogen/issues/195\n+ if 'summary' not in labels:\n+ if 'description' in labels:\n+ self.cfg['labels'].append({'name': 'summary', 'value': labels.get('description')})\n \n if self.template:\n template_file = self.template\n", "test_patch": "diff --git a/tests/test_dockerfile.py b/tests/test_dockerfile.py\nindex 3ab2885..9f34741 100644\n--- a/tests/test_dockerfile.py\n+++ b/tests/test_dockerfile.py\n@@ -170,7 +170,7 @@ class TestDockerfile(unittest.TestCase):\n generator.configure()\n generator.render_from_template()\n \n- self.assertEqual(generator.cfg['labels'], [{'name': 'description', 'value': 'This is a nice image'}])\n+ self.assertEqual(generator.cfg['labels'], [{'name': 'description', 'value': 'This is a nice image'}, {'name': 'summary', 'value': 'This is a nice image'}])\n \n with open(os.path.join(self.target, \"Dockerfile\"), \"r\") as f:\n dockerfile = f.read()\n", "FAIL_TO_PASS": ["tests/test_dockerfile.py::TestDockerfile::test_generating_description_label"]}], "all_FAIL_TO_PASS": ["tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_with_nice_message_when_artifact_without_url_is_not_found_locally", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_not_fetch_file_if_exists", "tests/test_dockerfile.py::TestDockerfile::test_generating_description_label"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "bvanelli__actualpy-47_x2", "level": 2, "source": "swerebench", "repo": "bvanelli/actualpy", "image": "swerebench/sweb.eval.x86_64.bvanelli_1776_actualpy-47:latest", "base_commit": "c59a360127c47b906e1a5d7a98974b3b3bcdda08", "num_bugs": 2, "bugs": [{"instance_id": "bvanelli__actualpy-47", "base_commit": "c59a360127c47b906e1a5d7a98974b3b3bcdda08", "gold_patch": "diff --git a/README.md b/README.md\nindex 3096b70..5c93e5b 100644\n--- a/README.md\n+++ b/README.md\n@@ -48,6 +48,22 @@ with Actual(\n print(t.date, account_name, t.notes, t.amount, category)\n ```\n \n+The `file` will be matched to either one of the following:\n+\n+- The name of the budget, found top the top left cornet\n+- The ID of the budget, a UUID that is only available if you inspect the result of the method `list_user_files`\n+- The Sync ID of the budget, a UUID available on the frontend on the \"Advanced options\"\n+- If none of those options work for you, you can search for the file manually with `list_user_files` and provide the\n+object directly:\n+\n+```python\n+from actual import Actual\n+\n+with Actual(\"http://localhost:5006\", password=\"mypass\") as actual:\n+ actual.set_file(actual.list_user_files().data[0])\n+ actual.download_budget()\n+```\n+\n ## Adding new transactions\n \n After you created your first budget (or when updating an existing budget), you can add new transactions by adding them\n@@ -80,6 +96,30 @@ Will produce:\n \n ![added-transaction](https://github.com/bvanelli/actualpy/blob/main/docs/static/added-transaction.png?raw=true)\n \n+## Updating existing transactions\n+\n+You may also update transactions using the SQLModel directly, you just need to make sure to commit the results at the\n+end:\n+\n+```python\n+from actual import Actual\n+from actual.queries import get_transactions\n+\n+\n+with Actual(base_url=\"http://localhost:5006\", password=\"mypass\", file=\"My budget\") as actual:\n+ for transaction in get_transactions(actual.session):\n+ # change the transactions notes\n+ if transaction.notes is not None and \"my pattern\" in transaction.notes:\n+ transaction.notes = transaction.notes + \" my suffix!\"\n+ # commit your changes!\n+ actual.commit()\n+\n+```\n+\n+> **WARNING:** You can also modify the relationships, for example the `transaction.payee.name`, but you to be aware that\n+> this payee might be used for more than one transaction. Whenever the relationship is anything but 1:1, you have to\n+> track the changes already done to prevent modifying a field twice.\n+\n ## Generating backups\n \n You can use actualpy to generate regular backups of your server files. Here is a script that will backup your server\ndiff --git a/actual/__init__.py b/actual/__init__.py\nindex 385059e..3ae112c 100644\n--- a/actual/__init__.py\n+++ b/actual/__init__.py\n@@ -103,8 +103,11 @@ class Actual(ActualServer):\n return self._session\n \n def set_file(self, file_id: Union[str, RemoteFileListDTO]) -> RemoteFileListDTO:\n- \"\"\"Sets the file id for the class for further requests. The file_id argument can be either a name or remote\n- id from the file. If the name is provided, only the first match is taken.\"\"\"\n+ \"\"\"\n+ Sets the file id for the class for further requests. The file_id argument can be either the name, the remote\n+ id or the group id (also known as sync_id) from the file. If there are duplicates for the name, this method\n+ will raise `UnknownFileId`.\n+ \"\"\"\n if isinstance(file_id, RemoteFileListDTO):\n self._file = file_id\n return file_id\n@@ -112,7 +115,7 @@ class Actual(ActualServer):\n selected_files = []\n user_files = self.list_user_files()\n for file in user_files.data:\n- if (file.file_id == file_id or file.name == file_id) and file.deleted == 0:\n+ if (file.file_id == file_id or file.name == file_id or file.group_id == file_id) and file.deleted == 0:\n selected_files.append(file)\n if len(selected_files) == 0:\n raise UnknownFileId(f\"Could not find a file id or identifier '{file_id}'\")\ndiff --git a/actual/queries.py b/actual/queries.py\nindex e66b849..4714377 100644\n--- a/actual/queries.py\n+++ b/actual/queries.py\n@@ -585,7 +585,7 @@ def get_ruleset(s: Session) -> RuleSet:\n for rule in get_rules(s):\n conditions = TypeAdapter(list[Condition]).validate_json(rule.conditions)\n actions = TypeAdapter(list[Action]).validate_json(rule.actions)\n- rs = Rule(conditions=conditions, operation=rule.conditions_op, actions=actions, stage=rule.stage)\n+ rs = Rule(conditions=conditions, operation=rule.conditions_op, actions=actions, stage=rule.stage) # noqa\n rule_set.append(rs)\n return RuleSet(rules=rule_set)\n \ndiff --git a/actual/rules.py b/actual/rules.py\nindex 83f72a9..6147b85 100644\n--- a/actual/rules.py\n+++ b/actual/rules.py\n@@ -33,6 +33,26 @@ class ActionType(enum.Enum):\n LINK_SCHEDULE = \"link-schedule\"\n \n \n+class BetweenValue(pydantic.BaseModel):\n+ \"\"\"Used for `isbetween` rules.\"\"\"\n+\n+ num_1: typing.Union[int, float] = pydantic.Field(alias=\"num1\")\n+ num_2: typing.Union[int, float] = pydantic.Field(alias=\"num2\")\n+\n+ def __str__(self):\n+ return f\"({self.num_1}, {self.num_2})\"\n+\n+ @pydantic.model_validator(mode=\"after\")\n+ def convert_value(self):\n+ if isinstance(self.num_1, float):\n+ self.num_1 = int(self.num_1 * 100)\n+ if isinstance(self.num_2, float):\n+ self.num_2 = int(self.num_2 * 100)\n+ # sort the values\n+ self.num_1, self.num_2 = sorted((self.num_1, self.num_2))\n+ return self\n+\n+\n class ValueType(enum.Enum):\n DATE = \"date\"\n ID = \"id\"\n@@ -56,9 +76,9 @@ class ValueType(enum.Enum):\n # must be BOOLEAN\n return operation.value in (\"is\",)\n \n- def validate(self, value: typing.Union[int, list[str], str, None], as_list: bool = False) -> bool:\n- if isinstance(value, list) and as_list:\n- return all(self.validate(v) for v in value)\n+ def validate(self, value: typing.Union[int, list[str], str, None], operation: ConditionType = None) -> bool:\n+ if isinstance(value, list) and operation in (ConditionType.ONE_OF, ConditionType.NOT_ONE_OF):\n+ return all(self.validate(v, None) for v in value)\n if value is None:\n return True\n if self == ValueType.ID:\n@@ -73,7 +93,10 @@ class ValueType(enum.Enum):\n res = False\n return res\n elif self == ValueType.NUMBER:\n- return isinstance(value, int)\n+ if operation == ConditionType.IS_BETWEEN:\n+ return isinstance(value, BetweenValue)\n+ else:\n+ return isinstance(value, int)\n else:\n # must be BOOLEAN\n return isinstance(value, bool)\n@@ -113,7 +136,7 @@ def get_value(\n def condition_evaluation(\n op: ConditionType,\n true_value: typing.Union[int, list[str], str, datetime.date, None],\n- self_value: typing.Union[int, list[str], str, datetime.date, None],\n+ self_value: typing.Union[int, list[str], str, datetime.date, BetweenValue, None],\n options: dict = None,\n ) -> bool:\n \"\"\"Helper function to evaluate the condition based on the true_value, value found on the transaction, and the\n@@ -147,10 +170,14 @@ def condition_evaluation(\n # https://github.com/actualbudget/actual/blob/243703b2f70532ec1acbd3088dda879b5d07a5b3/packages/loot-core/src/shared/rules.ts#L261-L263\n interval = round(abs(self_value) * 0.075, 2)\n return self_value - interval <= true_value <= self_value + interval\n- elif op in (ConditionType.ONE_OF, ConditionType.CONTAINS):\n+ elif op == ConditionType.ONE_OF:\n return true_value in self_value\n- elif op in (ConditionType.NOT_ONE_OF, ConditionType.DOES_NOT_CONTAIN):\n+ elif op == ConditionType.CONTAINS:\n+ return self_value in true_value\n+ elif op == ConditionType.NOT_ONE_OF:\n return true_value not in self_value\n+ elif op == ConditionType.DOES_NOT_CONTAIN:\n+ return self_value not in true_value\n elif op == ConditionType.GT:\n return true_value > self_value\n elif op == ConditionType.GTE:\n@@ -159,6 +186,8 @@ def condition_evaluation(\n return self_value > true_value\n elif op == ConditionType.LTE:\n return self_value >= true_value\n+ elif op == ConditionType.IS_BETWEEN:\n+ return self_value.num_1 <= true_value <= self_value.num_2\n else:\n raise ActualError(f\"Operation {op} not supported\")\n \n@@ -198,7 +227,9 @@ class Condition(pydantic.BaseModel):\n \"amount_outflow\",\n ]\n op: ConditionType\n- value: typing.Union[int, float, str, list[str], Schedule, list[BaseModel], BaseModel, datetime.date, None]\n+ value: typing.Union[\n+ int, float, str, list[str], Schedule, list[BaseModel], BetweenValue, BaseModel, datetime.date, None\n+ ]\n type: typing.Optional[ValueType] = None\n options: typing.Optional[dict] = None\n \n@@ -240,8 +271,7 @@ class Condition(pydantic.BaseModel):\n elif isinstance(self.value, list) and len(self.value) and isinstance(self.value[0], pydantic.BaseModel):\n self.value = [v.id if hasattr(v, \"id\") else v for v in self.value]\n # make sure the data matches the value type\n- as_list = self.op in (ConditionType.IS_BETWEEN, ConditionType.ONE_OF, ConditionType.NOT_ONE_OF)\n- if not self.type.validate(self.value, as_list=as_list):\n+ if not self.type.validate(self.value, self.op):\n raise ValueError(f\"Value {self.value} is not valid for type {self.type.name} and operation {self.op.name}\")\n return self\n \n", "test_patch": "diff --git a/tests/test_rules.py b/tests/test_rules.py\nindex ab3d684..fce1352 100644\n--- a/tests/test_rules.py\n+++ b/tests/test_rules.py\n@@ -73,6 +73,18 @@ def test_datetime_rule():\n assert Condition(field=\"date\", op=\"lt\", value=target_date + datetime.timedelta(days=1)).run(t) is True\n \n \n+def test_string_condition():\n+ mock = MagicMock()\n+ acct = create_account(mock, \"Bank\")\n+ t = create_transaction(mock, datetime.date(2024, 1, 1), acct, \"\", \"foo\")\n+ assert Condition(field=\"notes\", op=\"oneOf\", value=[\"foo\", \"bar\"]).run(t) is True\n+ assert Condition(field=\"notes\", op=\"notOneOf\", value=[\"foo\", \"bar\"]).run(t) is False\n+ assert Condition(field=\"notes\", op=\"contains\", value=\"fo\").run(t) is True\n+ assert Condition(field=\"notes\", op=\"contains\", value=\"foobar\").run(t) is False\n+ assert Condition(field=\"notes\", op=\"doesNotContain\", value=\"foo\").run(t) is False\n+ assert Condition(field=\"notes\", op=\"doesNotContain\", value=\"foobar\").run(t) is True\n+\n+\n def test_numeric_condition():\n t = create_transaction(MagicMock(), datetime.date(2024, 1, 1), \"Bank\", \"\", amount=5)\n c1 = Condition(field=\"amount_inflow\", op=\"gt\", value=10.0)\n@@ -86,6 +98,10 @@ def test_numeric_condition():\n assert c2.run(t) is True\n c3 = Condition(field=\"amount\", op=\"isapprox\", value=5.5)\n assert c3.run(t) is False\n+ # isbetween condition\n+ c4 = Condition(field=\"amount\", op=\"isbetween\", value={\"num1\": 5.0, \"num2\": 10.0})\n+ assert c4.run(t) is True\n+ assert str(c4) == \"'amount' isbetween (500, 1000)\" # value gets converted when input as float\n \n \n def test_complex_rule():\n@@ -133,6 +149,8 @@ def test_invalid_inputs():\n Action(field=\"date\", value=\"foo\")\n with pytest.raises(ValueError):\n Condition(field=\"description\", op=\"is\", value=\"foo\") # not an uuid\n+ with pytest.raises(ValueError):\n+ Condition(field=\"amount\", op=\"isbetween\", value=5)\n with pytest.raises(ActualError):\n Action(field=\"notes\", op=\"set-split-amount\", value=\"foo\").run(None) # noqa: use None instead of transaction\n with pytest.raises(ActualError):\n@@ -166,7 +184,7 @@ def test_value_type_value_validation():\n assert ValueType.BOOLEAN.validate(\"\") is False\n # list and NoneType\n assert ValueType.DATE.validate(None)\n- assert ValueType.DATE.validate([\"2024-10-04\"], as_list=True) is True\n+ assert ValueType.DATE.validate([\"2024-10-04\"], ConditionType.ONE_OF) is True\n \n \n def test_value_type_from_field():\n", "FAIL_TO_PASS": ["tests/test_rules.py::test_string_condition", "tests/test_rules.py::test_numeric_condition", "tests/test_rules.py::test_invalid_inputs"]}, {"instance_id": "bvanelli__actualpy-55", "base_commit": "f7210990432f8748a7707463be7ba477fc717bdd", "gold_patch": "diff --git a/actual/rules.py b/actual/rules.py\nindex 6147b85..de1fd65 100644\n--- a/actual/rules.py\n+++ b/actual/rules.py\n@@ -2,7 +2,9 @@ from __future__ import annotations\n \n import datetime\n import enum\n+import re\n import typing\n+import unicodedata\n \n import pydantic\n \n@@ -12,6 +14,14 @@ from actual.database import BaseModel, Transactions, get_attribute_by_table_name\n from actual.schedules import Schedule\n \n \n+def get_normalized_string(value: str) -> str:\n+ \"\"\"Normalization of string for comparison. Uses lowercase and Canonical Decomposition.\n+\n+ See https://github.com/actualbudget/actual/blob/a22160579d6e1f7a17213561cec79c321a14525b/packages/loot-core/src/shared/normalisation.ts\n+ \"\"\"\n+ return unicodedata.normalize(\"NFD\", value.lower())\n+\n+\n class ConditionType(enum.Enum):\n IS = \"is\"\n IS_APPROX = \"isapprox\"\n@@ -25,6 +35,7 @@ class ConditionType(enum.Enum):\n DOES_NOT_CONTAIN = \"doesNotContain\"\n NOT_ONE_OF = \"notOneOf\"\n IS_BETWEEN = \"isbetween\"\n+ MATCHES = \"matches\"\n \n \n class ActionType(enum.Enum):\n@@ -67,7 +78,7 @@ class ValueType(enum.Enum):\n if self == ValueType.DATE:\n return operation.value in (\"is\", \"isapprox\", \"gt\", \"gte\", \"lt\", \"lte\")\n elif self == ValueType.STRING:\n- return operation.value in (\"is\", \"contains\", \"oneOf\", \"isNot\", \"doesNotContain\", \"notOneOf\")\n+ return operation.value in (\"is\", \"contains\", \"oneOf\", \"isNot\", \"doesNotContain\", \"notOneOf\", \"matches\")\n elif self == ValueType.ID:\n return operation.value in (\"is\", \"isNot\", \"oneOf\", \"notOneOf\")\n elif self == ValueType.NUMBER:\n@@ -130,6 +141,11 @@ def get_value(\n return datetime.datetime.strptime(str(value), \"%Y%m%d\").date()\n elif value_type is ValueType.BOOLEAN:\n return int(value) # database accepts 0 or 1\n+ elif value_type is ValueType.STRING:\n+ if isinstance(value, list):\n+ return [get_value(v, value_type) for v in value]\n+ else:\n+ return get_normalized_string(value)\n return value\n \n \n@@ -173,7 +189,9 @@ def condition_evaluation(\n elif op == ConditionType.ONE_OF:\n return true_value in self_value\n elif op == ConditionType.CONTAINS:\n- return self_value in true_value\n+ return get_normalized_string(self_value) in get_normalized_string(true_value)\n+ elif op == ConditionType.MATCHES:\n+ return bool(re.match(self_value, true_value, re.IGNORECASE))\n elif op == ConditionType.NOT_ONE_OF:\n return true_value not in self_value\n elif op == ConditionType.DOES_NOT_CONTAIN:\n", "test_patch": "diff --git a/tests/test_rules.py b/tests/test_rules.py\nindex fce1352..bc28ec9 100644\n--- a/tests/test_rules.py\n+++ b/tests/test_rules.py\n@@ -81,8 +81,19 @@ def test_string_condition():\n assert Condition(field=\"notes\", op=\"notOneOf\", value=[\"foo\", \"bar\"]).run(t) is False\n assert Condition(field=\"notes\", op=\"contains\", value=\"fo\").run(t) is True\n assert Condition(field=\"notes\", op=\"contains\", value=\"foobar\").run(t) is False\n+ assert Condition(field=\"notes\", op=\"matches\", value=\"f.*\").run(t) is True\n+ assert Condition(field=\"notes\", op=\"matches\", value=\"g.*\").run(t) is False\n assert Condition(field=\"notes\", op=\"doesNotContain\", value=\"foo\").run(t) is False\n assert Condition(field=\"notes\", op=\"doesNotContain\", value=\"foobar\").run(t) is True\n+ # test the cases where the case do not match\n+ assert Condition(field=\"notes\", op=\"oneOf\", value=[\"FOO\", \"BAR\"]).run(t) is True\n+ assert Condition(field=\"notes\", op=\"notOneOf\", value=[\"FOO\", \"BAR\"]).run(t) is False\n+ assert Condition(field=\"notes\", op=\"contains\", value=\"FO\").run(t) is True\n+ assert Condition(field=\"notes\", op=\"contains\", value=\"FOOBAR\").run(t) is False\n+ assert Condition(field=\"notes\", op=\"matches\", value=\"F.*\").run(t) is True\n+ assert Condition(field=\"notes\", op=\"matches\", value=\"G.*\").run(t) is False\n+ assert Condition(field=\"notes\", op=\"doesNotContain\", value=\"FOO\").run(t) is False\n+ assert Condition(field=\"notes\", op=\"doesNotContain\", value=\"FOOBAR\").run(t) is True\n \n \n def test_numeric_condition():\n", "FAIL_TO_PASS": ["tests/test_rules.py::test_string_condition"]}], "all_FAIL_TO_PASS": ["tests/test_rules.py::test_string_condition", "tests/test_rules.py::test_numeric_condition", "tests/test_rules.py::test_invalid_inputs", "tests/test_rules.py::test_string_condition"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "LLNL__hatchet-279_x2", "level": 2, "source": "swerebench", "repo": "LLNL/hatchet", "image": "swerebench/sweb.eval.x86_64.llnl_1776_hatchet-279:latest", "base_commit": "e27bb05ecd9c9aa3dc1c56545daac980ed1e616e", "num_bugs": 2, "bugs": [{"instance_id": "LLNL__hatchet-279", "base_commit": "e27bb05ecd9c9aa3dc1c56545daac980ed1e616e", "gold_patch": "diff --git a/docs/index.rst b/docs/index.rst\nindex 6d127a6..814134c 100644\n--- a/docs/index.rst\n+++ b/docs/index.rst\n@@ -64,6 +64,12 @@ following `paper `_:\n \n basic_tutorial\n \n+.. toctree::\n+ :maxdepth: 2\n+ :caption: Reference\n+\n+ publications\n+\n .. toctree::\n :maxdepth: 2\n :caption: API Docs\ndiff --git a/docs/publications.rst b/docs/publications.rst\nnew file mode 100644\nindex 0000000..513b03f\n--- /dev/null\n+++ b/docs/publications.rst\n@@ -0,0 +1,27 @@\n+.. Copyright 2020 Lawrence Livermore National Security, LLC and other\n+ Hatchet Project Developers. See the top-level LICENSE file for details.\n+\n+ SPDX-License-Identifier: MIT\n+\n+******************************\n+Publications and Presentations\n+******************************\n+\n+Publications\n+============\n+\n+- Stephanie Brink, Ian Lumsden, Connor Scully-Allison, Katy Williams, Olga Pearce, Todd Gamblin, Michela Taufer, Katherine Isaacs, Abhinav Bhatele. `Usability and Performance Improvements in Hatchet `_. Presented at the `ProTools 2020 Workshop `_, held in conjunction with the International Conference for High Performance Computing, Networking, Storage and Analysis (SC '20), held virtually.\n+\n+- Abhinav Bhatele, Stephanie Brink, and Todd Gamblin. `Hatchet: Pruning the Overgrowth in Parallel Profiles `_. In Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC '19), Denver, CO.\n+\n+Posters\n+=======\n+\n+- Ian Lumsden. `Graph-Based Profiling Analysis using Hatchet `_. Presented at SC '20. `Slides `_ | `Video Presentation `_\n+\n+- Suraj P. Kesavan, Harsh Bhatia, Abhinav Bhatele, Stephanie Brink, Olga Pearce, Todd Gamblin, Peer-Timo Bremer, and Kwan-Liu Ma. `Scalable Comparative Visualization of Ensembles of Call Graphs Using CallFlow`. Presented at SC '20.\n+\n+Tutorials\n+=========\n+\n+- Performance Analysis using Hatchet, LLNL, July 29/31, 2020.\ndiff --git a/hatchet/graphframe.py b/hatchet/graphframe.py\nindex 083ce58..8be16b8 100644\n--- a/hatchet/graphframe.py\n+++ b/hatchet/graphframe.py\n@@ -134,116 +134,11 @@ class GraphFrame:\n \n @staticmethod\n def from_literal(graph_dict):\n- \"\"\"Create a GraphFrame from a list of dictionaries.\n-\n- TODO: calculate inclusive metrics automatically.\n-\n- Example:\n-\n- .. code-block:: console\n-\n- dag_ldict = [\n- {\n- \"name\": \"A\",\n- \"type\": \"function\",\n- \"metrics\": {\"time (inc)\": 130.0, \"time\": 0.0},\n- \"children\": [\n- {\n- \"name\": \"B\",\n- \"type\": \"function\",\n- \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n- \"children\": [\n- {\n- \"name\": \"C\",\n- \"type\": \"function\",\n- \"metrics\": {\"time (inc)\": 5.0, \"time\": 5.0},\n- \"children\": [\n- {\n- \"name\": \"D\",\n- \"type\": \"function\",\n- \"metrics\": {\"time (inc)\": 8.0, \"time\": 1.0},\n- }\n- ],\n- }\n- ],\n- },\n- {\n- \"name\": \"E\",\n- \"type\": \"function\",\n- \"metrics\": {\"time (inc)\": 55.0, \"time\": 10.0},\n- \"children\": [\n- {\n- \"name\": \"H\",\n- \"type\": \"function\",\n- \"metrics\": {\"time (inc)\": 1.0, \"time\": 9.0}\n- }\n- ],\n- },\n- ],\n- }\n- ]\n-\n- Return:\n- (GraphFrame): graphframe containing data from dictionaries\n- \"\"\"\n-\n- def parse_node_literal(child_dict, hparent):\n- \"\"\"Create node_dict for one node and then call the function\n- recursively on all children.\n- \"\"\"\n-\n- hnode = Node(\n- Frame({\"name\": child_dict[\"name\"], \"type\": child_dict[\"type\"]}), hparent\n- )\n-\n- node_dicts.append(\n- dict(\n- {\"node\": hnode, \"name\": child_dict[\"name\"]}, **child_dict[\"metrics\"]\n- )\n- )\n- hparent.add_child(hnode)\n-\n- if \"children\" in child_dict:\n- for child in child_dict[\"children\"]:\n- parse_node_literal(child, hnode)\n-\n- list_roots = []\n- node_dicts = []\n-\n- # start with creating a node_dict for each root\n- for i in range(len(graph_dict)):\n- graph_root = Node(\n- Frame({\"name\": graph_dict[i][\"name\"], \"type\": graph_dict[i][\"type\"]}),\n- None,\n- )\n-\n- node_dict = {\"node\": graph_root, \"name\": graph_dict[i][\"name\"]}\n- node_dict.update(**graph_dict[i][\"metrics\"])\n- node_dicts.append(node_dict)\n-\n- list_roots.append(graph_root)\n-\n- # call recursively on all children of root\n- if \"children\" in graph_dict[i]:\n- for child in graph_dict[i][\"children\"]:\n- parse_node_literal(child, graph_root)\n-\n- graph = Graph(list_roots)\n- graph.enumerate_traverse()\n-\n- exc_metrics = []\n- inc_metrics = []\n- for key in graph_dict[i][\"metrics\"].keys():\n- if \"(inc)\" in key:\n- inc_metrics.append(key)\n- else:\n- exc_metrics.append(key)\n-\n- dataframe = pd.DataFrame(data=node_dicts)\n- dataframe.set_index([\"node\"], inplace=True)\n- dataframe.sort_index(inplace=True)\n+ \"\"\"Create a GraphFrame from a list of dictionaries.\"\"\"\n+ # import this lazily to avoid circular dependencies\n+ from .readers.literal_reader import LiteralReader\n \n- return GraphFrame(graph, dataframe, exc_metrics, inc_metrics)\n+ return LiteralReader(graph_dict).read()\n \n @staticmethod\n def from_lists(*lists):\ndiff --git a/hatchet/readers/literal_reader.py b/hatchet/readers/literal_reader.py\nnew file mode 100644\nindex 0000000..c7a6a7e\n--- /dev/null\n+++ b/hatchet/readers/literal_reader.py\n@@ -0,0 +1,147 @@\n+# Copyright 2017-2020 Lawrence Livermore National Security, LLC and other\n+# Hatchet Project Developers. See the top-level LICENSE file for details.\n+#\n+# SPDX-License-Identifier: MIT\n+\n+import pandas as pd\n+\n+import hatchet.graphframe\n+from hatchet.node import Node\n+from hatchet.graph import Graph\n+from hatchet.frame import Frame\n+\n+\n+class LiteralReader:\n+ \"\"\"Create a GraphFrame from a list of dictionaries.\n+\n+ TODO: calculate inclusive metrics automatically.\n+\n+ Example:\n+\n+ .. code-block:: console\n+\n+ dag_ldict = [\n+ {\n+ \"name\": \"A\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 130.0, \"time\": 0.0},\n+ \"children\": [\n+ {\n+ \"name\": \"B\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"C\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 5.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"D\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 8.0, \"time\": 1.0},\n+ }\n+ ],\n+ }\n+ ],\n+ },\n+ {\n+ \"name\": \"E\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 55.0, \"time\": 10.0},\n+ \"children\": [\n+ {\n+ \"name\": \"H\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 1.0, \"time\": 9.0}\n+ }\n+ ],\n+ },\n+ ],\n+ }\n+ ]\n+\n+ Return:\n+ (GraphFrame): graphframe containing data from dictionaries\n+ \"\"\"\n+\n+ def __init__(self, graph_dict):\n+ \"\"\"Read from list of dictionaries.\n+\n+ graph_dict (dict): List of dictionaries encoding nodes.\n+ \"\"\"\n+ self.graph_dict = graph_dict\n+\n+ def parse_node_literal(self, frame_to_node_dict, node_dicts, child_dict, hparent):\n+ \"\"\"Create node_dict for one node and then call the function\n+ recursively on all children.\n+ \"\"\"\n+ frame = None\n+ if \"duplicate\" not in child_dict:\n+ frame = Frame({\"name\": child_dict[\"name\"]})\n+ hnode = Node(frame, hparent)\n+\n+ node_dict = dict(\n+ {\"node\": hnode, \"name\": child_dict[\"name\"]}, **child_dict[\"metrics\"]\n+ )\n+\n+ node_dicts.append(node_dict)\n+ frame_to_node_dict[frame] = hnode\n+ elif \"duplicate\" in child_dict:\n+ frame = Frame({\"name\": child_dict[\"name\"]})\n+ hnode = frame_to_node_dict.get(frame)\n+ if not hnode:\n+ hnode = Node(frame, hparent)\n+ node_dict = dict(\n+ {\"node\": hnode, \"name\": child_dict[\"name\"]}, **child_dict[\"metrics\"]\n+ )\n+ node_dicts.append(node_dict)\n+ frame_to_node_dict[frame] = hnode\n+\n+ hparent.add_child(hnode)\n+\n+ if \"children\" in child_dict:\n+ for child in child_dict[\"children\"]:\n+ self.parse_node_literal(frame_to_node_dict, node_dicts, child, hnode)\n+\n+ def read(self):\n+ list_roots = []\n+ node_dicts = []\n+ frame_to_node_dict = {}\n+ frame = None\n+\n+ # start with creating a node_dict for each root\n+ for i in range(len(self.graph_dict)):\n+ frame = Frame({\"name\": self.graph_dict[i][\"name\"]})\n+ graph_root = Node(frame, None)\n+\n+ node_dict = {\"node\": graph_root, \"name\": self.graph_dict[i][\"name\"]}\n+ node_dict.update(**self.graph_dict[i][\"metrics\"])\n+ node_dicts.append(node_dict)\n+\n+ list_roots.append(graph_root)\n+ frame_to_node_dict[frame] = graph_root\n+\n+ # call recursively on all children of root\n+ if \"children\" in self.graph_dict[i]:\n+ for child in self.graph_dict[i][\"children\"]:\n+ self.parse_node_literal(\n+ frame_to_node_dict, node_dicts, child, graph_root\n+ )\n+\n+ graph = Graph(list_roots)\n+ graph.enumerate_traverse()\n+\n+ exc_metrics = []\n+ inc_metrics = []\n+ for key in self.graph_dict[i][\"metrics\"].keys():\n+ if \"(inc)\" in key:\n+ inc_metrics.append(key)\n+ else:\n+ exc_metrics.append(key)\n+\n+ dataframe = pd.DataFrame(data=node_dicts)\n+ dataframe.set_index([\"node\"], inplace=True)\n+ dataframe.sort_index(inplace=True)\n+\n+ return hatchet.graphframe.GraphFrame(graph, dataframe, exc_metrics, inc_metrics)\n", "test_patch": "diff --git a/hatchet/tests/caliper.py b/hatchet/tests/caliper.py\nindex d30e40c..27f518c 100644\n--- a/hatchet/tests/caliper.py\n+++ b/hatchet/tests/caliper.py\n@@ -195,4 +195,6 @@ def test_graphframe_to_literal(lulesh_caliper_json):\n gf = GraphFrame.from_caliper_json(str(lulesh_caliper_json))\n graph_literal = gf.to_literal()\n \n- assert len(graph_literal) == len(gf.graph.roots)\n+ gf2 = GraphFrame.from_literal(graph_literal)\n+\n+ assert len(gf.graph) == len(gf2.graph)\ndiff --git a/hatchet/tests/conftest.py b/hatchet/tests/conftest.py\nindex ffbbf55..71a9634 100644\n--- a/hatchet/tests/conftest.py\n+++ b/hatchet/tests/conftest.py\n@@ -717,3 +717,124 @@ def mock_dag_literal_module_more_complex():\n ]\n \n return dag_ldict\n+\n+\n+@pytest.fixture\n+def mock_graph_literal_duplicates():\n+ \"\"\"Creates a mock tree with duplicate nodes.\"\"\"\n+ graph_dict = [\n+ {\n+ \"name\": \"a\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 130.0, \"time\": 0.0},\n+ \"children\": [\n+ {\n+ \"name\": \"b\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"d\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"e\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ {\n+ \"name\": \"f\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ ],\n+ }\n+ ],\n+ },\n+ {\n+ \"name\": \"c\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"a\",\n+ \"duplicate\": \"True\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ {\n+ \"name\": \"d\",\n+ \"duplicate\": \"True\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ ],\n+ },\n+ ],\n+ }\n+ ]\n+\n+ return graph_dict\n+\n+\n+@pytest.fixture\n+def mock_graph_literal_duplicate_first():\n+ \"\"\"Creates a mock tree with node with duplicate first.\"\"\"\n+ graph_dict = [\n+ {\n+ \"name\": \"a\",\n+ \"duplicate\": True,\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 130.0, \"time\": 0.0},\n+ \"children\": [\n+ {\n+ \"name\": \"b\",\n+ \"duplicate\": True,\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"d\",\n+ \"duplicate\": True,\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"e\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ {\n+ \"name\": \"f\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ ],\n+ }\n+ ],\n+ },\n+ {\n+ \"name\": \"c\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ \"children\": [\n+ {\n+ \"name\": \"a\",\n+ \"duplicate\": \"True\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ {\n+ \"name\": \"d\",\n+ \"duplicate\": \"True\",\n+ \"type\": \"function\",\n+ \"metrics\": {\"time (inc)\": 20.0, \"time\": 5.0},\n+ },\n+ ],\n+ },\n+ ],\n+ }\n+ ]\n+\n+ return graph_dict\ndiff --git a/hatchet/tests/graph_literal.py b/hatchet/tests/graph_literal.py\nindex 09f39cd..837a90e 100644\n--- a/hatchet/tests/graph_literal.py\n+++ b/hatchet/tests/graph_literal.py\n@@ -17,4 +17,25 @@ def test_graphframe_to_literal(mock_graph_literal):\n gf = GraphFrame.from_literal(mock_graph_literal)\n graph_literal = gf.to_literal()\n \n- assert len(graph_literal) == len(mock_graph_literal) == len(gf.graph.roots)\n+ test_literal_output = gf.from_literal(graph_literal)\n+\n+ assert len(test_literal_output.graph.roots) == len(gf.graph.roots)\n+ assert len(test_literal_output.graph) == len(gf.graph)\n+\n+\n+def test_with_duplicates(mock_graph_literal_duplicates):\n+ gf = GraphFrame.from_literal(mock_graph_literal_duplicates)\n+\n+ assert len(gf.graph) == 6\n+\n+ graph_literal = gf.to_literal()\n+ assert mock_graph_literal_duplicates.sort() == graph_literal.sort()\n+\n+\n+def test_with_duplicate_in_first_node(mock_graph_literal_duplicate_first):\n+ gf = GraphFrame.from_literal(mock_graph_literal_duplicate_first)\n+\n+ assert len(gf.graph) == 6\n+\n+ graph_literal = gf.to_literal()\n+ assert mock_graph_literal_duplicate_first.sort() == graph_literal.sort()\ndiff --git a/hatchet/tests/graphframe.py b/hatchet/tests/graphframe.py\nindex 67e644e..ff859f6 100644\n--- a/hatchet/tests/graphframe.py\n+++ b/hatchet/tests/graphframe.py\n@@ -976,11 +976,11 @@ def test_output_with_cycle_graphs():\n assert \"d\" in a_c_children\n assert \"d\" in a_b_children\n \n- # check certian edges are in dot\n+ # check certain edges are in dot\n for edge in dot_edges:\n assert edge in dotout\n \n- # check that a certian number of occurences\n+ # check that a certain number of occurences\n # of same node are in tree indicating multiple\n # edges\n assert treeout.count(\"a\") == 2\ndiff --git a/hatchet/tests/hpctoolkit.py b/hatchet/tests/hpctoolkit.py\nindex 25f6766..98a0c98 100644\n--- a/hatchet/tests/hpctoolkit.py\n+++ b/hatchet/tests/hpctoolkit.py\n@@ -198,11 +198,15 @@ def test_graphframe_to_literal(data_dir, calc_pi_hpct_db):\n gf = GraphFrame.from_hpctoolkit(str(calc_pi_hpct_db))\n graph_literal = gf.to_literal()\n \n- assert len(graph_literal) == len(gf.graph.roots)\n+ gf2 = GraphFrame.from_literal(graph_literal)\n+\n+ assert len(gf.graph) == len(gf2.graph)\n \n \n def test_graphframe_to_literal_with_threads(data_dir, osu_allgather_hpct_db):\n gf = GraphFrame.from_hpctoolkit(str(osu_allgather_hpct_db))\n graph_literal = gf.to_literal()\n \n- assert len(graph_literal) == len(gf.graph.roots)\n+ gf2 = GraphFrame.from_literal(graph_literal)\n+\n+ assert len(gf.graph) == len(gf2.graph)\ndiff --git a/hatchet/tests/pyinstrument.py b/hatchet/tests/pyinstrument.py\nindex 3eb6e30..9bef9a4 100644\n--- a/hatchet/tests/pyinstrument.py\n+++ b/hatchet/tests/pyinstrument.py\n@@ -117,4 +117,6 @@ def test_graphframe_to_literal(hatchet_pyinstrument_json):\n gf = GraphFrame.from_pyinstrument(str(hatchet_pyinstrument_json))\n graph_literal = gf.to_literal()\n \n- assert len(graph_literal) == len(gf.graph.roots)\n+ gf2 = GraphFrame.from_literal(graph_literal)\n+\n+ assert len(gf.graph) == len(gf2.graph)\n", "FAIL_TO_PASS": ["hatchet/tests/caliper.py::test_graphframe_to_literal", "hatchet/tests/graph_literal.py::test_graphframe_to_literal", "hatchet/tests/graph_literal.py::test_with_duplicates", "hatchet/tests/graph_literal.py::test_with_duplicate_in_first_node", "hatchet/tests/hpctoolkit.py::test_graphframe_to_literal", "hatchet/tests/hpctoolkit.py::test_graphframe_to_literal_with_threads", "hatchet/tests/pyinstrument.py::test_graphframe_to_literal"]}, {"instance_id": "LLNL__hatchet-294", "base_commit": "ef433f509c733fe927445e0bc6e068c2e03e7164", "gold_patch": "diff --git a/hatchet/external/console.py b/hatchet/external/console.py\nindex 4be2194..4d89370 100644\n--- a/hatchet/external/console.py\n+++ b/hatchet/external/console.py\n@@ -59,6 +59,13 @@ class ConsoleRenderer:\n self.highlight = kwargs[\"highlight_name\"]\n self.invert_colormap = kwargs[\"invert_colormap\"]\n \n+ if self.metric not in dataframe.columns:\n+ raise KeyError(\n+ \"metric_column={} does not exist in the dataframe, please select a valid column.\".format(\n+ self.metric\n+ )\n+ )\n+\n if self.invert_colormap:\n self.colors.colormap.reverse()\n \ndiff --git a/hatchet/graphframe.py b/hatchet/graphframe.py\nindex ddaa8b9..0c68196 100644\n--- a/hatchet/graphframe.py\n+++ b/hatchet/graphframe.py\n@@ -496,9 +496,6 @@ class GraphFrame:\n expand_names=\"expand_name\",\n context=\"context_column\",\n invert_colors=\"invert_colormap\",\n- color=\"\",\n- threshold=\"\",\n- unicode=\"\",\n )\n def tree(\n self,\n@@ -512,9 +509,6 @@ class GraphFrame:\n depth=10000,\n highlight_name=False,\n invert_colormap=False,\n- color=None, # remove in next release\n- threshold=None, # remove in next release\n- unicode=None, # remove in next release\n ):\n \"\"\"Format this graphframe as a tree and return the resulting string.\"\"\"\n color = sys.stdout.isatty()\ndiff --git a/hatchet/util/deprecated.py b/hatchet/util/deprecated.py\nindex 134fb95..4ab8ad4 100644\n--- a/hatchet/util/deprecated.py\n+++ b/hatchet/util/deprecated.py\n@@ -4,7 +4,6 @@\n # SPDX-License-Identifier: MIT\n \n import functools\n-import warnings\n \n \n def deprecated_params(**old_to_new):\n@@ -29,16 +28,16 @@ def rename_kwargs(fname, old_to_new, kwargs):\n \n # if parameter has been removed\n if not new:\n- warnings.warn(\n- '{}() parameter \"{}=\" has been removed.'.format(fname, old),\n- FutureWarning,\n+ raise ValueError(\n+ '{}() parameter \"{}=\" will be removed in a future release. Please remove it from this script.'.format(\n+ fname, old\n+ )\n )\n # if parameter has been deprecated and renamed\n else:\n- warnings.warn(\n+ raise ValueError(\n '{}() parameter \"{}=\" has been deprecated, please use \"{}=\".'.format(\n fname, old, new\n- ),\n- FutureWarning,\n+ )\n )\n kwargs[new] = kwargs.pop(old)\n", "test_patch": "diff --git a/hatchet/tests/graphframe.py b/hatchet/tests/graphframe.py\nindex 0be1a25..5f8572f 100644\n--- a/hatchet/tests/graphframe.py\n+++ b/hatchet/tests/graphframe.py\n@@ -909,18 +909,12 @@ def test_depth(mock_graph_literal):\n def test_tree_deprecated_parameters(mock_graph_literal):\n gf = GraphFrame.from_literal(mock_graph_literal)\n \n- with pytest.warns(FutureWarning):\n- gf.tree(color=True, metric=\"time\")\n-\n- with pytest.warns(FutureWarning):\n+ with pytest.raises(ValueError):\n gf.tree(invert_colors=True)\n \n- with pytest.warns(FutureWarning):\n+ with pytest.raises(ValueError):\n gf.tree(name=\"name\")\n \n- with pytest.warns(FutureWarning):\n- gf.tree(threshold=0.2)\n-\n with pytest.raises(TypeError):\n gf.tree(metric=\"time\", metric_column=\"time\")\n \n", "FAIL_TO_PASS": ["hatchet/tests/graphframe.py::test_tree_deprecated_parameters"]}], "all_FAIL_TO_PASS": ["hatchet/tests/caliper.py::test_graphframe_to_literal", "hatchet/tests/graph_literal.py::test_graphframe_to_literal", "hatchet/tests/graph_literal.py::test_with_duplicates", "hatchet/tests/graph_literal.py::test_with_duplicate_in_first_node", "hatchet/tests/hpctoolkit.py::test_graphframe_to_literal", "hatchet/tests/hpctoolkit.py::test_graphframe_to_literal_with_threads", "hatchet/tests/pyinstrument.py::test_graphframe_to_literal", "hatchet/tests/graphframe.py::test_tree_deprecated_parameters"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "larq__zookeeper-228_x2", "level": 2, "source": "swerebench", "repo": "larq/zookeeper", "image": "swerebench/sweb.eval.x86_64.larq_1776_zookeeper-228:latest", "base_commit": "52b97b05f09cf8f29d65cc82f1be1ce2fd6dfdc4", "num_bugs": 2, "bugs": [{"instance_id": "larq__zookeeper-228", "base_commit": "52b97b05f09cf8f29d65cc82f1be1ce2fd6dfdc4", "gold_patch": "diff --git a/zookeeper/core/component.py b/zookeeper/core/component.py\nindex e3fde1f..63b0ee6 100644\n--- a/zookeeper/core/component.py\n+++ b/zookeeper/core/component.py\n@@ -484,6 +484,14 @@ def configure_component_instance(\n conf_field_value = subclass()\n break\n \n+ # If this isn't the case, then it's a user type error, but we don't\n+ # throw here and instead let the run-time type-checking take care of\n+ # it (which will provide a better error message).\n+ if utils.is_component_instance(conf_field_value):\n+ # Set the component parent so that field value inheritence will\n+ # work correctly.\n+ conf_field_value.__component_parent__ = instance\n+\n # Set the value on the instance.\n instance.__component_configured_field_values__[\n field.name\n", "test_patch": "diff --git a/zookeeper/core/component_test.py b/zookeeper/core/component_test.py\nindex 1caf4fb..120557a 100644\n--- a/zookeeper/core/component_test.py\n+++ b/zookeeper/core/component_test.py\n@@ -809,3 +809,21 @@ def test_base_hasattr():\n \n assert not hasattr(instance, \"missing_attribute\")\n assert base_hasattr(instance, \"missing_attribute\")\n+\n+\n+def test_component_configure_component_passed_as_config():\n+ @component\n+ class Child:\n+ x: int = Field() # Inherited from parent\n+\n+ @component\n+ class Parent:\n+ x: int = Field(7)\n+ child: Child = ComponentField(Child)\n+\n+ instance = Parent()\n+ new_child_instance = Child()\n+ configure(instance, {\"child\": new_child_instance})\n+ assert instance.child is new_child_instance\n+ assert instance.child.__component_parent__ is instance\n+ assert instance.child.x == 7 # This value should be correctly inherited.\n", "FAIL_TO_PASS": ["zookeeper/core/component_test.py::test_component_configure_component_passed_as_config"]}, {"instance_id": "larq__zookeeper-241", "base_commit": "60ee7890ca7d8af30e480ef35096b96911265b80", "gold_patch": "diff --git a/zookeeper/core/component.py b/zookeeper/core/component.py\nindex 9d5d455..b16b97e 100644\n--- a/zookeeper/core/component.py\n+++ b/zookeeper/core/component.py\n@@ -78,7 +78,7 @@ print(c)\n \n import functools\n import inspect\n-from typing import AbstractSet, Any, Dict, Iterator, List, Optional, Type\n+from typing import AbstractSet, Any, Dict, Iterator, List, Optional, Tuple, Type\n \n from zookeeper.core import utils\n from zookeeper.core.factory_registry import FACTORY_REGISTRY\n@@ -303,6 +303,84 @@ def _wrap_dir(component_cls: Type) -> None:\n component_cls.__dir__ = wrapped_fn\n \n \n+######################################\n+# Implement the `ItemsView` protocol #\n+######################################\n+\n+# Implementing these three methods makes `dict(component_instance)`,\n+# `list(component_instance)`, et cetera be something sensible.\n+#\n+# In particular, `dict(component_instance)` has field names as keys and field\n+# values as values, giving a flattened view of the entire component tree\n+# including all sub-components. This dictionary is precisely the configuration\n+# that is required to completely re-create the component, including all\n+# sub-components, i.e. `configure(new_instance, dict(old_instance))`.\n+\n+\n+def __component_len__(instance) -> int:\n+ return len(list(iter(instance)))\n+\n+\n+def __component_contains__(instance, key: str) -> bool:\n+ if not isinstance(key, str):\n+ return False\n+\n+ if \".\" not in key:\n+ # The base case is whether or not this is a component field defined\n+ # on this class, that also has a value in scope (which excludes the\n+ # `allow_missing` fields without a configured value).\n+ return (\n+ key in instance.__component_fields__\n+ and key in instance.__component_fields_with_values_in_scope__\n+ )\n+\n+ # The recusive case is to split the key and check the sub-component.\n+ key_prefix = key.split(\".\")[0]\n+ if isinstance(instance.__component_fields__.get(key_prefix, None), ComponentField):\n+ try:\n+ sub_component = base_getattr(instance, key_prefix)\n+ if utils.is_component_instance(sub_component):\n+ return key[len(key_prefix) + 1 :] in sub_component\n+ except AttributeError:\n+ pass\n+\n+ return False\n+\n+\n+def __component_iter__(instance) -> Iterator[Tuple[str, Any]]:\n+ for field_name, field in instance.__component_fields__.items():\n+ # Get the field value. If there's an attribute error (possible\n+ # because of `allow_missing`), just skip.\n+ try:\n+ field_value = base_getattr(instance, field_name)\n+ except AttributeError:\n+ continue\n+\n+ # Check if the value is inherited and if so skip.\n+ parent_instance = next(\n+ utils.generate_component_ancestors_with_field(instance, field_name),\n+ None,\n+ )\n+ if (\n+ parent_instance is not None\n+ and base_getattr(parent_instance, field_name) is field_value\n+ ):\n+ continue\n+\n+ # If this is *not* a sub-component, yield the value directly.\n+ if not isinstance(field, ComponentField) or not utils.is_component_instance(\n+ field_value\n+ ):\n+ yield field_name, field_value\n+\n+ # Otherwise, yield the name of the sub-component class and\n+ # recursively yield from the sub-component.\n+ else:\n+ yield field_name, field_value.__class__.__qualname__\n+ for sub_field_name, sub_field_value in iter(field_value):\n+ yield f\"{field_name}.{sub_field_name}\", sub_field_value\n+\n+\n #################################\n # Pretty string representations #\n #################################\n@@ -495,7 +573,7 @@ def configure_component_instance(\n # If the field explicitly allows values to be missing, there's no need\n # to do anything.\n elif field.allow_missing:\n- pass\n+ continue\n \n # If there is only one concrete component subclass of the annotated\n # type, we assume the user must intend to use that subclass, and so\n@@ -706,6 +784,19 @@ def component(cls: Type):\n _wrap_delattr(cls)\n _wrap_dir(cls)\n \n+ # Implement the `ItemsView` protocol\n+ if hasattr(cls, \"__len__\") and cls.__len__ != __component_len__:\n+ raise TypeError(\"Component classes must not define a custom `__len__` method.\")\n+ cls.__len__ = __component_len__\n+ if hasattr(cls, \"__contains__\") and cls.__contains__ != __component_contains__:\n+ raise TypeError(\n+ \"Component classes must not define a custom `__contains__` method.\"\n+ )\n+ cls.__contains__ = __component_contains__\n+ if hasattr(cls, \"__iter__\") and cls.__iter__ != __component_iter__:\n+ raise TypeError(\"Component classes must not define a custom `__iter__` method.\")\n+ cls.__iter__ = __component_iter__\n+\n # Components should have nice `__str__` and `__repr__` methods.\n cls.__str__ = __component_str__\n cls.__repr__ = __component_repr__\n", "test_patch": "diff --git a/zookeeper/core/component_test.py b/zookeeper/core/component_test.py\nindex 120557a..fc4fce6 100644\n--- a/zookeeper/core/component_test.py\n+++ b/zookeeper/core/component_test.py\n@@ -262,6 +262,159 @@ def test_configure_interactive_prompt_for_subcomponent_choice():\n prompt.assert_called_once()\n \n \n+def test_len():\n+ with pytest.raises(\n+ TypeError, match=\"Component classes must not define a custom `__len__` method.\"\n+ ):\n+\n+ @component\n+ class InvalidComponent:\n+ def __len__():\n+ return\n+\n+ @component\n+ class Component:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ c: str = Field(allow_missing=True)\n+\n+ instance = Component()\n+ configure(instance, {\"a\": 10})\n+ # When a field is `allow_missing` it should not be counted.\n+ assert len(instance) == 2\n+\n+ instance = Component()\n+ configure(instance, {\"a\": 10, \"c\": \"foo\"})\n+ # But when the `allow_missing` field gets assigned a value it should be\n+ # counted.\n+ assert len(instance) == 3\n+\n+\n+def test_contains():\n+ with pytest.raises(\n+ TypeError,\n+ match=\"Component classes must not define a custom `__contains__` method.\",\n+ ):\n+\n+ @component\n+ class InvalidComponent:\n+ def __contains__():\n+ return\n+\n+ @component\n+ class Child:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field()\n+ c: str = Field(allow_missing=True)\n+\n+ @component\n+ class Parent:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ child: Child = ComponentField()\n+\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0)})\n+ assert \"a\" in instance\n+ assert \"b\" in instance\n+ assert \"child\" in instance\n+ assert \"child.a\" in instance\n+ assert \"child.b\" in instance\n+ assert \"child.c\" not in instance\n+\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0), \"child.c\": \"foo\"})\n+ assert \"a\" in instance\n+ assert \"b\" in instance\n+ assert \"child\" in instance\n+ assert \"child.a\" in instance\n+ assert \"child.b\" in instance\n+ assert \"child.c\" in instance\n+\n+\n+def test_iter():\n+ with pytest.raises(\n+ TypeError, match=\"Component classes must not define a custom `__iter__` method.\"\n+ ):\n+\n+ @component\n+ class InvalidComponent:\n+ def __iter__():\n+ return\n+\n+ @component\n+ class Child:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field()\n+ c: str = Field(allow_missing=True)\n+\n+ @component\n+ class Parent:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ child: Child = ComponentField()\n+\n+ # When no configured value is provided for `child.c`, there should be four\n+ # values in the iterator: `a` and `b` and `child` on the parent, and `b` on\n+ # the child. Notice that the `a` on the child (i.e. `child.a`) is not\n+ # included, because that value is inherited from the parent.\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0)})\n+ assert list(iter(instance)) == [\n+ (\"a\", 10),\n+ (\"b\", (5, -42.3)),\n+ (\"child\", \"test_iter..Child\"),\n+ (\"child.b\", (-1, 0.0)),\n+ ]\n+\n+ # The only difference from the above is that `child.c` should be included.\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0), \"child.c\": \"foo\"})\n+ assert list(iter(instance)) == [\n+ (\"a\", 10),\n+ (\"b\", (5, -42.3)),\n+ (\"child\", \"test_iter..Child\"),\n+ (\"child.b\", (-1, 0.0)),\n+ (\"child.c\", \"foo\"),\n+ ]\n+\n+\n+def test_itemsview_protocol():\n+ @component\n+ class Child:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field()\n+ c: str = Field(allow_missing=True)\n+\n+ @component\n+ class Parent:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ child: Child = ComponentField()\n+\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0)})\n+\n+ instance_dict = dict(instance)\n+\n+ # Check it's what we expect\n+ assert instance_dict == {\n+ \"a\": 10,\n+ \"b\": (5, -42.3),\n+ \"child\": \"test_itemsview_protocol..Child\",\n+ \"child.b\": (-1, 0.0),\n+ }\n+\n+ # Check that, using the old config, we can instantiate and configure an\n+ # identical component tree.\n+ new_instance = Parent()\n+ configure(new_instance, instance_dict)\n+ assert new_instance.a == instance.a\n+ assert new_instance.b == instance.b\n+ assert new_instance.child.a == instance.child.a\n+ assert new_instance.child.b == instance.child.b\n+\n+\n def test_str_and_repr():\n \"\"\"`__str__` and `__repr__` should give formatted strings that represent nested\n components nicely.\"\"\"\n", "FAIL_TO_PASS": ["zookeeper/core/component_test.py::test_len", "zookeeper/core/component_test.py::test_contains", "zookeeper/core/component_test.py::test_iter", "zookeeper/core/component_test.py::test_itemsview_protocol"]}], "all_FAIL_TO_PASS": ["zookeeper/core/component_test.py::test_component_configure_component_passed_as_config", "zookeeper/core/component_test.py::test_len", "zookeeper/core/component_test.py::test_contains", "zookeeper/core/component_test.py::test_iter", "zookeeper/core/component_test.py::test_itemsview_protocol"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cekit__cekit-874_x2", "level": 2, "source": "swerebench", "repo": "cekit/cekit", "image": "swerebench/sweb.eval.x86_64.cekit_1776_cekit-874:latest", "base_commit": "ef69585c8c145b049a2bfad741f191ffeb3ef78b", "num_bugs": 2, "bugs": [{"instance_id": "cekit__cekit-874", "base_commit": "ef69585c8c145b049a2bfad741f191ffeb3ef78b", "gold_patch": "diff --git a/cekit/builders/buildah.py b/cekit/builders/buildah.py\nindex d966a1a..d28b282 100644\n--- a/cekit/builders/buildah.py\n+++ b/cekit/builders/buildah.py\n@@ -33,6 +33,9 @@ class BuildahBuilder(Builder):\n if not self.params.no_squash:\n cmd.append(\"--squash\")\n \n+ if self.params.trace:\n+ cmd += [\"--log-level\", \"debug\"]\n+\n if self.params.pull:\n cmd.append(\"--pull-always\")\n \ndiff --git a/cekit/builders/osbs.py b/cekit/builders/osbs.py\nindex 3ae29c8..29f4e12 100644\n--- a/cekit/builders/osbs.py\n+++ b/cekit/builders/osbs.py\n@@ -260,6 +260,8 @@ class OSBSBuilder(Builder):\n cmd = [self._fedpkg]\n if self.params.user:\n cmd += [\"--user\", self.params.user]\n+ if self.params.trace:\n+ cmd += [\"--debug\"]\n cmd += [\"new-sources\"] + cache_artifacts\n \n with Chdir(self.dist_git_dir):\n@@ -278,6 +280,9 @@ class OSBSBuilder(Builder):\n git_tag: str = \"\"\n cmd: List[str] = [self._koji]\n \n+ if self.params.trace:\n+ cmd += [\"--debug\"]\n+\n if self.params.user:\n cmd += [\"--user\", self.params.user]\n \ndiff --git a/cekit/builders/podman.py b/cekit/builders/podman.py\nindex 979f16b..53c6fa0 100644\n--- a/cekit/builders/podman.py\n+++ b/cekit/builders/podman.py\n@@ -36,6 +36,9 @@ class PodmanBuilder(Builder):\n if not tags:\n tags = self.generator.get_tags()\n \n+ if self.params.trace:\n+ cmd += [\"--log-level\", \"debug\"]\n+\n if self.params.pull:\n cmd.append(\"--pull-always\")\n \ndiff --git a/cekit/cli.py b/cekit/cli.py\nindex 0cd464c..06dc948 100644\n--- a/cekit/cli.py\n+++ b/cekit/cli.py\n@@ -39,6 +39,7 @@ def verify_release_passed(ctx, param, value):\n show_default=True,\n )\n @click.option(\"-v\", \"--verbose\", help=\"Enable verbose output.\", is_flag=True)\n+@click.option(\"--trace\", help=\"Enable trace output.\", is_flag=True)\n @click.option(\"--nocolor\", help=\"Disable color output.\", is_flag=True)\n @click.option(\n \"--work-dir\",\n@@ -67,7 +68,7 @@ def verify_release_passed(ctx, param, value):\n show_default=True,\n )\n @click.version_option(message=\"%(version)s\", version=__version__)\n-def cli(descriptor, verbose, nocolor, work_dir, config, redhat, target):\n+def cli(descriptor, verbose, nocolor, work_dir, config, redhat, target, trace):\n \"\"\"\n ABOUT\n \n", "test_patch": "diff --git a/tests/test_integ_podman.py b/tests/test_integ_podman.py\nindex 20f0b2e..e319c98 100644\n--- a/tests/test_integ_podman.py\n+++ b/tests/test_integ_podman.py\n@@ -5,6 +5,7 @@ from __future__ import print_function\n import os\n import shutil\n \n+from _pytest.capture import CaptureResult\n from click.testing import CliRunner\n \n from cekit.cli import cli\n@@ -50,7 +51,7 @@ def test_podman_from_scratch(tmpdir):\n run_cekit(os.path.join(tmpdir, \"scratch\"), env={\"BUILDAH_LAYERS\": \"false\"})\n \n \n-def test_podman_operator_metadata(tmpdir):\n+def test_podman_operator_metadata(tmpdir, capfd):\n tmpdir = str(tmpdir)\n \n shutil.copytree(\n@@ -62,6 +63,14 @@ def test_podman_operator_metadata(tmpdir):\n # See: https://bugzilla.redhat.com/show_bug.cgi?id=1746022\n run_cekit(\n os.path.join(tmpdir, \"operator-metadata\"),\n- args=[\"--redhat\", \"build\", \"podman\"],\n+ args=[\"--redhat\", \"--trace\", \"build\", \"podman\"],\n env={\"BUILDAH_LAYERS\": \"false\"},\n )\n+\n+ output: CaptureResult = capfd.readouterr()\n+ print(output.err)\n+ assert 'level=debug msg=\"Called build.PersistentPreRunE' in output.err\n+ assert (\n+ \"Successfully tagged localhost/amq7/amq-streams-rhel7-operator-metadata:latest\"\n+ in output.out\n+ )\ndiff --git a/tests/test_unit_args.py b/tests/test_unit_args.py\nindex 349ec4e..1c6f24a 100644\n--- a/tests/test_unit_args.py\n+++ b/tests/test_unit_args.py\n@@ -32,6 +32,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": True,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -54,6 +55,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"custom-target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -76,6 +78,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -98,6 +101,7 @@ def _get_class_by_name(clazz):\n \"config\": \"custom-config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -120,6 +124,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -142,6 +147,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (\"foo\", \"bar\"),\n@@ -164,6 +170,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -190,6 +197,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -216,6 +224,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -242,6 +251,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -266,6 +276,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"overrides\": (),\n \"image\": \"image:1.0\",\n \"steps_url\": \"https://github.com/cekit/behave-test-steps.git\",\n@@ -287,6 +298,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -308,6 +320,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -333,6 +346,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n@@ -354,6 +368,7 @@ def _get_class_by_name(clazz):\n \"config\": \"~/.cekit/config\",\n \"redhat\": False,\n \"target\": \"target\",\n+ \"trace\": False,\n \"validate\": False,\n \"dry_run\": False,\n \"overrides\": (),\n", "FAIL_TO_PASS": ["tests/test_unit_args.py::test_args_command[args0-cekit.builders.docker_builder.DockerBuilder-params0]", "tests/test_unit_args.py::test_args_command[args1-cekit.builders.docker_builder.DockerBuilder-params1]", "tests/test_unit_args.py::test_args_command[args2-cekit.builders.docker_builder.DockerBuilder-params2]", "tests/test_unit_args.py::test_args_command[args3-cekit.builders.docker_builder.DockerBuilder-params3]", "tests/test_unit_args.py::test_args_command[args4-cekit.builders.docker_builder.DockerBuilder-params4]", "tests/test_unit_args.py::test_args_command[args5-cekit.builders.docker_builder.DockerBuilder-params5]", "tests/test_unit_args.py::test_args_command[args6-cekit.builders.osbs.OSBSBuilder-params6]", "tests/test_unit_args.py::test_args_command[args7-cekit.builders.osbs.OSBSBuilder-params7]", "tests/test_unit_args.py::test_args_command[args8-cekit.builders.osbs.OSBSBuilder-params8]", "tests/test_unit_args.py::test_args_command[args9-cekit.builders.osbs.OSBSBuilder-params9]", "tests/test_unit_args.py::test_args_command[args10-cekit.test.behave_tester.BehaveTester-params10]", "tests/test_unit_args.py::test_args_command[args11-cekit.builders.docker_builder.DockerBuilder-params11]", "tests/test_unit_args.py::test_args_command[args12-cekit.builders.osbs.OSBSBuilder-params12]", "tests/test_unit_args.py::test_args_command[args13-cekit.builders.docker_builder.DockerBuilder-params13]", "tests/test_unit_args.py::test_args_command[args14-cekit.builders.buildah.BuildahBuilder-params14]"]}, {"instance_id": "cekit__cekit-877", "base_commit": "376b6630407f72238a18102e35602121828ed9be", "gold_patch": "diff --git a/cekit/cli.py b/cekit/cli.py\nindex dcbd360..6a4cb1e 100644\n--- a/cekit/cli.py\n+++ b/cekit/cli.py\n@@ -13,7 +13,7 @@ from cekit.config import Config, default_work_dir\n from cekit.errors import CekitError\n from cekit.log import setup_logging\n from cekit.tools import Map\n-from cekit.version import __version__\n+from cekit.version import __version__, schema_version\n \n if TYPE_CHECKING:\n from cekit.builder import Command\n@@ -352,6 +352,12 @@ def test(image, overrides):\n default=\"https://github.com/cekit/behave-test-steps.git\",\n show_default=True,\n )\n+@click.option(\n+ \"--steps-ref\",\n+ help=\"Behave steps library reference (branch or tag)\",\n+ default=\"v%s\" % schema_version,\n+ show_default=True,\n+)\n @click.option(\"--wip\", help=\"Run test scenarios tagged with @wip only.\", is_flag=True)\n @click.option(\"--include-re\", help=\"Run only those features which match this regex\")\n @click.option(\"--exclude-re\", help=\"Do not run those features which match this regex\")\n@@ -362,7 +368,7 @@ def test(image, overrides):\n multiple=True,\n )\n @click.pass_context\n-def test_behave(ctx, steps_url, wip, names, include_re, exclude_re):\n+def test_behave(ctx, steps_url, steps_ref, wip, names, include_re, exclude_re):\n \"\"\"\n DESCRIPTION\n \n", "test_patch": "diff --git a/cekit/test/behave_tester.py b/cekit/test/behave_tester.py\nindex 6aee335..d411626 100644\n--- a/cekit/test/behave_tester.py\n+++ b/cekit/test/behave_tester.py\n@@ -5,7 +5,6 @@ from cekit.builder import Command\n from cekit.generator.behave import BehaveGenerator\n from cekit.test.behave_runner import BehaveTestRunner\n from cekit.test.collector import BehaveTestCollector\n-from cekit.version import schema_version\n \n LOGGER = logging.getLogger(\"cekit\")\n \n@@ -44,10 +43,8 @@ class BehaveTester(Command):\n \n self.generator.generate()\n \n- # The branch to clone is determined by the schema_version in the descriptor prefixed with `v`\n- # It defaults to the CEKIt current schema_version.\n self.collected = self.test_collector.collect(\n- self.generator.image.get(\"schema_version\", schema_version),\n+ self.params.steps_ref,\n self.params.steps_url,\n )\n \ndiff --git a/cekit/test/collector.py b/cekit/test/collector.py\nindex 2fd9f88..1d209a2 100644\n--- a/cekit/test/collector.py\n+++ b/cekit/test/collector.py\n@@ -41,7 +41,7 @@ class BehaveTestCollector(object):\n \n def _fetch_steps(self, version, url):\n \"\"\"Method fetches common steps\"\"\"\n- logger.info(\"Fetching common steps from '{}'.\".format(url))\n+ logger.info(\"Fetching common steps from '{}', ref '{}'.\".format(url, version))\n cmd = [\n \"git\",\n \"clone\",\n@@ -50,7 +50,7 @@ class BehaveTestCollector(object):\n url,\n self.test_dir,\n \"-b\",\n- \"v%s\" % version,\n+ \"%s\" % version,\n ]\n run_wrapper(cmd, False, f\"Could not fetch steps from {url}\")\n \ndiff --git a/docs/handbook/testing/behave.rst b/docs/handbook/testing/behave.rst\nindex 85fa491..38bcf2e 100644\n--- a/docs/handbook/testing/behave.rst\n+++ b/docs/handbook/testing/behave.rst\n@@ -122,6 +122,7 @@ Options\n \n * ``--wip`` -- Only run tests tagged with the ``@wip`` tag.\n * ``--steps-url`` -- A git repository url containing `steps `_ for tests.\n+* ``--steps-ref`` -- A reference (branch or tag) in the steps repository to check out\n * ``--name`` -- *Scenario* name to be executed\n * ``--include-re`` -- Regex of feature files which will be executed only\n * ``--exclude-re`` -- Regex of feature files which will not be executed\ndiff --git a/tests/test_unit_args.py b/tests/test_unit_args.py\nindex 124e7f7..7de9ffd 100644\n--- a/tests/test_unit_args.py\n+++ b/tests/test_unit_args.py\n@@ -286,6 +286,7 @@ def _get_class_by_name(clazz):\n \"overrides\": (),\n \"image\": \"image:1.0\",\n \"steps_url\": \"https://github.com/cekit/behave-test-steps.git\",\n+ \"steps_ref\": \"v1\",\n \"wip\": False,\n \"include_re\": None,\n \"exclude_re\": None,\n", "FAIL_TO_PASS": ["tests/test_unit_args.py::test_args_command[args10-cekit.test.behave_tester.BehaveTester-params10]"]}], "all_FAIL_TO_PASS": ["tests/test_unit_args.py::test_args_command[args0-cekit.builders.docker_builder.DockerBuilder-params0]", "tests/test_unit_args.py::test_args_command[args1-cekit.builders.docker_builder.DockerBuilder-params1]", "tests/test_unit_args.py::test_args_command[args2-cekit.builders.docker_builder.DockerBuilder-params2]", "tests/test_unit_args.py::test_args_command[args3-cekit.builders.docker_builder.DockerBuilder-params3]", "tests/test_unit_args.py::test_args_command[args4-cekit.builders.docker_builder.DockerBuilder-params4]", "tests/test_unit_args.py::test_args_command[args5-cekit.builders.docker_builder.DockerBuilder-params5]", "tests/test_unit_args.py::test_args_command[args6-cekit.builders.osbs.OSBSBuilder-params6]", "tests/test_unit_args.py::test_args_command[args7-cekit.builders.osbs.OSBSBuilder-params7]", "tests/test_unit_args.py::test_args_command[args8-cekit.builders.osbs.OSBSBuilder-params8]", "tests/test_unit_args.py::test_args_command[args9-cekit.builders.osbs.OSBSBuilder-params9]", "tests/test_unit_args.py::test_args_command[args10-cekit.test.behave_tester.BehaveTester-params10]", "tests/test_unit_args.py::test_args_command[args11-cekit.builders.docker_builder.DockerBuilder-params11]", "tests/test_unit_args.py::test_args_command[args12-cekit.builders.osbs.OSBSBuilder-params12]", "tests/test_unit_args.py::test_args_command[args13-cekit.builders.docker_builder.DockerBuilder-params13]", "tests/test_unit_args.py::test_args_command[args14-cekit.builders.buildah.BuildahBuilder-params14]", "tests/test_unit_args.py::test_args_command[args10-cekit.test.behave_tester.BehaveTester-params10]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Fatal1ty__mashumaro-127_x2", "level": 2, "source": "swerebench", "repo": "Fatal1ty/mashumaro", "image": "swerebench/sweb.eval.x86_64.fatal1ty_1776_mashumaro-127:latest", "base_commit": "73a937aebf8383da558cac3e71978cc1f8e6a0c7", "num_bugs": 2, "bugs": [{"instance_id": "Fatal1ty__mashumaro-127", "base_commit": "73a937aebf8383da558cac3e71978cc1f8e6a0c7", "gold_patch": "diff --git a/README.md b/README.md\nindex d1287b9..96a1ff2 100644\n--- a/README.md\n+++ b/README.md\n@@ -2364,7 +2364,7 @@ For simple one-time cases it's recommended to start from using a configurable\n serialized to json or to dict:\n \n ```python\n-from dataclasses import dataclass\n+from dataclasses import dataclass, field\n from typing import List\n from uuid import UUID\n \n@@ -2374,7 +2374,7 @@ from mashumaro.jsonschema import build_json_schema\n @dataclass\n class User:\n id: UUID\n- name: str\n+ name: str = field(metadata={\"description\": \"User name\"})\n \n \n print(build_json_schema(List[User]).to_json())\n@@ -2395,7 +2395,8 @@ print(build_json_schema(List[User]).to_json())\n \"format\": \"uuid\"\n },\n \"name\": {\n- \"type\": \"string\"\n+ \"type\": \"string\",\n+ \"description\": \"User name\"\n }\n },\n \"additionalProperties\": false,\ndiff --git a/mashumaro/jsonschema/schema.py b/mashumaro/jsonschema/schema.py\nindex 65c3ec3..7779aa6 100644\n--- a/mashumaro/jsonschema/schema.py\n+++ b/mashumaro/jsonschema/schema.py\n@@ -306,6 +306,9 @@ def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:\n f_name = f_instance.alias\n if f_default is not MISSING:\n f_schema.default = f_default\n+ description = f_instance.metadata.get(\"description\")\n+ if description:\n+ f_schema.description = description\n \n if not has_default:\n required.append(f_name)\n", "test_patch": "diff --git a/tests/test_jsonschema/test_jsonschema_generation.py b/tests/test_jsonschema/test_jsonschema_generation.py\nindex 626f977..5bf61a6 100644\n--- a/tests/test_jsonschema/test_jsonschema_generation.py\n+++ b/tests/test_jsonschema/test_jsonschema_generation.py\n@@ -126,7 +126,9 @@ def test_jsonschema_for_dataclass():\n c: Optional[int] = field(default=None, metadata={\"alias\": \"cc\"})\n d: str = \"\"\n e: int = field(init=False)\n- f: List[int] = field(default_factory=list)\n+ f: List[int] = field(\n+ default_factory=list, metadata={\"description\": \"description for f\"}\n+ )\n \n class Config:\n aliases = {\"a\": \"aa\", \"d\": \"dd\"}\n@@ -145,7 +147,8 @@ def test_jsonschema_for_dataclass():\n ),\n \"dd\": JSONSchema(type=JSONSchemaInstanceType.STRING, default=\"\"),\n \"f\": JSONArraySchema(\n- items=JSONSchema(type=JSONSchemaInstanceType.INTEGER)\n+ items=JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ description=\"description for f\",\n ),\n },\n additionalProperties=False,\n", "FAIL_TO_PASS": ["tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass"]}, {"instance_id": "Fatal1ty__mashumaro-128", "base_commit": "73a937aebf8383da558cac3e71978cc1f8e6a0c7", "gold_patch": "diff --git a/README.md b/README.md\nindex d1287b9..f6e11e6 100644\n--- a/README.md\n+++ b/README.md\n@@ -2698,7 +2698,9 @@ Object constraints:\n ### Extending JSON Schema\n \n Using a `Config` class it is possible to override some parts of the schema.\n-Currently, it works for dataclass fields via \"properties\" key:\n+Currently, you can do the following:\n+* override some field schemas using the \"properties\" key\n+* change `additionalProperties` using the \"additionalProperties\" key\n \n ```python\n from dataclasses import dataclass\n@@ -2716,7 +2718,8 @@ class FooBar:\n \"type\": \"string\",\n \"description\": \"bar\"\n }\n- }\n+ },\n+ \"additionalProperties\": True,\n }\n \n print(build_json_schema(FooBar).to_json())\n@@ -2738,7 +2741,7 @@ print(build_json_schema(FooBar).to_json())\n \"type\": \"integer\"\n }\n },\n- \"additionalProperties\": false,\n+ \"additionalProperties\": true,\n \"required\": [\n \"foo\",\n \"bar\"\n@@ -2747,6 +2750,9 @@ print(build_json_schema(FooBar).to_json())\n ```\n \n \n+You can also change the \"additionalProperties\" key to a specific schema\n+by passing it a `JSONSchema` instance instead of a bool value.\n+\n ### JSON Schema and custom serialization methods\n \n Mashumaro provides different ways to override default serialization methods for\ndiff --git a/mashumaro/jsonschema/schema.py b/mashumaro/jsonschema/schema.py\nindex 65c3ec3..9bce042 100644\n--- a/mashumaro/jsonschema/schema.py\n+++ b/mashumaro/jsonschema/schema.py\n@@ -285,15 +285,16 @@ def override_field_instance_type_if_needed(\n def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:\n # TODO: Self references might not work\n if is_dataclass(instance.origin_type):\n+ jsonschema_config = instance.get_config().json_schema\n schema = JSONObjectSchema(\n title=instance.origin_type.__name__,\n- additionalProperties=False,\n+ additionalProperties=jsonschema_config.get(\n+ \"additionalProperties\", False\n+ ),\n )\n properties: Dict[str, JSONSchema] = {}\n required = []\n- field_schema_overrides = instance.get_config().json_schema.get(\n- \"properties\", {}\n- )\n+ field_schema_overrides = jsonschema_config.get(\"properties\", {})\n for f_name, f_type, has_default, f_default in instance.fields():\n override = field_schema_overrides.get(f_name)\n f_instance = instance.copy(type=f_type, name=f_name)\n", "test_patch": "diff --git a/tests/test_jsonschema/test_jsonschema_generation.py b/tests/test_jsonschema/test_jsonschema_generation.py\nindex 626f977..0b08833 100644\n--- a/tests/test_jsonschema/test_jsonschema_generation.py\n+++ b/tests/test_jsonschema/test_jsonschema_generation.py\n@@ -1051,3 +1051,45 @@ def test_jsonschema_with_ref_prefix():\n .items.to_dict()\n == schema\n )\n+\n+\n+def test_jsonschema_with_additional_properties_true():\n+ @dataclass\n+ class DataClass:\n+ x: int\n+\n+ class Config(BaseConfig):\n+ json_schema = {\"additionalProperties\": True}\n+\n+ schema = JSONObjectSchema(\n+ title=\"DataClass\",\n+ properties={\n+ \"x\": JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ },\n+ additionalProperties=True,\n+ required=[\"x\"],\n+ )\n+ assert build_json_schema(DataClass) == schema\n+\n+\n+def test_jsonschema_with_additional_properties_schema():\n+ @dataclass\n+ class DataClass:\n+ x: int\n+\n+ class Config(BaseConfig):\n+ json_schema = {\n+ \"additionalProperties\": JSONSchema(\n+ type=JSONSchemaInstanceType.INTEGER\n+ )\n+ }\n+\n+ schema = JSONObjectSchema(\n+ title=\"DataClass\",\n+ properties={\n+ \"x\": JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ },\n+ additionalProperties=JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ required=[\"x\"],\n+ )\n+ assert build_json_schema(DataClass) == schema\n", "FAIL_TO_PASS": ["tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_true", "tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_schema"]}], "all_FAIL_TO_PASS": ["tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass", "tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_true", "tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_schema"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Parquery__icontract-114_x2", "level": 2, "source": "swerebench", "repo": "Parquery/icontract", "image": "swerebench/sweb.eval.x86_64.parquery_1776_icontract-114:latest", "base_commit": "5eecd149ac76db451a978ba208b95768fa1685af", "num_bugs": 2, "bugs": [{"instance_id": "Parquery__icontract-114", "base_commit": "5eecd149ac76db451a978ba208b95768fa1685af", "gold_patch": "diff --git a/icontract/_checkers.py b/icontract/_checkers.py\nindex 1dc79d3..e5909e2 100644\n--- a/icontract/_checkers.py\n+++ b/icontract/_checkers.py\n@@ -92,11 +92,12 @@ def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any])\n Assert that the contract holds as a precondition.\n \n :param contract: contract to be verified\n- :param resolved_kwargs: resolved keyword arguments (including the default values)\n+ :param resolved_kwargs:\n+ resolved keyword arguments of the call (including the default argument values of the decorated function)\n :return:\n \"\"\"\n # Check that all arguments to the condition function have been set.\n- missing_args = [arg_name for arg_name in contract.condition_args if arg_name not in resolved_kwargs]\n+ missing_args = [arg_name for arg_name in contract.mandatory_args if arg_name not in resolved_kwargs]\n if missing_args:\n raise TypeError(\n (\"The argument(s) of the precondition have not been set: {}. \"\n@@ -207,7 +208,7 @@ def _assert_postcondition(contract: Contract, resolved_kwargs: Mapping[str, Any]\n \"Expected 'result' to be set in the resolved keyword arguments of a postcondition.\"\n \n # Check that all arguments to the condition function have been set.\n- missing_args = [arg_name for arg_name in contract.condition_args if arg_name not in resolved_kwargs]\n+ missing_args = [arg_name for arg_name in contract.mandatory_args if arg_name not in resolved_kwargs]\n if missing_args:\n raise TypeError(\n (\"The argument(s) of the postcondition have not been set: {}. \"\ndiff --git a/icontract/_decorators.py b/icontract/_decorators.py\nindex f4cb5dc..e48b090 100644\n--- a/icontract/_decorators.py\n+++ b/icontract/_decorators.py\n@@ -326,7 +326,7 @@ class invariant: # pylint: disable=invalid-name\n self._contract = Contract(\n condition=condition, description=description, a_repr=a_repr, error=error, location=location)\n \n- if self._contract.condition_args and self._contract.condition_args != ['self']:\n+ if self._contract.mandatory_args and self._contract.mandatory_args != ['self']:\n raise ValueError(\"Expected an invariant condition with at most an argument 'self', but got: {}\".format(\n self._contract.condition_args))\n \ndiff --git a/icontract/_types.py b/icontract/_types.py\nindex c6e80d0..a7e01da 100644\n--- a/icontract/_types.py\n+++ b/icontract/_types.py\n@@ -37,9 +37,17 @@ class Contract:\n # pylint: disable=too-many-arguments\n self.condition = condition\n \n- self.condition_args = list(inspect.signature(condition).parameters.keys()) # type: List[str]\n+ signature = inspect.signature(condition)\n+\n+ # All argument names of the condition\n+ self.condition_args = list(signature.parameters.keys()) # type: List[str]\n self.condition_arg_set = set(self.condition_args) # type: Set[str]\n \n+ # Names of the mandatory arguments of the condition\n+ self.mandatory_args = [\n+ name for name, param in signature.parameters.items() if param.default == inspect.Parameter.empty\n+ ]\n+\n self.description = description\n self._a_repr = a_repr\n \n", "test_patch": "diff --git a/tests/test_invariant.py b/tests/test_invariant.py\nindex a971cd7..c18eba0 100644\n--- a/tests/test_invariant.py\n+++ b/tests/test_invariant.py\n@@ -386,6 +386,62 @@ class TestViolation(unittest.TestCase):\n self.assertIsNotNone(violation_error)\n self.assertEqual(\"z != 42: z was 42\", tests.error.wo_mandatory_location(str(violation_error)))\n \n+ def test_condition_as_function(self):\n+ def some_condition(self: 'A') -> bool: # type: ignore\n+ return self.x > 0\n+\n+ @icontract.invariant(some_condition)\n+ class A:\n+ def __init__(self) -> None:\n+ self.x = 100\n+\n+ def some_method(self) -> None:\n+ self.x = -1\n+\n+ def __repr__(self) -> str:\n+ return \"A(x={})\".format(self.x)\n+\n+ # Valid call\n+ a = A()\n+\n+ # Invalid call\n+ violation_error = None # type: Optional[icontract.ViolationError]\n+ try:\n+ a.some_method()\n+ except icontract.ViolationError as err:\n+ violation_error = err\n+\n+ self.assertIsNotNone(violation_error)\n+ self.assertEqual('some_condition: self was A(x=-1)', tests.error.wo_mandatory_location(str(violation_error)))\n+\n+ def test_condition_as_function_with_default_argument_value(self):\n+ def some_condition(self: 'A', y: int = 0) -> bool: # type: ignore\n+ return self.x > y\n+\n+ @icontract.invariant(some_condition)\n+ class A:\n+ def __init__(self) -> None:\n+ self.x = 100\n+\n+ def some_method(self) -> None:\n+ self.x = -1\n+\n+ def __repr__(self) -> str:\n+ return \"A(x={})\".format(self.x)\n+\n+ # Valid call\n+ a = A()\n+\n+ # Invalid call\n+ violation_error = None # type: Optional[icontract.ViolationError]\n+ try:\n+ a.some_method()\n+ except icontract.ViolationError as err:\n+ violation_error = err\n+\n+ self.assertIsNotNone(violation_error)\n+ self.assertEqual('some_condition: self was A(x=-1)', tests.error.wo_mandatory_location(str(violation_error)))\n+\n \n class TestProperty(unittest.TestCase):\n def test_property_getter(self):\ndiff --git a/tests/test_postcondition.py b/tests/test_postcondition.py\nindex 3cbe98a..4804dde 100644\n--- a/tests/test_postcondition.py\n+++ b/tests/test_postcondition.py\n@@ -41,6 +41,71 @@ class TestViolation(unittest.TestCase):\n \"result was -4\\n\"\n \"x was 1\", tests.error.wo_mandatory_location(str(violation_error)))\n \n+ def test_condition_as_function(self):\n+ def some_condition(result: int) -> bool:\n+ return result > 3\n+\n+ @icontract.ensure(some_condition)\n+ def some_func(x: int) -> int:\n+ return x\n+\n+ # Valid call\n+ some_func(x=4)\n+\n+ # Invalid call\n+ violation_error = None # type: Optional[icontract.ViolationError]\n+ try:\n+ some_func(x=1)\n+ except icontract.ViolationError as err:\n+ violation_error = err\n+\n+ self.assertIsNotNone(violation_error)\n+ self.assertEqual('some_condition: result was 1', tests.error.wo_mandatory_location(str(violation_error)))\n+\n+ def test_condition_as_function_with_default_argument_value(self):\n+ def some_condition(result: int, y: int = 0) -> bool:\n+ return result > y\n+\n+ @icontract.ensure(some_condition)\n+ def some_func(x: int) -> int:\n+ return x\n+\n+ # Valid call\n+ some_func(x=1)\n+\n+ # Invalid call\n+ violation_error = None # type: Optional[icontract.ViolationError]\n+ try:\n+ some_func(x=-1)\n+ except icontract.ViolationError as err:\n+ violation_error = err\n+\n+ self.assertIsNotNone(violation_error)\n+ self.assertEqual('some_condition: result was -1', tests.error.wo_mandatory_location(str(violation_error)))\n+\n+ def test_condition_as_function_with_default_argument_value_set(self):\n+ def some_condition(result: int, y: int = 0) -> bool:\n+ return result > y\n+\n+ @icontract.ensure(some_condition)\n+ def some_func(x: int, y: int) -> int:\n+ return x\n+\n+ # Valid call\n+ some_func(x=-1, y=-2)\n+\n+ # Invalid call\n+ violation_error = None # type: Optional[icontract.ViolationError]\n+ try:\n+ some_func(x=1, y=3)\n+ except icontract.ViolationError as err:\n+ violation_error = err\n+\n+ self.assertIsNotNone(violation_error)\n+ self.assertEqual('some_condition:\\n'\n+ 'result was 1\\n'\n+ 'y was 3', tests.error.wo_mandatory_location(str(violation_error)))\n+\n def test_with_description(self):\n @icontract.ensure(lambda result, x: result > x, \"expected summation\")\n def some_func(x: int, y: int = 5) -> int:\ndiff --git a/tests/test_precondition.py b/tests/test_precondition.py\nindex 9b08408..8709edb 100644\n--- a/tests/test_precondition.py\n+++ b/tests/test_precondition.py\n@@ -55,7 +55,7 @@ class TestViolation(unittest.TestCase):\n self.assertEqual(\"x must not be small: x > 3: x was 1\", tests.error.wo_mandatory_location(str(violation_error)))\n \n def test_condition_as_function(self):\n- def some_condition(x: int):\n+ def some_condition(x: int) -> bool:\n return x > 3\n \n @icontract.require(some_condition)\n@@ -71,6 +71,50 @@ class TestViolation(unittest.TestCase):\n self.assertIsNotNone(violation_error)\n self.assertEqual(\"some_condition: x was 1\", tests.error.wo_mandatory_location(str(violation_error)))\n \n+ def test_condition_as_function_with_default_argument_value(self):\n+ def some_condition(x: int, y: int = 0) -> bool:\n+ return x > y\n+\n+ @icontract.require(some_condition)\n+ def some_func(x: int) -> None:\n+ pass\n+\n+ # Valid call\n+ some_func(x=1)\n+\n+ # Invalid call\n+ violation_error = None # type: Optional[icontract.ViolationError]\n+ try:\n+ some_func(x=-1)\n+ except icontract.ViolationError as err:\n+ violation_error = err\n+\n+ self.assertIsNotNone(violation_error)\n+ self.assertEqual(\"some_condition: x was -1\", tests.error.wo_mandatory_location(str(violation_error)))\n+\n+ def test_condition_as_function_with_default_argument_value_set(self):\n+ def some_condition(x: int, y: int = 0) -> bool:\n+ return x > y\n+\n+ @icontract.require(some_condition)\n+ def some_func(x: int, y: int) -> None:\n+ pass\n+\n+ # Valid call\n+ some_func(x=3, y=1)\n+\n+ # Invalid call\n+ violation_error = None # type: Optional[icontract.ViolationError]\n+ try:\n+ some_func(x=-1, y=1)\n+ except icontract.ViolationError as err:\n+ violation_error = err\n+\n+ self.assertIsNotNone(violation_error)\n+ self.assertEqual('some_condition:\\n'\n+ 'x was -1\\n'\n+ 'y was 1', tests.error.wo_mandatory_location(str(violation_error)))\n+\n def test_with_pathlib(self):\n @icontract.require(lambda path: path.exists())\n def some_func(path: pathlib.Path) -> None:\n", "FAIL_TO_PASS": ["tests/test_invariant.py::TestViolation::test_condition_as_function_with_default_argument_value", "tests/test_postcondition.py::TestViolation::test_condition_as_function_with_default_argument_value", "tests/test_precondition.py::TestViolation::test_condition_as_function_with_default_argument_value"]}, {"instance_id": "Parquery__icontract-115", "base_commit": "21f6b8f51d4d458ee36b8a31cc091a5679a01000", "gold_patch": "diff --git a/icontract/_checkers.py b/icontract/_checkers.py\nindex e5909e2..19b1dcf 100644\n--- a/icontract/_checkers.py\n+++ b/icontract/_checkers.py\n@@ -58,7 +58,13 @@ def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args:\n \n # Override the defaults with the values actually suplied to the function.\n for i, func_arg in enumerate(args):\n- mapping[param_names[i]] = func_arg\n+ if i < len(param_names):\n+ mapping[param_names[i]] = func_arg\n+ else:\n+ # Silently ignore call arguments that were not specified in the function.\n+ # This way we let the underlying decorated function raise the exception\n+ # instead of frankensteining the exception here.\n+ pass\n \n for key, val in kwargs.items():\n mapping[key] = val\n@@ -336,7 +342,9 @@ def decorate_with_checker(func: CallableT) -> CallableT:\n \n resolved_kwargs['OLD'] = _Old(mapping=old_as_mapping)\n \n- # Execute the wrapped function\n+ # Ideally, we would catch any exception here and strip the checkers from the traceback.\n+ # Unfortunately, this can not be done in Python 3, see\n+ # https://stackoverflow.com/questions/44813333/how-can-i-elide-a-function-wrapper-from-the-traceback-in-python-3\n result = func(*args, **kwargs)\n \n if postconditions:\n", "test_patch": "diff --git a/tests/test_precondition.py b/tests/test_precondition.py\nindex 8709edb..0d4a8dc 100644\n--- a/tests/test_precondition.py\n+++ b/tests/test_precondition.py\n@@ -509,6 +509,34 @@ class TestInvalid(unittest.TestCase):\n self.assertEqual('Failed to negate the evaluation of the condition.',\n tests.error.wo_mandatory_location(str(value_error)))\n \n+ def test_unexpected_positional_argument(self):\n+ @icontract.require(lambda: True)\n+ def some_func() -> None:\n+ pass\n+\n+ type_error = None # type: Optional[TypeError]\n+ try:\n+ some_func(0) # pylint: disable=too-many-function-args\n+ except TypeError as err:\n+ type_error = err\n+\n+ self.assertIsNotNone(type_error)\n+ self.assertEqual('some_func() takes 0 positional arguments but 1 was given', str(type_error))\n+\n+ def test_unexpected_keyword_argument(self):\n+ @icontract.require(lambda: True)\n+ def some_func() -> None:\n+ pass\n+\n+ type_error = None # type: Optional[TypeError]\n+ try:\n+ some_func(x=0) # pylint: disable=unexpected-keyword-arg\n+ except TypeError as err:\n+ type_error = err\n+\n+ self.assertIsNotNone(type_error)\n+ self.assertEqual(\"some_func() got an unexpected keyword argument 'x'\", str(type_error))\n+\n \n if __name__ == '__main__':\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_precondition.py::TestInvalid::test_unexpected_positional_argument"]}], "all_FAIL_TO_PASS": ["tests/test_invariant.py::TestViolation::test_condition_as_function_with_default_argument_value", "tests/test_postcondition.py::TestViolation::test_condition_as_function_with_default_argument_value", "tests/test_precondition.py::TestViolation::test_condition_as_function_with_default_argument_value", "tests/test_precondition.py::TestInvalid::test_unexpected_positional_argument"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Ouranosinc__xclim-347_x2", "level": 2, "source": "swerebench", "repo": "Ouranosinc/xclim", "image": "swerebench/sweb.eval.x86_64.ouranosinc_1776_xclim-347:latest", "base_commit": "a4a8a7c4a7d2bb527ff11b77607189415c9def13", "num_bugs": 2, "bugs": [{"instance_id": "Ouranosinc__xclim-347", "base_commit": "a4a8a7c4a7d2bb527ff11b77607189415c9def13", "gold_patch": "diff --git a/HISTORY.rst b/HISTORY.rst\nindex 50dd6f92..ec7dbd31 100644\n--- a/HISTORY.rst\n+++ b/HISTORY.rst\n@@ -2,6 +2,11 @@\n History\n =======\n \n+0.14.x\n+------\n+* Fix in `subset.wrap_lons_and_split_at_greenwich` to preserve multi-region dataframes.\n+\n+\n 0.13.x (2020-01-10)\n -------------------\n * Documentation improvements: list of indicators, RTD theme, notebook example.\ndiff --git a/setup.cfg b/setup.cfg\nindex 1bb16fe4..df1ca2e7 100644\n--- a/setup.cfg\n+++ b/setup.cfg\n@@ -1,5 +1,5 @@\n [bumpversion]\n-current_version = 0.13.0\n+current_version = 0.13.1-beta\n commit = False\n tag = True\n parse = (?P\\d+)\\.(?P\\d+).(?P\\d+)(\\-(?P[a-z]+))?\ndiff --git a/setup.py b/setup.py\nindex 38f7694b..b3d84518 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -12,7 +12,7 @@ URL = \"https://github.com/Ouranosinc/xclim\"\n AUTHOR = \"Travis Logan\"\n AUTHOR_EMAIL = \"logan.travis@ouranos.ca\"\n REQUIRES_PYTHON = \">=3.6.0\"\n-VERSION = \"0.13.0\"\n+VERSION = \"0.13.1-beta\"\n LICENSE = \"Apache Software License 2.0\"\n \n with open(\"README.rst\") as readme_file:\ndiff --git a/xclim/__init__.py b/xclim/__init__.py\nindex f8a0186b..f6e7e099 100644\n--- a/xclim/__init__.py\n+++ b/xclim/__init__.py\n@@ -12,7 +12,7 @@ from xclim import seaIce\n \n __author__ = \"\"\"Travis Logan\"\"\"\n __email__ = \"logan.travis@ouranos.ca\"\n-__version__ = \"0.13.0\"\n+__version__ = \"0.13.1-beta\"\n \n \n def build_module(name, objs, doc=\"\", source=None, mode=\"ignore\"):\ndiff --git a/xclim/subset.py b/xclim/subset.py\nindex ff58380e..a61b36f8 100644\n--- a/xclim/subset.py\n+++ b/xclim/subset.py\n@@ -193,37 +193,38 @@ def wrap_lons_and_split_at_greenwich(func):\n stacklevel=4,\n )\n split_flag = False\n- if (poly.geometry.total_bounds[0] < 0) and (\n- poly.geometry.total_bounds[2] > 0\n- ):\n- split_flag = True\n- warnings.warn(\n- \"Geometry crosses the Greenwich Meridian. Proceeding to split polygon at Greenwich.\"\n- \" This feature is experimental. Output might not be accurate.\",\n- UserWarning,\n- stacklevel=4,\n- )\n-\n- # Create a meridian line at Greenwich, split polygons at this line and erase a buffer line\n- union = Polygon(cascaded_union(poly.geometry))\n- meridian = LineString([Point(0, 90), Point(0, -90)])\n- buffered = meridian.buffer(0.000000001)\n- split_polygons = split(union, meridian)\n- # TODO: This doesn't seem to be thread safe in Travis CI on macOS. Merits testing with a local machine.\n- buffered_split_polygons = [\n- feat for feat in split_polygons.difference(buffered)\n- ]\n-\n- # Load split features into a new GeoDataFrame with WGS84 CRS\n- split_gdf = gpd.GeoDataFrame(\n- list(range(len(buffered_split_polygons))),\n- geometry=buffered_split_polygons,\n- crs={\"init\": \"epsg:4326\"},\n- )\n- # split_gdf.crs = CRS.from_epsg(4326)\n- split_gdf.columns = [\"index\", \"geometry\"]\n-\n- poly = split_gdf\n+ for (index, feature) in poly.iterrows():\n+ if (feature.geometry.bounds[0] < 0) and (\n+ feature.geometry.bounds[2] > 0\n+ ):\n+ split_flag = True\n+ warnings.warn(\n+ \"Geometry crosses the Greenwich Meridian. Proceeding to split polygon at Greenwich.\"\n+ \" This feature is experimental. Output might not be accurate.\",\n+ UserWarning,\n+ stacklevel=4,\n+ )\n+\n+ # Create a meridian line at Greenwich, split polygons at this line and erase a buffer line\n+ union = Polygon(cascaded_union(feature.geometry))\n+ meridian = LineString([Point(0, 90), Point(0, -90)])\n+ buffered = meridian.buffer(0.000000001)\n+ split_polygons = split(union, meridian)\n+ # TODO: This doesn't seem to be thread safe in Travis CI on macOS. Merits testing with a local machine.\n+ buffered_split_polygons = [\n+ feat for feat in split_polygons.difference(buffered)\n+ ]\n+\n+ # Cannot assign iterable with `at` (pydata/pandas#26333) so a small hack:\n+ # Load split features into a new GeoDataFrame with WGS84 CRS\n+ split_gdf = gpd.GeoDataFrame(\n+ geometry=[cascaded_union(buffered_split_polygons)],\n+ crs={\"init\": \"epsg:4326\"},\n+ )\n+ poly.at[[index], \"geometry\"] = split_gdf.geometry.values\n+ # split_gdf.columns = [\"index\", \"geometry\"]\n+\n+ # feature = split_gdf\n \n # Reproject features in WGS84 CSR to use 0 to 360 as longitudinal values\n poly = poly.to_crs(\n@@ -238,6 +239,7 @@ def wrap_lons_and_split_at_greenwich(func):\n )\n poly = gpd.GeoDataFrame(poly.buffer(0.000000001), columns=[\"geometry\"])\n poly.crs = crs1\n+\n kwargs[\"poly\"] = poly\n \n return func(*args, **kwargs)\n@@ -253,7 +255,10 @@ def create_mask(\n poly: gpd.GeoDataFrame = None,\n wrap_lons: bool = False,\n ):\n- \"\"\"\n+ \"\"\"Creates a mask with values corresponding to the features in a GeoDataFrame.\n+\n+ The returned mask's points have the value of the first geometry of `poly` they fall in.\n+\n Parameters\n ----------\n x_dim : xarray.DataArray\n@@ -268,7 +273,33 @@ def create_mask(\n Returns\n -------\n xarray.DataArray\n+\n+ Examples\n+ --------\n+ >>> from xclim import subset\n+ >>> import xarray as xr\n+ >>> import geopandas as gpd\n+ >>> ds = xr.open_dataset('example.nc')\n+ >>> polys = gpd.read_file('regions.json')\n+ Get a mask from all polygons in 'regions.json'\n+ >>> mask = subset.create_mask(x_dim=ds.lon, y_dim=ds.lat, poly=polys)\n+ >>> ds = ds.assign_coords(regions=mask)\n+ Operations can be applied to each regions with `groupby`. Ex:\n+ >>> ds = ds.groupby('regions').mean()\n+ Extra step to retrieve the names of those polygons stored in the \"id\" column\n+ >>> region_names = xr.DataArray(polys.id, dims=('regions',)))\n+ >>> ds = ds.assign_coords(regions_names=region_names)\n \"\"\"\n+ # Check for intersections\n+ for i, (inda, pola) in enumerate(poly.iterrows()):\n+ for (indb, polb) in poly.loc[i + 1 :].iterrows():\n+ if pola.geometry.intersects(polb.geometry):\n+ warnings.warn(\n+ f\"List of shapes contains overlap between {inda} and {indb}. Only {inda} will be used.\",\n+ UserWarning,\n+ stacklevel=4,\n+ )\n+\n if len(x_dim.shape) == 1 & len(y_dim.shape) == 1:\n # create a 2d grid of lon, lat values\n lon1, lat1 = np.meshgrid(\n", "test_patch": "diff --git a/tests/test_subset.py b/tests/test_subset.py\nindex e3eacf7d..54462eea 100644\n--- a/tests/test_subset.py\n+++ b/tests/test_subset.py\n@@ -1,5 +1,6 @@\n import os\n \n+import geopandas as gpd\n import numpy as np\n import pytest\n import xarray as xr\n@@ -526,6 +527,7 @@ class TestSubsetShape:\n eastern_canada_geojson = os.path.join(TESTS_DATA, \"cmip5\", \"eastern_canada.json\")\n southern_qc_geojson = os.path.join(TESTS_DATA, \"cmip5\", \"southern_qc_geojson.json\")\n small_geojson = os.path.join(TESTS_DATA, \"cmip5\", \"small_geojson.json\")\n+ multi_regions_geojson = os.path.join(TESTS_DATA, \"cmip5\", \"multi_regions.json\")\n \n def compare_vals(self, ds, sub, vari, flag_2d=False):\n # check subsetted values against original\n@@ -649,6 +651,17 @@ class TestSubsetShape:\n assert len(sub.lon.values) == 3\n assert len(sub.lat.values) == 3\n \n+ def test_mask_multiregions(self):\n+ ds = xr.open_dataset(self.nc_file)\n+ regions = gpd.read_file(self.multi_regions_geojson)\n+\n+ mask = subset.create_mask(\n+ x_dim=ds.lon, y_dim=ds.lat, poly=regions, wrap_lons=True\n+ )\n+ vals, counts = np.unique(mask.values[mask.notnull()], return_counts=True)\n+ assert all(vals == [0, 1, 2])\n+ assert all(counts == [58, 250, 22])\n+\n \n class TestDistance:\n def test_values(self):\ndiff --git a/tests/testdata/cmip5/multi_regions.json b/tests/testdata/cmip5/multi_regions.json\nnew file mode 100644\nindex 00000000..8c0d9a7a\n--- /dev/null\n+++ b/tests/testdata/cmip5/multi_regions.json\n@@ -0,0 +1,162 @@\n+{\n+ \"type\": \"FeatureCollection\",\n+ \"features\": [\n+ {\n+ \"type\": \"Feature\",\n+ \"properties\": {\"id\": \"Qu\u00e9bec\"},\n+ \"geometry\": {\n+ \"type\": \"Polygon\",\n+ \"coordinates\": [\n+ [\n+ [\n+ -79.8046875,\n+ 63.39152174400882\n+ ],\n+ [\n+ -81.9140625,\n+ 48.22467264956519\n+ ],\n+ [\n+ -75.234375,\n+ 39.639537564366684\n+ ],\n+ [\n+ -62.9296875,\n+ 48.69096039092549\n+ ],\n+ [\n+ -48.515625,\n+ 54.57206165565852\n+ ],\n+ [\n+ -64.6875,\n+ 63.23362741232569\n+ ],\n+ [\n+ -78.046875,\n+ 63.39152174400882\n+ ],\n+ [\n+ -79.8046875,\n+ 63.39152174400882\n+ ]\n+ ]\n+ ]\n+ }\n+ },\n+ {\n+ \"type\": \"Feature\",\n+ \"properties\": {\"id\": \"Europe\"},\n+ \"geometry\": {\n+ \"type\": \"Polygon\",\n+ \"coordinates\": [\n+ [\n+ [\n+ -18.28125,\n+ 68.52823492039876\n+ ],\n+ [\n+ -27.0703125,\n+ 66.37275500247455\n+ ],\n+ [\n+ -18.28125,\n+ 61.10078883158897\n+ ],\n+ [\n+ -11.25,\n+ 55.57834467218206\n+ ],\n+ [\n+ -13.0078125,\n+ 46.800059446787316\n+ ],\n+ [\n+ -10.1953125,\n+ 32.84267363195431\n+ ],\n+ [\n+ 9.140625,\n+ 37.16031654673677\n+ ],\n+ [\n+ 29.53125,\n+ 33.137551192346145\n+ ],\n+ [\n+ 32.6953125,\n+ 42.8115217450979\n+ ],\n+ [\n+ 43.2421875,\n+ 48.45835188280866\n+ ],\n+ [\n+ 38.3203125,\n+ 65.6582745198266\n+ ],\n+ [\n+ 39.0234375,\n+ 70.8446726342528\n+ ],\n+ [\n+ 16.5234375,\n+ 73.42842364106816\n+ ],\n+ [\n+ -10.546875,\n+ 71.07405646336098\n+ ],\n+ [\n+ -18.28125,\n+ 68.00757101804004\n+ ],\n+ [\n+ -18.28125,\n+ 68.52823492039876\n+ ]\n+ ]\n+ ]\n+ }\n+ },\n+ {\n+ \"type\": \"Feature\",\n+ \"properties\": {\"id\": \"Newfoundland\"},\n+ \"geometry\": {\n+ \"type\": \"Polygon\",\n+ \"coordinates\": [\n+ [\n+ [\n+ -46.40625,\n+ 57.70414723434193\n+ ],\n+ [\n+ -57.65624999999999,\n+ 54.77534585936447\n+ ],\n+ [\n+ -64.6875,\n+ 46.800059446787316\n+ ],\n+ [\n+ -58.00781249999999,\n+ 40.713955826286046\n+ ],\n+ [\n+ -47.4609375,\n+ 45.583289756006316\n+ ],\n+ [\n+ -42.890625,\n+ 53.74871079689897\n+ ],\n+ [\n+ -46.40625,\n+ 57.70414723434193\n+ ]\n+ ]\n+ ]\n+ }\n+ }\n+ ]\n+}\n", "FAIL_TO_PASS": ["tests/test_subset.py::TestSubsetShape::test_mask_multiregions"]}, {"instance_id": "Ouranosinc__xclim-349", "base_commit": "7d331b5a2753f334d6e066d14ed64f6b5718e051", "gold_patch": "diff --git a/HISTORY.rst b/HISTORY.rst\nindex ec7dbd31..4d84de91 100644\n--- a/HISTORY.rst\n+++ b/HISTORY.rst\n@@ -5,6 +5,7 @@ History\n 0.14.x\n ------\n * Fix in `subset.wrap_lons_and_split_at_greenwich` to preserve multi-region dataframes.\n+* Improve the memory use of `indices.growing_season_length`.\n \n \n 0.13.x (2020-01-10)\ndiff --git a/xclim/atmos/_temperature.py b/xclim/atmos/_temperature.py\nindex 9fadd0b6..0129412f 100644\n--- a/xclim/atmos/_temperature.py\n+++ b/xclim/atmos/_temperature.py\n@@ -420,8 +420,7 @@ growing_season_length = Tas(\n description=\"{freq} number of days between the first occurrence of at least \"\n \"six consecutive days with mean daily temperature over {thresh} and \"\n \"the first occurrence of at least {window} consecutive days with \"\n- \"mean daily temperature below {thresh} after July 1st in the northern \"\n- \"hemisphere and January 1st in the southern hemisphere\",\n+ \"mean daily temperature below {thresh} after {mid_date}.\",\n cell_methods=\"\",\n compute=indices.growing_season_length,\n )\ndiff --git a/xclim/indices/_threshold.py b/xclim/indices/_threshold.py\nindex 486ee841..d950da28 100644\n--- a/xclim/indices/_threshold.py\n+++ b/xclim/indices/_threshold.py\n@@ -1,5 +1,7 @@\n import numpy as np\n import xarray\n+import datetime\n+from typing import Union\n \n from xclim import run_length as rl\n from xclim import utils\n@@ -304,15 +306,21 @@ def growing_degree_days(\n \n @declare_units(\"days\", tas=\"[temperature]\", thresh=\"[temperature]\")\n def growing_season_length(\n- tas: xarray.DataArray, thresh: str = \"5.0 degC\", window: int = 6, freq: str = \"YS\"\n+ tas: xarray.DataArray,\n+ thresh: str = \"5.0 degC\",\n+ window: int = 6,\n+ mid_date: str = \"07-01\",\n+ freq: str = \"YS\",\n ):\n r\"\"\"Growing season length.\n \n The number of days between the first occurrence of at least\n six consecutive days with mean daily temperature over 5\u2103 and\n the first occurrence of at least six consecutive days with\n- mean daily temperature below 5\u2103 after July 1st in the northern\n- hemisphere and January 1st in the southern hemisphere.\n+ mean daily temperature below 5\u2103 after a certain date. (Usually\n+ July 1st in the northern hemisphere and January 1st in the southern hemisphere.)\n+\n+ WARNING: The default values are only valid for the northern hemisphere.\n \n Parameters\n ---------\n@@ -322,6 +330,8 @@ def growing_season_length(\n Threshold temperature on which to base evaluation [\u2103] or [K]. Default: '5.0 degC'.\n window : int\n Minimum number of days with temperature above threshold to mark the beginning and end of growing season.\n+ mid_date : str\n+ Date of the year after which to look for the end of the season. Should have the format '%m-%d'.\n freq : str\n Resampling frequency; Defaults to \"YS\".\n \n@@ -344,50 +354,45 @@ def growing_season_length(\n .. math::\n \n TG_{ij} < 5 \u2103\n- \"\"\"\n \n- # i = xr.DataArray(np.arange(tas.time.size), dims='time')\n- # ind = xr.broadcast(i, tas)[0]\n- #\n- # c = ((tas > thresh) * 1).rolling(time=window).sum()\n- # i1 = ind.where(c == window).resample(time=freq).min(dim='time')\n- #\n- # # Resample sets the time to T00:00.\n- # i11 = i1.reindex_like(c, method='ffill')\n- #\n- # # TODO: Adjust for southern hemisphere\n- #\n- # #i2 = ind.where(c == 0).where(tas.time.dt.month >= 7)\n- # # add check to make sure indice of end of growing season is after growing season start\n- # i2 = ind.where((c==0) & (ind > i11)).where(tas.time.dt.month >= 7)\n- #\n- # d = i2 - i11\n- #\n- # # take min value (first occurence after july)\n- # gsl = d.resample(time=freq).min(dim='time')\n- #\n- # # turn nan into 0\n- # gsl = xr.where(np.isnan(gsl), 0, gsl)\n-\n- # compute growth season length on resampled data\n+ Examples\n+ --------\n+ If working in the Southern Hemisphere, one can use:\n+ >>> gsl = growing_season_length(tas, mid_date='01-01', freq='AS-Jul')\n+ \"\"\"\n thresh = utils.convert_units_to(thresh, tas)\n \n- c = ((tas > thresh) * 1).rolling(time=window).sum(allow_lazy=True, skipna=False)\n-\n- def compute_gsl(c):\n- nt = c.time.size\n- i = xarray.DataArray(np.arange(nt), dims=\"time\").chunk({\"time\": 1})\n- ind = xarray.broadcast(i, c)[0].chunk(c.chunks)\n- i1 = ind.where(c == window).min(dim=\"time\")\n- i1 = xarray.where(np.isnan(i1), nt, i1)\n- i11 = i1.reindex_like(c, method=\"ffill\")\n- i2 = ind.where((c == 0) & (ind > i11)).where(c.time.dt.month >= 7)\n- i2 = xarray.where(np.isnan(i2), nt, i2)\n- d = (i2 - i1).min(dim=\"time\")\n- return d\n-\n- gsl = c.resample(time=freq).apply(compute_gsl)\n-\n+ mid_doy = datetime.datetime.strptime(mid_date, \"%m-%d\").timetuple().tm_yday\n+\n+ def compute_gsl(yrdata):\n+ if (\n+ yrdata.chunks is not None\n+ and len(yrdata.chunks[yrdata.dims.index(\"time\")]) > 1\n+ ):\n+ yrdata = yrdata.chunk({\"time\": -1})\n+ mid_idx = np.where(yrdata.time.dt.dayofyear == mid_doy)[0]\n+ if (\n+ mid_idx.size == 0\n+ ): # The mid date is not in the group. Happens at boundaries.\n+ allNans = xarray.full_like(yrdata.isel(time=0), np.nan)\n+ allNans.attrs = {}\n+ return allNans\n+ end = rl.first_run(\n+ yrdata.where(yrdata.time >= yrdata.time[mid_idx][0]) < thresh,\n+ window,\n+ \"time\",\n+ )\n+ beg = rl.first_run(yrdata > thresh, window, \"time\")\n+ sl = end - beg\n+ sl = xarray.where(\n+ beg.isnull() & end.notnull(), 0, sl\n+ ) # If everything is under thresh\n+ sl = xarray.where(\n+ beg.notnull() & end.isnull(), yrdata.time.size - beg, sl\n+ ) # If gs is not ended at end of year\n+ return sl.where(sl >= 0) # When end happens before beg.\n+\n+ gsl = tas.resample(time=freq).map(compute_gsl)\n return gsl\n \n \ndiff --git a/xclim/run_length.py b/xclim/run_length.py\nindex 96811898..0824dc57 100644\n--- a/xclim/run_length.py\n+++ b/xclim/run_length.py\n@@ -262,7 +262,8 @@ def rle_1d(\n if n == 0:\n e = \"run length array empty\"\n warn(e)\n- return None, None, None\n+ # Returning None makes some other 1d func below fail.\n+ return np.array(np.nan), 0, np.array(np.nan)\n \n y = np.array(ia[1:] != ia[:-1]) # pairwise unequal (string safe)\n i = np.append(np.where(y), n - 1) # must include last element position\n", "test_patch": "diff --git a/tests/test_indices.py b/tests/test_indices.py\nindex b0a1161d..0c4297d1 100644\n--- a/tests/test_indices.py\n+++ b/tests/test_indices.py\n@@ -334,48 +334,32 @@ class TestGrowingDegreeDays:\n \n \n class TestGrowingSeasonLength:\n- def test_simple(self, tas_series):\n+ @pytest.mark.parametrize(\n+ \"d1,d2,expected\",\n+ [\n+ (\"1950-01-01\", \"1951-01-01\", 0), # No growing season\n+ (\"2000-01-01\", \"2000-12-31\", 365), # All year growing season\n+ (\"2000-07-10\", \"2001-01-01\", np.nan), # End happens before start\n+ (\"2000-06-15\", \"2001-01-01\", 199), # No end\n+ (\"2000-06-15\", \"2000-07-15\", 31), # Normal case\n+ ],\n+ )\n+ def test_simple(self, tas_series, d1, d2, expected):\n # test for different growing length\n \n- # generate 5 years of data\n- a = np.zeros(366 * 2 + 365 * 3)\n- tas = tas_series(a, start=\"2000/1/1\")\n-\n- # 2000 : no growing season\n-\n- # 2001 : growing season all year\n- d1 = \"27-12-2000\"\n- d2 = \"31-12-2001\"\n- buffer = tas.sel(time=slice(d1, d2))\n- tas = tas.where(~tas.time.isin(buffer.time), 280)\n-\n- # 2002 : growing season in June only\n- d1 = \"6-1-2002\"\n- d2 = \"6-10-2002\"\n- buffer = tas.sel(time=slice(d1, d2))\n- tas = tas.where(~tas.time.isin(buffer.time), 280)\n- #\n- # comment:\n- # correct answer should be 10 (i.e. there are 10 days\n- # with tas > 5 degC) but current definition imposes end\n- # of growing season to be equal or later than July 1st.\n-\n- # growing season in Aug only\n- d1 = \"8-1-2003\"\n- d2 = \"8-10-2003\"\n- buffer = tas.sel(time=slice(d1, d2))\n- tas = tas.where(~tas.time.isin(buffer.time), 280)\n-\n- # growing season from June to end of July\n- d1 = \"6-1-2004\"\n- d2 = \"7-31-2004\"\n- buffer = tas.sel(time=slice(d1, d2))\n- tas = tas.where(~tas.time.isin(buffer.time), 280)\n-\n+ # generate a year of data\n+ tas = tas_series(np.zeros(365), start=\"2000/1/1\")\n+ warm_period = tas.sel(time=slice(d1, d2))\n+ tas = tas.where(~tas.time.isin(warm_period.time), 280)\n gsl = xci.growing_season_length(tas)\n- target = [0, 365, 25, 10, 61]\n-\n- np.testing.assert_array_equal(gsl, target)\n+ np.testing.assert_array_equal(gsl, expected)\n+\n+ def test_southhemisphere(self, tas_series):\n+ tas = tas_series(np.zeros(2 * 365), start=\"2000/1/1\")\n+ warm_period = tas.sel(time=slice(\"2000-11-01\", \"2001-03-01\"))\n+ tas = tas.where(~tas.time.isin(warm_period.time), 280)\n+ gsl = xci.growing_season_length(tas, mid_date=\"01-01\", freq=\"AS-Jul\")\n+ np.testing.assert_array_equal(gsl.sel(time=\"2000-07-01\"), 121)\n \n \n class TestHeatingDegreeDays:\n", "FAIL_TO_PASS": ["tests/test_indices.py::TestGrowingSeasonLength::test_simple[2000-01-01-2000-12-31-365]", "tests/test_indices.py::TestGrowingSeasonLength::test_simple[2000-07-10-2001-01-01-nan]", "tests/test_indices.py::TestGrowingSeasonLength::test_simple[2000-06-15-2001-01-01-199]", "tests/test_indices.py::TestGrowingSeasonLength::test_southhemisphere"]}], "all_FAIL_TO_PASS": ["tests/test_subset.py::TestSubsetShape::test_mask_multiregions", "tests/test_indices.py::TestGrowingSeasonLength::test_simple[2000-01-01-2000-12-31-365]", "tests/test_indices.py::TestGrowingSeasonLength::test_simple[2000-07-10-2001-01-01-nan]", "tests/test_indices.py::TestGrowingSeasonLength::test_simple[2000-06-15-2001-01-01-199]", "tests/test_indices.py::TestGrowingSeasonLength::test_southhemisphere"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "fitbenchmarking__fitbenchmarking-1110_x2", "level": 2, "source": "swerebench", "repo": "fitbenchmarking/fitbenchmarking", "image": "swerebench/sweb.eval.x86_64.fitbenchmarking_1776_fitbenchmarking-1110:latest", "base_commit": "df465dc1b60d580dfb885ee9d03866c25988566f", "num_bugs": 2, "bugs": [{"instance_id": "fitbenchmarking__fitbenchmarking-1110", "base_commit": "df465dc1b60d580dfb885ee9d03866c25988566f", "gold_patch": "diff --git a/docs/source/users/options/minimizer_option.rst b/docs/source/users/options/minimizer_option.rst\nindex 2a48debb..12f52da4 100644\n--- a/docs/source/users/options/minimizer_option.rst\n+++ b/docs/source/users/options/minimizer_option.rst\n@@ -569,6 +569,12 @@ Hessian information as inputs.\n * `L-BFGS-B algorithm `__ (:code:`L-BFGS-B`)\n * `Truncated Newton (TNC) algorithm `__ (:code:`TNC`)\n * `Sequential Least SQuares Programming `__ (:code:`SLSQP`)\n+* `Constrained Optimization BY Linear Approximations `__ (:code:`COBYLA`)\n+* `Newton-CG trust-region `__ (:code:`trust-ncg`)\n+* `Nearly exact trust-region `__ (:code:`trust-exact`)\n+* `Newton Generalized Lanczos Trust Region `__ (:code:`trust-krylov`)\n+* `Trust-region for constrained optimization `__ (:code:`trust-constr`)\n+* `Dog-leg trust-region `__ (:code:`dogleg`)\n \n **Links** `Github - SciPy minimize `__\n \n@@ -587,6 +593,12 @@ The SciPy minimizers are set as follows:\n L-BFGS-B\n TNC\n SLSQP\n+ COBYLA\n+ trust-ncg\n+ trust-exact\n+ trust-krylov\n+ trust-constr\n+ dogleg\n \n .. _scipy-ls:\n \ndiff --git a/fitbenchmarking/controllers/scipy_controller.py b/fitbenchmarking/controllers/scipy_controller.py\nindex a845d5f4..4e4009fd 100644\n--- a/fitbenchmarking/controllers/scipy_controller.py\n+++ b/fitbenchmarking/controllers/scipy_controller.py\n@@ -15,14 +15,30 @@ class ScipyController(Controller):\n \"\"\"\n \n algorithm_check = {\n- 'all': ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG',\n- 'L-BFGS-B', 'TNC', 'SLSQP'],\n+ 'all': ['Nelder-Mead',\n+ 'Powell',\n+ 'CG',\n+ 'BFGS',\n+ 'Newton-CG',\n+ 'L-BFGS-B',\n+ 'TNC',\n+ 'SLSQP',\n+ 'COBYLA',\n+ 'trust-ncg',\n+ 'trust-exact',\n+ 'trust-krylov',\n+ 'trust-constr',\n+ 'dogleg'],\n 'ls': [None],\n- 'deriv_free': ['Nelder-Mead', 'Powell'],\n+ 'deriv_free': ['Nelder-Mead', 'Powell', 'COBYLA'],\n 'general': ['Nelder-Mead', 'Powell', 'CG', 'BFGS',\n 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP'],\n 'simplex': ['Nelder-Mead'],\n- 'trust_region': [],\n+ 'trust_region': ['trust-ncg',\n+ 'trust-exact',\n+ 'trust-krylov',\n+ 'trust-constr',\n+ 'dogleg'],\n 'levenberg-marquardt': [],\n 'gauss_newton': [],\n 'bfgs': ['BFGS', 'L-BFGS-B'],\n@@ -30,10 +46,24 @@ class ScipyController(Controller):\n 'steepest_descent': [],\n 'global_optimization': []}\n \n- jacobian_enabled_solvers = ['CG', 'BFGS', 'Newton-CG',\n- 'L-BFGS-B', 'TNC', 'SLSQP']\n-\n- hessian_enabled_solvers = ['Newton-CG']\n+ jacobian_enabled_solvers = ['CG',\n+ 'BFGS',\n+ 'Newton-CG',\n+ 'L-BFGS-B',\n+ 'TNC',\n+ 'SLSQP',\n+ 'trust-ncg',\n+ 'trust-exact',\n+ 'trust-krylov',\n+ 'trust-constr',\n+ 'dogleg']\n+\n+ hessian_enabled_solvers = ['Newton-CG',\n+ 'trust-ncg',\n+ 'trust-exact',\n+ 'trust-krylov',\n+ 'trust-constr',\n+ 'dogleg']\n \n def __init__(self, cost_func):\n \"\"\"\ndiff --git a/fitbenchmarking/utils/options.py b/fitbenchmarking/utils/options.py\nindex 1732aff2..9abe7d78 100644\n--- a/fitbenchmarking/utils/options.py\n+++ b/fitbenchmarking/utils/options.py\n@@ -52,8 +52,20 @@ class Options:\n 'matlab_stats': ['Levenberg-Marquardt'],\n 'minuit': ['minuit'],\n 'ralfit': ['gn', 'gn_reg', 'hybrid', 'hybrid_reg'],\n- 'scipy': ['Nelder-Mead', 'Powell', 'CG', 'BFGS',\n- 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP'],\n+ 'scipy': ['Nelder-Mead',\n+ 'Powell',\n+ 'CG',\n+ 'BFGS',\n+ 'Newton-CG',\n+ 'L-BFGS-B',\n+ 'TNC',\n+ 'SLSQP',\n+ 'COBYLA',\n+ 'trust-ncg',\n+ 'trust-exact',\n+ 'trust-krylov',\n+ 'trust-constr',\n+ 'dogleg'],\n 'scipy_ls': ['lm-scipy', 'trf', 'dogbox'],\n 'scipy_go': ['differential_evolution', 'shgo', 'dual_annealing']}\n VALID_FITTING = \\\n@@ -140,8 +152,20 @@ class Options:\n 'matlab_stats': ['Levenberg-Marquardt'],\n 'minuit': ['minuit'],\n 'ralfit': ['gn', 'gn_reg', 'hybrid', 'hybrid_reg'],\n- 'scipy': ['Nelder-Mead', 'Powell', 'CG', 'BFGS',\n- 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP'],\n+ 'scipy': ['Nelder-Mead',\n+ 'Powell',\n+ 'CG',\n+ 'BFGS',\n+ 'Newton-CG',\n+ 'L-BFGS-B',\n+ 'TNC',\n+ 'SLSQP',\n+ 'COBYLA',\n+ 'trust-ncg',\n+ 'trust-exact',\n+ 'trust-krylov',\n+ 'trust-constr',\n+ 'dogleg'],\n 'scipy_ls': ['lm-scipy', 'trf', 'dogbox'],\n 'scipy_go': ['differential_evolution', 'dual_annealing']}\n DEFAULT_FITTING = \\\n", "test_patch": "diff --git a/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py b/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py\nindex ecefc632..4b4fa7be 100644\n--- a/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py\n+++ b/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py\n@@ -191,7 +191,7 @@ class LoopOverSoftwareTests(unittest.TestCase):\n [fitbm_result.FittingResult(**self.result_args)\n for i in range(self.scipy_ls_len)]]\n loop_over_minimizers.side_effect = self.mock_func_call\n- expected_list_len = 13\n+ expected_list_len = 19\n expected_minimizer_failed = self.minimizer_failed\n self.shared_test(expected_list_len, expected_minimizer_failed)\n \ndiff --git a/fitbenchmarking/utils/tests/test_options_minimizers.py b/fitbenchmarking/utils/tests/test_options_minimizers.py\nindex 3261bc77..7f7d7654 100644\n--- a/fitbenchmarking/utils/tests/test_options_minimizers.py\n+++ b/fitbenchmarking/utils/tests/test_options_minimizers.py\n@@ -83,8 +83,20 @@ class MininimizerOptionTests(unittest.TestCase):\n \"\"\"\n Checks valid scipy minimizers are set correctly\n \"\"\"\n- expected = ['Nelder-Mead', 'Powell', 'CG', 'BFGS',\n- 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP']\n+ expected = ['Nelder-Mead',\n+ 'Powell',\n+ 'CG',\n+ 'BFGS',\n+ 'Newton-CG',\n+ 'L-BFGS-B',\n+ 'TNC',\n+ 'SLSQP',\n+ 'COBYLA',\n+ 'trust-ncg',\n+ 'trust-exact',\n+ 'trust-krylov',\n+ 'trust-constr',\n+ 'dogleg']\n actual = self.options.minimizers['scipy']\n self.assertEqual(expected, actual)\n \n", "FAIL_TO_PASS": ["fitbenchmarking/core/tests/test_fitting_benchmarking_software.py::LoopOverSoftwareTests::test_run_software_all_failed_minimizers", "fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_scipy"]}, {"instance_id": "fitbenchmarking__fitbenchmarking-1119", "base_commit": "e52a2f24eb5b727d719faacf66c49b878e332056", "gold_patch": "diff --git a/docs/source/users/options/minimizer_option.rst b/docs/source/users/options/minimizer_option.rst\nindex 5f62380c..7059eb57 100644\n--- a/docs/source/users/options/minimizer_option.rst\n+++ b/docs/source/users/options/minimizer_option.rst\n@@ -65,7 +65,7 @@ The Bumps minimizers are set as follows:\n `de` is not included in the default list of minimizers for bumps. To run this solver, you must\n explicitly set the minimizer as seen above.\n \n-.. _dfo:\n+.. _ceres:\n \n Ceres Solver (``ceres``)\n =============\n@@ -111,6 +111,8 @@ The Ceres Solver minimizers are set as follows:\n .. note::\n The PyCeres currently only works with Ceres Solver versions 2.0.0 \n \n+.. _dfo:\n+\n DFO (``dfo``)\n =============\n \n@@ -312,6 +314,11 @@ spectrometers.* We currently support:\n `proprietary product `__.\n Horace is made available under the the `GPL-3 licence `__.\n \n+.. code-block:: rst\n+\n+ [MINIMIZERS]\n+ horace: lm-lsqr\n+\n .. warning::\n The Horace Toolbox and MATLAB must be installed for this to be available; see :ref:`external-instructions`.\n \n@@ -672,6 +679,10 @@ The SciPy minimizers are set as follows:\n trust-constr\n dogleg\n \n+.. note::\n+ The Hessian enabled solvers are not run by default when `scipy` software is selected. In order to run these minimizers, you must explicitly\n+ set them as above.\n+\n .. _scipy-ls:\n \n SciPy LS (``scipy_ls``)\ndiff --git a/fitbenchmarking/utils/options.py b/fitbenchmarking/utils/options.py\nindex a1ef0b19..a949521e 100644\n--- a/fitbenchmarking/utils/options.py\n+++ b/fitbenchmarking/utils/options.py\n@@ -203,12 +203,7 @@ class Options:\n 'L-BFGS-B',\n 'TNC',\n 'SLSQP',\n- 'COBYLA',\n- 'trust-ncg',\n- 'trust-exact',\n- 'trust-krylov',\n- 'trust-constr',\n- 'dogleg'],\n+ 'COBYLA'],\n 'scipy_ls': ['lm-scipy', 'trf', 'dogbox'],\n 'scipy_go': ['differential_evolution', 'dual_annealing']}\n DEFAULT_FITTING = \\\n", "test_patch": "diff --git a/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py b/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py\nindex 4b4fa7be..6c70a75e 100644\n--- a/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py\n+++ b/fitbenchmarking/core/tests/test_fitting_benchmarking_software.py\n@@ -191,7 +191,7 @@ class LoopOverSoftwareTests(unittest.TestCase):\n [fitbm_result.FittingResult(**self.result_args)\n for i in range(self.scipy_ls_len)]]\n loop_over_minimizers.side_effect = self.mock_func_call\n- expected_list_len = 19\n+ expected_list_len = 14\n expected_minimizer_failed = self.minimizer_failed\n self.shared_test(expected_list_len, expected_minimizer_failed)\n \ndiff --git a/fitbenchmarking/utils/tests/test_options_minimizers.py b/fitbenchmarking/utils/tests/test_options_minimizers.py\nindex 7f7d7654..2cb7ade5 100644\n--- a/fitbenchmarking/utils/tests/test_options_minimizers.py\n+++ b/fitbenchmarking/utils/tests/test_options_minimizers.py\n@@ -91,12 +91,7 @@ class MininimizerOptionTests(unittest.TestCase):\n 'L-BFGS-B',\n 'TNC',\n 'SLSQP',\n- 'COBYLA',\n- 'trust-ncg',\n- 'trust-exact',\n- 'trust-krylov',\n- 'trust-constr',\n- 'dogleg']\n+ 'COBYLA']\n actual = self.options.minimizers['scipy']\n self.assertEqual(expected, actual)\n \n", "FAIL_TO_PASS": ["fitbenchmarking/core/tests/test_fitting_benchmarking_software.py::LoopOverSoftwareTests::test_run_software_all_failed_minimizers", "fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_scipy"]}], "all_FAIL_TO_PASS": ["fitbenchmarking/core/tests/test_fitting_benchmarking_software.py::LoopOverSoftwareTests::test_run_software_all_failed_minimizers", "fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_scipy", "fitbenchmarking/core/tests/test_fitting_benchmarking_software.py::LoopOverSoftwareTests::test_run_software_all_failed_minimizers", "fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_scipy"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "DevoInc__python-sdk-109_x2", "level": 2, "source": "swerebench", "repo": "DevoInc/python-sdk", "image": "swerebench/sweb.eval.x86_64.devoinc_1776_python-sdk-109:latest", "base_commit": "805bb8561837e83ced05d8326e5cd24658a870ba", "num_bugs": 2, "bugs": [{"instance_id": "DevoInc__python-sdk-109", "base_commit": "805bb8561837e83ced05d8326e5cd24658a870ba", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex d82fb96..28e86d5 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.\n ## Unreleased - 2021-11-18\n ### Fixed\n * Fix and skip some non-working tests\n+* `Lookup.send_headers` method not working as expected with key_index parameter\n+* Add `type_of_key` parameter to `Lookup.send_headers` method\n+* Avoid lookups' key element to be deleted when `Lookup.send_data_line` is invoked.\n \n \n ## [3.4.2] - 2021-05-18\ndiff --git a/devo/sender/lookup.py b/devo/sender/lookup.py\nindex a0ecea0..d92908e 100644\n--- a/devo/sender/lookup.py\n+++ b/devo/sender/lookup.py\n@@ -1,9 +1,9 @@\n # -*- coding: utf-8 -*-\n \"\"\" File with utils for send Lookups to Devo \"\"\"\n-import time\n-import sys\n import csv\n import re\n+import sys\n+import time\n \n \n def find_key_index(value=None, headers=None):\n@@ -62,7 +62,8 @@ class Lookup:\n # Helper methods\n # --------------------------------------------------------------------------\n def send_headers(self, headers=None, key=\"KEY\", event='START',\n- action='FULL', types=None, key_index=None):\n+ action='FULL', types=None, key_index=None,\n+ type_of_key=\"str\"):\n \"\"\"\n Send only the headers\n :param headers: list with headers names\n@@ -71,10 +72,12 @@ class Lookup:\n :param event: START or END\n :param action: FULL or INC to send new full lookup or for update one\n :param types: dict with types of each header\n+ :param type_of_key: the key's type (str by default)\n :return:\n \"\"\"\n p_headers = Lookup.list_to_headers(headers=headers, key=key,\n- types=types, key_index=key_index)\n+ types=types, key_index=key_index,\n+ type_of_key=type_of_key)\n self.send_control(event=event, headers=p_headers, action=action)\n \n def send_data_line(self, key=None, fields=None,\n@@ -320,16 +323,16 @@ class Lookup:\n :result str:\n \"\"\"\n # First the key\n- if key is not None:\n- out = '[{\"%s\":{\"type\":\"%s\",\"key\":true}}' % (key, types[key_index]\n- if key_index and types\n- else type_of_key)\n- elif key_index is not None:\n+ if key_index is not None:\n key = headers[key_index]\n out = '[{\"%s\":{\"type\":\"%s\",\"key\":true}}' % (key,\n types[key_index]\n if types\n else type_of_key)\n+ elif key is not None:\n+ out = '[{\"%s\":{\"type\":\"%s\",\"key\":true}}' % (key, types[key_index]\n+ if key_index and types\n+ else type_of_key)\n else:\n raise Exception(\"Not key identified\")\n \n@@ -365,10 +368,10 @@ class Lookup:\n :return:\n \"\"\"\n # First the key\n- out = '%s' % Lookup.clean_field(fields.pop(key_index))\n+ out = '%s' % Lookup.clean_field(fields[key_index])\n \n # The rest of the fields\n- for item in fields:\n+ for item in fields[:key_index] + fields[key_index + 1:]:\n out += Lookup.field_to_str(item)\n return out\n \n", "test_patch": "diff --git a/tests/sender/cli.py b/tests/sender/cli.py\nindex 5347e20..6885cea 100644\n--- a/tests/sender/cli.py\n+++ b/tests/sender/cli.py\n@@ -99,8 +99,8 @@ class TestSender(unittest.TestCase):\n \"--cert\", self.cert,\n \"--chain\", self.chain,\n \"--tag\", self.my_app,\n- \"--verify_mode\", 1,\n- '--check_hostname', True,\n+ \"--verify_mode\", 0,\n+ '--check_hostname', False,\n \"--line\", \"Test line\"])\n \n self.assertIsNone(result.exception)\ndiff --git a/tests/sender/send_lookup.py b/tests/sender/send_lookup.py\nindex f7a0652..4e7e416 100644\n--- a/tests/sender/send_lookup.py\n+++ b/tests/sender/send_lookup.py\n@@ -1,147 +1,248 @@\n import unittest\n from ssl import CERT_NONE\n+from unittest import mock\n+\n from devo.sender import Sender, SenderConfigSSL, Lookup\n from .load_certs import *\n \n \n class TestLookup(unittest.TestCase):\n def setUp(self):\n- self.server = os.getenv('DEVO_SENDER_SERVER', \"127.0.0.1\")\n- self.port = int(os.getenv('DEVO_SENDER_PORT', 4488))\n+ self.server = os.getenv(\"DEVO_SENDER_SERVER\", \"127.0.0.1\")\n+ self.port = int(os.getenv(\"DEVO_SENDER_PORT\", 4488))\n \n- self.key = os.getenv('DEVO_SENDER_KEY', CLIENT_KEY)\n- self.cert = os.getenv('DEVO_SENDER_CERT', CLIENT_CERT)\n- self.chain = os.getenv('DEVO_SENDER_CHAIN', CLIENT_CHAIN)\n+ self.key = os.getenv(\"DEVO_SENDER_KEY\", CLIENT_KEY)\n+ self.cert = os.getenv(\"DEVO_SENDER_CERT\", CLIENT_CERT)\n+ self.chain = os.getenv(\"DEVO_SENDER_CHAIN\", CLIENT_CHAIN)\n \n- self.lookup_name = 'Test_Lookup_of_today'\n- self.lookup_file = \"\".join((os.path.dirname(os.path.abspath(__file__)),\n- os.sep, \"testfile_lookup.csv\"))\n+ self.lookup_name = \"Test_Lookup_of_today\"\n+ self.lookup_file = \"\".join(\n+ (\n+ os.path.dirname(os.path.abspath(__file__)),\n+ os.sep,\n+ \"testfile_lookup.csv\",\n+ )\n+ )\n \n- self.lookup_key = 'KEY'\n+ self.lookup_key = \"KEY\"\n \n def test_ssl_lookup_csv_send(self):\n \n- engine_config = SenderConfigSSL(address=(self.server, self.port),\n- key=self.key, cert=self.cert,\n- chain=self.chain,\n- check_hostname=False,\n- verify_mode=CERT_NONE)\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ chain=self.chain,\n+ check_hostname=False,\n+ verify_mode=CERT_NONE,\n+ )\n con = Sender(engine_config)\n lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con)\n \n with open(self.lookup_file) as f:\n line = f.readline()\n \n- lookup.send_csv(self.lookup_file,\n- headers=line.rstrip().split(\",\"),\n- key=self.lookup_key)\n+ lookup.send_csv(\n+ self.lookup_file,\n+ headers=line.rstrip().split(\",\"),\n+ key=self.lookup_key,\n+ )\n \n con.socket.shutdown(0)\n \n # Add new line to lookup\n def test_ssl_lookup_new_line(self):\n- engine_config = SenderConfigSSL(address=(self.server, self.port),\n- key=self.key, cert=self.cert,\n- chain=self.chain,\n- check_hostname=False,\n- verify_mode=CERT_NONE)\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ chain=self.chain,\n+ check_hostname=False,\n+ verify_mode=CERT_NONE,\n+ )\n con = Sender(engine_config)\n \n lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con)\n- p_headers = Lookup.list_to_headers(['KEY', 'HEX', 'COLOR'], 'KEY')\n- lookup.send_control('START', p_headers, 'INC')\n+ p_headers = Lookup.list_to_headers([\"KEY\", \"HEX\", \"COLOR\"], \"KEY\")\n+ lookup.send_control(\"START\", p_headers, \"INC\")\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n+ raise Exception(\"Not msg sent!\")\n lookup.send_data_line(key=\"11\", fields=[\"11\", \"HEX12\", \"COLOR12\"])\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n- lookup.send_control('END', p_headers, 'INC')\n+ raise Exception(\"Not msg sent!\")\n+ lookup.send_control(\"END\", p_headers, \"INC\")\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n+ raise Exception(\"Not msg sent!\")\n+\n+ con.socket.shutdown(0)\n+\n+ def test_create_lookup_key_index_preserves_structure(self):\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ chain=self.chain,\n+ check_hostname=False,\n+ verify_mode=CERT_NONE,\n+ )\n+ con = Sender(engine_config)\n+ lookup = Lookup(name=self.lookup_name, con=con)\n+ headers = [\"col1\", \"col2\", \"col3\"]\n+ fields = [\"a\", \"b\", \"c\"]\n+\n+ expected_headers = '[{\"col1\":{\"type\":\"str\",\"key\":true}},{\"col2\":{\"type\":\"str\"}},{\"col3\":{\"type\":\"str\"}}]'\n+ with mock.patch.object(\n+ lookup, \"send_control\", wraps=lookup.send_control\n+ ) as lookup_spy:\n+ lookup.send_headers(\n+ headers=headers, key_index=0, event=\"START\", action=\"FULL\"\n+ )\n+ lookup_spy.assert_called_with(\n+ action=\"FULL\", event=\"START\", headers=expected_headers\n+ )\n+ lookup.send_data_line(key_index=0, fields=fields)\n+ lookup.send_headers(\n+ headers=headers, key_index=0, event=\"END\", action=\"FULL\"\n+ )\n+ lookup_spy.assert_called_with(\n+ action=\"FULL\", event=\"END\", headers=expected_headers\n+ )\n+ con.socket.shutdown(0)\n \n+ def test_send_headers_with_type_of_key(self):\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ chain=self.chain,\n+ check_hostname=False,\n+ verify_mode=CERT_NONE,\n+ )\n+ con = Sender(engine_config)\n+ lookup = Lookup(name=self.lookup_name, con=con)\n+ headers = [\"col1\", \"col2\", \"col3\"]\n+\n+ expected_headers = '[{\"col1\":{\"type\":\"int4\",\"key\":true}},{\"col2\":{\"type\":\"str\"}},{\"col3\":{\"type\":\"str\"}}]'\n+ with mock.patch.object(\n+ lookup, \"send_control\", wraps=lookup.send_control\n+ ) as lookup_spy:\n+ lookup.send_headers(\n+ headers=headers,\n+ key_index=0,\n+ type_of_key=\"int4\",\n+ event=\"START\",\n+ action=\"FULL\",\n+ )\n+ lookup_spy.assert_called_with(\n+ action=\"FULL\", event=\"START\", headers=expected_headers\n+ )\n con.socket.shutdown(0)\n \n # add new line deleting previous data\n def test_ssl_lookup_override(self):\n- engine_config = SenderConfigSSL(address=(self.server, self.port),\n- key=self.key, cert=self.cert,\n- chain=self.chain,\n- check_hostname=False,\n- verify_mode=CERT_NONE)\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ chain=self.chain,\n+ check_hostname=False,\n+ verify_mode=CERT_NONE,\n+ )\n con = Sender(engine_config)\n \n lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con)\n- p_headers = Lookup.list_to_headers(['KEY', 'HEX', 'COLOR'], 'KEY')\n- lookup.send_control('START', p_headers, 'FULL')\n+ p_headers = Lookup.list_to_headers([\"KEY\", \"HEX\", \"COLOR\"], \"KEY\")\n+ lookup.send_control(\"START\", p_headers, \"FULL\")\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n+ raise Exception(\"Not msg sent!\")\n lookup.send_data_line(key=\"11\", fields=[\"11\", \"HEX12\", \"COLOR12\"])\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n- lookup.send_control('END', p_headers, 'FULL')\n+ raise Exception(\"Not msg sent!\")\n+ lookup.send_control(\"END\", p_headers, \"FULL\")\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n+ raise Exception(\"Not msg sent!\")\n \n con.socket.shutdown(0)\n \n # delete a line from lookup\n def test_ssl_lookup_delete_line(self):\n- engine_config = SenderConfigSSL(address=(self.server, self.port),\n- key=self.key, cert=self.cert,\n- chain=self.chain,\n- check_hostname=False,\n- verify_mode=CERT_NONE)\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ chain=self.chain,\n+ check_hostname=False,\n+ verify_mode=CERT_NONE,\n+ )\n con = Sender(engine_config)\n \n lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con)\n- p_headers = Lookup.list_to_headers(['KEY', 'HEX', 'COLOR'], 'KEY')\n- lookup.send_control('START', p_headers, 'INC')\n+ p_headers = Lookup.list_to_headers([\"KEY\", \"HEX\", \"COLOR\"], \"KEY\")\n+ lookup.send_control(\"START\", p_headers, \"INC\")\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n- lookup.send_data_line(key=\"11\", fields=[\"11\", \"HEX12\", \"COLOR12\"],\n- delete=True)\n+ raise Exception(\"Not msg sent!\")\n+ lookup.send_data_line(\n+ key=\"11\", fields=[\"11\", \"HEX12\", \"COLOR12\"], delete=True\n+ )\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n- lookup.send_control('END', p_headers, 'INC')\n+ raise Exception(\"Not msg sent!\")\n+ lookup.send_control(\"END\", p_headers, \"INC\")\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n+ raise Exception(\"Not msg sent!\")\n \n con.socket.shutdown(0)\n \n def test_ssl_lookup_simplify(self):\n- engine_config = SenderConfigSSL(address=(self.server, self.port),\n- key=self.key, cert=self.cert,\n- chain=self.chain,\n- check_hostname=False,\n- verify_mode=CERT_NONE)\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ chain=self.chain,\n+ check_hostname=False,\n+ verify_mode=CERT_NONE,\n+ )\n con = Sender(engine_config)\n \n lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con)\n- lookup.send_headers(headers=['KEY', 'HEX', 'COLOR'], key='KEY',\n- action='START')\n+ lookup.send_headers(\n+ headers=[\"KEY\", \"HEX\", \"COLOR\"], key=\"KEY\", action=\"START\"\n+ )\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n+ raise Exception(\"Not msg sent!\")\n lookup.send_data_line(key=\"11\", fields=[\"11\", \"HEX12\", \"COLOR12\"])\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n- lookup.send_headers(headers=['KEY', 'HEX', 'COLOR'], key='KEY',\n- action='END')\n+ raise Exception(\"Not msg sent!\")\n+ lookup.send_headers(\n+ headers=[\"KEY\", \"HEX\", \"COLOR\"], key=\"KEY\", action=\"END\"\n+ )\n if len(con.socket.recv(1000)) == 0:\n- raise Exception('Not msg sent!')\n+ raise Exception(\"Not msg sent!\")\n \n con.socket.shutdown(0)\n \n def test_check_is_number(self):\n- self.assertTrue(Lookup.is_number('5'))\n- self.assertTrue(Lookup.is_number('5.0'))\n+ self.assertTrue(Lookup.is_number(\"5\"))\n+ self.assertTrue(Lookup.is_number(\"5.0\"))\n \n def test_check_is_not_a_number(self):\n- self.assertFalse(Lookup.is_number('5551,HNBId=001D4C-1213120051,'\n- 'Fsn=1213120051,bSRName=,'\n- 'manualPscUsed=false'))\n- self.assertFalse(Lookup.is_number('5.'))\n- self.assertFalse(Lookup.is_number('5,0'))\n+ self.assertFalse(\n+ Lookup.is_number(\n+ \"5551,HNBId=001D4C-1213120051,\"\n+ \"Fsn=1213120051,bSRName=,\"\n+ \"manualPscUsed=false\"\n+ )\n+ )\n+ self.assertFalse(Lookup.is_number(\"5.\"))\n+ self.assertFalse(Lookup.is_number(\"5,0\"))\n+\n+ def test_process_fields_does_not_modify_arguments(self):\n+ fields = [\"a\", \"b\", \"c\"]\n+\n+ processed_fields = Lookup.process_fields(fields, key_index=1)\n+\n+ self.assertEqual(fields, [\"a\", \"b\", \"c\"])\n+ self.assertEqual(processed_fields, '\"b\",\"a\",\"c\"')\n \n \n-if __name__ == '__main__':\n+if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["tests/sender/send_lookup.py::TestLookup::test_process_fields_does_not_modify_arguments"]}, {"instance_id": "DevoInc__python-sdk-113", "base_commit": "3fa89f73be41307044fec587eb13b563201cd8f9", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 28e86d5..6686fd3 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -10,7 +10,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.\n * `Lookup.send_headers` method not working as expected with key_index parameter\n * Add `type_of_key` parameter to `Lookup.send_headers` method\n * Avoid lookups' key element to be deleted when `Lookup.send_data_line` is invoked.\n-\n+### Added\n+ * Double quotes on lookups can be escaped by adding `\"escape_quotes\": true` to the config file.\n \n ## [3.4.2] - 2021-05-18\n ### Added\ndiff --git a/devo/sender/lookup.py b/devo/sender/lookup.py\nindex d92908e..db089e3 100644\n--- a/devo/sender/lookup.py\n+++ b/devo/sender/lookup.py\n@@ -6,6 +6,7 @@ import sys\n import time\n \n \n+\n def find_key_index(value=None, headers=None):\n \"\"\"Find index of key value in a list\"\"\"\n for index, val in enumerate(headers):\n@@ -43,7 +44,7 @@ class Lookup:\n CONTROL_TABLE = \"my.lookup.control\"\n \n def __init__(self, name=\"example\", historic_tag=None,\n- con=None, delay=5):\n+ con=None, delay=5, escape_quotes=False):\n \n if not re.match(r\"^[A-Za-z0-9_]+$\", name):\n raise Exception('Devo Lookup: The name of the lookup is incorrect,'\n@@ -58,6 +59,7 @@ class Lookup:\n self.historic_tag = historic_tag\n self.name = name.replace(\" \", \"_\")\n self.delay = delay\n+ self.escape_quotes = escape_quotes\n \n # Helper methods\n # --------------------------------------------------------------------------\n@@ -92,9 +94,11 @@ class Lookup:\n :return:\n \"\"\"\n # TODO: Deprecate this if with list_to_fields in v4\n- p_fields = Lookup.list_to_fields(fields=fields, key=key) \\\n+ p_fields = Lookup.list_to_fields(fields=fields, key=key,\n+ escape_quotes=self.escape_quotes) \\\n if key_index is None \\\n- else Lookup.process_fields(fields=fields, key_index=key_index)\n+ else Lookup.process_fields(fields=fields, key_index=key_index,\n+ escape_quotes=self.escape_quotes)\n self.send_data(row=p_fields, delete=delete)\n \n @staticmethod\n@@ -206,8 +210,10 @@ class Lookup:\n if delete_index is not None:\n for fields in spam_reader:\n field_action = fields.pop(delete_index)\n- p_fields = Lookup.process_fields(fields=fields,\n- key_index=key_index)\n+ p_fields = Lookup.process_fields(\n+ fields=fields,\n+ key_index=key_index,\n+ escape_quotes=self.escape_quotes)\n self.send_data(row=p_fields,\n delete=field_action == \"delete\"\n or field_action == \"DELETE\")\n@@ -218,8 +224,10 @@ class Lookup:\n counter += 1\n else:\n for fields in spam_reader:\n- p_fields = Lookup.process_fields(fields=fields,\n- key_index=key_index)\n+ p_fields = Lookup.process_fields(\n+ fields=fields,\n+ key_index=key_index,\n+ escape_quotes=self.escape_quotes)\n self.send_data(row=p_fields)\n \n # Send full log for historic\n@@ -351,16 +359,16 @@ class Lookup:\n return out\n \n @staticmethod\n- def field_to_str(field):\n+ def field_to_str(field, escape_quotes=False):\n \"\"\"\n Convert one value to STR, cleaning it\n :param field: field to clean\n :return:\n \"\"\"\n- return ',%s' % Lookup.clean_field(field)\n+ return ',%s' % Lookup.clean_field(field, escape_quotes)\n \n @staticmethod\n- def process_fields(fields=None, key_index=None):\n+ def process_fields(fields=None, key_index=None, escape_quotes=False):\n \"\"\"\n Method to convert list with one row/fields to STR to send\n :param fields: fields list\n@@ -368,23 +376,23 @@ class Lookup:\n :return:\n \"\"\"\n # First the key\n- out = '%s' % Lookup.clean_field(fields[key_index])\n+ out = '%s' % Lookup.clean_field(fields[key_index], escape_quotes)\n \n # The rest of the fields\n for item in fields[:key_index] + fields[key_index + 1:]:\n- out += Lookup.field_to_str(item)\n+ out += Lookup.field_to_str(item, escape_quotes)\n return out\n \n # TODO: Deprecated\n @staticmethod\n- def list_to_fields(fields=None, key=\"key\"):\n+ def list_to_fields(fields=None, key=\"key\", escape_quotes=False):\n \"\"\"\n Transform list item to the object we need send to Devo for each row\n :param list fields: list of field names\n :param str key: key name, optional\n :result str\n \"\"\"\n- key = Lookup.clean_field(key)\n+ key = Lookup.clean_field(key, escape_quotes)\n # First the key\n out = '%s' % key\n \n@@ -393,7 +401,7 @@ class Lookup:\n \n # The rest of the fields\n for item in fields:\n- item = Lookup.clean_field(item)\n+ item = Lookup.clean_field(item, escape_quotes)\n # If file is the key don't add\n if item == key:\n continue\n@@ -401,7 +409,7 @@ class Lookup:\n return out\n \n @staticmethod\n- def clean_field(field=None):\n+ def clean_field(field=None, escape_quotes=False):\n \"\"\"\n Strip and quotechar the fields\n :param str field: field for clean\n@@ -414,6 +422,9 @@ class Lookup:\n if Lookup.is_number(field):\n return field\n \n+ if escape_quotes:\n+ field = field.replace('\"', '\"\"')\n+\n return '\"%s\"' % field\n \n @staticmethod\ndiff --git a/docs/sender/lookup.md b/docs/sender/lookup.md\nindex 3cde900..04105a4 100644\n--- a/docs/sender/lookup.md\n+++ b/docs/sender/lookup.md\n@@ -18,13 +18,15 @@ object into the _lookup_ variable with the new parameters or add in the CLI flag\n Example:\n \n ```\n-{ sender\": {\n+{ \n+ sender\": {\n ...\n },\n \"lookup\": {\n \"name\": \"Test_Lookup_of_180306_02\",\n \"file\": \"test_lookup.csv\",\n \"lkey\": \"KEY\"\n+ \"escape_quotes\": true\n }\n }\n ```\n@@ -225,3 +227,24 @@ You can use config file to send types list:\n ....\n }}\n ```\n+##### Double quotes in the field value\n+\n+Any double quotes inside the field value can cause trouble when sending the lookup if this is not escaped.\n+An example of this case can be seen below:\n+\n+`lookup.send_data_line(key=\"11\", fields=[\"11\", 'double quotes must escaped\"'])`\n+\n+That lookup creation will fail because that double quote will be interpreted as a field termination and \n+the number of fields for that row will unmatch the corresponding number of columns. To avoid this, \n+add `\"escape_quotes\": true` to the lookup configuration file and `escape_quotes=True` to the `Lookup` constructor. \n+Below, an example for the constructor is shown:\n+\n+```\n+`lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con, escape_quotes=True)`\n+```\n+\n+To see an example for the lookup configuration please refer to the one shown at the start of the document.\n+\n+This will escape ALL double quotes in the field value by adding a second double quote to it.\n+\n+The default behavior is to NOT escape any double quotes. \n\\ No newline at end of file\n", "test_patch": "diff --git a/tests/sender/send_lookup.py b/tests/sender/send_lookup.py\nindex 4e7e416..a0937a8 100644\n--- a/tests/sender/send_lookup.py\n+++ b/tests/sender/send_lookup.py\n@@ -243,6 +243,96 @@ class TestLookup(unittest.TestCase):\n self.assertEqual(fields, [\"a\", \"b\", \"c\"])\n self.assertEqual(processed_fields, '\"b\",\"a\",\"c\"')\n \n+ # Clean field\n+ def test_clean_field_parametrized(self):\n+ test_params = [\n+ (\"No double quotes\", False, '\"No double quotes\"'),\n+ (\"No double quotes\", True, '\"No double quotes\"'),\n+ ('Double quotes\"', False, '\"Double quotes\"\"'),\n+ ('Double quotes\"', True, '\"Double quotes\"\"\"')\n+ ]\n+ for field, escape_quotes, expected_result in test_params:\n+ with self.subTest(\n+ field=field,\n+ escape_quotes=escape_quotes,\n+ expected_result=expected_result\n+ ):\n+ result = Lookup.clean_field(field, escape_quotes)\n+ self.assertEqual(result, expected_result)\n+\n+ # Test to make sure escape_quotes is propagated correctly\n+ def test_escape_quotes_in_send_data_line_key(self):\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ )\n+ con = Sender(engine_config)\n+\n+ lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con,\n+ escape_quotes=True)\n+\n+ with mock.patch.object(Lookup, 'clean_field',\n+ wraps=Lookup.clean_field) as clean_field:\n+ lookup.send_data_line(key=\"11\", fields=[\"11\", 'Double quotes\"'])\n+ clean_field.assert_called_with('Double quotes\"', True)\n+\n+ # Test to make sure escape_quotes is propagated correctly\n+ def test_escape_quotes_in_send_data_line(self):\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ )\n+ con = Sender(engine_config)\n+\n+ lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con,\n+ escape_quotes=True)\n+\n+ with mock.patch.object(Lookup, 'clean_field',\n+ wraps=Lookup.clean_field) as clean_field:\n+ lookup.send_data_line(fields=[\"11\", 'Double quotes\"'])\n+ clean_field.assert_called_with('Double quotes\"', True)\n+\n+ # Test to make sure escape_quotes is propagated correctly\n+\n+ def test_escape_quotes_in_send_csv(self):\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ )\n+ con = Sender(engine_config)\n+\n+ lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con,\n+ escape_quotes=True)\n+\n+ with mock.patch.object(Lookup, 'clean_field',\n+ wraps=Lookup.clean_field) as clean_field:\n+ lookup.send_csv(path=self.lookup_file,\n+ has_header=True,\n+ key=self.lookup_key)\n+ clean_field.assert_called_with('ffffff', True)\n+\n+ # Test to make sure escape_quotes is propagated correctly\n+\n+ def test_escape_quotes_in_send_csv_delete_index(self):\n+ engine_config = SenderConfigSSL(\n+ address=(self.server, self.port),\n+ key=self.key,\n+ cert=self.cert,\n+ )\n+ con = Sender(engine_config)\n+\n+ lookup = Lookup(name=self.lookup_name, historic_tag=None, con=con,\n+ escape_quotes=True)\n+\n+ with mock.patch.object(Lookup, 'clean_field',\n+ wraps=Lookup.clean_field) as clean_field:\n+ lookup.send_csv(path=self.lookup_file,\n+ has_header=True,\n+ key=self.lookup_key, delete_field=\"Green\")\n+ clean_field.assert_called_with('ffffff', True)\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["tests/sender/send_lookup.py::TestLookup::test_clean_field_parametrized"]}], "all_FAIL_TO_PASS": ["tests/sender/send_lookup.py::TestLookup::test_process_fields_does_not_modify_arguments", "tests/sender/send_lookup.py::TestLookup::test_clean_field_parametrized"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "codalab__codalab-worksheets-3343_x2", "level": 2, "source": "swerebench", "repo": "codalab/codalab-worksheets", "image": "swerebench/sweb.eval.x86_64.codalab_1776_codalab-worksheets-3343:latest", "base_commit": "e900111cf4b3a86960907f3e60e258b440dda335", "num_bugs": 2, "bugs": [{"instance_id": "codalab__codalab-worksheets-3343", "base_commit": "e900111cf4b3a86960907f3e60e258b440dda335", "gold_patch": "diff --git a/codalab/lib/interactive_session.py b/codalab/lib/interactive_session.py\nindex 9ee96254..73b252be 100644\n--- a/codalab/lib/interactive_session.py\n+++ b/codalab/lib/interactive_session.py\n@@ -31,7 +31,7 @@ class InteractiveSession:\n 9. Stop and remove the interactive session container.\n \"\"\"\n \n- _BASH_HISTORY_CONTAINER_PATH = \"/usr/sbin/.bash_history\"\n+ _BASH_HISTORY_CONTAINER_PATH = \"/root/.bash_history\"\n _CHOOSE_COMMAND_INSTRUCTIONS = (\n \"\\n\\n#\\n\"\n \"# Choose the commands to use for cl run:\\n\"\n@@ -143,14 +143,14 @@ class InteractiveSession:\n volumes[get_docker_path(key)] = dependency_local_path\n \n name = self._get_container_name()\n- # Start a container as a non-root user. Root (id = 0) is the default user within a container.\n- # When passing a numeric ID, the user does not have to exist in the container.\n+ # Start a container as a root user. Root (id = 0) is the default user within a container.\n command = [\n 'docker run',\n '-it',\n f'--name {name}',\n f'-w {os.path.sep}{self._session_uuid}',\n- '-u 1',\n+ # TODO: figure out a way to run as a non-root user and be able to save the bash_history on any machine\n+ # '-u 1',\n ]\n command.extend(\n [\ndiff --git a/codalab/rest/bundles.py b/codalab/rest/bundles.py\nindex 2f001e26..711463a8 100644\n--- a/codalab/rest/bundles.py\n+++ b/codalab/rest/bundles.py\n@@ -403,7 +403,7 @@ def _fetch_locations():\n bundle_uuids = query_get_list('uuids')\n bundle_link_urls = local.model.get_bundle_metadata(bundle_uuids, \"link_url\")\n uuids_to_locations = {\n- uuid: bundle_link_urls.get(\"uuid\") or local.bundle_store.get_bundle_location(uuid)\n+ uuid: bundle_link_urls.get(uuid) or local.bundle_store.get_bundle_location(uuid)\n for uuid in bundle_uuids\n }\n return dict(data=uuids_to_locations)\n", "test_patch": "diff --git a/tests/unit/lib/interactive_session_test.py b/tests/unit/lib/interactive_session_test.py\nindex 584e7873..f5c5ab6d 100644\n--- a/tests/unit/lib/interactive_session_test.py\n+++ b/tests/unit/lib/interactive_session_test.py\n@@ -14,9 +14,9 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -u 1 -v '\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n '[\\s\\S]{0,100}local\\/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n- '-v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw some-docker-image bash'\n+ '-v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n@@ -31,9 +31,9 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -u 1 -v '\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n '[\\s\\S]{0,100}local\\/path1/sub/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2/sub/path2'\n- ':\\/0x[a-z0-9]{32}\\/key2:ro -v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw some-docker-image bash'\n+ ':\\/0x[a-z0-9]{32}\\/key2:ro -v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n", "FAIL_TO_PASS": ["tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths"]}, {"instance_id": "codalab__codalab-worksheets-3393", "base_commit": "4fa4d6cd844bbb25f41813f35dc355de476b914a", "gold_patch": "diff --git a/codalab/lib/interactive_session.py b/codalab/lib/interactive_session.py\nindex 73b252be..2164e2c9 100644\n--- a/codalab/lib/interactive_session.py\n+++ b/codalab/lib/interactive_session.py\n@@ -6,6 +6,7 @@ import docker\n import os\n import shutil\n import sys\n+from typing import Dict, List\n \n \n class InteractiveSession:\n@@ -23,7 +24,7 @@ class InteractiveSession:\n 3. Mount the dependencies as read-only.\n 4. Set working directory to some arbitrary path: `/`\n 5. The user will interact with this container and try out different commands. Once satisfied the user will\n- exit the bash session. All the commands the user tried out will be stored at path `/root/.bash_history`\n+ exit the bash session. All the commands the user tried out will be stored at path `/usr/sbin/.bash_history`\n in the container.\n 6. Copy `.bash_history` out to the host machine.\n 7. Open an editor and allow the user to select and edit commands for the official run.\n@@ -31,7 +32,7 @@ class InteractiveSession:\n 9. Stop and remove the interactive session container.\n \"\"\"\n \n- _BASH_HISTORY_CONTAINER_PATH = \"/root/.bash_history\"\n+ _BASH_HISTORY_CONTAINER_PATH = \"/usr/sbin/.bash_history\"\n _CHOOSE_COMMAND_INSTRUCTIONS = (\n \"\\n\\n#\\n\"\n \"# Choose the commands to use for cl run:\\n\"\n@@ -74,15 +75,15 @@ class InteractiveSession:\n \n self._docker_client = docker.from_env(timeout=InteractiveSession._MAX_SESSION_TIMEOUT)\n self._session_uuid = generate_uuid()\n+ self._host_bundle_path: str = os.path.join(\n+ self._manager.codalab_home, 'local_bundles', self._session_uuid\n+ )\n \n self._verbose = verbose\n self._stdout = stdout\n self._stderr = stderr\n \n def start(self):\n- self._host_bundle_path = os.path.join(\n- self._manager.codalab_home, 'local_bundles', self._session_uuid\n- )\n os.makedirs(self._host_bundle_path)\n \n # Create a blank file which will be used as the bash history file that will later be\n@@ -123,7 +124,7 @@ class InteractiveSession:\n return os.path.sep + os.path.join(self._session_uuid, sub_path)\n \n # Use a dict to keep track of volumes to mount. The key is the path on Docker and the value is the local path.\n- volumes = {}\n+ volumes: Dict[str, str] = {}\n for key, bundle_target in self._dependencies:\n dependency_local_path = os.path.realpath(\n os.path.join(\n@@ -142,30 +143,34 @@ class InteractiveSession:\n else:\n volumes[get_docker_path(key)] = dependency_local_path\n \n- name = self._get_container_name()\n- # Start a container as a root user. Root (id = 0) is the default user within a container.\n- command = [\n+ name: str = self._get_container_name()\n+ container_working_directory: str = f'{os.path.sep}{self._session_uuid}'\n+\n+ # Start a container as a non-root user\n+ command: List[str] = [\n 'docker run',\n '-it',\n f'--name {name}',\n- f'-w {os.path.sep}{self._session_uuid}',\n- # TODO: figure out a way to run as a non-root user and be able to save the bash_history on any machine\n- # '-u 1',\n+ f'-w {container_working_directory}',\n+ f'-e HOME={container_working_directory}',\n+ f'-e HISTFILE={InteractiveSession._BASH_HISTORY_CONTAINER_PATH}',\n+ '-e PROMPT_COMMAND=\"history -a\"',\n+ '-u $(id -u):$(id -g)',\n ]\n command.extend(\n [\n # Example: -v local_path/some_folder:/0x707e903500e54bcf9b072ac7e3f5ed36_dependencies/foo:ro\n- '-v {}:{}:ro'.format(local_path, docker_path)\n+ f'-v {local_path}:{docker_path}:ro'\n for docker_path, local_path in volumes.items()\n ]\n )\n- command.append(\n- '-v {}:{}:rw'.format(\n- self._host_bash_history_path, InteractiveSession._BASH_HISTORY_CONTAINER_PATH\n- )\n+ command.extend(\n+ [\n+ f'-v {self._host_bash_history_path}:{InteractiveSession._BASH_HISTORY_CONTAINER_PATH}:rw',\n+ f'-v {self._host_bundle_path}:{container_working_directory}:rw',\n+ ]\n )\n command.append(self._docker_image)\n- command.append('bash')\n return ' '.join(command)\n \n def cleanup(self):\n@@ -175,6 +180,7 @@ class InteractiveSession:\n self._container.stop()\n self._container.remove()\n shutil.rmtree(self._host_bundle_path, ignore_errors=True)\n+\n if self._verbose:\n print('Done.\\n', file=self._stdout)\n \n", "test_patch": "diff --git a/tests/unit/lib/interactive_session_test.py b/tests/unit/lib/interactive_session_test.py\nindex f5c5ab6d..6fb78c06 100644\n--- a/tests/unit/lib/interactive_session_test.py\n+++ b/tests/unit/lib/interactive_session_test.py\n@@ -14,9 +14,10 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n- '[\\s\\S]{0,100}local\\/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n- '-v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} '\n+ '-e HOME=\\/0x[a-z0-9]{32} -e HISTFILE=\\/usr\\/sbin\\/\\.bash_history -e PROMPT_COMMAND=\"history -a\" -u \\$\\(id -u\\):\\$\\(id -g\\) '\n+ '-v [\\s\\S]{0,100}local\\/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n+ '-v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw -v [\\s\\S]{0,100}\\/0x[a-z0-9]{32}:\\/0x[a-z0-9]{32}:rw some-docker-image'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n@@ -31,9 +32,10 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n- '[\\s\\S]{0,100}local\\/path1/sub/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2/sub/path2'\n- ':\\/0x[a-z0-9]{32}\\/key2:ro -v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} '\n+ '-e HOME=\\/0x[a-z0-9]{32} -e HISTFILE=\\/usr\\/sbin\\/\\.bash_history -e PROMPT_COMMAND=\"history -a\" -u \\$\\(id -u\\):\\$\\(id -g\\) '\n+ '-v [\\s\\S]{0,100}local\\/path1/sub/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2/sub/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n+ '-v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw -v [\\s\\S]{0,100}\\/0x[a-z0-9]{32}:\\/0x[a-z0-9]{32}:rw some-docker-image'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n", "FAIL_TO_PASS": ["tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths"]}], "all_FAIL_TO_PASS": ["tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "PyPSA__linopy-77_x2", "level": 2, "source": "swerebench", "repo": "PyPSA/linopy", "image": "swerebench/sweb.eval.x86_64.pypsa_1776_linopy-77:latest", "base_commit": "b05fb5b8c96bf6b885696de98d880c2f430e7192", "num_bugs": 2, "bugs": [{"instance_id": "PyPSA__linopy-77", "base_commit": "b05fb5b8c96bf6b885696de98d880c2f430e7192", "gold_patch": "diff --git a/doc/release_notes.rst b/doc/release_notes.rst\nindex 9158982..21e1cbf 100644\n--- a/doc/release_notes.rst\n+++ b/doc/release_notes.rst\n@@ -5,6 +5,7 @@ Upcoming Release\n ----------------\n \n * Linopy now defines and uses a fixed set of solver status and termination codes. This allows for a more consistent and reliable handling of solver results. The new codes are defined in the `linopy.consants` module. The implementation is inspired by https://github.com/0b11001111 and the implementation in this `PyPSA fork `_\n+* The automated summation of repeated variables in one constraint is now supported. Before the implementation for constraints like `x + x + x <= 5` was only working for solvers with a corresponding fallback computation. This is now fixed.\n * Integer variables are now fully supported.\n * Support exporting problems to MPS file via fast highspy MPS-writer.\n * The internal data structure of linopy classes were updated to a safer design. Instead of being defined as inherited xarray classes, the class `Variable`, `LinearExpression` and `Constraint` are now dataclasses with containing the xarray objects in the data field. This allows the package to have more flexible function design and a reduced set of wrapped functions that are sensible to use in the optimization context.\ndiff --git a/linopy/constraints.py b/linopy/constraints.py\nindex 55ea651..f1d5972 100644\n--- a/linopy/constraints.py\n+++ b/linopy/constraints.py\n@@ -541,7 +541,11 @@ class Constraints:\n \n shape = (ncons, nvars) # same as model.nvars/ncons but already there\n \n- return coo_matrix((data, (rows, cols)), shape=shape)\n+ # Group repeated variables in the same constraint\n+ df = pd.DataFrame({\"data\": data, \"rows\": rows, \"cols\": cols})\n+ df = df.groupby([\"rows\", \"cols\"], as_index=False).sum()\n+\n+ return coo_matrix((df.data, (df.rows, df.cols)), shape=shape)\n \n \n class AnonymousConstraint:\ndiff --git a/linopy/expressions.py b/linopy/expressions.py\nindex 7539290..3e9e9f0 100644\n--- a/linopy/expressions.py\n+++ b/linopy/expressions.py\n@@ -700,6 +700,7 @@ class LinearExpression:\n \n if not np.issubdtype(self.vars.dtype, np.integer):\n return self.assign(vars=self.vars.fillna(-1).astype(int))\n+\n return self\n \n def equals(self, other: \"LinearExpression\"):\ndiff --git a/linopy/io.py b/linopy/io.py\nindex f9bc36f..a38a0b5 100644\n--- a/linopy/io.py\n+++ b/linopy/io.py\n@@ -11,6 +11,7 @@ from pathlib import Path\n from tempfile import TemporaryDirectory\n \n import numpy as np\n+import pandas as pd\n import xarray as xr\n from numpy import asarray, concatenate, ones_like, zeros_like\n from tqdm import tqdm\n@@ -102,6 +103,10 @@ def constraints_to_file(m, f, log=False):\n \n if not c.size:\n continue\n+ # Group repeated variables in the same constraint\n+ df = pd.DataFrame({\"coeffs\": c, \"labels\": l, \"vars\": v})\n+ df = df.groupby([\"labels\", \"vars\"], as_index=False).sum()\n+ c, l, v = df.coeffs.values, df.labels.values, df.vars.values\n \n diff_con = l[:-1] != l[1:]\n new_con_b = concatenate([asarray([True]), diff_con])\n@@ -323,6 +328,9 @@ def to_highspy(m):\n def to_block_files(m, fn):\n \"\"\"\n Write out the linopy model to a block structured output.\n+\n+ Experimental: This function does not support grouping duplicated variables\n+ in one constraint row yet!\n \"\"\"\n if fn is None:\n fn = TemporaryDirectory(prefix=\"linopy-problem-\", dir=m.solver_dir).name\n@@ -389,7 +397,7 @@ def to_block_files(m, fn):\n \n def filtered(arr, mask, key):\n \"\"\"\n- Set coefficients to zero for mask, keep others unchanged.\n+ Set coefficients to zero where mask is False, keep others unchanged.\n \n PIPS requires this information to set the shape of sub-matrices.\n \"\"\"\n", "test_patch": "diff --git a/test/test_matrices.py b/test/test_matrices.py\nindex 61939da..403692a 100644\n--- a/test/test_matrices.py\n+++ b/test/test_matrices.py\n@@ -50,3 +50,16 @@ def test_basic_matrices_masked():\n assert m.matrices.clabels.shape == m.matrices.sense.shape\n assert m.matrices.vlabels.shape == m.matrices.ub.shape\n assert m.matrices.vlabels.shape == m.matrices.lb.shape\n+\n+\n+def test_matrices_duplicated_variables():\n+ m = Model()\n+\n+ x = m.add_variables(pd.Series([0, 0]), 1, name=\"x\")\n+ y = m.add_variables(4, pd.Series([8, 10]), name=\"y\")\n+ z = m.add_variables(0, pd.DataFrame([[1, 2], [3, 4], [5, 6]]).T, name=\"z\")\n+ m.add_constraints(x + x + y + y + z + z == 0)\n+\n+ A = m.matrices.A.todense()\n+ assert A[0, 0] == 2\n+ assert np.isin(np.unique(A), [0, 2]).all()\ndiff --git a/test/test_optimization.py b/test/test_optimization.py\nindex b3998b0..5a52432 100644\n--- a/test/test_optimization.py\n+++ b/test/test_optimization.py\n@@ -79,6 +79,19 @@ def model_with_inf():\n return m\n \n \n+@pytest.fixture\n+def model_with_duplicated_variables():\n+ m = Model()\n+\n+ lower = pd.Series(0, range(10))\n+ x = m.add_variables(coords=[lower.index], name=\"x\")\n+\n+ m.add_constraints(x + x, GREATER_EQUAL, 10)\n+ m.objective = 1 * x\n+\n+ return m\n+\n+\n @pytest.fixture\n def milp_binary_model():\n m = Model()\n@@ -220,6 +233,13 @@ def test_default_settings_chunked(model_chunked, solver, io_api):\n assert np.isclose(model_chunked.objective_value, 3.3)\n \n \n+@pytest.mark.parametrize(\"solver,io_api\", params)\n+def test_duplicated_variables(model_with_duplicated_variables, solver, io_api):\n+ status, condition = model_with_duplicated_variables.solve(solver, io_api=io_api)\n+ assert status == \"ok\"\n+ assert all(model_with_duplicated_variables.solution[\"x\"] == 5)\n+\n+\n @pytest.mark.parametrize(\"solver,io_api\", params)\n def test_set_files(tmp_path, model, solver, io_api):\n status, condition = model.solve(\n", "FAIL_TO_PASS": ["test/test_optimization.py::test_duplicated_variables[glpk-lp]", "test/test_optimization.py::test_duplicated_variables[cbc-lp]"]}, {"instance_id": "PyPSA__linopy-79", "base_commit": "1ea0bab835f979063eea96287f12cb083c6d37e2", "gold_patch": "diff --git a/linopy/expressions.py b/linopy/expressions.py\nindex 3e9e9f0..d7c8b7b 100644\n--- a/linopy/expressions.py\n+++ b/linopy/expressions.py\n@@ -495,6 +495,26 @@ class LinearExpression:\n cond = _expr_unwrap(cond)\n return self.__class__(self.data.where(cond, other=other, **kwargs))\n \n+ def diff(self, dim, n=1):\n+ \"\"\"\n+ Calculate the n-th order discrete difference along given axis.\n+\n+ This operation call ``xarray.Dataset.diff`` but ensures preserving the\n+ linopy.LinearExpression type.\n+\n+ Parameters\n+ ----------\n+ dim : str\n+ Dimension over which to calculate the finite difference.\n+ n : int, optional\n+ The number of times values are differenced.\n+\n+ Returns\n+ -------\n+ linopy.LinearExpression\n+ \"\"\"\n+ return self - self.shift({dim: n})\n+\n def groupby(\n self,\n group,\n@@ -532,6 +552,7 @@ class LinearExpression:\n )\n return LinearExpressionGroupby(groups)\n \n+ @deprecated(\"0.1.0\", \"0.1.2\", details=\"Use groupby (followed by sum) instead.\")\n def groupby_sum(self, group):\n \"\"\"\n Sum expression over groups.\n@@ -597,6 +618,7 @@ class LinearExpression:\n )\n return LinearExpressionRolling(rolling)\n \n+ @deprecated(\"0.1.0\", \"0.1.2\", details=\"Use rolling (followed by sum) instead.\")\n def rolling_sum(self, **kwargs):\n \"\"\"\n Rolling sum of the linear expression.\ndiff --git a/linopy/variables.py b/linopy/variables.py\nindex 9572f87..934cf28 100644\n--- a/linopy/variables.py\n+++ b/linopy/variables.py\n@@ -442,6 +442,26 @@ class Variable:\n \"\"\"\n return self.to_linexpr().sum(dims)\n \n+ def diff(self, dim, n=1):\n+ \"\"\"\n+ Calculate the n-th order discrete difference along the given dimension.\n+\n+ This function works exactly in the same way as ``LinearExpression.diff()``.\n+\n+ Parameters\n+ ----------\n+ dim : str\n+ Dimension over which to calculate the finite difference.\n+ n : int, default: 1\n+ The number of times values are differenced.\n+\n+ Returns\n+ -------\n+ linopy.LinearExpression\n+ Finite difference expression.\n+ \"\"\"\n+ return self.to_linexpr().diff(dim, n)\n+\n def where(self, cond, other=-1, **kwargs):\n \"\"\"\n Filter variables based on a condition.\n", "test_patch": "diff --git a/test/test_linear_expression.py b/test/test_linear_expression.py\nindex 8d81b0e..8a76c96 100644\n--- a/test/test_linear_expression.py\n+++ b/test/test_linear_expression.py\n@@ -302,6 +302,16 @@ def test_linear_expression_shift(v):\n assert (shifted.vars.loc[:1] == -1).all()\n \n \n+def test_linear_expression_diff(v):\n+ diff = v.to_linexpr().diff(\"dim_2\")\n+ assert diff.nterm == 2\n+\n+\n+def test_linear_expression_diff(v):\n+ diff = v.diff(\"dim_2\")\n+ assert diff.nterm == 2\n+\n+\n def test_linear_expression_groupby(v):\n expr = 1 * v\n groups = xr.DataArray([1] * 10 + [2] * 10, coords=v.coords)\n", "FAIL_TO_PASS": ["test/test_linear_expression.py::test_linear_expression_diff"]}], "all_FAIL_TO_PASS": ["test/test_optimization.py::test_duplicated_variables[glpk-lp]", "test/test_optimization.py::test_duplicated_variables[cbc-lp]", "test/test_linear_expression.py::test_linear_expression_diff"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "bradshjg__flask-githubapp-23_x2", "level": 2, "source": "swerebench", "repo": "bradshjg/flask-githubapp", "image": "swerebench/sweb.eval.x86_64.bradshjg_1776_flask-githubapp-23:latest", "base_commit": "3f5da29cb0740cc92068e0f8c8774bc182e253c4", "num_bugs": 2, "bugs": [{"instance_id": "bradshjg__flask-githubapp-23", "base_commit": "3f5da29cb0740cc92068e0f8c8774bc182e253c4", "gold_patch": "diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml\nindex 33b65fe..4fabdfb 100644\n--- a/.github/workflows/release.yml\n+++ b/.github/workflows/release.yml\n@@ -3,7 +3,9 @@\n \n name: PyPI release\n \n-on: [release]\n+on:\n+ release:\n+ types: [published]\n \n jobs:\n publish:\ndiff --git a/flask_githubapp/core.py b/flask_githubapp/core.py\nindex 34af98f..3072a87 100644\n--- a/flask_githubapp/core.py\n+++ b/flask_githubapp/core.py\n@@ -2,9 +2,9 @@\n import hmac\n import logging\n \n-from flask import abort, current_app, jsonify, request, _app_ctx_stack\n+from flask import abort, current_app, jsonify, make_response, request, _app_ctx_stack\n from github3 import GitHub, GitHubEnterprise\n-\n+from werkzeug.exceptions import BadRequest\n \n LOG = logging.getLogger(__name__)\n \n@@ -167,6 +167,23 @@ class GitHubApp(object):\n functions_to_call = []\n calls = {}\n \n+ if not request.is_json:\n+ error_message = 'Invalid HTTP Content-Type header for JSON body ' \\\n+ '(must be application/json or application/*+json).'\n+ LOG.error(error_message)\n+ error_response = make_response(jsonify(status='ERROR', description=error_message),\n+ 400)\n+ abort(error_response)\n+\n+ try:\n+ request.json\n+ except BadRequest:\n+ error_message = 'Invalid HTTP body (must be JSON).'\n+ LOG.error(error_message)\n+ error_response = make_response(jsonify(status='ERROR', description=error_message),\n+ 400)\n+ abort(error_response)\n+\n event = request.headers['X-GitHub-Event']\n action = request.json.get('action')\n \n", "test_patch": "diff --git a/tests/test_core.py b/tests/test_core.py\nindex 326cbdb..593c568 100644\n--- a/tests/test_core.py\n+++ b/tests/test_core.py\n@@ -242,3 +242,37 @@ def test_view_returns_map_of_called_functions_and_returned_data(app, mocker):\n 'event_action_function': 'bar',\n }\n }\n+\n+def test_invalid_json_header_returns_error(github_app):\n+ \"\"\"HTTP request have a valid json content type\"\"\"\n+ github_app.config['GITHUBAPP_SECRET'] = False\n+ with github_app.test_client() as client:\n+ resp = client.post('/',\n+ data=json.dumps({'installation': {'id': 2},\n+ 'action': 'bar'}),\n+ headers={\n+ 'X-GitHub-Event': 'foo',\n+ 'Content-Type': 'text/plain'\n+ })\n+ assert resp.status_code == 400\n+ assert resp.json == {\n+ 'status': 'ERROR',\n+ 'description': 'Invalid HTTP Content-Type header for JSON body '\n+ '(must be application/json or application/*+json).'\n+ }\n+\n+def test_invalid_json_body_returns_error(github_app):\n+ \"\"\"HTTP request have a valid json body\"\"\"\n+ github_app.config['GITHUBAPP_SECRET'] = False\n+ with github_app.test_client() as client:\n+ resp = client.post('/',\n+ data='invalid json',\n+ headers={\n+ 'X-GitHub-Event': 'foo',\n+ 'Content-Type': 'application/json'\n+ })\n+ assert resp.status_code == 400\n+ assert resp.json == {\n+ 'status': 'ERROR',\n+ 'description': 'Invalid HTTP body (must be JSON).'\n+ }\n", "FAIL_TO_PASS": ["tests/test_core.py::test_invalid_json_header_returns_error", "tests/test_core.py::test_invalid_json_body_returns_error"]}, {"instance_id": "bradshjg__flask-githubapp-25", "base_commit": "4465e4fd69a14e0452a6d38a1fa1c5aa68baf653", "gold_patch": "diff --git a/flask_githubapp/core.py b/flask_githubapp/core.py\nindex 3072a87..661f8d0 100644\n--- a/flask_githubapp/core.py\n+++ b/flask_githubapp/core.py\n@@ -12,6 +12,14 @@ STATUS_FUNC_CALLED = 'HIT'\n STATUS_NO_FUNC_CALLED = 'MISS'\n \n \n+class GitHubAppError(Exception):\n+ pass\n+\n+\n+class GitHubAppValidationError(GitHubAppError):\n+ pass\n+\n+\n class GitHubApp(object):\n \"\"\"The GitHubApp object provides the central interface for interacting GitHub hooks\n and creating GitHub app clients.\n@@ -163,30 +171,37 @@ class GitHubApp(object):\n \n return decorator\n \n- def _flask_view_func(self):\n- functions_to_call = []\n- calls = {}\n-\n+ def _validate_request(self):\n if not request.is_json:\n- error_message = 'Invalid HTTP Content-Type header for JSON body ' \\\n- '(must be application/json or application/*+json).'\n- LOG.error(error_message)\n- error_response = make_response(jsonify(status='ERROR', description=error_message),\n- 400)\n- abort(error_response)\n+ raise GitHubAppValidationError('Invalid HTTP Content-Type header for JSON body '\n+ '(must be application/json or application/*+json).')\n \n try:\n request.json\n except BadRequest:\n- error_message = 'Invalid HTTP body (must be JSON).'\n- LOG.error(error_message)\n- error_response = make_response(jsonify(status='ERROR', description=error_message),\n- 400)\n- abort(error_response)\n+ raise GitHubAppValidationError('Invalid HTTP body (must be JSON).')\n+\n+ event = request.headers.get('X-GitHub-Event')\n+\n+ if event is None:\n+ raise GitHubAppValidationError('Missing X-GitHub-Event HTTP header.')\n \n- event = request.headers['X-GitHub-Event']\n action = request.json.get('action')\n \n+ return event, action\n+\n+ def _flask_view_func(self):\n+ functions_to_call = []\n+ calls = {}\n+\n+ try:\n+ event, action = self._validate_request()\n+ except GitHubAppValidationError as e:\n+ LOG.error(e)\n+ error_response = make_response(jsonify(status='ERROR', description=str(e)),\n+ 400)\n+ return abort(error_response)\n+\n if current_app.config['GITHUBAPP_SECRET'] is not False:\n self._verify_webhook()\n \n@@ -220,10 +235,10 @@ class GitHubApp(object):\n else:\n LOG.warning('Signature header missing. Configure your GitHub App with a secret or set GITHUBAPP_SECRET'\n 'to False to disable verification.')\n- abort(400)\n+ return abort(400)\n \n mac = hmac.new(self.secret, msg=request.data, digestmod=digestmod)\n \n if not hmac.compare_digest(mac.hexdigest(), signature):\n LOG.warning('GitHub hook signature verification failed.')\n- abort(400)\n+ return abort(400)\n", "test_patch": "diff --git a/tests/test_core.py b/tests/test_core.py\nindex 593c568..32de120 100644\n--- a/tests/test_core.py\n+++ b/tests/test_core.py\n@@ -276,3 +276,19 @@ def test_invalid_json_body_returns_error(github_app):\n 'status': 'ERROR',\n 'description': 'Invalid HTTP body (must be JSON).'\n }\n+\n+def test_missing_event_header_returns_error(github_app):\n+ \"\"\"HTTP request must havea X-GitHub-Event header\"\"\"\n+ github_app.config['GITHUBAPP_SECRET'] = False\n+ with github_app.test_client() as client:\n+ resp = client.post('/',\n+ data=json.dumps({'installation': {'id': 2},\n+ 'action': 'bar'}),\n+ headers={\n+ 'Content-Type': 'application/json'\n+ })\n+ assert resp.status_code == 400\n+ assert resp.json == {\n+ 'status': 'ERROR',\n+ 'description': 'Missing X-GitHub-Event HTTP header.'\n+ }\n", "FAIL_TO_PASS": ["tests/test_core.py::test_missing_event_header_returns_error"]}], "all_FAIL_TO_PASS": ["tests/test_core.py::test_invalid_json_header_returns_error", "tests/test_core.py::test_invalid_json_body_returns_error", "tests/test_core.py::test_missing_event_header_returns_error"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "astropy__ccdproc-757_x2", "level": 2, "source": "swerebench", "repo": "astropy/ccdproc", "image": "swerebench/sweb.eval.x86_64.astropy_1776_ccdproc-757:latest", "base_commit": "4e6da3b2ba516cafbe65683d68e26b988dac6a4f", "num_bugs": 2, "bugs": [{"instance_id": "astropy__ccdproc-757", "base_commit": "4e6da3b2ba516cafbe65683d68e26b988dac6a4f", "gold_patch": "diff --git a/AUTHORS.rst b/AUTHORS.rst\nindex aaf3470..f067a45 100644\n--- a/AUTHORS.rst\n+++ b/AUTHORS.rst\n@@ -56,6 +56,7 @@ Alphabetical list of contributors\n * Nathan Walker (@walkerna22)\n * Benjamin Weiner (@bjweiner)\n * Jiyong Youn (@hletrd)\n+* Yash Gondhalekar (@Yash-10)\n \n (If you have contributed to the ccdproc project and your name is missing,\n please send an email to the coordinators, or\ndiff --git a/CHANGES.rst b/CHANGES.rst\nindex 1d9ac18..d21f3a1 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -16,6 +16,8 @@ Bug Fixes\n - ``test_image_collection.py`` in the test suite no longer produces\n permanent files on disk and cleans up after itself. [#738]\n \n+- Change ``Combiner`` to allow accepting either a list or a generator [#757]\n+\n 2.1.0 (2019-12-24)\n ------------------\n \ndiff --git a/ccdproc/combiner.py b/ccdproc/combiner.py\nindex 2e6eefc..39f3e28 100644\n--- a/ccdproc/combiner.py\n+++ b/ccdproc/combiner.py\n@@ -22,8 +22,8 @@ class Combiner:\n \n Parameters\n -----------\n- ccd_list : list\n- A list of CCDData objects that will be combined together.\n+ ccd_iter : list or generator\n+ A list or generator of CCDData objects that will be combined together.\n \n dtype : str or `numpy.dtype` or None, optional\n Allows user to set dtype. See `numpy.array` ``dtype`` parameter\n@@ -33,7 +33,7 @@ class Combiner:\n Raises\n ------\n TypeError\n- If the ``ccd_list`` are not `~astropy.nddata.CCDData` objects, have different\n+ If the ``ccd_iter`` are not `~astropy.nddata.CCDData` objects, have different\n units, or are different shapes.\n \n Examples\n@@ -56,15 +56,18 @@ class Combiner:\n [ 0.66666667, 0.66666667, 0.66666667, 0.66666667],\n [ 0.66666667, 0.66666667, 0.66666667, 0.66666667]])\n \"\"\"\n- def __init__(self, ccd_list, dtype=None):\n- if ccd_list is None:\n- raise TypeError(\"ccd_list should be a list of CCDData objects.\")\n+ def __init__(self, ccd_iter, dtype=None):\n+ if ccd_iter is None:\n+ raise TypeError(\"ccd_iter should be a list or a generator of CCDData objects.\")\n \n if dtype is None:\n dtype = np.float64\n \n default_shape = None\n default_unit = None\n+\n+ ccd_list = list(ccd_iter)\n+\n for ccd in ccd_list:\n # raise an error if the objects aren't CCDData objects\n if not isinstance(ccd, CCDData):\n", "test_patch": "diff --git a/ccdproc/tests/test_combiner.py b/ccdproc/tests/test_combiner.py\nindex a9988d3..b758c66 100644\n--- a/ccdproc/tests/test_combiner.py\n+++ b/ccdproc/tests/test_combiner.py\n@@ -696,3 +696,13 @@ def test_ystep_calculation(num_chunks, expected):\n \n xstep, ystep = _calculate_step_sizes(2000, 2000, num_chunks)\n assert xstep == expected[0] and ystep == expected[1]\n+\n+def test_combiner_gen():\n+ ccd_data = ccd_data_func()\n+ def create_gen():\n+ yield ccd_data\n+ yield ccd_data\n+ yield ccd_data\n+ c = Combiner(create_gen())\n+ assert c.data_arr.shape == (3, 100, 100)\n+ assert c.data_arr.mask.shape == (3, 100, 100)\n", "FAIL_TO_PASS": ["ccdproc/tests/test_combiner.py::test_combiner_gen"]}, {"instance_id": "astropy__ccdproc-762", "base_commit": "1a5934c7dd8010cdfdf7fce34850eded775ba055", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex d21f3a1..b9f20a2 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -4,6 +4,9 @@\n New Features\n ^^^^^^^^^^^^\n \n+- Improve integration of ``ImageFileCollection`` with image combination\n+ and document that integration [#762]\n+\n Other Changes and Additions\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n - Add memory_profiler as a test requirement [#739]\n@@ -14,7 +17,7 @@ Bug Fixes\n ^^^^^^^^^\n \n - ``test_image_collection.py`` in the test suite no longer produces\n- permanent files on disk and cleans up after itself. [#738]\n+ permanent files on disk and cleans up after itself. [#738]\n \n - Change ``Combiner`` to allow accepting either a list or a generator [#757]\n \ndiff --git a/ccdproc/combiner.py b/ccdproc/combiner.py\nindex 39f3e28..d85c55e 100644\n--- a/ccdproc/combiner.py\n+++ b/ccdproc/combiner.py\n@@ -676,8 +676,12 @@ def combine(img_list, output_file=None,\n elif isinstance(img_list, str) and (',' in img_list):\n img_list = img_list.split(',')\n else:\n- raise ValueError(\n- \"unrecognised input for list of images to combine.\")\n+ try:\n+ # Maybe the input can be made into a list, so try that\n+ img_list = list(img_list)\n+ except TypeError:\n+ raise ValueError(\n+ \"unrecognised input for list of images to combine.\")\n \n # Select Combine function to call in Combiner\n if method == 'average':\ndiff --git a/docs/image_combination.rst b/docs/image_combination.rst\nindex 0922d21..012fa5b 100644\n--- a/docs/image_combination.rst\n+++ b/docs/image_combination.rst\n@@ -4,9 +4,13 @@ Combining images and generating masks from clipping\n ===================================================\n \n .. note::\n- No attempt has been made yet to optimize memory usage in\n- `~ccdproc.Combiner`. A copy is made, and a mask array\n- constructed, for each input image.\n+ There are currently two interfaces to image combination. One is through\n+ the `~ccdproc.Combiner` class, the other through the `~ccdproc.combine`\n+ function. They offer *almost* identical capabilities. The primary\n+ difference is that `~ccdproc.combine` allows you to place an upper\n+ limit on the amount of memory used.\n+\n+ Work to improve the performance of image combination is ongoing.\n \n \n The first step in combining a set of images is creating a\n@@ -133,6 +137,48 @@ using `~ccdproc.Combiner.average_combine` or\n `~ccdproc.Combiner.median_combine`).\n \n \n+.. _combination_with_IFC\n+Image combination using `~ccdproc.ImageFileCollection`\n+------------------------------------------------------\n+\n+There are a couple of ways that image combination can be done if you are using\n+`~ccdproc.ImageFileCollection` to\n+:ref:`manage a folder of images `.\n+\n+For this example, a temporary folder with images in it is created:\n+\n+ >>> from tempfile import mkdtemp\n+ >>> from pathlib import Path\n+ >>> import numpy as np\n+ >>> from astropy.nddata import CCDData\n+ >>> from ccdproc import ImageFileCollection, Combiner, combine\n+ >>>\n+ >>> ccd = CCDData(np.ones([5, 5]), unit='adu')\n+ >>>\n+ >>> # Make a temporary folder as a path object\n+ >>> image_folder = Path(mkdtemp())\n+ >>> # Put several copies ccd in the temporary folder\n+ >>> _ = [ccd.write(image_folder / f\"ccd-{i}.fits\") for i in range(3)]\n+ >>> ifc = ImageFileCollection(image_folder)\n+\n+To combine images using the `~ccdproc.Combiner` class you can use the ``ccds``\n+method of the `~ccdproc.ImageFileCollection`:\n+\n+ >>> c = Combiner(ifc.ccds())\n+ >>> avg_combined = c.average_combine()\n+\n+There two ways combine images using the `~ccdproc.combine` function. If the\n+images are large enough to combine in memory, then use the file names as the argument to `~ccdproc.combine`, like this:\n+\n+ >>> avg_combo_mem_lim = combine(ifc.files_filtered(include_path=True),\n+ ... mem_limit=1e9)\n+\n+If memory use is not an issue, then the ``ccds`` method can be used here too:\n+\n+ >>> avg_combo = combine(ifc.ccds())\n+\n+\n+\n .. _reprojection:\n \n Combination with image transformation and alignment\ndiff --git a/setup.cfg b/setup.cfg\nindex fac559b..827bd83 100644\n--- a/setup.cfg\n+++ b/setup.cfg\n@@ -4,6 +4,7 @@ minversion = 2.2\n testpaths = \"ccdproc\" \"docs\"\n norecursedirs = build docs/_build\n doctest_plus = enabled\n+addopts = --doctest-rst\n markers =\n data_size(N): set dimension of square data array for ccd_data fixture\n data_scale(s): set the scale of the normal distribution used to generate data\n", "test_patch": "diff --git a/ccdproc/tests/test_combiner.py b/ccdproc/tests/test_combiner.py\nindex b758c66..1c158a0 100644\n--- a/ccdproc/tests/test_combiner.py\n+++ b/ccdproc/tests/test_combiner.py\n@@ -10,6 +10,7 @@ from astropy.utils.data import get_pkg_data_filename\n from astropy.nddata import CCDData\n \n from ccdproc.combiner import Combiner, combine, _calculate_step_sizes\n+from ccdproc.image_collection import ImageFileCollection\n from ccdproc.tests.pytest_fixtures import ccd_data as ccd_data_func\n \n \n@@ -373,6 +374,43 @@ def test_combiner_result_dtype():\n np.testing.assert_array_almost_equal(res.data, ref)\n \n \n+def test_combiner_image_file_collection_input(tmp_path):\n+ # Regression check for #754\n+ ccd = ccd_data_func()\n+ for i in range(3):\n+ ccd.write(tmp_path / f'ccd-{i}.fits')\n+\n+ ifc = ImageFileCollection(tmp_path)\n+ comb = Combiner(ifc.ccds())\n+ np.testing.assert_array_almost_equal(ccd.data,\n+ comb.average_combine().data)\n+\n+\n+def test_combine_image_file_collection_input(tmp_path):\n+ # Another regression check for #754 but this time with the\n+ # combine function instead of Combiner\n+ ccd = ccd_data_func()\n+ for i in range(3):\n+ ccd.write(tmp_path / f'ccd-{i}.fits')\n+\n+ ifc = ImageFileCollection(tmp_path)\n+\n+ comb_files = combine(ifc.files_filtered(include_path=True),\n+ method='average')\n+\n+ comb_ccds = combine(ifc.ccds(), method='average')\n+\n+ np.testing.assert_array_almost_equal(ccd.data,\n+ comb_files.data)\n+ np.testing.assert_array_almost_equal(ccd.data,\n+ comb_ccds.data)\n+\n+ with pytest.raises(FileNotFoundError):\n+ # This should fail because the test is not running in the\n+ # folder where the images are.\n+ _ = combine(ifc.files_filtered())\n+\n+\n # test combiner convenience function works with list of ccddata objects\n def test_combine_average_ccddata():\n fitsfile = get_pkg_data_filename('data/a8280271.fits')\n", "FAIL_TO_PASS": ["ccdproc/tests/test_combiner.py::test_combine_image_file_collection_input"]}], "all_FAIL_TO_PASS": ["ccdproc/tests/test_combiner.py::test_combiner_gen", "ccdproc/tests/test_combiner.py::test_combine_image_file_collection_input"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ResearchObject__ro-crate-py-163_x2", "level": 2, "source": "swerebench", "repo": "ResearchObject/ro-crate-py", "image": "swerebench/sweb.eval.x86_64.researchobject_1776_ro-crate-py-163:latest", "base_commit": "b3e24baaff92636dc58d910f6f1103d4f86a4c31", "num_bugs": 2, "bugs": [{"instance_id": "ResearchObject__ro-crate-py-163", "base_commit": "b3e24baaff92636dc58d910f6f1103d4f86a4c31", "gold_patch": "diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py\nindex 57bcd39..5d5a98d 100644\n--- a/rocrate/rocrate.py\n+++ b/rocrate/rocrate.py\n@@ -142,7 +142,7 @@ class ROCrate():\n \n root_entity = entities.pop(root_id)\n assert root_id == root_entity.pop('@id')\n- parts = root_entity.pop('hasPart', [])\n+ parts = as_list(root_entity.pop('hasPart', []))\n self.add(RootDataset(self, root_id, properties=root_entity))\n preview_entity = entities.pop(Preview.BASENAME, None)\n if preview_entity and not gen_preview:\n@@ -167,7 +167,7 @@ class ROCrate():\n else:\n instance = cls(self, source / id_, id_, properties=entity)\n self.add(instance)\n- self.__add_parts(entity.get(\"hasPart\", []), entities, source)\n+ self.__add_parts(as_list(entity.get(\"hasPart\", [])), entities, source)\n \n def __read_contextual_entities(self, entities):\n type_map = {_.__name__: _ for _ in subclasses(ContextEntity)}\n", "test_patch": "diff --git a/test/test_read.py b/test/test_read.py\nindex 9aa3e96..43bf328 100644\n--- a/test/test_read.py\n+++ b/test/test_read.py\n@@ -499,17 +499,17 @@ def test_indirect_data_entity(tmpdir):\n {\n \"@id\": \"./\",\n \"@type\": \"Dataset\",\n- \"hasPart\": [{\"@id\": \"d1\"}]\n+ \"hasPart\": {\"@id\": \"d1\"}\n },\n {\n \"@id\": \"d1\",\n \"@type\": \"Dataset\",\n- \"hasPart\": [{\"@id\": \"d1/d2\"}]\n+ \"hasPart\": {\"@id\": \"d1/d2\"}\n },\n {\n \"@id\": \"d1/d2\",\n \"@type\": \"Dataset\",\n- \"hasPart\": [{\"@id\": \"d1/d2/f1\"}]\n+ \"hasPart\": {\"@id\": \"d1/d2/f1\"}\n },\n {\n \"@id\": \"d1/d2/f1\",\n", "FAIL_TO_PASS": ["test/test_read.py::test_indirect_data_entity"]}, {"instance_id": "ResearchObject__ro-crate-py-166", "base_commit": "0d3c63946d2a0ab5aeaa5f3bc228db76455c80f8", "gold_patch": "diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py\nindex 5d5a98d..d3041a1 100644\n--- a/rocrate/rocrate.py\n+++ b/rocrate/rocrate.py\n@@ -75,9 +75,6 @@ class ROCrate():\n def __init__(self, source=None, gen_preview=False, init=False, exclude=None):\n self.exclude = exclude\n self.__entity_map = {}\n- self.default_entities = []\n- self.data_entities = []\n- self.contextual_entities = []\n # TODO: add this as @base in the context? At least when loading\n # from zip\n self.uuid = uuid.uuid4()\n@@ -136,14 +133,14 @@ class ROCrate():\n \n def __read_data_entities(self, entities, source, gen_preview):\n metadata_id, root_id = find_root_entity_id(entities)\n- MetadataClass = metadata_class(metadata_id)\n- metadata_properties = entities.pop(metadata_id)\n- self.add(MetadataClass(self, metadata_id, properties=metadata_properties))\n-\n root_entity = entities.pop(root_id)\n assert root_id == root_entity.pop('@id')\n parts = as_list(root_entity.pop('hasPart', []))\n self.add(RootDataset(self, root_id, properties=root_entity))\n+ MetadataClass = metadata_class(metadata_id)\n+ metadata_properties = entities.pop(metadata_id)\n+ self.add(MetadataClass(self, metadata_id, properties=metadata_properties))\n+\n preview_entity = entities.pop(Preview.BASENAME, None)\n if preview_entity and not gen_preview:\n self.add(Preview(self, source / Preview.BASENAME, properties=preview_entity))\n@@ -176,6 +173,23 @@ class ROCrate():\n cls = pick_type(entity, type_map, fallback=ContextEntity)\n self.add(cls(self, identifier, entity))\n \n+ @property\n+ def default_entities(self):\n+ return [e for e in self.__entity_map.values()\n+ if isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview))]\n+\n+ @property\n+ def data_entities(self):\n+ return [e for e in self.__entity_map.values()\n+ if not isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview))\n+ and hasattr(e, \"write\")]\n+\n+ @property\n+ def contextual_entities(self):\n+ return [e for e in self.__entity_map.values()\n+ if not isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview))\n+ and not hasattr(e, \"write\")]\n+\n @property\n def name(self):\n return self.root_dataset.get('name')\n@@ -379,18 +393,13 @@ class ROCrate():\n key = e.canonical_id()\n if isinstance(e, RootDataset):\n self.root_dataset = e\n- if isinstance(e, (Metadata, LegacyMetadata)):\n+ elif isinstance(e, (Metadata, LegacyMetadata)):\n self.metadata = e\n- if isinstance(e, Preview):\n+ elif isinstance(e, Preview):\n self.preview = e\n- if isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview)):\n- self.default_entities.append(e)\n elif hasattr(e, \"write\"):\n- self.data_entities.append(e)\n if key not in self.__entity_map:\n self.root_dataset.append_to(\"hasPart\", e)\n- else:\n- self.contextual_entities.append(e)\n self.__entity_map[key] = e\n return entities[0] if len(entities) == 1 else entities\n \n@@ -412,21 +421,11 @@ class ROCrate():\n if e is self.metadata:\n raise ValueError(\"cannot delete the metadata entity\")\n if e is self.preview:\n- self.default_entities.remove(e)\n self.preview = None\n elif hasattr(e, \"write\"):\n- try:\n- self.data_entities.remove(e)\n- except ValueError:\n- pass\n self.root_dataset[\"hasPart\"] = [_ for _ in self.root_dataset.get(\"hasPart\", []) if _ != e]\n if not self.root_dataset[\"hasPart\"]:\n del self.root_dataset._jsonld[\"hasPart\"]\n- else:\n- try:\n- self.contextual_entities.remove(e)\n- except ValueError:\n- pass\n self.__entity_map.pop(e.canonical_id(), None)\n \n def _copy_unlisted(self, top, base_path):\n", "test_patch": "diff --git a/test/test_model.py b/test/test_model.py\nindex 0324d90..e7b5343 100644\n--- a/test/test_model.py\n+++ b/test/test_model.py\n@@ -475,3 +475,33 @@ def test_context(helpers):\n crate.metadata.extra_terms[k] = v\n jsonld = crate.metadata.generate()\n assert jsonld[\"@context\"] == [base_context, wfrun_ctx, {k: v}]\n+\n+\n+def test_add_no_duplicates(test_data_dir, tmpdir):\n+ source = test_data_dir / \"sample_file.txt\"\n+ crate = ROCrate()\n+ f1 = crate.add_file(source, properties={\"name\": \"sample file\"})\n+ ret = crate.get(source.name)\n+ assert ret is f1\n+ assert ret[\"name\"] == \"sample file\"\n+ assert ret in crate.get_entities()\n+ assert crate.data_entities == [f1]\n+ f2 = crate.add_file(source, properties={\"name\": \"foobar\"})\n+ ret = crate.get(source.name)\n+ assert ret is f2\n+ assert ret[\"name\"] == \"foobar\"\n+ assert ret in crate.get_entities()\n+ assert f1 not in crate.get_entities()\n+ assert crate.data_entities == [f2]\n+ joe = crate.add(Person(crate, \"#joe\", properties={\"name\": \"Joe\"}))\n+ ret = crate.get(\"#joe\")\n+ assert ret is joe\n+ assert ret in crate.get_entities()\n+ assert ret[\"name\"] == \"Joe\"\n+ assert crate.contextual_entities == [joe]\n+ jim = crate.add(Person(crate, \"#joe\", properties={\"name\": \"Jim\"}))\n+ ret = crate.get(\"#joe\")\n+ assert ret is jim\n+ assert ret[\"name\"] == \"Jim\"\n+ assert ret in crate.get_entities()\n+ assert crate.contextual_entities == [jim]\n", "FAIL_TO_PASS": ["test/test_model.py::test_add_no_duplicates"]}], "all_FAIL_TO_PASS": ["test/test_read.py::test_indirect_data_entity", "test/test_model.py::test_add_no_duplicates"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cunybpl__isdparser-2_x2", "level": 2, "source": "swerebench", "repo": "cunybpl/isdparser", "image": "swerebench/sweb.eval.x86_64.cunybpl_1776_isdparser-2:latest", "base_commit": "f1012bd8ef09d842733409eb848d45857c13300e", "num_bugs": 2, "bugs": [{"instance_id": "cunybpl__isdparser-2", "base_commit": "f1012bd8ef09d842733409eb848d45857c13300e", "gold_patch": "diff --git a/isdparser/_version.py b/isdparser/_version.py\nindex aa70592..b72bd09 100644\n--- a/isdparser/_version.py\n+++ b/isdparser/_version.py\n@@ -1,1 +1,1 @@\n-VERSION='0.2.0'\n\\ No newline at end of file\n+VERSION='0.2.1'\n\\ No newline at end of file\ndiff --git a/isdparser/record.py b/isdparser/record.py\nindex 3e70bfe..78c1885 100644\n--- a/isdparser/record.py\n+++ b/isdparser/record.py\n@@ -49,19 +49,21 @@ class ISDRecordFactory(object):\n __slots__ = ('_control', '_mandatory')\n \n def __init__(self, \n- control: Tuple[str, List[Measure]]=('control', control_measures()), \n- mandatory: Tuple[str, List[Measure]]=('mandatory', mandatory_measures())):\n+ control: Tuple[str, List[Measure]]=None, \n+ mandatory: Tuple[str, List[Measure]]=None):\n \"\"\"Creates an ISDRecord from a single line from an isd file. \n Object configuration uses Section and Measure object APIs internally. \n+ If control and mandatory were not given, ('control', control_measures()) and ('mandatory', mandatory_measures())) \n+ will be used instead.\n \n Args:\n control (Tuple[str, List[Measure]], optional): A name and list of control measures. \n- Defaults to ('control', control_measures()).\n+ Defaults to None.\n mandatory (Tuple[str, List[Measure]], optional): A name and list of section measures. \n- Defaults to ('mandatory', mandatory_measures()).\n+ Defaults to None.\n \"\"\"\n- self._control = control\n- self._mandatory = mandatory\n+ self._control = control if control else ('control', control_measures())\n+ self._mandatory = mandatory if mandatory else ('mandatory', mandatory_measures())\n \n \n @staticmethod \n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 5fb53a3..b61f1fc 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -2,8 +2,12 @@ import pytest\n \n \n @pytest.fixture\n-def isd_record_string(): \n- return \"\"\"0130010230999992020010100004+69067+018533FM-12+007999999V0200501N001019999999N999999999-00291-00381099661\n- ADDAA199999919MA1999999098701MD1810211+9999OD139900601999REMSYN06401023 16/// /0501 11029 21038 39870 49966 58021 6//// 333 91106=\"\"\"\n+def isd_record_strings_list(): \n+ return [\"\"\"0130010230999992020010100004+69067+018533FM-12+007999999V0200501N001019999999N999999999-00291-00381099661\n+ ADDAA199999919MA1999999098701MD1810211+9999OD139900601999REMSYN06401023 16/// /0501 11029 21038 39870 49966 58021 6//// 333 91106=\"\"\",\n+ \"\"\"0130010230999992020020100004+69067+018533FM-12+007999999V0200501N001019999999N999999999-00291-00381099661\n+ ADDAA199999919MA1999999098701MD1810211+9999OD139900601999REMSYN06401023 16/// /0501 11029 21038 39870 49966 58021 6//// 333 91106=\"\"\",\n+ \"\"\"0130010230999992020030100004+69067+018533FM-12+007999999V0200501N001019999999N999999999-00291-00381099661\n+ ADDAA199999919MA1999999098701MD1810211+9999OD139900601999REMSYN06401023 16/// /0501 11029 21038 39870 49966 58021 6//// 333 91106=\"\"\"]\n \n \ndiff --git a/tests/test_record.py b/tests/test_record.py\nindex 9ac717e..84b3f0d 100644\n--- a/tests/test_record.py\n+++ b/tests/test_record.py\n@@ -5,6 +5,7 @@ tc = unittest.TestCase()\n \n from isdparser.measures import Measure, Section\n from isdparser.record import ISDRecord, ISDRecordFactory\n+import copy\n \n def test_isdrecord(mocker): \n \n@@ -48,11 +49,12 @@ def test_isdrecordfactory_static_methods():\n \n \n \n-def test_isdrecordfactory_on_record_string(isd_record_string):\n+def test_isdrecordfactory_on_record_string(isd_record_strings_list):\n \n- result = ISDRecordFactory().create(isd_record_string)\n \n- expected = {\n+ result = [ISDRecordFactory().create(line) for line in isd_record_strings_list]\n+\n+ exp0 = {\n 'datestamp': datetime.datetime(2020, 1, 1, 0, 0, tzinfo=datetime.timezone.utc), \n 'identifier': '010230-99999', \n 'sections': [\n@@ -97,4 +99,17 @@ def test_isdrecordfactory_on_record_string(isd_record_string):\n ]\n }\n \n- tc.assertDictEqual(expected, result.schema())\n\\ No newline at end of file\n+ exp1 = copy.deepcopy(exp0)\n+ exp1['datestamp'] = datetime.datetime(2020, 2, 1, 0, 0, tzinfo=datetime.timezone.utc)\n+ exp1['sections'][0]['measures'][2]['value'] = '20200201'\n+\n+ exp2 = copy.deepcopy(exp0)\n+ exp2['datestamp'] = datetime.datetime(2020, 3, 1, 0, 0, tzinfo=datetime.timezone.utc)\n+ exp2['sections'][0]['measures'][2]['value'] = '20200301'\n+\n+ expected = [exp0, exp1, exp2]\n+\n+ for res in result:\n+ datestamp = res.schema()['datestamp']\n+ exp = list(filter(lambda x: x['datestamp'] == datestamp, expected))[0]\n+ tc.assertDictEqual(exp, res.schema())\n\\ No newline at end of file\n", "FAIL_TO_PASS": ["tests/test_record.py::test_isdrecordfactory_on_record_string"]}, {"instance_id": "cunybpl__isdparser-4", "base_commit": "d36f19a863deb257f5766d866340421d8704d8cc", "gold_patch": "diff --git a/isdparser/_version.py b/isdparser/_version.py\nindex b72bd09..5aa75f8 100644\n--- a/isdparser/_version.py\n+++ b/isdparser/_version.py\n@@ -1,1 +1,1 @@\n-VERSION='0.2.1'\n\\ No newline at end of file\n+VERSION='0.2.3'\n\\ No newline at end of file\ndiff --git a/isdparser/measures.py b/isdparser/measures.py\nindex f42a6fe..0434f96 100644\n--- a/isdparser/measures.py\n+++ b/isdparser/measures.py\n@@ -86,7 +86,7 @@ class Measure(object):\n Returns:\n Measure: the instance.\n \"\"\"\n- self._value = value \n+ self._value = value.strip() if type(value) is str else value\n return self\n \n \n", "test_patch": "diff --git a/tests/test_measures.py b/tests/test_measures.py\nindex bc73332..5bc33c8 100644\n--- a/tests/test_measures.py\n+++ b/tests/test_measures.py\n@@ -77,6 +77,19 @@ def test_categorical_measure():\n \n tc.assertDictEqual(expected, m.schema())\n \n+ test_mapping_with_whitespace = {\n+ 'blah': 'blah blah blah'\n+ }\n+\n+ m = CategoricalMeasure('my_measure', Position(1,5), test_mapping_with_whitespace, missing='9')\n+ m.set_value('blah ')\n+ expected = {\n+ 'measure': 'my_measure', \n+ 'value': 'blah', \n+ 'description': 'blah blah blah'\n+ }\n+ tc.assertDictEqual(expected, m.schema())\n+\n \n def test_section(mocker): \n \n", "FAIL_TO_PASS": ["tests/test_measures.py::test_categorical_measure"]}], "all_FAIL_TO_PASS": ["tests/test_record.py::test_isdrecordfactory_on_record_string", "tests/test_measures.py::test_categorical_measure"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "astropenguin__pandas-dataclasses-109_x2", "level": 2, "source": "swerebench", "repo": "astropenguin/pandas-dataclasses", "image": "swerebench/sweb.eval.x86_64.astropenguin_1776_pandas-dataclasses-109:latest", "base_commit": "5a2e8c3dad5615eb18c8928d9155a4cbafc5bace", "num_bugs": 2, "bugs": [{"instance_id": "astropenguin__pandas-dataclasses-109", "base_commit": "5a2e8c3dad5615eb18c8928d9155a4cbafc5bace", "gold_patch": "diff --git a/README.md b/README.md\nindex 61461ac..f9bf148 100644\n--- a/README.md\n+++ b/README.md\n@@ -17,13 +17,13 @@ pandas-dataclass makes it easy to create [pandas] data (DataFrame and Series) by\n \n ```python\n from dataclasses import dataclass\n-from pandas_dataclasses import AsDataFrame, Data, Index\n+from pandas_dataclasses import AsFrame, Data, Index\n ```\n \n \n ```python\n @dataclass\n-class Weather(AsDataFrame):\n+class Weather(AsFrame):\n \"\"\"Weather information.\"\"\"\n \n year: Index[int]\n@@ -72,7 +72,7 @@ pip install pandas-dataclasses\n pandas-dataclasses provides you the following features:\n \n - Type hints for dataclass fields (`Attr`, `Column`, `Data`, `Index`) to specify the data type and name of each element in pandas data\n-- Mix-in classes for dataclasses (`As`, `AsDataFrame`, `AsSeries`) to create pandas data by a classmethod (`new`) that takes the same arguments as dataclass initialization\n+- Mix-in classes for dataclasses (`As`, `AsFrame`, `AsSeries`) to create pandas data by a classmethod (`new`) that takes the same arguments as dataclass initialization\n \n When you call `new`, it will first create a dataclass object and then create a Series or DataFrame object from the dataclass object according the type hints and values in it.\n In the example above, `df = Weather.new(...)` is thus equivalent to:\n@@ -81,36 +81,36 @@ In the example above, `df = Weather.new(...)` is thus equivalent to:\n Click to see all imports\n \n ```python\n-from pandas_dataclasses import asdataframe\n+from pandas_dataclasses import asframe\n ```\n \n \n ```python\n obj = Weather([2020, ...], [1, ...], [7.1, ...], [2.4, ...])\n-df = asdataframe(obj)\n+df = asframe(obj)\n ```\n \n-where `asdataframe` is a conversion function.\n+where `asframe` is a conversion function.\n pandas-dataclasses does not touch the dataclass object creation itself; this allows you to fully customize your dataclass before conversion by the dataclass features (`field`, `__post_init__`, ...).\n \n ## Basic usage\n \n ### DataFrame creation\n \n-As shown in the example above, a dataclass that has the `AsDataFrame` mix-in will create DataFrame objects:\n+As shown in the example above, a dataclass that has the `AsFrame` mix-in will create DataFrame objects:\n \n
\n Click to see all imports\n \n ```python\n from dataclasses import dataclass\n-from pandas_dataclasses import AsDataFrame, Data, Index\n+from pandas_dataclasses import AsFrame, Data, Index\n ```\n
\n \n ```python\n @dataclass\n-class Weather(AsDataFrame):\n+class Weather(AsFrame):\n \"\"\"Weather information.\"\"\"\n \n year: Index[int]\n@@ -159,7 +159,7 @@ class Weather(AsSeries):\n ser = Weather.new(...)\n ```\n \n-Unlike `AsDataFrame`, the second and subsequent data fields are ignored in the Series creation even if they exist.\n+Unlike `AsFrame`, the second and subsequent data fields are ignored in the Series creation even if they exist.\n Other rules are the same as for the DataFrame creation.\n \n ## Advanced usage\n@@ -173,13 +173,13 @@ Fields typed by `Attr` are *attribute fields*, each value of which will become a\n \n ```python\n from dataclasses import dataclass\n-from pandas_dataclasses import AsDataFrame, Attr, Data, Index\n+from pandas_dataclasses import AsFrame, Attr, Data, Index\n ```\n \n \n ```python\n @dataclass\n-class Weather(AsDataFrame):\n+class Weather(AsFrame):\n \"\"\"Weather information.\"\"\"\n \n year: Index[int]\n@@ -210,13 +210,13 @@ The name of attribute, data, or index can be explicitly specified by adding a ha\n ```python\n from dataclasses import dataclass\n from typing import Annotated as Ann\n-from pandas_dataclasses import AsDataFrame, Attr, Data, Index\n+from pandas_dataclasses import AsFrame, Attr, Data, Index\n ```\n \n \n ```python\n @dataclass\n-class Weather(AsDataFrame):\n+class Weather(AsFrame):\n \"\"\"Weather information.\"\"\"\n \n year: Ann[Index[int], \"Year\"]\n@@ -255,13 +255,13 @@ If an annotation is a [format string], it will be formatted by a dataclass objec\n ```python\n from dataclasses import dataclass\n from typing import Annotated as Ann\n-from pandas_dataclasses import AsDataFrame, Data, Index\n+from pandas_dataclasses import AsFrame, Data, Index\n ```\n \n \n ```python\n @dataclass\n-class Weather(AsDataFrame):\n+class Weather(AsFrame):\n \"\"\"Weather information.\"\"\"\n \n year: Ann[Index[int], \"Year\"]\n@@ -287,13 +287,13 @@ Adding tuple annotations to data fields will create DataFrame objects with hiera\n ```python\n from dataclasses import dataclass\n from typing import Annotated as Ann\n-from pandas_dataclasses import AsDataFrame, Data, Index\n+from pandas_dataclasses import AsFrame, Data, Index\n ```\n \n \n ```python\n @dataclass\n-class Weather(AsDataFrame):\n+class Weather(AsFrame):\n \"\"\"Weather information.\"\"\"\n \n year: Ann[Index[int], \"Year\"]\n@@ -328,13 +328,13 @@ Column names can be (explicitly) specified by *column fields* (with hashable ann\n ```python\n from dataclasses import dataclass\n from typing import Annotated as Ann\n-from pandas_dataclasses import AsDataFrame, Column, Data, Index\n+from pandas_dataclasses import AsFrame, Column, Data, Index\n ```\n \n \n ```python\n @dataclass\n-class Weather(AsDataFrame):\n+class Weather(AsFrame):\n \"\"\"Weather information.\"\"\"\n \n year: Ann[Index[int], \"Year\"]\n@@ -368,7 +368,7 @@ If a tuple annotation has [format string]s, they will also be formatted by a dat\n \n ### Custom pandas factory\n \n-A custom class can be specified as a factory for the Series or DataFrame creation by `As`, the generic version of `AsDataFrame` and `AsSeries`.\n+A custom class can be specified as a factory for the Series or DataFrame creation by `As`, the generic version of `AsFrame` and `AsSeries`.\n Note that the custom class must be a subclass of either `pandas.Series` or `pandas.DataFrame`:\n \n
\ndiff --git a/pandas_dataclasses/__init__.py b/pandas_dataclasses/__init__.py\nindex fe0a274..18a5d75 100644\n--- a/pandas_dataclasses/__init__.py\n+++ b/pandas_dataclasses/__init__.py\n@@ -1,6 +1,7 @@\n __all__ = [\n \"As\",\n \"AsDataFrame\",\n+ \"AsFrame\",\n \"AsSeries\",\n \"Attr\",\n \"Column\",\n@@ -9,13 +10,14 @@ __all__ = [\n \"Other\",\n \"Spec\",\n \"asdataframe\",\n+ \"asframe\",\n \"asseries\",\n \"core\",\n ]\n \n \n from . import core\n-from .core.asdata import *\n+from .core.aspandas import *\n from .core.mixins import *\n from .core.specs import *\n from .core.typing import *\n@@ -23,3 +25,12 @@ from .core.typing import *\n \n # metadata\n __version__ = \"0.8.0\"\n+\n+\n+# aliases\n+AsDataFrame = AsFrame\n+\"\"\"Alias of ``core.mixins.AsFrame``.\"\"\"\n+\n+\n+asdataframe = asframe\n+\"\"\"Alias of ``core.aspandas.asframe``.\"\"\"\ndiff --git a/pandas_dataclasses/core/__init__.py b/pandas_dataclasses/core/__init__.py\nindex cd94a78..b44c4f9 100644\n--- a/pandas_dataclasses/core/__init__.py\n+++ b/pandas_dataclasses/core/__init__.py\n@@ -1,7 +1,7 @@\n-__all__ = [\"asdata\", \"mixins\", \"specs\", \"typing\"]\n+__all__ = [\"aspandas\", \"mixins\", \"specs\", \"typing\"]\n \n \n-from . import asdata\n+from . import aspandas\n from . import mixins\n from . import specs\n from . import typing\ndiff --git a/pandas_dataclasses/core/asdata.py b/pandas_dataclasses/core/aspandas.py\nsimilarity index 88%\nrename from pandas_dataclasses/core/asdata.py\nrename to pandas_dataclasses/core/aspandas.py\nindex 29265a5..b7003c4 100644\n--- a/pandas_dataclasses/core/asdata.py\n+++ b/pandas_dataclasses/core/aspandas.py\n@@ -1,4 +1,4 @@\n-__all__ = [\"asdataframe\", \"asseries\"]\n+__all__ = [\"asframe\", \"asseries\"]\n \n \n # standard library\n@@ -12,26 +12,26 @@ import pandas as pd\n \n # submodules\n from .specs import Spec\n-from .typing import P, DataClass, PandasClass, TDataFrame, TSeries\n+from .typing import P, DataClass, PandasClass, TFrame, TSeries\n \n \n # runtime functions\n @overload\n-def asdataframe(obj: PandasClass[P, TDataFrame], *, factory: None = None) -> TDataFrame:\n+def asframe(obj: PandasClass[P, TFrame], *, factory: None = None) -> TFrame:\n ...\n \n \n @overload\n-def asdataframe(obj: DataClass[P], *, factory: Callable[..., TDataFrame]) -> TDataFrame:\n+def asframe(obj: DataClass[P], *, factory: Callable[..., TFrame]) -> TFrame:\n ...\n \n \n @overload\n-def asdataframe(obj: DataClass[P], *, factory: None = None) -> pd.DataFrame:\n+def asframe(obj: DataClass[P], *, factory: None = None) -> pd.DataFrame:\n ...\n \n \n-def asdataframe(obj: Any, *, factory: Any = None) -> Any:\n+def asframe(obj: Any, *, factory: Any = None) -> Any:\n \"\"\"Create a DataFrame object from a dataclass object.\"\"\"\n spec = Spec.from_dataclass(type(obj)) @ obj\n \ndiff --git a/pandas_dataclasses/core/mixins.py b/pandas_dataclasses/core/mixins.py\nindex 74b32f7..f1cfad1 100644\n--- a/pandas_dataclasses/core/mixins.py\n+++ b/pandas_dataclasses/core/mixins.py\n@@ -1,4 +1,4 @@\n-__all__ = [\"As\", \"AsDataFrame\", \"AsSeries\"]\n+__all__ = [\"As\", \"AsFrame\", \"AsSeries\"]\n \n \n # standard library\n@@ -14,7 +14,7 @@ from typing_extensions import get_args, get_origin\n \n \n # submodules\n-from .asdata import asdataframe, asseries\n+from .aspandas import asframe, asseries\n from .typing import P, T, Pandas, PandasClass, TPandas\n \n \n@@ -51,7 +51,7 @@ class As(Generic[TPandas]):\n return MethodType(get_creator(cls), cls)\n \n \n-AsDataFrame = As[pd.DataFrame]\n+AsFrame = As[pd.DataFrame]\n \"\"\"Alias of ``As[pandas.DataFrame]``.\"\"\"\n \n \n@@ -72,7 +72,7 @@ def get_creator(cls: Any) -> Callable[..., Pandas]:\n origin = get_origin(return_) or return_\n \n if issubclass(origin, pd.DataFrame):\n- converter: Any = asdataframe\n+ converter: Any = asframe\n elif issubclass(origin, pd.Series):\n converter = asseries\n else:\ndiff --git a/pandas_dataclasses/core/typing.py b/pandas_dataclasses/core/typing.py\nindex dc0704a..4275ff7 100644\n--- a/pandas_dataclasses/core/typing.py\n+++ b/pandas_dataclasses/core/typing.py\n@@ -38,7 +38,7 @@ Pandas = Union[pd.DataFrame, \"pd.Series[Any]\"]\n P = ParamSpec(\"P\")\n T = TypeVar(\"T\")\n TPandas = TypeVar(\"TPandas\", bound=Pandas)\n-TDataFrame = TypeVar(\"TDataFrame\", bound=pd.DataFrame)\n+TFrame = TypeVar(\"TFrame\", bound=pd.DataFrame)\n TSeries = TypeVar(\"TSeries\", bound=\"pd.Series[Any]\")\n \n \n", "test_patch": "diff --git a/tests/test_asdata.py b/tests/test_aspandas.py\nsimilarity index 86%\nrename from tests/test_asdata.py\nrename to tests/test_aspandas.py\nindex d71000e..ea9b088 100644\n--- a/tests/test_asdata.py\n+++ b/tests/test_aspandas.py\n@@ -6,8 +6,8 @@ from typing import cast\n import pandas as pd\n from pandas.testing import assert_frame_equal, assert_series_equal\n from data import Weather, weather, df_weather_true, ser_weather_true\n-from pandas_dataclasses import Spec, asdataframe, asseries\n-from pandas_dataclasses.core.asdata import get_attrs, get_columns, get_data, get_index\n+from pandas_dataclasses import Spec, asframe, asseries\n+from pandas_dataclasses.core.aspandas import get_attrs, get_columns, get_data, get_index\n \n \n # test data\n@@ -15,12 +15,12 @@ spec = Spec.from_dataclass(Weather) @ weather\n \n \n # test functions\n-def test_asseries() -> None:\n- assert_series_equal(asseries(weather), ser_weather_true)\n+def test_asframe() -> None:\n+ assert_frame_equal(asframe(weather), df_weather_true)\n \n \n-def test_asdataframe() -> None:\n- assert_frame_equal(asdataframe(weather), df_weather_true)\n+def test_asseries() -> None:\n+ assert_series_equal(asseries(weather), ser_weather_true)\n \n \n def test_get_attrs() -> None:\ndiff --git a/tests/test_mixins.py b/tests/test_mixins.py\nindex 7aed087..a6e39da 100644\n--- a/tests/test_mixins.py\n+++ b/tests/test_mixins.py\n@@ -7,7 +7,7 @@ from typing import Any\n import pandas as pd\n from pandas.testing import assert_frame_equal, assert_series_equal\n from data import Weather, weather, df_weather_true, ser_weather_true\n-from pandas_dataclasses import As, AsDataFrame, AsSeries\n+from pandas_dataclasses import As, AsFrame, AsSeries\n \n \n # test data\n@@ -15,47 +15,47 @@ def factory(*args: Any, **kwargs: Any) -> pd.Series: # type: ignore\n return pd.Series(*args, **kwargs) # type: ignore\n \n \n-class CustomDataFrame(pd.DataFrame):\n+class UserFrame(pd.DataFrame):\n pass\n \n \n-class CustomSeries(pd.Series): # type: ignore\n+class UserSeries(pd.Series): # type: ignore\n pass\n \n \n @dataclass\n-class DataFrameWeather(Weather, AsDataFrame):\n+class Frame(Weather, AsFrame):\n pass\n \n \n @dataclass\n-class CustomDataFrameWeather(Weather, As[CustomDataFrame]):\n+class CustomFrame(Weather, As[UserFrame]):\n pass\n \n \n @dataclass\n-class SeriesWeather(Weather, AsSeries):\n+class Series(Weather, AsSeries):\n pass\n \n \n @dataclass\n-class FactorySeriesWeather(Weather, AsSeries, factory=factory):\n+class CustomSeries(Weather, As[UserSeries]):\n pass\n \n \n @dataclass\n-class CustomSeriesWeather(Weather, As[CustomSeries]):\n+class FactorySeries(Weather, AsSeries, factory=factory):\n pass\n \n \n @dataclass\n-class FloatSeriesWeather(Weather, As[\"pd.Series[float]\"], factory=pd.Series):\n+class FloatSeries(Weather, As[\"pd.Series[float]\"], factory=pd.Series):\n pass\n \n \n # test functions\n-def test_dataframe_weather() -> None:\n- df_weather = DataFrameWeather.new(\n+def test_frame() -> None:\n+ df_weather = Frame.new(\n year=weather.year,\n month=weather.month,\n temp_avg=weather.temp_avg,\n@@ -68,8 +68,8 @@ def test_dataframe_weather() -> None:\n assert_frame_equal(df_weather, df_weather_true)\n \n \n-def test_custom_dataframe_weather() -> None:\n- df_weather = CustomDataFrameWeather.new(\n+def test_custom_frame() -> None:\n+ df_weather = CustomFrame.new(\n year=weather.year,\n month=weather.month,\n temp_avg=weather.temp_avg,\n@@ -78,12 +78,12 @@ def test_custom_dataframe_weather() -> None:\n wind_max=weather.wind_max,\n )\n \n- assert isinstance(df_weather, CustomDataFrame)\n+ assert isinstance(df_weather, UserFrame)\n assert_frame_equal(df_weather, df_weather_true, check_frame_type=False)\n \n \n-def test_series_weather() -> None:\n- ser_weather = SeriesWeather.new(\n+def test_series() -> None:\n+ ser_weather = Series.new(\n year=weather.year,\n month=weather.month,\n temp_avg=weather.temp_avg,\n@@ -96,8 +96,8 @@ def test_series_weather() -> None:\n assert_series_equal(ser_weather, ser_weather_true)\n \n \n-def test_factory_series_weather() -> None:\n- ser_weather = FactorySeriesWeather.new(\n+def test_custom_series() -> None:\n+ ser_weather = CustomSeries.new(\n year=weather.year,\n month=weather.month,\n temp_avg=weather.temp_avg,\n@@ -106,12 +106,12 @@ def test_factory_series_weather() -> None:\n wind_max=weather.wind_max,\n )\n \n- assert isinstance(ser_weather, pd.Series)\n- assert_series_equal(ser_weather, ser_weather_true)\n+ assert isinstance(ser_weather, UserSeries)\n+ assert_series_equal(ser_weather, ser_weather_true, check_series_type=False)\n \n \n-def test_custom_series_weather() -> None:\n- ser_weather = CustomSeriesWeather.new(\n+def test_factory_series() -> None:\n+ ser_weather = FactorySeries.new(\n year=weather.year,\n month=weather.month,\n temp_avg=weather.temp_avg,\n@@ -120,12 +120,12 @@ def test_custom_series_weather() -> None:\n wind_max=weather.wind_max,\n )\n \n- assert isinstance(ser_weather, CustomSeries)\n- assert_series_equal(ser_weather, ser_weather_true, check_series_type=False)\n+ assert isinstance(ser_weather, pd.Series)\n+ assert_series_equal(ser_weather, ser_weather_true)\n \n \n-def test_float_series_weather() -> None:\n- ser_weather = FloatSeriesWeather.new(\n+def test_float_series() -> None:\n+ ser_weather = FloatSeries.new(\n year=weather.year,\n month=weather.month,\n temp_avg=weather.temp_avg,\n", "FAIL_TO_PASS": ["tests/test_aspandas.py::test_asframe", "tests/test_aspandas.py::test_asseries", "tests/test_aspandas.py::test_get_attrs", "tests/test_aspandas.py::test_get_columns", "tests/test_aspandas.py::test_get_data", "tests/test_aspandas.py::test_get_index", "tests/test_mixins.py::test_frame", "tests/test_mixins.py::test_custom_frame", "tests/test_mixins.py::test_series", "tests/test_mixins.py::test_custom_series", "tests/test_mixins.py::test_factory_series", "tests/test_mixins.py::test_float_series"]}, {"instance_id": "astropenguin__pandas-dataclasses-120", "base_commit": "018349844877e1984a527ce664bf11a2f2285413", "gold_patch": "diff --git a/pandas_dataclasses/core/typing.py b/pandas_dataclasses/core/typing.py\nindex a97a6a0..161ce48 100644\n--- a/pandas_dataclasses/core/typing.py\n+++ b/pandas_dataclasses/core/typing.py\n@@ -2,6 +2,7 @@ __all__ = [\"Attr\", \"Column\", \"Data\", \"Index\", \"Other\"]\n \n \n # standard library\n+import types\n from dataclasses import Field\n from enum import Enum, auto\n from itertools import chain\n@@ -149,6 +150,9 @@ def get_dtype(tp: Any) -> Optional[str]:\n if dtype is Any or dtype is type(None):\n return None\n \n+ if is_union_type(dtype):\n+ dtype = get_args(dtype)[0]\n+\n if get_origin(dtype) is Literal:\n dtype = get_args(dtype)[0]\n \n@@ -179,3 +183,12 @@ def get_role(tp: Any, default: Role = Role.OTHER) -> Role:\n return get_annotations(tp)[0] # type: ignore\n except TypeError:\n return default\n+\n+\n+def is_union_type(tp: Any) -> bool:\n+ \"\"\"Check if a type hint is a union type.\"\"\"\n+ if get_origin(tp) is Union:\n+ return True\n+\n+ UnionType = getattr(types, \"UnionType\", None)\n+ return UnionType is not None and isinstance(tp, UnionType)\n", "test_patch": "diff --git a/tests/test_typing.py b/tests/test_typing.py\nindex de6d646..4ef0e43 100644\n--- a/tests/test_typing.py\n+++ b/tests/test_typing.py\n@@ -16,12 +16,14 @@ testdata_dtype = [\n (Data[Any], None),\n (Data[None], None),\n (Data[int], np.dtype(\"i8\")),\n+ (Data[Union[int, None]], np.dtype(\"i8\")),\n (Data[L[\"i8\"]], np.dtype(\"i8\")),\n (Data[L[\"boolean\"]], pd.BooleanDtype()),\n (Data[L[\"category\"]], pd.CategoricalDtype()),\n (Index[Any], None),\n (Index[None], None),\n (Index[int], np.dtype(\"i8\")),\n+ (Index[Union[int, None]], np.dtype(\"i8\")),\n (Index[L[\"i8\"]], np.dtype(\"i8\")),\n (Index[L[\"boolean\"]], pd.BooleanDtype()),\n (Index[L[\"category\"]], pd.CategoricalDtype()),\n", "FAIL_TO_PASS": ["tests/test_typing.py::test_get_dtype[tp3-dtype3]", "tests/test_typing.py::test_get_dtype[tp10-dtype10]"]}], "all_FAIL_TO_PASS": ["tests/test_aspandas.py::test_asframe", "tests/test_aspandas.py::test_asseries", "tests/test_aspandas.py::test_get_attrs", "tests/test_aspandas.py::test_get_columns", "tests/test_aspandas.py::test_get_data", "tests/test_aspandas.py::test_get_index", "tests/test_mixins.py::test_frame", "tests/test_mixins.py::test_custom_frame", "tests/test_mixins.py::test_series", "tests/test_mixins.py::test_custom_series", "tests/test_mixins.py::test_factory_series", "tests/test_mixins.py::test_float_series", "tests/test_typing.py::test_get_dtype[tp3-dtype3]", "tests/test_typing.py::test_get_dtype[tp10-dtype10]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aio-libs__yarl-959_x2", "level": 2, "source": "swerebench", "repo": "aio-libs/yarl", "image": "swerebench/sweb.eval.x86_64.aio-libs_1776_yarl-959:latest", "base_commit": "e8cc8abbf0fa76bda0533b0440204b5b125f56bf", "num_bugs": 2, "bugs": [{"instance_id": "aio-libs__yarl-959", "base_commit": "e8cc8abbf0fa76bda0533b0440204b5b125f56bf", "gold_patch": "diff --git a/CHANGES/883.bugfix b/CHANGES/883.bugfix\nnew file mode 100644\nindex 0000000..9864377\n--- /dev/null\n+++ b/CHANGES/883.bugfix\n@@ -0,0 +1,4 @@\n+Started raising :py:exc:`TypeError` when a string value is passed into\n+:py:meth:`~yarl.URL.build` as the ``port`` argument -- by :user:`commonism`.\n+\n+Previously the empty string as port would create malformed URLs when rendered as string representations.\ndiff --git a/yarl/_url.py b/yarl/_url.py\nindex c8f2acb..d5202db 100644\n--- a/yarl/_url.py\n+++ b/yarl/_url.py\n@@ -233,6 +233,8 @@ class URL:\n raise ValueError(\n 'Can\\'t mix \"authority\" with \"user\", \"password\", \"host\" or \"port\".'\n )\n+ if not isinstance(port, (int, type(None))):\n+ raise TypeError(\"The port is required to be int.\")\n if port and not host:\n raise ValueError('Can\\'t build URL with \"port\" but without \"host\".')\n if query and query_string:\n", "test_patch": "diff --git a/tests/test_url_build.py b/tests/test_url_build.py\nindex 51969fa..ed07736 100644\n--- a/tests/test_url_build.py\n+++ b/tests/test_url_build.py\n@@ -32,12 +32,28 @@ def test_build_with_scheme_and_host():\n assert u == URL(\"http://127.0.0.1\")\n \n \n-def test_build_with_port():\n- with pytest.raises(ValueError):\n- URL.build(port=8000)\n-\n- u = URL.build(scheme=\"http\", host=\"127.0.0.1\", port=8000)\n- assert str(u) == \"http://127.0.0.1:8000\"\n+@pytest.mark.parametrize(\n+ (\"port\", \"exc\", \"match\"),\n+ [\n+ pytest.param(\n+ 8000,\n+ ValueError,\n+ r\"\"\"(?x)\n+ ^\n+ Can't\\ build\\ URL\\ with\\ \"port\"\\ but\\ without\\ \"host\"\\.\n+ $\n+ \"\"\",\n+ id=\"port-only\",\n+ ),\n+ pytest.param(\n+ \"\", TypeError, r\"^The port is required to be int\\.$\", id=\"port-str\"\n+ ),\n+ ],\n+)\n+def test_build_with_port(port, exc, match):\n+ print(match)\n+ with pytest.raises(exc, match=match):\n+ URL.build(port=port)\n \n \n def test_build_with_user():\n", "FAIL_TO_PASS": ["tests/test_url_build.py::test_build_with_port[port-str]"]}, {"instance_id": "aio-libs__yarl-1026", "base_commit": "433beaf2dc85c9f009e56e78a57bf1bd69ee5155", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex e5dd481..d2e92be 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -105,7 +105,7 @@ Bug fixes\n ---------\n \n - Stopped dropping trailing slashes in :py:meth:`~yarl.URL.joinpath` -- by :user:`gmacon`. (:issue:`862`, :issue:`866`)\n-- Started accepting string subclasses in ``__truediv__()`` operations (``URL / segment``) -- by :user:`mjpieters`. (:issue:`871`, :issue:`884`)\n+- Started accepting string subclasses in :meth:`~yarl.URL.__truediv__` operations (``URL / segment``) -- by :user:`mjpieters`. (:issue:`871`, :issue:`884`)\n - Fixed the human representation of URLs with square brackets in usernames and passwords -- by :user:`mjpieters`. (:issue:`876`, :issue:`882`)\n - Updated type hints to include ``URL.missing_port()``, ``URL.__bytes__()``\n and the ``encoding`` argument to :py:meth:`~yarl.URL.joinpath`\n@@ -174,7 +174,7 @@ Contributor-facing changes\n Bugfixes\n --------\n \n-- Fix regression with ``__truediv__`` and absolute URLs with empty paths causing the raw path to lack the leading ``/``.\n+- Fix regression with :meth:`~yarl.URL.__truediv__` and absolute URLs with empty paths causing the raw path to lack the leading ``/``.\n (`#854 `_)\n \n \n@@ -196,7 +196,7 @@ Features\n --------\n \n - Added ``URL.joinpath(*elements)``, to create a new URL appending multiple path elements. (`#704 `_)\n-- Made ``URL.__truediv__()`` return ``NotImplemented`` if called with an\n+- Made :meth:`URL.__truediv__() ` return ``NotImplemented`` if called with an\n unsupported type \u2014 by :user:`michaeljpeters`.\n (`#832 `_)\n \ndiff --git a/CHANGES/1026.bugfix.rst b/CHANGES/1026.bugfix.rst\nnew file mode 100644\nindex 0000000..eeae24c\n--- /dev/null\n+++ b/CHANGES/1026.bugfix.rst\n@@ -0,0 +1,21 @@\n+Joining URLs with empty segments has been changed\n+to match :rfc:`3986`.\n+\n+Previously empty segments would be removed from path,\n+breaking use-cases such as\n+\n+.. code-block:: python\n+\n+ URL(\"https://web.archive.org/web/\") / \"https://github.com/\"\n+\n+Now :meth:`/ operation ` and :meth:`URL.joinpath() `\n+keep empty segments, but do not introduce new empty segments.\n+e.g.\n+\n+.. code-block:: python\n+\n+ URL(\"https://example.org/\") / \"\"\n+\n+does not introduce an empty segment.\n+\n+-- by :user:`commonism` and :user:`youtux`\ndiff --git a/CHANGES/1026.doc.rst b/CHANGES/1026.doc.rst\nnew file mode 100644\nindex 0000000..daabece\n--- /dev/null\n+++ b/CHANGES/1026.doc.rst\n@@ -0,0 +1,2 @@\n+The pre-existing :meth:`/ magic method `\n+has been documented in the API reference -- by :user:`commonism`.\ndiff --git a/docs/api.rst b/docs/api.rst\nindex 5a4c325..e8e6eb5 100644\n--- a/docs/api.rst\n+++ b/docs/api.rst\n@@ -844,6 +844,20 @@ The path is encoded if needed.\n \n .. versionadded:: 1.9\n \n+.. method:: URL.__truediv__(url)\n+\n+ Shortcut for :meth:`URL.joinpath` with a single element and ``encoded=False``.\n+\n+ .. doctest::\n+\n+ >>> url = URL('http://example.com/path?arg#frag') / 'to'\n+ >>> url\n+ URL('http://example.com/path/to')\n+ >>> url.parts\n+ ('/', 'path', 'to')\n+\n+ .. versionadded:: 0.9\n+\n .. method:: URL.join(url)\n \n Construct a full (\u201cabsolute\u201d) URL by combining a \u201cbase URL\u201d\ndiff --git a/yarl/_url.py b/yarl/_url.py\nindex 9cca27e..84b9519 100644\n--- a/yarl/_url.py\n+++ b/yarl/_url.py\n@@ -713,28 +713,34 @@ class URL:\n \"Path in a URL with authority should start with a slash ('/') if set\"\n )\n \n- def _make_child(self, segments, encoded=False):\n- \"\"\"add segments to self._val.path, accounting for absolute vs relative paths\"\"\"\n- # keep the trailing slash if the last segment ends with /\n- parsed = [\"\"] if segments and segments[-1][-1:] == \"/\" else []\n- for seg in reversed(segments):\n- if not seg:\n- continue\n- if seg[0] == \"/\":\n+ def _make_child(self, paths, encoded=False):\n+ \"\"\"\n+ add paths to self._val.path, accounting for absolute vs relative paths,\n+ keep existing, but do not create new, empty segments\n+ \"\"\"\n+ parsed = []\n+ for idx, path in enumerate(reversed(paths)):\n+ # empty segment of last is not removed\n+ last = idx == 0\n+ if path and path[0] == \"/\":\n raise ValueError(\n- f\"Appending path {seg!r} starting from slash is forbidden\"\n- )\n- seg = seg if encoded else self._PATH_QUOTER(seg)\n- if \"/\" in seg:\n- parsed += (\n- sub for sub in reversed(seg.split(\"/\")) if sub and sub != \".\"\n+ f\"Appending path {path!r} starting from slash is forbidden\"\n )\n- elif seg != \".\":\n- parsed.append(seg)\n+ path = path if encoded else self._PATH_QUOTER(path)\n+ segments = [\n+ segment for segment in reversed(path.split(\"/\")) if segment != \".\"\n+ ]\n+ if not segments:\n+ continue\n+ # remove trailing empty segment for all but the last path\n+ segment_slice_start = int(not last and segments[0] == \"\")\n+ parsed += segments[segment_slice_start:]\n parsed.reverse()\n- old_path = self._val.path\n- if old_path:\n- parsed = [*old_path.rstrip(\"/\").split(\"/\"), *parsed]\n+\n+ if self._val.path and (old_path_segments := self._val.path.split(\"/\")):\n+ old_path_cutoff = -1 if old_path_segments[-1] == \"\" else None\n+ parsed = [*old_path_segments[:old_path_cutoff], *parsed]\n+\n if self.is_absolute():\n parsed = _normalize_path_segments(parsed)\n if parsed and parsed[0] != \"\":\n", "test_patch": "diff --git a/tests/test_url.py b/tests/test_url.py\nindex 725e946..a8f1351 100644\n--- a/tests/test_url.py\n+++ b/tests/test_url.py\n@@ -799,6 +799,9 @@ def test_div_with_dots():\n pytest.param(\n \"/path/\", (\"to\",), \"http://example.com/path/to\", id=\"path-with-slash\"\n ),\n+ pytest.param(\n+ \"/path\", (\"\",), \"http://example.com/path/\", id=\"path-add-trailing-slash\"\n+ ),\n pytest.param(\n \"/path?a=1#frag\",\n (\"to\",),\n@@ -806,6 +809,15 @@ def test_div_with_dots():\n id=\"cleanup-query-and-fragment\",\n ),\n pytest.param(\"\", (\"path/\",), \"http://example.com/path/\", id=\"trailing-slash\"),\n+ pytest.param(\n+ \"\",\n+ (\n+ \"path\",\n+ \"\",\n+ ),\n+ \"http://example.com/path/\",\n+ id=\"trailing-slash-empty-string\",\n+ ),\n pytest.param(\n \"\", (\"path/\", \"to/\"), \"http://example.com/path/to/\", id=\"duplicate-slash\"\n ),\n@@ -827,6 +839,39 @@ def test_joinpath(base, to_join, expected):\n assert str(url.joinpath(*to_join)) == expected\n \n \n+@pytest.mark.parametrize(\n+ \"base,to_join,expected\",\n+ [\n+ pytest.param(\"path\", \"a\", \"path/a\", id=\"default_default\"),\n+ pytest.param(\"path\", \"./a\", \"path/a\", id=\"default_relative\"),\n+ pytest.param(\"path/\", \"a\", \"path/a\", id=\"empty-segment_default\"),\n+ pytest.param(\"path/\", \"./a\", \"path/a\", id=\"empty-segment_relative\"),\n+ pytest.param(\"path\", \".//a\", \"path//a\", id=\"default_empty-segment\"),\n+ pytest.param(\"path/\", \".//a\", \"path//a\", id=\"empty-segment_empty_segment\"),\n+ pytest.param(\"path//\", \"a\", \"path//a\", id=\"empty-segments_default\"),\n+ pytest.param(\"path//\", \"./a\", \"path//a\", id=\"empty-segments_relative\"),\n+ pytest.param(\"path//\", \".//a\", \"path///a\", id=\"empty-segments_empty-segment\"),\n+ pytest.param(\"path\", \"a/\", \"path/a/\", id=\"default_trailing-empty-segment\"),\n+ pytest.param(\"path\", \"a//\", \"path/a//\", id=\"default_trailing-empty-segments\"),\n+ pytest.param(\"path\", \"a//b\", \"path/a//b\", id=\"default_embedded-empty-segment\"),\n+ ],\n+)\n+def test_joinpath_empty_segments(base, to_join, expected):\n+ url = URL(f\"http://example.com/{base}\")\n+ assert (\n+ f\"http://example.com/{expected}\" == str(url.joinpath(to_join))\n+ and str(url / to_join) == f\"http://example.com/{expected}\"\n+ )\n+\n+\n+def test_joinpath_single_empty_segments():\n+ \"\"\"joining standalone empty segments does not create empty segments\"\"\"\n+ a = URL(\"/1//2///3\")\n+ assert a.parts == (\"/\", \"1\", \"\", \"2\", \"\", \"\", \"3\")\n+ b = URL(\"scheme://host\").joinpath(*a.parts[1:])\n+ assert b.path == \"/1/2/3\"\n+\n+\n @pytest.mark.parametrize(\n \"url,to_join,expected\",\n [\n", "FAIL_TO_PASS": ["tests/test_url.py::test_joinpath_empty_segments[empty-segment_empty_segment]", "tests/test_url.py::test_joinpath_empty_segments[default_empty-segment]", "tests/test_url.py::test_joinpath_empty_segments[default_embedded-empty-segment]", "tests/test_url.py::test_joinpath_empty_segments[empty-segments_empty-segment]", "tests/test_url.py::test_joinpath_empty_segments[default_trailing-empty-segments]", "tests/test_url.py::test_joinpath_empty_segments[empty-segments_default]", "tests/test_url.py::test_joinpath_empty_segments[empty-segments_relative]", "tests/test_url.py::test_joinpath[path-add-trailing-slash]", "tests/test_url.py::test_joinpath[trailing-slash-empty-string]"]}], "all_FAIL_TO_PASS": ["tests/test_url_build.py::test_build_with_port[port-str]", "tests/test_url.py::test_joinpath_empty_segments[empty-segment_empty_segment]", "tests/test_url.py::test_joinpath_empty_segments[default_empty-segment]", "tests/test_url.py::test_joinpath_empty_segments[default_embedded-empty-segment]", "tests/test_url.py::test_joinpath_empty_segments[empty-segments_empty-segment]", "tests/test_url.py::test_joinpath_empty_segments[default_trailing-empty-segments]", "tests/test_url.py::test_joinpath_empty_segments[empty-segments_default]", "tests/test_url.py::test_joinpath_empty_segments[empty-segments_relative]", "tests/test_url.py::test_joinpath[path-add-trailing-slash]", "tests/test_url.py::test_joinpath[trailing-slash-empty-string]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "dask__dask-4756_x2", "level": 2, "source": "swerebench", "repo": "dask/dask", "image": "swerebench/sweb.eval.x86_64.dask_1776_dask-4756:latest", "base_commit": "d8a4f3be9a6ec685261ed043a45ecc019055ec0d", "num_bugs": 2, "bugs": [{"instance_id": "dask__dask-4756", "base_commit": "d8a4f3be9a6ec685261ed043a45ecc019055ec0d", "gold_patch": "diff --git a/dask/array/core.py b/dask/array/core.py\nindex 7086c51e0..bdcf53956 100644\n--- a/dask/array/core.py\n+++ b/dask/array/core.py\n@@ -3087,6 +3087,8 @@ def asanyarray(a):\n return a\n elif hasattr(a, 'to_dask_array'):\n return a.to_dask_array()\n+ elif hasattr(a, 'data') and type(a).__module__.startswith('xarray.'):\n+ return asanyarray(a.data)\n elif isinstance(a, (list, tuple)) and any(isinstance(i, Array) for i in a):\n a = stack(a)\n elif not isinstance(getattr(a, 'shape', None), Iterable):\ndiff --git a/dask/array/routines.py b/dask/array/routines.py\nindex 261f7501e..815de0747 100644\n--- a/dask/array/routines.py\n+++ b/dask/array/routines.py\n@@ -609,6 +609,13 @@ def histogram(a, bins=None, range=None, normed=False, weights=None, density=None\n raise ValueError('Input array and weights must have the same '\n 'chunked structure')\n \n+ if normed is not False:\n+ raise ValueError(\n+ \"The normed= keyword argument has been deprecated. \"\n+ \"Please use density instead. \"\n+ \"See the numpy.histogram docstring for more information.\"\n+ )\n+\n if not np.iterable(bins):\n bin_token = bins\n mn, mx = range\n@@ -619,7 +626,7 @@ def histogram(a, bins=None, range=None, normed=False, weights=None, density=None\n bins = np.linspace(mn, mx, bins + 1, endpoint=True)\n else:\n bin_token = bins\n- token = tokenize(a, bin_token, range, normed, weights, density)\n+ token = tokenize(a, bin_token, range, weights, density)\n \n nchunks = len(list(flatten(a.__dask_keys__())))\n chunks = ((1,) * nchunks, (len(bins) - 1,))\n@@ -654,12 +661,7 @@ def histogram(a, bins=None, range=None, normed=False, weights=None, density=None\n else:\n return n, bins\n else:\n- # deprecated, will be removed from Numpy 2.0\n- if normed:\n- db = from_array(np.diff(bins).astype(float), chunks=n.chunks)\n- return n / (n * db).sum(), bins\n- else:\n- return n, bins\n+ return n, bins\n \n \n @wraps(np.cov)\ndiff --git a/dask/dataframe/core.py b/dask/dataframe/core.py\nindex 65b3873d4..4166acfc3 100644\n--- a/dask/dataframe/core.py\n+++ b/dask/dataframe/core.py\n@@ -495,7 +495,8 @@ Dask Name: {name}, {task} tasks\"\"\".format(klass=self.__class__.__name__,\n Arguments and keywords to pass to the function. The partition will\n be the first argument, and these will be passed *after*. Arguments\n and keywords may contain ``Scalar``, ``Delayed`` or regular\n- python objects.\n+ python objects. DataFrame-like args (both dask and pandas) will be\n+ repartitioned to align (if necessary) before applying the function.\n $META\n \n Examples\n@@ -3775,7 +3776,9 @@ def map_partitions(func, *args, **kwargs):\n args, kwargs :\n Arguments and keywords to pass to the function. At least one of the\n args should be a Dask.dataframe. Arguments and keywords may contain\n- ``Scalar``, ``Delayed`` or regular python objects.\n+ ``Scalar``, ``Delayed`` or regular python objects. DataFrame-like args\n+ (both dask and pandas) will be repartitioned to align (if necessary)\n+ before applying the function.\n $META\n \"\"\"\n meta = kwargs.pop('meta', no_default)\ndiff --git a/docs/source/optimize.rst b/docs/source/optimize.rst\nindex 17a303a34..9a5604569 100644\n--- a/docs/source/optimize.rst\n+++ b/docs/source/optimize.rst\n@@ -67,14 +67,18 @@ Here we are counting the occurrence of the words ``'orange``, ``'apple'``, and\n ``'pear'`` in the list of words, formatting an output string reporting the\n results, printing the output, and then returning the output string.\n \n-To perform the computation, we pass the Dask graph and the desired output keys\n-to a scheduler ``get`` function:\n+To perform the computation, we first remove unnecessary components from the\n+graph using the ``cull`` function and then pass the Dask graph and the desired\n+output keys to a scheduler ``get`` function:\n \n .. code-block:: python\n \n >>> from dask.threaded import get\n+ >>> from dask.optimization import cull\n \n >>> outputs = ['print1', 'print2']\n+ >>> dsk2, _ = cull(dsk, outputs) # remove unnecessary tasks from the graph\n+\n >>> results = get(dsk, outputs)\n word list has 2 occurrences of apple, out of 7 words\n word list has 2 occurrences of orange, out of 7 words\n@@ -84,10 +88,12 @@ to a scheduler ``get`` function:\n 'word list has 2 occurrences of apple, out of 7 words')\n \n As can be seen above, the scheduler computed only the requested outputs\n-(``'print3'`` was never computed). This is because the scheduler internally\n-calls ``cull``, which removes the unnecessary tasks from the graph. Even though\n-this is done internally in the scheduler, it can be beneficial to call it at\n-the start of a series of optimizations to reduce the amount of work done in\n+(``'print3'`` was never computed). This is because we called the\n+``dask.optimization.cull`` function, which removes the unnecessary tasks from\n+the graph.\n+\n+Culling is part of the default optimization pass of almost all collections.\n+Often you want to call it somewhat early to reduce the amount of work done in\n later steps:\n \n .. code-block:: python\n", "test_patch": "diff --git a/dask/array/tests/test_routines.py b/dask/array/tests/test_routines.py\nindex b14ef6864..558414c61 100644\n--- a/dask/array/tests/test_routines.py\n+++ b/dask/array/tests/test_routines.py\n@@ -570,10 +570,6 @@ def test_histogram_extra_args_and_shapes():\n \n for v, bins, w in data:\n # density\n- assert_eq(da.histogram(v, bins=bins, normed=True)[0],\n- np.histogram(v, bins=bins, normed=True)[0])\n-\n- # normed\n assert_eq(da.histogram(v, bins=bins, density=True)[0],\n np.histogram(v, bins=bins, density=True)[0])\n \n@@ -585,6 +581,15 @@ def test_histogram_extra_args_and_shapes():\n da.histogram(v, bins=bins, weights=w, density=True)[0])\n \n \n+def test_histogram_normed_deprecation():\n+ x = da.arange(10)\n+ with pytest.raises(ValueError) as info:\n+ da.histogram(x, bins=[1, 2, 3], normed=True)\n+\n+ assert 'density' in str(info.value)\n+ assert 'deprecated' in str(info.value).lower()\n+\n+\n @pytest.mark.parametrize(\"bins, hist_range\", [\n (None, None),\n (10, None),\ndiff --git a/dask/array/tests/test_xarray.py b/dask/array/tests/test_xarray.py\nnew file mode 100644\nindex 000000000..43ea55b7f\n--- /dev/null\n+++ b/dask/array/tests/test_xarray.py\n@@ -0,0 +1,12 @@\n+import pytest\n+\n+import dask.array as da\n+from ..utils import assert_eq\n+\n+xr = pytest.importorskip('xarray')\n+\n+\n+def test_xarray():\n+ y = da.mean(xr.DataArray([1, 2, 3.0]))\n+\n+ assert_eq(y, y)\n", "FAIL_TO_PASS": ["dask/array/tests/test_routines.py::test_histogram_normed_deprecation"]}, {"instance_id": "dask__dask-4831", "base_commit": "01fe81fe8ee020acdd6296a72b33e81dfd4ed4b6", "gold_patch": "diff --git a/dask/array/core.py b/dask/array/core.py\nindex f9fa56a15..40c6bc0a6 100644\n--- a/dask/array/core.py\n+++ b/dask/array/core.py\n@@ -536,7 +536,7 @@ def map_blocks(func, *args, **kwargs):\n chunks2 = []\n for i, (c, nb) in enumerate(zip(chunks, out.numblocks)):\n if isinstance(c, tuple):\n- # We only check cases where numblocks > 1. Becuase of\n+ # We only check cases where numblocks > 1. Because of\n # broadcasting, we can't (easily) validate the chunks\n # when the number of blocks is 1.\n # See https://github.com/dask/dask/issues/4299 for more.\n@@ -555,16 +555,19 @@ def map_blocks(func, *args, **kwargs):\n num_chunks = {}\n shapes = {}\n \n- for i, arg in enumerate(args):\n- if isinstance(arg, Array):\n- starts[i] = [np.cumsum((0,) + c) for c in arg.chunks]\n+ for i, (arg, in_ind) in enumerate(argpairs):\n+ if in_ind is not None:\n shapes[i] = arg.shape\n- num_chunks[i] = arg.numblocks\n- for k, v in kwargs.items():\n- if isinstance(v, Array):\n- starts[k] = [np.cumsum((0,) + c) for c in v.chunks]\n- shapes[k] = arg.shape\n- num_chunks[i] = arg.numblocks\n+ if drop_axis:\n+ # We concatenate along dropped axes, so we need to treat them\n+ # as if there is only a single chunk.\n+ starts[i] = [(np.cumsum((0,) + arg.chunks[j])\n+ if ind in out_ind else np.array([0, arg.shape[j]]))\n+ for j, ind in enumerate(in_ind)]\n+ num_chunks[i] = tuple(len(s) - 1 for s in starts[i])\n+ else:\n+ starts[i] = [np.cumsum((0,) + c) for c in arg.chunks]\n+ num_chunks[i] = arg.numblocks\n out_starts = [np.cumsum((0,) + c) for c in out.chunks]\n \n for k, v in dsk.items():\n@@ -572,21 +575,16 @@ def map_blocks(func, *args, **kwargs):\n v = v[0]\n [(key, task)] = v.dsk.items() # unpack subgraph callable\n \n- if new_axis:\n- # anything using the keys in dsk is incorrect, as the\n- # original array doesn't have values for `new_axis`.\n- old_k = tuple(x for i, x in enumerate(k[1:]) if i not in new_axis)\n- else:\n- old_k = k[1:]\n-\n+ # Get position of chunk, indexed by axis labels\n+ location = {out_ind[i]: loc for i, loc in enumerate(k[1:])}\n info = {}\n for i, shape in shapes.items():\n # Compute chunk key in the array, taking broadcasting into\n # account. We don't directly know which dimensions are\n # broadcast, but any dimension with only one chunk can be\n # treated as broadcast.\n- arr_k = old_k[-len(shape):]\n- arr_k = tuple(j if num_chunks[i][ij] > 1 else 0 for ij, j in enumerate(arr_k))\n+ arr_k = tuple(location.get(ind, 0) if num_chunks[i][j] > 1 else 0\n+ for j, ind in enumerate(argpairs[i][1]))\n info[i] = {'shape': shape,\n 'num-chunks': num_chunks[i],\n 'array-location': [(starts[i][ij][j], starts[i][ij][j + 1])\ndiff --git a/docs/source/setup.rst b/docs/source/setup.rst\nindex 60d71f3e3..818a46594 100644\n--- a/docs/source/setup.rst\n+++ b/docs/source/setup.rst\n@@ -84,3 +84,4 @@ how to set up Dask on a variety of local and distributed hardware.\n setup/cloud.rst\n setup/adaptive.rst\n setup/docker.rst\n+ setup/custom-startup.rst\ndiff --git a/docs/source/setup/custom-startup.rst b/docs/source/setup/custom-startup.rst\nnew file mode 100644\nindex 000000000..eebe92efb\n--- /dev/null\n+++ b/docs/source/setup/custom-startup.rst\n@@ -0,0 +1,73 @@\n+Custom Initialization\n+=====================\n+\n+Often we want to run custom code when we start up or tear down a scheduler or\n+worker. We might do this manually with functions like ``Client.run`` or\n+``Client.run_on_scheduler``, but this is error prone and difficult to automate.\n+\n+To resolve this, Dask includes a few mechanisms to run arbitrary code around\n+the lifecycle of a Scheduler or Worker.\n+\n+Preload Scripts\n+---------------\n+\n+Both ``dask-scheduler`` and ``dask-worker`` support a ``--preload`` option that\n+allows custom initialization of each scheduler/worker respectively. A module or\n+Python file passed as a ``--preload`` value is guaranteed to be imported before\n+establishing any connection. A ``dask_setup(service)`` function is called if\n+found, with a ``Scheduler`` or ``Worker`` instance as the argument. As the\n+service stops, ``dask_teardown(service)`` is called if present.\n+\n+To support additional configuration, a single ``--preload`` module may register\n+additional command-line arguments by exposing ``dask_setup`` as a Click_\n+command. This command will be used to parse additional arguments provided to\n+``dask-worker`` or ``dask-scheduler`` and will be called before service\n+initialization.\n+\n+.. _Click: http://click.pocoo.org/\n+\n+\n+As an example, consider the following file that creates a\n+:doc:`scheduler plugin ` and registers it with the scheduler\n+\n+.. code-block:: python\n+\n+ # scheduler-setup.py\n+ import click\n+\n+ from distributed.diagnostics.plugin import SchedulerPlugin\n+\n+ class MyPlugin(SchedulerPlugin):\n+ def __init__(self, print_count):\n+ self.print_count = print_count\n+ SchedulerPlugin.__init__(self)\n+\n+ def add_worker(self, scheduler=None, worker=None, **kwargs):\n+ print(\"Added a new worker at:\", worker)\n+ if self.print_count and scheduler is not None:\n+ print(\"Total workers:\", len(scheduler.workers))\n+\n+ @click.command()\n+ @click.option(\"--print-count/--no-print-count\", default=False)\n+ def dask_setup(scheduler, print_count):\n+ plugin = MyPlugin(print_count)\n+ scheduler.add_plugin(plugin)\n+\n+We can then run this preload script by referring to its filename (or module name\n+if it is on the path) when we start the scheduler::\n+\n+ dask-scheduler --preload scheduler-setup.py --print-count\n+\n+\n+Worker Lifecycle Plugins\n+------------------------\n+\n+You can also create a class with setup and teardown methods, and register that\n+class with the scheduler to give to every worker.\n+\n+.. currentmodule:: distributed\n+\n+.. autosummary::\n+ Client.register_worker_plugin\n+\n+.. automethod:: Client.register_worker_plugin\n", "test_patch": "diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py\nindex b4b5cc30d..2da84ff96 100644\n--- a/dask/array/tests/test_array_core.py\n+++ b/dask/array/tests/test_array_core.py\n@@ -1115,7 +1115,7 @@ def test_map_blocks_block_info():\n assert_eq(z, x + x + 1 + 100)\n \n \n-def test_map_blocks_block_info_with_axis():\n+def test_map_blocks_block_info_with_new_axis():\n # https://github.com/dask/dask/issues/4298\n values = da.from_array(np.array(['a', 'a', 'b', 'c']), 2)\n \n@@ -1145,6 +1145,40 @@ def test_map_blocks_block_info_with_axis():\n assert_eq(z, np.ones((4, 3), dtype='f8'))\n \n \n+def test_map_blocks_block_info_with_drop_axis():\n+ # https://github.com/dask/dask/issues/4584\n+ values = da.from_array(np.array([[1, 2, 4],\n+ [8, 16, 32],\n+ [64, 128, 256],\n+ [1024, 2048, 4096]], dtype='u4'), (2, 1))\n+\n+ def func(x, block_info=None):\n+ assert set(block_info.keys()) == {0, None}\n+ assert block_info[0]['shape'] == (4, 3)\n+ # drop_axis concatenates along the dropped dimension, hence not (2, 3)\n+ assert block_info[0]['num-chunks'] == (2, 1)\n+ assert block_info[None]['shape'] == (4,)\n+ assert block_info[None]['num-chunks'] == (2,)\n+ assert block_info[None]['chunk-shape'] == (2,)\n+ assert block_info[None]['dtype'] == np.dtype('u4')\n+\n+ assert block_info[0]['chunk-location'] in {(0, 0), (1, 0)}\n+\n+ if block_info[0]['chunk-location'] == (0, 0):\n+ assert block_info[0]['array-location'] == [(0, 2), (0, 3)]\n+ assert block_info[None]['chunk-location'] == (0,)\n+ assert block_info[None]['array-location'] == [(0, 2)]\n+ elif block_info[0]['chunk-location'] == (1, 0):\n+ assert block_info[0]['array-location'] == [(2, 4), (0, 3)]\n+ assert block_info[None]['chunk-location'] == (1,)\n+ assert block_info[None]['array-location'] == [(2, 4)]\n+\n+ return np.sum(x, axis=1, dtype='u4')\n+\n+ z = values.map_blocks(func, drop_axis=1, dtype='u4')\n+ assert_eq(z, np.array([7, 56, 448, 7168], dtype='u4'))\n+\n+\n def test_map_blocks_block_info_with_broadcast():\n expected0 = [\n {'shape': (3, 4), 'num-chunks': (1, 2), 'array-location': [(0, 3), (0, 2)], 'chunk-location': (0, 0)},\n", "FAIL_TO_PASS": ["dask/array/tests/test_array_core.py::test_map_blocks_block_info_with_drop_axis"]}], "all_FAIL_TO_PASS": ["dask/array/tests/test_routines.py::test_histogram_normed_deprecation", "dask/array/tests/test_array_core.py::test_map_blocks_block_info_with_drop_axis"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jpadilla__pyjwt-644_x2", "level": 2, "source": "swerebench", "repo": "jpadilla/pyjwt", "image": "swerebench/sweb.eval.x86_64.jpadilla_1776_pyjwt-644:latest", "base_commit": "8de44287752f9d2c0112bb3062389462d56ead86", "num_bugs": 2, "bugs": [{"instance_id": "jpadilla__pyjwt-644", "base_commit": "8de44287752f9d2c0112bb3062389462d56ead86", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex b049e9e..f122fe7 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -15,6 +15,7 @@ Fixed\n \n - Prefer `headers[\"alg\"]` to `algorithm` in `jwt.encode()`. `#673 `__\n - Fix aud validation to support {'aud': null} case. `#670 `__\n+- Make `typ` optional in JWT to be compliant with RFC7519. `#644 `__\n \n Added\n ~~~~~\ndiff --git a/docs/installation.rst b/docs/installation.rst\nindex 6da2ccd..925da97 100644\n--- a/docs/installation.rst\n+++ b/docs/installation.rst\n@@ -7,6 +7,9 @@ You can install ``PyJWT`` with ``pip``:\n \n $ pip install pyjwt\n \n+\n+.. _installation_cryptography\n+\n Cryptographic Dependencies (Optional)\n -------------------------------------\n \ndiff --git a/docs/usage.rst b/docs/usage.rst\nindex c5372af..2eacb96 100644\n--- a/docs/usage.rst\n+++ b/docs/usage.rst\n@@ -17,6 +17,8 @@ Encoding & Decoding Tokens with HS256\n Encoding & Decoding Tokens with RS256 (RSA)\n -------------------------------------------\n \n+RSA encoding and decoding require the ``cryptography`` module. See :ref:`installation_cryptography`.\n+\n .. code-block:: pycon\n \n >>> import jwt\ndiff --git a/jwt/api_jws.py b/jwt/api_jws.py\nindex 6cefb2c..3a16294 100644\n--- a/jwt/api_jws.py\n+++ b/jwt/api_jws.py\n@@ -99,6 +99,8 @@ class PyJWS:\n if headers:\n self._validate_headers(headers)\n header.update(headers)\n+ if not header[\"typ\"]:\n+ del header[\"typ\"]\n \n json_header = json.dumps(\n header, separators=(\",\", \":\"), cls=json_encoder\n", "test_patch": "diff --git a/tests/test_api_jws.py b/tests/test_api_jws.py\nindex fbeda02..07d1511 100644\n--- a/tests/test_api_jws.py\n+++ b/tests/test_api_jws.py\n@@ -650,6 +650,65 @@ class TestJWS:\n assert \"testheader\" in header_obj\n assert header_obj[\"testheader\"] == headers[\"testheader\"]\n \n+ def test_encode_with_typ(self, jws):\n+ payload = \"\"\"\n+ {\n+ \"iss\": \"https://scim.example.com\",\n+ \"iat\": 1458496404,\n+ \"jti\": \"4d3559ec67504aaba65d40b0363faad8\",\n+ \"aud\": [\n+ \"https://scim.example.com/Feeds/98d52461fa5bbc879593b7754\",\n+ \"https://scim.example.com/Feeds/5d7604516b1d08641d7676ee7\"\n+ ],\n+ \"events\": {\n+ \"urn:ietf:params:scim:event:create\": {\n+ \"ref\":\n+ \"https://scim.example.com/Users/44f6142df96bd6ab61e7521d9\",\n+ \"attributes\": [\"id\", \"name\", \"userName\", \"password\", \"emails\"]\n+ }\n+ }\n+ }\n+ \"\"\"\n+ token = jws.encode(\n+ payload.encode(\"utf-8\"), \"secret\", headers={\"typ\": \"secevent+jwt\"}\n+ )\n+\n+ header = token[0 : token.index(\".\")].encode()\n+ header = base64url_decode(header)\n+ header_obj = json.loads(header)\n+\n+ assert \"typ\" in header_obj\n+ assert header_obj[\"typ\"] == \"secevent+jwt\"\n+\n+ def test_encode_with_typ_empty_string(self, jws, payload):\n+ token = jws.encode(payload, \"secret\", headers={\"typ\": \"\"})\n+\n+ header = token[0 : token.index(\".\")].encode()\n+ header = base64url_decode(header)\n+ header_obj = json.loads(header)\n+\n+ assert \"typ\" not in header_obj\n+\n+ def test_encode_with_typ_none(self, jws, payload):\n+ token = jws.encode(payload, \"secret\", headers={\"typ\": None})\n+\n+ header = token[0 : token.index(\".\")].encode()\n+ header = base64url_decode(header)\n+ header_obj = json.loads(header)\n+\n+ assert \"typ\" not in header_obj\n+\n+ def test_encode_with_typ_without_keywords(self, jws, payload):\n+ headers = {\"foo\": \"bar\"}\n+ token = jws.encode(payload, \"secret\", \"HS256\", headers, None)\n+\n+ header = token[0 : token.index(\".\")].encode()\n+ header = base64url_decode(header)\n+ header_obj = json.loads(header)\n+\n+ assert \"foo\" in header_obj\n+ assert header_obj[\"foo\"] == \"bar\"\n+\n def test_encode_fails_on_invalid_kid_types(self, jws, payload):\n with pytest.raises(InvalidTokenError) as exc:\n jws.encode(payload, \"secret\", headers={\"kid\": 123})\ndiff --git a/tests/test_api_jwt.py b/tests/test_api_jwt.py\nindex 1faa05f..a6230b3 100644\n--- a/tests/test_api_jwt.py\n+++ b/tests/test_api_jwt.py\n@@ -16,6 +16,7 @@ from jwt.exceptions import (\n InvalidIssuerError,\n MissingRequiredClaimError,\n )\n+from jwt.utils import base64url_decode\n \n from .utils import crypto_required, key_path, utc_timestamp\n \n@@ -167,6 +168,32 @@ class TestJWT:\n lambda: jwt.encode(t, \"secret\", algorithms=[\"HS256\"]),\n )\n \n+ def test_encode_with_typ(self, jwt):\n+ payload = {\n+ \"iss\": \"https://scim.example.com\",\n+ \"iat\": 1458496404,\n+ \"jti\": \"4d3559ec67504aaba65d40b0363faad8\",\n+ \"aud\": [\n+ \"https://scim.example.com/Feeds/98d52461fa5bbc879593b7754\",\n+ \"https://scim.example.com/Feeds/5d7604516b1d08641d7676ee7\",\n+ ],\n+ \"events\": {\n+ \"urn:ietf:params:scim:event:create\": {\n+ \"ref\": \"https://scim.example.com/Users/44f6142df96bd6ab61e7521d9\",\n+ \"attributes\": [\"id\", \"name\", \"userName\", \"password\", \"emails\"],\n+ }\n+ },\n+ }\n+ token = jwt.encode(\n+ payload, \"secret\", algorithm=\"HS256\", headers={\"typ\": \"secevent+jwt\"}\n+ )\n+ header = token[0 : token.index(\".\")].encode()\n+ header = base64url_decode(header)\n+ header_obj = json.loads(header)\n+\n+ assert \"typ\" in header_obj\n+ assert header_obj[\"typ\"] == \"secevent+jwt\"\n+\n def test_decode_raises_exception_if_exp_is_not_int(self, jwt):\n # >>> jwt.encode({'exp': 'not-an-int'}, 'secret')\n example_jwt = (\n", "FAIL_TO_PASS": ["tests/test_api_jws.py::TestJWS::test_encode_with_typ_empty_string", "tests/test_api_jws.py::TestJWS::test_encode_with_typ_none"]}, {"instance_id": "jpadilla__pyjwt-657", "base_commit": "fdd795ad08f91fb110d1578619506bfb767fdb30", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex f122fe7..1c1c451 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -10,6 +10,8 @@ This project adheres to `Semantic Versioning `__.\n Changed\n ~~~~~~~\n \n+- Remove arbitrary kwalgs. `#657 `__\n+\n Fixed\n ~~~~~\n \ndiff --git a/jwt/api_jws.py b/jwt/api_jws.py\nindex 3a16294..8061c97 100644\n--- a/jwt/api_jws.py\n+++ b/jwt/api_jws.py\n@@ -137,7 +137,6 @@ class PyJWS:\n key: str = \"\",\n algorithms: List[str] = None,\n options: Dict = None,\n- **kwargs,\n ) -> Dict[str, Any]:\n if options is None:\n options = {}\n@@ -166,9 +165,8 @@ class PyJWS:\n key: str = \"\",\n algorithms: List[str] = None,\n options: Dict = None,\n- **kwargs,\n ) -> str:\n- decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)\n+ decoded = self.decode_complete(jwt, key, algorithms, options)\n return decoded[\"payload\"]\n \n def get_unverified_header(self, jwt):\ndiff --git a/jwt/api_jwt.py b/jwt/api_jwt.py\nindex 48a9316..c5fbbc5 100644\n--- a/jwt/api_jwt.py\n+++ b/jwt/api_jwt.py\n@@ -68,7 +68,9 @@ class PyJWT:\n key: str = \"\",\n algorithms: List[str] = None,\n options: Dict = None,\n- **kwargs,\n+ audience: Optional[Union[str, List[str]]] = None,\n+ issuer: Optional[str] = None,\n+ leeway: Union[float, timedelta] = 0,\n ) -> Dict[str, Any]:\n if options is None:\n options = {\"verify_signature\": True}\n@@ -92,7 +94,6 @@ class PyJWT:\n key=key,\n algorithms=algorithms,\n options=options,\n- **kwargs,\n )\n \n try:\n@@ -103,7 +104,7 @@ class PyJWT:\n raise DecodeError(\"Invalid payload string: must be a json object\")\n \n merged_options = {**self.options, **options}\n- self._validate_claims(payload, merged_options, **kwargs)\n+ self._validate_claims(payload, merged_options, audience, issuer, leeway)\n \n decoded[\"payload\"] = payload\n return decoded\n@@ -114,18 +115,20 @@ class PyJWT:\n key: str = \"\",\n algorithms: List[str] = None,\n options: Dict = None,\n- **kwargs,\n+ audience: Optional[Union[str, List[str]]] = None,\n+ issuer: Optional[str] = None,\n+ leeway: Union[float, timedelta] = 0,\n ) -> Dict[str, Any]:\n- decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)\n+ decoded = self.decode_complete(\n+ jwt, key, algorithms, options, audience, issuer, leeway\n+ )\n return decoded[\"payload\"]\n \n- def _validate_claims(\n- self, payload, options, audience=None, issuer=None, leeway=0, **kwargs\n- ):\n+ def _validate_claims(self, payload, options, audience, issuer, leeway):\n if isinstance(leeway, timedelta):\n leeway = leeway.total_seconds()\n \n- if not isinstance(audience, (bytes, str, type(None), Iterable)):\n+ if not isinstance(audience, (str, type(None), Iterable)):\n raise TypeError(\"audience must be a string, iterable, or None\")\n \n self._validate_required_claims(payload, options)\n", "test_patch": "diff --git a/tests/test_api_jwt.py b/tests/test_api_jwt.py\nindex a6230b3..3f274a3 100644\n--- a/tests/test_api_jwt.py\n+++ b/tests/test_api_jwt.py\n@@ -106,6 +106,17 @@ class TestJWT:\n exception = context.value\n assert str(exception) == \"Invalid payload string: must be a json object\"\n \n+ def test_decode_with_unknown_parameter_throws_exception(self, jwt):\n+ secret = \"secret\"\n+ example_jwt = (\n+ b\"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9\"\n+ b\".eyJoZWxsbyI6ICJ3b3JsZCJ9\"\n+ b\".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8\"\n+ )\n+\n+ with pytest.raises(TypeError):\n+ jwt.decode(example_jwt, key=secret, foo=\"bar\", algorithms=[\"HS256\"])\n+\n def test_decode_with_invalid_audience_param_throws_exception(self, jwt):\n secret = \"secret\"\n example_jwt = (\n", "FAIL_TO_PASS": ["tests/test_api_jwt.py::TestJWT::test_decode_with_unknown_parameter_throws_exception"]}], "all_FAIL_TO_PASS": ["tests/test_api_jws.py::TestJWS::test_encode_with_typ_empty_string", "tests/test_api_jws.py::TestJWS::test_encode_with_typ_none", "tests/test_api_jwt.py::TestJWT::test_decode_with_unknown_parameter_throws_exception"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "hhatto__autopep8-464_x2", "level": 2, "source": "swerebench", "repo": "hhatto/autopep8", "image": "swerebench/sweb.eval.x86_64.hhatto_1776_autopep8-464:latest", "base_commit": "40bcf6f126f11f6957f7b2c31d880245843b2242", "num_bugs": 2, "bugs": [{"instance_id": "hhatto__autopep8-464", "base_commit": "40bcf6f126f11f6957f7b2c31d880245843b2242", "gold_patch": "diff --git a/autopep8.py b/autopep8.py\nindex d07f74c..258f30c 100755\n--- a/autopep8.py\n+++ b/autopep8.py\n@@ -1313,14 +1313,15 @@ class FixPEP8(object):\n old = []\n for t in tts:\n if tokenize.COMMENT == t[0] and old:\n- comment_index = old[3][1]\n+ comment_row, comment_index = old[3]\n break\n old = t\n break\n if not operator_position:\n return\n target_operator = target[operator_position[0]:operator_position[1]]\n- if comment_index:\n+\n+ if comment_index and comment_row == 1:\n self.source[line_index] = '{}{}'.format(\n target[:operator_position[0]].rstrip(),\n target[comment_index:])\n@@ -1329,6 +1330,7 @@ class FixPEP8(object):\n target[:operator_position[0]].rstrip(),\n target[operator_position[1]:].lstrip(),\n target[operator_position[1]:])\n+\n next_line = self.source[line_index + 1]\n next_line_indent = 0\n m = re.match(r'\\s*', next_line)\n", "test_patch": "diff --git a/test/test_autopep8.py b/test/test_autopep8.py\nindex d1c6e3a..aa502d1 100755\n--- a/test/test_autopep8.py\n+++ b/test/test_autopep8.py\n@@ -4425,6 +4425,24 @@ b = (1 +\n with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n self.assertEqual(fixed, result)\n \n+ def test_w504_comment_on_first_line(self):\n+ line = 'x = (1 | # test\\n2)\\n'\n+ fixed = 'x = (1 # test\\n| 2)\\n'\n+ with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n+ self.assertEqual(fixed, result)\n+\n+ def test_w504_comment_on_second_line(self):\n+ line = 'x = (1 |\\n2) # test\\n'\n+ fixed = 'x = (1\\n| 2) # test\\n'\n+ with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n+ self.assertEqual(fixed, result)\n+\n+ def test_w504_comment_on_each_lines(self):\n+ line = 'x = (1 |# test\\n2 |# test\\n3) # test\\n'\n+ fixed = 'x = (1# test\\n| 2# test\\n| 3) # test\\n'\n+ with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n+ self.assertEqual(fixed, result)\n+\n def test_w504_with_e265_ignore_option(self):\n line = '(width == 0 +\\n height == 0)\\n'\n with autopep8_context(line, options=['--ignore=E265']) as result:\n", "FAIL_TO_PASS": ["test/test_autopep8.py::SystemTests::test_w504_comment_on_second_line"]}, {"instance_id": "hhatto__autopep8-466", "base_commit": "89886b439f35778ac1edefbc93ad9aa411d889d1", "gold_patch": "diff --git a/autopep8.py b/autopep8.py\nindex 8fc548a..3a55a01 100755\n--- a/autopep8.py\n+++ b/autopep8.py\n@@ -100,6 +100,9 @@ SHORTEN_OPERATOR_GROUPS = frozenset([\n \n DEFAULT_IGNORE = 'E226,E24,W50,W690' # TODO: use pycodestyle.DEFAULT_IGNORE\n DEFAULT_INDENT_SIZE = 4\n+# these fixes conflict with each other, if the `--ignore` setting causes both\n+# to be enabled, disable both of them\n+CONFLICTING_CODES = ('W503', 'W504')\n \n SELECTED_GLOBAL_FIXED_METHOD_CODES = ['W602', ]\n \n@@ -3662,6 +3665,14 @@ def parse_args(arguments, apply_config=False):\n \n if args.ignore:\n args.ignore = _split_comma_separated(args.ignore)\n+ if not all(\n+ any(\n+ conflicting_code.startswith(ignore_code)\n+ for ignore_code in args.ignore\n+ )\n+ for conflicting_code in CONFLICTING_CODES\n+ ):\n+ args.ignore.update(CONFLICTING_CODES)\n elif not args.select:\n if args.aggressive:\n # Enable everything by default if aggressive.\n", "test_patch": "diff --git a/test/test_autopep8.py b/test/test_autopep8.py\nindex 14981e8..a35d318 100755\n--- a/test/test_autopep8.py\n+++ b/test/test_autopep8.py\n@@ -4475,6 +4475,24 @@ if True:\n with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n self.assertEqual(fixed, result)\n \n+ def test_w504_not_applied_by_default_when_modifying_with_ignore(self):\n+ line = \"\"\"\\\n+q = 1\n+\n+\n+\n+\n+def x(y, z):\n+ if (\n+ y and\n+ z\n+ ):\n+ pass\n+\"\"\"\n+ fixed = line.replace('\\n\\n\\n\\n', '\\n\\n')\n+ with autopep8_context(line, options=['--ignore=E265']) as result:\n+ self.assertEqual(fixed, result)\n+\n def test_w601(self):\n line = 'a = {0: 1}\\na.has_key(0)\\n'\n fixed = 'a = {0: 1}\\n0 in a\\n'\n", "FAIL_TO_PASS": ["test/test_autopep8.py::SystemTests::test_w504_not_applied_by_default_when_modifying_with_ignore"]}], "all_FAIL_TO_PASS": ["test/test_autopep8.py::SystemTests::test_w504_comment_on_second_line", "test/test_autopep8.py::SystemTests::test_w504_not_applied_by_default_when_modifying_with_ignore"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "GenericMappingTools__pygmt-574_x2", "level": 2, "source": "swerebench", "repo": "GenericMappingTools/pygmt", "image": "swerebench/sweb.eval.x86_64.genericmappingtools_1776_pygmt-574:latest", "base_commit": "4856d64e441434e395c5b8e7874022052c76f9af", "num_bugs": 2, "bugs": [{"instance_id": "GenericMappingTools__pygmt-574", "base_commit": "4856d64e441434e395c5b8e7874022052c76f9af", "gold_patch": "diff --git a/pygmt/modules.py b/pygmt/modules.py\nindex 73392410..94512ec3 100644\n--- a/pygmt/modules.py\n+++ b/pygmt/modules.py\n@@ -1,6 +1,7 @@\n \"\"\"\n Non-plot GMT modules.\n \"\"\"\n+import numpy as np\n import xarray as xr\n \n from .clib import Session\n@@ -55,7 +56,7 @@ def grdinfo(grid, **kwargs):\n \n @fmt_docstring\n @use_alias(C=\"per_column\", I=\"spacing\", T=\"nearest_multiple\")\n-def info(fname, **kwargs):\n+def info(table, **kwargs):\n \"\"\"\n Get information about data tables.\n \n@@ -74,8 +75,9 @@ def info(fname, **kwargs):\n \n Parameters\n ----------\n- fname : str\n- The file name of the input data table file.\n+ table : pandas.DataFrame or np.ndarray or str\n+ Either a pandas dataframe, a 1D/2D numpy.ndarray or a file name to an\n+ ASCII data table.\n per_column : bool\n Report the min/max values per column in separate columns.\n spacing : str\n@@ -88,14 +90,25 @@ def info(fname, **kwargs):\n Report the min/max of the first (0'th) column to the nearest multiple\n of dz and output this as the string *-Tzmin/zmax/dz*.\n \"\"\"\n- if not isinstance(fname, str):\n- raise GMTInvalidInput(\"'info' only accepts file names.\")\n+ kind = data_kind(table)\n+ with Session() as lib:\n+ if kind == \"file\":\n+ file_context = dummy_context(table)\n+ elif kind == \"matrix\":\n+ _table = np.asanyarray(table)\n+ if table.ndim == 1: # 1D arrays need to be 2D and transposed\n+ _table = np.transpose(np.atleast_2d(_table))\n+ file_context = lib.virtualfile_from_matrix(_table)\n+ else:\n+ raise GMTInvalidInput(f\"Unrecognized data type: {type(table)}\")\n \n- with GMTTempFile() as tmpfile:\n- arg_str = \" \".join([fname, build_arg_string(kwargs), \"->\" + tmpfile.name])\n- with Session() as lib:\n- lib.call_module(\"info\", arg_str)\n- return tmpfile.read()\n+ with GMTTempFile() as tmpfile:\n+ with file_context as fname:\n+ arg_str = \" \".join(\n+ [fname, build_arg_string(kwargs), \"->\" + tmpfile.name]\n+ )\n+ lib.call_module(\"info\", arg_str)\n+ return tmpfile.read()\n \n \n @fmt_docstring\n", "test_patch": "diff --git a/pygmt/tests/test_info.py b/pygmt/tests/test_info.py\nindex 3e9da3ab..b7eadc53 100644\n--- a/pygmt/tests/test_info.py\n+++ b/pygmt/tests/test_info.py\n@@ -4,7 +4,9 @@ Tests for gmtinfo\n import os\n \n import numpy as np\n+import pandas as pd\n import pytest\n+import xarray as xr\n \n from .. import info\n from ..exceptions import GMTInvalidInput\n@@ -14,8 +16,8 @@ POINTS_DATA = os.path.join(TEST_DATA_DIR, \"points.txt\")\n \n \n def test_info():\n- \"Make sure info works\"\n- output = info(fname=POINTS_DATA)\n+ \"Make sure info works on file name inputs\"\n+ output = info(table=POINTS_DATA)\n expected_output = (\n f\"{POINTS_DATA}: N = 20 \"\n \"<11.5309/61.7074> \"\n@@ -25,33 +27,61 @@ def test_info():\n assert output == expected_output\n \n \n+def test_info_dataframe():\n+ \"Make sure info works on pandas.DataFrame inputs\"\n+ table = pd.read_csv(POINTS_DATA, sep=\" \", header=None)\n+ output = info(table=table)\n+ expected_output = (\n+ \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n+ )\n+ assert output == expected_output\n+\n+\n+def test_info_2d_array():\n+ \"Make sure info works on 2D numpy.ndarray inputs\"\n+ table = np.loadtxt(POINTS_DATA)\n+ output = info(table=table)\n+ expected_output = (\n+ \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n+ )\n+ assert output == expected_output\n+\n+\n+def test_info_1d_array():\n+ \"Make sure info works on 1D numpy.ndarray inputs\"\n+ output = info(table=np.arange(20))\n+ expected_output = \": N = 20 <0/19>\\n\"\n+ assert output == expected_output\n+\n+\n def test_info_per_column():\n \"Make sure the per_column option works\"\n- output = info(fname=POINTS_DATA, per_column=True)\n+ output = info(table=POINTS_DATA, per_column=True)\n assert output == \"11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338\\n\"\n \n \n def test_info_spacing():\n \"Make sure the spacing option works\"\n- output = info(fname=POINTS_DATA, spacing=0.1)\n+ output = info(table=POINTS_DATA, spacing=0.1)\n assert output == \"-R11.5/61.8/-3/7.9\\n\"\n \n \n def test_info_per_column_spacing():\n \"Make sure the per_column and spacing options work together\"\n- output = info(fname=POINTS_DATA, per_column=True, spacing=0.1)\n+ output = info(table=POINTS_DATA, per_column=True, spacing=0.1)\n assert output == \"11.5 61.8 -3 7.9 0.1412 0.9338\\n\"\n \n \n def test_info_nearest_multiple():\n \"Make sure the nearest_multiple option works\"\n- output = info(fname=POINTS_DATA, nearest_multiple=0.1)\n+ output = info(table=POINTS_DATA, nearest_multiple=0.1)\n assert output == \"-T11.5/61.8/0.1\\n\"\n \n \n def test_info_fails():\n- \"Make sure info raises an exception if not given a file name\"\n- with pytest.raises(GMTInvalidInput):\n- info(fname=21)\n+ \"\"\"\n+ Make sure info raises an exception if not given either a file name, pandas\n+ DataFrame, or numpy ndarray\n+ \"\"\"\n with pytest.raises(GMTInvalidInput):\n- info(fname=np.arange(20))\n+ info(table=xr.DataArray(21))\n", "FAIL_TO_PASS": ["pygmt/tests/test_info.py::test_info", "pygmt/tests/test_info.py::test_info_dataframe", "pygmt/tests/test_info.py::test_info_2d_array", "pygmt/tests/test_info.py::test_info_1d_array", "pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple", "pygmt/tests/test_info.py::test_info_fails"]}, {"instance_id": "GenericMappingTools__pygmt-575", "base_commit": "89857c32c7e61c57fb1f03993cfb090c76366783", "gold_patch": "diff --git a/pygmt/modules.py b/pygmt/modules.py\nindex 94512ec3..1cacf67d 100644\n--- a/pygmt/modules.py\n+++ b/pygmt/modules.py\n@@ -60,14 +60,17 @@ def info(table, **kwargs):\n \"\"\"\n Get information about data tables.\n \n- Reads from files and finds the extreme values in each of the columns.\n- It recognizes NaNs and will print warnings if the number of columns vary\n- from record to record. As an option, it will find the extent of the first\n- n columns rounded up and down to the nearest multiple of the supplied\n- increments. By default, this output will be in the form *-Rw/e/s/n*,\n- or the output will be in column form for as many columns as there are\n- increments provided. The *nearest_multiple* option will provide a\n- *-Tzmin/zmax/dz* string for makecpt.\n+ Reads from files and finds the extreme values in each of the columns\n+ reported as min/max pairs. It recognizes NaNs and will print warnings if\n+ the number of columns vary from record to record. As an option, it will\n+ find the extent of the first two columns rounded up and down to the nearest\n+ multiple of the supplied increments given by *spacing*. Such output will be\n+ in a numpy.ndarray form ``[w, e, s, n]``, which can be used directly as the\n+ *region* argument for other modules (hence only dx and dy are needed). If\n+ the *per_column* option is combined with *spacing*, then the numpy.ndarray\n+ output will be rounded up/down for as many columns as there are increments\n+ provided in *spacing*. A similar option *nearest_multiple* option will\n+ provide a numpy.ndarray in the form of ``[zmin, zmax, dz]`` for makecpt.\n \n Full option list at :gmt-docs:`gmtinfo.html`\n \n@@ -83,12 +86,21 @@ def info(table, **kwargs):\n spacing : str\n ``'[b|p|f|s]dx[/dy[/dz...]]'``.\n Report the min/max of the first n columns to the nearest multiple of\n- the provided increments and output results in the form *-Rw/e/s/n*\n- (unless *per_column* is set).\n+ the provided increments and output results in the form\n+ ``[w, e, s, n]``.\n nearest_multiple : str\n ``'dz[+ccol]'``\n Report the min/max of the first (0'th) column to the nearest multiple\n- of dz and output this as the string *-Tzmin/zmax/dz*.\n+ of dz and output this in the form ``[zmin, zmax, dz]``.\n+\n+ Returns\n+ -------\n+ output : np.ndarray or str\n+ Return type depends on whether any of the 'per_column', 'spacing', or\n+ 'nearest_multiple' parameters are set.\n+\n+ - np.ndarray if either of the above parameters are used.\n+ - str if none of the above parameters are used.\n \"\"\"\n kind = data_kind(table)\n with Session() as lib:\n@@ -108,7 +120,16 @@ def info(table, **kwargs):\n [fname, build_arg_string(kwargs), \"->\" + tmpfile.name]\n )\n lib.call_module(\"info\", arg_str)\n- return tmpfile.read()\n+ result = tmpfile.read()\n+\n+ if any(arg in kwargs for arg in [\"C\", \"I\", \"T\"]):\n+ # Converts certain output types into a numpy array\n+ # instead of a raw string that is less useful.\n+ if result.startswith((\"-R\", \"-T\")): # e.g. -R0/1/2/3 or -T0/9/1\n+ result = result[2:].replace(\"/\", \" \")\n+ result = np.loadtxt(result.splitlines())\n+\n+ return result\n \n \n @fmt_docstring\n", "test_patch": "diff --git a/pygmt/tests/test_info.py b/pygmt/tests/test_info.py\nindex b7eadc53..142b56dc 100644\n--- a/pygmt/tests/test_info.py\n+++ b/pygmt/tests/test_info.py\n@@ -4,6 +4,7 @@ Tests for gmtinfo\n import os\n \n import numpy as np\n+import numpy.testing as npt\n import pandas as pd\n import pytest\n import xarray as xr\n@@ -57,25 +58,42 @@ def test_info_1d_array():\n def test_info_per_column():\n \"Make sure the per_column option works\"\n output = info(table=POINTS_DATA, per_column=True)\n- assert output == \"11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338\\n\"\n+ npt.assert_allclose(\n+ actual=output, desired=[11.5309, 61.7074, -2.9289, 7.8648, 0.1412, 0.9338]\n+ )\n \n \n def test_info_spacing():\n \"Make sure the spacing option works\"\n output = info(table=POINTS_DATA, spacing=0.1)\n- assert output == \"-R11.5/61.8/-3/7.9\\n\"\n+ npt.assert_allclose(actual=output, desired=[11.5, 61.8, -3, 7.9])\n+\n+\n+def test_info_spacing_bounding_box():\n+ \"Make sure the spacing option for writing a bounding box works\"\n+ output = info(table=POINTS_DATA, spacing=\"b\")\n+ npt.assert_allclose(\n+ actual=output,\n+ desired=[\n+ [11.5309, -2.9289],\n+ [61.7074, -2.9289],\n+ [61.7074, 7.8648],\n+ [11.5309, 7.8648],\n+ [11.5309, -2.9289],\n+ ],\n+ )\n \n \n def test_info_per_column_spacing():\n \"Make sure the per_column and spacing options work together\"\n output = info(table=POINTS_DATA, per_column=True, spacing=0.1)\n- assert output == \"11.5 61.8 -3 7.9 0.1412 0.9338\\n\"\n+ npt.assert_allclose(actual=output, desired=[11.5, 61.8, -3, 7.9, 0.1412, 0.9338])\n \n \n def test_info_nearest_multiple():\n \"Make sure the nearest_multiple option works\"\n output = info(table=POINTS_DATA, nearest_multiple=0.1)\n- assert output == \"-T11.5/61.8/0.1\\n\"\n+ npt.assert_allclose(actual=output, desired=[11.5, 61.8, 0.1])\n \n \n def test_info_fails():\n", "FAIL_TO_PASS": ["pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_spacing_bounding_box", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple"]}], "all_FAIL_TO_PASS": ["pygmt/tests/test_info.py::test_info", "pygmt/tests/test_info.py::test_info_dataframe", "pygmt/tests/test_info.py::test_info_2d_array", "pygmt/tests/test_info.py::test_info_1d_array", "pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple", "pygmt/tests/test_info.py::test_info_fails", "pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_spacing_bounding_box", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "childsish__dynamic-yaml-6_x2", "level": 2, "source": "swerebench", "repo": "childsish/dynamic-yaml", "image": "swerebench/sweb.eval.x86_64.childsish_1776_dynamic-yaml-6:latest", "base_commit": "e28c8cfce18459f28b3f6bfd65d4c5ba3f230e71", "num_bugs": 2, "bugs": [{"instance_id": "childsish__dynamic-yaml-6", "base_commit": "e28c8cfce18459f28b3f6bfd65d4c5ba3f230e71", "gold_patch": "diff --git a/dynamic_yaml/__init__.py b/dynamic_yaml/__init__.py\nindex 8e77e89..1b505aa 100644\n--- a/dynamic_yaml/__init__.py\n+++ b/dynamic_yaml/__init__.py\n@@ -27,5 +27,5 @@ add_wrappers(DynamicYamlLoader)\n \n def load(stream, loader=DynamicYamlLoader, recursive=False):\n result = yaml.load(stream, Loader=loader)\n- result.set_as_root(recursive=recursive)\n+ result._set_as_root(recursive=recursive)\n return result\ndiff --git a/dynamic_yaml/yaml_wrappers.py b/dynamic_yaml/yaml_wrappers.py\nindex 4ed1322..14c5ecc 100644\n--- a/dynamic_yaml/yaml_wrappers.py\n+++ b/dynamic_yaml/yaml_wrappers.py\n@@ -1,81 +1,85 @@\n import re\n \n-from collections import Sequence, Mapping\n+from collections.abc import Collection, Mapping, MutableMapping, MutableSequence, Sequence\n \n \n-class YamlDict(dict):\n- def __init__(self, *args, **kwargs):\n- super().__init__(*args, **kwargs)\n- super().__setattr__('_root', self)\n+class DynamicYamlObject(Collection):\n+ def __init__(self):\n+ super().__setattr__('_collection', {})\n+ super().__setattr__('_root', {})\n super().__setattr__('_recursive', False)\n super().__setattr__('_regx', re.compile('.*{.*}.*'))\n \n- def __getattr__(self, key):\n- if key in self:\n- return self[key]\n- return super().__getattribute__(key)\n+ def __iter__(self):\n+ yield from super().__getattribute__('_collection')\n \n- def __setattr__(self, key, value):\n- self[key] = value\n+ def __contains__(self, value: object) -> bool:\n+ return value in super().__getattribute__('_collection')\n+\n+ def __len__(self) -> int:\n+ return len(super().__getattribute__('_collection'))\n \n def __getitem__(self, key):\n- v = super().__getitem__(key)\n- if isinstance(v, str):\n- while self._regx.match(v) is not None:\n- v = v.format(**super().__getattribute__('_root'))\n- if not self._recursive:\n+ value = super().__getattribute__('_collection')[key]\n+ if isinstance(value, str):\n+ while super().__getattribute__('_regx').match(value) is not None:\n+ value = value.format(**super().__getattribute__('_root')._collection)\n+ if not super().__getattribute__('_recursive'):\n break\n- return v\n+ return value\n \n def __setitem__(self, key, value):\n if isinstance(value, Mapping) and not isinstance(value, YamlDict):\n value = YamlDict(value)\n- value.set_as_root(super().__getattribute__('_root'))\n+ value._set_as_root(super().__getattribute__('_root'))\n elif isinstance(value, Sequence) and not isinstance(value, (str, YamlList)):\n value = YamlList(value)\n- value.set_as_root(super().__getattribute__('_root'))\n- super().__setitem__(key, value)\n+ value._set_as_root(super().__getattribute__('_root'))\n+ super().__getattribute__('_collection')[key] = value\n+\n+ def __delitem__(self, key):\n+ del super().__getattribute__('_collection')[key]\n \n- def set_as_root(self, root=None, *, recursive=False):\n+ def _values(self):\n+ raise NotImplementedError('This method must be implemented in the child class')\n+\n+ def _set_as_root(self, root=None, *, recursive=False):\n super().__setattr__('_recursive', recursive)\n if root is not None:\n super().__setattr__('_root', root)\n- for k, v in self.items():\n- if hasattr(v, 'set_as_root'):\n- v.set_as_root(super().__getattribute__('_root'), recursive=recursive)\n+ for value in self._values():\n+ if isinstance(value, DynamicYamlObject):\n+ value._set_as_root(super().__getattribute__('_root'), recursive=recursive)\n+\n+\n+class YamlDict(DynamicYamlObject, MutableMapping):\n+ def __init__(self, *args, **kwargs):\n+ super().__init__()\n+ super().__setattr__('_collection', dict(*args, **kwargs))\n+ super().__setattr__('_root', self)\n \n+ def __getattr__(self, key):\n+ if key in self:\n+ return self[key]\n+ return super().__getattribute__(key)\n \n-class YamlList(list):\n+ def __setattr__(self, key, value):\n+ self[key] = value\n+\n+ def _values(self):\n+ return super().__getattribute__('_collection').values()\n+\n+\n+class YamlList(DynamicYamlObject, MutableSequence):\n ROOT_NAME = 'root'\n \n def __init__(self, *args, **kwargs):\n- super().__init__(*args, **kwargs)\n- super().__setattr__('_root', {YamlList.ROOT_NAME: self})\n- super().__setattr__('_recursive', False)\n- super().__setattr__('_regx', re.compile('.*{.*}.*'))\n-\n- def __getitem__(self, key):\n- v = super().__getitem__(key)\n- if isinstance(v, str):\n- while self._regx.match(v) is not None:\n- v = v.format(**super().__getattribute__('_root'))\n- if not self._recursive:\n- break\n- return v\n+ super().__init__()\n+ super().__setattr__('_collection', list(*args, **kwargs))\n+ super().__setattr__('_root', YamlDict([(YamlList.ROOT_NAME, self)]))\n \n- def __setitem__(self, key, value):\n- if isinstance(value, Mapping) and not isinstance(value, YamlDict):\n- value = YamlDict(value)\n- value.set_as_root(super().__getattribute__('_root'))\n- elif isinstance(value, Sequence) and not isinstance(value, (str, YamlList)):\n- value = YamlList(value)\n- value.set_as_root(super().__getattribute__('_root'))\n- super().__setitem__(key, value)\n+ def insert(self, index: int, object):\n+ super().__getattribute__('_collection').insert(index, object)\n \n- def set_as_root(self, root=None, *, recursive=False):\n- super().__setattr__('_recursive', recursive)\n- if root is not None:\n- super().__setattr__('_root', root)\n- for v in self:\n- if hasattr(v, 'set_as_root'):\n- v.set_as_root(super().__getattribute__('_root'), recursive=recursive)\n+ def _values(self):\n+ return super().__getattribute__('_collection')\n", "test_patch": "diff --git a/tests/test_yaml_dict.py b/tests/test_dynamic_yaml.py\nsimilarity index 75%\nrename from tests/test_yaml_dict.py\nrename to tests/test_dynamic_yaml.py\nindex 3d7990d..c666952 100644\n--- a/tests/test_yaml_dict.py\n+++ b/tests/test_dynamic_yaml.py\n@@ -4,7 +4,29 @@ from unittest import TestCase, main\n from dynamic_yaml import load\n \n \n-class TestYamlDict(TestCase):\n+class TestDynamicYaml(TestCase):\n+ def test_list(self):\n+ config = '''\n+ - a\n+ - b\n+ - c\n+ '''\n+ res = load(config)\n+ self.assertEqual('a', res[0])\n+ self.assertEqual('b', res[1])\n+ self.assertEqual('c', res[2])\n+\n+ def test_list_resolution(self):\n+ config = '''\n+ - a\n+ - b\n+ - '{root[0]}'\n+ '''\n+ res = load(config)\n+ self.assertEqual('a', res[0])\n+ self.assertEqual('b', res[1])\n+ self.assertEqual('a', res[2])\n+\n def test_dict(self):\n config = '''\n a: 1\n@@ -12,7 +34,9 @@ class TestYamlDict(TestCase):\n c: a\n '''\n res = load(config)\n- self.assertDictEqual({'a': 1, 'b': 2, 'c': 'a'}, res)\n+ self.assertEqual(1, res.a)\n+ self.assertEqual(2, res.b)\n+ self.assertEqual('a', res.c)\n \n def test_nested_dict(self):\n config = '''\n@@ -23,7 +47,10 @@ class TestYamlDict(TestCase):\n e: 'a'\n '''\n res = load(config)\n- self.assertDictEqual({'a': 1, 'b': {'c': 3, 'd': 4, 'e': 'a'}}, res)\n+ self.assertEqual(1, res.a)\n+ self.assertEqual(3, res.b.c)\n+ self.assertEqual(4, res.b.d)\n+ self.assertEqual('a', res.b.e)\n \n def test_deeply_nested_dict(self):\n config = '''\n@@ -37,7 +64,11 @@ class TestYamlDict(TestCase):\n h: 5\n '''\n res = load(config)\n- self.assertDictEqual({'a': 1, 'b': {'c': 2, 'd': 3, 'e': {'f': 4, 'g': {'h': 5}}}}, res)\n+ self.assertEqual(1, res.a)\n+ self.assertEqual(2, res.b.c)\n+ self.assertEqual(3, res.b.d)\n+ self.assertEqual(4, res.b.e.f)\n+ self.assertEqual(5, res.b.e.g.h)\n \n def test_resolve_simple(self):\n config = '''\n@@ -144,13 +175,28 @@ class TestYamlDict(TestCase):\n def test_recursive(self):\n config = '''\n prefix: /opt/ml\n- input_path: \"{prefix}/input\"\n+ input_path: '{prefix}/input'\n training_data_path: '{input_path}/data/training'\n '''\n \n res = load(config, recursive=True)\n+ self.assertEqual('/opt/ml/input', res.input_path)\n self.assertEqual('/opt/ml/input/data/training', res.training_data_path)\n \n+ def test_keyword_args(self):\n+ config = '''\n+ prefix: /opt/ml\n+ input_path: '{prefix}/input'\n+ training_data_path: '{input_path}/data/training'\n+ '''\n+\n+ def inner_test(input_path, training_data_path, **kwargs):\n+ self.assertEqual('/opt/ml/input', input_path)\n+ self.assertEqual('/opt/ml/input/data/training', training_data_path)\n+\n+ res = load(config, recursive=True)\n+ inner_test(**res)\n+\n \n if __name__ == '__main__':\n import sys\n", "FAIL_TO_PASS": ["tests/test_dynamic_yaml.py::TestDynamicYaml::test_keyword_args"]}, {"instance_id": "childsish__dynamic-yaml-18", "base_commit": "73895727841024969b854b1c524ce8aa70527f46", "gold_patch": "diff --git a/dynamic_yaml/yaml_wrappers.py b/dynamic_yaml/yaml_wrappers.py\nindex 14c5ecc..1a08d27 100644\n--- a/dynamic_yaml/yaml_wrappers.py\n+++ b/dynamic_yaml/yaml_wrappers.py\n@@ -78,6 +78,10 @@ class YamlList(DynamicYamlObject, MutableSequence):\n super().__setattr__('_collection', list(*args, **kwargs))\n super().__setattr__('_root', YamlDict([(YamlList.ROOT_NAME, self)]))\n \n+ def __iter__(self):\n+ for i in range(len(self)):\n+ yield self[i]\n+\n def insert(self, index: int, object):\n super().__getattribute__('_collection').insert(index, object)\n \n", "test_patch": "diff --git a/tests/test_dynamic_yaml.py b/tests/test_dynamic_yaml.py\nindex c666952..3cd4bee 100644\n--- a/tests/test_dynamic_yaml.py\n+++ b/tests/test_dynamic_yaml.py\n@@ -197,6 +197,34 @@ class TestDynamicYaml(TestCase):\n res = load(config, recursive=True)\n inner_test(**res)\n \n+ def test_list_iteration(self):\n+ config = '''\n+ targets:\n+ v1: value1\n+ v2: value2\n+ query:\n+ - '{targets.v1}'\n+ - '{targets.v2}'\n+ '''\n+\n+ res = load(config)\n+ self.assertEqual(['value1', 'value2'], list(res.query))\n+\n+ def test_dict_iteration(self):\n+ config = '''\n+ targets:\n+ v1: value1\n+ v2: value2\n+ query:\n+ v1: '{targets.v1}'\n+ v2: '{targets.v2}'\n+ '''\n+\n+ res = load(config)\n+ self.assertEqual(['v1', 'v2'], list(res.query))\n+ self.assertEqual(['value1', 'value2'], list(res.query.values()))\n+ self.assertEqual([('v1', 'value1'), ('v2', 'value2')], list(res.query.items()))\n+\n \n if __name__ == '__main__':\n import sys\n", "FAIL_TO_PASS": ["tests/test_dynamic_yaml.py::TestDynamicYaml::test_list_iteration"]}], "all_FAIL_TO_PASS": ["tests/test_dynamic_yaml.py::TestDynamicYaml::test_keyword_args", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_list_iteration"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "dask__dask-3254_x2", "level": 2, "source": "swerebench", "repo": "dask/dask", "image": "swerebench/sweb.eval.x86_64.dask_1776_dask-3254:latest", "base_commit": "cc9f8db12e4c43b61fb79bb74bbd71b3cd8ba1f7", "num_bugs": 2, "bugs": [{"instance_id": "dask__dask-3254", "base_commit": "cc9f8db12e4c43b61fb79bb74bbd71b3cd8ba1f7", "gold_patch": "diff --git a/dask/array/core.py b/dask/array/core.py\nindex 6f132e1ad..a4990fe95 100644\n--- a/dask/array/core.py\n+++ b/dask/array/core.py\n@@ -1754,9 +1754,9 @@ class Array(Base):\n return cumprod(self, axis, dtype, out=out)\n \n @derived_from(np.ndarray)\n- def squeeze(self):\n+ def squeeze(self, axis=None):\n from .routines import squeeze\n- return squeeze(self)\n+ return squeeze(self, axis)\n \n def rechunk(self, chunks, threshold=None, block_size_limit=None):\n \"\"\" See da.rechunk for docstring \"\"\"\ndiff --git a/dask/array/routines.py b/dask/array/routines.py\nindex 8f1ea653a..da414204b 100644\n--- a/dask/array/routines.py\n+++ b/dask/array/routines.py\n@@ -5,7 +5,6 @@ import warnings\n from collections import Iterable\n from distutils.version import LooseVersion\n from functools import wraps, partial\n-from itertools import product\n from numbers import Integral\n from operator import getitem\n \n@@ -836,20 +835,23 @@ def ravel(array):\n \n @wraps(np.squeeze)\n def squeeze(a, axis=None):\n- if 1 not in a.shape:\n- return a\n if axis is None:\n axis = tuple(i for i, d in enumerate(a.shape) if d == 1)\n- b = a.map_blocks(partial(np.squeeze, axis=axis), dtype=a.dtype)\n- chunks = tuple(bd for bd in b.chunks if bd != (1,))\n+ elif not isinstance(axis, tuple):\n+ axis = (axis,)\n+\n+ if any(a.shape[i] != 1 for i in axis):\n+ raise ValueError(\"cannot squeeze axis with size other than one\")\n+\n+ for i in axis:\n+ if not (-a.ndim <= i < a.ndim):\n+ raise ValueError(\"%i out of bounds for %i-D array\" % (i, a.ndim))\n \n- name = 'squeeze-' + tokenize(a, axis)\n- old_keys = list(product([b.name], *[range(len(bd)) for bd in b.chunks]))\n- new_keys = list(product([name], *[range(len(bd)) for bd in chunks]))\n+ axis = tuple(i % a.ndim for i in axis)\n \n- dsk = {n: b.dask[o] for o, n in zip(old_keys, new_keys)}\n+ sl = tuple(0 if i in axis else slice(None) for i, s in enumerate(a.shape))\n \n- return Array(sharedict.merge(b.dask, (name, dsk)), name, chunks, dtype=a.dtype)\n+ return a[sl]\n \n \n def topk(k, x):\ndiff --git a/dask/bag/core.py b/dask/bag/core.py\nindex 9ad1ff047..3b30bebf8 100644\n--- a/dask/bag/core.py\n+++ b/dask/bag/core.py\n@@ -918,21 +918,65 @@ class Bag(Base):\n def join(self, other, on_self, on_other=None):\n \"\"\" Joins collection with another collection.\n \n- Other collection must be an Iterable, and not a Bag.\n+ Other collection must be one of the following:\n \n+ 1. An iterable. We recommend tuples over lists for internal\n+ performance reasons.\n+ 2. A delayed object, pointing to a tuple. This is recommended if the\n+ other collection is sizable and you're using the distributed\n+ scheduler. Dask is able to pass around data wrapped in delayed\n+ objects with greater sophistication.\n+ 3. A Bag with a single partition\n+\n+ You might also consider Dask Dataframe, whose join operations are much\n+ more heavily optimized.\n+\n+ Parameters\n+ ----------\n+ other: Iterable, Delayed, Bag\n+ Other collection on which to join\n+ on_self: callable\n+ Function to call on elements in this collection to determine a\n+ match\n+ on_other: callable (defaults to on_self)\n+ Function to call on elements in the other collection to determine a\n+ match\n+\n+ Examples\n+ --------\n >>> people = from_sequence(['Alice', 'Bob', 'Charlie'])\n >>> fruit = ['Apple', 'Apricot', 'Banana']\n >>> list(people.join(fruit, lambda x: x[0])) # doctest: +SKIP\n [('Apple', 'Alice'), ('Apricot', 'Alice'), ('Banana', 'Bob')]\n \"\"\"\n- assert isinstance(other, Iterable)\n- assert not isinstance(other, Bag)\n+ name = 'join-' + tokenize(self, other, on_self, on_other)\n+ dsk = {}\n+ if isinstance(other, Bag):\n+ if other.npartitions == 1:\n+ dsk.update(other.dask)\n+ dsk['join-%s-other' % name] = (list, other._keys()[0])\n+ other = other._keys()[0]\n+ else:\n+ msg = (\"Multi-bag joins are not implemented. \"\n+ \"We recommend Dask dataframe if appropriate\")\n+ raise NotImplementedError(msg)\n+ elif isinstance(other, Delayed):\n+ dsk.update(other.dask)\n+ other = other._key\n+ elif isinstance(other, Iterable):\n+ other = other\n+ else:\n+ msg = (\"Joined argument must be single-partition Bag, \"\n+ \" delayed object, or Iterable, got %s\" %\n+ type(other).__name)\n+ raise TypeError(msg)\n+\n if on_other is None:\n on_other = on_self\n- name = 'join-' + tokenize(self, other, on_self, on_other)\n- dsk = dict(((name, i), (list, (join, on_other, other,\n- on_self, (self.name, i))))\n- for i in range(self.npartitions))\n+\n+ dsk.update({(name, i): (list, (join, on_other, other,\n+ on_self, (self.name, i)))\n+ for i in range(self.npartitions)})\n return type(self)(merge(self.dask, dsk), name, self.npartitions)\n \n def product(self, other):\ndiff --git a/docs/source/changelog.rst b/docs/source/changelog.rst\nindex 12a4cda26..56632fa08 100644\n--- a/docs/source/changelog.rst\n+++ b/docs/source/changelog.rst\n@@ -19,10 +19,10 @@ DataFrame\n - Add ``dd.tseries.Resampler.agg`` (:pr:`3202`) `Richard Postelnik`_\n - Support operations that mix dataframes and arrays (:pr:`3230`) `Matthew Rocklin`_\n \n-\n Bag\n +++\n \n+- Support joining against single-partitioned bags and delayed objects (:pr:`3254`) `Matthew Rocklin`_\n \n Core\n ++++\ndiff --git a/docs/source/index.rst b/docs/source/index.rst\nindex 3edb01201..a045f7771 100644\n--- a/docs/source/index.rst\n+++ b/docs/source/index.rst\n@@ -190,7 +190,7 @@ distributed memory clusters.\n scheduling.rst\n distributed.rst\n \n-**Diagnosing Perofmrance**\n+**Diagnosing Performance**\n \n Parallel code can be tricky to debug and profile. Dask provides a several tools\n to help make debugging and profiling graph execution easier.\n", "test_patch": "diff --git a/dask/array/tests/test_routines.py b/dask/array/tests/test_routines.py\nindex f37b9f817..f084adbd2 100644\n--- a/dask/array/tests/test_routines.py\n+++ b/dask/array/tests/test_routines.py\n@@ -710,13 +710,35 @@ def test_ravel():\n assert_eq(np.ravel(x), da.ravel(a))\n \n \n-def test_squeeze():\n- x = da.ones((10, 1), chunks=(3, 1))\n+@pytest.mark.parametrize('is_func', [True, False])\n+@pytest.mark.parametrize('axis', [None, 0, -1, (0, -1)])\n+def test_squeeze(is_func, axis):\n+ a = np.arange(10)[None, :, None, None]\n+ d = da.from_array(a, chunks=(1, 3, 1, 1))\n+\n+ if is_func:\n+ a_s = np.squeeze(a, axis=axis)\n+ d_s = da.squeeze(d, axis=axis)\n+ else:\n+ a_s = a.squeeze(axis=axis)\n+ d_s = d.squeeze(axis=axis)\n+\n+ assert_eq(d_s, a_s)\n+ assert same_keys(d_s, da.squeeze(d, axis=axis))\n \n- assert_eq(x.squeeze(), x.compute().squeeze())\n+ if axis is None:\n+ axis = tuple(range(a.ndim))\n+ else:\n+ axis = axis if isinstance(axis, tuple) else (axis,)\n+ axis = tuple(i % a.ndim for i in axis)\n+ axis = tuple(\n+ i for i, c in enumerate(d.chunks) if i in axis and len(c) == 1\n+ )\n \n- assert x.squeeze().chunks == ((3, 3, 3, 1),)\n- assert same_keys(x.squeeze(), x.squeeze())\n+ exp_d_s_chunks = tuple(\n+ c for i, c in enumerate(d.chunks) if i not in axis\n+ )\n+ assert d_s.chunks == exp_d_s_chunks\n \n \n def test_vstack():\ndiff --git a/dask/bag/tests/test_bag.py b/dask/bag/tests/test_bag.py\nindex 004139fba..cd9bf68d2 100644\n--- a/dask/bag/tests/test_bag.py\n+++ b/dask/bag/tests/test_bag.py\n@@ -32,6 +32,15 @@ L = list(range(5)) * 3\n b = Bag(dsk, 'x', 3)\n \n \n+def assert_eq(a, b):\n+ if hasattr(a, 'compute'):\n+ a = a.compute(get=dask.local.get_sync)\n+ if hasattr(b, 'compute'):\n+ b = b.compute(get=dask.local.get_sync)\n+\n+ assert a == b\n+\n+\n def iseven(x):\n return x % 2 == 0\n \n@@ -353,12 +362,18 @@ def test_var():\n assert float(b.var()) == 2.0\n \n \n-def test_join():\n- c = b.join([1, 2, 3], on_self=isodd, on_other=iseven)\n- assert list(c) == list(join(iseven, [1, 2, 3], isodd, list(b)))\n- assert (list(b.join([1, 2, 3], isodd)) ==\n- list(join(isodd, [1, 2, 3], isodd, list(b))))\n- assert c.name == b.join([1, 2, 3], on_self=isodd, on_other=iseven).name\n+@pytest.mark.parametrize('transform', [\n+ identity,\n+ dask.delayed,\n+ lambda x: db.from_sequence(x, npartitions=1)\n+])\n+def test_join(transform):\n+ other = transform([1, 2, 3])\n+ c = b.join(other, on_self=isodd, on_other=iseven)\n+ assert_eq(c, list(join(iseven, [1, 2, 3], isodd, list(b))))\n+ assert_eq(b.join(other, isodd),\n+ list(join(isodd, [1, 2, 3], isodd, list(b))))\n+ assert c.name == b.join(other, on_self=isodd, on_other=iseven).name\n \n \n def test_foldby():\n", "FAIL_TO_PASS": ["dask/array/tests/test_routines.py::test_squeeze[None-False]", "dask/array/tests/test_routines.py::test_squeeze[0-True]", "dask/array/tests/test_routines.py::test_squeeze[0-False]", "dask/array/tests/test_routines.py::test_squeeze[-1-True]", "dask/array/tests/test_routines.py::test_squeeze[-1-False]", "dask/array/tests/test_routines.py::test_squeeze[axis3-True]", "dask/array/tests/test_routines.py::test_squeeze[axis3-False]", "dask/bag/tests/test_bag.py::test_join[delayed]", "dask/bag/tests/test_bag.py::test_join[]"]}, {"instance_id": "dask__dask-3301", "base_commit": "11a50f0d329bdaf1ea6b7f0cff9500f55699fd36", "gold_patch": "diff --git a/dask/array/core.py b/dask/array/core.py\nindex a4990fe95..1d3d54f75 100644\n--- a/dask/array/core.py\n+++ b/dask/array/core.py\n@@ -1208,7 +1208,12 @@ class Array(Base):\n \n @wraps(store)\n def store(self, target, **kwargs):\n- return store([self], [target], **kwargs)\n+ r = store([self], [target], **kwargs)\n+\n+ if kwargs.get(\"return_stored\", False):\n+ r = r[0]\n+\n+ return r\n \n def to_hdf5(self, filename, datapath, **kwargs):\n \"\"\" Store array in HDF5 file\n@@ -2611,8 +2616,12 @@ def concatenate(seq, axis=0, allow_unknown_chunksizes=False):\n \n cum_dims = [0] + list(accumulate(add, [len(a.chunks[axis]) for a in seq]))\n \n- dt = reduce(np.promote_types, [a.dtype for a in seq])\n- seq = [x.astype(dt) for x in seq]\n+ seq_dtypes = [a.dtype for a in seq]\n+ if len(set(seq_dtypes)) > 1:\n+ dt = reduce(np.promote_types, seq_dtypes)\n+ seq = [x.astype(dt) for x in seq]\n+ else:\n+ dt = seq_dtypes[0]\n \n names = [a.name for a in seq]\n \n", "test_patch": "diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py\nindex cc233f4b4..87f420c25 100644\n--- a/dask/array/tests/test_array_core.py\n+++ b/dask/array/tests/test_array_core.py\n@@ -335,6 +335,17 @@ def test_concatenate():\n pytest.raises(ValueError, lambda: concatenate([a, b, c], axis=2))\n \n \n+@pytest.mark.parametrize('dtypes', [(('>f8', '>f8'), '>f8'),\n+ ((']", "dask/array/tests/test_array_core.py::test_concatenate_types[dtypes0]", "dask/array/tests/test_array_core.py::test_store_method_return"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "alexander-akhmetov__python-telegram-168_x2", "level": 2, "source": "swerebench", "repo": "alexander-akhmetov/python-telegram", "image": "swerebench/sweb.eval.x86_64.alexander-akhmetov_1776_python-telegram-168:latest", "base_commit": "9d5bece5ac489e70dc773f1d8ec7592c7a9fea78", "num_bugs": 2, "bugs": [{"instance_id": "alexander-akhmetov__python-telegram-168", "base_commit": "9d5bece5ac489e70dc773f1d8ec7592c7a9fea78", "gold_patch": "diff --git a/telegram/client.py b/telegram/client.py\nindex 9744d32..5a1ea27 100644\n--- a/telegram/client.py\n+++ b/telegram/client.py\n@@ -227,6 +227,15 @@ class Telegram:\n \n return self.call_method('getUser', params={'user_id': user_id})\n \n+ def get_user_full_info(self, user_id: int) -> AsyncResult:\n+ \"\"\"\n+ Requests the full information about a user with id = user_id.\n+\n+ https://core.telegram.org/tdlib/docs/classtd_1_1td__api_1_1get_user_full_info.html\n+ \"\"\"\n+\n+ return self.call_method('getUserFullInfo', params={'user_id': user_id})\n+\n def get_chats(self, offset_order: int = 0, offset_chat_id: int = 0, limit: int = 100) -> AsyncResult:\n \"\"\"\n Returns a list of chats:\n", "test_patch": "diff --git a/tests/requirements.txt b/tests/requirements.txt\nindex 5f70074..a053c78 100644\n--- a/tests/requirements.txt\n+++ b/tests/requirements.txt\n@@ -1,6 +1,6 @@\n-pytest==6.2.3\n+pytest==6.2.2\n flake8==3.9.0\n-pylint==2.7.4\n+pylint==2.7.2\n ipdb==0.13.7\n mypy==0.812\n black==20.8b1\ndiff --git a/tests/test_telegram_methods.py b/tests/test_telegram_methods.py\nindex 80e7954..e5d7229 100644\n--- a/tests/test_telegram_methods.py\n+++ b/tests/test_telegram_methods.py\n@@ -201,6 +201,32 @@ class TestTelegram:\n \n telegram._tdjson.send.assert_called_once_with(exp_data)\n \n+ def test_get_user(self, telegram):\n+ user_id = 1\n+\n+ async_result = telegram.get_user(user_id=user_id)\n+\n+ exp_data = {\n+ '@type': 'getUser',\n+ 'user_id': user_id,\n+ '@extra': {'request_id': async_result.id},\n+ }\n+\n+ telegram._tdjson.send.assert_called_once_with(exp_data)\n+\n+ def test_get_user_full_info(self, telegram):\n+ user_id = 1\n+\n+ async_result = telegram.get_user_full_info(user_id=user_id)\n+\n+ exp_data = {\n+ '@type': 'getUserFullInfo',\n+ 'user_id': user_id,\n+ '@extra': {'request_id': async_result.id},\n+ }\n+\n+ telegram._tdjson.send.assert_called_once_with(exp_data)\n+\n def test_get_chat(self, telegram):\n chat_id = 1\n \n", "FAIL_TO_PASS": ["tests/test_telegram_methods.py::TestTelegram::test_get_user_full_info"]}, {"instance_id": "alexander-akhmetov__python-telegram-208", "base_commit": "534ff81b5fb48eb256ea7e8fbcd6c2ef240b142e", "gold_patch": "diff --git a/telegram/client.py b/telegram/client.py\nindex 5a1ea27..01a567c 100644\n--- a/telegram/client.py\n+++ b/telegram/client.py\n@@ -41,6 +41,7 @@ class AuthorizationState(enum.Enum):\n WAIT_TDLIB_PARAMETERS = 'authorizationStateWaitTdlibParameters'\n WAIT_ENCRYPTION_KEY = 'authorizationStateWaitEncryptionKey'\n WAIT_PHONE_NUMBER = 'authorizationStateWaitPhoneNumber'\n+ WAIT_REGISTRATION = 'authorizationStateWaitRegistration'\n READY = 'authorizationStateReady'\n CLOSING = 'authorizationStateClosing'\n CLOSED = 'authorizationStateClosed'\n@@ -542,7 +543,10 @@ class Telegram:\n - AuthorizationState.WAIT_PASSWORD if a telegram password is required.\n The caller should ask the telegram password\n to the end user and then call send_password(password)\n- - AuthorizationState.READY if the login process scceeded.\n+ - AuthorizationState.WAIT_REGISTRATION if a the user must finish registration\n+ The caller should ask the first and last names\n+ to the end user and then call register_user(first, last)\n+ - AuthorizationState.READY if the login process succeeded.\n \"\"\"\n if self.proxy_server:\n self._send_add_proxy()\n@@ -554,11 +558,13 @@ class Telegram:\n AuthorizationState.WAIT_PHONE_NUMBER: self._send_phone_number_or_bot_token,\n AuthorizationState.WAIT_CODE: self._send_telegram_code,\n AuthorizationState.WAIT_PASSWORD: self._send_password,\n+ AuthorizationState.WAIT_REGISTRATION: self._register_user,\n }\n \n blocking_actions = (\n AuthorizationState.WAIT_CODE,\n AuthorizationState.WAIT_PASSWORD,\n+ AuthorizationState.WAIT_REGISTRATION,\n )\n \n if self.phone:\n@@ -710,3 +716,38 @@ class Telegram:\n self.authorization_state = self._wait_authorization_result(result)\n \n return self.authorization_state\n+\n+ def _register_user(self, first: Optional[str] = None, last: Optional[str] = None) -> AsyncResult:\n+ logger.info('Registering user')\n+ if first is None:\n+ first = input('Enter first name: ')\n+ if last is None:\n+ last = input('Enter last name: ')\n+\n+ data = {\n+ '@type': 'registerUser',\n+ 'first_name': first,\n+ 'last_name': last,\n+ }\n+ return self._send_data(data, result_id='updateAuthorizationState')\n+\n+ def register_user(self, first: str, last: str) -> AuthorizationState:\n+ \"\"\"\n+ Finishes the new user registration process\n+\n+ Args:\n+ first the user's first name\n+ last the user's last name\n+ If either argument is None, it will be asked to the user using the input() function\n+\n+ Returns\n+ - AuthorizationState. The called have to call `login` to continue the login process.\n+\n+ Raises:\n+ - RuntimeError if the login failed\n+\n+ \"\"\"\n+ result = self._register_user(first, last)\n+ self.authorization_state = self._wait_authorization_result(result)\n+\n+ return self.authorization_state\n", "test_patch": "diff --git a/tests/test_telegram_methods.py b/tests/test_telegram_methods.py\nindex e5d7229..0164f04 100644\n--- a/tests/test_telegram_methods.py\n+++ b/tests/test_telegram_methods.py\n@@ -438,6 +438,9 @@ class TestTelegram__login_non_blocking:\n data={'authorization_state': {'@type': 'authorizationStateWaitCode'}}\n )\n telegram._send_telegram_code = lambda _: _get_async_result(\n+ data={'authorization_state': {'@type': 'authorizationStateWaitRegistration'}}\n+ )\n+ telegram._register_user = lambda _, __: _get_async_result(\n data={'authorization_state': {'@type': 'authorizationStateWaitPassword'}}\n )\n telegram._send_password = lambda _: _get_async_result(\n@@ -448,6 +451,10 @@ class TestTelegram__login_non_blocking:\n assert state == AuthorizationState.WAIT_CODE\n telegram.send_code('123')\n \n+ state = telegram.login(blocking=False)\n+ assert state == AuthorizationState.WAIT_REGISTRATION\n+ telegram.register_user('new', 'user')\n+\n state = telegram.login(blocking=False)\n assert state == AuthorizationState.WAIT_PASSWORD\n telegram.send_password('456')\n", "FAIL_TO_PASS": ["tests/test_telegram_methods.py::TestTelegram__login_non_blocking::test_login_process_with_phone"]}], "all_FAIL_TO_PASS": ["tests/test_telegram_methods.py::TestTelegram::test_get_user_full_info", "tests/test_telegram_methods.py::TestTelegram__login_non_blocking::test_login_process_with_phone"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "allrod5__parameters-validation-3_x2", "level": 2, "source": "swerebench", "repo": "allrod5/parameters-validation", "image": "swerebench/sweb.eval.x86_64.allrod5_1776_parameters-validation-3:latest", "base_commit": "8a36fbaa01780960d8963fba35aae3f06efcc6a5", "num_bugs": 2, "bugs": [{"instance_id": "allrod5__parameters-validation-3", "base_commit": "8a36fbaa01780960d8963fba35aae3f06efcc6a5", "gold_patch": "diff --git a/parameters_validation/validate_parameters_decorator.py b/parameters_validation/validate_parameters_decorator.py\nindex 877f496..7aea24b 100644\n--- a/parameters_validation/validate_parameters_decorator.py\n+++ b/parameters_validation/validate_parameters_decorator.py\n@@ -33,6 +33,6 @@ def validate_parameters(func):\n continue\n annotation(parameters[parameter], parameter)\n \n- func(*args, **kwargs)\n+ return func(*args, **kwargs)\n \n return wrapper\ndiff --git a/setup.py b/setup.py\nindex 884467f..efdb614 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -16,7 +16,7 @@ extras = {\n \n setup(\n name='parameters-validation',\n- version='1.1.0',\n+ version='1.1.1',\n packages=['parameters_validation'],\n url='https://github.com/allrod5/parameters-validation',\n license='MIT',\n", "test_patch": "diff --git a/test/__init__.py b/tests/__init__.py\nsimilarity index 100%\nrename from test/__init__.py\nrename to tests/__init__.py\ndiff --git a/tests/bugfixes/__init__.py b/tests/bugfixes/__init__.py\nnew file mode 100644\nindex 0000000..e69de29\ndiff --git a/tests/bugfixes/test_return_value_is_preserved.py b/tests/bugfixes/test_return_value_is_preserved.py\nnew file mode 100644\nindex 0000000..af96bc4\n--- /dev/null\n+++ b/tests/bugfixes/test_return_value_is_preserved.py\n@@ -0,0 +1,27 @@\n+\"\"\"\n+This test covers a fix for a bug first reported in\n+https://github.com/allrod5/parameters-validation/issues/2\n+\n+In version 1.1.0 a function annotated with decorator\n+@validate_parameters would return None regardless of it's actual\n+return value\n+\n+This bug was fixed in version 1.1.1\n+\"\"\"\n+from parameters_validation import non_null, validate_parameters\n+\n+\n+def test_return_value_is_preserved():\n+ # given\n+ @validate_parameters\n+ def guinea_pig(front: str, back: non_null(str)):\n+ result = None\n+ if front:\n+ result = front + '-' + back\n+ return result\n+\n+ # when\n+ return_value = guinea_pig(\"one\", \"two\")\n+\n+ # then\n+ assert return_value == \"one-two\"\n", "FAIL_TO_PASS": ["tests/bugfixes/test_return_value_is_preserved.py::test_return_value_is_preserved"]}, {"instance_id": "allrod5__parameters-validation-6", "base_commit": "611c5d4744dde3354ee7e8460d199bc79ee4af94", "gold_patch": "diff --git a/parameters_validation/validate_parameters_decorator.py b/parameters_validation/validate_parameters_decorator.py\nindex 7aea24b..4cc3d7c 100644\n--- a/parameters_validation/validate_parameters_decorator.py\n+++ b/parameters_validation/validate_parameters_decorator.py\n@@ -24,10 +24,7 @@ def validate_parameters(func):\n specs = inspect.getfullargspec(func)\n @wraps(func)\n def wrapper(*args, **kwargs):\n- parameters = kwargs.copy()\n- for arg_value, parameter in zip(args, specs.args):\n- parameters[parameter] = arg_value\n-\n+ parameters = get_parameter_value_dict(args, kwargs)\n for parameter, annotation in specs.annotations.items():\n if not hasattr(annotation, \"_parameter_validation\"):\n continue\n@@ -35,4 +32,22 @@ def validate_parameters(func):\n \n return func(*args, **kwargs)\n \n+ def get_parameter_value_dict(args, kwargs):\n+ parameters = kwargs.copy()\n+ for arg_value, parameter in zip(args, specs.args):\n+ parameters[parameter] = arg_value\n+ if specs.defaults:\n+ for default_parameter, default_value in zip(specs.args, specs.defaults):\n+ if default_parameter in parameters:\n+ pass\n+ parameters[default_parameter] = default_value\n+ if specs.kwonlydefaults:\n+ for default_parameter, default_value in zip(\n+ specs.kwonlyargs, specs.kwonlydefaults\n+ ):\n+ if default_parameter in parameters:\n+ pass\n+ parameters[default_parameter] = default_value\n+ return parameters\n+\n return wrapper\n", "test_patch": "diff --git a/tests/bugfixes/test_strongly_typed_on_default_parameters.py b/tests/bugfixes/test_strongly_typed_on_default_parameters.py\nnew file mode 100644\nindex 0000000..aa6d8a2\n--- /dev/null\n+++ b/tests/bugfixes/test_strongly_typed_on_default_parameters.py\n@@ -0,0 +1,26 @@\n+\"\"\"\n+This test covers a fix for a bug first reported in\n+https://github.com/allrod5/parameters-validation/issues/5\n+\n+In version 1.1.1 a function annotated with decorator\n+@validate_parameters would crash if the builtin validation\n+`strongly_typed` is used for a parameter with default value\n+and there is a call to this function that uses the default value\n+\n+This bug was fixed in version 1.1.2\n+\"\"\"\n+from parameters_validation import non_null, validate_parameters, strongly_typed\n+\n+\n+def test_strongly_typed_on_default_parameters():\n+ # given\n+ default_value = \"default value\"\n+ @validate_parameters\n+ def guinea_pig(a: strongly_typed(str) = default_value):\n+ return a\n+\n+ # when\n+ return_value = guinea_pig()\n+\n+ # then\n+ assert return_value == default_value\n", "FAIL_TO_PASS": ["tests/bugfixes/test_strongly_typed_on_default_parameters.py::test_strongly_typed_on_default_parameters"]}], "all_FAIL_TO_PASS": ["tests/bugfixes/test_return_value_is_preserved.py::test_return_value_is_preserved", "tests/bugfixes/test_strongly_typed_on_default_parameters.py::test_strongly_typed_on_default_parameters"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "briancurtin__deprecation-12_x2", "level": 2, "source": "swerebench", "repo": "briancurtin/deprecation", "image": "swerebench/sweb.eval.x86_64.briancurtin_1776_deprecation-12:latest", "base_commit": "70bb27fef996b214d7b698ed3124fb598220eea9", "num_bugs": 2, "bugs": [{"instance_id": "briancurtin__deprecation-12", "base_commit": "70bb27fef996b214d7b698ed3124fb598220eea9", "gold_patch": "diff --git a/deprecation.py b/deprecation.py\nindex 28a21ee..00598db 100644\n--- a/deprecation.py\n+++ b/deprecation.py\n@@ -10,6 +10,7 @@\n # License for the specific language governing permissions and limitations\n # under the License.\n import functools\n+import textwrap\n import warnings\n \n from packaging import version\n@@ -167,8 +168,31 @@ def deprecated(deprecated_in=None, removed_in=None, current_version=None,\n deprecation_note = (\"*Deprecated{deprecated_in}{removed_in}\"\n \"{period}{details}*\".format(**parts))\n \n- function.__doc__ = \"\\n\\n\".join([existing_docstring,\n+ pos = existing_docstring.find(\"\\n\")\n+\n+ if pos != -1:\n+ # With a multi-line docstring, when we modify\n+ # existing_docstring to add our deprecation_note,\n+ # if we're not careful we'll interfere with the\n+ # indentation levels of the contents below the\n+ # first line, or as PEP 257 calls it, the summary\n+ # line. Since the summary line can start on the\n+ # same line as the \"\"\", dedenting the whole thing\n+ # won't help. Split the summary and contents up,\n+ # dedent the contents independently, then join\n+ # summary, dedent'ed contents, and our\n+ # deprecation_note.\n+\n+ summary = existing_docstring[:pos]\n+ contents = existing_docstring[pos:]\n+\n+ function.__doc__ = \"\".join([summary,\n+ textwrap.dedent(contents),\n+ \"\\n\\n\",\n deprecation_note])\n+ else:\n+ function.__doc__ = \"\\n\\n\".join([existing_docstring,\n+ deprecation_note])\n \n @functools.wraps(function)\n def _inner(*args, **kwargs):\ndiff --git a/sample.py b/sample.py\nindex be00938..9373753 100644\n--- a/sample.py\n+++ b/sample.py\n@@ -14,6 +14,19 @@ def won():\n return 1\n \n \n+@deprecation.deprecated(deprecated_in=\"1.0\", removed_in=\"2.0\",\n+ current_version=__version__,\n+ details=\"Use the ``one`` function instead\")\n+def uno():\n+ \"\"\"Esta funci\u00f3n regresa 1\n+\n+ This is Spanish for 'This function returns 1'\n+\n+ This is also here to show that multiline docstrings work\n+ \"\"\"\n+ return 1\n+\n+\n def one():\n \"\"\"This function returns 1\"\"\"\n return 1\ndiff --git a/setup.py b/setup.py\nindex ffe453a..3da8a87 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -28,6 +28,7 @@ setup(name=\"deprecation\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n+ \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n \"Topic :: Software Development :: Libraries :: Python Modules\"]\ndiff --git a/tox.ini b/tox.ini\nindex 3458187..026704c 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -1,5 +1,5 @@\n [tox]\n-envlist = py35,py34,py27,pypy,flake8\n+envlist = py37,py36,py35,py34,py27,pypy3,pypy,flake8\n skipsdist = True\n \n [testenv]\n", "test_patch": "diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py\nindex 3364f9c..cf9d420 100644\n--- a/tests/test_deprecation.py\n+++ b/tests/test_deprecation.py\n@@ -43,6 +43,30 @@ class Test_deprecated(unittest2.TestCase):\n \n self.assertEqual(fn.__doc__, test[\"__doc__\"])\n \n+ def test_multiline_docstring(self):\n+ docstring = \"summary line\\n\\ndetails\\nand more details\\n\"\n+ for test in [{\"args\": {},\n+ \"__doc__\": \"%s\\n\\n*Deprecated*\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\"},\n+ \"__doc__\": \"%s\\n\\n*Deprecated in 1.0.*\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\", \"removed_in\": \"2.0\"},\n+ \"__doc__\": \"%s\\n\\n*Deprecated in 1.0, \"\n+ \"to be removed in 2.0.*\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\", \"removed_in\": \"2.0\",\n+ \"details\": \"some details\"},\n+ \"__doc__\": \"%s\\n\\n*Deprecated in 1.0, \"\n+ \"to be removed in 2.0. some details*\"}]:\n+ with self.subTest(**test):\n+ @deprecation.deprecated(**test[\"args\"])\n+ def fn():\n+ \"\"\"summary line\n+\n+ details\n+ and more details\n+ \"\"\"\n+\n+ self.assertEqual(fn.__doc__, test[\"__doc__\"] % docstring)\n+\n def test_warning_raised(self):\n ret_val = \"lololol\"\n \n", "FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_multiline_docstring"]}, {"instance_id": "briancurtin__deprecation-14", "base_commit": "3ad94c2de7c313d0ca20a8ce4c9247a0faaa8018", "gold_patch": "diff --git a/deprecation.py b/deprecation.py\nindex 00598db..a64b5b7 100644\n--- a/deprecation.py\n+++ b/deprecation.py\n@@ -9,6 +9,7 @@\n # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n # License for the specific language governing permissions and limitations\n # under the License.\n+import collections\n import functools\n import textwrap\n import warnings\n@@ -51,9 +52,22 @@ class DeprecatedWarning(DeprecationWarning):\n super(DeprecatedWarning, self).__init__()\n \n def __str__(self):\n- return (\"%s is deprecated as of %s and will \"\n- \"be removed in %s. %s\" % (self.function, self.deprecated_in,\n- self.removed_in, self.details))\n+ # Use a defaultdict to give us the empty string\n+ # when a part isn't included.\n+ parts = collections.defaultdict(str)\n+ parts[\"function\"] = self.function\n+\n+ if self.deprecated_in:\n+ parts[\"deprecated\"] = \" as of %s\" % self.deprecated_in\n+ if self.removed_in:\n+ parts[\"removed\"] = \" and will be removed in %s\" % self.removed_in\n+ if any([self.deprecated_in, self.removed_in, self.details]):\n+ parts[\"period\"] = \".\"\n+ if self.details:\n+ parts[\"details\"] = \" %s\" % self.details\n+\n+ return (\"%(function)s is deprecated%(deprecated)s%(removed)s\"\n+ \"%(period)s%(details)s\" % (parts))\n \n \n class UnsupportedWarning(DeprecatedWarning):\n@@ -67,9 +81,15 @@ class UnsupportedWarning(DeprecatedWarning):\n \"\"\"\n \n def __str__(self):\n- return (\"%s is unsupported as of %s. %s\" % (self.function,\n- self.removed_in,\n- self.details))\n+ parts = collections.defaultdict(str)\n+ parts[\"function\"] = self.function\n+ parts[\"removed\"] = self.removed_in\n+\n+ if self.details:\n+ parts[\"details\"] = \" %s\" % self.details\n+\n+ return (\"%(function)s is unsupported as of %(removed)s.\"\n+ \"%(details)s\" % (parts))\n \n \n def deprecated(deprecated_in=None, removed_in=None, current_version=None,\n", "test_patch": "diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py\nindex cf9d420..55e05bd 100644\n--- a/tests/test_deprecation.py\n+++ b/tests/test_deprecation.py\n@@ -71,14 +71,33 @@ class Test_deprecated(unittest2.TestCase):\n ret_val = \"lololol\"\n \n for test in [{\"args\": {}, # No args just means deprecated\n- \"warning\": deprecation.DeprecatedWarning},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated\"},\n+ {\"args\": {\"details\": \"do something else.\"},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated. do something else.\"},\n {\"args\": {\"deprecated_in\": \"1.0\",\n \"current_version\": \"2.0\"},\n- \"warning\": deprecation.DeprecatedWarning},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated as of 1.0.\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\",\n+ \"removed_in\": \"3.0\",\n+ \"current_version\": \"2.0\"},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": (\"method is deprecated as of 1.0 \"\n+ \"and will be removed in 3.0.\")},\n {\"args\": {\"deprecated_in\": \"1.0\",\n \"removed_in\": \"2.0\",\n \"current_version\": \"2.0\"},\n- \"warning\": deprecation.UnsupportedWarning}]:\n+ \"warning\": deprecation.UnsupportedWarning,\n+ \"message\": \"method is unsupported as of 2.0.\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\",\n+ \"removed_in\": \"2.0\",\n+ \"current_version\": \"2.0\",\n+ \"details\": \"do something else.\"},\n+ \"warning\": deprecation.UnsupportedWarning,\n+ \"message\": (\"method is unsupported as of 2.0. \"\n+ \"do something else.\")}]:\n with self.subTest(**test):\n class Test(object):\n @deprecation.deprecated(**test[\"args\"])\n@@ -93,6 +112,8 @@ class Test_deprecated(unittest2.TestCase):\n \n self.assertEqual(len(caught_warnings), 1)\n self.assertEqual(caught_warnings[0].category, test[\"warning\"])\n+ self.assertEqual(str(caught_warnings[0].message),\n+ test[\"message\"])\n \n def test_DeprecatedWarning_not_raised(self):\n ret_val = \"lololol\"\n", "FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_warning_raised"]}], "all_FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_multiline_docstring", "tests/test_deprecation.py::Test_deprecated::test_warning_raised"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "hgrecco__pint-652_x2", "level": 2, "source": "swerebench", "repo": "hgrecco/pint", "image": "swerebench/sweb.eval.x86_64.hgrecco_1776_pint-652:latest", "base_commit": "0c4a9503b9fe00a62a90c33cb49cb047784766d3", "num_bugs": 2, "bugs": [{"instance_id": "hgrecco__pint-652", "base_commit": "0c4a9503b9fe00a62a90c33cb49cb047784766d3", "gold_patch": "diff --git a/docs/wrapping.rst b/docs/wrapping.rst\nindex a4913b3..dd9a39f 100644\n--- a/docs/wrapping.rst\n+++ b/docs/wrapping.rst\n@@ -148,6 +148,37 @@ airmass::\n def solar_position(lat, lon, press, tamb, timestamp):\n return zenith, azimuth, airmass\n \n+Optional arguments\n+------------------\n+\n+For a function with named keywords with optional values, use a tuple for all\n+arguments:\n+\n+.. doctest::\n+\n+ >>> @ureg.wraps(ureg.second, (ureg.meters, ureg.meters/ureg.second**2))\n+ ... def calculate_time_to_fall(height, gravity=Q_(9.8, 'm/s^2'), verbose=False):\n+ ... \"\"\"Calculate time to fall from a height h.\n+ ...\n+ ... By default, the gravity is assumed to be earth gravity,\n+ ... but it can be modified.\n+ ...\n+ ... d = .5 * g * t**2\n+ ... t = sqrt(2 * d / g)\n+ ... \"\"\"\n+ ... t = sqrt(2 * height / gravity)\n+ ... if verbose: print(str(t) + \" seconds to fall\")\n+ ... return t\n+ ...\n+ >>> lunar_module_height = Q_(22, 'feet') + Q_(11, 'inches')\n+ >>> calculate_time_to_fall(lunar_module_height, verbose=True)\n+ 1.1939473204801092 seconds to fall\n+ \n+ >>>\n+ >>> moon_gravity = Q_(1.625, 'm/s^2')\n+ >>> tcalculate_time_to_fall(lunar_module_height, moon_gravity)\n+ \n+\n \n Specifying relations between arguments\n --------------------------------------\n@@ -171,6 +202,19 @@ You can use more than one label:\n ... def some_function(x, y, z):\n ... pass\n \n+With optional arguments\n+\n+.. doctest::\n+\n+ >>> @ureg.wraps('=A*B', ('=A', '=B'))\n+ ... def get_displacement(time, rate=Q_(1, 'm/s')):\n+ ... return time * rate\n+ ...\n+ >>> get_displacement(Q_(2, 's'))\n+ \n+ >>> get_displacement(Q_(2, 's'), Q_(1, 'deg/s'))\n+ \n+\n \n Ignoring an argument or return value\n ------------------------------------\ndiff --git a/pint/registry_helpers.py b/pint/registry_helpers.py\nindex 1105038..4a8b862 100644\n--- a/pint/registry_helpers.py\n+++ b/pint/registry_helpers.py\n@@ -15,6 +15,12 @@ from .compat import string_types, zip_longest\n from .errors import DimensionalityError\n from .util import to_units_container, UnitsContainer\n \n+try:\n+ from inspect import signature\n+except ImportError:\n+ # Python2 does not have the inspect library. Import the backport.\n+ from funcsigs import signature\n+\n \n def _replace_units(original_units, values_by_name):\n \"\"\"Convert a unit compatible type to a UnitsContainer.\n@@ -165,6 +171,19 @@ def wraps(ureg, ret, args, strict=True):\n @functools.wraps(func, assigned=assigned, updated=updated)\n def wrapper(*values, **kw):\n \n+\n+ # Named keywords may have been left blank. Wherever the named keyword is blank,\n+ # fill it in with the default value.\n+ sig = signature(func)\n+ bound_arguments = sig.bind(*values, **kw)\n+\n+ for param in sig.parameters.values():\n+ if param.name not in bound_arguments.arguments:\n+ bound_arguments.arguments[param.name] = param.default\n+\n+ values = [bound_arguments.arguments[key] for key in sig.parameters.keys()]\n+ kw = {}\n+ \n # In principle, the values are used as is\n # When then extract the magnitudes when needed.\n new_values, values_by_name = converter(ureg, values, strict)\ndiff --git a/setup.py b/setup.py\nindex 354a79d..1bcae3c 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -60,4 +60,10 @@ setup(\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n- ])\n+ ],\n+ extras_require={\n+ ':python_version == \"2.7\"': [\n+ 'funcsigs',\n+ ],\n+ },\n+ )\n", "test_patch": "diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py\nindex 158fbe1..0cefce9 100644\n--- a/pint/testsuite/test_issues.py\n+++ b/pint/testsuite/test_issues.py\n@@ -571,3 +571,57 @@ class TestIssuesNP(QuantityTestCase):\n \n self.assertEqual(f(ureg.Quantity(1, '')), 2)\n self.assertRaises(DimensionalityError, f, ureg.Quantity(1, 'm'))\n+\n+ def test_issue625a(self):\n+ try:\n+ from inspect import signature\n+ except ImportError:\n+ # Python2 does not have the inspect library. Import the backport.\n+ from funcsigs import signature\n+\n+ ureg = UnitRegistry()\n+ Q_ = ureg.Quantity\n+ from math import sqrt\n+\n+ @ureg.wraps(ureg.second, (ureg.meters, ureg.meters/ureg.second**2))\n+ def calculate_time_to_fall(height, gravity=Q_(9.8, 'm/s^2')):\n+ \"\"\"Calculate time to fall from a height h with a default gravity.\n+\n+ By default, the gravity is assumed to be earth gravity,\n+ but it can be modified.\n+\n+ d = .5 * g * t**2\n+ t = sqrt(2 * d / g)\n+ \"\"\"\n+ return sqrt(2 * height / gravity)\n+\n+ lunar_module_height = Q_(10, 'm')\n+ t1 = calculate_time_to_fall(lunar_module_height)\n+ print(t1)\n+ self.assertAlmostEqual(t1, Q_(1.4285714285714286, 's'))\n+\n+ moon_gravity = Q_(1.625, 'm/s^2')\n+ t2 = calculate_time_to_fall(lunar_module_height, moon_gravity)\n+ self.assertAlmostEqual(t2, Q_(3.508232077228117, 's'))\n+\n+ def test_issue625b(self):\n+ try:\n+ from inspect import signature\n+ except ImportError:\n+ # Python2 does not have the inspect library. Import the backport.\n+ from funcsigs import signature\n+\n+ ureg = UnitRegistry()\n+ Q_ = ureg.Quantity\n+\n+ @ureg.wraps('=A*B', ('=A', '=B'))\n+ def get_displacement(time, rate=Q_(1, 'm/s')):\n+ \"\"\"Calculates displacement from a duration and default rate.\n+ \"\"\"\n+ return time * rate\n+\n+ d1 = get_displacement(Q_(2, 's'))\n+ self.assertAlmostEqual(d1, Q_(2, 'm'))\n+\n+ d2 = get_displacement(Q_(2, 's'), Q_(1, 'deg/s'))\n+ self.assertAlmostEqual(d2, Q_(2,' deg'))\n", "FAIL_TO_PASS": ["pint/testsuite/test_issues.py::TestIssuesNP::test_issue625a", "pint/testsuite/test_issues.py::TestIssuesNP::test_issue625b"]}, {"instance_id": "hgrecco__pint-658", "base_commit": "ba5cc0e76243c3e1e2b82999a71425ce3c6f3c1e", "gold_patch": "diff --git a/docs/wrapping.rst b/docs/wrapping.rst\nindex dd9a39f..6ce6411 100644\n--- a/docs/wrapping.rst\n+++ b/docs/wrapping.rst\n@@ -246,3 +246,12 @@ In the decorator format:\n ... def pendulum_period(length):\n ... return 2*math.pi*math.sqrt(length/G)\n \n+If you just want to check the dimensionality of a quantity, you can do so with the built-in 'check' function.\n+\n+.. doctest::\n+\n+ >>> distance = 1 * ureg.m\n+ >>> distance.check('[length]')\n+ True\n+ >>> distance.check('[time]')\n+ False\ndiff --git a/pint/quantity.py b/pint/quantity.py\nindex 88bfdac..ef25509 100644\n--- a/pint/quantity.py\n+++ b/pint/quantity.py\n@@ -294,6 +294,11 @@ class _Quantity(PrettyIPython, SharedRegistryObject):\n \n return self._dimensionality\n \n+ def check(self, dimension):\n+ \"\"\"Return true if the quantity's dimension matches passed dimension.\n+ \"\"\"\n+ return self.dimensionality == dimension\n+\n @classmethod\n def from_tuple(cls, tup):\n return cls(tup[0], UnitsContainer(tup[1]))\ndiff --git a/pint/registry_helpers.py b/pint/registry_helpers.py\nindex 4a8b862..5ac0dbd 100644\n--- a/pint/registry_helpers.py\n+++ b/pint/registry_helpers.py\n@@ -130,6 +130,20 @@ def _parse_wrap_args(args, registry=None):\n \n return _converter\n \n+def _apply_defaults(func, args, kwargs):\n+ \"\"\"Apply default keyword arguments.\n+\n+ Named keywords may have been left blank. This function applies the default\n+ values so that every argument is defined.\n+ \"\"\"\n+\n+ sig = signature(func)\n+ bound_arguments = sig.bind(*args)\n+ for param in sig.parameters.values():\n+ if param.name not in bound_arguments.arguments:\n+ bound_arguments.arguments[param.name] = param.default\n+ args = [bound_arguments.arguments[key] for key in sig.parameters.keys()]\n+ return args, {} \n \n def wraps(ureg, ret, args, strict=True):\n \"\"\"Wraps a function to become pint-aware.\n@@ -171,18 +185,7 @@ def wraps(ureg, ret, args, strict=True):\n @functools.wraps(func, assigned=assigned, updated=updated)\n def wrapper(*values, **kw):\n \n-\n- # Named keywords may have been left blank. Wherever the named keyword is blank,\n- # fill it in with the default value.\n- sig = signature(func)\n- bound_arguments = sig.bind(*values, **kw)\n-\n- for param in sig.parameters.values():\n- if param.name not in bound_arguments.arguments:\n- bound_arguments.arguments[param.name] = param.default\n-\n- values = [bound_arguments.arguments[key] for key in sig.parameters.keys()]\n- kw = {}\n+ values, kw = _apply_defaults(func, values, kw)\n \n # In principle, the values are used as is\n # When then extract the magnitudes when needed.\n@@ -228,13 +231,17 @@ def check(ureg, *args):\n \n @functools.wraps(func, assigned=assigned, updated=updated)\n def wrapper(*values, **kwargs):\n- for dim, value in zip_longest(dimensions, values):\n+ values, kwargs = _apply_defaults(func, values, kwargs)\n+ if len(dimensions) > len(values):\n+ raise TypeError(\"%s takes %i parameters, but %i dimensions were passed\"\n+ % (func.__name__, len(values), len(dimensions)))\n+ for dim, value in zip(dimensions, values):\n \n if dim is None:\n continue\n \n- val_dim = ureg.get_dimensionality(value)\n- if val_dim != dim:\n+ if not ureg.Quantity(value).check(dim):\n+ val_dim = ureg.get_dimensionality(value)\n raise DimensionalityError(value, 'a quantity of',\n val_dim, dim)\n return func(*values, **kwargs)\n", "test_patch": "diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py\nindex 0cefce9..4dbcb98 100644\n--- a/pint/testsuite/test_issues.py\n+++ b/pint/testsuite/test_issues.py\n@@ -625,3 +625,38 @@ class TestIssuesNP(QuantityTestCase):\n \n d2 = get_displacement(Q_(2, 's'), Q_(1, 'deg/s'))\n self.assertAlmostEqual(d2, Q_(2,' deg'))\n+\n+ def test_issue655a(self):\n+ ureg = UnitRegistry()\n+ distance = 1 * ureg.m\n+ time = 1 * ureg.s\n+ velocity = distance / time\n+ self.assertEqual(distance.check('[length]'), True)\n+ self.assertEqual(distance.check('[time]'), False)\n+ self.assertEqual(velocity.check('[length] / [time]'), True)\n+ self.assertEqual(velocity.check('1 / [time] * [length]'), True)\n+\n+ def test_issue(self):\n+ import math\n+ try:\n+ from inspect import signature\n+ except ImportError:\n+ # Python2 does not have the inspect library. Import the backport\n+ from funcsigs import signature\n+\n+ ureg = UnitRegistry()\n+ Q_ = ureg.Quantity\n+ @ureg.check('[length]', '[length]/[time]^2')\n+ def pendulum_period(length, G=Q_(1, 'standard_gravity')):\n+ print(length)\n+ return (2*math.pi*(length/G)**.5).to('s')\n+ l = 1 * ureg.m\n+ # Assume earth gravity\n+ t = pendulum_period(l)\n+ self.assertAlmostEqual(t, Q_('2.0064092925890407 second'))\n+ # Use moon gravity\n+ moon_gravity = Q_(1.625, 'm/s^2')\n+ t = pendulum_period(l, moon_gravity)\n+ self.assertAlmostEqual(t, Q_('4.928936075204336 second'))\n+\n+\ndiff --git a/pint/testsuite/test_unit.py b/pint/testsuite/test_unit.py\nindex 0e7b17f..b9e3b06 100644\n--- a/pint/testsuite/test_unit.py\n+++ b/pint/testsuite/test_unit.py\n@@ -437,13 +437,13 @@ class TestRegistry(QuantityTestCase):\n \n g2 = ureg.check('[speed]')(gfunc)\n self.assertRaises(DimensionalityError, g2, 3.0, 1)\n- self.assertRaises(DimensionalityError, g2, 2 * ureg.parsec)\n+ self.assertRaises(TypeError, g2, 2 * ureg.parsec)\n self.assertRaises(DimensionalityError, g2, 2 * ureg.parsec, 1.0)\n self.assertEqual(g2(2.0 * ureg.km / ureg.hour, 2), 1 * ureg.km / ureg.hour)\n \n g3 = ureg.check('[speed]', '[time]', '[mass]')(gfunc)\n- self.assertRaises(DimensionalityError, g3, 1 * ureg.parsec, 1 * ureg.angstrom)\n- self.assertRaises(DimensionalityError, g3, 1 * ureg.parsec, 1 * ureg.angstrom, 1 * ureg.kilogram)\n+ self.assertRaises(TypeError, g3, 1 * ureg.parsec, 1 * ureg.angstrom)\n+ self.assertRaises(TypeError, g3, 1 * ureg.parsec, 1 * ureg.angstrom, 1 * ureg.kilogram)\n \n def test_to_ref_vs_to(self):\n self.ureg.autoconvert_offset_to_baseunit = True\n", "FAIL_TO_PASS": ["pint/testsuite/test_unit.py::TestRegistry::test_check", "pint/testsuite/test_unit.py::TestRegistryWithDefaultRegistry::test_check"]}], "all_FAIL_TO_PASS": ["pint/testsuite/test_issues.py::TestIssuesNP::test_issue625a", "pint/testsuite/test_issues.py::TestIssuesNP::test_issue625b", "pint/testsuite/test_unit.py::TestRegistry::test_check", "pint/testsuite/test_unit.py::TestRegistryWithDefaultRegistry::test_check"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "kiwicom__structlog-sentry-18_x2", "level": 2, "source": "swerebench", "repo": "kiwicom/structlog-sentry", "image": "swerebench/sweb.eval.x86_64.kiwicom_1776_structlog-sentry-18:latest", "base_commit": "00ba79ef470ed81f4e396fde134f6612aa34551d", "num_bugs": 2, "bugs": [{"instance_id": "kiwicom__structlog-sentry-18", "base_commit": "00ba79ef470ed81f4e396fde134f6612aa34551d", "gold_patch": "diff --git a/README.md b/README.md\nindex f0cfe2f..7d67e81 100644\n--- a/README.md\n+++ b/README.md\n@@ -67,6 +67,12 @@ except RequestException:\n This will automatically collect `sys.exc_info()` along with the message, if you want\n to turn this behavior off, just pass `exc_info=False`.\n \n+When you want to use structlog's built-in\n+[`format_exc_info`](http://www.structlog.org/en/stable/api.html#structlog.processors.format_exc_info)\n+processor, make that the `SentryProcessor` comes *before* `format_exc_info`!\n+Otherwise, the `SentryProcessor` won't have an `exc_info` to work with, because\n+it's removed from the event by `format_exc_info`.\n+\n Logging calls with no `sys.exc_info()` are also automatically captured by Sentry:\n \n ```python\ndiff --git a/structlog_sentry/__init__.py b/structlog_sentry/__init__.py\nindex 8a5d041..d175653 100644\n--- a/structlog_sentry/__init__.py\n+++ b/structlog_sentry/__init__.py\n@@ -39,7 +39,7 @@ class SentryProcessor:\n \n :param event_dict: structlog event_dict\n \"\"\"\n- exc_info = event_dict.pop(\"exc_info\", True)\n+ exc_info = event_dict.get(\"exc_info\", True)\n if exc_info is True:\n # logger.exeception() or logger.error(exc_info=True)\n exc_info = sys.exc_info()\n", "test_patch": "diff --git a/test/test_sentry_processor.py b/test/test_sentry_processor.py\nindex 22ca188..39f69f3 100644\n--- a/test/test_sentry_processor.py\n+++ b/test/test_sentry_processor.py\n@@ -98,6 +98,27 @@ def test_sentry_log_failure_exc_info_true(mocker, level):\n assert kwargs[\"hint\"][\"exc_info\"][0] == ZeroDivisionError\n \n \n+def test_sentry_log_leave_exc_info_untouched(mocker):\n+ \"\"\"Make sure exc_info remains in event_data at the end of the processor.\n+\n+ The structlog built-in format_exc_info processor pops the key and formats\n+ it. Using SentryProcessor, and format_exc_info wasn't possible before,\n+ because the latter one didn't have an exc_info to work with.\n+\n+ https://github.com/kiwicom/structlog-sentry/issues/16\n+ \"\"\"\n+ mocker.patch(\"structlog_sentry.capture_event\")\n+\n+ event_data = {\"level\": \"warning\", \"event\": \"some.event\", \"exc_info\": True}\n+ processor = SentryProcessor()\n+ try:\n+ 1 / 0\n+ except ZeroDivisionError:\n+ processor(None, None, event_data)\n+\n+ assert \"exc_info\" in event_data\n+\n+\n @pytest.mark.parametrize(\"level\", [\"debug\", \"info\", \"warning\"])\n def test_sentry_log_no_extra(mocker, level):\n m_capture_event = mocker.patch(\"structlog_sentry.capture_event\")\n", "FAIL_TO_PASS": ["test/test_sentry_processor.py::test_sentry_log_leave_exc_info_untouched"]}, {"instance_id": "kiwicom__structlog-sentry-19", "base_commit": "2fcdc295d35e0425859fe304e7e6de21237affca", "gold_patch": "diff --git a/README.md b/README.md\nindex 7d67e81..e02f2f1 100644\n--- a/README.md\n+++ b/README.md\n@@ -31,6 +31,7 @@ sentry_sdk.init() # pass dsn in argument or via SENTRY_DSN env variable\n \n structlog.configure(\n processors=[\n+ structlog.stdlib.add_logger_name, # optional, but before SentryProcessor()\n structlog.stdlib.add_log_level, # required before SentryProcessor()\n SentryProcessor(level=logging.ERROR),\n ],\n@@ -42,8 +43,9 @@ structlog.configure(\n log = structlog.get_logger()\n ```\n \n-Do not forget to add the `structlog.stdlib.add_log_level` processor before\n-`SentryProcessor`. The `SentryProcessor` class takes the following arguments:\n+Do not forget to add the `structlog.stdlib.add_log_level` and optionally the\n+`structlog.stdlib.add_logger_name` processors before `SentryProcessor`. The\n+`SentryProcessor` class takes the following arguments:\n \n - `level` - events of this or higher levels will be reported to Sentry,\n default is `WARNING`\n@@ -95,6 +97,7 @@ You can set some or all of key/value pairs of structlog `event_dict` as sentry `\n ```python\n structlog.configure(\n processors=[\n+ structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n SentryProcessor(level=logging.ERROR, tag_keys=[\"city\", \"timezone\"]),\n ],...\n@@ -109,6 +112,7 @@ If you want to have all event data as tags, create the `SentryProcessor` with `t\n ```python\n structlog.configure(\n processors=[\n+ structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n SentryProcessor(level=logging.ERROR, tag_keys=\"__all__\"),\n ],...\n@@ -123,6 +127,7 @@ Sometimes you may want to skip this, specially when sending the `event_dict` as\n ```python\n structlog.configure(\n processors=[\n+ structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n SentryProcessor(level=logging.ERROR, as_extra=False, tag_keys=\"__all__\"),\n ],...\ndiff --git a/structlog_sentry/__init__.py b/structlog_sentry/__init__.py\nindex d175653..f63ce6b 100644\n--- a/structlog_sentry/__init__.py\n+++ b/structlog_sentry/__init__.py\n@@ -52,6 +52,8 @@ class SentryProcessor:\n \n event[\"message\"] = event_dict.get(\"event\")\n event[\"level\"] = event_dict.get(\"level\")\n+ if \"logger\" in event_dict:\n+ event[\"logger\"] = event_dict[\"logger\"]\n \n if self._as_extra:\n event[\"extra\"] = self._original_event_dict\n", "test_patch": "diff --git a/test/test_sentry_processor.py b/test/test_sentry_processor.py\nindex 39f69f3..a9d70e8 100644\n--- a/test/test_sentry_processor.py\n+++ b/test/test_sentry_processor.py\n@@ -98,6 +98,30 @@ def test_sentry_log_failure_exc_info_true(mocker, level):\n assert kwargs[\"hint\"][\"exc_info\"][0] == ZeroDivisionError\n \n \n+absent = object()\n+\n+\n+@pytest.mark.parametrize(\"logger\", [\"some.logger.name\", absent])\n+def test_sentry_add_logger_name(mocker, logger):\n+ m_capture_event = mocker.patch(\"structlog_sentry.capture_event\")\n+\n+ event_data = {\"level\": \"warning\", \"event\": \"some.event\"}\n+ if logger is not absent:\n+ event_data[\"logger\"] = logger\n+\n+ processor = SentryProcessor(as_extra=False)\n+ processor(None, None, event_data)\n+\n+ if logger is absent:\n+ m_capture_event.assert_called_once_with(\n+ {\"level\": \"warning\", \"message\": \"some.event\"}, hint=None\n+ )\n+ else:\n+ m_capture_event.assert_called_once_with(\n+ {\"level\": \"warning\", \"message\": \"some.event\", \"logger\": logger}, hint=None\n+ )\n+\n+\n def test_sentry_log_leave_exc_info_untouched(mocker):\n \"\"\"Make sure exc_info remains in event_data at the end of the processor.\n \n", "FAIL_TO_PASS": ["test/test_sentry_processor.py::test_sentry_add_logger_name[some.logger.name]"]}], "all_FAIL_TO_PASS": ["test/test_sentry_processor.py::test_sentry_log_leave_exc_info_untouched", "test/test_sentry_processor.py::test_sentry_add_logger_name[some.logger.name]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "janehmueller__python-json-config-48_x2", "level": 2, "source": "swerebench", "repo": "janehmueller/python-json-config", "image": "swerebench/sweb.eval.x86_64.janehmueller_1776_python-json-config-48:latest", "base_commit": "b1cf8cf5b3882d6a80881433cb692857afe948f6", "num_bugs": 2, "bugs": [{"instance_id": "janehmueller__python-json-config-48", "base_commit": "b1cf8cf5b3882d6a80881433cb692857afe948f6", "gold_patch": "diff --git a/python_json_config/__version__.py b/python_json_config/__version__.py\nindex c68196d..a955fda 100644\n--- a/python_json_config/__version__.py\n+++ b/python_json_config/__version__.py\n@@ -1,1 +1,1 @@\n-__version__ = \"1.2.0\"\n+__version__ = \"1.2.1\"\ndiff --git a/python_json_config/config_node.py b/python_json_config/config_node.py\nindex 9fb07b3..07a8d04 100644\n--- a/python_json_config/config_node.py\n+++ b/python_json_config/config_node.py\n@@ -144,11 +144,9 @@ class ConfigNode(object):\n prefixes = [prefix] if isinstance(prefix, str) else prefix\n for key in os.environ:\n for prefix in prefixes:\n- if key.startswith(prefix):\n+ if key.startswith(f\"{prefix}_\"):\n value = os.environ[key]\n- cleaned_key = key[len(prefix):]\n- if cleaned_key[0] == \"_\":\n- cleaned_key = cleaned_key[1:]\n+ cleaned_key = key[len(prefix) + 1:]\n cleaned_key = cleaned_key.lower().split(\"_\")\n self.update(path=cleaned_key, value=value, upsert=True)\n \n", "test_patch": "diff --git a/tests/config_builder_test.py b/tests/config_builder_test.py\nindex 6a6030d..e01fa54 100644\n--- a/tests/config_builder_test.py\n+++ b/tests/config_builder_test.py\n@@ -1,5 +1,4 @@\n import json\n-import os\n \n import pytest\n from jsonschema import ValidationError\n@@ -168,21 +167,15 @@ def test_optional_validation(path):\n \n \n def test_merge_env_variable():\n- prefix = \"PYTHONJSONCONFIG\"\n- variables = {f\"{prefix}_TESTVALUE1\": \"bla\", f\"{prefix}_TESTVALUE2\": \"1\"}\n- for key, value in variables.items():\n- os.environ[key] = value\n-\n+ prefix1 = \"PYTHONJSONCONFIG\"\n+ prefixes2 = [\"PREFIX1\", \"PREFIX2\"]\n builder = ConfigBuilder()\n- builder.merge_with_env_variables(prefix)\n- config = builder.parse_config({\"testvalue1\": \"blub\", \"testvalue3\": 5})\n \n- assert config.testvalue1 == \"bla\"\n- assert config.testvalue2 == \"1\"\n- assert config.testvalue3 == 5\n+ builder.merge_with_env_variables(prefix1)\n+ assert builder._ConfigBuilder__environment_variable_prefixes == [prefix1]\n \n- for key, value in variables.items():\n- del os.environ[key]\n+ builder.merge_with_env_variables(prefixes2)\n+ assert builder._ConfigBuilder__environment_variable_prefixes == [prefix1] + prefixes2\n \n \n def test_build_from_serialized_config(path):\ndiff --git a/tests/config_node/test_crud.py b/tests/config_node/test_crud.py\nindex 503e4c1..16737a7 100644\n--- a/tests/config_node/test_crud.py\n+++ b/tests/config_node/test_crud.py\n@@ -142,12 +142,16 @@ def test_merge_env_variable():\n for key, value in variables.items():\n os.environ[key] = value\n \n+ invalid_prefix = \"PYTHONJSONCONFIGTEST\"\n+ os.environ[invalid_prefix] = \"invalid\"\n+\n config = ConfigNode({\"testvalue1\": \"blub\", \"testvalue3\": 5})\n config.merge_with_env_variables(prefix)\n \n assert config.testvalue1 == \"bla\"\n assert config.testvalue2 == \"1\"\n assert config.testvalue3 == 5\n+ assert \"test\" not in config\n \n for key, value in variables.items():\n del os.environ[key]\n", "FAIL_TO_PASS": ["tests/config_node/test_crud.py::test_merge_env_variable"]}, {"instance_id": "janehmueller__python-json-config-53", "base_commit": "c80d515a9139f13671cc41408dad3660cc0c4686", "gold_patch": "diff --git a/python_json_config/config_node.py b/python_json_config/config_node.py\nindex 07a8d04..ce524d2 100644\n--- a/python_json_config/config_node.py\n+++ b/python_json_config/config_node.py\n@@ -5,7 +5,7 @@ from typing import List, Union, Tuple\n \n import msgpack\n \n-from .utils import normalize_path\n+from .utils import normalize_path, parse_env_variable_name\n \n \n class ConfigNode(object):\n@@ -20,7 +20,7 @@ class ConfigNode(object):\n :param config_dict: Source dictionary containing the part of the config that will be in this node and its\n children. Each dictionary value in this dictionary will become another ConfigNode that is\n a child of this node.\n- :param path: The access path to this node, i.e. the config keys that are used to access thos node.\n+ :param path: The access path to this node, i.e. the config keys that are used to access this node.\n :param strict_access: If True, an error will be thrown if a non-existing field is accessed. If False,\n None will be returned instead.\n :param required_fields: A list of field names, for which an error will be thrown if they are accessed but don't\n@@ -146,8 +146,7 @@ class ConfigNode(object):\n for prefix in prefixes:\n if key.startswith(f\"{prefix}_\"):\n value = os.environ[key]\n- cleaned_key = key[len(prefix) + 1:]\n- cleaned_key = cleaned_key.lower().split(\"_\")\n+ cleaned_key = parse_env_variable_name(key[len(prefix) + 1:])\n self.update(path=cleaned_key, value=value, upsert=True)\n \n \"\"\"\ndiff --git a/python_json_config/utils.py b/python_json_config/utils.py\nindex 555be79..b6c885a 100644\n--- a/python_json_config/utils.py\n+++ b/python_json_config/utils.py\n@@ -1,3 +1,4 @@\n+import re\n from typing import Union, List\n \n \n@@ -5,3 +6,32 @@ def normalize_path(path: Union[str, List[str]]) -> List[str]:\n if isinstance(path, str):\n path = path.split(\".\")\n return path\n+\n+\n+def parse_env_variable_name(variable: str) -> List[str]:\n+ \"\"\"\n+ Parse the name of an environment variable into a config path. Underscores in the names of variables are escaped with\n+ an extra underscore. (E.g., the field test_value will be set by the variable TEST__VALUE).\n+ :param variable: the name of the environment variable\n+ :return: the path extracted from the name of the environment variable\n+ \"\"\"\n+ # Split only on single underscores\n+ split_variable = re.split(\"([^_]+)_([^_]+)\", variable.lower())\n+ path = [element for element in split_variable if element]\n+\n+ # If the path contains single elements only consisting of underscores, join the previous and next element together.\n+ # (e.g., [\"test\", \"__\", \"value\"] becomes [\"test__value\"])\n+ underscore_indices = [i for i, item in enumerate(path) if re.search(\"^_+$\", item)]\n+ for index in underscore_indices:\n+ path[index - 1:index + 2] = [\"\".join(path[index - 1:index + 2])]\n+\n+ # Remove the extra underscore from names containing underscores (that was used to escape the underscore).\n+ # (e.g., [\"test__value\"] becomes [\"test_value\"])\n+ for index, element in enumerate(path):\n+ if \"_\" in element:\n+ underscore_match = re.search(\"[_]+\", element)\n+ underscores = underscore_match.group(0)\n+ if len(underscores) > 1:\n+ path[index] = element.replace(underscores, underscores[:-1])\n+\n+ return path\n", "test_patch": "diff --git a/tests/config_node/test_crud.py b/tests/config_node/test_crud.py\nindex 16737a7..764e339 100644\n--- a/tests/config_node/test_crud.py\n+++ b/tests/config_node/test_crud.py\n@@ -155,3 +155,28 @@ def test_merge_env_variable():\n \n for key, value in variables.items():\n del os.environ[key]\n+\n+\n+def test_merge_env_variable_underscore_name():\n+ prefix = \"PYTHONJSONCONFIG\"\n+ variables = {\n+ f\"{prefix}_TEST__VALUE1\": \"bla\",\n+ f\"{prefix}_TEST_VALUE2\": \"1\",\n+ f\"{prefix}_TEST_TEST2__VALUES_VALUE2\": \"3\"\n+ }\n+ for key, value in variables.items():\n+ os.environ[key] = value\n+\n+ config = ConfigNode({\"test_value1\": \"blub\",\n+ \"test\": {\n+ \"value2\": \"5\",\n+ \"test2_values\": {\"value2\": 1}\n+ }})\n+ config.merge_with_env_variables(prefix)\n+\n+ assert config.test_value1 == \"bla\"\n+ assert config.test.value2 == \"1\"\n+ assert config.test.test2_values.value2 == \"3\"\n+\n+ for key, value in variables.items():\n+ del os.environ[key]\n", "FAIL_TO_PASS": ["tests/config_node/test_crud.py::test_merge_env_variable_underscore_name"]}], "all_FAIL_TO_PASS": ["tests/config_node/test_crud.py::test_merge_env_variable", "tests/config_node/test_crud.py::test_merge_env_variable_underscore_name"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "just-work__fffw-64_x2", "level": 2, "source": "swerebench", "repo": "just-work/fffw", "image": "swerebench/sweb.eval.x86_64.just-work_1776_fffw-64:latest", "base_commit": "fefda959ec043f1869b38026fc3c8a9679bf45bc", "num_bugs": 2, "bugs": [{"instance_id": "just-work__fffw-64", "base_commit": "fefda959ec043f1869b38026fc3c8a9679bf45bc", "gold_patch": "diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py\nindex bd06ae6..ff1baa2 100644\n--- a/fffw/encoding/filters.py\n+++ b/fffw/encoding/filters.py\n@@ -1,4 +1,4 @@\n-from dataclasses import dataclass, replace, asdict, field\n+from dataclasses import dataclass, replace, asdict, field, fields\n from typing import Union, List, cast\n \n from fffw.graph import base\n@@ -91,7 +91,8 @@ class Filter(mixins.StreamValidationMixin, base.Node, Params):\n \n Inputs and outputs are not copied.\n \"\"\"\n- kwargs = asdict(self)\n+ skip = [f.name for f in fields(self) if not f.init]\n+ kwargs = {k: v for k, v in asdict(self).items() if k not in skip}\n # noinspection PyArgumentList\n return type(self)(**kwargs) # type: ignore\n \n", "test_patch": "diff --git a/tests/test_vector.py b/tests/test_vector.py\nindex 50794cd..bc4e8c8 100644\n--- a/tests/test_vector.py\n+++ b/tests/test_vector.py\n@@ -1,4 +1,4 @@\n-from dataclasses import dataclass, replace\n+from dataclasses import dataclass, replace, asdict\n from typing import cast, Tuple\n \n from fffw.encoding import *\n@@ -373,3 +373,17 @@ class VectorTestCase(BaseTestCase):\n '-c:a', 'libfdk_aac',\n 'output2.mp5'\n )\n+\n+ def test_clone_filter_with_skipped_params(self):\n+ \"\"\"\n+ A filter with `init=False` param is cloned correctly.\n+ \"\"\"\n+ @dataclass\n+ class MyFilter(filters.VideoFilter):\n+ my_flag: bool = param(init=False, default=True)\n+\n+ f = MyFilter()\n+\n+ cloned = f._clone()\n+\n+ self.assertTrue(asdict(cloned)['my_flag'])\n", "FAIL_TO_PASS": ["tests/test_vector.py::VectorTestCase::test_clone_filter_with_skipped_params"]}, {"instance_id": "just-work__fffw-68", "base_commit": "ec1451b6347ac0c9a8da3947651d7b15ebf0212d", "gold_patch": "diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py\nindex ff1baa2..1ef1505 100644\n--- a/fffw/encoding/filters.py\n+++ b/fffw/encoding/filters.py\n@@ -3,7 +3,7 @@ from typing import Union, List, cast\n \n from fffw.graph import base\n from fffw.encoding import mixins\n-from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO\n+from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO, AudioMeta\n from fffw.graph.meta import StreamType, Device\n from fffw.wrapper.params import Params, param\n \n@@ -330,16 +330,26 @@ class Concat(Filter):\n duration = TS(0)\n scenes = []\n streams: List[str] = []\n+ samples = 0\n+ sampling_rate = None\n for meta in metadata:\n duration += meta.duration\n+ if isinstance(meta, AudioMeta):\n+ samples += meta.samples\n+ if sampling_rate is None:\n+ sampling_rate = meta.sampling_rate\n+ else:\n+ assert sampling_rate == meta.sampling_rate\n scenes.extend(meta.scenes)\n for stream in meta.streams:\n if not streams or streams[-1] != stream:\n # Add all streams for each concatenated metadata and remove\n # contiguous duplicates.\n streams.append(stream)\n- return replace(metadata[0], duration=duration,\n- scenes=scenes, streams=streams)\n+ kwargs = dict(duration=duration, scenes=scenes, streams=streams)\n+ if samples != 0:\n+ kwargs['samples'] = samples\n+ return replace(metadata[0], **kwargs)\n \n \n @dataclass\n", "test_patch": "diff --git a/tests/test_graph.py b/tests/test_graph.py\nindex 5e82f6e..905464c 100644\n--- a/tests/test_graph.py\n+++ b/tests/test_graph.py\n@@ -35,7 +35,10 @@ class FilterGraphTestCase(TestCase):\n par=1.0,\n duration=300.0,\n )\n- self.audio_metadata = audio_meta_data()\n+ self.audio_metadata = audio_meta_data(\n+ duration=200.0,\n+ sampling_rate=48000,\n+ samples_count=200*48000)\n \n self.source = inputs.Input(\n input_file='input.mp4',\n@@ -239,6 +242,25 @@ class FilterGraphTestCase(TestCase):\n self.assertEqual(self.video_metadata.duration + vs.meta.duration,\n vm.duration)\n \n+ def test_concat_audio_metadata(self):\n+ \"\"\"\n+ Concat filter sums samples count for audio streams.\n+ \"\"\"\n+ audio_meta = audio_meta_data(duration=1000.0, sampling_rate=48000,\n+ samples_count=48000 * 1000)\n+ a = inputs.Stream(AUDIO, meta=audio_meta)\n+ self.input_list.append(inputs.input_file('second.mp4', a))\n+ concat = a | Concat(AUDIO)\n+ self.source | concat\n+\n+ concat > self.output\n+\n+ am = cast(AudioMeta, self.output.codecs[-1].get_meta_data())\n+ self.assertEqual(self.audio_metadata.duration + audio_meta.duration,\n+ am.duration)\n+ self.assertEqual(self.audio_metadata.samples + audio_meta.samples,\n+ am.samples)\n+\n def test_trim_metadata(self):\n \"\"\"\n Trim filter sets start and changes stream duration.\n", "FAIL_TO_PASS": ["tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata"]}], "all_FAIL_TO_PASS": ["tests/test_vector.py::VectorTestCase::test_clone_filter_with_skipped_params", "tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NREL__hescore-hpxml-163_x2", "level": 2, "source": "swerebench", "repo": "NREL/hescore-hpxml", "image": "swerebench/sweb.eval.x86_64.nrel_1776_hescore-hpxml-163:latest", "base_commit": "37a5e1e821fd3c625e082336a1a7219697f0220e", "num_bugs": 2, "bugs": [{"instance_id": "NREL__hescore-hpxml-163", "base_commit": "37a5e1e821fd3c625e082336a1a7219697f0220e", "gold_patch": "diff --git a/docs/source/translation/hvac_distribution.rst b/docs/source/translation/hvac_distribution.rst\nindex 12766e8e..3676c227 100644\n--- a/docs/source/translation/hvac_distribution.rst\n+++ b/docs/source/translation/hvac_distribution.rst\n@@ -81,8 +81,8 @@ Duct Insulation\n \n If the any of the ``Ducts`` elements in a particular\n :ref:`location ` have a ``DuctInsulationRValue`` or\n-``DuctInsulationThickness`` that is greater than zero, all of the ducts in that\n-location are considered insulated.\n+``DuctInsulationThickness`` that is greater than zero or have a ``DuctInsulationMaterial`` that is not ``None``, \n+all of the ducts in that location are considered insulated.\n \n Duct Sealing\n ************\ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 55b7e4ee..58119ed2 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -577,7 +577,8 @@ class HPXMLtoHEScoreTranslatorBase(object):\n duct_fracs_by_hescore_duct_loc[hescore_duct_location] += frac_duct_area\n \n # Duct Insulation\n- duct_has_ins = self.xpath(duct_el, 'h:DuctInsulationRValue > 0 or h:DuctInsulationThickness > 0')\n+ duct_has_ins = self.xpath(duct_el, 'h:DuctInsulationRValue > 0 or h:DuctInsulationThickness > 0 or\\\n+ count(h:DuctInsulationMaterial[not(h:None)]) > 0')\n hescore_duct_loc_has_insulation[hescore_duct_location] = \\\n hescore_duct_loc_has_insulation[hescore_duct_location] or duct_has_ins\n \n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex dab1f7eb..2c401201 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -3042,6 +3042,70 @@ class TestHEScoreV3(unittest.TestCase, ComparatorBase):\n d_v3 = tr_v3.hpxml_to_hescore()\n self.assertEqual(d_v3['building']['systems']['hvac'][0]['hvac_distribution'][0]['location'], 'unvented_crawl')\n \n+ def test_v3_duct_insulation(self):\n+ tr = self._load_xmlfile('hescore_min_v3')\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], False)\n+\n+ E = self.element_maker()\n+ el = self.xpath('//h:Ducts/h:DuctLocation')\n+ duct_ins_mat = E.DuctInsulationMaterial(\n+ E.Batt('unknown')\n+ )\n+ el.addprevious(duct_ins_mat)\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], True)\n+ el.getparent().remove(duct_ins_mat)\n+\n+ duct_ins_mat = E.DuctInsulationMaterial(\n+ E.LooseFill('unknown')\n+ )\n+ el.addprevious(duct_ins_mat)\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], True)\n+ el.getparent().remove(duct_ins_mat)\n+\n+ duct_ins_mat = E.DuctInsulationMaterial(\n+ E.Rigid('unknown')\n+ )\n+ el.addprevious(duct_ins_mat)\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], True)\n+ el.getparent().remove(duct_ins_mat)\n+\n+ duct_ins_mat = E.DuctInsulationMaterial(\n+ E.SprayFoam('unknown')\n+ )\n+ el.addprevious(duct_ins_mat)\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], True)\n+ el.getparent().remove(duct_ins_mat)\n+\n+ duct_ins_mat = E.DuctInsulationMaterial(\n+ E.Other()\n+ )\n+ el.addprevious(duct_ins_mat)\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], True)\n+ el.getparent().remove(duct_ins_mat)\n+\n+ none_type = getattr(E, 'None')\n+ duct_ins_mat = E.DuctInsulationMaterial(\n+ none_type\n+ )\n+ el.addprevious(duct_ins_mat)\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], False)\n+ el.getparent().remove(duct_ins_mat)\n+\n+ duct_ins_mat = E.DuctInsulationMaterial(\n+ E.Unknown()\n+ )\n+ el.addprevious(duct_ins_mat)\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building']['systems']['hvac'][0]['hvac_distribution'][0]['insulated'], True)\n+ el.getparent().remove(duct_ins_mat)\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestHEScoreV3::test_v3_duct_insulation"]}, {"instance_id": "NREL__hescore-hpxml-169", "base_commit": "974933e77b66154cc2302c553374006d7151a15c", "gold_patch": "diff --git a/docs/source/translation/building_address.rst b/docs/source/translation/building_address.rst\nindex 33449491..8fdf52c7 100644\n--- a/docs/source/translation/building_address.rst\n+++ b/docs/source/translation/building_address.rst\n@@ -33,8 +33,10 @@ format for HEScore.\n \n HPXML allows for two lines of address elements. If both are used, the lines will\n be concatenated with a space between for submission to the HEScore\n-``building_address.address`` field. All of the HPXML elements shown in the\n-above code snippet are required with the exception of ``Address2``\n+``building_address.address`` field. All of the HPXML elements shown in the above\n+code snippet are required with the exception of ``Address2``. Additionally, if a\n+zip plus 4 code is entered in HPXML, it will be trimmed to just the 5 digit zip\n+code before being passed to HEScore.\n \n .. _assessment-type-mapping:\n \ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex bfb1f4d5..169a39dd 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -816,7 +816,8 @@ class HPXMLtoHEScoreTranslatorBase(object):\n raise ElementNotFoundError(hpxmladdress, 'h:Address1/text() | h:Address2/text()', {})\n bldgaddr['city'] = xpath(b, 'h:Site/h:Address/h:CityMunicipality/text()', raise_err=True)\n bldgaddr['state'] = xpath(b, 'h:Site/h:Address/h:StateCode/text()', raise_err=True)\n- bldgaddr['zip_code'] = xpath(b, 'h:Site/h:Address/h:ZipCode/text()', raise_err=True)\n+ hpxml_zipcode = xpath(b, 'h:Site/h:Address/h:ZipCode/text()', raise_err=True)\n+ bldgaddr['zip_code'] = re.match(r\"([0-9]{5})(-[0-9]{4})?\", hpxml_zipcode).group(1)\n transaction_type = xpath(self.hpxmldoc, 'h:XMLTransactionHeaderInformation/h:Transaction/text()')\n is_mentor = xpath(b, 'boolean(h:ProjectStatus/h:extension/h:HEScoreMentorAssessment)')\n if is_mentor:\n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 117daa04..ff02c0ff 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -3048,6 +3048,14 @@ class TestHEScore2021Updates(unittest.TestCase, ComparatorBase):\n self.assertEqual(res3['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n self.assertFalse(res3['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n \n+ def test_zip_plus4(self):\n+ tr = self._load_xmlfile('hescore_min_v3')\n+ el = self.xpath('//h:ZipCode')\n+ orig_zipcode = str(el.text)\n+ el.text = el.text + '-1234'\n+ res = tr.hpxml_to_hescore()\n+ self.assertEqual(res['building_address']['zip_code'], orig_zipcode)\n+\n \n class TestHEScoreV3(unittest.TestCase, ComparatorBase):\n \n", "FAIL_TO_PASS": ["tests/test_translation.py::TestHEScore2021Updates::test_zip_plus4"]}], "all_FAIL_TO_PASS": ["tests/test_translation.py::TestHEScoreV3::test_v3_duct_insulation", "tests/test_translation.py::TestHEScore2021Updates::test_zip_plus4"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ESSS__oop-ext-21_x2", "level": 2, "source": "swerebench", "repo": "ESSS/oop-ext", "image": "swerebench/sweb.eval.x86_64.esss_1776_oop-ext-21:latest", "base_commit": "00000f0c728003d078fa48a7a0b121725326d491", "num_bugs": 2, "bugs": [{"instance_id": "ESSS__oop-ext-21", "base_commit": "00000f0c728003d078fa48a7a0b121725326d491", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex f98b109..41e5a14 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -1,6 +1,11 @@\n-0.5.0 (2019-12-12)\n+0.5.1 (2019-12-20)\n ==================\n \n+* Fixes an issue (#20) where mocked `classmethods` weren't considered a valid method during internal checks.\n+\n+0.5.0 (2019-12-12)\n+------------------\n+\n * Add optional argument ``requires_declaration`` so users can decide whether or not ``@ImplementsInterface`` declarations are necessary.\n \n 0.4.0 (2019-12-03)\ndiff --git a/src/oop_ext/interface/_interface.py b/src/oop_ext/interface/_interface.py\nindex c84ffa2..5fd1ffa 100644\n--- a/src/oop_ext/interface/_interface.py\n+++ b/src/oop_ext/interface/_interface.py\n@@ -590,10 +590,13 @@ def _IsMethod(member):\n 3) instances of Method (should it be implementors of \"IMethod\"?)\n \n \"\"\"\n+ from unittest import mock\n+\n return (\n inspect.isfunction(member)\n or inspect.ismethod(member)\n or isinstance(member, Method)\n+ or isinstance(member, mock.MagicMock)\n )\n \n \n", "test_patch": "diff --git a/src/oop_ext/interface/_tests/test_interface.py b/src/oop_ext/interface/_tests/test_interface.py\nindex 60bcc10..8beb611 100644\n--- a/src/oop_ext/interface/_tests/test_interface.py\n+++ b/src/oop_ext/interface/_tests/test_interface.py\n@@ -814,11 +814,13 @@ def test_interface_subclass_mocked(mocker, check_before, autospec):\n pass\n \n if check_before:\n- interface.IsImplementation(Bar, II)\n+ interface.IsImplementation(Bar, II, requires_declaration=False)\n+ interface.IsImplementation(Bar, II, requires_declaration=True)\n \n mocker.patch.object(Foo, \"foo\", autospec=autospec)\n \n- assert interface.IsImplementation(Bar, II) == (autospec or check_before)\n+ assert interface.IsImplementation(Bar, II, requires_declaration=False)\n+ assert interface.IsImplementation(Bar, II, requires_declaration=True)\n \n \n def testErrorOnInterfaceDeclaration():\n@@ -882,3 +884,23 @@ def testIsImplementationOfAny():\n AssertImplements(a_obj, _InterfM3)\n assert IsImplementationOfAny(A, [_InterfM1, _InterfM2, _InterfM3, _InterfM4])\n assert not IsImplementationOfAny(A, [_InterfM1, _InterfM2, _InterfM4])\n+\n+\n+def testClassMethodBug(mocker):\n+ \"\"\"\n+ Issue #20\n+ \"\"\"\n+\n+ class IFoo(Interface):\n+ @classmethod\n+ def foo(cls):\n+ \"\"\n+\n+ @ImplementsInterface(IFoo)\n+ class FooImplementation:\n+ @classmethod\n+ def foo(cls):\n+ \"\"\n+\n+ mocker.spy(FooImplementation, \"foo\")\n+ AssertImplements(FooImplementation, IFoo, requires_declaration=True)\n", "FAIL_TO_PASS": ["src/oop_ext/interface/_tests/test_interface.py::test_interface_subclass_mocked[False-False]", "src/oop_ext/interface/_tests/test_interface.py::testClassMethodBug"]}, {"instance_id": "ESSS__oop-ext-23", "base_commit": "a6b298e39a84fdc2344ca36857d3e31a0b741b29", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 41e5a14..0de729f 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -1,6 +1,11 @@\n-0.5.1 (2019-12-20)\n+0.6.0 (2020-01-31)\n ==================\n \n+* Change back the default value of ``requires_declaration`` to ``True`` and fix an error (#22) where the cache wasn 't properly cleared.\n+\n+0.5.1 (2019-12-20)\n+------------------\n+\n * Fixes an issue (#20) where mocked `classmethods` weren't considered a valid method during internal checks.\n \n 0.5.0 (2019-12-12)\ndiff --git a/src/oop_ext/interface/_interface.py b/src/oop_ext/interface/_interface.py\nindex 5fd1ffa..d87f910 100644\n--- a/src/oop_ext/interface/_interface.py\n+++ b/src/oop_ext/interface/_interface.py\n@@ -191,7 +191,7 @@ def _IsClass(obj):\n return isinstance(obj, type)\n \n \n-def IsImplementation(class_or_instance, interface, *, requires_declaration=False):\n+def IsImplementation(class_or_instance, interface, *, requires_declaration=True):\n \"\"\"\n :type class_or_instance: type or classobj or object\n \n@@ -199,9 +199,11 @@ def IsImplementation(class_or_instance, interface, *, requires_declaration=False\n \n :type requires_declaration: bool\n If `True`, the Interface must have been explicitly declared through :py:func:`ImplementsInterface`\n- for `class_or_interface` to be considered an implementation of `interface`. Alternatively, it's\n- possible to use :py:func:`DeclareClassImplements` from outside the class in order to tell that\n- interfaces are implemented.\n+ for `class_or_interface` to be considered an implementation of `interface`. Otherwise it'd only\n+ check if `class_or_interface` has all methods defined on `interface`.\n+ Note that `class_or_instance` attributes are never evaluated.\n+ Alternatively, it's possible to use :py:func:`DeclareClassImplements` from outside the class in\n+ order to tell which interfaces are implemented.\n \n :rtype: bool\n \n@@ -225,7 +227,7 @@ def IsImplementation(class_or_instance, interface, *, requires_declaration=False\n return is_implementation\n \n \n-def IsImplementationOfAny(class_or_instance, interfaces, *, requires_declaration=False):\n+def IsImplementationOfAny(class_or_instance, interfaces, *, requires_declaration=True):\n \"\"\"\n Check if the class or instance implements any of the given interfaces\n \n@@ -252,7 +254,7 @@ def IsImplementationOfAny(class_or_instance, interfaces, *, requires_declaration\n return False\n \n \n-def AssertImplements(class_or_instance, interface, *, requires_declaration=False):\n+def AssertImplements(class_or_instance, interface, *, requires_declaration=True):\n \"\"\"\n If given a class, will try to match the class against a given interface. If given an object\n (instance), will try to match the class of the given object.\n@@ -309,7 +311,7 @@ __ImplementsCache = __ResultsCache()\n __ImplementedInterfacesCache = __ResultsCache()\n \n \n-def _CheckIfClassImplements(class_, interface, *, requires_declaration=False):\n+def _CheckIfClassImplements(class_, interface, *, requires_declaration=True):\n \"\"\"\n :type class_: type or classobj\n :param class_:\n@@ -863,10 +865,11 @@ def DeclareClassImplements(class_, *interfaces):\n try:\n for interface in interfaces:\n # Forget any previous checks\n- __ImplementsCache.ForgetResult((class_, interface))\n+ __ImplementsCache.ForgetResult((class_, interface, False))\n+ __ImplementsCache.ForgetResult((class_, interface, True))\n __ImplementedInterfacesCache.ForgetResult(class_)\n \n- AssertImplements(class_, interface)\n+ AssertImplements(class_, interface, requires_declaration=False)\n except:\n # Roll back...\n class_.__implements__ = old_implements\n", "test_patch": "diff --git a/src/oop_ext/interface/_tests/test_interface.py b/src/oop_ext/interface/_tests/test_interface.py\nindex 8beb611..737a454 100644\n--- a/src/oop_ext/interface/_tests/test_interface.py\n+++ b/src/oop_ext/interface/_tests/test_interface.py\n@@ -72,7 +72,7 @@ def testBasics():\n \n assert IsImplementation(C, I) == True # OK\n # C2 shouldn't need to declare `@ImplementsInterface(I)`\n- assert IsImplementation(C2, I) == True\n+ assert IsImplementation(C2, I, requires_declaration=False) == True\n assert IsImplementation(C2, I, requires_declaration=True) == False\n assert not IsImplementation(D, I) == True # nope\n \n@@ -87,7 +87,9 @@ def testBasics():\n # Now declare that C2 implements I\n DeclareClassImplements(C2, I)\n \n- assert IsImplementation(C2, I) == True # Does not declare\n+ assert (\n+ IsImplementation(C2, I, requires_declaration=True) == True\n+ ) # Even if it doesn't declare\n \n \n def testMissingMethod():\n@@ -514,12 +516,16 @@ def testAdaptableInterface():\n \n \n def testNull():\n- AssertImplements(Null(), _InterfM2) # Not raises BadImplementationError\n+ AssertImplements(\n+ Null(), _InterfM2, requires_declaration=False\n+ ) # Not raises BadImplementationError\n \n class ExtendedNull(Null):\n \"\"\n \n- AssertImplements(ExtendedNull(), _InterfM2) # Not raises BadImplementationError\n+ AssertImplements(\n+ ExtendedNull(), _InterfM2, requires_declaration=False\n+ ) # Not raises BadImplementationError\n \n \n def testSetItem():\n@@ -575,7 +581,7 @@ def testImplementorWithAny():\n def m3(self, *args, **kwargs):\n \"\"\n \n- AssertImplements(M3(), _InterfM3)\n+ AssertImplements(M3(), _InterfM3, requires_declaration=False)\n \n \n def testInterfaceCheckRequiresInterface():\n@@ -687,7 +693,7 @@ def testDeclareClassImplements():\n with pytest.raises(AssertionError):\n DeclareClassImplements(C0, I1)\n \n- assert IsImplementation(C1, I1) == True\n+ assert IsImplementation(C1, I1, requires_declaration=False) == True\n \n DeclareClassImplements(C1, I1)\n \n@@ -881,9 +887,13 @@ def testIsImplementationOfAny():\n \"\"\n \n a_obj = A()\n- AssertImplements(a_obj, _InterfM3)\n- assert IsImplementationOfAny(A, [_InterfM1, _InterfM2, _InterfM3, _InterfM4])\n- assert not IsImplementationOfAny(A, [_InterfM1, _InterfM2, _InterfM4])\n+ AssertImplements(a_obj, _InterfM3, requires_declaration=False)\n+ assert IsImplementationOfAny(\n+ A, [_InterfM1, _InterfM2, _InterfM3, _InterfM4], requires_declaration=False\n+ )\n+ assert not IsImplementationOfAny(\n+ A, [_InterfM1, _InterfM2, _InterfM4], requires_declaration=False\n+ )\n \n \n def testClassMethodBug(mocker):\n", "FAIL_TO_PASS": ["src/oop_ext/interface/_tests/test_interface.py::testBasics"]}], "all_FAIL_TO_PASS": ["src/oop_ext/interface/_tests/test_interface.py::test_interface_subclass_mocked[False-False]", "src/oop_ext/interface/_tests/test_interface.py::testClassMethodBug", "src/oop_ext/interface/_tests/test_interface.py::testBasics"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "GenericMappingTools__pygmt-1484_x2", "level": 2, "source": "swerebench", "repo": "GenericMappingTools/pygmt", "image": "swerebench/sweb.eval.x86_64.genericmappingtools_1776_pygmt-1484:latest", "base_commit": "4163497b9a12bcfc35b337ced20dde9afae10ce7", "num_bugs": 2, "bugs": [{"instance_id": "GenericMappingTools__pygmt-1484", "base_commit": "4163497b9a12bcfc35b337ced20dde9afae10ce7", "gold_patch": "diff --git a/pygmt/clib/conversion.py b/pygmt/clib/conversion.py\nindex 24c6c447..57b2f92c 100644\n--- a/pygmt/clib/conversion.py\n+++ b/pygmt/clib/conversion.py\n@@ -82,7 +82,7 @@ def dataarray_to_matrix(grid):\n \"\"\"\n if len(grid.dims) != 2:\n raise GMTInvalidInput(\n- \"Invalid number of grid dimensions '{}'. Must be 2.\".format(len(grid.dims))\n+ f\"Invalid number of grid dimensions '{len(grid.dims)}'. Must be 2.\"\n )\n # Extract region and inc from the grid\n region = []\n@@ -96,9 +96,11 @@ def dataarray_to_matrix(grid):\n coord_inc = coord_incs[0]\n if not np.allclose(coord_incs, coord_inc):\n raise GMTInvalidInput(\n- \"Grid appears to have irregular spacing in the '{}' dimension.\".format(\n- dim\n- )\n+ f\"Grid appears to have irregular spacing in the '{dim}' dimension.\"\n+ )\n+ if coord_inc == 0:\n+ raise GMTInvalidInput(\n+ f\"Grid has a zero increment in the '{dim}' dimension.\"\n )\n region.extend(\n [\n", "test_patch": "diff --git a/pygmt/tests/test_clib.py b/pygmt/tests/test_clib.py\nindex 4f2b8f4a..f31a28fc 100644\n--- a/pygmt/tests/test_clib.py\n+++ b/pygmt/tests/test_clib.py\n@@ -743,6 +743,24 @@ def test_dataarray_to_matrix_inc_fails():\n dataarray_to_matrix(grid)\n \n \n+def test_dataarray_to_matrix_zero_inc_fails():\n+ \"\"\"\n+ Check that dataarray_to_matrix fails for zero increments grid.\n+ \"\"\"\n+ data = np.ones((5, 5), dtype=\"float32\")\n+ x = np.linspace(0, 1, 5)\n+ y = np.zeros_like(x)\n+ grid = xr.DataArray(data, coords=[(\"y\", y), (\"x\", x)])\n+ with pytest.raises(GMTInvalidInput):\n+ dataarray_to_matrix(grid)\n+\n+ y = np.linspace(0, 1, 5)\n+ x = np.zeros_like(x)\n+ grid = xr.DataArray(data, coords=[(\"y\", y), (\"x\", x)])\n+ with pytest.raises(GMTInvalidInput):\n+ dataarray_to_matrix(grid)\n+\n+\n def test_get_default():\n \"\"\"\n Make sure get_default works without crashing and gives reasonable results.\n", "FAIL_TO_PASS": ["pygmt/tests/test_clib.py::test_dataarray_to_matrix_zero_inc_fails"]}, {"instance_id": "GenericMappingTools__pygmt-1530", "base_commit": "6aba9aea0484b1c9038a3ee63c3360d596401acb", "gold_patch": "diff --git a/pygmt/clib/conversion.py b/pygmt/clib/conversion.py\nindex 57b2f92c..7c94b788 100644\n--- a/pygmt/clib/conversion.py\n+++ b/pygmt/clib/conversion.py\n@@ -1,6 +1,8 @@\n \"\"\"\n Functions to convert data types into ctypes friendly formats.\n \"\"\"\n+import warnings\n+\n import numpy as np\n import pandas as pd\n from pygmt.exceptions import GMTInvalidInput\n@@ -95,9 +97,14 @@ def dataarray_to_matrix(grid):\n coord_incs = coord[1:] - coord[0:-1]\n coord_inc = coord_incs[0]\n if not np.allclose(coord_incs, coord_inc):\n- raise GMTInvalidInput(\n- f\"Grid appears to have irregular spacing in the '{dim}' dimension.\"\n+ # calculate the increment if irregular spacing is found\n+ coord_inc = (coord[-1] - coord[0]) / (coord.size - 1)\n+ msg = (\n+ f\"Grid may have irregular spacing in the '{dim}' dimension, \"\n+ \"but GMT only supports regular spacing. Calculated regular spacing \"\n+ f\"{coord_inc} is assumed in the '{dim}' dimension.\"\n )\n+ warnings.warn(msg, category=RuntimeWarning)\n if coord_inc == 0:\n raise GMTInvalidInput(\n f\"Grid has a zero increment in the '{dim}' dimension.\"\n", "test_patch": "diff --git a/pygmt/tests/test_clib.py b/pygmt/tests/test_clib.py\nindex e88c04a8..b240015b 100644\n--- a/pygmt/tests/test_clib.py\n+++ b/pygmt/tests/test_clib.py\n@@ -805,16 +805,18 @@ def test_dataarray_to_matrix_dims_fails():\n dataarray_to_matrix(grid)\n \n \n-def test_dataarray_to_matrix_inc_fails():\n+def test_dataarray_to_matrix_irregular_inc_warning():\n \"\"\"\n- Check that it fails for variable increments.\n+ Check that it warns for variable increments, see also\n+ https://github.com/GenericMappingTools/pygmt/issues/1468.\n \"\"\"\n data = np.ones((4, 5), dtype=\"float64\")\n x = np.linspace(0, 1, 5)\n y = np.logspace(2, 3, 4)\n grid = xr.DataArray(data, coords=[(\"y\", y), (\"x\", x)])\n- with pytest.raises(GMTInvalidInput):\n+ with pytest.warns(expected_warning=RuntimeWarning) as record:\n dataarray_to_matrix(grid)\n+ assert len(record) == 1\n \n \n def test_dataarray_to_matrix_zero_inc_fails():\n", "FAIL_TO_PASS": ["pygmt/tests/test_clib.py::test_dataarray_to_matrix_irregular_inc_warning"]}], "all_FAIL_TO_PASS": ["pygmt/tests/test_clib.py::test_dataarray_to_matrix_zero_inc_fails", "pygmt/tests/test_clib.py::test_dataarray_to_matrix_irregular_inc_warning"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getsentry__sentry-python-4179_x2", "level": 2, "source": "swerebench", "repo": "getsentry/sentry-python", "image": "swerebench/sweb.eval.x86_64.getsentry_1776_sentry-python-4179:latest", "base_commit": "5715734eac1c5fb4b6ec61ef459080c74fa777b5", "num_bugs": 2, "bugs": [{"instance_id": "getsentry__sentry-python-4179", "base_commit": "5715734eac1c5fb4b6ec61ef459080c74fa777b5", "gold_patch": "diff --git a/sentry_sdk/tracing_utils.py b/sentry_sdk/tracing_utils.py\nindex 6aa4e488..ba566957 100644\n--- a/sentry_sdk/tracing_utils.py\n+++ b/sentry_sdk/tracing_utils.py\n@@ -5,7 +5,7 @@ import re\n import sys\n from collections.abc import Mapping\n from datetime import timedelta\n-from decimal import ROUND_DOWN, Decimal\n+from decimal import ROUND_DOWN, Context, Decimal\n from functools import wraps\n from random import Random\n from urllib.parse import quote, unquote\n@@ -871,7 +871,11 @@ def _generate_sample_rand(\n sample_rand = rng.uniform(lower, upper)\n \n # Round down to exactly six decimal-digit precision.\n- return Decimal(sample_rand).quantize(Decimal(\"0.000001\"), rounding=ROUND_DOWN)\n+ # Setting the context is needed to avoid an InvalidOperation exception\n+ # in case the user has changed the default precision.\n+ return Decimal(sample_rand).quantize(\n+ Decimal(\"0.000001\"), rounding=ROUND_DOWN, context=Context(prec=6)\n+ )\n \n \n def _sample_rand_range(parent_sampled, sample_rate):\n", "test_patch": "diff --git a/tests/tracing/test_sample_rand.py b/tests/tracing/test_sample_rand.py\nindex b8f5c042..ef277a3d 100644\n--- a/tests/tracing/test_sample_rand.py\n+++ b/tests/tracing/test_sample_rand.py\n@@ -1,3 +1,4 @@\n+import decimal\n from unittest import mock\n \n import pytest\n@@ -53,3 +54,28 @@ def test_transaction_uses_incoming_sample_rand(\n # Transaction event captured if sample_rand < sample_rate, indicating that\n # sample_rand is used to make the sampling decision.\n assert len(events) == int(sample_rand < sample_rate)\n+\n+\n+def test_decimal_context(sentry_init, capture_events):\n+ \"\"\"\n+ Ensure that having a decimal context with a precision below 6\n+ does not cause an InvalidOperation exception.\n+ \"\"\"\n+ sentry_init(traces_sample_rate=1.0)\n+ events = capture_events()\n+\n+ old_prec = decimal.getcontext().prec\n+ decimal.getcontext().prec = 2\n+\n+ try:\n+ with mock.patch(\n+ \"sentry_sdk.tracing_utils.Random.uniform\", return_value=0.123456789\n+ ):\n+ with sentry_sdk.start_transaction() as transaction:\n+ assert (\n+ transaction.get_baggage().sentry_items[\"sample_rand\"] == \"0.123456\"\n+ )\n+ finally:\n+ decimal.getcontext().prec = old_prec\n+\n+ assert len(events) == 1\n", "FAIL_TO_PASS": ["tests/tracing/test_sample_rand.py::test_decimal_context"]}, {"instance_id": "getsentry__sentry-python-4231", "base_commit": "2c3776c582a23b6936c76ef53008bf63f861b6fd", "gold_patch": "diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py\nindex ae0b9025..ca249fe8 100644\n--- a/sentry_sdk/tracing.py\n+++ b/sentry_sdk/tracing.py\n@@ -1,3 +1,4 @@\n+from decimal import Decimal\n import uuid\n import warnings\n from datetime import datetime, timedelta, timezone\n@@ -1198,10 +1199,8 @@ class Transaction(Span):\n self.sampled = False\n return\n \n- # Now we roll the dice. self._sample_rand is inclusive of 0, but not of 1,\n- # so strict < is safe here. In case sample_rate is a boolean, cast it\n- # to a float (True becomes 1.0 and False becomes 0.0)\n- self.sampled = self._sample_rand < self.sample_rate\n+ # Now we roll the dice.\n+ self.sampled = self._sample_rand < Decimal.from_float(self.sample_rate)\n \n if self.sampled:\n logger.debug(\ndiff --git a/sentry_sdk/tracing_utils.py b/sentry_sdk/tracing_utils.py\nindex ba566957..552f4fd5 100644\n--- a/sentry_sdk/tracing_utils.py\n+++ b/sentry_sdk/tracing_utils.py\n@@ -5,7 +5,7 @@ import re\n import sys\n from collections.abc import Mapping\n from datetime import timedelta\n-from decimal import ROUND_DOWN, Context, Decimal\n+from decimal import ROUND_DOWN, Decimal, DefaultContext, localcontext\n from functools import wraps\n from random import Random\n from urllib.parse import quote, unquote\n@@ -872,10 +872,13 @@ def _generate_sample_rand(\n \n # Round down to exactly six decimal-digit precision.\n # Setting the context is needed to avoid an InvalidOperation exception\n- # in case the user has changed the default precision.\n- return Decimal(sample_rand).quantize(\n- Decimal(\"0.000001\"), rounding=ROUND_DOWN, context=Context(prec=6)\n- )\n+ # in case the user has changed the default precision or set traps.\n+ with localcontext(DefaultContext) as ctx:\n+ ctx.prec = 6\n+ return Decimal(sample_rand).quantize(\n+ Decimal(\"0.000001\"),\n+ rounding=ROUND_DOWN,\n+ )\n \n \n def _sample_rand_range(parent_sampled, sample_rate):\n", "test_patch": "diff --git a/tests/tracing/test_sample_rand.py b/tests/tracing/test_sample_rand.py\nindex ef277a3d..f9c10aa0 100644\n--- a/tests/tracing/test_sample_rand.py\n+++ b/tests/tracing/test_sample_rand.py\n@@ -1,4 +1,5 @@\n import decimal\n+from decimal import Inexact, FloatOperation\n from unittest import mock\n \n import pytest\n@@ -58,14 +59,19 @@ def test_transaction_uses_incoming_sample_rand(\n \n def test_decimal_context(sentry_init, capture_events):\n \"\"\"\n- Ensure that having a decimal context with a precision below 6\n+ Ensure that having a user altered decimal context with a precision below 6\n does not cause an InvalidOperation exception.\n \"\"\"\n sentry_init(traces_sample_rate=1.0)\n events = capture_events()\n \n old_prec = decimal.getcontext().prec\n+ old_inexact = decimal.getcontext().traps[Inexact]\n+ old_float_operation = decimal.getcontext().traps[FloatOperation]\n+\n decimal.getcontext().prec = 2\n+ decimal.getcontext().traps[Inexact] = True\n+ decimal.getcontext().traps[FloatOperation] = True\n \n try:\n with mock.patch(\n@@ -77,5 +83,7 @@ def test_decimal_context(sentry_init, capture_events):\n )\n finally:\n decimal.getcontext().prec = old_prec\n+ decimal.getcontext().traps[Inexact] = old_inexact\n+ decimal.getcontext().traps[FloatOperation] = old_float_operation\n \n assert len(events) == 1\n", "FAIL_TO_PASS": ["tests/tracing/test_sample_rand.py::test_decimal_context"]}], "all_FAIL_TO_PASS": ["tests/tracing/test_sample_rand.py::test_decimal_context", "tests/tracing/test_sample_rand.py::test_decimal_context"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ipython__ipykernel-1056_x2", "level": 2, "source": "swerebench", "repo": "ipython/ipykernel", "image": "swerebench/sweb.eval.x86_64.ipython_1776_ipykernel-1056:latest", "base_commit": "04e1d753e328194be391b62ffd22662f0fe6dc56", "num_bugs": 2, "bugs": [{"instance_id": "ipython__ipykernel-1056", "base_commit": "04e1d753e328194be391b62ffd22662f0fe6dc56", "gold_patch": "diff --git a/.github/workflows/downstream.yml b/.github/workflows/downstream.yml\nindex ab1f103..57c8561 100644\n--- a/.github/workflows/downstream.yml\n+++ b/.github/workflows/downstream.yml\n@@ -84,6 +84,41 @@ jobs:\n pip install -e \".[test]\"\n python test_ipykernel.py\n \n+ qtconsole:\n+ runs-on: ubuntu-latest\n+ timeout-minutes: 20\n+ steps:\n+ - name: Checkout\n+ uses: actions/checkout@v3\n+\n+ - name: Setup Python\n+ uses: actions/setup-python@v4\n+ with:\n+ python-version: \"3.9\"\n+ architecture: \"x64\"\n+\n+ - name: Install System Packages\n+ run: |\n+ sudo apt-get update\n+ sudo apt-get install -y --no-install-recommends '^libxcb.*-dev' libx11-xcb-dev libglu1-mesa-dev libxrender-dev libxi-dev libxkbcommon-dev libxkbcommon-x11-dev\n+ - name: Install qtconsole dependencies\n+ shell: bash -l {0}\n+ run: |\n+ cd ${GITHUB_WORKSPACE}/..\n+ git clone https://github.com/jupyter/qtconsole.git\n+ cd qtconsole\n+ ${pythonLocation}/bin/python -m pip install -e \".[test]\"\n+ ${pythonLocation}/bin/python -m pip install pyqt5\n+ - name: Install Jupyter-Client changes\n+ shell: bash -l {0}\n+ run: ${pythonLocation}/bin/python -m pip install -e .\n+\n+ - name: Test qtconsole\n+ shell: bash -l {0}\n+ run: |\n+ cd ${GITHUB_WORKSPACE}/../qtconsole\n+ xvfb-run --auto-servernum ${pythonLocation}/bin/python -m pytest -x -vv -s --full-trace --color=yes qtconsole\n+\n downstream_check: # This job does nothing and is only used for the branch protection\n if: always()\n needs:\n@@ -92,6 +127,7 @@ jobs:\n - jupyter_client\n - ipyparallel\n - jupyter_kernel_test\n+ - qtconsole\n runs-on: ubuntu-latest\n steps:\n - name: Decide whether the needed jobs succeeded or failed\ndiff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex 295232e..77f9f07 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -42,7 +42,7 @@ class BaseComm(comm.base_comm.BaseComm):\n \n \n # but for backwards compatibility, we need to inherit from LoggingConfigurable\n-class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n+class Comm(BaseComm, traitlets.config.LoggingConfigurable):\n \"\"\"Class for communicating between a Frontend and a Kernel\"\"\"\n \n kernel = Instance(\"ipykernel.kernelbase.Kernel\", allow_none=True) # type:ignore[assignment]\n@@ -68,12 +68,16 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def _default_comm_id(self):\n return uuid.uuid4().hex\n \n- def __init__(self, *args, **kwargs):\n- # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n+ def __init__(self, target_name='', data=None, metadata=None, buffers=None, **kwargs):\n+ # Handle differing arguments between base classes.\n+ kernel = kwargs.pop('kernel', None)\n+ if target_name:\n+ kwargs['target_name'] = target_name\n+ BaseComm.__init__(\n+ self, data=data, metadata=metadata, buffers=buffers, **kwargs\n+ ) # type:ignore[call-arg]\n+ kwargs['kernel'] = kernel\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n- # drop arguments not in BaseComm\n- kwargs.pop(\"kernel\", None)\n- BaseComm.__init__(self, *args, **kwargs)\n \n \n __all__ = [\"Comm\"]\ndiff --git a/ipykernel/comm/manager.py b/ipykernel/comm/manager.py\nindex 6bf73ad..c11b562 100644\n--- a/ipykernel/comm/manager.py\n+++ b/ipykernel/comm/manager.py\n@@ -9,7 +9,7 @@ import traitlets\n import traitlets.config\n \n \n-class CommManager(traitlets.config.LoggingConfigurable, comm.base_comm.CommManager):\n+class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable):\n \n kernel = traitlets.Instance(\"ipykernel.kernelbase.Kernel\")\n comms = traitlets.Dict()\n@@ -17,5 +17,5 @@ class CommManager(traitlets.config.LoggingConfigurable, comm.base_comm.CommManag\n \n def __init__(self, **kwargs):\n # CommManager doesn't take arguments, so we explicitly forward arguments\n- traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n comm.base_comm.CommManager.__init__(self)\n+ traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex f8b0764..405841f 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -1,3 +1,5 @@\n+import unittest.mock\n+\n from ipykernel.comm import Comm, CommManager\n from ipykernel.ipkernel import IPythonKernel\n \n@@ -47,10 +49,12 @@ def test_comm_manager(kernel):\n manager.register_target(\"fizz\", fizz)\n \n kernel.comm_manager = manager\n- comm = Comm()\n- comm.on_msg(on_msg)\n- comm.on_close(on_close)\n- manager.register_comm(comm)\n+ with unittest.mock.patch.object(Comm, \"publish_msg\") as publish_msg:\n+ comm = Comm()\n+ comm.on_msg(on_msg)\n+ comm.on_close(on_close)\n+ manager.register_comm(comm)\n+ assert publish_msg.call_count == 1\n \n assert manager.get_comm(comm.comm_id) == comm\n assert manager.get_comm('foo') is None\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm_manager"]}, {"instance_id": "ipython__ipykernel-1061", "base_commit": "2c66b2de835856b19b25c6a890d9665902dda907", "gold_patch": "diff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex 77f9f07..6ec6ff3 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -70,13 +70,16 @@ class Comm(BaseComm, traitlets.config.LoggingConfigurable):\n \n def __init__(self, target_name='', data=None, metadata=None, buffers=None, **kwargs):\n # Handle differing arguments between base classes.\n+ had_kernel = 'kernel' in kwargs\n kernel = kwargs.pop('kernel', None)\n if target_name:\n kwargs['target_name'] = target_name\n BaseComm.__init__(\n self, data=data, metadata=metadata, buffers=buffers, **kwargs\n ) # type:ignore[call-arg]\n- kwargs['kernel'] = kernel\n+ # only re-add kernel if explicitly provided\n+ if had_kernel:\n+ kwargs['kernel'] = kernel\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n \n \n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex 405841f..5ec0d45 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -2,15 +2,18 @@ import unittest.mock\n \n from ipykernel.comm import Comm, CommManager\n from ipykernel.ipkernel import IPythonKernel\n+from ipykernel.kernelbase import Kernel\n \n \n-def test_comm(kernel):\n+def test_comm(kernel: Kernel) -> None:\n manager = CommManager(kernel=kernel)\n- kernel.comm_manager = manager\n+ kernel.comm_manager = manager # type:ignore\n \n c = Comm(kernel=kernel, target_name=\"bar\")\n msgs = []\n \n+ assert kernel is c.kernel # type:ignore\n+\n def on_close(msg):\n msgs.append(msg)\n \n@@ -28,7 +31,7 @@ def test_comm(kernel):\n assert c.target_name == \"bar\"\n \n \n-def test_comm_manager(kernel):\n+def test_comm_manager(kernel: Kernel) -> None:\n manager = CommManager(kernel=kernel)\n msgs = []\n \n@@ -48,7 +51,7 @@ def test_comm_manager(kernel):\n manager.register_target(\"foo\", foo)\n manager.register_target(\"fizz\", fizz)\n \n- kernel.comm_manager = manager\n+ kernel.comm_manager = manager # type:ignore\n with unittest.mock.patch.object(Comm, \"publish_msg\") as publish_msg:\n comm = Comm()\n comm.on_msg(on_msg)\n@@ -56,6 +59,11 @@ def test_comm_manager(kernel):\n manager.register_comm(comm)\n assert publish_msg.call_count == 1\n \n+ # make sure that when we don't pass a kernel, the 'default' kernel is taken\n+ Kernel._instance = kernel # type:ignore\n+ assert comm.kernel is kernel # type:ignore\n+ Kernel.clear_instance()\n+\n assert manager.get_comm(comm.comm_id) == comm\n assert manager.get_comm('foo') is None\n \n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm_manager", "ipykernel/tests/test_comm.py::test_comm_in_manager"]}], "all_FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm_manager", "ipykernel/tests/test_comm.py::test_comm_manager", "ipykernel/tests/test_comm.py::test_comm_in_manager"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "dask__dask-11699_x2", "level": 2, "source": "swerebench", "repo": "dask/dask", "image": "swerebench/sweb.eval.x86_64.dask_1776_dask-11699:latest", "base_commit": "d8eb38e97db5a83d893b178a2bb8ec7c34bd8f29", "num_bugs": 2, "bugs": [{"instance_id": "dask__dask-11699", "base_commit": "d8eb38e97db5a83d893b178a2bb8ec7c34bd8f29", "gold_patch": "diff --git a/dask/array/slicing.py b/dask/array/slicing.py\nindex 0927e2613..473c42646 100644\n--- a/dask/array/slicing.py\n+++ b/dask/array/slicing.py\n@@ -12,7 +12,7 @@ import numpy as np\n from tlz import concat, memoize, merge, pluck\n \n from dask import core\n-from dask._task_spec import Alias, Task, TaskRef\n+from dask._task_spec import Alias, DataNode, Task, TaskRef\n from dask.array.chunk import getitem\n from dask.base import is_dask_collection, tokenize\n from dask.highlevelgraph import HighLevelGraph\n@@ -209,7 +209,16 @@ def slice_with_newaxes(out_name, in_name, blockdims, index):\n for k, v in dsk.items():\n if k[0] == out_name:\n k2 = (out_name,) + expand(k[1:], 0)\n- dsk2[k2] = Task(k2, v.func, v.args[0], expand_orig(v.args[1], None))\n+ if isinstance(v.args[1], Alias):\n+ # positional indexing with newaxis\n+ indexer = expand_orig(dsk[v.args[1].key].value[1], None)\n+ tok = \"shuffle-taker-\" + tokenize(indexer)\n+ dsk2[tok] = DataNode(tok, (1, indexer))\n+ arg = TaskRef(tok)\n+ else:\n+ arg = expand_orig(v.args[1], None)\n+ # raise NotImplementedError\n+ dsk2[k2] = Task(k2, v.func, v.args[0], arg)\n else:\n dsk2[k] = v\n \ndiff --git a/dask/dataframe/dask_expr/_reductions.py b/dask/dataframe/dask_expr/_reductions.py\nindex 5b5f248dd..5ba667896 100644\n--- a/dask/dataframe/dask_expr/_reductions.py\n+++ b/dask/dataframe/dask_expr/_reductions.py\n@@ -1427,6 +1427,7 @@ class ValueCounts(ReductionConstantDim):\n reduction_chunk = M.value_counts\n reduction_aggregate = methods.value_counts_aggregate\n reduction_combine = methods.value_counts_combine\n+ split_by = None\n \n @functools.cached_property\n def _meta(self):\n@@ -1441,8 +1442,8 @@ class ValueCounts(ReductionConstantDim):\n return func(_concat(inputs), observed=True, **kwargs)\n \n @property\n- def split_by(self):\n- return self.frame._meta.name\n+ def shuffle_by_index(self):\n+ return True\n \n @property\n def chunk_kwargs(self):\n", "test_patch": "diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py\nindex e72ec9d30..bf2171d00 100644\n--- a/dask/array/tests/test_array_core.py\n+++ b/dask/array/tests/test_array_core.py\n@@ -5145,9 +5145,16 @@ def test_dask_array_holds_scipy_sparse_containers():\n @pytest.mark.parametrize(\"sparse_module_path\", [\"scipy.sparse\", \"cupyx.scipy.sparse\"])\n def test_scipy_sparse_indexing(index, sparse_module_path):\n sp = pytest.importorskip(sparse_module_path)\n- x = da.random.default_rng().random((1000, 10), chunks=(100, 10))\n- x[x < 0.9] = 0\n- y = x.map_blocks(sp.csr_matrix)\n+\n+ if sparse_module_path == \"cupyx.scipy.sparse\":\n+ backend = \"cupy\"\n+ else:\n+ backend = \"numpy\"\n+\n+ with dask.config.set({\"array.backend\": backend}):\n+ x = da.random.default_rng().random((1000, 10), chunks=(100, 10))\n+ x[x < 0.9] = 0\n+ y = x.map_blocks(sp.csr_matrix)\n \n assert not (\n x[index, :].compute(scheduler=\"single-threaded\")\ndiff --git a/dask/array/tests/test_slicing.py b/dask/array/tests/test_slicing.py\nindex 46366c2a8..28eef7841 100644\n--- a/dask/array/tests/test_slicing.py\n+++ b/dask/array/tests/test_slicing.py\n@@ -1131,3 +1131,9 @@ def test_vindex_with_dask_array():\n \n with pytest.raises(IndexError, match=msg):\n darr.vindex[(dindexer, None)]\n+\n+\n+def test_positional_indexer_newaxis():\n+ arr = da.array([0, 1, 2])\n+ new = arr[[True, True, False], np.newaxis]\n+ assert_eq(new, arr.compute()[[True, True, False], np.newaxis])\ndiff --git a/dask/dataframe/dask_expr/tests/test_reductions.py b/dask/dataframe/dask_expr/tests/test_reductions.py\nindex b10030ac0..744e648cb 100644\n--- a/dask/dataframe/dask_expr/tests/test_reductions.py\n+++ b/dask/dataframe/dask_expr/tests/test_reductions.py\n@@ -558,3 +558,16 @@ def test_reductions_timestamps_display():\n data = pd.to_datetime([\"2024-10-02 12:00:00\", \"2024-10-02 14:00:00\"])\n df = from_pandas(pd.DataFrame({\"valid_time\": data}))\n assert df[\"valid_time\"].min().__repr__()\n+\n+\n+def test_value_counts_shuffle_properly():\n+ pdf = pd.DataFrame(\n+ {\n+ \"A\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n+ \"B\": [11, 12, 13, 4, 15, 6, 17, 8, 19, 10],\n+ }\n+ )\n+ df = from_pandas(pdf, npartitions=2)\n+ result = (df[\"A\"] == df[\"B\"]).value_counts()\n+ expected = (pdf[\"A\"] == pdf[\"B\"]).value_counts()\n+ assert_eq(result, expected)\n", "FAIL_TO_PASS": ["dask/array/tests/test_slicing.py::test_positional_indexer_newaxis", "dask/dataframe/dask_expr/tests/test_reductions.py::test_value_counts_shuffle_properly"]}, {"instance_id": "dask__dask-11707", "base_commit": "c5524337c7abf5f9c5436736cbc8c081c193e8ab", "gold_patch": "diff --git a/dask/array/creation.py b/dask/array/creation.py\nindex ec7e96f8e..0f69d165c 100644\n--- a/dask/array/creation.py\n+++ b/dask/array/creation.py\n@@ -436,7 +436,7 @@ def arange(\n meta = meta_from_array(like) if like is not None else None\n \n if dtype is None:\n- dtype = np.arange(start, stop, step * num if num else step).dtype\n+ dtype = np.arange(type(start)(0), type(stop)(0), step).dtype\n \n chunks = normalize_chunks(chunks, (num,), dtype=dtype)\n \ndiff --git a/dask/array/slicing.py b/dask/array/slicing.py\nindex 473c42646..aebbfbf0f 100644\n--- a/dask/array/slicing.py\n+++ b/dask/array/slicing.py\n@@ -2020,9 +2020,9 @@ def setitem(x, v, indices):\n \n Parameters\n ----------\n- x : numpy array\n+ x : numpy/cupy/etc. array\n The array to be assigned to.\n- v : numpy array\n+ v : numpy/cupy/etc. array\n The values which will be assigned.\n indices : list of `slice`, `int`, or numpy array\n The indices describing the elements of x to be assigned from\n@@ -2038,7 +2038,7 @@ def setitem(x, v, indices):\n \n Returns\n -------\n- numpy array\n+ numpy/cupy/etc. array\n A new independent array with assigned elements, unless v is\n empty (i.e. has zero size) in which case then the input array\n is returned and the indices are ignored.\n@@ -2086,8 +2086,11 @@ def setitem(x, v, indices):\n if not np.ma.isMA(x) and np.ma.isMA(v):\n x = x.view(np.ma.MaskedArray)\n \n- # Copy the array to guarantee no other objects are corrupted\n- x = x.copy()\n+ # Copy the array to guarantee no other objects are corrupted.\n+ # When x is the output of a scalar __getitem__ call, it is a\n+ # np.generic, which is read-only. Convert it to a (writeable)\n+ # 0-d array. x could also be a cupy array etc.\n+ x = np.asarray(x) if isinstance(x, np.generic) else x.copy()\n \n # Do the assignment\n try:\n", "test_patch": "diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py\nindex f6873bf41..b136b5302 100644\n--- a/dask/array/tests/test_array_core.py\n+++ b/dask/array/tests/test_array_core.py\n@@ -5771,3 +5771,17 @@ def test_load_store_chunk():\n )\n expected = np.array([])\n assert all(actual == expected)\n+\n+\n+def test_scalar_setitem():\n+ \"\"\"After a da.Array.__getitem__ call that returns a scalar, the chunk contains a\n+ read-only np.generic instead of a writeable np.ndarray. This is a specific quirk of\n+ numpy; cupy and other backends always return a 0-dimensional array.\n+ Make sure that __setitem__ still works.\n+ \"\"\"\n+ x = da.zeros(1)\n+ y = x[0]\n+ assert isinstance(y.compute(), np.generic)\n+ y[()] = 2\n+ assert_eq(y, 2.0)\n+ assert isinstance(y.compute(), np.ndarray)\ndiff --git a/dask/array/tests/test_creation.py b/dask/array/tests/test_creation.py\nindex e8f51479f..fef3272e8 100644\n--- a/dask/array/tests/test_creation.py\n+++ b/dask/array/tests/test_creation.py\n@@ -254,35 +254,58 @@ def test_arange():\n assert da.arange(10).chunks == ((10,),)\n \n \n+arange_dtypes = [\n+ np.uint8,\n+ np.uint64,\n+ np.int8,\n+ np.int64,\n+ np.float32,\n+ np.float64,\n+]\n+\n+\n+# FIXME hypothesis would be much better suited for this\n+@pytest.mark.parametrize(\"start_type\", arange_dtypes + [int, float])\n+@pytest.mark.parametrize(\"stop_type\", arange_dtypes + [int, float])\n+@pytest.mark.parametrize(\"step_type\", arange_dtypes + [int, float])\n+def test_arange_dtype_infer(start_type, stop_type, step_type):\n+ start = start_type(3)\n+ stop = stop_type(13)\n+ step = step_type(2)\n+ a_np = np.arange(start, stop, step)\n+ a_da = da.arange(start, stop, step)\n+ assert_eq(a_np, a_da)\n+\n+\n+@pytest.mark.parametrize(\"dtype\", arange_dtypes)\n+def test_arange_dtype_force(dtype):\n+ assert da.arange(10, dtype=dtype).dtype == dtype\n+ assert da.arange(np.float32(10), dtype=dtype).dtype == dtype\n+ assert da.arange(np.int64(10), dtype=dtype).dtype == dtype\n+\n+\n+@pytest.mark.skipif(np.array(0).dtype == np.int32, reason=\"64-bit platforms only\")\n @pytest.mark.parametrize(\n- \"start,stop,step,dtype\",\n+ \"start,stop,step\",\n [\n- (0, 1, 1, None), # int64\n- (1.5, 2, 1, None), # float64\n- (1, 2.5, 1, None), # float64\n- (1, 2, 0.5, None), # float64\n- (np.float32(1), np.float32(2), np.float32(1), None), # promoted to float64\n- (np.int32(1), np.int32(2), np.int32(1), None), # promoted to int64\n- (np.uint32(1), np.uint32(2), np.uint32(1), None), # promoted to int64\n- (np.uint64(1), np.uint64(2), np.uint64(1), None), # promoted to float64\n- (np.uint32(1), np.uint32(2), np.uint32(1), np.uint32),\n- (np.uint64(1), np.uint64(2), np.uint64(1), np.uint64),\n- # numpy.arange gives unexpected results\n- # https://github.com/numpy/numpy/issues/11505\n- # (1j, 2, 1, None),\n- # (1, 2j, 1, None),\n- # (1, 2, 1j, None),\n- # (1+2j, 2+3j, 1+.1j, None),\n+ (2**63 - 10_000, 2**63 - 1, 1),\n+ (2**63 - 1, 2**63 - 10_000, -1),\n+ (0, 2**63 - 1, 2**63 - 10_000),\n+ (0.0, 2**63 - 1, 2**63 - 10_000),\n+ (0.0, -9_131_138_316_486_228_481, -92_233_720_368_547_759),\n ],\n )\n-def test_arange_dtypes(start, stop, step, dtype):\n- a_np = np.arange(start, stop, step, dtype=dtype)\n- a_da = da.arange(start, stop, step, dtype=dtype, chunks=-1)\n+def test_arange_very_large_args(start, stop, step):\n+ \"\"\"Test args that are very close to 2**63\n+ https://github.com/dask/dask/issues/11706\n+ \"\"\"\n+ a_np = np.arange(start, stop, step)\n+ a_da = da.arange(start, stop, step)\n assert_eq(a_np, a_da)\n \n \n @pytest.mark.xfail(\n- reason=\"Casting floats to ints is not supported since edge\"\n+ reason=\"Casting floats to ints is not supported since edge \"\n \"behavior is not specified or guaranteed by NumPy.\"\n )\n def test_arange_cast_float_int_step():\n", "FAIL_TO_PASS": ["dask/array/tests/test_array_core.py::test_scalar_setitem", "dask/array/tests/test_creation.py::test_arange_very_large_args[0-9223372036854775807-9223372036854765808]", "dask/array/tests/test_creation.py::test_arange_very_large_args[0.0--9131138316486228481--92233720368547759]"]}], "all_FAIL_TO_PASS": ["dask/array/tests/test_slicing.py::test_positional_indexer_newaxis", "dask/dataframe/dask_expr/tests/test_reductions.py::test_value_counts_shuffle_properly", "dask/array/tests/test_array_core.py::test_scalar_setitem", "dask/array/tests/test_creation.py::test_arange_very_large_args[0-9223372036854775807-9223372036854765808]", "dask/array/tests/test_creation.py::test_arange_very_large_args[0.0--9131138316486228481--92233720368547759]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Stewori__pytypes-37_x2", "level": 2, "source": "swerebench", "repo": "Stewori/pytypes", "image": "swerebench/sweb.eval.x86_64.stewori_1776_pytypes-37:latest", "base_commit": "5736ecd2878aca5c78df44aeeaef13303cbfa5f2", "num_bugs": 2, "bugs": [{"instance_id": "Stewori__pytypes-37", "base_commit": "5736ecd2878aca5c78df44aeeaef13303cbfa5f2", "gold_patch": "diff --git a/pytypes/type_util.py b/pytypes/type_util.py\nindex 13c991e..f6227c8 100644\n--- a/pytypes/type_util.py\n+++ b/pytypes/type_util.py\n@@ -900,7 +900,7 @@ def resolve_fw_decl(in_type, module_name=None, globs=None, level=0):\n for in_tp in args])\n ret = resolve_fw_decl(res, None, globs)[1] or ret\n return in_type, ret\n- elif hasattr(in_type, '__args__'):\n+ elif hasattr(in_type, '__args__') and in_type.__args__ is not None:\n return in_type, any([resolve_fw_decl(in_tp, None, globs)[1] \\\n for in_tp in in_type.__args__])\n return in_type, False\n", "test_patch": "diff --git a/tests/test_typechecker.py b/tests/test_typechecker.py\nindex d6acaf9..ddd2745 100644\n--- a/tests/test_typechecker.py\n+++ b/tests/test_typechecker.py\n@@ -23,7 +23,7 @@ from numbers import Real\n import pytypes\n from pytypes import typechecked, override, auto_override, no_type_check, get_types, \\\n get_type_hints, TypeCheckError, InputTypeError, ReturnTypeError, OverrideError, \\\n- TypeSyntaxError, check_argument_types, annotations, get_member_types\n+ TypeSyntaxError, check_argument_types, annotations, get_member_types, resolve_fw_decl\n pytypes.clean_traceback = False\n try:\n from backports import typing\n@@ -4652,5 +4652,18 @@ class Test_check_argument_types_Python3_5(unittest.TestCase):\n self.assertRaises(InputTypeError, lambda:\n py3.test_inner_class_testf1_err())\n \n+\n+class Test_utils(unittest.TestCase):\n+ # See: https://github.com/Stewori/pytypes/issues/36\n+ def test_resolve_fw_decl(self):\n+ T = typing.TypeVar('T')\n+\n+ class Foo(typing.Generic[T]):\n+ pass\n+\n+ # No exception.\n+ resolve_fw_decl(Foo)\n+\n+\n if __name__ == '__main__':\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_typechecker.py::Test_utils::test_resolve_fw_decl"]}, {"instance_id": "Stewori__pytypes-38", "base_commit": "152a2218bfa1b96ae5d866542ee4ad148b1b7b5d", "gold_patch": "diff --git a/pytypes/type_util.py b/pytypes/type_util.py\nindex f6227c8..976f96f 100644\n--- a/pytypes/type_util.py\n+++ b/pytypes/type_util.py\n@@ -22,10 +22,10 @@ import typing\n import collections\n from inspect import isfunction, ismethod, isclass, ismodule\n try:\n- from backports.typing import Tuple, Dict, List, Set, Union, Any, \\\n+ from backports.typing import Tuple, Dict, List, Set, FrozenSet, Union, Any, \\\n Sequence, Mapping, TypeVar, Container, Generic, Sized, Iterable\n except ImportError:\n- from typing import Tuple, Dict, List, Set, Union, Any, \\\n+ from typing import Tuple, Dict, List, Set, FrozenSet, Union, Any, \\\n Sequence, Mapping, TypeVar, Container, Generic, Sized, Iterable\n try:\n # Python 3.7\n@@ -465,9 +465,13 @@ def _deep_type(obj, checked, checked_len, depth = None, max_sample = None):\n tpl1 = tuple(_deep_type(t, checked, checked_len2, depth-1) for t in ksmpl)\n tpl2 = tuple(_deep_type(t, checked, checked_len2, depth-1) for t in vsmpl)\n res = Dict[Union[tpl1], Union[tpl2]]\n- elif res == set:\n+ elif res == set or res == frozenset:\n+ if res == set:\n+ typ = Set\n+ else:\n+ typ = FrozenSet\n if len(obj) == 0:\n- return Empty[Set]\n+ return Empty[typ]\n if max_sample == -1 or max_sample >= len(obj)-1 or len(obj) <= 2:\n tpl = tuple(_deep_type(t, checked, depth-1) for t in obj)\n else:\n@@ -485,7 +489,7 @@ def _deep_type(obj, checked, checked_len, depth = None, max_sample = None):\n j -= 1\n smpl.append(next(itr))\n tpl = tuple(_deep_type(t, checked, depth-1) for t in smpl)\n- res = Set[Union[tpl]]\n+ res = typ[Union[tpl]]\n elif res == types.GeneratorType:\n res = get_generator_type(obj)\n elif sys.version_info.major == 2 and isinstance(obj, types.InstanceType):\n", "test_patch": "diff --git a/tests/test_typechecker.py b/tests/test_typechecker.py\nindex ddd2745..9106d6b 100644\n--- a/tests/test_typechecker.py\n+++ b/tests/test_typechecker.py\n@@ -4664,6 +4664,10 @@ class Test_utils(unittest.TestCase):\n # No exception.\n resolve_fw_decl(Foo)\n \n+ # See: https://github.com/Stewori/pytypes/issues/35\n+ def test_frozenset(self):\n+ self.assertTrue(pytypes.is_of_type(frozenset({1, 2, 'a', None, 'b'}), typing.AbstractSet[typing.Union[str, int, None]]))\n+\n \n if __name__ == '__main__':\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_typechecker.py::Test_utils::test_frozenset"]}], "all_FAIL_TO_PASS": ["tests/test_typechecker.py::Test_utils::test_resolve_fw_decl", "tests/test_typechecker.py::Test_utils::test_frozenset"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jackdewinter__pymarkdown-1246_x2", "level": 2, "source": "swerebench", "repo": "jackdewinter/pymarkdown", "image": "swerebench/sweb.eval.x86_64.jackdewinter_1776_pymarkdown-1246:latest", "base_commit": "911e871a488de37a5b90ebaf9e2f489e278848a3", "num_bugs": 2, "bugs": [{"instance_id": "jackdewinter__pymarkdown-1246", "base_commit": "911e871a488de37a5b90ebaf9e2f489e278848a3", "gold_patch": "diff --git a/newdocs/src/changelog.md b/newdocs/src/changelog.md\nindex 39b9359f..be928638 100644\n--- a/newdocs/src/changelog.md\n+++ b/newdocs/src/changelog.md\n@@ -5,12 +5,24 @@\n \n ### Added\n \n-- None\n+- [Issue 1233](https://github.com/jackdewinter/pymarkdown/issues/1233)\n+- [Issue 1234](https://github.com/jackdewinter/pymarkdown/issues/1234)\n+- [Issue 1235](https://github.com/jackdewinter/pymarkdown/issues/1235)\n+ - Adding more comprehensive \"drop X\" tests where multiple levels of\n+ containers are involved, and then dropping one or more of those\n+ containers in a single line.\n \n \n ### Fixed\n \n-- None\n+- [Issue 1233](https://github.com/jackdewinter/pymarkdown/issues/1233)\n+- [Issue 1234](https://github.com/jackdewinter/pymarkdown/issues/1234)\n+- [Issue 1235](https://github.com/jackdewinter/pymarkdown/issues/1235)\n+ - Adding new \"drop_x\" tests and resolve any scan issues with them.\n+- [Issue 1243](https://github.com/jackdewinter/pymarkdown/issues/1243)\n+- [Issue 1245](https://github.com/jackdewinter/pymarkdown/issues/1245)\n+ - Handling leading spaces in `__fix_spacing` function now that data\n+ is present.\n \n \n ### Changed\ndiff --git a/publish/coverage.json b/publish/coverage.json\nindex 7133420f..398dc062 100644\n--- a/publish/coverage.json\n+++ b/publish/coverage.json\n@@ -2,12 +2,12 @@\n \"projectName\": \"pymarkdown\",\n \"reportSource\": \"pytest\",\n \"branchLevel\": {\n- \"totalMeasured\": 5385,\n- \"totalCovered\": 5385\n+ \"totalMeasured\": 5393,\n+ \"totalCovered\": 5392\n },\n \"lineLevel\": {\n- \"totalMeasured\": 21081,\n- \"totalCovered\": 21081\n+ \"totalMeasured\": 21094,\n+ \"totalCovered\": 21093\n }\n }\n \ndiff --git a/pymarkdown/block_quotes/block_quote_count_helper.py b/pymarkdown/block_quotes/block_quote_count_helper.py\nindex f4e30a01..77568df7 100644\n--- a/pymarkdown/block_quotes/block_quote_count_helper.py\n+++ b/pymarkdown/block_quotes/block_quote_count_helper.py\n@@ -328,7 +328,9 @@ class BlockQuoteCountHelper:\n )\n assert parser_state.original_line_to_parse is not None\n if (\n- parser_state.original_line_to_parse[\n+ embedded_list_stack_token.indent_level\n+ >= len(parser_state.original_line_to_parse)\n+ or parser_state.original_line_to_parse[\n start_index : embedded_list_stack_token.indent_level\n ].strip()\n or parser_state.original_line_to_parse[\ndiff --git a/pymarkdown/plugins/rule_md_031.py b/pymarkdown/plugins/rule_md_031.py\nindex ceb970a7..07d958bc 100644\n--- a/pymarkdown/plugins/rule_md_031.py\n+++ b/pymarkdown/plugins/rule_md_031.py\n@@ -359,7 +359,8 @@ class RuleMd031(RulePlugin):\n removed_list_token = cast(\n ListStartMarkdownToken, self.__removed_container_stack_token\n )\n- assert removed_list_token.leading_spaces is not None\n+ if removed_list_token.leading_spaces is None:\n+ return\n split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n split_spaces_length = len(split_spaces)\n if split_spaces_length > 1:\n@@ -461,6 +462,40 @@ class RuleMd031(RulePlugin):\n else 1\n )\n \n+ def __fix_spacing_one_container(\n+ self, context: PluginScanContext, token: MarkdownToken\n+ ) -> bool:\n+ did_special_list_fix = False\n+ if self.__leading_space_index_tracker.get_container_stack_item(\n+ -1\n+ ).is_block_quote_start:\n+ self.__fix_spacing_block_quote(token)\n+ else:\n+ did_special_list_fix = self.__fix_spacing_list(context, token)\n+ return did_special_list_fix\n+\n+ def __fix_spacing_removed_container(\n+ self, context: PluginScanContext, token: MarkdownToken\n+ ) -> None:\n+ _ = token\n+ assert self.__removed_container_stack_token is not None\n+ if self.__removed_container_stack_token.is_list_start:\n+ removed_list_token = cast(\n+ ListStartMarkdownToken, self.__removed_container_stack_token\n+ )\n+ if removed_list_token.leading_spaces is not None:\n+ split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n+ split_spaces.append(\"\")\n+ else:\n+ split_spaces = [\"\"]\n+ self.register_fix_token_request(\n+ context,\n+ self.__removed_container_stack_token,\n+ \"next_token\",\n+ \"leading_spaces\",\n+ \"\\n\".join(split_spaces),\n+ )\n+\n def __fix_spacing(\n self, context: PluginScanContext, token: MarkdownToken, special_case: bool\n ) -> None:\n@@ -469,30 +504,9 @@ class RuleMd031(RulePlugin):\n self.__fix_spacing_special_case(context, token)\n return\n if self.__leading_space_index_tracker.in_at_least_one_container():\n- if self.__leading_space_index_tracker.get_container_stack_item(\n- -1\n- ).is_block_quote_start:\n- self.__fix_spacing_block_quote(token)\n- else:\n- did_special_list_fix = self.__fix_spacing_list(context, token)\n+ did_special_list_fix = self.__fix_spacing_one_container(context, token)\n elif self.__removed_container_stack_token:\n- if self.__removed_container_stack_token.is_list_start:\n- removed_list_token = cast(\n- ListStartMarkdownToken, self.__removed_container_stack_token\n- )\n- assert removed_list_token.leading_spaces is None\n- # if removed_list_token.leading_spaces is not None:\n- # split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n- # split_spaces.append(\"\")\n- # else:\n- split_spaces = [\"\"]\n- self.register_fix_token_request(\n- context,\n- self.__removed_container_stack_token,\n- \"next_token\",\n- \"leading_spaces\",\n- \"\\n\".join(split_spaces),\n- )\n+ self.__fix_spacing_removed_container(context, token)\n \n new_token = copy.deepcopy(token)\n self.__fix_count += 1\ndiff --git a/pymarkdown/transform_markdown/transform_containers.py b/pymarkdown/transform_markdown/transform_containers.py\nindex 9c95cadb..18b20bc9 100644\n--- a/pymarkdown/transform_markdown/transform_containers.py\n+++ b/pymarkdown/transform_markdown/transform_containers.py\n@@ -1435,11 +1435,15 @@ class TransformContainers:\n do_it = True\n if token_stack[-1].is_list_start and removed_tokens[-1].is_list_start:\n removed_list_token = cast(ListStartMarkdownToken, removed_tokens[-1])\n- assert removed_list_token.leading_spaces is not None\n- removed_token_split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n removed_token_index = removed_token_indices[-1]\n- assert removed_token_index < len(removed_token_split_spaces)\n- removed_token_indices[-1] += 1\n+ if removed_list_token.leading_spaces is None:\n+ assert removed_token_index == 0\n+ else:\n+ removed_token_split_spaces = removed_list_token.leading_spaces.split(\n+ \"\\n\"\n+ )\n+ assert removed_token_index < len(removed_token_split_spaces)\n+ removed_token_indices[-1] += 1\n do_it = False\n block_me = True\n if do_it:\n@@ -1858,13 +1862,14 @@ class TransformContainers:\n if token_stack[-1].is_new_list_item\n else cast(ListStartMarkdownToken, token_stack[-1])\n )\n- assert (\n- prev_list_token.leading_spaces is not None\n- ), \"Leading spaces must be defined by this point.\"\n- split_leading_spaces = prev_list_token.leading_spaces.split(\n- ParserHelper.newline_character\n- )\n- if last_container_token_index < len(split_leading_spaces):\n+ split_leading_spaces = None\n+ if prev_list_token.leading_spaces is not None:\n+ split_leading_spaces = prev_list_token.leading_spaces.split(\n+ ParserHelper.newline_character\n+ )\n+ if split_leading_spaces is not None and last_container_token_index < len(\n+ split_leading_spaces\n+ ):\n POGGER.debug(f\" -->{ParserHelper.make_value_visible(split_leading_spaces)}\")\n POGGER.debug(\n f\" primary-->container_line>:{ParserHelper.make_value_visible(container_line)}:<\"\n", "test_patch": "diff --git a/publish/test-results.json b/publish/test-results.json\nindex cffe29c8..7e2b78aa 100644\n--- a/publish/test-results.json\n+++ b/publish/test-results.json\n@@ -1367,7 +1367,7 @@\n \"totalTests\": 653,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 84,\n+ \"skippedTests\": 62,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\n@@ -1620,10 +1620,10 @@\n },\n {\n \"name\": \"test.test_markdown_extra\",\n- \"totalTests\": 203,\n+ \"totalTests\": 206,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 2,\n+ \"skippedTests\": 3,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\ndiff --git a/test/rules/test_md031.py b/test/rules/test_md031.py\nindex b99e3eef..435a4958 100644\n--- a/test/rules/test_md031.py\n+++ b/test/rules/test_md031.py\n@@ -30,6 +30,8 @@ The value for property 'plugins.md031.list_items' must be of type 'bool'.\"\"\",\n ),\n ]\n \n+skip_fix_asserts = True\n+\n scanTests = [\n pluginRuleTest(\n \"good_both_fenced_with_consistent\",\n@@ -1600,7 +1602,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"+ list\n > inner list\n > couple of lines\n@@ -2678,7 +2679,8 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> > >\n > > > > fourth block 1\n > > > > fourth block 2\n@@ -2788,7 +2790,8 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> > >\n > > > > fourth block 1\n > > > > fourth block 2\n@@ -3156,7 +3159,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3183,8 +3186,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- use_debug=True,\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3390,7 +3391,6 @@ A code block\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -3748,7 +3748,8 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"1. > >\n > > block 3\n > > block 3\n@@ -4032,7 +4033,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > +\n > list 3\n > + list 3\n@@ -4298,7 +4298,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > block 1\n > > > block 2\n@@ -4405,7 +4404,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4510,7 +4508,7 @@ A code block\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4538,7 +4536,7 @@ A code block\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4678,7 +4676,6 @@ A code block\n {temp_source_path}:7:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4735,7 +4732,6 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4796,7 +4792,6 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -5002,7 +4997,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5264,7 +5258,6 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5600,8 +5593,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + list 1\n > > block 2\n > > block 3\n@@ -5683,7 +5674,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + list 1\n > > block 2\n > > block 3\n@@ -5860,7 +5850,6 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + list 1\n > + list 2\n > list 3\n@@ -6264,7 +6253,6 @@ another list\n {temp_source_path}:6:7: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6294,7 +6282,7 @@ another list\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6353,8 +6341,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- use_debug=True,\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6448,7 +6434,8 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6479,7 +6466,8 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6510,8 +6498,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6688,8 +6674,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6753,7 +6737,8 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6786,7 +6771,8 @@ another list\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6819,8 +6805,6 @@ another list\n {temp_source_path}:8:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -7021,8 +7005,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7144,8 +7126,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7242,7 +7222,8 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > + list 1\n > list 2\n@@ -7273,7 +7254,6 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > + list 1\n > list 2\n@@ -7578,7 +7558,7 @@ another list\n + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050a0\n \"bad_fenced_block_in_list_in_list_with_previous_inner_block_double_drop\",\n source_file_contents=\"\"\"+ + list 1\n > block 2.1\n@@ -7593,7 +7573,8 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -7798,7 +7779,6 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"+ + list 1\n + + + list 2.1\n list 2.2\n@@ -8194,7 +8174,8 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + > -----\n > > block 1\n > > block 2\n@@ -8470,7 +8451,8 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8780,7 +8762,8 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n > block 1\n > block 2\n@@ -8868,7 +8851,8 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n > block 1\n > block 2\n@@ -9131,7 +9115,7 @@ another list\n + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050b0 test_extra_050b1\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\",\n source_file_contents=\"\"\"+ + + -----\n + list 1\n@@ -9147,7 +9131,9 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_fix_debug=True,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n + list 1\n list 2\n@@ -9176,7 +9162,8 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n + list 1\n list 2\ndiff --git a/test/test_markdown_extra.py b/test/test_markdown_extra.py\nindex eec32ac3..272eec4c 100644\n--- a/test/test_markdown_extra.py\n+++ b/test/test_markdown_extra.py\n@@ -9042,6 +9042,207 @@ def test_extra_049l4a():\n act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=True)\n \n \n+@pytest.mark.gfm\n+@pytest.mark.skip\n+def test_extra_050a0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_with_previous_inner_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + list 1\n+ > block 2.1\n+ > block 2.2\n+ ```block\n+ A code block\n+ ```\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:: \\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: :\\n\\n]\",\n+ \"[para(1,5):]\",\n+ \"[text(1,5):list 1:]\",\n+ \"[end-para:::True]\",\n+ \"[block-quote(2,5): : > \\n > ]\",\n+ \"[para(2,7):\\n]\",\n+ \"[text(2,7):block 2.1\\nblock 2.2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,3):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[para(7,3):]\",\n+ \"[text(7,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(8,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • list 1\n+
      \n+

      block 2.1\n+block 2.2

      \n+
      \n+
    • \n+
    \n+
    A code block\n+
    \n+another list
  • \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050b0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ + list 1\n+ list 2\n+ + list 3\n+ ```block\n+ A code block\n+ ```\n+ + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: : \\n \\n \\n]\",\n+ \"[ulist(1,5):+::6: ]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[ulist(2,7):+::8: : ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,7):8: :]\",\n+ \"[para(4,9):]\",\n+ \"[text(4,9):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,5):`:3:block:::::]\",\n+ \"[text(6,5):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[li(8,3):4: :]\",\n+ \"[para(8,5):]\",\n+ \"[text(8,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(9,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
          \n+
        • list 1\n+list 2
        • \n+
        • list 3
        • \n+
        \n+
      • \n+
      \n+
      A code block\n+
      \n+
    • \n+
    • another list
    • \n+
    \n+
  • \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050b1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ + list 1\n+ list 2\n+ + list 3\n+\n+ ```block\n+ A code block\n+ ```\n+\n+ + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: : \\n \\n \\n\\n]\",\n+ \"[ulist(1,5):+::6: ]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[ulist(2,7):+::8: : \\n]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,7):8: :]\",\n+ \"[para(4,9):]\",\n+ \"[text(4,9):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(5,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(6,5):`:3:block:::::]\",\n+ \"[text(7,5):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(9,1):]\",\n+ \"[li(10,3):4: :]\",\n+ \"[para(10,5):]\",\n+ \"[text(10,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(11,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
          \n+
        • list 1\n+list 2
        • \n+
        • list 3
        • \n+
        \n+
      • \n+
      \n+
      A code block\n+
      \n+
    • \n+
    • \n+

      another list

      \n+
    • \n+
    \n+
  • \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n @pytest.mark.gfm\n def test_extra_999():\n \"\"\"\n@@ -9100,33 +9301,52 @@ def test_extra_999():\n # bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_double_drop\n # bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\n # bad_fenced_block_in_block_quote_with_previous_inner_list_double_drop\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_block_triple_drop_with_thematics\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_block_quad_drop_with_thematics\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_list_double_drop\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_list_triple_drop\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_triple_drop\n+# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_double_drop\n+# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n \n # Assert\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_list_triple_drop\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_block_double_drop_with_thematics\n-# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop\n-# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_triple_drop\n+\n+# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_triple_drop_with_thematics\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop_with_thematics\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\transform_markdown\\transform_containers.py\", line 424, in __abcd\n+# assert keep_going\n+# AssertionError\n+\n+# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_triple_drop\n+# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_quad_drop\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\transform_markdown\\transform_containers.py\", line 454, in __abcd_final_list\n+# assert removed_token_indices[0] < len(split_bleading_spaces)\n+# AssertionError\n+\n+\n+# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\transform_markdown\\transform_containers.py\", line 503, in __abcd_final\n+# assert container_indices_copy[-1] == len(list_split_spaces) - 1\n+# AssertionError\n+\n+# (probably bad regen after fix)\n # bad_fenced_block_in_list_in_list_with_previous_inner_block_double_drop\n # bad_fenced_block_in_block_quote_in_list_in_list_with_previous_list_triple_drop\n-# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_double_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_block_quad_drop\n # bad_fenced_block_in_block_quote_in_list_in_list_with_previous_block_triple_drop\n-# bad_fenced_block_in_list_in_list_with_previous_inner_list_double_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_block_double_drop_with_thematics\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_block_triple_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_list_triple_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop\n+# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\tokens\\markdown_token.py\", line 599, in adjust_line_number\n+# raise BadPluginFixError(\n+# pymarkdown.plugin_manager.bad_plugin_fix_error.BadPluginFixError: Token 'fcode-block' can only be modified during the token pass in fix mode.\n+\n+# (probably bad regen after fix)\n # bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_blockx_double_drop\n # bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_list_triple_drop_and_thematics\n-# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n-# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_triple_drop_with_thematics\n-# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n-# bad_fenced_block_in_list_in_block_quote_with_previous_inner_list_double_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_list_quad_drop]\n-# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_quad_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_quad_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_block_quad_drop\n-# bad_fenced_block_in_block_quote_in_list_with_previous_inner_list_triple_drop\n-# bad_fenced_block_in_block_quote_in_list_with_previous_inner_block_triple_drop\n-# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_double_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop_with_thematics\n-# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop\n-# bad_fenced_block_in_list_with_previous_inner_block_double_drop\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\block_quotes\\block_quote_processor.py\", line 698, in __handle_existing_block_quote_fenced_special_part_two\n+# assert sd == \">\"\n+# AssertionError\n", "FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_with_previous_inner_block_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_list_with_previous_inner_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_with_previous_inner_list_double_drop]"]}, {"instance_id": "jackdewinter__pymarkdown-1248", "base_commit": "cee1f3f5575f73b671deb4374c6e7a263fa40df9", "gold_patch": "diff --git a/newdocs/src/changelog.md b/newdocs/src/changelog.md\nindex be928638..9acc115f 100644\n--- a/newdocs/src/changelog.md\n+++ b/newdocs/src/changelog.md\n@@ -23,6 +23,10 @@\n - [Issue 1245](https://github.com/jackdewinter/pymarkdown/issues/1245)\n - Handling leading spaces in `__fix_spacing` function now that data\n is present.\n+- [Issue 1247](https://github.com/jackdewinter/pymarkdown/issues/1247)\n+ - In 3+ drop cases with only lists and no block quotes, indent is\n+ not calculated properly on rehydrate. This in turn causes the\n+ fixed text to be wrong.\n \n \n ### Changed\ndiff --git a/publish/coverage.json b/publish/coverage.json\nindex 398dc062..11801c21 100644\n--- a/publish/coverage.json\n+++ b/publish/coverage.json\n@@ -2,12 +2,12 @@\n \"projectName\": \"pymarkdown\",\n \"reportSource\": \"pytest\",\n \"branchLevel\": {\n- \"totalMeasured\": 5393,\n- \"totalCovered\": 5392\n+ \"totalMeasured\": 5403,\n+ \"totalCovered\": 5401\n },\n \"lineLevel\": {\n- \"totalMeasured\": 21094,\n- \"totalCovered\": 21093\n+ \"totalMeasured\": 21123,\n+ \"totalCovered\": 21122\n }\n }\n \ndiff --git a/pymarkdown/plugins/rule_md_031.py b/pymarkdown/plugins/rule_md_031.py\nindex 07d958bc..c6ebf6fc 100644\n--- a/pymarkdown/plugins/rule_md_031.py\n+++ b/pymarkdown/plugins/rule_md_031.py\n@@ -56,6 +56,7 @@ class RuleMd031(RulePlugin):\n self.__removed_container_adjustments: Optional[\n List[PendingContainerAdjustment]\n ] = None\n+ self.__last_end_container_tokens: List[MarkdownToken] = []\n \n self.__leading_space_index_tracker = LeadingSpaceIndexTracker()\n \n@@ -513,17 +514,26 @@ class RuleMd031(RulePlugin):\n new_token.adjust_line_number(context, self.__fix_count)\n assert self.__last_token is not None\n if token.is_fenced_code_block and self.__last_token.is_list_end:\n+ end_container_index = len(self.__last_end_container_tokens) - 1\n+ while (\n+ end_container_index >= 0\n+ and self.__last_end_container_tokens[end_container_index].is_list_end\n+ ):\n+ end_container_index -= 1\n+ first_token = self.__last_end_container_tokens[end_container_index + 1]\n replacement_tokens: List[MarkdownToken] = [\n BlankLineMarkdownToken(\n extracted_whitespace=\"\",\n position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n column_delta=1,\n- ),\n- self.__last_token,\n- new_token,\n+ )\n ]\n+ replacement_tokens.extend(\n+ self.__last_end_container_tokens[end_container_index + 1 :]\n+ )\n+ replacement_tokens.append(new_token)\n self.register_replace_tokens_request(\n- context, self.__last_token, token, replacement_tokens\n+ context, first_token, token, replacement_tokens\n )\n elif did_special_list_fix:\n assert self.__last_token and self.__last_token.is_block_quote_end\n@@ -755,6 +765,11 @@ class RuleMd031(RulePlugin):\n ):\n self.__last_non_end_token = token\n \n+ if token.is_block_quote_end or token.is_list_end:\n+ self.__last_end_container_tokens.append(token)\n+ else:\n+ self.__last_end_container_tokens.clear()\n+\n self.__second_last_token = self.__last_token\n self.__last_token = token\n self.__removed_container_stack_token = None\ndiff --git a/pymarkdown/transform_markdown/transform_containers.py b/pymarkdown/transform_markdown/transform_containers.py\nindex 18b20bc9..f3d5eb56 100644\n--- a/pymarkdown/transform_markdown/transform_containers.py\n+++ b/pymarkdown/transform_markdown/transform_containers.py\n@@ -426,9 +426,55 @@ class TransformContainers:\n \n # pylint: enable=too-many-arguments, too-many-boolean-expressions\n \n+ @staticmethod\n+ def __abcd_final_list_second_half(\n+ removed_tokens: List[MarkdownToken],\n+ removed_token_indices: List[int],\n+ container_stack: List[MarkdownToken],\n+ possible_prefix: Optional[str],\n+ ) -> Optional[str]:\n+ container_stack_copy: List[MarkdownToken] = container_stack[:]\n+ container_stack_copy.extend(removed_tokens[::-1])\n+ is_only_list_starts_on_stack = not any(\n+ i.is_block_quote_start for i in container_stack_copy\n+ )\n+\n+ prefix = None\n+ if is_only_list_starts_on_stack and possible_prefix is not None:\n+ prefix = possible_prefix\n+ token_index = len(removed_tokens) - 1\n+ while token_index >= 0:\n+ list_token = cast(ListStartMarkdownToken, removed_tokens[token_index])\n+ assert list_token.leading_spaces is None\n+ assert removed_token_indices[token_index] == 0\n+ token_index -= 1\n+ del removed_tokens[0]\n+ del removed_token_indices[0]\n+\n+ list_token = cast(ListStartMarkdownToken, container_stack[-1])\n+ current_indent_level = list_token.indent_level if container_stack else 0\n+ prefix = \" \" * current_indent_level\n+ else:\n+ if removed_tokens[0].is_block_quote_start:\n+ removed_block_quote_token = cast(\n+ BlockQuoteMarkdownToken, removed_tokens[0]\n+ )\n+ assert removed_block_quote_token.bleading_spaces is not None\n+ split_bleading_spaces = removed_block_quote_token.bleading_spaces.split(\n+ \"\\n\"\n+ )\n+ assert removed_token_indices[0] < len(split_bleading_spaces)\n+ prefix = \"\" if possible_prefix is None else possible_prefix\n+ prefix = f\"{split_bleading_spaces[removed_token_indices[0]]}{prefix}\"\n+ del removed_tokens[0]\n+ del removed_token_indices[0]\n+ return prefix\n+\n @staticmethod\n def __abcd_final_list(\n- removed_tokens: List[MarkdownToken], removed_token_indices: List[int]\n+ removed_tokens: List[MarkdownToken],\n+ removed_token_indices: List[int],\n+ container_stack: List[MarkdownToken],\n ) -> Optional[str]:\n removed_list_token = cast(ListStartMarkdownToken, removed_tokens[0])\n assert removed_list_token.leading_spaces is not None\n@@ -437,26 +483,17 @@ class TransformContainers:\n # prefix is None for most cases\n possible_prefix = None\n if (\n- removed_token_indices[0] < len(split_leading_spaces)\n- and split_leading_spaces[removed_token_indices[0]]\n+ removed_token_indices[0]\n+ < len(split_leading_spaces)\n+ # and split_leading_spaces[removed_token_indices[0]]\n ):\n possible_prefix = split_leading_spaces[removed_token_indices[0]]\n del removed_tokens[0]\n del removed_token_indices[0]\n \n- prefix = None\n- if removed_tokens[0].is_block_quote_start:\n- removed_block_quote_token = cast(BlockQuoteMarkdownToken, removed_tokens[0])\n- assert removed_block_quote_token.bleading_spaces is not None\n- split_bleading_spaces = removed_block_quote_token.bleading_spaces.split(\n- \"\\n\"\n- )\n- assert removed_token_indices[0] < len(split_bleading_spaces)\n- prefix = \"\" if possible_prefix is None else possible_prefix\n- prefix = f\"{split_bleading_spaces[removed_token_indices[0]]}{prefix}\"\n- del removed_tokens[0]\n- del removed_token_indices[0]\n- return prefix\n+ return TransformContainers.__abcd_final_list_second_half(\n+ removed_tokens, removed_token_indices, container_stack, possible_prefix\n+ )\n \n @staticmethod\n def __abcd_final(\n@@ -506,7 +543,7 @@ class TransformContainers:\n del removed_token_indices[0]\n else:\n prefix = TransformContainers.__abcd_final_list(\n- removed_tokens, removed_token_indices\n+ removed_tokens, removed_token_indices, container_stack\n )\n return prefix\n \n", "test_patch": "diff --git a/publish/test-results.json b/publish/test-results.json\nindex 7e2b78aa..0fe7cc94 100644\n--- a/publish/test-results.json\n+++ b/publish/test-results.json\n@@ -1367,7 +1367,7 @@\n \"totalTests\": 653,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 62,\n+ \"skippedTests\": 61,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\n@@ -1620,7 +1620,7 @@\n },\n {\n \"name\": \"test.test_markdown_extra\",\n- \"totalTests\": 206,\n+ \"totalTests\": 210,\n \"failedTests\": 0,\n \"errorTests\": 0,\n \"skippedTests\": 3,\ndiff --git a/test/rules/test_md031.py b/test/rules/test_md031.py\nindex 435a4958..d1538cae 100644\n--- a/test/rules/test_md031.py\n+++ b/test/rules/test_md031.py\n@@ -30,6 +30,7 @@ The value for property 'plugins.md031.list_items' must be of type 'bool'.\"\"\",\n ),\n ]\n \n+skip_fix_bad_markdown = True\n skip_fix_asserts = True\n \n scanTests = [\n@@ -810,7 +811,7 @@ A code block\n This is a blank line and some text.\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n scan_expected_return_code=1,\n scan_expected_output=\"\"\"{temp_source_path}:3:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n {temp_source_path}:5:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n@@ -2188,7 +2189,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > > block 3\n > > > block 3\n > > > block 3\n@@ -2469,7 +2470,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + block 3\n > > block 3\n > > + block 3\n@@ -2652,7 +2653,7 @@ A code block\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > > fourth block 1\n > > > > fourth block 2\n@@ -2910,7 +2911,7 @@ A code block\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > + inner list 1\n > > > inner list 2\n@@ -2939,7 +2940,7 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > + inner list 1\n > > > inner list 2\n@@ -3130,7 +3131,7 @@ A code block\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n use_debug=True,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n@@ -3270,7 +3271,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3300,7 +3301,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3419,7 +3420,7 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -3537,7 +3538,7 @@ ______\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -4245,7 +4246,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > block 1\n > > > block 2\n@@ -4350,7 +4351,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4377,7 +4378,7 @@ A code block\n {temp_source_path}:6:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4480,7 +4481,7 @@ A code block\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4822,7 +4823,7 @@ A code block\n {temp_source_path}:8:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4853,7 +4854,7 @@ A code block\n {temp_source_path}:8:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4944,7 +4945,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5080,7 +5081,7 @@ A code block\n {temp_source_path}:7:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5109,7 +5110,7 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5200,7 +5201,7 @@ A code block\n {temp_source_path}:7:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5229,7 +5230,7 @@ A code block\n {temp_source_path}:7:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5317,7 +5318,7 @@ A code block\n {temp_source_path}:8:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5348,7 +5349,7 @@ A code block\n {temp_source_path}:8:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5647,7 +5648,7 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + list 1\n > > block 2\n > > block 3\n@@ -6312,7 +6313,7 @@ another list\n \"\"\",\n disable_rules=\"md032,md027,md007,md023\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6643,7 +6644,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6947,7 +6948,7 @@ another list\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -6976,7 +6977,7 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7064,7 +7065,7 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7095,7 +7096,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7347,7 +7348,7 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > + list 1\n > list 2\n@@ -7657,7 +7658,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -7688,7 +7689,7 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -8293,7 +8294,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > > block 1\n > > block 2\n@@ -8420,7 +8421,7 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8546,7 +8547,7 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8579,7 +8580,7 @@ another list\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8776,7 +8777,7 @@ another list\n another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050c2 test_extra_050c3\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\",\n source_file_contents=\"\"\"+ + + -----\n > block 1\n@@ -8866,7 +8867,7 @@ another list\n + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050c0 test_extra_050c1\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\",\n source_file_contents=\"\"\"+ + + -----\n > block 1\n@@ -8883,7 +8884,6 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n > block 1\n > block 2\ndiff --git a/test/test_markdown_extra.py b/test/test_markdown_extra.py\nindex 272eec4c..191c52c5 100644\n--- a/test/test_markdown_extra.py\n+++ b/test/test_markdown_extra.py\n@@ -9243,6 +9243,279 @@ list 2\n act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n \n \n+@pytest.mark.gfm\n+def test_extra_050c0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+ -----\n+ ```block\n+ A code block\n+ ```\n+ -----\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:: \\n \\n \\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[tbreak(4,3):-::-----]\",\n+ \"[fcode-block(5,3):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(8,3):-::-----]\",\n+ \"[para(9,3):]\",\n+ \"[text(9,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(10,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+another list
  • \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+ -----\n+\n+ ```block\n+ A code block\n+ ```\n+\n+ -----\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2::\\n \\n \\n \\n\\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[tbreak(4,3):-::-----]\",\n+ \"[BLANK(5,1):]\",\n+ \"[fcode-block(6,3):`:3:block:::::]\",\n+ \"[text(7,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(9,1):]\",\n+ \"[tbreak(10,3):-::-----]\",\n+ \"[para(11,3):]\",\n+ \"[text(11,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(12,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+

    another list

    \n+
  • \n+
\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c2():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+```block\n+A code block\n+```\n+-----\n+another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,1):`:3:block:::::]\",\n+ \"[text(5,1):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,1):-::-----]\",\n+ \"[para(8,1):]\",\n+ \"[text(8,1):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(9,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
  • \n+
\n+
A code block\n+
\n+
\n+

another list

\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c3():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+\n+```block\n+A code block\n+```\n+\n+-----\n+another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > \\n]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(4,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,1):`:3:block:::::]\",\n+ \"[text(6,1):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,1):]\",\n+ \"[tbreak(9,1):-::-----]\",\n+ \"[para(10,1):]\",\n+ \"[text(10,1):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(11,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
  • \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
  • \n+
\n+
A code block\n+
\n+
\n+

another list

\"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n @pytest.mark.gfm\n def test_extra_999():\n \"\"\"\n@@ -9270,9 +9543,9 @@ def test_extra_999():\n \n \n # Fix\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n \n # Bad fix\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n", "FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics]", "test/test_markdown_extra.py::test_extra_050c0", "test/test_markdown_extra.py::test_extra_050c1"]}], "all_FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_with_previous_inner_block_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_list_with_previous_inner_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics]", "test/test_markdown_extra.py::test_extra_050c0", "test/test_markdown_extra.py::test_extra_050c1"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Duke-GCB__bespin-cli-16_x2", "level": 2, "source": "swerebench", "repo": "Duke-GCB/bespin-cli", "image": "swerebench/sweb.eval.x86_64.duke-gcb_1776_bespin-cli-16:latest", "base_commit": "471cd4df56c852bee11fcb4725dc6b4e9053e08c", "num_bugs": 2, "bugs": [{"instance_id": "Duke-GCB__bespin-cli-16", "base_commit": "471cd4df56c852bee11fcb4725dc6b4e9053e08c", "gold_patch": "diff --git a/bespin/api.py b/bespin/api.py\nindex 5558ccd..dad9652 100644\n--- a/bespin/api.py\n+++ b/bespin/api.py\n@@ -103,7 +103,7 @@ class BespinApi(object):\n return self._post_request('/job-file-stage-groups/', {})\n \n def dds_job_input_files_post(self, project_id, file_id, destination_path, sequence_group, sequence,\n- dds_user_credentials, stage_group_id):\n+ dds_user_credentials, stage_group_id, size):\n data = {\n \"project_id\": project_id,\n \"file_id\": file_id,\n@@ -111,7 +111,8 @@ class BespinApi(object):\n \"sequence_group\": sequence_group,\n \"sequence\": sequence,\n \"dds_user_credentials\": dds_user_credentials,\n- \"stage_group\": stage_group_id\n+ \"stage_group\": stage_group_id,\n+ \"size\": size,\n }\n return self._post_request('/dds-job-input-files/', data)\n \ndiff --git a/bespin/commands.py b/bespin/commands.py\nindex c8c1fb6..e30d252 100644\n--- a/bespin/commands.py\n+++ b/bespin/commands.py\n@@ -288,8 +288,10 @@ class JobFile(object):\n dds_project_ids = set()\n sequence = 0\n for dds_file, path in self.get_dds_files_details():\n+ file_size = dds_file.current_version['upload']['size']\n api.dds_job_input_files_post(dds_file.project_id, dds_file.id, path, 0, sequence,\n- dds_user_credential['id'], stage_group_id=stage_group['id'])\n+ dds_user_credential['id'], stage_group_id=stage_group['id'],\n+ size=file_size)\n sequence += 1\n dds_project_ids.add(dds_file.project_id)\n user_job_order_json = self.create_user_job_order_json()\ndiff --git a/bespin/dukeds.py b/bespin/dukeds.py\nindex 8753d3f..47816e2 100644\n--- a/bespin/dukeds.py\n+++ b/bespin/dukeds.py\n@@ -8,6 +8,7 @@ INVALID_DUKEDS_FILE_PATH_MSG = \"Invalid DukeDS file path ({})\"\n DUKEDS_FILE_PATH_MISSING_PREFIX = INVALID_DUKEDS_FILE_PATH_MSG.format(\"missing prefix\")\n DUKEDS_FILE_PATH_MISSING_SLASH = INVALID_DUKEDS_FILE_PATH_MSG.format(\"missing / between project and file path\")\n \n+\n class DDSFileUtil(object):\n def __init__(self):\n self.client = Client()\n", "test_patch": "diff --git a/bespin/test_api.py b/bespin/test_api.py\nindex 99ad636..30f1804 100644\n--- a/bespin/test_api.py\n+++ b/bespin/test_api.py\n@@ -145,7 +145,8 @@ class BespinApiTestCase(TestCase):\n api = BespinApi(config=self.mock_config, user_agent_str=self.mock_user_agent_str)\n dds_input_file = api.dds_job_input_files_post(project_id='123', file_id='456', destination_path='data.txt',\n sequence_group=1, sequence=2,\n- dds_user_credentials=4, stage_group_id=5)\n+ dds_user_credentials=4, stage_group_id=5,\n+ size=1000)\n \n self.assertEqual(dds_input_file, 'dds-job-input-file1')\n expected_json = {\n@@ -155,7 +156,8 @@ class BespinApiTestCase(TestCase):\n 'sequence_group': 1,\n 'sequence': 2,\n 'dds_user_credentials': 4,\n- 'stage_group': 5\n+ 'stage_group': 5,\n+ 'size': 1000,\n }\n mock_requests.post.assert_called_with('someurl/dds-job-input-files/', headers=self.expected_headers,\n json=expected_json)\ndiff --git a/bespin/test_commands.py b/bespin/test_commands.py\nindex 5bd78a8..486bf81 100644\n--- a/bespin/test_commands.py\n+++ b/bespin/test_commands.py\n@@ -336,14 +336,15 @@ class JobFileTestCase(TestCase):\n 'myint': 555\n })\n job_file.get_dds_files_details = Mock()\n- mock_file = Mock(project_id=666)\n+ mock_file = Mock(project_id=666, current_version={'upload': {'size': 4002}})\n mock_file.id = 777\n job_file.get_dds_files_details.return_value = [[mock_file, 'somepath']]\n \n job_file.create_job(mock_api)\n \n mock_api.questionnaires_list.assert_called_with(tag='sometag')\n- mock_api.dds_job_input_files_post.assert_called_with(666, 777, 'somepath', 0, 0, 111, stage_group_id=333)\n+ mock_api.dds_job_input_files_post.assert_called_with(666, 777, 'somepath', 0, 0, 111, stage_group_id=333,\n+ size=4002)\n json_payload = '{\"myfile\": {\"class\": \"File\", \"path\": \"dds_project_somepath.txt\"}, \"myint\": 555}'\n mock_api.job_answer_set_post.assert_called_with('myjob', '001', json_payload, 222, 333)\n mock_api.job_answer_set_create_job.assert_called_with(444)\n", "FAIL_TO_PASS": ["bespin/test_api.py::BespinApiTestCase::test_dds_job_input_files_post", "bespin/test_commands.py::JobFileTestCase::test_create_job"]}, {"instance_id": "Duke-GCB__bespin-cli-18", "base_commit": "3cb0cf75ca821e051ea48d4b1a990f34acedd98d", "gold_patch": "diff --git a/bespin/commands.py b/bespin/commands.py\nindex e30d252..1766e96 100644\n--- a/bespin/commands.py\n+++ b/bespin/commands.py\n@@ -3,6 +3,7 @@ from bespin.config import ConfigFile\n from bespin.api import BespinApi\n from bespin.exceptions import IncompleteJobFileException\n from bespin.dukeds import DDSFileUtil\n+from bespin.dukeds import PATH_PREFIX as DUKEDS_PATH_PREFIX\n from tabulate import tabulate\n import yaml\n import json\n@@ -411,8 +412,8 @@ class JobOrderWalker(object):\n :param path: str: format dds:///\n :return: str: file path to be used for staging data when running the workflow\n \"\"\"\n- if path.startswith(\"dds://\"):\n- return path.replace(\"dds://\", \"dds_\").replace(\"/\", \"_\").replace(\":\", \"_\")\n+ if path.startswith(DUKEDS_PATH_PREFIX):\n+ return path.replace(DUKEDS_PATH_PREFIX, \"dds_\").replace(\"/\", \"_\").replace(\":\", \"_\")\n return path\n \n \n@@ -421,8 +422,10 @@ class JobOrderPlaceholderCheck(JobOrderWalker):\n self.keys_with_placeholders = set()\n \n def on_class_value(self, top_level_key, value):\n- if value['class'] == 'File' and value['path'] in USER_PLACEHOLDER_VALUES:\n- self.keys_with_placeholders.add(top_level_key)\n+ if value['class'] == 'File':\n+ path = value.get('path')\n+ if path and path in USER_PLACEHOLDER_VALUES:\n+ self.keys_with_placeholders.add(top_level_key)\n \n def on_simple_value(self, top_level_key, value):\n if value in USER_PLACEHOLDER_VALUES:\n@@ -432,7 +435,9 @@ class JobOrderPlaceholderCheck(JobOrderWalker):\n class JobOrderFormatFiles(JobOrderWalker):\n def on_class_value(self, top_level_key, value):\n if value['class'] == 'File':\n- value['path'] = self.format_file_path(value['path'])\n+ path = value.get('path')\n+ if path:\n+ value['path'] = self.format_file_path(path)\n \n \n class JobOrderFileDetails(JobOrderWalker):\n@@ -442,6 +447,7 @@ class JobOrderFileDetails(JobOrderWalker):\n \n def on_class_value(self, top_level_key, value):\n if value['class'] == 'File':\n- path = value['path']\n- dds_file = self.dds_file_util.find_file_for_path(path)\n- self.dds_files.append((dds_file, self.format_file_path(path)))\n+ path = value.get('path')\n+ if path and path.startswith(DUKEDS_PATH_PREFIX):\n+ dds_file = self.dds_file_util.find_file_for_path(path)\n+ self.dds_files.append((dds_file, self.format_file_path(path)))\n", "test_patch": "diff --git a/bespin/test_commands.py b/bespin/test_commands.py\nindex 486bf81..c03c245 100644\n--- a/bespin/test_commands.py\n+++ b/bespin/test_commands.py\n@@ -250,6 +250,14 @@ class JobFileTestCase(TestCase):\n 'class': 'File',\n 'path': 'dds://project/somepath.txt'\n },\n+ 'my_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'my_url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n 'myint': 123,\n 'myfileary': [\n {\n@@ -298,6 +306,14 @@ class JobFileTestCase(TestCase):\n 'path': 'dds_myproject_rawData_SAAAA_R2_001.fastq.gz'\n },\n 'name': 'Sample1'}])\n+ self.assertEqual(user_job_order['my_path_file'], {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ }, \"Plain file paths should not be modified.\")\n+ self.assertEqual(user_job_order['my_url_file'], {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ }, \"URL file paths should not be modified.\")\n \n @patch('bespin.commands.DDSFileUtil')\n def test_get_dds_files_details(self, mock_dds_file_util):\n@@ -529,7 +545,15 @@ class JobOrderWalkerTestCase(TestCase):\n 'class': 'File',\n 'path': 'somepath3'\n }]\n- }\n+ },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n })\n \n walker.on_simple_value.assert_has_calls([\n@@ -592,6 +616,14 @@ class JobOrderPlaceholderCheckTestCase(TestCase):\n 'path': FILE_PLACEHOLDER,\n }\n },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n }\n expected_keys = [\n 'bad_str', 'bad_int', 'bad_file', 'bad_str_ary', 'bad_file_ary', 'bad_file_dict',\n@@ -623,6 +655,14 @@ class JobOrderFormatFilesTestCase(TestCase):\n 'path': 'dds://project3/data/other/somepath.txt',\n }\n },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n }\n \n formatter = JobOrderFormatFiles()\n@@ -661,6 +701,14 @@ class JobOrderFileDetailsTestCase(TestCase):\n 'path': 'dds://project3/data/other/somepath.txt',\n }\n },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n }\n expected_dds_file_info = [\n ('ddsfiledata', 'dds_project1_data_somepath.txt'),\n", "FAIL_TO_PASS": ["bespin/test_commands.py::JobFileTestCase::test_create_user_job_order_json", "bespin/test_commands.py::JobOrderPlaceholderCheckTestCase::test_walk", "bespin/test_commands.py::JobOrderFormatFilesTestCase::test_walk", "bespin/test_commands.py::JobOrderFileDetailsTestCase::test_walk"]}], "all_FAIL_TO_PASS": ["bespin/test_api.py::BespinApiTestCase::test_dds_job_input_files_post", "bespin/test_commands.py::JobFileTestCase::test_create_job", "bespin/test_commands.py::JobFileTestCase::test_create_user_job_order_json", "bespin/test_commands.py::JobOrderPlaceholderCheckTestCase::test_walk", "bespin/test_commands.py::JobOrderFormatFilesTestCase::test_walk", "bespin/test_commands.py::JobOrderFileDetailsTestCase::test_walk"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ipython__ipykernel-1049_x2", "level": 2, "source": "swerebench", "repo": "ipython/ipykernel", "image": "swerebench/sweb.eval.x86_64.ipython_1776_ipykernel-1049:latest", "base_commit": "4dc303364ca73b5185685807de41c7fe4b4a4dc7", "num_bugs": 2, "bugs": [{"instance_id": "ipython__ipykernel-1049", "base_commit": "4dc303364ca73b5185685807de41c7fe4b4a4dc7", "gold_patch": "diff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex f1fb0c8..c06d233 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -71,6 +71,9 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def __init__(self, *args, **kwargs):\n # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n+ for name in self.trait_names():\n+ if name in kwargs:\n+ kwargs.pop(name)\n BaseComm.__init__(self, *args, **kwargs)\n \n \ndiff --git a/ipykernel/ipkernel.py b/ipykernel/ipkernel.py\nindex f86f304..4dfe59c 100644\n--- a/ipykernel/ipkernel.py\n+++ b/ipykernel/ipkernel.py\n@@ -5,6 +5,7 @@ import builtins\n import getpass\n import signal\n import sys\n+import threading\n import typing as t\n from contextlib import contextmanager\n from functools import partial\n@@ -46,9 +47,19 @@ def _create_comm(*args, **kwargs):\n return BaseComm(*args, **kwargs)\n \n \n+# there can only be one comm manager in a ipykernel process\n+_comm_lock = threading.Lock()\n+_comm_manager: t.Optional[CommManager] = None\n+\n+\n def _get_comm_manager(*args, **kwargs):\n \"\"\"Create a new CommManager.\"\"\"\n- return CommManager(*args, **kwargs)\n+ global _comm_manager\n+ if _comm_manager is None:\n+ with _comm_lock:\n+ if _comm_manager is None:\n+ _comm_manager = CommManager(*args, **kwargs)\n+ return _comm_manager\n \n \n comm.create_comm = _create_comm\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 33c0546..f1e536d 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -27,8 +27,8 @@ requires-python = \">=3.8\"\n dependencies = [\n \"debugpy>=1.0\",\n \"ipython>=7.23.1\",\n- \"comm>=0.1\",\n- \"traitlets>=5.1.0\",\n+ \"comm>=0.1.1\",\n+ \"traitlets>=5.4.0\",\n \"jupyter_client>=6.1.12\",\n \"tornado>=6.1\",\n \"matplotlib-inline>=0.1\",\n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex 3ab1e5c..9dd49f8 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -1,7 +1,87 @@\n-from ipykernel.comm import Comm\n+from ipykernel.comm import Comm, CommManager\n+from ipykernel.ipkernel import IPythonKernel\n \n \n-async def test_comm(kernel):\n- c = Comm()\n- c.kernel = kernel # type:ignore\n+def test_comm(kernel):\n+ manager = CommManager(kernel=kernel)\n+ kernel.comm_manager = manager\n+\n+ c = Comm(kernel=kernel)\n+ msgs = []\n+\n+ def on_close(msg):\n+ msgs.append(msg)\n+\n+ def on_message(msg):\n+ msgs.append(msg)\n+\n c.publish_msg(\"foo\")\n+ c.open({})\n+ c.on_msg(on_message)\n+ c.on_close(on_close)\n+ c.handle_msg({})\n+ c.handle_close({})\n+ c.close()\n+ assert len(msgs) == 2\n+\n+\n+def test_comm_manager(kernel):\n+ manager = CommManager(kernel=kernel)\n+ msgs = []\n+\n+ def foo(comm, msg):\n+ msgs.append(msg)\n+ comm.close()\n+\n+ def fizz(comm, msg):\n+ raise RuntimeError('hi')\n+\n+ def on_close(msg):\n+ msgs.append(msg)\n+\n+ def on_msg(msg):\n+ msgs.append(msg)\n+\n+ manager.register_target(\"foo\", foo)\n+ manager.register_target(\"fizz\", fizz)\n+\n+ kernel.comm_manager = manager\n+ comm = Comm()\n+ comm.on_msg(on_msg)\n+ comm.on_close(on_close)\n+ manager.register_comm(comm)\n+\n+ assert manager.get_comm(comm.comm_id) == comm\n+ assert manager.get_comm('foo') is None\n+\n+ msg = dict(content=dict(comm_id=comm.comm_id, target_name='foo'))\n+ manager.comm_open(None, None, msg)\n+ assert len(msgs) == 1\n+ msg['content']['target_name'] = 'bar'\n+ manager.comm_open(None, None, msg)\n+ assert len(msgs) == 1\n+ msg = dict(content=dict(comm_id=comm.comm_id, target_name='fizz'))\n+ manager.comm_open(None, None, msg)\n+ assert len(msgs) == 1\n+\n+ manager.register_comm(comm)\n+ assert manager.get_comm(comm.comm_id) == comm\n+ msg = dict(content=dict(comm_id=comm.comm_id))\n+ manager.comm_msg(None, None, msg)\n+ assert len(msgs) == 2\n+ msg['content']['comm_id'] = 'foo'\n+ manager.comm_msg(None, None, msg)\n+ assert len(msgs) == 2\n+\n+ manager.register_comm(comm)\n+ assert manager.get_comm(comm.comm_id) == comm\n+ msg = dict(content=dict(comm_id=comm.comm_id))\n+ manager.comm_close(None, None, msg)\n+ assert len(msgs) == 3\n+\n+ assert comm._closed\n+\n+\n+def test_comm_in_manager(ipkernel: IPythonKernel) -> None:\n+ comm = Comm()\n+ assert comm.comm_id in ipkernel.comm_manager.comms\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm", "ipykernel/tests/test_comm.py::test_comm_in_manager"]}, {"instance_id": "ipython__ipykernel-1051", "base_commit": "b13c46ac5fa800359748386c64f89402ac0e204e", "gold_patch": "diff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex c06d233..295232e 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -71,9 +71,8 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def __init__(self, *args, **kwargs):\n # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n- for name in self.trait_names():\n- if name in kwargs:\n- kwargs.pop(name)\n+ # drop arguments not in BaseComm\n+ kwargs.pop(\"kernel\", None)\n BaseComm.__init__(self, *args, **kwargs)\n \n \n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex 9dd49f8..f8b0764 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -6,7 +6,7 @@ def test_comm(kernel):\n manager = CommManager(kernel=kernel)\n kernel.comm_manager = manager\n \n- c = Comm(kernel=kernel)\n+ c = Comm(kernel=kernel, target_name=\"bar\")\n msgs = []\n \n def on_close(msg):\n@@ -23,6 +23,7 @@ def test_comm(kernel):\n c.handle_close({})\n c.close()\n assert len(msgs) == 2\n+ assert c.target_name == \"bar\"\n \n \n def test_comm_manager(kernel):\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm"]}], "all_FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm", "ipykernel/tests/test_comm.py::test_comm_in_manager", "ipykernel/tests/test_comm.py::test_comm"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Toloka__crowd-kit-114_x2", "level": 2, "source": "swerebench", "repo": "Toloka/crowd-kit", "image": "swerebench/sweb.eval.x86_64.toloka_1776_crowd-kit-114:latest", "base_commit": "582ff25fad992fe9d8fd4d448d9b30dc9e3cf15b", "num_bugs": 2, "bugs": [{"instance_id": "Toloka__crowd-kit-114", "base_commit": "582ff25fad992fe9d8fd4d448d9b30dc9e3cf15b", "gold_patch": "diff --git a/README.md b/README.md\nindex 467a837..e258116 100644\n--- a/README.md\n+++ b/README.md\n@@ -37,7 +37,8 @@ If you are interested in contributing to Crowd-Kit, use [uv](https://github.com/\n \n ```shell\n uv venv\n-uv pip install -e '.[dev,docs,learning]\n+uv pip install -e '.[dev,docs,learning]'\n+uv tool run pre-commit install\n ```\n \n We use [pytest](https://pytest.org/) for testing and a variety of linters, including [pre-commit](https://pre-commit.com/), [Black](https://github.com/psf/black), [isort](https://github.com/pycqa/isort), [Flake8](https://github.com/pycqa/flake8), [pyupgrade](https://github.com/asottile/pyupgrade), and [nbQA](https://github.com/nbQA-dev/nbQA), to simplify code maintenance.\ndiff --git a/crowdkit/aggregation/classification/dawid_skene.py b/crowdkit/aggregation/classification/dawid_skene.py\nindex aaf4307..1fbe7e2 100644\n--- a/crowdkit/aggregation/classification/dawid_skene.py\n+++ b/crowdkit/aggregation/classification/dawid_skene.py\n@@ -1,6 +1,6 @@\n __all__ = [\"DawidSkene\", \"OneCoinDawidSkene\"]\n \n-from typing import Any, List, Optional, cast\n+from typing import Any, List, Literal, Optional, cast\n \n import attr\n import numpy as np\n@@ -55,6 +55,47 @@ class DawidSkene(BaseClassificationAggregator):\n >>> true_labels = gt[:1000] # use the first 100 true labels\n >>> ds = DawidSkene(100)\n >>> result = ds.fit_predict(df, true_labels)\n+\n+ We can also provide the workers' initial error matrices, which come from historical performance data.\n+ There two strategies to initialize the workers' error matrices: `assign` and `addition`.\n+ Here we create simple error matrices with two workers:\n+\n+ ```\n+ 0 1\n+ worker label\n+ w851 0 9 1\n+ 1 1 9\n+ w6991 0 9 1\n+ 1 1 9\n+ ```\n+\n+ Note:\n+ 1. Make sure the error matrix is indexed by `worker` and `label`\n+ with columns for every `label_id` appeared in `data`.\n+ You can use the `pandas.MultiIndex` to create such an index, see the example below.\n+\n+ 2. When using `addition` strategy, the error matrix should contain the history **count**(not probability) that `worker` produces `observed_label`,\n+ given that the task true label is `true_label`.\n+\n+ When we use the `addition` strategy, partial error matrices are acceptable,\n+ which will be added to the workers' priori error matrices estimated from the given data.\n+\n+ Examples:\n+ >>> import pandas as pd\n+ >>> from crowdkit.aggregation import DawidSkene\n+ >>> from crowdkit.datasets import load_dataset\n+ >>> df, gt = load_dataset('relevance-2')\n+ >>> error_matrix_index = pd.MultiIndex.from_arrays([['w851', 'w851', 'w6991', 'w6991'], [0, 1, 0, 1]], names=['worker', 'label'])\n+ >>> initial_error = pd.DataFrame(\n+ ... data=[[9, 1], [1, 9], [9, 1], [1, 9]],\n+ ... index=error_matrix_index,\n+ ... columns=[0, 1],\n+ ... )\n+ >>> ds = DawidSkene(100, initial_error_strategy='addition')\n+ >>> result = ds.fit_predict(df, initial_error=initial_error)\n+\n+ We can also use the `assign` strategy to initialize the workers' error matrices.\n+ But in this case, the `initial_error` **must** contain all the workers' error matrices in the data.\n \"\"\"\n \n n_iter: int = attr.ib(default=100)\n@@ -64,6 +105,44 @@ class DawidSkene(BaseClassificationAggregator):\n \"\"\"The tolerance stopping criterion for iterative methods with a variable number of steps.\n The algorithm converges when the loss change is less than the `tol` parameter.\"\"\"\n \n+ initial_error_strategy: Optional[Literal[\"assign\", \"addition\"]] = attr.ib(\n+ default=None\n+ )\n+ \"\"\"The strategy for initializing the workers' error matrices.\n+ The `assign` strategy assigns the initial error matrix to the workers' error matrices;\n+ the `addition` strategy adds the initial error matrix with the workers' priori error matrices estimated\n+ from the given data. If `None`, the initial error matrix is not used.\n+\n+ Note:\n+ - `addition` strategy\n+ - The initial error matrix can be partial, not all workers' error matrices need to be provided.\n+ - The initial error matrix values should be the history **count** that\n+ `worker` produces `observed_label`, given that the task true label is `true_label`.\n+ For example(count values error matrix):\n+\n+ 0 1\n+ worker label\n+ w851 0 9 1\n+ 1 1 9\n+ w6991 0 9 1\n+ 1 1 9\n+\n+ - `assign` strategy\n+ - The initial error matrix must contain all the workers' error matrices in the data.\n+ - The initial error matrix values could be the probability or count that\n+ `worker` produces `observed_label`, given that the task true label is `true_label`.\n+ When given probability error matrix, the values should sum up to 1 for each worker at each `true_label` column.\n+ For example(probability values error matrix):\n+\n+ 0 1\n+ worker label\n+ w851 0 0.9 0.1\n+ 1 0.1 0.9\n+ w6991 0 0.9 0.1\n+ 1 0.1 0.9\n+ ...\n+ \"\"\"\n+\n probas_: Optional[pd.DataFrame] = attr.ib(init=False)\n \"\"\"The probability distributions of task labels.\n The `pandas.Series` data is indexed by `task` so that `labels.loc[task]` is the most likely true label of tasks.\"\"\"\n@@ -83,15 +162,22 @@ class DawidSkene(BaseClassificationAggregator):\n \"\"\" A list of loss values during training.\"\"\"\n \n @staticmethod\n- def _m_step(data: pd.DataFrame, probas: pd.DataFrame) -> pd.DataFrame:\n+ def _m_step(\n+ data: pd.DataFrame,\n+ probas: pd.DataFrame,\n+ initial_error: Optional[pd.DataFrame] = None,\n+ initial_error_strategy: Optional[Literal[\"assign\", \"addition\"]] = None,\n+ ) -> pd.DataFrame:\n \"\"\"Performs M-step of the Dawid-Skene algorithm.\n \n Estimates the workers' error probability matrix using the specified workers' responses and the true task label probabilities.\n \"\"\"\n joined = data.join(probas, on=\"task\")\n joined.drop(columns=[\"task\"], inplace=True)\n-\n errors = joined.groupby([\"worker\", \"label\"], sort=False).sum()\n+ # Apply the initial error matrix\n+ errors = initial_error_apply(errors, initial_error, initial_error_strategy)\n+ # Normalize the error matrix\n errors.clip(lower=_EPS, inplace=True)\n errors /= errors.groupby(\"worker\", sort=False).sum()\n \n@@ -160,7 +246,10 @@ class DawidSkene(BaseClassificationAggregator):\n return float(joint_expectation + entropy)\n \n def fit(\n- self, data: pd.DataFrame, true_labels: Optional[\"pd.Series[Any]\"] = None\n+ self,\n+ data: pd.DataFrame,\n+ true_labels: Optional[\"pd.Series[Any]\"] = None,\n+ initial_error: Optional[pd.DataFrame] = None,\n ) -> \"DawidSkene\":\n \"\"\"Fits the model to the training data with the EM algorithm.\n \n@@ -171,7 +260,12 @@ class DawidSkene(BaseClassificationAggregator):\n The `pandas.Series` data is indexed by `task` so that `labels.loc[task]` is the task ground truth label.\n When provided, the model will correct the probability distributions of task labels by the true labels\n during the iterative process.\n-\n+ initial_error (DataFrame): The workers' initial error matrices, comes from historical performance data.\n+ The `pandas.DataFrame` data is indexed by `worker` and `label` with a column\n+ for every `label_id` found in `data` so that `result.loc[worker, observed_label, true_label]` is the\n+ history **count** that `worker` produces `observed_label`, given that the task true label is `true_label`.\n+ When the `initial_error_strategy` is `assign`, the values in the error matrix can be the probability too.\n+ Check the examples in the class docstring for more details.\n Returns:\n DawidSkene: self.\n \"\"\"\n@@ -192,7 +286,7 @@ class DawidSkene(BaseClassificationAggregator):\n if true_labels is not None:\n probas = self._correct_probas_with_golden(probas, true_labels)\n priors = probas.mean()\n- errors = self._m_step(data, probas)\n+ errors = self._m_step(data, probas, initial_error, self.initial_error_strategy)\n loss = -np.inf\n self.loss_history_ = []\n \n@@ -225,7 +319,10 @@ class DawidSkene(BaseClassificationAggregator):\n return self\n \n def fit_predict_proba(\n- self, data: pd.DataFrame, true_labels: Optional[\"pd.Series[Any]\"] = None\n+ self,\n+ data: pd.DataFrame,\n+ true_labels: Optional[\"pd.Series[Any]\"] = None,\n+ initial_error: Optional[pd.DataFrame] = None,\n ) -> pd.DataFrame:\n \"\"\"Fits the model to the training data and returns probability distributions of labels for each task.\n \n@@ -236,6 +333,12 @@ class DawidSkene(BaseClassificationAggregator):\n The `pandas.Series` data is indexed by `task` so that `labels.loc[task]` is the task ground truth label.\n When provided, the model will correct the probability distributions of task labels by the true labels\n during the iterative process.\n+ initial_error (DataFrame): The workers' initial error matrices, comes from historical performance data.\n+ The `pandas.DataFrame` data is indexed by `worker` and `label` with a column\n+ for every `label_id` found in `data` so that `result.loc[worker, observed_label, true_label]` is the\n+ history **count** that `worker` produces `observed_label`, given that the task true label is `true_label`.\n+ When the `initial_error_strategy` is `assign`, the values in the error matrix can be the probability too.\n+ Check the examples in the class docstring for more details.\n \n Returns:\n DataFrame: Probability distributions of task labels.\n@@ -243,12 +346,15 @@ class DawidSkene(BaseClassificationAggregator):\n Each probability is in the range from 0 to 1, all task probabilities must sum up to 1.\n \"\"\"\n \n- self.fit(data, true_labels)\n+ self.fit(data, true_labels, initial_error)\n assert self.probas_ is not None, \"no probas_\"\n return self.probas_\n \n def fit_predict(\n- self, data: pd.DataFrame, true_labels: Optional[\"pd.Series[Any]\"] = None\n+ self,\n+ data: pd.DataFrame,\n+ true_labels: Optional[\"pd.Series[Any]\"] = None,\n+ initial_error: Optional[pd.DataFrame] = None,\n ) -> \"pd.Series[Any]\":\n \"\"\"Fits the model to the training data and returns the aggregated results.\n \n@@ -259,12 +365,18 @@ class DawidSkene(BaseClassificationAggregator):\n The `pandas.Series` data is indexed by `task` so that `labels.loc[task]` is the task ground truth label.\n When provided, the model will correct the probability distributions of task labels by the true labels\n during the iterative process.\n+ initial_error (DataFrame): The workers' initial error matrices, comes from historical performance data.\n+ The `pandas.DataFrame` data is indexed by `worker` and `label` with a column\n+ for every `label_id` found in `data` so that `result.loc[worker, observed_label, true_label]` is the\n+ history **count** that `worker` produces `observed_label`, given that the task true label is `true_label`.\n+ When the `initial_error_strategy` is `assign`, the values in the error matrix can be the probability too.\n+ Check the examples in the class docstring for more details.\n \n Returns:\n Series: Task labels. The `pandas.Series` data is indexed by `task` so that `labels.loc[task]` is the most likely true label of tasks.\n \"\"\"\n \n- self.fit(data, true_labels)\n+ self.fit(data, true_labels, initial_error)\n assert self.labels_ is not None, \"no labels_\"\n return self.labels_\n \n@@ -292,6 +404,46 @@ class DawidSkene(BaseClassificationAggregator):\n return corrected_probas\n \n \n+def initial_error_apply(\n+ errors: pd.DataFrame,\n+ initial_error: Optional[pd.DataFrame],\n+ initial_error_strategy: Optional[Literal[\"assign\", \"addition\"]],\n+) -> pd.DataFrame:\n+ if initial_error_strategy is None or initial_error is None:\n+ return errors\n+ # check the index names of initial_error\n+ if initial_error.index.names != errors.index.names:\n+ raise ValueError(\n+ f\"The index of initial_error must be: {errors.index.names},\"\n+ f\"but got: {initial_error.index.names}\"\n+ )\n+ if initial_error_strategy == \"assign\":\n+ # check the completeness of initial_error: all the workers in data should be in initial_error\n+ mask = errors.index.isin(initial_error.index)\n+ if not mask.all():\n+ not_found_workers = errors.index[~mask].get_level_values(\"worker\").unique()\n+ raise ValueError(\n+ f\"All the workers in data should be in initial_error: \"\n+ f\"Can not find {len(not_found_workers)} workers' error matrix in initial_error\"\n+ )\n+ # if the values in initial_error are probability, check the sum of each worker's error matrix\n+ if (initial_error <= 1.0).all().all() and not np.allclose(\n+ initial_error.groupby(\"worker\", sort=False).sum(), 1.0\n+ ):\n+ raise ValueError(\n+ \"The sum of each worker's error matrix in initial_error should be 1.0\"\n+ )\n+ errors = initial_error\n+ elif initial_error_strategy == \"addition\":\n+ errors = errors.add(initial_error, axis=\"index\", fill_value=0.0)\n+ else:\n+ raise ValueError(\n+ f\"Invalid initial_error_strategy: {initial_error_strategy},\"\n+ f\"should be 'assign' or 'addition'\"\n+ )\n+ return errors\n+\n+\n @attr.s\n class OneCoinDawidSkene(DawidSkene):\n r\"\"\"The **one-coin Dawid-Skene** aggregation model works exactly the same as the original Dawid-Skene model\n", "test_patch": "diff --git a/tests/aggregation/test_ds_aggregation.py b/tests/aggregation/test_ds_aggregation.py\nindex e6fdf5b..8fac92d 100644\n--- a/tests/aggregation/test_ds_aggregation.py\n+++ b/tests/aggregation/test_ds_aggregation.py\n@@ -3,7 +3,7 @@ Simplest aggregation algorithms tests on toy YSDA dataset\n Testing all boundary conditions and asserts\n \"\"\"\n \n-from typing import Any, List, cast\n+from typing import Any, List, Literal, Optional, cast\n \n import numpy as np\n import pandas as pd\n@@ -13,6 +13,330 @@ from pandas.testing import assert_frame_equal, assert_series_equal\n from crowdkit.aggregation import DawidSkene, OneCoinDawidSkene\n \n \n+class TestWorkerInitError:\n+\n+ @pytest.mark.parametrize(\n+ \"n_iter, tol, strategy\",\n+ [\n+ (10, 0, \"addition\"),\n+ (10, 0, \"assign\"),\n+ (10, 0, None),\n+ ],\n+ )\n+ def test_without_initial_error_on_toy_ysda(\n+ self,\n+ n_iter: int,\n+ tol: float,\n+ strategy: Optional[Literal[\"assign\", \"addition\"]],\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ ) -> None:\n+ \"\"\"\n+ Basic parameter compatibility test: None parameters\n+ \"\"\"\n+ np.random.seed(42)\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=strategy)\n+ assert_series_equal(\n+ ds.fit(toy_answers_df, initial_error=None).labels_.sort_index(), # type: ignore\n+ toy_ground_truth_df.sort_index(),\n+ )\n+\n+ @pytest.mark.parametrize(\n+ \"n_iter, tol, strategy\",\n+ [\n+ (10, 0, \"addition\"),\n+ (10, 0, \"assign\"),\n+ (100500, 1e-5, \"addition\"),\n+ (100500, 1e-5, \"assign\"),\n+ ],\n+ )\n+ def test_zero_error_addition_on_toy_ysda(\n+ self,\n+ n_iter: int,\n+ tol: float,\n+ strategy: Literal[\"assign\", \"addition\"],\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: pd.DataFrame,\n+ ) -> None:\n+ \"\"\"\n+ Basic parameter compatibility test: zeros initial error matrix\n+ \"\"\"\n+ np.random.seed(42)\n+ initial_error_df = toy_worker_init_error_zero_df\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=strategy)\n+ if strategy == \"addition\":\n+ assert_series_equal(\n+ ds.fit(toy_answers_df, initial_error=initial_error_df).labels_.sort_index(), # type: ignore\n+ toy_ground_truth_df.sort_index(),\n+ )\n+ else:\n+ with pytest.raises(\n+ ValueError,\n+ match=\"The sum of each worker's error matrix in initial_error should be 1.0\",\n+ ):\n+ ds.fit(toy_answers_df, initial_error=initial_error_df)\n+\n+ @pytest.mark.parametrize(\n+ \"n_iter, tol, strategy\",\n+ [\n+ (10, 0, \"addition\"),\n+ (10, 0, \"assign\"),\n+ (100500, 1e-5, \"addition\"),\n+ (100500, 1e-5, \"assign\"),\n+ ],\n+ )\n+ def test_zero_partial_error_on_toy_ysda(\n+ self,\n+ n_iter: int,\n+ tol: float,\n+ strategy: Literal[\"assign\", \"addition\"],\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: pd.DataFrame,\n+ ) -> None:\n+ \"\"\"\n+ Basic parameter compatibility test: when initial_error doesn't contain all workers\n+ \"\"\"\n+ np.random.seed(42)\n+ initial_error_df = toy_worker_init_error_zero_df[:3]\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=strategy)\n+ if strategy == \"addition\":\n+ assert_series_equal(\n+ ds.fit(toy_answers_df, initial_error=initial_error_df).labels_.sort_index(), # type: ignore\n+ toy_ground_truth_df.sort_index(),\n+ )\n+ else:\n+ with pytest.raises(\n+ ValueError,\n+ ):\n+ ds.fit(toy_answers_df, initial_error=initial_error_df)\n+\n+ @pytest.mark.parametrize(\n+ \"n_iter, tol, strategy\", [(10, 0, \"addition\"), (100500, 1e-5, \"addition\")]\n+ )\n+ def test_addition_consistency_on_toy_ysda(\n+ self,\n+ n_iter: int,\n+ tol: float,\n+ strategy: Literal[\"assign\", \"addition\"],\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: \"pd.Series[Any]\",\n+ ) -> None:\n+ \"\"\"\n+ Behavior test: when worker's init error matrix is similar to the error matrix in these tasks,\n+ the aggregation result should be the same as before(without init error)\n+ \"\"\"\n+ np.random.seed(42)\n+ # According to the ground truth data, w2's answer is always right.\n+ # so when we set the initial error matrix of w2 to almost right, we should get same results\n+ init_error_df = toy_worker_init_error_zero_df\n+ init_error_df[(\"w2\", \"yes\"), \"no\"] = 1\n+ init_error_df[(\"w2\", \"yes\"), \"yes\"] = 99\n+ init_error_df[(\"w2\", \"no\"), \"yes\"] = 1\n+ init_error_df[(\"w2\", \"no\"), \"no\"] = 99\n+\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=strategy)\n+ assert_series_equal(\n+ ds.fit(toy_answers_df, initial_error=init_error_df).labels_.sort_index(), # type: ignore\n+ toy_ground_truth_df.sort_index(),\n+ )\n+\n+ @pytest.mark.parametrize(\n+ \"n_iter, tol, strategy\", [(10, 0, \"assign\"), (100500, 1e-5, \"assign\")]\n+ )\n+ def test_assign_consistency_on_toy_ysda(\n+ self,\n+ n_iter: int,\n+ tol: float,\n+ strategy: Literal[\"assign\", \"addition\"],\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: \"pd.Series[Any]\",\n+ ) -> None:\n+ \"\"\"\n+ Behavior test: when worker's init error matrix is similar to the error matrix in these tasks,\n+ the aggregation result should be the same as before(without init error)\n+ \"\"\"\n+ # step1: get the original estimated error matrix\n+ np.random.seed(42)\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=None)\n+ assert_series_equal(\n+ ds.fit(toy_answers_df, initial_error=None).labels_.sort_index(), # type: ignore\n+ toy_ground_truth_df.sort_index(),\n+ )\n+ original_error_df = ds.errors_\n+\n+ # step2: use the original_error_df as initial_error to fit the model\n+ init_error_df = original_error_df\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=strategy)\n+ # step3: check the result, which should be the same as the original one\n+ assert_series_equal(\n+ ds.fit(toy_answers_df, initial_error=init_error_df).labels_.sort_index(), # type: ignore\n+ toy_ground_truth_df.sort_index(),\n+ )\n+\n+ @pytest.mark.parametrize(\n+ \"n_iter, tol, strategy\", [(10, 0, \"addition\"), (100500, 1e-5, \"addition\")]\n+ )\n+ def test_addition_desired_label_on_toy_ysda(\n+ self,\n+ n_iter: int,\n+ tol: float,\n+ strategy: Literal[\"assign\", \"addition\"],\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: \"pd.Series[Any]\",\n+ ) -> None:\n+ \"\"\"\n+ Behavior test: dedicate init error matrices should lead to desired results\n+ \"\"\"\n+ np.random.seed(42)\n+ # worker's annotation on t2: w1: yes, w2: yes, w3: yes, w4: no, w5: no\n+ # ground truth: t2: yes\n+\n+ # When we set workers' init error matrices as fellow, we should get the desired result\n+ # In these case, we want the t2's label to be no rather than yes\n+ init_error_df = toy_worker_init_error_zero_df\n+ item_indexes = [\n+ [(\"w1\", \"yes\"), \"no\"],\n+ [(\"w2\", \"yes\"), \"no\"],\n+ [(\"w3\", \"yes\"), \"no\"],\n+ [(\"w4\", \"no\"), \"no\"],\n+ [(\"w5\", \"no\"), \"no\"],\n+ ]\n+ for loc in item_indexes:\n+ init_error_df.loc[loc[0], loc[1]] = 99 # type: ignore\n+\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=strategy)\n+ ds = ds.fit(toy_answers_df, initial_error=init_error_df) # type: ignore\n+ assert ds.labels_[\"t2\"] == \"no\" # type: ignore\n+\n+ @pytest.mark.parametrize(\n+ \"n_iter, tol, strategy\", [(10, 0, \"assign\"), (100500, 1e-5, \"assign\")]\n+ )\n+ def test_assign_desired_label_on_toy_ysda(\n+ self,\n+ n_iter: int,\n+ tol: float,\n+ strategy: Literal[\"assign\", \"addition\"],\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: \"pd.Series[Any]\",\n+ ) -> None:\n+ \"\"\"\n+ Behavior test: dedicate init error matrices should lead to desired results\n+ \"\"\"\n+ np.random.seed(42)\n+ # worker's annotation on t2: w1: yes, w2: yes, w3: yes, w4: no, w5: no\n+ # ground truth: t2: yes\n+\n+ # When we set workers' init error matrices as fellow, we should get the desired result\n+ # In this case, we want the t2's label to be no rather than yes\n+ # init all probability with 0.5\n+ init_error_df = toy_worker_init_error_zero_df\n+ init_error_df.loc[:, :] = 0.5\n+ # set dedicated probability\n+ item_indexes = [\n+ [(\"w1\", \"yes\"), (\"w1\", \"no\")],\n+ [(\"w2\", \"yes\"), (\"w2\", \"no\")],\n+ [(\"w3\", \"yes\"), (\"w3\", \"no\")],\n+ [(\"w4\", \"no\"), (\"w4\", \"yes\")],\n+ [(\"w5\", \"no\"), (\"w5\", \"yes\")],\n+ ]\n+ for loc in item_indexes:\n+ init_error_df.loc[loc[0], \"no\"] = 0.99\n+ init_error_df.loc[loc[1], \"no\"] = 0.01\n+\n+ ds = DawidSkene(n_iter=n_iter, tol=tol, initial_error_strategy=strategy)\n+ ds = ds.fit(toy_answers_df, initial_error=init_error_df) # type: ignore\n+ assert ds.labels_[\"t2\"] == \"no\" # type: ignore\n+\n+ def test_addition_inner_state_on_toy_ysda(\n+ self,\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: \"pd.Series[Any]\",\n+ ) -> None:\n+ \"\"\"\n+ Inner state test.\n+\n+ Without init error, w2's error matrix(without avg) in iter 0 is as fellows:\n+\n+ no yes\n+ label\n+ yes 0.9 2.1\n+ no 1.4 0.6\n+\n+ After fitting with init error, w2's error matrix(without avg) in iter 0 should be:\n+\n+ no yes\n+ label\n+ yes 2 3\n+ no 2 1\n+\n+ After the avg of error matrix:\n+ no yes\n+ label\n+ yes 0.5 0.75\n+ no 0.5 0.25\n+ \"\"\"\n+ np.random.seed(42)\n+ init_error_df = toy_worker_init_error_zero_df\n+ init_error_df.loc[(\"w2\", \"yes\"), \"no\"] = 1.1 # 1.1 + 0.9 = 2\n+ init_error_df.loc[(\"w2\", \"yes\"), \"yes\"] = 0.9 # 0.9 + 2.1 = 3\n+ init_error_df.loc[(\"w2\", \"no\"), \"yes\"] = 0.4 # 0.4 + 0.6 = 1\n+ init_error_df.loc[(\"w2\", \"no\"), \"no\"] = 0.6 # 0.6 + 1.4 = 2\n+\n+ # fit with init error\n+ with_init_errors = DawidSkene(\n+ n_iter=0,\n+ tol=0.0,\n+ initial_error_strategy=\"addition\",\n+ ).fit(\n+ toy_answers_df, initial_error=init_error_df # type: ignore\n+ )\n+\n+ # check w2 error matrix\n+ item_probs = [\n+ (\"yes\", \"no\", 0.5),\n+ (\"yes\", \"yes\", 0.75),\n+ (\"no\", \"yes\", 0.25),\n+ (\"no\", \"no\", 0.5),\n+ ]\n+ for observed, label, prob in item_probs:\n+ assert np.isclose(with_init_errors.errors_.loc[\"w2\"].loc[observed, label], prob) # type: ignore\n+\n+ def test_assign_inner_state_on_toy_ysda(\n+ self,\n+ toy_answers_df: pd.DataFrame,\n+ toy_ground_truth_df: \"pd.Series[Any]\",\n+ toy_worker_init_error_zero_df: \"pd.Series[Any]\",\n+ ) -> None:\n+ \"\"\"\n+ Inner state test.\n+ \"\"\"\n+ np.random.seed(42)\n+ # generate random init error matrix\n+ init_error_df = toy_worker_init_error_zero_df\n+ init_error_df.loc[:, :] = np.random.randint(1, 100, size=init_error_df.shape)\n+ init_error_df = (\n+ init_error_df / init_error_df.groupby(\"worker\", sort=False).sum()\n+ )\n+ # fit with init error\n+ ds = DawidSkene(\n+ n_iter=0,\n+ tol=0.0,\n+ initial_error_strategy=\"assign\",\n+ ).fit(\n+ toy_answers_df, initial_error=init_error_df # type: ignore\n+ )\n+\n+ # check w2 error matrix\n+ assert_frame_equal(init_error_df, ds.errors_) # type: ignore\n+\n+\n @pytest.mark.parametrize(\"n_iter, tol\", [(10, 0), (100500, 1e-5)])\n def test_aggregate_ds_gold_on_toy_ysda(\n n_iter: int,\ndiff --git a/tests/conftest.py b/tests/conftest.py\nindex 898c3bf..6fc7bbf 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -67,6 +67,23 @@ def toy_gold_df() -> \"pd.Series[Any]\":\n )\n \n \n+@pytest.fixture\n+def toy_worker_init_error_zero_df() -> pd.DataFrame:\n+ \"\"\"\n+ The initial error matrix for toy dataset, which is filled with zeros.\n+ \"\"\"\n+ worker_labels = [[\"w1\", \"w2\", \"w3\", \"w4\", \"w5\"], [\"yes\", \"no\"]]\n+ worker_label_index = pd.MultiIndex.from_product(\n+ worker_labels, names=[\"worker\", \"label\"]\n+ )\n+ init_error_df = pd.DataFrame(\n+ np.zeros((len(worker_label_index), 2)),\n+ index=worker_label_index,\n+ columns=[\"no\", \"yes\"],\n+ )\n+ return init_error_df\n+\n+\n # Simple dataset that imitates real toloka answers\n \n \n", "FAIL_TO_PASS": ["tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_without_initial_error_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_without_initial_error_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_without_initial_error_on_toy_ysda[10-0-None]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_consistency_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_consistency_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_consistency_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_consistency_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_desired_label_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_desired_label_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_desired_label_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_desired_label_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_inner_state_on_toy_ysda", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_inner_state_on_toy_ysda"]}, {"instance_id": "Toloka__crowd-kit-128", "base_commit": "a90bdca30aeb1974adb3dd3230a45975f5df45fb", "gold_patch": "diff --git a/crowdkit/aggregation/classification/dawid_skene.py b/crowdkit/aggregation/classification/dawid_skene.py\nindex 65bca6b..07fe1f5 100644\n--- a/crowdkit/aggregation/classification/dawid_skene.py\n+++ b/crowdkit/aggregation/classification/dawid_skene.py\n@@ -578,3 +578,31 @@ class OneCoinDawidSkene(DawidSkene):\n self.labels_ = get_most_probable_labels(probas)\n \n return self\n+\n+ def fit_predict_proba(self, data: pd.DataFrame) -> pd.DataFrame: # type: ignore[override]\n+ \"\"\"Fits the model to the training data and returns probability distributions of labels for each task.\n+ Args:\n+ data (DataFrame): The training dataset of workers' labeling results\n+ which is represented as the `pandas.DataFrame` data containing `task`, `worker`, and `label` columns.\n+ Returns:\n+ DataFrame: Probability distributions of task labels.\n+ The `pandas.DataFrame` data is indexed by `task` so that `result.loc[task, label]` is the probability that the `task` true label is equal to `label`.\n+ Each probability is in the range from 0 to 1, all task probabilities must sum up to 1.\n+ \"\"\"\n+\n+ self.fit(data)\n+ assert self.probas_ is not None, \"no probas_\"\n+ return self.probas_\n+\n+ def fit_predict(self, data: pd.DataFrame) -> \"pd.Series[Any]\": # type: ignore[override]\n+ \"\"\"Fits the model to the training data and returns the aggregated results.\n+ Args:\n+ data (DataFrame): The training dataset of workers' labeling results\n+ which is represented as the `pandas.DataFrame` data containing `task`, `worker`, and `label` columns.\n+ Returns:\n+ Series: Task labels. The `pandas.Series` data is indexed by `task` so that `labels.loc[task]` is the most likely true label of tasks.\n+ \"\"\"\n+\n+ self.fit(data)\n+ assert self.labels_ is not None, \"no labels_\"\n+ return self.labels_\n", "test_patch": "diff --git a/tests/aggregation/test_ds_aggregation.py b/tests/aggregation/test_ds_aggregation.py\nindex 8fac92d..3e447d0 100644\n--- a/tests/aggregation/test_ds_aggregation.py\n+++ b/tests/aggregation/test_ds_aggregation.py\n@@ -404,6 +404,16 @@ def test_aggregate_hds_on_toy_ysda(\n toy_ground_truth_df.sort_index(),\n )\n \n+ assert_series_equal(\n+ OneCoinDawidSkene(n_iter=n_iter, tol=tol)\n+ .fit_predict(toy_answers_df)\n+ .sort_index(),\n+ toy_ground_truth_df.sort_index(),\n+ )\n+\n+ probas = OneCoinDawidSkene(n_iter=n_iter, tol=tol).fit_predict_proba(toy_answers_df)\n+ assert ((probas >= 0) & (probas <= 1)).all().all()\n+\n \n @pytest.mark.parametrize(\"n_iter, tol\", [(10, 0), (100500, 1e-5)])\n def test_aggregate_ds_on_simple(\n@@ -432,6 +442,18 @@ def test_aggregate_hds_on_simple(\n simple_ground_truth.sort_index(),\n )\n \n+ assert_series_equal(\n+ OneCoinDawidSkene(n_iter=n_iter, tol=tol)\n+ .fit_predict(simple_answers_df)\n+ .sort_index(),\n+ simple_ground_truth.sort_index(),\n+ )\n+\n+ probas = OneCoinDawidSkene(n_iter=n_iter, tol=tol).fit_predict_proba(\n+ simple_answers_df\n+ )\n+ assert ((probas >= 0) & (probas <= 1)).all().all()\n+\n \n def _make_probas(data: List[List[Any]]) -> pd.DataFrame:\n # TODO: column should not be an index!\n", "FAIL_TO_PASS": ["tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_toy_ysda[10-0]", "tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_toy_ysda[100500-1e-05]", "tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_simple[10-0]", "tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_simple[100500-1e-05]"]}], "all_FAIL_TO_PASS": ["tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_without_initial_error_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_without_initial_error_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_without_initial_error_on_toy_ysda[10-0-None]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_error_addition_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_zero_partial_error_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_consistency_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_consistency_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_consistency_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_consistency_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_desired_label_on_toy_ysda[10-0-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_desired_label_on_toy_ysda[100500-1e-05-addition]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_desired_label_on_toy_ysda[10-0-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_desired_label_on_toy_ysda[100500-1e-05-assign]", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_addition_inner_state_on_toy_ysda", "tests/aggregation/test_ds_aggregation.py::TestWorkerInitError::test_assign_inner_state_on_toy_ysda", "tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_toy_ysda[10-0]", "tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_toy_ysda[100500-1e-05]", "tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_simple[10-0]", "tests/aggregation/test_ds_aggregation.py::test_aggregate_hds_on_simple[100500-1e-05]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "horejsek__python-fastjsonschema-112_x2", "level": 2, "source": "swerebench", "repo": "horejsek/python-fastjsonschema", "image": "swerebench/sweb.eval.x86_64.horejsek_1776_python-fastjsonschema-112:latest", "base_commit": "4b0d76cb07d78f047813c6bcda01879ee0a0216c", "num_bugs": 2, "bugs": [{"instance_id": "horejsek__python-fastjsonschema-112", "base_commit": "4b0d76cb07d78f047813c6bcda01879ee0a0216c", "gold_patch": "diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py\nindex 5c40de7..b79b1f9 100644\n--- a/fastjsonschema/draft04.py\n+++ b/fastjsonschema/draft04.py\n@@ -349,8 +349,16 @@ class CodeGeneratorDraft04(CodeGenerator):\n \"\"\"\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n+ self.l(\n+ 'def fn(var): '\n+ 'return frozenset(dict((k, fn(v)) '\n+ 'for k, v in var.items()).items()) '\n+ 'if hasattr(var, \"items\") else tuple(fn(v) '\n+ 'for v in var) '\n+ 'if isinstance(var, (dict, list)) else str(var) '\n+ 'if isinstance(var, bool) else var')\n self.create_variable_with_length()\n- with self.l('if {variable}_len > len(set(str({variable}_x) for {variable}_x in {variable})):'):\n+ with self.l('if {variable}_len > len(set(fn({variable}_x) for {variable}_x in {variable})):'):\n self.exc('{name} must contain unique items', rule='uniqueItems')\n \n def generate_items(self):\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 756429e..de91132 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -13,6 +13,11 @@ from fastjsonschema import JsonSchemaException, compile\n from fastjsonschema.draft07 import CodeGeneratorDraft07\n \n \n+def pytest_configure(config):\n+ config.addinivalue_line(\"markers\", \"none\")\n+ config.addinivalue_line(\"markers\", \"benchmark\")\n+\n+\n @pytest.fixture\n def asserter():\n def f(definition, value, expected, formats={}):\ndiff --git a/tests/test_array.py b/tests/test_array.py\nindex 3d77435..19289ab 100644\n--- a/tests/test_array.py\n+++ b/tests/test_array.py\n@@ -51,6 +51,20 @@ def test_min_items(asserter, value, expected):\n ([1], [1]),\n ([1, 1], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n ([1, 2, 3], [1, 2, 3]),\n+ ([True, False], [True, False]),\n+ ([True, True], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ (['abc', 'bce', 'hhh'], ['abc', 'bce', 'hhh']),\n+ (['abc', 'abc'], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': 'a'}, {'b': 'b'}], [{'a': 'a'}, {'b': 'b'}]),\n+ ([{'a': 'a'}, {'a': 'a'}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': 'a', 'b': 'b'}, {'b': 'b', 'c': 'c'}], [{'a': 'a', 'b': 'b'}, {'b': 'b', 'c': 'c'}]),\n+ ([{'a': 'a', 'b': 'b'}, {'b': 'b', 'a': 'a'}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([1, '1'], [1, '1']),\n+ ([{'a': 'b'}, \"{'a': 'b'}\"], [{'a': 'b'}, \"{'a': 'b'}\"]),\n+ ([[1, 2], [2, 1]], [[1, 2], [2, 1]]),\n+ ([[1, 2], [1, 2]], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': {'b': {'c': [1, 2]}}}, {'a': {'b': {'c': [1, 2]}}}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': {'b': {'c': [2, 1]}}}, {'a': {'b': {'c': [1, 2]}}}], [{'a': {'b': {'c': [2, 1]}}}, {'a': {'b': {'c': [1, 2]}}}]),\n ])\n def test_unique_items(asserter, value, expected):\n asserter({\n", "FAIL_TO_PASS": ["tests/test_array.py::test_unique_items[value11-expected11]", "tests/test_array.py::test_unique_items[value12-expected12]", "tests/test_array.py::test_unique_items[value13-expected13]"]}, {"instance_id": "horejsek__python-fastjsonschema-116", "base_commit": "32476cfd4d97f92cae52d686eb471361503bf4ba", "gold_patch": "diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py\nindex a5b132b..394f263 100644\n--- a/fastjsonschema/draft04.py\n+++ b/fastjsonschema/draft04.py\n@@ -26,7 +26,7 @@ class CodeGeneratorDraft04(CodeGenerator):\n # vs. 9 ms with a regex! Other modules are also ineffective or not available in standard\n # library. Some regexps are not 100% precise but good enough, fast and without dependencies.\n FORMAT_REGEXS = {\n- 'date-time': r'^\\d{4}-[01]\\d-[0-3]\\d(t|T)[0-2]\\d:[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:[+-][0-2]\\d:[0-5]\\d|z|Z)\\Z',\n+ 'date-time': r'^\\d{4}-[01]\\d-[0-3]\\d(t|T)[0-2]\\d:[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:[+-][0-2]\\d:[0-5]\\d|[+-][0-2]\\d[0-5]\\d|z|Z)\\Z',\n 'email': r'^[^@]+@[^@]+\\.[^@]+\\Z',\n 'hostname': r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]{0,61}[A-Za-z0-9])\\Z',\n 'ipv4': r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\Z',\n", "test_patch": "diff --git a/tests/test_format.py b/tests/test_format.py\nindex f742344..c43abc5 100644\n--- a/tests/test_format.py\n+++ b/tests/test_format.py\n@@ -14,6 +14,7 @@ exc = JsonSchemaValueException('data must be date-time', value='{data}', name='d\n ('2018-02-05T14:17:10.00Z\\n', exc),\n ('2018-02-05T14:17:10.00Z', '2018-02-05T14:17:10.00Z'),\n ('2018-02-05T14:17:10Z', '2018-02-05T14:17:10Z'),\n+ ('2020-09-09T01:01:01+0100', '2020-09-09T01:01:01+0100'),\n ])\n def test_datetime(asserter, value, expected):\n asserter({'type': 'string', 'format': 'date-time'}, value, expected)\n", "FAIL_TO_PASS": ["tests/test_format.py::test_datetime[2020-09-09T01:01:01+0100-2020-09-09T01:01:01+0100]"]}], "all_FAIL_TO_PASS": ["tests/test_array.py::test_unique_items[value11-expected11]", "tests/test_array.py::test_unique_items[value12-expected12]", "tests/test_array.py::test_unique_items[value13-expected13]", "tests/test_format.py::test_datetime[2020-09-09T01:01:01+0100-2020-09-09T01:01:01+0100]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "fitbenchmarking__fitbenchmarking-1337_x2", "level": 2, "source": "swerebench", "repo": "fitbenchmarking/fitbenchmarking", "image": "swerebench/sweb.eval.x86_64.fitbenchmarking_1776_fitbenchmarking-1337:latest", "base_commit": "546e9783dafe0ab502cceff43e4464c6ef5de843", "num_bugs": 2, "bugs": [{"instance_id": "fitbenchmarking__fitbenchmarking-1337", "base_commit": "546e9783dafe0ab502cceff43e4464c6ef5de843", "gold_patch": "diff --git a/fitbenchmarking/core/results_output.py b/fitbenchmarking/core/results_output.py\nindex 73d4b72c..b9d0cd73 100644\n--- a/fitbenchmarking/core/results_output.py\n+++ b/fitbenchmarking/core/results_output.py\n@@ -588,8 +588,12 @@ def check_max_solvers(opts, solvers, max_solvers):\n return opts\n \n \n-def display_page(pathname, profile_instances_all_groups,\n- layout, max_solvers):\n+def display_page(\n+ pathname: str,\n+ profile_instances_all_groups: \"dict[str, dict[str, DashPerfProfile]]\",\n+ layout: \"list\",\n+ max_solvers: int\n+):\n \"\"\"\n Update the layout of the dash app.\n \n@@ -621,7 +625,18 @@ def display_page(pathname, profile_instances_all_groups,\n new_layout = layout\n \n try:\n+ first_metric = True\n+ current_styles = {}\n+ avail_styles = []\n for metric in metric_str.split('+'):\n+ if first_metric:\n+ current_styles = group_profiles[metric].current_styles\n+ avail_styles = group_profiles[metric].avail_styles\n+ first_metric = False\n+ else:\n+ group_profiles[metric].current_styles = current_styles\n+ group_profiles[metric].avail_styles = avail_styles\n+\n new_layout = new_layout + [group_profiles[metric].layout()]\n except KeyError:\n return (\"404 Page Error! The path was not recognized. \\n\"\n", "test_patch": "diff --git a/fitbenchmarking/core/tests/test_results_output.py b/fitbenchmarking/core/tests/test_results_output.py\nindex e9223b45..3c61e58b 100644\n--- a/fitbenchmarking/core/tests/test_results_output.py\n+++ b/fitbenchmarking/core/tests/test_results_output.py\n@@ -22,11 +22,8 @@ from fitbenchmarking.core.results_output import (_extract_tags,\n create_directories,\n create_plots,\n create_problem_level_index,\n- display_page,\n- preprocess_data,\n- save_results,\n- update_warning)\n-\n+ display_page, preprocess_data,\n+ save_results, update_warning)\n from fitbenchmarking.results_processing.performance_profiler import \\\n DashPerfProfile\n from fitbenchmarking.utils.checkpoint import Checkpoint\n@@ -675,6 +672,33 @@ class DisplayPageTests(unittest.TestCase):\n 'visual NIST_low_difficulty-Runtime']\n self.assertEqual(output_ids, expected_ids)\n \n+ def test_styles_consistent_when_two_plts(self):\n+ \"\"\"\n+ Test that the styles of lines on the graphs are consistent when\n+ pathname refers to two plots.\n+ \"\"\"\n+ pathname = \"127.0.0.1:5009/NIST_low_difficulty/pp/acc+runtime\"\n+ pps = self.profile_instances_all_groups[\"NIST_low_difficulty\"]\n+ pp = pps[\"acc\"]\n+ pp.current_styles[\"solver1\"] = pp.avail_styles.pop()\n+\n+ _ = display_page(\n+ pathname,\n+ self.profile_instances_all_groups,\n+ self.layout,\n+ self.max_solvers\n+ )\n+\n+ self.assertDictEqual(\n+ pps[\"acc\"].current_styles,\n+ pps[\"runtime\"].current_styles\n+ )\n+\n+ self.assertListEqual(\n+ pps[\"acc\"].avail_styles,\n+ pps[\"runtime\"].avail_styles\n+ )\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_styles_consistent_when_two_plts"]}, {"instance_id": "fitbenchmarking__fitbenchmarking-1338", "base_commit": "798f3bc6058a5a3b2207e5fc19d059bdfc18d4b0", "gold_patch": "diff --git a/fitbenchmarking/core/results_output.py b/fitbenchmarking/core/results_output.py\nindex b9d0cd73..6d660eb8 100644\n--- a/fitbenchmarking/core/results_output.py\n+++ b/fitbenchmarking/core/results_output.py\n@@ -592,7 +592,8 @@ def display_page(\n pathname: str,\n profile_instances_all_groups: \"dict[str, dict[str, DashPerfProfile]]\",\n layout: \"list\",\n- max_solvers: int\n+ max_solvers: int,\n+ run_id: str\n ):\n \"\"\"\n Update the layout of the dash app.\n@@ -605,18 +606,25 @@ def display_page(\n :type layout: list of dcc or html components\n :param max_solvers: Maximum number of solvers that can be plotted\n :type max_solvers: int\n+ :param run_id: The id for the run that is plotted in dash\n+ :type run_id: str\n \n :return: The updated layout\n :rtype: html.Div\n \"\"\"\n \n try:\n- _, group, plot, metric_str = pathname.split('/')\n+ _, plot_id, group, plot, metric_str = pathname.split('/')\n except ValueError:\n- return (\"404 Page Error! Path does not have the expected shape. \"\n+ return (\"404 Page Error! Path does not have the expected format. \"\n \"Please provide it in the following form: \\n\"\n- \"ip-address:port/problem_set/plot/performance_profile.\")\n+ \"ip-address:port/run_id/problem_set/plot/performance_profile.\")\n \n+ if run_id != plot_id:\n+ return (\n+ \"404 Page Error! Dash plots are not available for these results.\"\n+ \"You can use `fitbenchmarking --load-checkpoint` to fix this.\"\n+ )\n if plot != \"pp\":\n return f\"404 Page Error! Plot type '{plot}' not available.\"\n \n@@ -744,7 +752,9 @@ def run_dash_app(options, pp_dfs_all_prob_sets) -> None:\n x,\n profile_instances_all_groups=profile_instances_all_groups,\n layout=layout,\n- max_solvers=max_solvers)\n+ max_solvers=max_solvers,\n+ run_id=options.run_id,\n+ )\n )\n \n app.run(port=options.port)\ndiff --git a/fitbenchmarking/results_processing/tables.py b/fitbenchmarking/results_processing/tables.py\nindex b8321e72..0e159376 100644\n--- a/fitbenchmarking/results_processing/tables.py\n+++ b/fitbenchmarking/results_processing/tables.py\n@@ -140,6 +140,7 @@ def create_results_tables(options, results, best_results, group_dir, fig_dir,\n os.path.relpath(table.pp_locations[p], group_dir)\n for p in table.pps],\n pp_dash_url=f'http://127.0.0.1:{options.port}/'\n+ f\"{options.run_id}/\"\n f'{os.path.basename(group_dir)}/'\n f'pp/{\"+\".join(table.pps)}',\n cbar=cbar,\ndiff --git a/fitbenchmarking/utils/options.py b/fitbenchmarking/utils/options.py\nindex ebc600a1..d2f257d4 100644\n--- a/fitbenchmarking/utils/options.py\n+++ b/fitbenchmarking/utils/options.py\n@@ -6,6 +6,7 @@ This file will handle all interaction with the options configuration file.\n import configparser\n import glob\n import os\n+import uuid\n \n import matplotlib.pyplot as plt\n \n@@ -346,6 +347,8 @@ class Options:\n :type additional_options: dict\n \n \"\"\"\n+ self.run_id = uuid.uuid4().hex\n+\n # additional_options is initialied to an empty dict if\n # no value is given\n if additional_options is None:\n", "test_patch": "diff --git a/fitbenchmarking/core/tests/test_results_output.py b/fitbenchmarking/core/tests/test_results_output.py\nindex 3c61e58b..26c8d09f 100644\n--- a/fitbenchmarking/core/tests/test_results_output.py\n+++ b/fitbenchmarking/core/tests/test_results_output.py\n@@ -13,6 +13,7 @@ from unittest.mock import patch\n \n import pandas as pd\n from dash import dcc, html\n+from parameterized import parameterized\n \n from fitbenchmarking import test_files\n from fitbenchmarking.core.results_output import (_extract_tags,\n@@ -646,11 +647,13 @@ class DisplayPageTests(unittest.TestCase):\n Test that the expected layout components are returned when the\n pathname refers to one plot only.\n \"\"\"\n- pathname = \"127.0.0.1:5009/NIST_low_difficulty/pp/acc\"\n- output_div = display_page(pathname,\n- self.profile_instances_all_groups,\n- self.layout,\n- self.max_solvers)\n+ pathname = \"127.0.0.1:5009/abc/NIST_low_difficulty/pp/acc\"\n+ output_div = display_page(\n+ pathname=pathname,\n+ profile_instances_all_groups=self.profile_instances_all_groups,\n+ layout=self.layout,\n+ max_solvers=self.max_solvers,\n+ run_id=\"abc\")\n output_ids = list(output_div)\n expected_ids = ['Log axis toggle', 'dropdown', 'warning',\n 'visual NIST_low_difficulty-Accuracy']\n@@ -661,23 +664,46 @@ class DisplayPageTests(unittest.TestCase):\n Test that the expected layout components are returned when the\n pathname refers to two plots.\n \"\"\"\n- pathname = \"127.0.0.1:5009/NIST_low_difficulty/pp/acc+runtime\"\n- output_div = display_page(pathname,\n- self.profile_instances_all_groups,\n- self.layout,\n- self.max_solvers)\n+ pathname = \"127.0.0.1:5009/123/NIST_low_difficulty/pp/acc+runtime\"\n+ output_div = display_page(\n+ pathname=pathname,\n+ profile_instances_all_groups=self.profile_instances_all_groups,\n+ layout=self.layout,\n+ max_solvers=self.max_solvers,\n+ run_id=\"123\",\n+ )\n output_ids = list(output_div)\n expected_ids = ['Log axis toggle', 'dropdown', 'warning',\n 'visual NIST_low_difficulty-Accuracy',\n 'visual NIST_low_difficulty-Runtime']\n self.assertEqual(output_ids, expected_ids)\n \n+ @parameterized.expand([\n+ (\"127.0.0.1:5009/old_id/NIST_low_difficulty/pp/acc+runtime\", \"new_id\"),\n+ (\"127.0.0.1:5009/abc/NIST_low_difficulty/??/acc+runtime\", \"abc\"),\n+ (\"127.0.0.1:5009/abc/pp/acc+runtime\", \"abc\"),\n+ ])\n+ def test_dash_url_404(self, pathname, run_id):\n+ \"\"\"\n+ Tests that errors are reported when the dash url is not correct.\n+ \"\"\"\n+ output_div = display_page(\n+ pathname=pathname,\n+ profile_instances_all_groups=self.profile_instances_all_groups,\n+ layout=self.layout,\n+ max_solvers=self.max_solvers,\n+ run_id=run_id,\n+ )\n+ assert (\n+ isinstance(output_div, str) and output_div.startswith(\"404\")\n+ )\n+\n def test_styles_consistent_when_two_plts(self):\n \"\"\"\n Test that the styles of lines on the graphs are consistent when\n pathname refers to two plots.\n \"\"\"\n- pathname = \"127.0.0.1:5009/NIST_low_difficulty/pp/acc+runtime\"\n+ pathname = \"127.0.0.1:5009/abc/NIST_low_difficulty/pp/acc+runtime\"\n pps = self.profile_instances_all_groups[\"NIST_low_difficulty\"]\n pp = pps[\"acc\"]\n pp.current_styles[\"solver1\"] = pp.avail_styles.pop()\n@@ -686,7 +712,8 @@ class DisplayPageTests(unittest.TestCase):\n pathname,\n self.profile_instances_all_groups,\n self.layout,\n- self.max_solvers\n+ self.max_solvers,\n+ run_id=\"abc\"\n )\n \n self.assertDictEqual(\ndiff --git a/fitbenchmarking/utils/tests/test_options_generic.py b/fitbenchmarking/utils/tests/test_options_generic.py\nindex eb4e4dbc..6c877b39 100644\n--- a/fitbenchmarking/utils/tests/test_options_generic.py\n+++ b/fitbenchmarking/utils/tests/test_options_generic.py\n@@ -80,6 +80,10 @@ class OptionsWriteTests(unittest.TestCase):\n options.stored_file_name = \"\"\n new_options.stored_file_name = \"\"\n \n+ # Overwrite run_id\n+ options.run_id = \"\"\n+ new_options.run_id = \"\"\n+\n self.assertDictEqual(options.__dict__, new_options.__dict__)\n \n def test_write_to_stream(self):\n@@ -101,6 +105,10 @@ class OptionsWriteTests(unittest.TestCase):\n options.stored_file_name = \"\"\n new_options.stored_file_name = \"\"\n \n+ # Overwrite run_id\n+ options.run_id = \"\"\n+ new_options.run_id = \"\"\n+\n os.remove(new_file_name)\n self.assertDictEqual(options.__dict__, new_options.__dict__)\n \n", "FAIL_TO_PASS": ["fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_dash_url_404_0_127_0_0_1_5009_old_id_NIST_low_difficulty_pp_acc_runtime", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_dash_url_404_1_127_0_0_1_5009_abc_NIST_low_difficulty_acc_runtime", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_dash_url_404_2_127_0_0_1_5009_abc_pp_acc_runtime", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_layout_returned_when_one_plot", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_layout_returned_when_two_plots", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_styles_consistent_when_two_plts"]}], "all_FAIL_TO_PASS": ["fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_styles_consistent_when_two_plts", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_dash_url_404_0_127_0_0_1_5009_old_id_NIST_low_difficulty_pp_acc_runtime", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_dash_url_404_1_127_0_0_1_5009_abc_NIST_low_difficulty_acc_runtime", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_dash_url_404_2_127_0_0_1_5009_abc_pp_acc_runtime", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_layout_returned_when_one_plot", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_layout_returned_when_two_plots", "fitbenchmarking/core/tests/test_results_output.py::DisplayPageTests::test_styles_consistent_when_two_plts"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "leonardt__hwtypes-39_x2", "level": 2, "source": "swerebench", "repo": "leonardt/hwtypes", "image": "swerebench/sweb.eval.x86_64.leonardt_1776_hwtypes-39:latest", "base_commit": "cc7e418eb3561970bd6ca87779f858528670b67c", "num_bugs": 2, "bugs": [{"instance_id": "leonardt__hwtypes-39", "base_commit": "cc7e418eb3561970bd6ca87779f858528670b67c", "gold_patch": "diff --git a/README.md b/README.md\nindex 1324025..2d1e3ed 100644\n--- a/README.md\n+++ b/README.md\n@@ -12,9 +12,3 @@ pip install hwtypes\n brew install gmp mpfr libmpc\n pip install hwtypes\n ```\n-\n-## CentOS\n-```\n-yum install libmpc-devel mpfr-devel gmp-devel\n-pip install hwtypes\n-```\ndiff --git a/hwtypes/fp_vector.py b/hwtypes/fp_vector.py\nindex 68d833c..9fd7320 100644\n--- a/hwtypes/fp_vector.py\n+++ b/hwtypes/fp_vector.py\n@@ -1,11 +1,11 @@\n-import typing as tp\n import functools\n-import random\n import gmpy2\n+import random\n+import typing as tp\n import warnings\n \n-from .fp_vector_abc import AbstractFPVector, RoundingMode\n from .bit_vector import Bit, BitVector, SIntVector\n+from .fp_vector_abc import AbstractFPVector, RoundingMode\n \n __ALL__ = ['FPVector']\n \n@@ -42,7 +42,36 @@ def set_context(fn: tp.Callable) -> tp.Callable:\n class FPVector(AbstractFPVector):\n @set_context\n def __init__(self, value):\n- value = gmpy2.mpfr(value)\n+ # Because for some reason gmpy2.mpfr is a function and not a type\n+ if isinstance(value, type(gmpy2.mpfr(0))):\n+ #need to specify precision because mpfr will use the input\n+ #precision not the context precision when constructing from mpfr\n+ value = gmpy2.mpfr(value, self._ctx_.precision)\n+ elif isinstance(value, FPVector):\n+ value = gmpy2.mpfr(value._value, self._ctx_.precision)\n+ elif isinstance(value, (int, float, type(gmpy2.mpz(0)), type(gmpy2.mpq(0)))):\n+ value = gmpy2.mpfr(value)\n+ elif isinstance(value, str):\n+ try:\n+ #Handles '0.5'\n+ value = gmpy2.mpfr(value)\n+ except ValueError:\n+ try:\n+ #Handles '1/2'\n+ value = gmpy2.mpfr(gmpy2.mpq(value))\n+ except ValueError:\n+ raise ValueError('Invalid string')\n+ elif hasattr(value, '__float__'):\n+ value = gmpy2.mpfr(float(value))\n+ elif hasattr(value, '__int__'):\n+ value = gmpy2.mpfr(int(value))\n+ else:\n+ try:\n+ #if gmpy2 doesn't complain I wont\n+ value = gmpy2.mpfr(value)\n+ except TypeError:\n+ raise TypeError(f\"Can't construct FPVector from {type(value)}\")\n+\n if gmpy2.is_nan(value) and not type(self).ieee_compliance:\n if gmpy2.is_signed(value):\n self._value = gmpy2.mpfr('-inf')\n", "test_patch": "diff --git a/tests/test_fp.py b/tests/test_fp.py\nindex 7cff76d..20628da 100644\n--- a/tests/test_fp.py\n+++ b/tests/test_fp.py\n@@ -127,6 +127,30 @@ def _c_type_vector(T):\n \n NTESTS = 100\n \n+@pytest.mark.parametrize(\"mode\", [\n+ RoundingMode.RNE,\n+ RoundingMode.RNA,\n+ RoundingMode.RTP,\n+ RoundingMode.RTN,\n+ RoundingMode.RTZ,\n+ ])\n+@pytest.mark.parametrize(\"ieee\", [False, True])\n+def test_init(mode, ieee):\n+ BigFloat = FPVector[27,100, mode, ieee]\n+ class F:\n+ def __float__(self):\n+ return 0.5\n+\n+ class I:\n+ def __int__(self):\n+ return 1\n+\n+ assert BigFloat(0.5) == BigFloat(F())\n+ assert BigFloat(1) == BigFloat(I())\n+ assert BigFloat(0.5) == BigFloat('0.5')\n+ assert BigFloat('1/3') == BigFloat(1)/BigFloat(3)\n+ assert BigFloat('1/3') != BigFloat(1/3) # as 1/3 is performed in python floats\n+\n @pytest.mark.parametrize(\"FT\", [\n FPVector[8, 7, RoundingMode.RNE, True],\n FPVector[8, 7, RoundingMode.RNE, False],\n", "FAIL_TO_PASS": ["tests/test_fp.py::test_init[False-RoundingMode.RNE]", "tests/test_fp.py::test_init[False-RoundingMode.RNA]", "tests/test_fp.py::test_init[False-RoundingMode.RTP]", "tests/test_fp.py::test_init[False-RoundingMode.RTN]", "tests/test_fp.py::test_init[False-RoundingMode.RTZ]", "tests/test_fp.py::test_init[True-RoundingMode.RNE]", "tests/test_fp.py::test_init[True-RoundingMode.RNA]", "tests/test_fp.py::test_init[True-RoundingMode.RTP]", "tests/test_fp.py::test_init[True-RoundingMode.RTN]", "tests/test_fp.py::test_init[True-RoundingMode.RTZ]"]}, {"instance_id": "leonardt__hwtypes-50", "base_commit": "11bf81a76f31f703248e3d5b84a9c631bd618422", "gold_patch": "diff --git a/hwtypes/bit_vector.py b/hwtypes/bit_vector.py\nindex 885b2cb..e7f0010 100644\n--- a/hwtypes/bit_vector.py\n+++ b/hwtypes/bit_vector.py\n@@ -175,6 +175,10 @@ class BitVector(AbstractBitVector):\n def __repr__(self):\n return \"BitVector[{size}]({value})\".format(value=self._value, size=self.size)\n \n+ @property\n+ def value(self):\n+ return self._value\n+\n def __setitem__(self, index, value):\n if isinstance(index, slice):\n raise NotImplementedError()\n@@ -211,10 +215,11 @@ class BitVector(AbstractBitVector):\n def __len__(self):\n return self.size\n \n- # Note: In concat(x, y), the MSB of the result is the MSB of x.\n- @classmethod\n- def concat(cls, x, y):\n- return cls.unsized_t[x.size+y.size](y.bits() + x.bits())\n+ def concat(self, other):\n+ T = type(self).unsized_t\n+ if not isinstance(other, T):\n+ raise TypeError(f'value must of type {T}')\n+ return T[self.size+other.size](self.value | (other.value << self.size))\n \n def bvnot(self):\n return type(self)(~self.as_uint())\n@@ -246,12 +251,12 @@ class BitVector(AbstractBitVector):\n @bv_cast\n def bvrol(self, other):\n other = other.as_uint() % len(self)\n- return self.concat( self[other:], self[0:other] )\n+ return self[:other].concat(self[other:])\n \n @bv_cast\n def bvror(self, other):\n other = (len(self) - other.as_uint()) % len(self)\n- return self.concat( self[other:], self[0:other] )\n+ return self[:other].concat(self[other:])\n \n @bv_cast\n def bvcomp(self, other):\n@@ -400,7 +405,7 @@ class BitVector(AbstractBitVector):\n raise ValueError()\n \n T = type(self).unsized_t\n- return T.concat(T[1](self[-1]).repeat(ext), self)\n+ return self.concat(T[1](self[-1]).repeat(ext))\n \n def ext(self, ext):\n return self.zext(other)\n@@ -411,7 +416,7 @@ class BitVector(AbstractBitVector):\n raise ValueError()\n \n T = type(self).unsized_t\n- return T.concat(T[ext](0), self)\n+ return self.concat(T[ext](0))\n \n @staticmethod\n def random(width):\ndiff --git a/hwtypes/bit_vector_abc.py b/hwtypes/bit_vector_abc.py\nindex 616ee76..1521849 100644\n--- a/hwtypes/bit_vector_abc.py\n+++ b/hwtypes/bit_vector_abc.py\n@@ -176,10 +176,8 @@ class AbstractBitVector(metaclass=AbstractBitVectorMeta):\n def __len__(self) -> int:\n pass\n \n- #could still be staticmethod but I think thats annoying\n- @classmethod\n @abstractmethod\n- def concat(cls, x, y) -> 'AbstractBitVector':\n+ def concat(self, other) -> 'AbstractBitVector':\n pass\n \n @abstractmethod\ndiff --git a/hwtypes/fp_vector.py b/hwtypes/fp_vector.py\nindex 9fd7320..3e1f0f0 100644\n--- a/hwtypes/fp_vector.py\n+++ b/hwtypes/fp_vector.py\n@@ -269,15 +269,15 @@ class FPVector(AbstractFPVector):\n sign_bit = BitVector[1](gmpy2.is_signed(self._value))\n \n if self.fp_is_zero():\n- return BitVector.concat(sign_bit, BitVector[cls.size-1](0))\n+ return BitVector[cls.size-1](0).concat(sign_bit)\n elif self.fp_is_infinite():\n exp_bits = BitVector[cls.exponent_size](-1)\n mantissa_bits = BitVector[cls.mantissa_size](0)\n- return BitVector.concat(BitVector.concat(sign_bit, exp_bits), mantissa_bits)\n+ return mantissa_bits.concat(exp_bits).concat(sign_bit)\n elif self.fp_is_NaN():\n exp_bits = BitVector[cls.exponent_size](-1)\n mantissa_bits = BitVector[cls.mantissa_size](1)\n- return BitVector.concat(BitVector.concat(sign_bit, exp_bits), mantissa_bits)\n+ return mantissa_bits.concat(exp_bits).concat(sign_bit)\n \n \n bias = (1 << (cls.exponent_size - 1)) - 1\n@@ -307,7 +307,7 @@ class FPVector(AbstractFPVector):\n mantissa = BitVector[cls.mantissa_size+1](mantissa_int)\n exp_bits = BitVector[cls.exponent_size](exp)\n mantissa_bits = mantissa[:cls.mantissa_size]\n- return BitVector.concat(BitVector.concat(sign_bit, exp_bits), mantissa_bits)\n+ return mantissa_bits.concat(exp_bits).concat(sign_bit)\n \n @classmethod\n @set_context\ndiff --git a/hwtypes/smt_bit_vector.py b/hwtypes/smt_bit_vector.py\nindex 892dcdc..0b46323 100644\n--- a/hwtypes/smt_bit_vector.py\n+++ b/hwtypes/smt_bit_vector.py\n@@ -231,7 +231,7 @@ class SMTBitVector(AbstractBitVector):\n raise ValueError('Iterable is not the correct size')\n cls = type(self)\n B1 = cls.unsized_t[1]\n- self._value = ft.reduce(cls.concat, map(B1, reversed(value))).value\n+ self._value = ft.reduce(lambda acc, elem : acc.concat(elem), map(B1, value)).value\n elif isinstance(value, int):\n self._value = smt.BV(value % (1 << self.size), self.size)\n \n@@ -320,9 +320,11 @@ class SMTBitVector(AbstractBitVector):\n def __len__(self):\n return self.size\n \n- @classmethod\n- def concat(cls, x, y):\n- return cls.unsized_t[x.size + y.size](smt.BVConcat(x.value, y.value))\n+ def concat(self, other):\n+ T = type(self).unsized_t\n+ if not isinstance(other, T):\n+ raise TypeError(f'value must of type {T}')\n+ return T[self.size + other.size](smt.BVConcat(other.value, self.value))\n \n def bvnot(self):\n return type(self)(smt.BVNot(self.value))\ndiff --git a/hwtypes/z3_bit_vector.py b/hwtypes/z3_bit_vector.py\nindex c555656..9947eb1 100644\n--- a/hwtypes/z3_bit_vector.py\n+++ b/hwtypes/z3_bit_vector.py\n@@ -229,7 +229,7 @@ class z3BitVector(AbstractBitVector):\n raise ValueError('Iterable is not the correct size')\n cls = type(self)\n B1 = cls.unsized_t[1]\n- self._value = ft.reduce(cls.concat, map(B1, reversed(value))).value\n+ self._value = ft.reduce(lambda acc, elem : acc.concat(elem), map(B1, value)).value\n elif isinstance(value, int):\n self._value = z3.BitVecVal(value, self.size)\n \n@@ -318,9 +318,11 @@ class z3BitVector(AbstractBitVector):\n def __len__(self):\n return self.size\n \n- @classmethod\n- def concat(cls, x, y):\n- return cls.unsized_t[x.size + y.size](z3.Concat(x.value, y.value))\n+ def concat(self, other):\n+ T = type(self).unsized_t\n+ if not isinstance(other, T):\n+ raise TypeError(f'value must of type {T}')\n+ return T[self.size + other.size](z3.Concat(other.value, self.value))\n \n def bvnot(self):\n return type(self)(~self.value)\n", "test_patch": "diff --git a/tests/test_concat.py b/tests/test_concat.py\nindex 7f9f6af..1a5dfa6 100644\n--- a/tests/test_concat.py\n+++ b/tests/test_concat.py\n@@ -1,8 +1,25 @@\n from hwtypes import BitVector\n+import random\n \n-def test_concat():\n+NTESTS = 10\n+MAX_BITS = 128\n+\n+def test_concat_const():\n a = BitVector[4](4)\n b = BitVector[4](1)\n- c = BitVector.concat(a, b)\n- expected = BitVector[8]([1,0,0,0,0,0,1,0])\n+ c = a.concat(b)\n+ print(a.binary_string())\n+ print(c.binary_string())\n+ expected = BitVector[8]([0,0,1,0,1,0,0,0])\n assert expected == c\n+\n+def test_concat_random():\n+ for _ in range(NTESTS):\n+ n1 = random.randint(1, MAX_BITS)\n+ n2 = random.randint(1, MAX_BITS)\n+ a = BitVector.random(n1)\n+ b = BitVector.random(n2)\n+ c = a.concat(b)\n+ assert c.size == a.size + b.size\n+ assert c == BitVector[n1 + n2](a.bits() + b.bits())\n+ assert c.binary_string() == b.binary_string() + a.binary_string()\ndiff --git a/tests/test_fp.py b/tests/test_fp.py\nindex 20628da..d44a34d 100644\n--- a/tests/test_fp.py\n+++ b/tests/test_fp.py\n@@ -125,7 +125,7 @@ def _c_type_vector(T):\n \n return vector\n \n-NTESTS = 100\n+NTESTS = 128\n \n @pytest.mark.parametrize(\"mode\", [\n RoundingMode.RNE,\n@@ -247,6 +247,37 @@ def test_reinterpret_bv(FT):\n assert bv1[:ms] != 0\n assert bv2[:ms] != 0\n \n+def test_reinterpret_bv_corner():\n+ for _ in range(NTESTS):\n+ FT = FPVector[random.randint(3, 16),\n+ random.randint(2, 64),\n+ random.choice(list(RoundingMode)),\n+ True]\n+ bv_pinf = BitVector[FT.mantissa_size](0).concat(BitVector[FT.exponent_size](-1)).concat(BitVector[1](0))\n+ bv_ninf = BitVector[FT.mantissa_size](0).concat(BitVector[FT.exponent_size](-1)).concat(BitVector[1](1))\n+ pinf = FT.reinterpret_from_bv(bv_pinf)\n+ ninf = FT.reinterpret_from_bv(bv_ninf)\n+ assert pinf.reinterpret_as_bv() == bv_pinf\n+ assert ninf.reinterpret_as_bv() == bv_ninf\n+ assert pinf.fp_is_positive()\n+ assert pinf.fp_is_infinite()\n+ assert ninf.fp_is_negative()\n+ assert ninf.fp_is_infinite()\n+\n+ bv_pz = BitVector[FT.size](0)\n+ bv_nz = BitVector[FT.size-1](0).concat(BitVector[1](1))\n+ pz = FT.reinterpret_from_bv(bv_pz)\n+ nz = FT.reinterpret_from_bv(bv_nz)\n+ assert pz.reinterpret_as_bv() == bv_pz\n+ assert nz.reinterpret_as_bv() == bv_nz\n+ assert pz.fp_is_zero()\n+ assert nz.fp_is_zero()\n+\n+ bv_nan = BitVector[FT.mantissa_size](1).concat(BitVector[FT.exponent_size](-1)).concat(BitVector[1](0))\n+ nan = FT.reinterpret_from_bv(bv_nan)\n+ assert nan.reinterpret_as_bv() == bv_nan\n+ assert nan.fp_is_NaN()\n+\n @pytest.mark.parametrize(\"CT, FT\", [\n (_c_type_vector(ctypes.c_float), FPVector[8, 23, RoundingMode.RNE, True]),\n (_c_type_vector(ctypes.c_double), FPVector[11, 52, RoundingMode.RNE, True]),])\n", "FAIL_TO_PASS": ["tests/test_concat.py::test_concat_const", "tests/test_concat.py::test_concat_random", "tests/test_fp.py::test_reinterpret_bv_corner"]}], "all_FAIL_TO_PASS": ["tests/test_fp.py::test_init[False-RoundingMode.RNE]", "tests/test_fp.py::test_init[False-RoundingMode.RNA]", "tests/test_fp.py::test_init[False-RoundingMode.RTP]", "tests/test_fp.py::test_init[False-RoundingMode.RTN]", "tests/test_fp.py::test_init[False-RoundingMode.RTZ]", "tests/test_fp.py::test_init[True-RoundingMode.RNE]", "tests/test_fp.py::test_init[True-RoundingMode.RNA]", "tests/test_fp.py::test_init[True-RoundingMode.RTP]", "tests/test_fp.py::test_init[True-RoundingMode.RTN]", "tests/test_fp.py::test_init[True-RoundingMode.RTZ]", "tests/test_concat.py::test_concat_const", "tests/test_concat.py::test_concat_random", "tests/test_fp.py::test_reinterpret_bv_corner"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ilevkivskyi__typing_inspect-71_x2", "level": 2, "source": "swerebench", "repo": "ilevkivskyi/typing_inspect", "image": "swerebench/sweb.eval.x86_64.ilevkivskyi_1776_typing_inspect-71:latest", "base_commit": "6dd6b38bc12bcbaf814fb0c69a801365b81e3611", "num_bugs": 2, "bugs": [{"instance_id": "ilevkivskyi__typing_inspect-71", "base_commit": "6dd6b38bc12bcbaf814fb0c69a801365b81e3611", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex 1fb80e9..6cf3061 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -5,6 +5,7 @@ matrix:\n fast_finish: true\n include:\n - python: 3.9\n+ - python: 3.9.1\n - python: 3.8\n - python: 3.7\n - python: 3.6\ndiff --git a/typing_inspect.py b/typing_inspect.py\nindex d3a0604..c11b856 100644\n--- a/typing_inspect.py\n+++ b/typing_inspect.py\n@@ -8,10 +8,14 @@ Example usage::\n # NOTE: This module must support Python 2.7 in addition to Python 3.x\n \n import sys\n+import types\n+\n from mypy_extensions import _TypedDictMeta as _TypedDictMeta_Mypy\n-if sys.version_info[:3] >= (3, 4, 0) and sys.version_info[:3] < (3, 9, 0):\n+\n+# See comments in typing_extensions source on why the switch is at 3.9.2\n+if (3, 4, 0) <= sys.version_info[:3] < (3, 9, 2):\n from typing_extensions import _TypedDictMeta as _TypedDictMeta_TE\n-elif sys.version_info[:3] >= (3, 9, 0):\n+elif sys.version_info[:3] >= (3, 9, 2):\n # typing_extensions.TypedDict is a re-export from typing.\n from typing import _TypedDictMeta as _TypedDictMeta_TE\n else:\n@@ -35,7 +39,7 @@ if NEW_TYPING:\n from typing_extensions import Final, Literal\n if sys.version_info[:3] >= (3, 9, 0):\n from typing import _SpecialGenericAlias\n- typingGenericAlias = (_GenericAlias, _SpecialGenericAlias)\n+ typingGenericAlias = (_GenericAlias, _SpecialGenericAlias, types.GenericAlias)\n else:\n typingGenericAlias = (_GenericAlias,)\n else:\n@@ -463,7 +467,7 @@ def get_args(tp, evaluate=None):\n if NEW_TYPING:\n if evaluate is not None and not evaluate:\n raise ValueError('evaluate can only be True in Python >= 3.7')\n- if isinstance(tp, _GenericAlias):\n+ if isinstance(tp, typingGenericAlias):\n res = tp.__args__\n if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:\n res = (list(res[:-1]), res[-1])\n@@ -485,7 +489,7 @@ def get_args(tp, evaluate=None):\n # backport of union's subs_tree\n tree = _union_subs_tree(tp)\n elif is_generic_type(tp):\n- # backport of genericmeta's subs_tree\n+ # backport of GenericMeta's subs_tree\n tree = _generic_subs_tree(tp)\n elif is_tuple_type(tp):\n # ad-hoc (inspired by union)\n", "test_patch": "diff --git a/test_typing_inspect.py b/test_typing_inspect.py\nindex c5fc753..58a03ee 100644\n--- a/test_typing_inspect.py\n+++ b/test_typing_inspect.py\n@@ -115,6 +115,7 @@ class Other(dict):\n \"\"\"\n \n PY36 = sys.version_info[:3] >= (3, 6, 0)\n+PY39 = sys.version_info[:3] >= (3, 9, 0)\n if PY36:\n exec(PY36_TESTS)\n \n@@ -131,6 +132,8 @@ class IsUtilityTestCase(TestCase):\n T = TypeVar('T')\n samples = [Generic, Generic[T], Iterable[int], Mapping,\n MutableMapping[T, List[int]], Sequence[Union[str, bytes]]]\n+ if PY39:\n+ samples.extend([list[int], dict[str, list[int]]])\n nonsamples = [int, Union[int, str], Union[int, T], Callable[..., T],\n Optional, bytes, list] + CLASSVAR_GENERIC\n self.sample_test(is_generic_type, samples, nonsamples)\n@@ -149,6 +152,8 @@ class IsUtilityTestCase(TestCase):\n \n def test_tuple(self):\n samples = [Tuple, Tuple[str, int], Tuple[Iterable, ...]]\n+ if PY39:\n+ samples.append(tuple[int, str])\n nonsamples = [int, tuple, 42, List[int], NamedTuple('N', [('x', int)])]\n self.sample_test(is_tuple_type, samples, nonsamples)\n if SUBCLASSABLE_TUPLES:\n@@ -301,6 +306,8 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_origin(ClassVar[int]), None)\n self.assertEqual(get_origin(Generic), Generic)\n self.assertEqual(get_origin(Generic[T]), Generic)\n+ if PY39:\n+ self.assertEqual(get_origin(list[int]), list)\n if GENERIC_TUPLE_PARAMETRIZABLE:\n tp = List[Tuple[T, T]][int]\n self.assertEqual(get_origin(tp), list if NEW_TYPING else List)\n@@ -323,6 +330,8 @@ class GetUtilityTestCase(TestCase):\n if EXISTING_UNIONS_SUBSCRIPTABLE:\n self.assertEqual(get_parameters(Union[S_co, Tuple[T, T]][int, U]), (U,))\n self.assertEqual(get_parameters(Mapping[T, Tuple[S_co, T]]), (T, S_co))\n+ if PY39:\n+ self.assertEqual(get_parameters(dict[int, T]), (T,))\n \n @skipIf(NEW_TYPING, \"Not supported in Python 3.7\")\n def test_last_args(self):\n@@ -389,6 +398,11 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_args(Literal[\"value\"], evaluate=True), (\"value\",))\n self.assertEqual(get_args(Literal[1, 2, 3], evaluate=True), (1, 2, 3))\n \n+ if PY39:\n+ self.assertEqual(get_args(list[int]), (int,))\n+ self.assertEqual(get_args(tuple[int, str]), (int, str))\n+ self.assertEqual(get_args(list[list[int]]), (list[int],))\n+\n def test_bound(self):\n T = TypeVar('T')\n TB = TypeVar('TB', bound=int)\n", "FAIL_TO_PASS": ["test_typing_inspect.py::IsUtilityTestCase::test_generic", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_parameters"]}, {"instance_id": "ilevkivskyi__typing_inspect-74", "base_commit": "d1d46f4c2429dd0a60f902fa7b728d67bb2d1582", "gold_patch": "diff --git a/typing_inspect.py b/typing_inspect.py\nindex c11b856..4c765e3 100644\n--- a/typing_inspect.py\n+++ b/typing_inspect.py\n@@ -467,7 +467,8 @@ def get_args(tp, evaluate=None):\n if NEW_TYPING:\n if evaluate is not None and not evaluate:\n raise ValueError('evaluate can only be True in Python >= 3.7')\n- if isinstance(tp, typingGenericAlias):\n+ # Note special aliases on Python 3.9 don't have __args__.\n+ if isinstance(tp, typingGenericAlias) and hasattr(tp, '__args__'):\n res = tp.__args__\n if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:\n res = (list(res[:-1]), res[-1])\n", "test_patch": "diff --git a/test_typing_inspect.py b/test_typing_inspect.py\nindex 58a03ee..7e9d432 100644\n--- a/test_typing_inspect.py\n+++ b/test_typing_inspect.py\n@@ -402,6 +402,8 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_args(list[int]), (int,))\n self.assertEqual(get_args(tuple[int, str]), (int, str))\n self.assertEqual(get_args(list[list[int]]), (list[int],))\n+ # This would return (~T,) before Python 3.9.\n+ self.assertEqual(get_args(List), ())\n \n def test_bound(self):\n T = TypeVar('T')\n", "FAIL_TO_PASS": ["test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated"]}], "all_FAIL_TO_PASS": ["test_typing_inspect.py::IsUtilityTestCase::test_generic", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_parameters", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "astropy__astroquery-3116_x2", "level": 2, "source": "swerebench", "repo": "astropy/astroquery", "image": "swerebench/sweb.eval.x86_64.astropy_1776_astroquery-3116:latest", "base_commit": "88b640990ccb590905c3bc45ebda983c2963b148", "num_bugs": 2, "bugs": [{"instance_id": "astropy__astroquery-3116", "base_commit": "88b640990ccb590905c3bc45ebda983c2963b148", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex b6e9cc50..aba8224a 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -217,6 +217,12 @@ mpc\n - Rename ``MPC.get_mpc_object_endpoint`` to ``MPC._get_mpc_object_endpoint`` to\n indicate that it is a private method. [#3089]\n \n+xmatch\n+^^^^^^\n+\n+- Fix xmatch query for two local tables. The second table was written over the first one,\n+ resulting in a confusing \"missing cat1\" error. [#3116]\n+\n \n 0.4.7 (2024-03-08)\n ==================\ndiff --git a/astroquery/xmatch/core.py b/astroquery/xmatch/core.py\nindex 6d9768a3..57cc9549 100644\n--- a/astroquery/xmatch/core.py\n+++ b/astroquery/xmatch/core.py\n@@ -42,7 +42,7 @@ class XMatchClass(BaseQuery):\n If the table is uploaded or accessed through a URL, it must be\n in VOTable or CSV format with the positions in J2000\n equatorial frame and as decimal degrees numbers.\n- cat2 : str or file\n+ cat2 : str, file or `~astropy.table.Table`\n Identifier of the second table. Follows the same rules as *cat1*.\n max_distance : `~astropy.units.Quantity`\n Maximum distance to look for counterparts.\n@@ -127,17 +127,22 @@ class XMatchClass(BaseQuery):\n catstr = 'cat{0}'.format(cat_index)\n if isinstance(cat, str):\n payload[catstr] = cat\n- elif isinstance(cat, Table):\n- # write the Table's content into a new, temporary CSV-file\n- # so that it can be pointed to via the `files` option\n- # file will be closed when garbage-collected\n- fp = StringIO()\n- cat.write(fp, format='ascii.csv')\n- fp.seek(0)\n- kwargs['files'] = {catstr: ('cat1.csv', fp.read())}\n else:\n- # assume it's a file-like object, support duck-typing\n- kwargs['files'] = {catstr: ('cat1.csv', cat.read())}\n+ # create the dictionary of uploaded files\n+ if \"files\" not in kwargs:\n+ kwargs[\"files\"] = {}\n+ if isinstance(cat, Table):\n+ # write the Table's content into a new, temporary CSV-file\n+ # so that it can be pointed to via the `files` option\n+ # file will be closed when garbage-collected\n+\n+ fp = StringIO()\n+ cat.write(fp, format='ascii.csv')\n+ fp.seek(0)\n+ kwargs['files'].update({catstr: (f'cat{cat_index}.csv', fp.read())})\n+ else:\n+ # assume it's a file-like object, support duck-typing\n+ kwargs['files'].update({catstr: (f'cat{cat_index}.csv', cat.read())})\n \n if not self.is_table_available(cat):\n if ((colRA is None) or (colDec is None)):\n", "test_patch": "diff --git a/astroquery/xmatch/tests/test_xmatch.py b/astroquery/xmatch/tests/test_xmatch.py\nindex d16f1507..d1c9899a 100644\n--- a/astroquery/xmatch/tests/test_xmatch.py\n+++ b/astroquery/xmatch/tests/test_xmatch.py\n@@ -104,3 +104,13 @@ def test_xmatch_query_cat1_table_local(monkeypatch):\n 'errHalfMaj', 'errHalfMin', 'errPosAng', 'Jmag', 'Hmag', 'Kmag',\n 'e_Jmag', 'e_Hmag', 'e_Kmag', 'Qfl', 'Rfl', 'X', 'MeasureJD']\n assert len(table) == 11\n+\n+\n+def test_two_local_tables():\n+ table1 = Table({'a': [1], 'b': [1], 'c': [1]})\n+ table2 = Table({'a': [1], 'b': [1], 'c': [1]})\n+ payload = XMatch().query(cat1=table1, cat2=table2,\n+ colRA1=\"a\", colDec1=\"b\", colRA2=\"a\", colDec2=\"b\",\n+ max_distance=1 * arcsec,\n+ get_query_payload=True)\n+ assert 'cat1' in payload[1][\"files\"] and 'cat2' in payload[1][\"files\"]\n", "FAIL_TO_PASS": ["astroquery/xmatch/tests/test_xmatch.py::test_two_local_tables"]}, {"instance_id": "astropy__astroquery-3168", "base_commit": "aeccd83259aaa9ebdc9a48325791f89789e4324d", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 80dfdf76..390c5ab8 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -286,6 +286,9 @@ xmatch\n - Fix xmatch query for two local tables. The second table was written over the first one,\n resulting in a confusing \"missing cat1\" error. [#3116]\n \n+- Make the error message clearer about VizieR tables not available for\n+ crossmatching [#3168]\n+\n \n 0.4.7 (2024-03-08)\n ==================\ndiff --git a/astroquery/xmatch/core.py b/astroquery/xmatch/core.py\nindex 57cc9549..051f07a2 100644\n--- a/astroquery/xmatch/core.py\n+++ b/astroquery/xmatch/core.py\n@@ -146,7 +146,12 @@ class XMatchClass(BaseQuery):\n \n if not self.is_table_available(cat):\n if ((colRA is None) or (colDec is None)):\n- raise ValueError('Specify the name of the RA/Dec columns in the input table.')\n+ raise ValueError(\n+ f\"'{cat}' is not available on the XMatch server. If you are \"\n+ \"using a VizieR table name, note that only tables with \"\n+ \"coordinates are available on the XMatch server. If you are \"\n+ f\"using a local table, the arguments 'colRA{cat_index}' and \"\n+ f\"'colDec{cat_index}' must be provided.\")\n # if `cat1` is not a VizieR table,\n # it is assumed it's either a URL or an uploaded table\n payload['colRA{0}'.format(cat_index)] = colRA\n", "test_patch": "diff --git a/astroquery/xmatch/tests/test_xmatch.py b/astroquery/xmatch/tests/test_xmatch.py\nindex d1c9899a..8c303516 100644\n--- a/astroquery/xmatch/tests/test_xmatch.py\n+++ b/astroquery/xmatch/tests/test_xmatch.py\n@@ -1,5 +1,6 @@\n # Licensed under a 3-clause BSD style license - see LICENSE.rst\n from pathlib import Path\n+import re\n \n import requests\n import pytest\n@@ -114,3 +115,13 @@ def test_two_local_tables():\n max_distance=1 * arcsec,\n get_query_payload=True)\n assert 'cat1' in payload[1][\"files\"] and 'cat2' in payload[1][\"files\"]\n+\n+\n+def test_table_not_available(monkeypatch):\n+ xm = XMatch()\n+ monkeypatch.setattr(xm, '_request', request_mockreturn)\n+ cat1 = \"vizier:J/A+A/331/81/table2\"\n+ cat2 = \"blabla\"\n+ # reproduces #1464\n+ with pytest.raises(ValueError, match=f\"'{re.escape(cat1)}' is not available *\"):\n+ xm.query_async(cat1=cat1, cat2=cat2, max_distance=5 * arcsec)\n", "FAIL_TO_PASS": ["astroquery/xmatch/tests/test_xmatch.py::test_table_not_available"]}], "all_FAIL_TO_PASS": ["astroquery/xmatch/tests/test_xmatch.py::test_two_local_tables", "astroquery/xmatch/tests/test_xmatch.py::test_table_not_available"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "canonical__operator-823_x2", "level": 2, "source": "swerebench", "repo": "canonical/operator", "image": "swerebench/sweb.eval.x86_64.canonical_1776_operator-823:latest", "base_commit": "77ac36224aa7f79d4ab7c2b11d060a52c8b83ae4", "num_bugs": 2, "bugs": [{"instance_id": "canonical__operator-823", "base_commit": "77ac36224aa7f79d4ab7c2b11d060a52c8b83ae4", "gold_patch": "diff --git a/ops/model.py b/ops/model.py\nindex 6c51a81..5532a70 100644\n--- a/ops/model.py\n+++ b/ops/model.py\n@@ -93,7 +93,7 @@ if typing.TYPE_CHECKING:\n _RelationsMeta_Raw = Dict[str, ops.charm.RelationMeta]\n # mapping from container name to container metadata\n _ContainerMeta_Raw = Dict[str, ops.charm.ContainerMeta]\n- _IPAddress = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]\n+ _NetworkAddress = Union[ipaddress.IPv4Address, ipaddress.IPv6Address, str]\n _Network = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]\n \n _ServiceInfoMapping = Mapping[str, pebble.ServiceInfo]\n@@ -692,6 +692,17 @@ class Binding:\n return self._network\n \n \n+def _cast_network_address(raw: str) -> '_NetworkAddress':\n+ # fields marked as network addresses need not be IPs; they could be\n+ # hostnames that juju failed to resolve. In that case, we'll log a\n+ # debug message and leave it as-is.\n+ try:\n+ return ipaddress.ip_address(raw)\n+ except ValueError:\n+ logger.debug(\"could not cast {} to IPv4/v6 address\".format(raw))\n+ return raw\n+\n+\n class Network:\n \"\"\"Network space details.\n \n@@ -725,15 +736,15 @@ class Network:\n if addrs is not None:\n for address_info in addrs:\n self.interfaces.append(NetworkInterface(interface_name, address_info))\n- self.ingress_addresses = [] # type: List[_IPAddress]\n+ self.ingress_addresses = [] # type: List[_NetworkAddress]\n for address in network_info.get('ingress-addresses', []):\n- self.ingress_addresses.append(ipaddress.ip_address(address))\n+ self.ingress_addresses.append(_cast_network_address(address))\n self.egress_subnets = [] # type: List[_Network]\n for subnet in network_info.get('egress-subnets', []):\n self.egress_subnets.append(ipaddress.ip_network(subnet))\n \n @property\n- def bind_address(self) -> Optional['_IPAddress']:\n+ def bind_address(self) -> Optional['_NetworkAddress']:\n \"\"\"A single address that your application should bind() to.\n \n For the common case where there is a single answer. This represents a single\n@@ -746,7 +757,7 @@ class Network:\n return None\n \n @property\n- def ingress_address(self):\n+ def ingress_address(self) -> Optional['_NetworkAddress']:\n \"\"\"The address other applications should use to connect to your unit.\n \n Due to things like public/private addresses, NAT and tunneling, the address you bind()\n@@ -782,8 +793,8 @@ class NetworkInterface:\n address = address_info.get('address')\n \n # The value field may be empty.\n- address_ = ipaddress.ip_address(address) if address else None\n- self.address = address_ # type: Optional[_IPAddress]\n+ address_ = _cast_network_address(address) if address else None\n+ self.address = address_ # type: Optional[_NetworkAddress]\n cidr = address_info.get('cidr') # type: str\n # The cidr field may be empty, see LP: #1864102.\n if cidr:\n", "test_patch": "diff --git a/test/test_model.py b/test/test_model.py\nindex 495859f..173168f 100755\n--- a/test/test_model.py\n+++ b/test/test_model.py\n@@ -1912,6 +1912,16 @@ class TestModelBindings(unittest.TestCase):\n self.assertEqual(binding.network.interfaces[i].address, ipaddress.ip_address(address))\n self.assertEqual(binding.network.interfaces[i].subnet, ipaddress.ip_network(subnet))\n \n+ for (i, (name, address, subnet)) in enumerate([\n+ ('lo', '192.0.2.2', '192.0.2.0/24'),\n+ ('lo', 'dead:beef::1', 'dead:beef::/64'),\n+ ('tun', '192.0.3.3', '192.0.3.3/32'),\n+ ('tun', '2001:db8::3', '2001:db8::3/128'),\n+ ('tun', 'fe80::1:1', 'fe80::/64')]):\n+ self.assertEqual(binding.network.interfaces[i].name, name)\n+ self.assertEqual(binding.network.interfaces[i].address, ipaddress.ip_address(address))\n+ self.assertEqual(binding.network.interfaces[i].subnet, ipaddress.ip_network(subnet))\n+\n def test_invalid_keys(self):\n # Basic validation for passing invalid keys.\n for name in (object, 0):\n@@ -2058,6 +2068,20 @@ class TestModelBindings(unittest.TestCase):\n binding = self.model.get_binding(self.model.get_relation(binding_name))\n self.assertEqual(binding.network.egress_subnets, [])\n \n+ def test_unresolved_ingress_addresses(self):\n+ # sometimes juju fails to resolve an url to an IP, in which case\n+ # ingress-addresses will be the 'raw' url instead of an IP.\n+ network_data = json.dumps({\n+ 'ingress-addresses': [\n+ 'foo.bar.baz.com'\n+ ],\n+ })\n+ fake_script(self, 'network-get',\n+ '''[ \"$1\" = db0 ] && echo '{}' || exit 1'''.format(network_data))\n+ binding_name = 'db0'\n+ binding = self.model.get_binding(self.model.get_relation(binding_name))\n+ self.assertEqual(binding.network.ingress_addresses, ['foo.bar.baz.com'])\n+\n \n class TestModelBackend(unittest.TestCase):\n \n", "FAIL_TO_PASS": ["test/test_model.py::TestModelBindings::test_unresolved_ingress_addresses"]}, {"instance_id": "canonical__operator-860", "base_commit": "28251faf41868017aec5add2b59a80719f5354db", "gold_patch": "diff --git a/ops/model.py b/ops/model.py\nindex 9412ae9..79af88f 100644\n--- a/ops/model.py\n+++ b/ops/model.py\n@@ -1418,17 +1418,17 @@ class Container:\n # instance that is in fact 'ready'.\n self._pebble.get_system_info()\n except pebble.ConnectionError as e:\n- logger.debug(\"Pebble API is not ready; ConnectionError: %s\", e.message())\n+ logger.debug(\"Pebble API is not ready; ConnectionError: %s\", e)\n return False\n except FileNotFoundError as e:\n # In some cases, charm authors can attempt to hit the Pebble API before it has had the\n # chance to create the UNIX socket in the shared volume.\n- logger.debug(\"Pebble API is not ready; UNIX socket not found:\", str(e))\n+ logger.debug(\"Pebble API is not ready; UNIX socket not found: %s\", e)\n return False\n except pebble.APIError as e:\n # An API error is only raised when the Pebble API returns invalid JSON, or the response\n # cannot be read. Both of these are a likely indicator that something is wrong.\n- logger.warning(\"Pebble API is not ready; APIError: %s\", str(e))\n+ logger.warning(\"Pebble API is not ready; APIError: %s\", e)\n return False\n return True\n \ndiff --git a/ops/pebble.py b/ops/pebble.py\nindex 71de6fb..0c15c3d 100644\n--- a/ops/pebble.py\n+++ b/ops/pebble.py\n@@ -333,14 +333,6 @@ class Error(Exception):\n def __repr__(self):\n return '<{}.{} {}>'.format(type(self).__module__, type(self).__name__, self.args)\n \n- def name(self):\n- \"\"\"Return a string representation of the model plus class.\"\"\"\n- return '<{}.{}>'.format(type(self).__module__, type(self).__name__)\n-\n- def message(self):\n- \"\"\"Return the message passed as an argument.\"\"\"\n- return self.args[0]\n-\n \n class TimeoutError(TimeoutError, Error):\n \"\"\"Raised when a polling timeout occurs.\"\"\"\n", "test_patch": "diff --git a/ops/testing.py b/ops/testing.py\nindex d92609b..98507a5 100755\n--- a/ops/testing.py\n+++ b/ops/testing.py\n@@ -1406,6 +1406,7 @@ class _TestingModelBackend:\n if self._resource_dir is not None:\n self._resource_dir.cleanup()\n self._resource_dir = None\n+ self._harness_tmp_dir.cleanup()\n \n def _get_resource_dir(self) -> pathlib.Path:\n if self._resource_dir is None:\ndiff --git a/test/test_model.py b/test/test_model.py\nindex 173168f..e1ff14d 100755\n--- a/test/test_model.py\n+++ b/test/test_model.py\n@@ -33,7 +33,14 @@ import ops.testing\n from ops import model\n from ops._private import yaml\n from ops.charm import RelationMeta, RelationRole\n-from ops.pebble import APIError, FileInfo, FileType, ServiceInfo\n+from ops.pebble import (\n+ APIError,\n+ ConnectionError,\n+ FileInfo,\n+ FileType,\n+ ServiceInfo,\n+ SystemInfo,\n+)\n \n \n class TestModel(unittest.TestCase):\n@@ -1354,8 +1361,9 @@ containers:\n self.container.replan()\n self.assertEqual(self.pebble.requests, [('replan',)])\n \n- def test_get_system_info(self):\n- self.container.can_connect()\n+ def test_can_connect(self):\n+ self.pebble.responses.append(SystemInfo.from_dict({'version': '1.0.0'}))\n+ self.assertTrue(self.container.can_connect())\n self.assertEqual(self.pebble.requests, [('get_system_info',)])\n \n def test_start(self):\n@@ -1687,10 +1695,37 @@ containers:\n ('remove_path', '/path/2', True),\n ])\n \n- def test_bare_can_connect_call(self):\n- self.pebble.responses.append('dummy')\n+ def test_can_connect_simple(self):\n+ self.pebble.responses.append(SystemInfo.from_dict({'version': '1.0.0'}))\n self.assertTrue(self.container.can_connect())\n \n+ def test_can_connect_connection_error(self):\n+ def raise_error():\n+ raise ConnectionError('connection error!')\n+ self.pebble.get_system_info = raise_error\n+ with self.assertLogs('ops.model', level='DEBUG') as cm:\n+ self.assertFalse(self.container.can_connect())\n+ self.assertEqual(len(cm.output), 1)\n+ self.assertRegex(cm.output[0], r'DEBUG:ops.model:.*: connection error!')\n+\n+ def test_can_connect_file_not_found_error(self):\n+ def raise_error():\n+ raise FileNotFoundError('file not found!')\n+ self.pebble.get_system_info = raise_error\n+ with self.assertLogs('ops.model', level='DEBUG') as cm:\n+ self.assertFalse(self.container.can_connect())\n+ self.assertEqual(len(cm.output), 1)\n+ self.assertRegex(cm.output[0], r'DEBUG:ops.model:.*: file not found!')\n+\n+ def test_can_connect_api_error(self):\n+ def raise_error():\n+ raise APIError('body', 404, 'status', 'api error!')\n+ self.pebble.get_system_info = raise_error\n+ with self.assertLogs('ops.model') as cm:\n+ self.assertFalse(self.container.can_connect())\n+ self.assertEqual(len(cm.output), 1)\n+ self.assertRegex(cm.output[0], r'WARNING:ops.model:.*: api error!')\n+\n def test_exec(self):\n self.pebble.responses.append('fake_exec_process')\n p = self.container.exec(\n@@ -1759,6 +1794,7 @@ class MockPebbleClient:\n \n def get_system_info(self):\n self.requests.append(('get_system_info',))\n+ return self.responses.pop(0)\n \n def replan_services(self):\n self.requests.append(('replan',))\ndiff --git a/test/test_pebble.py b/test/test_pebble.py\nindex 924d110..d076795 100644\n--- a/test/test_pebble.py\n+++ b/test/test_pebble.py\n@@ -1248,7 +1248,7 @@ class TestMultipartParser(unittest.TestCase):\n if not test.error:\n self.fail('unexpected error:', err)\n break\n- self.assertEqual(test.error, err.message())\n+ self.assertEqual(test.error, str(err))\n else:\n if test.error:\n self.fail('missing expected error: {!r}'.format(test.error))\n", "FAIL_TO_PASS": ["test/test_model.py::TestContainerPebble::test_can_connect_file_not_found_error"]}], "all_FAIL_TO_PASS": ["test/test_model.py::TestModelBindings::test_unresolved_ingress_addresses", "test/test_model.py::TestContainerPebble::test_can_connect_file_not_found_error"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "dlr-eoc__ukis-pysat-47_x2", "level": 2, "source": "swerebench", "repo": "dlr-eoc/ukis-pysat", "image": "swerebench/sweb.eval.x86_64.dlr-eoc_1776_ukis-pysat-47:latest", "base_commit": "8ebed56f52694f469e2ea9cb4c0f4142326f2496", "num_bugs": 2, "bugs": [{"instance_id": "dlr-eoc__ukis-pysat-47", "base_commit": "8ebed56f52694f469e2ea9cb4c0f4142326f2496", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex e04d08e..8334b7f 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -13,7 +13,7 @@ Changed\n ~~~~~~~\r\n something was changed\r\n \r\n-[master] (2020-06-16)\r\n+[master] (2020-**-**)\r\n ----------------------\r\n \r\n Added\r\n@@ -24,6 +24,10 @@ Fixed\n *****\r\n - ``file.get_ts_from_sentinel_filename()``: Return datetime.datetime objects instead of timestamp strings #42\r\n \r\n+Changed\r\n+*******\r\n+- ``raster.Image()``: update of init signature to be less confusing #41\r\n+\r\n [0.4.0] (2020-06-05)\r\n ----------------------\r\n \r\ndiff --git a/ukis_pysat/raster.py b/ukis_pysat/raster.py\nindex 3eeb1bd..f8ce71a 100644\n--- a/ukis_pysat/raster.py\n+++ b/ukis_pysat/raster.py\n@@ -1,8 +1,10 @@\n-#!/usr/bin/env python3\r\n+# -*- coding: utf-8 -*-\r\n \r\n import math\r\n from itertools import product\r\n \r\n+from ukis_pysat.members import Platform\r\n+\r\n try:\r\n import numpy as np\r\n import rasterio\r\n@@ -22,41 +24,46 @@ except ImportError as e:\n )\r\n raise ImportError(str(e) + \"\\n\\n\" + msg)\r\n \r\n-from ukis_pysat.members import Platform\r\n-\r\n \r\n class Image:\r\n- def __init__(self, path=None, dataset=None, arr=None, dimorder=\"first\"):\r\n+\r\n+ da_arr = None\r\n+\r\n+ def __init__(self, data, dimorder=\"first\", crs=None, transform=None):\r\n \"\"\"\r\n- :param path: str, path to raster (default: None)\r\n- :param dataset: rasterio.io.DatasetReader (default: None)\r\n- :param arr: np.ndarray (default: None)\r\n- :param dimorder: dimensions order of arr. return channels or bands as 'first' or 'last' dimension. should match\r\n- the dimensions order of the input array when initializing an image from an array (default: 'first)\r\n+ :param data: rasterio.io.DatasetReader or path to raster or np.ndarray of shape (bands, rows, columns)\r\n+ :param dimorder: Order of channels or bands 'first' or 'last' (default: 'first')\r\n+ :param crs: Coordinate reference system used when creating form array. If 'data' is np.ndarray this is required (default: None)\r\n+ :param transform: Affine transformation mapping the pixel space to geographic space. If 'data' is np.ndarray this is required (default:None)\r\n \"\"\"\r\n- if path:\r\n- if isinstance(path, str):\r\n- self.dataset = rasterio.open(path)\r\n- self.__arr = self.dataset.read()\r\n- else:\r\n- raise TypeError(f\"path must be of type str\")\r\n+ if dimorder in (\"first\", \"last\"):\r\n+ self.dimorder = dimorder\r\n else:\r\n- if isinstance(dataset, rasterio.io.DatasetReader) and isinstance(arr, np.ndarray):\r\n- self.dataset = dataset\r\n- if dimorder == \"first\":\r\n- self.__arr = arr\r\n- elif dimorder == \"last\":\r\n- self.__arr = reshape_as_raster(arr)\r\n- else:\r\n- raise AttributeError(\"dimorder for bands or channels must be either 'first' or 'last'.\")\r\n+ raise TypeError(\"dimorder for bands or channels must be either 'first' or 'last'.\")\r\n+ try:\r\n+ self.dataset = rasterio.open(data)\r\n+ self.crs = self.dataset.crs\r\n+ self.transform = self.dataset.transform\r\n+ self.__arr = self.dataset.read()\r\n+ except (TypeError, AttributeError):\r\n+ if isinstance(data, rasterio.io.DatasetReader):\r\n+ self.dataset = data\r\n+ self.crs = self.dataset.crs\r\n+ self.transform = self.dataset.transform\r\n+ self.__arr = self.dataset.read()\r\n+ elif isinstance(data, np.ndarray):\r\n+ if crs is None:\r\n+ raise TypeError(\"if dataset is of type np.ndarray crs must not be None\")\r\n+ if transform is None:\r\n+ raise TypeError(\"if dataset is of type np.ndarray transform must not be None\")\r\n+ meta = {\"dtype\": data.dtype, \"count\": data.shape[0], \"crs\": crs, \"driver\": \"GTiff\"}\r\n+ self.__arr = data\r\n+ self.transform = transform\r\n+ self.dataset = self.__update_dataset(meta).open()\r\n+ self.crs = self.dataset.crs\r\n+ self.transform = self.dataset.transform\r\n else:\r\n- raise TypeError(\r\n- f\"dataset must be of type rasterio.io.DatasetReader and arr must be of type \" f\"numpy.ndarray\"\r\n- )\r\n- self.dimorder = dimorder\r\n- self.transform = self.dataset.transform\r\n- self.crs = self.dataset.crs\r\n- self.da_arr = None\r\n+ raise TypeError(\"dataset must be of type str, rasterio.io.DatasetReader or np.ndarray\")\r\n \r\n @property\r\n def arr(self):\r\n@@ -77,16 +84,18 @@ class Image:\n valid_data_window = windows.get_data_window(self.__arr, nodata=nodata)\r\n return windows.bounds(valid_data_window, windows.transform(valid_data_window, self.transform))\r\n \r\n- def mask_image(self, bbox, crop=True, pad=False, **kwargs):\r\n+ def mask_image(self, bbox, crop=True, pad=False, mode=\"constant\", constant_values=0):\r\n \"\"\"Mask the area outside of the input shapes with no data.\r\n \r\n :param bbox: bounding box of type tuple or Shapely Polygon\r\n :param crop: bool, see rasterio.mask. Optional, (default: True)\r\n :param pad: pads image, should only be used when bbox.bounds extent img.bounds, optional (default: False)\r\n+ :param mode: str, how to pad, see rasterio.pad. Optional (default: 'constant') \r\n+ :param constant_values: nodata value, padding should be filled with, optional (default: 0)\r\n \"\"\"\r\n # TODO https://github.com/mapbox/rasterio/issues/995\r\n if pad:\r\n- self.dataset = self._pad_to_bbox(bbox, **kwargs).open()\r\n+ self.dataset = self._pad_to_bbox(bbox, mode, constant_values).open()\r\n \r\n if isinstance(bbox, polygon.Polygon):\r\n self.__arr, self.transform = rasterio.mask.mask(self.dataset, [bbox], crop=crop)\r\n@@ -96,7 +105,7 @@ class Image:\n raise TypeError(f\"bbox must be of type tuple or Shapely Polygon\")\r\n \r\n # update for further processing\r\n- self.dataset = self.__update_dataset().open()\r\n+ self.dataset = self.__update_dataset(self.dataset.meta).open()\r\n \r\n def _pad_to_bbox(self, bbox, mode=\"constant\", constant_values=0):\r\n \"\"\"Buffers array with biggest difference to bbox and adjusts affine transform matrix. Can be used to fill\r\n@@ -132,20 +141,21 @@ class Image:\n \r\n self.__arr = destination\r\n \r\n- return self.__update_dataset()\r\n+ return self.__update_dataset(self.dataset.meta)\r\n \r\n- def __update_dataset(self):\r\n+ def __update_dataset(self, meta):\r\n \"\"\"Update dataset without writing to file after it theoretically changed.\r\n \r\n+ :param meta: The basic metadata of the dataset as returned from the meta property of rasterio Datasets\r\n :return: closed dataset in memory\r\n \"\"\"\r\n- mem_profile = self.dataset.meta\r\n- mem_profile.update(\r\n+\r\n+ meta.update(\r\n {\"height\": self.__arr.shape[-2], \"width\": self.__arr.shape[-1], \"transform\": self.transform,}\r\n )\r\n \r\n memfile = MemoryFile()\r\n- ds = memfile.open(**mem_profile)\r\n+ ds = memfile.open(**meta)\r\n ds.write(self.__arr)\r\n \r\n return memfile\r\n@@ -193,7 +203,7 @@ class Image:\n self.__arr = destination\r\n self.transform = transform\r\n self.crs = dst_crs\r\n- self.dataset = self.__update_dataset().open()\r\n+ self.dataset = self.__update_dataset(self.dataset.meta).open()\r\n \r\n def dn2toa(self, platform, mtl_file=None, wavelengths=None):\r\n \"\"\"This method converts digital numbers to top of atmosphere reflectance, like described here:\r\n@@ -373,7 +383,7 @@ class Image:\n :param nodata: nodata value, e.g. 255 (default: None, means nodata value of dataset will be used)\r\n :param compress: compression, e.g. 'lzw' (default: None)\r\n \"\"\"\r\n- if dtype == 'min':\r\n+ if dtype == \"min\":\r\n dtype = get_minimum_dtype(self.__arr)\r\n \r\n profile = self.dataset.meta\r\n@@ -400,7 +410,3 @@ class Image:\n def close(self):\r\n \"\"\"closes Image\"\"\"\r\n self.dataset.close()\r\n-\r\n-\r\n-if __name__ == \"__main__\":\r\n- pass\r\n", "test_patch": "diff --git a/tests/test_data.py b/tests/test_data.py\nindex 4a5fca2..37bdf3b 100644\n--- a/tests/test_data.py\n+++ b/tests/test_data.py\n@@ -2,8 +2,8 @@ import os\n import traceback\r\n import unittest\r\n \r\n-from ukis_pysat.members import Datahub, Platform\r\n from ukis_pysat.data import Source\r\n+from ukis_pysat.members import Datahub, Platform\r\n \r\n # os.environ[\"EARTHEXPLORER_USER\"] = \"Tim\"\r\n # os.environ[\"EARTHEXPLORER_PW\"] = \"TheEnchanter\"\r\n@@ -121,6 +121,7 @@ class DownloadTest(unittest.TestCase):\n with self.assertRaises(TypeError, msg=f\"aoi must be of type string or tuple\"):\r\n src.prep_aoi(1)\r\n \r\n+ @unittest.skip(\"until API is reachable again\")\r\n # @unittest.skip(\"uncomment when you set ENVs with credentials\")\r\n def test_query_metadata(self):\r\n for i in range(len(queries)):\r\n@@ -144,9 +145,12 @@ class DownloadTest(unittest.TestCase):\n def test_download_image(self):\r\n src = Source(datahub=Datahub.File, datadir=target_dir)\r\n with self.assertRaises(Exception, msg=\"download_image not supported for Datahub.File.\"):\r\n- src.download_image(platform=Datahub.File, product_uuid=\"1\", target_dir=target_dir,)\r\n+ src.download_image(\r\n+ platform=Datahub.File, product_uuid=\"1\", target_dir=target_dir,\r\n+ )\r\n # TODO download tests\r\n \r\n+ @unittest.skip(\"until API is reachable again\")\r\n # @unittest.skip(\"uncomment when you set ENVs with credentials\")\r\n def test_download_quicklook(self):\r\n for i in range(len(queries)):\r\n@@ -171,7 +175,9 @@ class DownloadTest(unittest.TestCase):\n \r\n src = Source(datahub=Datahub.File, datadir=target_dir)\r\n with self.assertRaises(NotImplementedError, msg=f\"download_quicklook not supported for Datahub.File.\"):\r\n- src.download_quicklook(platform=Datahub.File, product_uuid=\"1\", target_dir=target_dir,)\r\n+ src.download_quicklook(\r\n+ platform=Datahub.File, product_uuid=\"1\", target_dir=target_dir,\r\n+ )\r\n \r\n \r\n if __name__ == \"__main__\":\r\ndiff --git a/tests/test_raster.py b/tests/test_raster.py\nindex 7e7cc02..ea32ae0 100644\n--- a/tests/test_raster.py\n+++ b/tests/test_raster.py\n@@ -1,3 +1,4 @@\n+#!/usr/bin/env python3\r\n import os\r\n import unittest\r\n \r\n@@ -7,32 +8,55 @@ from rasterio import windows\n from rasterio.coords import BoundingBox\r\n from rasterio.transform import from_bounds\r\n from shapely.geometry import box\r\n-\r\n from ukis_pysat.members import Platform\r\n from ukis_pysat.raster import Image\r\n \r\n-img = Image(path=os.path.join(os.path.dirname(__file__), \"testfiles\", \"dummy.tif\"))\r\n+TEST_FILE = os.path.join(os.path.dirname(__file__), \"testfiles\", \"dummy.tif\")\r\n \r\n \r\n class DataTest(unittest.TestCase):\r\n+ def setUp(self):\r\n+ self.img = Image(TEST_FILE)\r\n+\r\n+ def tearDown(self):\r\n+ self.img.close()\r\n+\r\n def test_init(self):\r\n- with self.assertRaises(TypeError, msg=f\"path must be of type str\"):\r\n- Image(path=1)\r\n+ img = Image(self.img.dataset)\r\n+ self.assertTrue(np.array_equal(self.img.arr, img.arr))\r\n+ img.close()\r\n \r\n- with self.assertRaises(\r\n- TypeError, msg=f\"dataset must be of type rasterio.io.DatasetReader and arr must be of type numpy.ndarray\"\r\n- ):\r\n- Image(dataset=1, arr=img.arr)\r\n+ def test_init_fail_invalid_path(self):\r\n+ with self.assertRaises(TypeError):\r\n+ Image(1)\r\n \r\n- with self.assertRaises(\r\n- TypeError, msg=f\"dataset must be of type rasterio.io.DatasetReader and arr must be of type numpy.ndarray\"\r\n- ):\r\n- Image(arr=img.arr)\r\n+ def test_init_fail_invalid_dataset(self):\r\n+ with self.assertRaises(TypeError,):\r\n+ Image(1)\r\n \r\n- self.assertTrue(np.array_equal(img.arr, Image(dataset=img.dataset, arr=img.arr).arr))\r\n+ def test_init_with_arry_fail_missing_crs_and_transform(self):\r\n+ with self.assertRaises(TypeError):\r\n+ Image(data=self.img.arr)\r\n+\r\n+ def test_init_with_arry_fail_missing_transform(self):\r\n+ with self.assertRaises(TypeError):\r\n+ Image(data=self.img.arr, crs=self.img.crs)\r\n+\r\n+ def test_init_with_array(self):\r\n+ img = Image(self.img.arr, crs=self.img.crs, transform=self.img.transform)\r\n+ self.assertTrue(np.array_equal(self.img.arr, img.arr))\r\n+ img.close()\r\n+\r\n+ def test_init_with_arry_fail_missing_crs(self):\r\n+ with self.assertRaises(TypeError):\r\n+ Image(data=self.img.arr, crs=self.img.transform)\r\n+\r\n+ def test_dimorder_error(self):\r\n+ with self.assertRaises(TypeError):\r\n+ img_first = Image(TEST_FILE, dimorder=\"middle\")\r\n \r\n def test_arr(self):\r\n- img_first = Image(path=os.path.join(os.path.dirname(__file__), \"testfiles\", \"dummy.tif\"), dimorder=\"first\")\r\n+ img_first = Image(TEST_FILE, dimorder=\"first\")\r\n img_first.mask_image(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n self.assertEqual(img_first.arr.shape, (1, 385, 502))\r\n self.assertEqual(\r\n@@ -48,8 +72,9 @@ class DataTest(unittest.TestCase):\n )\r\n ),\r\n )\r\n+ img_first.close()\r\n \r\n- img_last = Image(path=os.path.join(os.path.dirname(__file__), \"testfiles\", \"dummy.tif\"), dimorder=\"last\")\r\n+ img_last = Image(TEST_FILE, dimorder=\"last\")\r\n img_last.mask_image(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n self.assertEqual(img_last.arr.shape, (385, 502, 1))\r\n self.assertEqual(\r\n@@ -65,64 +90,62 @@ class DataTest(unittest.TestCase):\n )\r\n ),\r\n )\r\n+ img_last.close()\r\n \r\n- img = Image(path=os.path.join(os.path.dirname(__file__), \"testfiles\", \"dummy.tif\"), dimorder=\"first\")\r\n- img_first = Image(dataset=img.dataset, arr=np.ones((1, 385, 502)), dimorder=\"first\")\r\n+ img_first = Image(np.ones((1, 385, 502)), dimorder=\"first\", crs=self.img.crs, transform=self.img.transform)\r\n self.assertEqual(img_first.arr.shape, (1, 385, 502))\r\n+ img_first.close()\r\n \r\n- img_last = Image(dataset=img.dataset, arr=np.ones((385, 502, 1)), dimorder=\"last\")\r\n+ img_last = Image(np.ones((1, 385, 502)), dimorder=\"last\", crs=self.img.crs, transform=self.img.transform)\r\n self.assertEqual(img_last.arr.shape, (385, 502, 1))\r\n-\r\n- with self.assertRaises(AttributeError, msg=\"dimorder for bands or channels must be either 'first' or 'last'.\"):\r\n- img_first = Image(path=os.path.join(os.path.dirname(__file__), \"testfiles\", \"dummy.tif\"), dimorder=\"middle\")\r\n- img_first.arr\r\n+ img_last.close()\r\n \r\n def test_get_valid_data_bbox(self):\r\n self.assertEqual(\r\n- img.get_valid_data_bbox(), (11.896863892, 51.515176657, 11.896863892, 51.515176657),\r\n+ self.img.get_valid_data_bbox(), (11.896863892, 51.515176657, 11.896863892, 51.515176657),\r\n )\r\n self.assertEqual(\r\n- img.get_valid_data_bbox(nodata=1), (11.896863892, 51.446545369, 11.9578595, 51.515176657),\r\n+ self.img.get_valid_data_bbox(nodata=1), (11.896863892, 51.446545369, 11.9578595, 51.515176657),\r\n )\r\n \r\n def test_mask_image(self):\r\n with self.assertRaises(TypeError, msg=\"bbox must be of type tuple or Shapely Polygon\"):\r\n- img.mask_image([1, 2, 3])\r\n+ self.img.mask_image([1, 2, 3])\r\n \r\n- img.mask_image(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n+ self.img.mask_image(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n self.assertEqual(\r\n- img.dataset.bounds,\r\n+ self.img.dataset.bounds,\r\n BoundingBox(\r\n left=11.902702941366716, bottom=51.46639813686387, right=11.947798368783504, top=51.50098327545026,\r\n ),\r\n )\r\n \r\n- img.mask_image((11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n+ self.img.mask_image((11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))\r\n self.assertEqual(\r\n- img.dataset.bounds,\r\n+ self.img.dataset.bounds,\r\n BoundingBox(\r\n left=11.902702941366716, bottom=51.46639813686387, right=11.947798368783504, top=51.50098327545026,\r\n ),\r\n )\r\n \r\n- img.mask_image(\r\n+ self.img.mask_image(\r\n box(11.8919236802142620, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,), pad=True,\r\n )\r\n self.assertEqual(\r\n- img.dataset.bounds,\r\n+ self.img.dataset.bounds,\r\n BoundingBox(\r\n left=11.891923157920472, bottom=51.46639813686387, right=11.947798368783504, top=51.50098327545026\r\n ),\r\n )\r\n \r\n def test_warp(self):\r\n- self.assertEqual(img.crs, \"EPSG:4326\")\r\n+ self.assertEqual(self.img.crs, \"EPSG:4326\")\r\n \r\n- img.warp(\"EPSG:3857\")\r\n- self.assertEqual(img.crs, \"EPSG:3857\")\r\n+ self.img.warp(\"EPSG:3857\")\r\n+ self.assertEqual(self.img.crs, \"EPSG:3857\")\r\n \r\n- img.warp(\"EPSG:4326\", resolution=1.0)\r\n- self.assertEqual(1.0, img.transform.to_gdal()[1])\r\n+ self.img.warp(\"EPSG:4326\", resolution=1.0)\r\n+ self.assertEqual(1.0, self.img.transform.to_gdal()[1])\r\n \r\n def test_dn2toa(self):\r\n target_dir = os.path.join(os.path.dirname(__file__), \"testfiles\", \"satellite_data\")\r\n@@ -160,33 +183,33 @@ class DataTest(unittest.TestCase):\n ]\r\n \r\n for i in range(len(tests)):\r\n- img_dn = Image(path=tests[i][\"dn_file\"])\r\n- img_toa = Image(path=tests[i][\"toa_file\"])\r\n+ img_dn = Image(tests[i][\"dn_file\"])\r\n+ img_toa = Image(tests[i][\"toa_file\"])\r\n img_dn.dn2toa(\r\n platform=tests[i][\"platform\"], mtl_file=tests[i][\"mtl_file\"], wavelengths=tests[i][\"wavelengths\"]\r\n )\r\n self.assertTrue(np.array_equal(img_dn.arr, img_toa.arr))\r\n \r\n with self.assertRaises(AttributeError, msg=f\"'mtl_file' has to be set if platform is {Platform.Landsat8}.\"):\r\n- img.dn2toa(platform=Platform.Landsat8)\r\n+ self.img.dn2toa(platform=Platform.Landsat8)\r\n \r\n with self.assertRaises(\r\n AttributeError,\r\n msg=f\"Cannot convert dn2toa. Platform {Platform.Sentinel1} not \"\r\n f\"supported [Landsat-5, Landsat-7, Landsat-8, Sentinel-2]. \",\r\n ):\r\n- img.dn2toa(platform=Platform.Sentinel1)\r\n+ self.img.dn2toa(platform=Platform.Sentinel1)\r\n \r\n def test__lookup_bands(self):\r\n self.assertEqual(\r\n- [\"1\", \"2\", \"3\"], img._lookup_bands(Platform.Landsat5, [\"Blue\", \"Green\", \"Red\"]),\r\n+ [\"1\", \"2\", \"3\"], self.img._lookup_bands(Platform.Landsat5, [\"Blue\", \"Green\", \"Red\"]),\r\n )\r\n self.assertEqual(\r\n- [\"8\", \"10\", \"11\"], img._lookup_bands(Platform.Landsat8, [\"PAN\", \"Tirs1\", \"Tirs2\"]),\r\n+ [\"8\", \"10\", \"11\"], self.img._lookup_bands(Platform.Landsat8, [\"PAN\", \"Tirs1\", \"Tirs2\"]),\r\n )\r\n \r\n def test_get_tiles(self):\r\n- for idx, each in enumerate(img.get_tiles(5, 5, 1)):\r\n+ for idx, each in enumerate(self.img.get_tiles(5, 5, 1)):\r\n self.assertIsInstance(each, windows.Window)\r\n if idx == 2578:\r\n self.assertEqual(each, windows.Window(col_off=79, row_off=649, width=7, height=7))\r\n@@ -194,24 +217,24 @@ class DataTest(unittest.TestCase):\n self.assertEqual(idx, 20807)\r\n \r\n def test_get_subset(self):\r\n- for idx, each in enumerate(img.get_tiles(5, 5, 1)):\r\n+ for idx, each in enumerate(self.img.get_tiles(5, 5, 1)):\r\n if idx == 2578:\r\n- array, bounds = img.get_subset(each)\r\n+ array, bounds = self.img.get_subset(each)\r\n self.assertTrue(np.array_equal(array, np.zeros(shape=(7, 7), dtype=array.dtype)))\r\n self.assertEqual(bounds, (11.903960582768779, 51.45624717410995, 11.904589403469808, 51.45687599481152))\r\n \r\n def test_get_dask_array(self):\r\n- self.assertIsInstance(img.to_dask_array(chunk_size=(1, 10, 10)), dask.array.core.Array)\r\n+ self.assertIsInstance(self.img.to_dask_array(chunk_size=(1, 10, 10)), dask.array.core.Array)\r\n \r\n def test_write_to_file(self):\r\n- img.write_to_file(r\"result.tif\", np.uint16)\r\n+ self.img.write_to_file(r\"result.tif\", np.uint16)\r\n img2 = Image(\"result.tif\")\r\n- self.assertTrue(np.array_equal(img2.arr, img.arr))\r\n+ self.assertTrue(np.array_equal(img2.arr, self.img.arr))\r\n \r\n img2.close()\r\n os.remove(r\"result.tif\")\r\n \r\n- img.write_to_file(r\"result.tif\", \"min\", compress=\"lzw\")\r\n+ self.img.write_to_file(r\"result.tif\", \"min\", compress=\"lzw\")\r\n img2 = Image(\"result.tif\")\r\n self.assertEqual(img2.arr.dtype, \"uint8\")\r\n self.assertEqual(img2.dataset.profile[\"compress\"], \"lzw\")\r\n@@ -219,6 +242,14 @@ class DataTest(unittest.TestCase):\n img2.close()\r\n os.remove(r\"result.tif\")\r\n \r\n+ img3 = Image(self.img.arr, crs=self.img.crs, transform=self.img.transform)\r\n+ img3.write_to_file(r\"result.tif\", np.uint16)\r\n+ img3.close()\r\n+ img4 = Image(\"result.tif\")\r\n+ self.assertTrue(np.array_equal(img4.arr, self.img.arr))\r\n+ img4.close()\r\n+ os.remove(r\"result.tif\")\r\n+\r\n \r\n if __name__ == \"__main__\":\r\n unittest.main()\r\n", "FAIL_TO_PASS": ["tests/test_raster.py::DataTest::test_arr", "tests/test_raster.py::DataTest::test_dimorder_error", "tests/test_raster.py::DataTest::test_init", "tests/test_raster.py::DataTest::test_init_with_array", "tests/test_raster.py::DataTest::test_write_to_file"]}, {"instance_id": "dlr-eoc__ukis-pysat-51", "base_commit": "39b43d24edb8be6f3eb9738b9f4f8d8bdd6cd8e8", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex c3f20aa..d15c395 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -27,7 +27,8 @@ Fixed\n \r\n Changed\r\n *******\r\n-- ``raster.Image()``: update of init signature to be less confusing #41\r\n+- ``raster.Image()``: update of init signature to be less confusing #41 #50\r\n+\r\n \r\n [0.4.0] (2020-06-05)\r\n ----------------------\r\ndiff --git a/ukis_pysat/raster.py b/ukis_pysat/raster.py\nindex 59483a0..e0ac79c 100644\n--- a/ukis_pysat/raster.py\n+++ b/ukis_pysat/raster.py\n@@ -40,40 +40,43 @@ class Image:\n self.dimorder = dimorder\r\n else:\r\n raise TypeError(\"dimorder for bands or channels must be either 'first' or 'last'.\")\r\n- try:\r\n+\r\n+ if isinstance(data, rasterio.io.DatasetReader):\r\n+ self.dataset = data\r\n+ self.crs = self.dataset.crs\r\n+ self.transform = self.dataset.transform\r\n+ self.__arr = self.dataset.read()\r\n+\r\n+ elif isinstance(data, str):\r\n self.dataset = rasterio.open(data)\r\n self.crs = self.dataset.crs\r\n self.transform = self.dataset.transform\r\n self.__arr = self.dataset.read()\r\n- except (TypeError, AttributeError):\r\n- if isinstance(data, rasterio.io.DatasetReader):\r\n- self.dataset = data\r\n- self.crs = self.dataset.crs\r\n- self.transform = self.dataset.transform\r\n- self.__arr = self.dataset.read()\r\n- elif isinstance(data, np.ndarray):\r\n- if crs is None:\r\n- raise TypeError(\"if dataset is of type np.ndarray crs must not be None\")\r\n- if transform is None:\r\n- raise TypeError(\"if dataset is of type np.ndarray transform must not be None\")\r\n- meta = {\"dtype\": data.dtype, \"count\": data.shape[0], \"crs\": crs, \"driver\": \"GTiff\"}\r\n+\r\n+ elif isinstance(data, np.ndarray):\r\n+ if crs is None:\r\n+ raise TypeError(\"if dataset is of type np.ndarray crs must not be None\")\r\n+ if transform is None:\r\n+ raise TypeError(\"if dataset is of type np.ndarray transform must not be None\")\r\n+ if dimorder == \"first\":\r\n self.__arr = data\r\n- self.transform = transform\r\n- self.dataset = self.__update_dataset(meta).open()\r\n- self.crs = self.dataset.crs\r\n- self.transform = self.dataset.transform\r\n else:\r\n- raise TypeError(\"dataset must be of type str, rasterio.io.DatasetReader or np.ndarray\")\r\n+ self.__arr = reshape_as_raster(data)\r\n+ meta = {\"dtype\": self.__arr.dtype, \"count\": self.__arr.shape[0], \"crs\": crs, \"driver\": \"GTiff\"}\r\n+ self.transform = transform\r\n+ self.dataset = self.__update_dataset(meta).open()\r\n+ self.crs = self.dataset.crs\r\n+ self.transform = self.dataset.transform\r\n+ else:\r\n+ raise TypeError(\"dataset must be of type rasterio.io.DatasetReader, str or np.ndarray\")\r\n \r\n @property\r\n def arr(self):\r\n \"\"\"array property\"\"\"\r\n if self.dimorder == \"first\":\r\n return self.__arr\r\n- elif self.dimorder == \"last\":\r\n- return reshape_as_image(self.__arr)\r\n else:\r\n- raise AttributeError(\"dimorder for bands or channels must be either 'first' or 'last'.\")\r\n+ return reshape_as_image(self.__arr)\r\n \r\n def get_valid_data_bbox(self, nodata=0):\r\n \"\"\"bounding box covering the input array's valid data pixels.\r\n@@ -90,7 +93,7 @@ class Image:\n :param bbox: bounding box of type tuple or Shapely Polygon\r\n :param crop: bool, see rasterio.mask. Optional, (default: True)\r\n :param pad: pads image, should only be used when bbox.bounds extent img.bounds, optional (default: False)\r\n- :param mode: str, how to pad, see rasterio.pad. Optional (default: 'constant') \r\n+ :param mode: str, how to pad, see rasterio.pad. Optional (default: 'constant')\r\n :param constant_values: nodata value, padding should be filled with, optional (default: 0)\r\n \"\"\"\r\n # TODO https://github.com/mapbox/rasterio/issues/995\r\n", "test_patch": "diff --git a/tests/test_raster.py b/tests/test_raster.py\nindex ea32ae0..b09158a 100644\n--- a/tests/test_raster.py\n+++ b/tests/test_raster.py\n@@ -96,7 +96,7 @@ class DataTest(unittest.TestCase):\n self.assertEqual(img_first.arr.shape, (1, 385, 502))\r\n img_first.close()\r\n \r\n- img_last = Image(np.ones((1, 385, 502)), dimorder=\"last\", crs=self.img.crs, transform=self.img.transform)\r\n+ img_last = Image(np.ones((385, 502, 1)), dimorder=\"last\", crs=self.img.crs, transform=self.img.transform)\r\n self.assertEqual(img_last.arr.shape, (385, 502, 1))\r\n img_last.close()\r\n \r\n", "FAIL_TO_PASS": ["tests/test_raster.py::DataTest::test_arr"]}], "all_FAIL_TO_PASS": ["tests/test_raster.py::DataTest::test_arr", "tests/test_raster.py::DataTest::test_dimorder_error", "tests/test_raster.py::DataTest::test_init", "tests/test_raster.py::DataTest::test_init_with_array", "tests/test_raster.py::DataTest::test_write_to_file", "tests/test_raster.py::DataTest::test_arr"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Scille__umongo-190_x2", "level": 2, "source": "swerebench", "repo": "Scille/umongo", "image": "swerebench/sweb.eval.x86_64.scille_1776_umongo-190:latest", "base_commit": "3f5339442d1ec3ce66d4e41dabcdb8242bf2e684", "num_bugs": 2, "bugs": [{"instance_id": "Scille__umongo-190", "base_commit": "3f5339442d1ec3ce66d4e41dabcdb8242bf2e684", "gold_patch": "diff --git a/umongo/fields.py b/umongo/fields.py\nindex 4a57703..2cb87e3 100644\n--- a/umongo/fields.py\n+++ b/umongo/fields.py\n@@ -165,6 +165,18 @@ class FloatField(BaseField, ma_fields.Float):\n pass\n \n \n+def _round_to_millisecond(datetime):\n+ \"\"\"Round a datetime to millisecond precision\n+\n+ MongoDB stores datetimes with a millisecond precision.\n+ For consistency, use the same precision in the object representation.\n+ \"\"\"\n+ microseconds = round(datetime.microsecond, -3)\n+ if microseconds == 1000000:\n+ return datetime.replace(microsecond=0) + dt.timedelta(seconds=1)\n+ return datetime.replace(microsecond=microseconds)\n+\n+\n class DateTimeField(BaseField, ma_fields.DateTime):\n \n def _deserialize(self, value, attr, data):\n@@ -172,9 +184,7 @@ class DateTimeField(BaseField, ma_fields.DateTime):\n ret = value\n else:\n ret = super()._deserialize(value, attr, data)\n- # MongoDB stores datetimes with a millisecond precision.\n- # Don't keep more precision in the object than in the database.\n- return ret.replace(microsecond=round(ret.microsecond, -3))\n+ return _round_to_millisecond(ret)\n \n \n class LocalDateTimeField(BaseField, ma_fields.LocalDateTime):\n@@ -184,9 +194,7 @@ class LocalDateTimeField(BaseField, ma_fields.LocalDateTime):\n ret = value\n else:\n ret = super()._deserialize(value, attr, data)\n- # MongoDB stores datetimes with a millisecond precision.\n- # Don't keep more precision in the object than in the database.\n- return ret.replace(microsecond=round(ret.microsecond, -3))\n+ return _round_to_millisecond(ret)\n \n \n # class TimeField(BaseField, ma_fields.Time):\n", "test_patch": "diff --git a/tests/test_fields.py b/tests/test_fields.py\nindex b2503c0..d4d2133 100644\n--- a/tests/test_fields.py\n+++ b/tests/test_fields.py\n@@ -171,6 +171,19 @@ class TestFields(BaseTest):\n })\n assert data['a'].microsecond == 123000\n assert data['b'].microsecond == 123000\n+ s = MySchema()\n+ data, _ = s.load({\n+ 'a': dt.datetime(2016, 8, 6, 12, 59, 59, 999876),\n+ 'b': dt.datetime(2016, 8, 6, 12, 59, 59, 999876),\n+ })\n+ assert data['a'].hour == 13\n+ assert data['b'].hour == 13\n+ assert data['a'].minute == 0\n+ assert data['b'].minute == 0\n+ assert data['a'].second == 0\n+ assert data['b'].second == 0\n+ assert data['a'].microsecond == 0\n+ assert data['b'].microsecond == 0\n \n def test_strictdatetime(self):\n \n", "FAIL_TO_PASS": ["tests/test_fields.py::TestFields::test_datetime"]}, {"instance_id": "Scille__umongo-191", "base_commit": "7f8c4cd62e61d1a62a70706f1780248bb3c3ad2a", "gold_patch": "diff --git a/umongo/fields.py b/umongo/fields.py\nindex 2cb87e3..c2ba09a 100644\n--- a/umongo/fields.py\n+++ b/umongo/fields.py\n@@ -248,9 +248,7 @@ class StrictDateTimeField(BaseField, ma_bonus_fields.StrictDateTime):\n ret = self._set_tz_awareness(value)\n else:\n ret = super()._deserialize(value, attr, data)\n- # MongoDB stores datetimes with a millisecond precision.\n- # Don't keep more precision in the object than in the database.\n- return ret.replace(microsecond=round(ret.microsecond, -3))\n+ return _round_to_millisecond(ret)\n \n def _deserialize_from_mongo(self, value):\n return self._set_tz_awareness(value)\n", "test_patch": "diff --git a/tests/test_fields.py b/tests/test_fields.py\nindex d4d2133..9b90b05 100644\n--- a/tests/test_fields.py\n+++ b/tests/test_fields.py\n@@ -243,6 +243,11 @@ class TestFields(BaseTest):\n s = MySchema()\n data, _ = s.load({'a': dt.datetime(2016, 8, 6, 12, 30, 30, 123456)})\n assert data['a'].microsecond == 123000\n+ data, _ = s.load({'a': dt.datetime(2016, 8, 6, 12, 59, 59, 999876)})\n+ assert data['a'].hour == 13\n+ assert data['a'].minute == 0\n+ assert data['a'].second == 0\n+ assert data['a'].microsecond == 0\n \n def test_date(self):\n \n", "FAIL_TO_PASS": ["tests/test_fields.py::TestFields::test_strictdatetime"]}], "all_FAIL_TO_PASS": ["tests/test_fields.py::TestFields::test_datetime", "tests/test_fields.py::TestFields::test_strictdatetime"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getsentry__responses-558_x2", "level": 2, "source": "swerebench", "repo": "getsentry/responses", "image": "swerebench/sweb.eval.x86_64.getsentry_1776_responses-558:latest", "base_commit": "3d83a88382bf5cedefbbab3986bbfeeb07883fac", "num_bugs": 2, "bugs": [{"instance_id": "getsentry__responses-558", "base_commit": "3d83a88382bf5cedefbbab3986bbfeeb07883fac", "gold_patch": "diff --git a/CHANGES b/CHANGES\nindex fbf8ddb..bcd26b5 100644\n--- a/CHANGES\n+++ b/CHANGES\n@@ -1,3 +1,8 @@\n+0.22.0\n+------\n+\n+* Add `passthrough` argument to `BaseResponse` object. See #557\n+\n 0.21.0\n ------\n \ndiff --git a/README.rst b/README.rst\nindex cd06dba..357bd76 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -1172,14 +1172,18 @@ need to allow an entire domain or path subtree to send requests:\n responses.add_passthru(re.compile(\"https://percy.io/\\\\w+\"))\n \n \n-Lastly, you can use the ``response.passthrough`` attribute on ``BaseResponse`` or\n-use ``PassthroughResponse`` to enable a response to behave as a pass through.\n+Lastly, you can use the ``passthrough`` argument of the ``Response`` object\n+to force a response to behave as a pass through.\n \n .. code-block:: python\n \n # Enable passthrough for a single response\n- response = Response(responses.GET, \"http://example.com\", body=\"not used\")\n- response.passthrough = True\n+ response = Response(\n+ responses.GET,\n+ \"http://example.com\",\n+ body=\"not used\",\n+ passthrough=True,\n+ )\n responses.add(response)\n \n # Use PassthroughResponse\ndiff --git a/responses/__init__.py b/responses/__init__.py\nindex 9ab2570..30b9597 100644\n--- a/responses/__init__.py\n+++ b/responses/__init__.py\n@@ -354,6 +354,8 @@ class BaseResponse(object):\n url: _URLPatternType,\n match_querystring: Union[bool, object] = None,\n match: \"_MatcherIterable\" = (),\n+ *,\n+ passthrough: bool = False,\n ) -> None:\n self.method: str = method\n # ensure the url has a default path set if the url is a string\n@@ -366,6 +368,7 @@ class BaseResponse(object):\n \n self.match: \"_MatcherIterable\" = match\n self.call_count: int = 0\n+ self.passthrough = passthrough\n \n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, BaseResponse):\n@@ -596,7 +599,8 @@ class CallbackResponse(BaseResponse):\n \n \n class PassthroughResponse(BaseResponse):\n- passthrough: bool = True\n+ def __init__(self, *args: Any, **kwargs: Any):\n+ super().__init__(*args, passthrough=True, **kwargs)\n \n \n class OriginalResponseShim(object):\n", "test_patch": "diff --git a/responses/tests/test_responses.py b/responses/tests/test_responses.py\nindex 4dd93f0..083fced 100644\n--- a/responses/tests/test_responses.py\n+++ b/responses/tests/test_responses.py\n@@ -1589,6 +1589,31 @@ def test_passthrough_flag(httpserver):\n assert_reset()\n \n \n+def test_passthrough_kwarg(httpserver):\n+ httpserver.serve_content(\"OK\", headers={\"Content-Type\": \"text/plain\"})\n+\n+ def configure_response(passthrough):\n+ responses.get(httpserver.url, body=\"MOCK\", passthrough=passthrough)\n+\n+ @responses.activate\n+ def run_passthrough():\n+ configure_response(passthrough=True)\n+ resp = requests.get(httpserver.url)\n+ assert_response(resp, \"OK\")\n+\n+ @responses.activate\n+ def run_mocked():\n+ configure_response(passthrough=False)\n+ resp = requests.get(httpserver.url)\n+ assert_response(resp, \"MOCK\")\n+\n+ run_mocked()\n+ assert_reset()\n+\n+ run_passthrough()\n+ assert_reset()\n+\n+\n def test_passthrough_response(httpserver):\n httpserver.serve_content(\"OK\", headers={\"Content-Type\": \"text/plain\"})\n \n", "FAIL_TO_PASS": ["responses/tests/test_responses.py::test_passthrough_kwarg"]}, {"instance_id": "getsentry__responses-564", "base_commit": "b12933515a59e07652039b0481ec4cf278a58727", "gold_patch": "diff --git a/CHANGES b/CHANGES\nindex bcd26b5..d088093 100644\n--- a/CHANGES\n+++ b/CHANGES\n@@ -2,6 +2,7 @@\n ------\n \n * Add `passthrough` argument to `BaseResponse` object. See #557\n+* Fix `registries` leak. See #563\n \n 0.21.0\n ------\ndiff --git a/responses/__init__.py b/responses/__init__.py\nindex 30b9597..1a6bd2e 100644\n--- a/responses/__init__.py\n+++ b/responses/__init__.py\n@@ -181,9 +181,6 @@ def get_wrapped(\n Wrapped function\n \n \"\"\"\n- if registry is not None:\n- responses._set_registry(registry)\n-\n assert_mock = std_mock.patch.object(\n target=responses,\n attribute=\"assert_all_requests_are_fired\",\n@@ -195,6 +192,9 @@ def get_wrapped(\n @wraps(func)\n async def wrapper(*args: Any, **kwargs: Any) -> Any: # type: ignore[misc]\n \n+ if registry is not None:\n+ responses._set_registry(registry)\n+\n with assert_mock, responses:\n return await func(*args, **kwargs)\n \n@@ -203,6 +203,9 @@ def get_wrapped(\n @wraps(func)\n def wrapper(*args: Any, **kwargs: Any) -> Any: # type: ignore[misc]\n \n+ if registry is not None:\n+ responses._set_registry(registry)\n+\n with assert_mock, responses:\n # set 'assert_all_requests_are_fired' temporarily for a single run.\n # Mock automatically unsets to avoid leakage to another decorated\n", "test_patch": "diff --git a/responses/tests/test_registries.py b/responses/tests/test_registries.py\nindex 4dd5765..2ab035b 100644\n--- a/responses/tests/test_registries.py\n+++ b/responses/tests/test_registries.py\n@@ -43,6 +43,44 @@ def test_set_registry():\n assert_reset()\n \n \n+def test_set_registry_reversed():\n+ \"\"\"See https://github.com/getsentry/responses/issues/563\"\"\"\n+\n+ class CustomRegistry(registries.FirstMatchRegistry):\n+ pass\n+\n+ @responses.activate\n+ def run():\n+ # test that registry does not leak to another test\n+ assert type(responses.mock.get_registry()) == registries.FirstMatchRegistry\n+\n+ @responses.activate(registry=CustomRegistry)\n+ def run_with_registry():\n+ assert type(responses.mock.get_registry()) == CustomRegistry\n+\n+ run()\n+ run_with_registry()\n+ assert_reset()\n+\n+\n+async def test_registry_async():\n+ class CustomRegistry(registries.FirstMatchRegistry):\n+ pass\n+\n+ @responses.activate\n+ async def run():\n+ # test that registry does not leak to another test\n+ assert type(responses.mock.get_registry()) == registries.FirstMatchRegistry\n+\n+ @responses.activate(registry=CustomRegistry)\n+ async def run_with_registry():\n+ assert type(responses.mock.get_registry()) == CustomRegistry\n+\n+ await run()\n+ await run_with_registry()\n+ assert_reset()\n+\n+\n def test_set_registry_context_manager():\n def run():\n class CustomRegistry(registries.FirstMatchRegistry):\n", "FAIL_TO_PASS": ["responses/tests/test_registries.py::test_set_registry_reversed"]}], "all_FAIL_TO_PASS": ["responses/tests/test_responses.py::test_passthrough_kwarg", "responses/tests/test_registries.py::test_set_registry_reversed"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "awdeorio__mailmerge-95_x2", "level": 2, "source": "swerebench", "repo": "awdeorio/mailmerge", "image": "swerebench/sweb.eval.x86_64.awdeorio_1776_mailmerge-95:latest", "base_commit": "a95c4951e91edac5c7bfa5e19f2389c7e4657d47", "num_bugs": 2, "bugs": [{"instance_id": "awdeorio__mailmerge-95", "base_commit": "a95c4951e91edac5c7bfa5e19f2389c7e4657d47", "gold_patch": "diff --git a/mailmerge/template_message.py b/mailmerge/template_message.py\nindex c90c505..135bba8 100644\n--- a/mailmerge/template_message.py\n+++ b/mailmerge/template_message.py\n@@ -102,8 +102,13 @@ class TemplateMessage(object):\n # Create empty multipart message\n multipart_message = email.mime.multipart.MIMEMultipart('alternative')\n \n- # Copy headers, preserving duplicate headers\n+ # Copy headers. Avoid duplicate Content-Type and MIME-Version headers,\n+ # which we set explicitely. MIME-Version was set when we created an\n+ # empty mulitpart message. Content-Type will be set when we copy the\n+ # original text later.\n for header_key in set(self._message.keys()):\n+ if header_key.lower() in [\"content-type\", \"mime-version\"]:\n+ continue\n values = self._message.get_all(header_key, failobj=[])\n for value in values:\n multipart_message[header_key] = value\n", "test_patch": "diff --git a/tests/test_template_message.py b/tests/test_template_message.py\nindex 18e0d5d..346975f 100644\n--- a/tests/test_template_message.py\n+++ b/tests/test_template_message.py\n@@ -624,3 +624,56 @@ def test_attachment_empty(tmp_path):\n template_message = TemplateMessage(template_path)\n with pytest.raises(MailmergeError):\n template_message.render({})\n+\n+\n+def test_duplicate_headers_attachment(tmp_path):\n+ \"\"\"Verify multipart messages do not contain duplicate headers.\n+\n+ Duplicate headers are rejected by some SMTP servers.\n+ \"\"\"\n+ # Simple attachment\n+ attachment_path = Path(tmp_path/\"attachment.txt\")\n+ attachment_path.write_text(u\"Hello world\\n\")\n+\n+ # Simple message\n+ template_path = tmp_path / \"template.txt\"\n+ template_path.write_text(textwrap.dedent(u\"\"\"\\\n+ TO: to@test.com\n+ SUBJECT: Testing mailmerge\n+ FROM: from@test.com>\n+ ATTACHMENT: attachment.txt\n+\n+ {{message}}\n+ \"\"\"))\n+ template_message = TemplateMessage(template_path)\n+ _, _, message = template_message.render({\n+ \"message\": \"Hello world\"\n+ })\n+\n+ # Verifty no duplicate headers\n+ assert len(message.keys()) == len(set(message.keys()))\n+\n+\n+def test_duplicate_headers_markdown(tmp_path):\n+ \"\"\"Verify multipart messages do not contain duplicate headers.\n+\n+ Duplicate headers are rejected by some SMTP servers.\n+ \"\"\"\n+ template_path = tmp_path / \"template.txt\"\n+ template_path.write_text(textwrap.dedent(u\"\"\"\\\n+ TO: to@test.com\n+ SUBJECT: Testing mailmerge\n+ FROM: from@test.com\n+ CONTENT-TYPE: text/markdown\n+\n+ ```\n+ Message as code block: {{message}}\n+ ```\n+ \"\"\"))\n+ template_message = TemplateMessage(template_path)\n+ _, _, message = template_message.render({\n+ \"message\": \"hello world\",\n+ })\n+\n+ # Verifty no duplicate headers\n+ assert len(message.keys()) == len(set(message.keys()))\n", "FAIL_TO_PASS": ["tests/test_template_message.py::test_duplicate_headers_attachment", "tests/test_template_message.py::test_duplicate_headers_markdown"]}, {"instance_id": "awdeorio__mailmerge-101", "base_commit": "d08667a8f2a7a9e7ad64e58c2bc049a80726bf3c", "gold_patch": "diff --git a/mailmerge/template_message.py b/mailmerge/template_message.py\nindex 135bba8..9a12fc4 100644\n--- a/mailmerge/template_message.py\n+++ b/mailmerge/template_message.py\n@@ -115,9 +115,11 @@ class TemplateMessage(object):\n \n # Copy text, preserving original encoding\n original_text = self._message.get_payload(decode=True)\n+ original_subtype = self._message.get_content_subtype()\n original_encoding = str(self._message.get_charset())\n multipart_message.attach(email.mime.text.MIMEText(\n original_text,\n+ _subtype=original_subtype,\n _charset=original_encoding,\n ))\n \n", "test_patch": "diff --git a/tests/test_template_message.py b/tests/test_template_message.py\nindex 346975f..621a2bd 100644\n--- a/tests/test_template_message.py\n+++ b/tests/test_template_message.py\n@@ -611,7 +611,7 @@ def test_attachment_multiple(tmp_path):\n \n \n def test_attachment_empty(tmp_path):\n- \"\"\"Errr on empty attachment field.\"\"\"\n+ \"\"\"Err on empty attachment field.\"\"\"\n template_path = tmp_path / \"template.txt\"\n template_path.write_text(textwrap.dedent(u\"\"\"\\\n TO: to@test.com\n@@ -626,6 +626,75 @@ def test_attachment_empty(tmp_path):\n template_message.render({})\n \n \n+def test_contenttype_attachment_html_body(tmpdir):\n+ \"\"\"\n+ Verify that the content-type of the message is correctly retained with an\n+ HTML body.\n+ \"\"\"\n+ # Simple attachment\n+ attachment_path = Path(tmpdir/\"attachment.txt\")\n+ attachment_path.write_text(u\"Hello world\\n\")\n+\n+ # HTML template\n+ template_path = Path(tmpdir/\"template.txt\")\n+ template_path.write_text(textwrap.dedent(u\"\"\"\\\n+ TO: to@test.com\n+ FROM: from@test.com\n+ ATTACHMENT: attachment.txt\n+ CONTENT-TYPE: text/html\n+\n+ Hello world\n+ \"\"\"))\n+\n+ # Render in tmpdir\n+ with tmpdir.as_cwd():\n+ template_message = TemplateMessage(template_path)\n+ _, _, message = template_message.render({})\n+\n+ # Verify that the message content type is HTML\n+ payload = message.get_payload()\n+ assert len(payload) == 2\n+ assert payload[0].get_content_type() == 'text/html'\n+\n+\n+def test_contenttype_attachment_markdown_body(tmpdir):\n+ \"\"\"\n+ Verify that the content-types of the MarkDown message are correct when\n+ attachments are included.\n+ \"\"\"\n+ # Simple attachment\n+ attachment_path = Path(tmpdir/\"attachment.txt\")\n+ attachment_path.write_text(u\"Hello world\\n\")\n+\n+ # HTML template\n+ template_path = Path(tmpdir/\"template.txt\")\n+ template_path.write_text(textwrap.dedent(u\"\"\"\\\n+ TO: to@test.com\n+ FROM: from@test.com\n+ ATTACHMENT: attachment.txt\n+ CONTENT-TYPE: text/markdown\n+\n+ Hello **world**\n+ \"\"\"))\n+\n+ # Render in tmpdir\n+ with tmpdir.as_cwd():\n+ template_message = TemplateMessage(template_path)\n+ _, _, message = template_message.render({})\n+\n+ # Markdown: Make sure there is a plaintext part and an HTML part\n+ payload = message.get_payload()\n+ assert len(payload) == 3\n+\n+ # Ensure that the first part is plaintext and the second part\n+ # is HTML (as per RFC 2046)\n+ plaintext_part = payload[0]\n+ assert plaintext_part['Content-Type'].startswith(\"text/plain\")\n+\n+ html_part = payload[1]\n+ assert html_part['Content-Type'].startswith(\"text/html\")\n+\n+\n def test_duplicate_headers_attachment(tmp_path):\n \"\"\"Verify multipart messages do not contain duplicate headers.\n \n", "FAIL_TO_PASS": ["tests/test_template_message.py::test_contenttype_attachment_html_body"]}], "all_FAIL_TO_PASS": ["tests/test_template_message.py::test_duplicate_headers_attachment", "tests/test_template_message.py::test_duplicate_headers_markdown", "tests/test_template_message.py::test_contenttype_attachment_html_body"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cta-observatory__lstmcpipe-398_x2", "level": 2, "source": "swerebench", "repo": "cta-observatory/lstmcpipe", "image": "swerebench/sweb.eval.x86_64.cta-observatory_1776_lstmcpipe-398:latest", "base_commit": "825c042148c211e0581d5ae4068b6d3d296debb3", "num_bugs": 2, "bugs": [{"instance_id": "cta-observatory__lstmcpipe-398", "base_commit": "825c042148c211e0581d5ae4068b6d3d296debb3", "gold_patch": "diff --git a/lstmcpipe/utils.py b/lstmcpipe/utils.py\nindex a122672..6ab3063 100644\n--- a/lstmcpipe/utils.py\n+++ b/lstmcpipe/utils.py\n@@ -256,6 +256,11 @@ class SbatchLstMCStage:\n def compose_wrap_command(self, wrap_command=None, source_env=\"\", backend=\"\"):\n if wrap_command is None or wrap_command == \"\":\n warnings.warn(\"You must pass a command to be batched! \")\n+ else:\n+ # Remove trailing semicolon and any extra spaces\n+ wrap_command = wrap_command.rstrip(\";\").strip()\n+ # exit if any command fails\n+ wrap_command = wrap_command + ' || exit ' + r'\\$?'\n if source_env != \"\" and not source_env.strip().endswith(\";\"):\n source_env = f\"{source_env.strip()}; \"\n if backend != \"\" and not backend.strip().endswith(\";\"):\n", "test_patch": "diff --git a/lstmcpipe/tests/test_utils.py b/lstmcpipe/tests/test_utils.py\nindex 4be15ab..7957757 100644\n--- a/lstmcpipe/tests/test_utils.py\n+++ b/lstmcpipe/tests/test_utils.py\n@@ -6,10 +6,10 @@ from ruamel.yaml import YAML\n from lstmcpipe.utils import rerun_cmd, dump_lstchain_std_config, SbatchLstMCStage, run_command\n \n \n-def test_save_log_to_file():\n+def test_save_log_to_file(tmp_path):\n from ..utils import save_log_to_file\n \n- outfile_yml = Path('dummy_log.yml')\n+ outfile_yml = Path(tmp_path, 'dummy_log.yml')\n \n dummy_log = {'dummy_jobid': 'sbatch --parsable --wrap=\"sleep 10\"'}\n save_log_to_file(dummy_log, outfile_yml)\n@@ -74,14 +74,14 @@ def test_sbatch_lst_mc_stage():\n sbatch = SbatchLstMCStage(stage=\"r0_to_dl1\", wrap_command=\"command to be batched\")\n assert (\n sbatch.slurm_command == 'sbatch --parsable --partition=long --job-name=r0_dl1 --array=0-0%100 '\n- '--error=./slurm-%j.e --output=./slurm-%j.o --wrap=\"command to be batched\"'\n+ '--error=./slurm-%j.e --output=./slurm-%j.o --wrap=\"command to be batched' + ' || exit ' + r'\\$?\"'\n )\n \n sbatch.extra_slurm_options = {'account': 'lstrta', 'partition': 'xxl', 'mem': '160G', 'cpus-per-task': 32}\n assert (\n sbatch.slurm_command == 'sbatch --parsable --partition=xxl --job-name=r0_dl1 --array=0-0%100 '\n- '--error=./slurm-%j.e --output=./slurm-%j.o --account=lstrta --mem=160G '\n- '--cpus-per-task=32 --wrap=\"command to be batched\"'\n+ '--error=./slurm-%j.e --output=./slurm-%j.o --account=lstrta --mem=160G '\n+ '--cpus-per-task=32 --wrap=\"command to be batched' + ' || exit ' + r'\\$?\"'\n )\n \n sbatch.extra_slurm_options = None\n@@ -93,7 +93,10 @@ def test_sbatch_lst_mc_stage():\n source_env=\"source .bashrc_file; conda activate \",\n backend=\" export MPLBACKEND=Agg \",\n )\n- assert sbatch.wrap_cmd == '--wrap=\"export MPLBACKEND=Agg; source .bashrc_file; conda activate; python args\"'\n+ assert (\n+ sbatch.wrap_cmd\n+ == '--wrap=\"export MPLBACKEND=Agg; source .bashrc_file; conda activate; python args' + ' || exit ' + r'\\$?\"'\n+ )\n \n with pytest.raises(ValueError):\n sbatch.submit() # slurm not installed\n", "FAIL_TO_PASS": ["lstmcpipe/tests/test_utils.py::test_sbatch_lst_mc_stage"]}, {"instance_id": "cta-observatory__lstmcpipe-399", "base_commit": "c2340d1a4d046d327ddabd8c287afdee6edc7ec2", "gold_patch": "diff --git a/lstmcpipe/utils.py b/lstmcpipe/utils.py\nindex 6ab3063..723c7ea 100644\n--- a/lstmcpipe/utils.py\n+++ b/lstmcpipe/utils.py\n@@ -285,7 +285,7 @@ class SbatchLstMCStage:\n if slurm_deps is None or slurm_deps == \"\":\n return \"\"\n elif all(items != \"\" for items in slurm_deps.split(\",\")):\n- return f\"--dependency={dependency_type}:{slurm_deps}\"\n+ return f\"--dependency={dependency_type}:{slurm_deps.replace(',',':')}\"\n else:\n raise ValueError(\"Slurm dependencies contain an empty value between commas, i.e.; ,'', \")\n \n", "test_patch": "diff --git a/lstmcpipe/tests/test_utils.py b/lstmcpipe/tests/test_utils.py\nindex 7957757..505671e 100644\n--- a/lstmcpipe/tests/test_utils.py\n+++ b/lstmcpipe/tests/test_utils.py\n@@ -86,7 +86,7 @@ def test_sbatch_lst_mc_stage():\n \n sbatch.extra_slurm_options = None\n sbatch.slurm_dependencies = \"123,243,345,456\"\n- assert sbatch._construct_slurm_dependencies() == \"--dependency=afterok:123,243,345,456\"\n+ assert sbatch._construct_slurm_dependencies() == \"--dependency=afterok:123:243:345:456\"\n \n sbatch.compose_wrap_command(\n wrap_command=\"python args\",\n", "FAIL_TO_PASS": ["lstmcpipe/tests/test_utils.py::test_sbatch_lst_mc_stage"]}], "all_FAIL_TO_PASS": ["lstmcpipe/tests/test_utils.py::test_sbatch_lst_mc_stage", "lstmcpipe/tests/test_utils.py::test_sbatch_lst_mc_stage"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "devopshq__artifactory-53_x2", "level": 2, "source": "swerebench", "repo": "devopshq/artifactory", "image": "swerebench/sweb.eval.x86_64.devopshq_1776_artifactory-53:latest", "base_commit": "b63e93ff509fd1d4ba619d7db2d3abab02624e32", "num_bugs": 2, "bugs": [{"instance_id": "devopshq__artifactory-53", "base_commit": "b63e93ff509fd1d4ba619d7db2d3abab02624e32", "gold_patch": "diff --git a/artifactory.py b/artifactory.py\nindex 48547ec..3b14d4f 100755\n--- a/artifactory.py\n+++ b/artifactory.py\n@@ -344,6 +344,10 @@ class _ArtifactoryFlavour(pathlib._Flavour):\n before it, including '/artifactory/' itself is treated as drive.\n The next folder is treated as root, and everything else is taken\n for relative path.\n+\n+ If '/artifactory/' is not in the URI. Everything before the path\n+ component is treated as drive. The first folder of the path is\n+ treated as root, and everything else is taken for relative path.\n \"\"\"\n drv = ''\n root = ''\n@@ -353,8 +357,20 @@ class _ArtifactoryFlavour(pathlib._Flavour):\n mark = without_http_prefix(base).rstrip(sep) + sep\n parts = part.split(mark)\n else:\n- mark = sep + 'artifactory' + sep\n- parts = part.split(mark)\n+ url = urllib3.util.parse_url(part)\n+ if url.path is None or url.path == sep:\n+ if url.scheme:\n+ return part.rstrip(sep), '', ''\n+ return '', '', part\n+ elif 'artifactory' in url.path:\n+ mark = sep + 'artifactory' + sep\n+ parts = part.split(mark)\n+ else:\n+ drv = part.split(url.path)[0]\n+ path_parts = url.path.strip(sep).split(sep)\n+ root = sep + path_parts[0] + sep\n+ rest = sep.join(path_parts[1:])\n+ return drv, root, rest\n \n if len(parts) >= 2:\n drv = parts[0] + mark.rstrip(sep)\n", "test_patch": "diff --git a/tests/unit/test_artifactory_path.py b/tests/unit/test_artifactory_path.py\nindex 4405b3b..0460d7f 100644\n--- a/tests/unit/test_artifactory_path.py\n+++ b/tests/unit/test_artifactory_path.py\n@@ -89,6 +89,37 @@ class ArtifactoryFlavorTest(unittest.TestCase):\n check(\"https://artifactory.a.b.c.d/artifactory/foo/bar\",\n ('https://artifactory.a.b.c.d/artifactory', '/foo/', 'bar'))\n \n+ def test_splitroot_custom_drv(self):\n+ \"\"\"\n+ https://github.com/devopshq/artifactory/issues/31\n+ \"\"\"\n+ check = self._check_splitroot\n+\n+ check(\"https://artifactory.example.com\",\n+ ('https://artifactory.example.com', '', ''))\n+ check(\"https://artifactory.example.com/\",\n+ ('https://artifactory.example.com', '', ''))\n+ check(\"https://artifactory.example.com/root\",\n+ ('https://artifactory.example.com', '/root/', ''))\n+ check(\"https://artifactory.example.com/root/\",\n+ ('https://artifactory.example.com', '/root/', ''))\n+ check(\"https://artifactory.example.com/root/parts\",\n+ ('https://artifactory.example.com', '/root/', 'parts'))\n+ check(\"https://artifactory.example.com/root/parts/\",\n+ ('https://artifactory.example.com', '/root/', 'parts'))\n+ check(\"https://artifacts.example.com\",\n+ ('https://artifacts.example.com', '', ''))\n+ check(\"https://artifacts.example.com/\",\n+ ('https://artifacts.example.com', '', ''))\n+ check(\"https://artifacts.example.com/root\",\n+ ('https://artifacts.example.com', '/root/', ''))\n+ check(\"https://artifacts.example.com/root/\",\n+ ('https://artifacts.example.com', '/root/', ''))\n+ check(\"https://artifacts.example.com/root/parts\",\n+ ('https://artifacts.example.com', '/root/', 'parts'))\n+ check(\"https://artifacts.example.com/root/parts/\",\n+ ('https://artifacts.example.com', '/root/', 'parts'))\n+\n def test_splitroot_custom_root(self):\n check = self._check_splitroot\n \n", "FAIL_TO_PASS": ["tests/unit/test_artifactory_path.py::ArtifactoryFlavorTest::test_splitroot_custom_drv"]}, {"instance_id": "devopshq__artifactory-60", "base_commit": "9813bc6d86e7ede9dc395dbfeaf7f5e02030f29c", "gold_patch": "diff --git a/artifactory.py b/artifactory.py\nindex 3b14d4f..079b7c4 100755\n--- a/artifactory.py\n+++ b/artifactory.py\n@@ -358,11 +358,16 @@ class _ArtifactoryFlavour(pathlib._Flavour):\n parts = part.split(mark)\n else:\n url = urllib3.util.parse_url(part)\n+\n+ if (without_http_prefix(part).strip(\"/\") == part.strip(\"/\") and\n+ url.path and not url.path.strip(\"/\").startswith(\"artifactory\")):\n+ return '', '', part\n+\n if url.path is None or url.path == sep:\n if url.scheme:\n return part.rstrip(sep), '', ''\n return '', '', part\n- elif 'artifactory' in url.path:\n+ elif url.path.lstrip(\"/\").startswith(\"artifactory\"):\n mark = sep + 'artifactory' + sep\n parts = part.split(mark)\n else:\n", "test_patch": "diff --git a/tests/unit/test_artifactory_path.py b/tests/unit/test_artifactory_path.py\nindex 0460d7f..8fd13d9 100644\n--- a/tests/unit/test_artifactory_path.py\n+++ b/tests/unit/test_artifactory_path.py\n@@ -88,6 +88,9 @@ class ArtifactoryFlavorTest(unittest.TestCase):\n ('http://artifactory.local/artifactory', '/foo/', 'bar'))\n check(\"https://artifactory.a.b.c.d/artifactory/foo/bar\",\n ('https://artifactory.a.b.c.d/artifactory', '/foo/', 'bar'))\n+ check(\"https://artifactory.a.b.c.d/artifactory/foo/artifactory/bar\",\n+ ('https://artifactory.a.b.c.d/artifactory', '/foo/',\n+ 'artifactory/bar'))\n \n def test_splitroot_custom_drv(self):\n \"\"\"\n@@ -119,6 +122,8 @@ class ArtifactoryFlavorTest(unittest.TestCase):\n ('https://artifacts.example.com', '/root/', 'parts'))\n check(\"https://artifacts.example.com/root/parts/\",\n ('https://artifacts.example.com', '/root/', 'parts'))\n+ check(\"https://artifacts.example.com/root/artifactory/parts/\",\n+ ('https://artifacts.example.com', '/root/', 'artifactory/parts'))\n \n def test_splitroot_custom_root(self):\n check = self._check_splitroot\n@@ -137,6 +142,8 @@ class ArtifactoryFlavorTest(unittest.TestCase):\n ('http://custom/root', '/foo/', 'bar'))\n check(\"https://custom/root/foo/baz\",\n ('https://custom/root', '/foo/', 'baz'))\n+ check(\"https://custom/root/foo/with/artifactory/folder/baz\",\n+ ('https://custom/root', '/foo/', 'with/artifactory/folder/baz'))\n \n def test_parse_parts(self):\n check = self._check_parse_parts\n@@ -160,6 +167,11 @@ class ArtifactoryFlavorTest(unittest.TestCase):\n ('http://example.com/artifactory', '/foo/',\n ['http://example.com/artifactory/foo/', 'bar', 'artifactory']))\n \n+ check(['http://example.com/artifactory/foo/bar/artifactory/fi'],\n+ ('http://example.com/artifactory', '/foo/',\n+ ['http://example.com/artifactory/foo/', 'bar', 'artifactory',\n+ 'fi']))\n+\n \n class PureArtifactoryPathTest(unittest.TestCase):\n cls = artifactory.PureArtifactoryPath\n@@ -225,6 +237,23 @@ class PureArtifactoryPathTest(unittest.TestCase):\n c = b / \"path.txt\"\n self.assertEqual(str(c), \"http://b/artifactory/reponame/f/path.txt\")\n \n+ def test_join_with_artifactory_folder(self):\n+ P = self.cls\n+\n+ b = P(\"http://b/artifactory/reponame/path/with/artifactory/folder\")\n+ c = b / \"path.txt\"\n+ self.assertEqual(str(c), \"http://b/artifactory/reponame/path/with/artifactory/folder/path.txt\")\n+\n+ def test_join_with_multiple_folder_and_artifactory_substr_in_it(self):\n+ \"\"\"\n+ https://github.com/devopshq/artifactory/issues/58\n+ \"\"\"\n+ P = self.cls\n+\n+ b = P(\"http://b/artifactory/reponame\")\n+ c = b / \"path/with/multiple/subdir/and/artifactory/path.txt\"\n+ self.assertEqual(str(c), \"http://b/artifactory/reponame/path/with/multiple/subdir/and/artifactory/path.txt\")\n+\n \n class ArtifactoryAccessorTest(unittest.TestCase):\n \"\"\" Test the real artifactory integration \"\"\"\n", "FAIL_TO_PASS": ["tests/unit/test_artifactory_path.py::ArtifactoryFlavorTest::test_splitroot_custom_drv", "tests/unit/test_artifactory_path.py::PureArtifactoryPathTest::test_join_with_multiple_folder_and_artifactory_substr_in_it"]}], "all_FAIL_TO_PASS": ["tests/unit/test_artifactory_path.py::ArtifactoryFlavorTest::test_splitroot_custom_drv", "tests/unit/test_artifactory_path.py::ArtifactoryFlavorTest::test_splitroot_custom_drv", "tests/unit/test_artifactory_path.py::PureArtifactoryPathTest::test_join_with_multiple_folder_and_artifactory_substr_in_it"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "astanin__python-tabulate-96_x2", "level": 2, "source": "swerebench", "repo": "astanin/python-tabulate", "image": "swerebench/sweb.eval.x86_64.astanin_1776_python-tabulate-96:latest", "base_commit": "2552e6dfb23cac990aeabb27b86745878d62247e", "num_bugs": 2, "bugs": [{"instance_id": "astanin__python-tabulate-96", "base_commit": "2552e6dfb23cac990aeabb27b86745878d62247e", "gold_patch": "diff --git a/tabulate.py b/tabulate.py\nindex 5d57167..d611dc1 100755\n--- a/tabulate.py\n+++ b/tabulate.py\n@@ -1022,7 +1022,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex=\"default\"):\n elif hasattr(tabular_data, \"index\"):\n # values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0)\n keys = list(tabular_data)\n- if tabular_data.index.name is not None:\n+ if showindex in [\"default\", \"always\", True] and tabular_data.index.name is not None:\n if isinstance(tabular_data.index.name, list):\n keys[:0] = tabular_data.index.name\n else:\n", "test_patch": "diff --git a/test/test_output.py b/test/test_output.py\nindex 0e72c71..061d302 100644\n--- a/test/test_output.py\n+++ b/test/test_output.py\n@@ -1363,7 +1363,8 @@ def test_pandas_without_index():\n import pandas\n \n df = pandas.DataFrame(\n- [[\"one\", 1], [\"two\", None]], columns=[\"string\", \"number\"], index=[\"a\", \"b\"]\n+ [[\"one\", 1], [\"two\", None]], columns=[\"string\", \"number\"],\n+ index=pandas.Index([\"a\", \"b\"], name=\"index\")\n )\n expected = \"\\n\".join(\n [\n", "FAIL_TO_PASS": ["test/test_output.py::test_pandas_without_index"]}, {"instance_id": "astanin__python-tabulate-139", "base_commit": "b2c26bcb70e497f674b38aa7e29de12c0123708a", "gold_patch": "diff --git a/tabulate.py b/tabulate.py\nindex 0579fb3..0a23f3c 100644\n--- a/tabulate.py\n+++ b/tabulate.py\n@@ -1189,6 +1189,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex=\"default\"):\n headers = rows[0]\n headers = list(map(_text_type, headers)) # headers should be strings\n rows = rows[1:]\n+ elif headers == \"firstrow\":\n+ headers = []\n \n headers = list(map(_text_type, headers))\n rows = list(map(list, rows))\n", "test_patch": "diff --git a/test/test_output.py b/test/test_output.py\nindex eed4489..b751e5e 100644\n--- a/test/test_output.py\n+++ b/test/test_output.py\n@@ -1412,6 +1412,13 @@ def test_empty_data_without_headers():\n assert_equal(expected, result)\n \n \n+def test_empty_data_with_headers():\n+ \"Output: table with empty data and headers as firstrow\"\n+ expected = \"\"\n+ result = tabulate([], headers=\"firstrow\")\n+ assert_equal(expected, result)\n+\n+\n def test_floatfmt():\n \"Output: floating point format\"\n result = tabulate([[\"1.23456789\"], [1.0]], floatfmt=\".3f\", tablefmt=\"plain\")\n", "FAIL_TO_PASS": ["test/test_output.py::test_empty_data_with_headers"]}], "all_FAIL_TO_PASS": ["test/test_output.py::test_pandas_without_index", "test/test_output.py::test_empty_data_with_headers"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Duke-GCB__bespin-cli-15_x2", "level": 2, "source": "swerebench", "repo": "Duke-GCB/bespin-cli", "image": "swerebench/sweb.eval.x86_64.duke-gcb_1776_bespin-cli-15:latest", "base_commit": "70450d7b00c477580d6851b8aaa65433a54cf415", "num_bugs": 2, "bugs": [{"instance_id": "Duke-GCB__bespin-cli-15", "base_commit": "70450d7b00c477580d6851b8aaa65433a54cf415", "gold_patch": "diff --git a/bespin/argparser.py b/bespin/argparser.py\nindex 5fc8fa3..f97d735 100644\n--- a/bespin/argparser.py\n+++ b/bespin/argparser.py\n@@ -40,6 +40,8 @@ class ArgParser(object):\n jobs_subparser = jobs_parser.add_subparsers()\n \n list_jobs_parser = jobs_subparser.add_parser('list', description='list workflows')\n+ list_jobs_parser.add_argument('-a', '--all', action='store_true',\n+ help='show all workflow versions instead of just the most recent.')\n list_jobs_parser.set_defaults(func=self._run_list_workflows)\n \n def _create_job_parser(self, subparsers):\n@@ -79,8 +81,8 @@ class ArgParser(object):\n def _run_list_jobs(self, _):\n self.target_object.jobs_list()\n \n- def _run_list_workflows(self, _):\n- self.target_object.workflows_list()\n+ def _run_list_workflows(self, args):\n+ self.target_object.workflows_list(all_versions=args.all)\n \n def _run_init_job(self, args):\n self.target_object.init_job(args.tag, args.outfile)\ndiff --git a/bespin/commands.py b/bespin/commands.py\nindex 8f7271d..c8c1fb6 100644\n--- a/bespin/commands.py\n+++ b/bespin/commands.py\n@@ -44,6 +44,7 @@ USER_PLACEHOLDER_DICT = {\n }\n }\n \n+\n class Commands(object):\n \"\"\"\n Commands run based on command line input.\n@@ -61,12 +62,13 @@ class Commands(object):\n config = ConfigFile().read_or_create_config()\n return BespinApi(config, user_agent_str=self.user_agent_str)\n \n- def workflows_list(self):\n+ def workflows_list(self, all_versions):\n \"\"\"\n Print out a table of workflows/questionnaires\n+ :param all_versions: bool: when true show all versions otherwise show most recent\n \"\"\"\n api = self._create_api()\n- workflow_data = WorkflowDetails(api)\n+ workflow_data = WorkflowDetails(api, all_versions)\n print(Table(workflow_data.column_names, workflow_data.get_column_data()))\n \n def jobs_list(self):\n@@ -167,10 +169,11 @@ class WorkflowDetails(object):\n \"\"\"\n Creates column data based on workflows/questionnaires\n \"\"\"\n- TAG_COLUMN_NAME = \"latest version tag\"\n+ TAG_COLUMN_NAME = \"version tag\"\n \n- def __init__(self, api):\n+ def __init__(self, api, all_versions):\n self.api = api\n+ self.all_versions = all_versions\n self.column_names = [\"id\", \"name\", self.TAG_COLUMN_NAME]\n \n def get_column_data(self):\n@@ -181,10 +184,13 @@ class WorkflowDetails(object):\n data = []\n for workflow in self.api.workflows_list():\n if len(workflow['versions']):\n- latest_version = workflow['versions'][-1]\n- for questionnaire in self.api.questionnaires_list(workflow_version=latest_version):\n- workflow[self.TAG_COLUMN_NAME] = questionnaire['tag']\n- data.append(workflow)\n+ versions = workflow['versions']\n+ if not self.all_versions:\n+ versions = versions[-1:]\n+ for version in versions:\n+ for questionnaire in self.api.questionnaires_list(workflow_version=version):\n+ workflow[self.TAG_COLUMN_NAME] = questionnaire['tag']\n+ data.append(dict(workflow))\n return data\n \n \n", "test_patch": "diff --git a/bespin/test_argparse.py b/bespin/test_argparse.py\nindex 1f1cd6e..1af15be 100644\n--- a/bespin/test_argparse.py\n+++ b/bespin/test_argparse.py\n@@ -10,9 +10,17 @@ class ArgParserTestCase(TestCase):\n self.target_object = Mock()\n self.arg_parser = ArgParser(version_str='1.0', target_object=self.target_object)\n \n- def test_workflows_list(self):\n+ def test_workflows_list_current_versions(self):\n self.arg_parser.parse_and_run_commands([\"workflows\", \"list\"])\n- self.target_object.workflows_list.assert_called()\n+ self.target_object.workflows_list.assert_called_with(all_versions=False)\n+\n+ def test_workflows_list_all_versions(self):\n+ self.arg_parser.parse_and_run_commands([\"workflows\", \"list\", \"--all\"])\n+ self.target_object.workflows_list.assert_called_with(all_versions=True)\n+\n+ def test_workflows_list_all_versions_short_flag(self):\n+ self.arg_parser.parse_and_run_commands([\"workflows\", \"list\", \"-a\"])\n+ self.target_object.workflows_list.assert_called_with(all_versions=True)\n \n def test_init_job(self):\n self.arg_parser.parse_and_run_commands([\"jobs\", \"init\", \"--tag\", \"exome/v1/human\"])\ndiff --git a/bespin/test_commands.py b/bespin/test_commands.py\nindex e3756c8..5bd78a8 100644\n--- a/bespin/test_commands.py\n+++ b/bespin/test_commands.py\n@@ -18,13 +18,30 @@ class CommandsTestCase(TestCase):\n @patch('bespin.commands.WorkflowDetails')\n @patch('bespin.commands.Table')\n @patch('bespin.commands.print')\n- def test_workflows_list(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api, mock_config_file):\n+ def test_workflows_list_latest_versions(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api,\n+ mock_config_file):\n commands = Commands(self.version_str, self.user_agent_str)\n- commands.workflows_list()\n+ commands.workflows_list(all_versions=False)\n workflow_details = mock_workflow_details.return_value\n mock_table.assert_called_with(workflow_details.column_names,\n workflow_details.get_column_data.return_value)\n mock_print.assert_called_with(mock_table.return_value)\n+ mock_workflow_details.assert_called_with(mock_bespin_api.return_value, False)\n+\n+ @patch('bespin.commands.ConfigFile')\n+ @patch('bespin.commands.BespinApi')\n+ @patch('bespin.commands.WorkflowDetails')\n+ @patch('bespin.commands.Table')\n+ @patch('bespin.commands.print')\n+ def test_workflows_list_all_versions(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api,\n+ mock_config_file):\n+ commands = Commands(self.version_str, self.user_agent_str)\n+ commands.workflows_list(all_versions=True)\n+ workflow_details = mock_workflow_details.return_value\n+ mock_table.assert_called_with(workflow_details.column_names,\n+ workflow_details.get_column_data.return_value)\n+ mock_print.assert_called_with(mock_table.return_value)\n+ mock_workflow_details.assert_called_with(mock_bespin_api.return_value, True)\n \n @patch('bespin.commands.ConfigFile')\n @patch('bespin.commands.BespinApi')\n@@ -156,9 +173,9 @@ class WorkflowDetailsTestCase(TestCase):\n mock_api.questionnaires_list.return_value = [\n {'tag': 'exome/v2/human'}\n ]\n- details = WorkflowDetails(mock_api)\n+ details = WorkflowDetails(mock_api, all_versions=False)\n expected_data = [{'id': 1,\n- 'latest version tag': 'exome/v2/human',\n+ 'version tag': 'exome/v2/human',\n 'name': 'exome',\n 'versions': [1, 2]}]\n column_data = details.get_column_data()\n@@ -166,12 +183,50 @@ class WorkflowDetailsTestCase(TestCase):\n self.assertEqual(column_data, expected_data)\n mock_api.questionnaires_list.assert_called_with(workflow_version=2)\n \n- def test_ignores_workflows_without_versions(self):\n+ mock_api.questionnaires_list.reset_mock()\n+ mock_api.questionnaires_list.side_effect = [\n+ [{'tag': 'exome/v1/human'}],\n+ [{'tag': 'exome/v2/human'}]\n+ ]\n+ details = WorkflowDetails(mock_api, all_versions=True)\n+ expected_data = [\n+ {\n+ 'id': 1,\n+ 'version tag': 'exome/v1/human',\n+ 'name': 'exome',\n+ 'versions': [1, 2]\n+ },\n+ {\n+ 'id': 1,\n+ 'version tag': 'exome/v2/human',\n+ 'name': 'exome',\n+ 'versions': [1, 2]\n+ },\n+ ]\n+ column_data = details.get_column_data()\n+ self.assertEqual(len(column_data), 2)\n+ self.assertEqual(column_data, expected_data)\n+ mock_api.questionnaires_list.assert_has_calls([\n+ call(workflow_version=1),\n+ call(workflow_version=2),\n+ ])\n+\n+ def test_ignores_workflows_without_versions_when_latest(self):\n+ mock_api = Mock()\n+ mock_api.workflows_list.return_value = [\n+ {'id': 1, 'name': 'no-versions', 'versions': []},\n+ ]\n+ details = WorkflowDetails(mock_api, all_versions=False)\n+ column_data = details.get_column_data()\n+ self.assertEqual(len(column_data), 0)\n+ mock_api.questionnaires_list.assert_not_called()\n+\n+ def test_ignores_workflows_without_versions_when_all(self):\n mock_api = Mock()\n mock_api.workflows_list.return_value = [\n {'id': 1, 'name': 'no-versions', 'versions': []},\n ]\n- details = WorkflowDetails(mock_api)\n+ details = WorkflowDetails(mock_api, all_versions=True)\n column_data = details.get_column_data()\n self.assertEqual(len(column_data), 0)\n mock_api.questionnaires_list.assert_not_called()\n", "FAIL_TO_PASS": ["bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions_short_flag", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_current_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_all_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_latest_versions", "bespin/test_commands.py::WorkflowDetailsTestCase::test_get_column_data", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_all", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_latest"]}, {"instance_id": "Duke-GCB__bespin-cli-16", "base_commit": "471cd4df56c852bee11fcb4725dc6b4e9053e08c", "gold_patch": "diff --git a/bespin/api.py b/bespin/api.py\nindex 5558ccd..dad9652 100644\n--- a/bespin/api.py\n+++ b/bespin/api.py\n@@ -103,7 +103,7 @@ class BespinApi(object):\n return self._post_request('/job-file-stage-groups/', {})\n \n def dds_job_input_files_post(self, project_id, file_id, destination_path, sequence_group, sequence,\n- dds_user_credentials, stage_group_id):\n+ dds_user_credentials, stage_group_id, size):\n data = {\n \"project_id\": project_id,\n \"file_id\": file_id,\n@@ -111,7 +111,8 @@ class BespinApi(object):\n \"sequence_group\": sequence_group,\n \"sequence\": sequence,\n \"dds_user_credentials\": dds_user_credentials,\n- \"stage_group\": stage_group_id\n+ \"stage_group\": stage_group_id,\n+ \"size\": size,\n }\n return self._post_request('/dds-job-input-files/', data)\n \ndiff --git a/bespin/commands.py b/bespin/commands.py\nindex c8c1fb6..e30d252 100644\n--- a/bespin/commands.py\n+++ b/bespin/commands.py\n@@ -288,8 +288,10 @@ class JobFile(object):\n dds_project_ids = set()\n sequence = 0\n for dds_file, path in self.get_dds_files_details():\n+ file_size = dds_file.current_version['upload']['size']\n api.dds_job_input_files_post(dds_file.project_id, dds_file.id, path, 0, sequence,\n- dds_user_credential['id'], stage_group_id=stage_group['id'])\n+ dds_user_credential['id'], stage_group_id=stage_group['id'],\n+ size=file_size)\n sequence += 1\n dds_project_ids.add(dds_file.project_id)\n user_job_order_json = self.create_user_job_order_json()\ndiff --git a/bespin/dukeds.py b/bespin/dukeds.py\nindex 8753d3f..47816e2 100644\n--- a/bespin/dukeds.py\n+++ b/bespin/dukeds.py\n@@ -8,6 +8,7 @@ INVALID_DUKEDS_FILE_PATH_MSG = \"Invalid DukeDS file path ({})\"\n DUKEDS_FILE_PATH_MISSING_PREFIX = INVALID_DUKEDS_FILE_PATH_MSG.format(\"missing prefix\")\n DUKEDS_FILE_PATH_MISSING_SLASH = INVALID_DUKEDS_FILE_PATH_MSG.format(\"missing / between project and file path\")\n \n+\n class DDSFileUtil(object):\n def __init__(self):\n self.client = Client()\n", "test_patch": "diff --git a/bespin/test_api.py b/bespin/test_api.py\nindex 99ad636..30f1804 100644\n--- a/bespin/test_api.py\n+++ b/bespin/test_api.py\n@@ -145,7 +145,8 @@ class BespinApiTestCase(TestCase):\n api = BespinApi(config=self.mock_config, user_agent_str=self.mock_user_agent_str)\n dds_input_file = api.dds_job_input_files_post(project_id='123', file_id='456', destination_path='data.txt',\n sequence_group=1, sequence=2,\n- dds_user_credentials=4, stage_group_id=5)\n+ dds_user_credentials=4, stage_group_id=5,\n+ size=1000)\n \n self.assertEqual(dds_input_file, 'dds-job-input-file1')\n expected_json = {\n@@ -155,7 +156,8 @@ class BespinApiTestCase(TestCase):\n 'sequence_group': 1,\n 'sequence': 2,\n 'dds_user_credentials': 4,\n- 'stage_group': 5\n+ 'stage_group': 5,\n+ 'size': 1000,\n }\n mock_requests.post.assert_called_with('someurl/dds-job-input-files/', headers=self.expected_headers,\n json=expected_json)\ndiff --git a/bespin/test_commands.py b/bespin/test_commands.py\nindex 5bd78a8..486bf81 100644\n--- a/bespin/test_commands.py\n+++ b/bespin/test_commands.py\n@@ -336,14 +336,15 @@ class JobFileTestCase(TestCase):\n 'myint': 555\n })\n job_file.get_dds_files_details = Mock()\n- mock_file = Mock(project_id=666)\n+ mock_file = Mock(project_id=666, current_version={'upload': {'size': 4002}})\n mock_file.id = 777\n job_file.get_dds_files_details.return_value = [[mock_file, 'somepath']]\n \n job_file.create_job(mock_api)\n \n mock_api.questionnaires_list.assert_called_with(tag='sometag')\n- mock_api.dds_job_input_files_post.assert_called_with(666, 777, 'somepath', 0, 0, 111, stage_group_id=333)\n+ mock_api.dds_job_input_files_post.assert_called_with(666, 777, 'somepath', 0, 0, 111, stage_group_id=333,\n+ size=4002)\n json_payload = '{\"myfile\": {\"class\": \"File\", \"path\": \"dds_project_somepath.txt\"}, \"myint\": 555}'\n mock_api.job_answer_set_post.assert_called_with('myjob', '001', json_payload, 222, 333)\n mock_api.job_answer_set_create_job.assert_called_with(444)\n", "FAIL_TO_PASS": ["bespin/test_api.py::BespinApiTestCase::test_dds_job_input_files_post", "bespin/test_commands.py::JobFileTestCase::test_create_job"]}], "all_FAIL_TO_PASS": ["bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions_short_flag", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_current_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_all_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_latest_versions", "bespin/test_commands.py::WorkflowDetailsTestCase::test_get_column_data", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_all", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_latest", "bespin/test_api.py::BespinApiTestCase::test_dds_job_input_files_post", "bespin/test_commands.py::JobFileTestCase::test_create_job"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "dask__distributed-2969_x2", "level": 2, "source": "swerebench", "repo": "dask/distributed", "image": "swerebench/sweb.eval.x86_64.dask_1776_distributed-2969:latest", "base_commit": "b083b10d64763b38e559096127d6e3e0c0638c31", "num_bugs": 2, "bugs": [{"instance_id": "dask__distributed-2969", "base_commit": "b083b10d64763b38e559096127d6e3e0c0638c31", "gold_patch": "diff --git a/distributed/__init__.py b/distributed/__init__.py\nindex ca36613c..d79993df 100644\n--- a/distributed/__init__.py\n+++ b/distributed/__init__.py\n@@ -3,7 +3,7 @@ from dask.config import config\n from .actor import Actor, ActorFuture\n from .core import connect, rpc\n from .deploy import LocalCluster, Adaptive, SpecCluster\n-from .diagnostics import progress\n+from .diagnostics.progressbar import progress\n from .client import (\n Client,\n Executor,\ndiff --git a/distributed/utils.py b/distributed/utils.py\nindex c8ea8d64..65f5c188 100644\n--- a/distributed/utils.py\n+++ b/distributed/utils.py\n@@ -904,22 +904,43 @@ def tmpfile(extension=\"\"):\n \n \n def ensure_bytes(s):\n- \"\"\" Turn string or bytes to bytes\n+ \"\"\"Attempt to turn `s` into bytes.\n+\n+ Parameters\n+ ----------\n+ s : Any\n+ The object to be converted. Will correctly handled\n+\n+ * str\n+ * bytes\n+ * objects implementing the buffer protocol (memoryview, ndarray, etc.)\n+\n+ Returns\n+ -------\n+ b : bytes\n+\n+ Raises\n+ ------\n+ TypeError\n+ When `s` cannot be converted\n+\n+ Examples\n+ --------\n \n >>> ensure_bytes('123')\n b'123'\n >>> ensure_bytes(b'123')\n b'123'\n \"\"\"\n- if isinstance(s, bytes):\n- return s\n- if isinstance(s, memoryview):\n- return s.tobytes()\n- if isinstance(s, bytearray): # noqa: F821\n- return bytes(s)\n if hasattr(s, \"encode\"):\n return s.encode()\n- raise TypeError(\"Object %s is neither a bytes object nor has an encode method\" % s)\n+ else:\n+ try:\n+ return bytes(s)\n+ except Exception as e:\n+ raise TypeError(\n+ \"Object %s is neither a bytes object nor has an encode method\" % s\n+ ) from e\n \n \n def divide_n_among_bins(n, bins):\ndiff --git a/docs/source/limitations.rst b/docs/source/limitations.rst\nindex 3c64d445..e272359e 100644\n--- a/docs/source/limitations.rst\n+++ b/docs/source/limitations.rst\n@@ -35,7 +35,6 @@ Dask assumes the following about your functions and your data:\n - Dask may run your functions multiple times,\n such as if a worker holding an intermediate result dies. Any side effects\n should be `idempotent `_.\n--\n \n Security\n --------\n", "test_patch": "diff --git a/distributed/protocol/tests/test_arrow.py b/distributed/protocol/tests/test_arrow.py\nindex a363ee95..37aff3a2 100644\n--- a/distributed/protocol/tests/test_arrow.py\n+++ b/distributed/protocol/tests/test_arrow.py\n@@ -3,9 +3,9 @@ import pytest\n \n pa = pytest.importorskip(\"pyarrow\")\n \n+import distributed\n from distributed.utils_test import gen_cluster\n-from distributed.protocol import deserialize, serialize\n-\n+from distributed.protocol import deserialize, serialize, to_serialize\n \n df = pd.DataFrame({\"A\": list(\"abc\"), \"B\": [1, 2, 3]})\n tbl = pa.Table.from_pandas(df, preserve_index=False)\n@@ -35,3 +35,12 @@ def test_scatter(obj):\n assert obj.equals(result)\n \n run_test()\n+\n+\n+def test_dumps_compression():\n+ # https://github.com/dask/distributed/issues/2966\n+ # large enough to trigger compression\n+ t = pa.Table.from_pandas(pd.DataFrame({\"A\": [1] * 10000}))\n+ msg = {\"op\": \"update\", \"data\": to_serialize(t)}\n+ result = distributed.protocol.loads(distributed.protocol.dumps(msg))\n+ assert result[\"data\"].equals(t)\ndiff --git a/distributed/tests/test_utils.py b/distributed/tests/test_utils.py\nindex e5e18eb3..81541686 100644\n--- a/distributed/tests/test_utils.py\n+++ b/distributed/tests/test_utils.py\n@@ -1,3 +1,4 @@\n+import array\n import datetime\n from functools import partial\n import io\n@@ -275,13 +276,25 @@ def test_funcname():\n \n \n def test_ensure_bytes():\n- data = [b\"1\", \"1\", memoryview(b\"1\"), bytearray(b\"1\")]\n+ data = [b\"1\", \"1\", memoryview(b\"1\"), bytearray(b\"1\"), array.array(\"b\", [49])]\n for d in data:\n result = ensure_bytes(d)\n assert isinstance(result, bytes)\n assert result == b\"1\"\n \n \n+def test_ensure_bytes_ndarray():\n+ result = ensure_bytes(np.arange(12))\n+ assert isinstance(result, bytes)\n+\n+\n+def test_ensure_bytes_pyarrow_buffer():\n+ pa = pytest.importorskip(\"pyarrow\")\n+ buf = pa.py_buffer(b\"123\")\n+ result = ensure_bytes(buf)\n+ assert isinstance(result, bytes)\n+\n+\n def test_nbytes():\n def check(obj, expected):\n assert nbytes(obj) == expected\n", "FAIL_TO_PASS": ["distributed/tests/test_utils.py::test_ensure_bytes", "distributed/tests/test_utils.py::test_ensure_bytes_ndarray"]}, {"instance_id": "dask__distributed-3021", "base_commit": "1ef4f70dc7f8fe048d11104ee8daad04b82227e9", "gold_patch": "diff --git a/distributed/utils.py b/distributed/utils.py\nindex 9f14d58d..b7f6631c 100644\n--- a/distributed/utils.py\n+++ b/distributed/utils.py\n@@ -1434,7 +1434,9 @@ def format_dashboard_link(host, port):\n scheme = \"https\"\n else:\n scheme = \"http\"\n- return template.format(scheme=scheme, host=host, port=port, **os.environ)\n+ return template.format(\n+ **toolz.merge(os.environ, dict(scheme=scheme, host=host, port=port))\n+ )\n \n \n def is_coroutine_function(f):\n", "test_patch": "diff --git a/distributed/tests/test_utils.py b/distributed/tests/test_utils.py\nindex bf2d8456..ff733a1a 100644\n--- a/distributed/tests/test_utils.py\n+++ b/distributed/tests/test_utils.py\n@@ -2,6 +2,7 @@ import array\n import datetime\n from functools import partial\n import io\n+import os\n import queue\n import socket\n import sys\n@@ -40,6 +41,7 @@ from distributed.utils import (\n parse_bytes,\n parse_timedelta,\n warn_on_duration,\n+ format_dashboard_link,\n )\n from distributed.utils_test import loop, loop_in_thread # noqa: F401\n from distributed.utils_test import div, has_ipv6, inc, throws, gen_test, captured_logger\n@@ -582,3 +584,17 @@ def test_is_valid_xml():\n assert is_valid_xml(\"foo\")\n with pytest.raises(Exception):\n assert is_valid_xml(\"foo\")\n+\n+\n+def test_format_dashboard_link():\n+ with dask.config.set({\"distributed.dashboard.link\": \"foo\"}):\n+ assert format_dashboard_link(\"host\", 1234) == \"foo\"\n+\n+ assert \"host\" in format_dashboard_link(\"host\", 1234)\n+ assert \"1234\" in format_dashboard_link(\"host\", 1234)\n+\n+ try:\n+ os.environ[\"host\"] = \"hello\"\n+ assert \"hello\" not in format_dashboard_link(\"host\", 1234)\n+ finally:\n+ del os.environ[\"host\"]\n", "FAIL_TO_PASS": ["distributed/tests/test_utils.py::test_format_dashboard_link"]}], "all_FAIL_TO_PASS": ["distributed/tests/test_utils.py::test_ensure_bytes", "distributed/tests/test_utils.py::test_ensure_bytes_ndarray", "distributed/tests/test_utils.py::test_format_dashboard_link"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cwacek__python-jsonschema-objects-179_x2", "level": 2, "source": "swerebench", "repo": "cwacek/python-jsonschema-objects", "image": "swerebench/sweb.eval.x86_64.cwacek_1776_python-jsonschema-objects-179:latest", "base_commit": "c4ace6de887690a04399c62a52ac6d481930c5a5", "num_bugs": 2, "bugs": [{"instance_id": "cwacek__python-jsonschema-objects-179", "base_commit": "c4ace6de887690a04399c62a52ac6d481930c5a5", "gold_patch": "diff --git a/python_jsonschema_objects/classbuilder.py b/python_jsonschema_objects/classbuilder.py\nindex 8178397..809095e 100644\n--- a/python_jsonschema_objects/classbuilder.py\n+++ b/python_jsonschema_objects/classbuilder.py\n@@ -399,9 +399,20 @@ class TypeRef(object):\n \n \n class TypeProxy(object):\n- def __init__(self, types):\n+ slots = (\"__title__\", \"_types\")\n+\n+ def __init__(self, types, title=None):\n+ self.__title__ = title\n self._types = types\n \n+ def from_json(self, jsonmsg):\n+ import json\n+\n+ msg = json.loads(jsonmsg)\n+ obj = self(**msg)\n+ obj.validate()\n+ return obj\n+\n def __call__(self, *a, **kw):\n validation_errors = []\n valid_types = self._types\n@@ -434,25 +445,44 @@ class ClassBuilder(object):\n self.resolved = {}\n self.under_construction = set()\n \n- def resolve_classes(self, iterable):\n+ def expand_references(self, source_uri, iterable):\n+ \"\"\" Give an iterable of jsonschema descriptors, expands any\n+ of them that are $ref objects, and otherwise leaves them alone. \n+ \"\"\"\n pp = []\n for elem in iterable:\n if \"$ref\" in elem:\n- ref = elem[\"$ref\"]\n- uri = util.resolve_ref_uri(self.resolver.resolution_scope, ref)\n- if uri in self.resolved:\n- pp.append(self.resolved[uri])\n- else:\n- with self.resolver.resolving(ref) as resolved:\n- self.resolved[uri] = self.construct(\n- uri, resolved, (ProtocolBase,)\n- )\n- pp.append(self.resolved[uri])\n+ pp.append(self.resolve_type(elem[\"$ref\"], source_uri))\n else:\n pp.append(elem)\n \n return pp\n \n+ def resolve_type(self, ref, source):\n+ \"\"\" Return a resolved type for a URI, potentially constructing one if necessary\"\"\"\n+ uri = util.resolve_ref_uri(self.resolver.resolution_scope, ref)\n+ if uri in self.resolved:\n+ return self.resolved[uri]\n+\n+ elif uri in self.under_construction:\n+ logger.debug(\n+ util.lazy_format(\n+ \"Using a TypeRef to avoid a cyclic reference for {0} -> {1} \",\n+ uri,\n+ source,\n+ )\n+ )\n+ return TypeRef(uri, self.resolved)\n+ else:\n+ logger.debug(\n+ util.lazy_format(\n+ \"Resolving direct reference object {0} -> {1}\", source, uri\n+ )\n+ )\n+ with self.resolver.resolving(ref) as resolved:\n+ self.resolved[uri] = self.construct(uri, resolved, (ProtocolBase,))\n+ return self.resolved[uri]\n+\n def construct(self, uri, *args, **kw):\n \"\"\" Wrapper to debug things \"\"\"\n logger.debug(util.lazy_format(\"Constructing {0}\", uri))\n@@ -472,11 +502,19 @@ class ClassBuilder(object):\n raise NotImplementedError(\"anyOf is not supported as bare property\")\n \n elif \"oneOf\" in clsdata:\n- self.resolved[uri] = self._build_object(uri, clsdata, parent, **kw)\n+ \"\"\" If this object itself has a 'oneOf' designation, \n+ then construct a TypeProxy.\n+ \"\"\"\n+ klasses = self.construct_objects(clsdata[\"oneOf\"], uri)\n+\n+ logger.debug(\n+ util.lazy_format(\"Designating {0} as TypeProxy for {1}\", uri, klasses)\n+ )\n+ self.resolved[uri] = TypeProxy(klasses, title=clsdata.get(\"title\"))\n return self.resolved[uri]\n \n elif \"allOf\" in clsdata:\n- potential_parents = self.resolve_classes(clsdata[\"allOf\"])\n+ potential_parents = self.expand_references(uri, clsdata[\"allOf\"])\n parents = []\n for p in potential_parents:\n if isinstance(p, dict):\n@@ -509,25 +547,8 @@ class ClassBuilder(object):\n )\n else:\n ref = clsdata[\"$ref\"]\n- refuri = util.resolve_ref_uri(self.resolver.resolution_scope, ref)\n- if refuri in self.under_construction:\n- logger.debug(\n- util.lazy_format(\n- \"Resolving cyclic reference from {0} to {1}.\", uri, refuri\n- )\n- )\n- return TypeRef(refuri, self.resolved)\n- else:\n- logger.debug(\n- util.lazy_format(\n- \"Resolving direct reference object for {0}: {1}\",\n- uri,\n- refuri,\n- )\n- )\n-\n- with self.resolver.resolving(refuri) as resolved:\n- self.resolved[uri] = self.construct(refuri, resolved, parent)\n+ typ = self.resolve_type(ref, uri)\n+ self.resolved[uri] = typ\n \n return self.resolved[uri]\n \n@@ -639,23 +660,14 @@ class ClassBuilder(object):\n \n elif \"type\" not in detail and \"$ref\" in detail:\n ref = detail[\"$ref\"]\n- uri = util.resolve_ref_uri(self.resolver.resolution_scope, ref)\n- logger.debug(\n- util.lazy_format(\n- \"Resolving reference {0} for {1}.{2}\", ref, nm, prop\n- )\n- )\n- if uri in self.resolved:\n- typ = self.resolved[uri]\n- else:\n- typ = self.construct(uri, detail, (ProtocolBase,))\n+ typ = self.resolve_type(ref, \".\".join([nm, prop]))\n \n props[prop] = make_property(prop, {\"type\": typ}, typ.__doc__)\n- properties[prop][\"$ref\"] = uri\n+ properties[prop][\"$ref\"] = ref\n properties[prop][\"type\"] = typ\n \n elif \"oneOf\" in detail:\n- potential = self.resolve_classes(detail[\"oneOf\"])\n+ potential = self.expand_references(nm, detail[\"oneOf\"])\n logger.debug(\n util.lazy_format(\"Designating {0} as oneOf {1}\", prop, potential)\n )\n@@ -665,16 +677,13 @@ class ClassBuilder(object):\n elif \"type\" in detail and detail[\"type\"] == \"array\":\n if \"items\" in detail and isinstance(detail[\"items\"], dict):\n if \"$ref\" in detail[\"items\"]:\n- uri = util.resolve_ref_uri(\n- self.resolver.resolution_scope, detail[\"items\"][\"$ref\"]\n- )\n- typ = self.construct(uri, detail[\"items\"])\n+ typ = self.resolve_type(detail[\"items\"][\"$ref\"], nm)\n constraints = copy.copy(detail)\n constraints[\"strict\"] = kw.get(\"strict\")\n propdata = {\n \"type\": \"array\",\n \"validator\": python_jsonschema_objects.wrapper_types.ArrayWrapper.create(\n- uri, item_constraint=typ, **constraints\n+ nm, item_constraint=typ, **constraints\n ),\n }\n \n@@ -683,20 +692,9 @@ class ClassBuilder(object):\n try:\n if \"oneOf\" in detail[\"items\"]:\n typ = TypeProxy(\n- [\n- self.construct(uri + \"_%s\" % i, item_detail)\n- if \"$ref\" not in item_detail\n- else self.construct(\n- util.resolve_ref_uri(\n- self.resolver.resolution_scope,\n- item_detail[\"$ref\"],\n- ),\n- item_detail,\n- )\n- for i, item_detail in enumerate(\n- detail[\"items\"][\"oneOf\"]\n- )\n- ]\n+ self.construct_objects(\n+ detail[\"items\"][\"oneOf\"], uri\n+ )\n )\n else:\n typ = self.construct(uri, detail[\"items\"])\n@@ -738,14 +736,6 @@ class ClassBuilder(object):\n \n props[prop] = make_property(prop, {\"type\": typ}, desc)\n \n- \"\"\" If this object itself has a 'oneOf' designation, then\n- make the validation 'type' the list of potential objects.\n- \"\"\"\n- if \"oneOf\" in clsdata:\n- klasses = self.resolve_classes(clsdata[\"oneOf\"])\n- # Need a validation to check that it meets one of them\n- props[\"__validation__\"] = {\"type\": klasses}\n-\n props[\"__extensible__\"] = pattern_properties.ExtensibleValidator(\n nm, clsdata, self\n )\n@@ -777,6 +767,14 @@ class ClassBuilder(object):\n \n return cls\n \n+ def construct_objects(self, oneOfList, uri):\n+ return [\n+ self.construct(uri + \"_%s\" % i, item_detail)\n+ if \"$ref\" not in item_detail\n+ else self.resolve_type(item_detail[\"$ref\"], uri + \"_%s\" % i)\n+ for i, item_detail in enumerate(oneOfList)\n+ ]\n+\n \n def make_property(prop, info, desc=\"\"):\n from . import descriptors\ndiff --git a/python_jsonschema_objects/pattern_properties.py b/python_jsonschema_objects/pattern_properties.py\nindex 2ebdf1b..c4a07a6 100644\n--- a/python_jsonschema_objects/pattern_properties.py\n+++ b/python_jsonschema_objects/pattern_properties.py\n@@ -30,7 +30,7 @@ class ExtensibleValidator(object):\n self._additional_type = True\n else:\n if \"$ref\" in addlProp:\n- refs = builder.resolve_classes([addlProp])\n+ typ = builder.resolve_type(addlProp[\"$ref\"], name)\n else:\n uri = \"{0}/{1}_{2}\".format(\n name, \"\", \"\"\n@@ -38,23 +38,23 @@ class ExtensibleValidator(object):\n builder.resolved[uri] = builder.construct(\n uri, addlProp, (cb.ProtocolBase,)\n )\n- refs = [builder.resolved[uri]]\n+ typ = builder.resolved[uri]\n \n- self._additional_type = refs[0]\n+ self._additional_type = typ\n \n for pattern, typedef in six.iteritems(schemadef.get(\"patternProperties\", {})):\n if \"$ref\" in typedef:\n- refs = builder.resolve_classes([typedef])\n+ typ = builder.resolve_type(typedef[\"$ref\"], name)\n else:\n uri = \"{0}/{1}_{2}\".format(name, \"\", pattern)\n \n builder.resolved[uri] = builder.construct(\n uri, typedef, (cb.ProtocolBase,)\n )\n- refs = [builder.resolved[uri]]\n+ typ = builder.resolved[uri]\n \n self._pattern_types.append(\n- PatternDef(pattern=re.compile(pattern), schema_type=refs[0])\n+ PatternDef(pattern=re.compile(pattern), schema_type=typ)\n )\n \n def _make_type(self, typ, val):\ndiff --git a/python_jsonschema_objects/wrapper_types.py b/python_jsonschema_objects/wrapper_types.py\nindex c2ce58f..4d7ea91 100644\n--- a/python_jsonschema_objects/wrapper_types.py\n+++ b/python_jsonschema_objects/wrapper_types.py\n@@ -251,7 +251,9 @@ class ArrayWrapper(collections.MutableSequence):\n )\n from python_jsonschema_objects import classbuilder\n \n- klassbuilder = addl_constraints.pop(\"classbuilder\", None)\n+ klassbuilder = addl_constraints.pop(\n+ \"classbuilder\", None\n+ ) # type: python_jsonschema_objects.classbuilder.ClassBuilder\n props = {}\n \n if item_constraint is not None:\n@@ -290,23 +292,9 @@ class ArrayWrapper(collections.MutableSequence):\n )\n )\n \n- uri = item_constraint[\"$ref\"]\n- if uri in klassbuilder.resolved:\n- logger.debug(\n- util.lazy_format(\n- \"Using previously resolved object for {0}\", uri\n- )\n- )\n- else:\n- logger.debug(util.lazy_format(\"Resolving object for {0}\", uri))\n-\n- with klassbuilder.resolver.resolving(uri) as resolved:\n- # Set incase there is a circular reference in schema definition\n- klassbuilder.resolved[uri] = klassbuilder.construct(\n- uri, resolved, (classbuilder.ProtocolBase,)\n- )\n-\n- item_constraint = klassbuilder.resolved[uri]\n+ item_constraint = klassbuilder.resolve_type(\n+ item_constraint[\"$ref\"], name\n+ )\n \n elif isdict and item_constraint.get(\"type\") == \"array\":\n # We need to create a sub-array validator.\n@@ -318,22 +306,9 @@ class ArrayWrapper(collections.MutableSequence):\n elif isdict and \"oneOf\" in item_constraint:\n # We need to create a TypeProxy validator\n uri = \"{0}_{1}\".format(name, \"\")\n- type_array = []\n- for i, item_detail in enumerate(item_constraint[\"oneOf\"]):\n- if \"$ref\" in item_detail:\n- subtype = klassbuilder.construct(\n- util.resolve_ref_uri(\n- klassbuilder.resolver.resolution_scope,\n- item_detail[\"$ref\"],\n- ),\n- item_detail,\n- )\n- else:\n- subtype = klassbuilder.construct(\n- uri + \"_%s\" % i, item_detail\n- )\n-\n- type_array.append(subtype)\n+ type_array = klassbuilder.construct_objects(\n+ item_constraint[\"oneOf\"], uri\n+ )\n \n item_constraint = classbuilder.TypeProxy(type_array)\n \n", "test_patch": "diff --git a/test/test_feature_151.py b/test/test_feature_151.py\nnew file mode 100644\nindex 0000000..3798287\n--- /dev/null\n+++ b/test/test_feature_151.py\n@@ -0,0 +1,31 @@\n+import pytest\n+import python_jsonschema_objects as pjo\n+\n+\n+def test_simple_array_oneOf():\n+ basicSchemaDefn = {\n+ \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n+ \"title\": \"Test\",\n+ \"properties\": {\n+ \"SimpleArrayOfNumberOrString\": {\"$ref\": \"#/definitions/simparray\"}\n+ },\n+ \"required\": [\"SimpleArrayOfNumberOrString\"],\n+ \"type\": \"object\",\n+ \"definitions\": {\n+ \"simparray\": {\n+ \"oneOf\": [\n+ {\"type\": \"array\", \"items\": {\"type\": \"number\"}},\n+ {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n+ ]\n+ }\n+ },\n+ }\n+\n+ builder = pjo.ObjectBuilder(basicSchemaDefn)\n+\n+ ns = builder.build_classes()\n+ ns.Test().from_json('{\"SimpleArrayOfNumberOrString\" : [0, 1]}')\n+ ns.Test().from_json('{\"SimpleArrayOfNumberOrString\" : [\"Hi\", \"There\"]}')\n+\n+ with pytest.raises(pjo.ValidationError):\n+ ns.Test().from_json('{\"SimpleArrayOfNumberOrString\" : [\"Hi\", 0]}')\ndiff --git a/test/test_pytest.py b/test/test_pytest.py\nindex 2ae8a5e..b1106e1 100644\n--- a/test/test_pytest.py\n+++ b/test/test_pytest.py\n@@ -529,3 +529,12 @@ def test_default_values(default):\n \n x = ns.Test()\n assert x.sample == default[\"default\"]\n+\n+\n+def test_justareference_example(markdown_examples):\n+\n+ builder = pjs.ObjectBuilder(\n+ markdown_examples[\"Just a Reference\"], resolved=markdown_examples\n+ )\n+ ns = builder.build_classes()\n+ ns.JustAReference(\"Hello\")\ndiff --git a/test/test_regression_156.py b/test/test_regression_156.py\nindex 138bbe0..48837bc 100644\n--- a/test/test_regression_156.py\n+++ b/test/test_regression_156.py\n@@ -18,3 +18,11 @@ def test_regression_156(markdown_examples):\n # round-trip serialize-deserialize into class defined with `oneOf`\n classes.Multipleobjects.from_json(er.serialize())\n classes.Multipleobjects.from_json(vgr.serialize())\n+\n+\n+def test_toplevel_oneof_gets_a_name(markdown_examples):\n+ builder = pjo.ObjectBuilder(\n+ markdown_examples[\"MultipleObjects\"], resolved=markdown_examples\n+ )\n+ classes = builder.build_classes(named_only=True)\n+ assert classes.Multipleobjects.__title__ is not None\n", "FAIL_TO_PASS": ["test/test_feature_151.py::test_simple_array_oneOf"]}, {"instance_id": "cwacek__python-jsonschema-objects-190", "base_commit": "8d6b992919bf240f4142acb2bbbf8c1dca41bcb6", "gold_patch": "diff --git a/python_jsonschema_objects/classbuilder.py b/python_jsonschema_objects/classbuilder.py\nindex 809095e..5524b18 100644\n--- a/python_jsonschema_objects/classbuilder.py\n+++ b/python_jsonschema_objects/classbuilder.py\n@@ -127,6 +127,9 @@ class ProtocolBase(collections.MutableMapping):\n obj.validate()\n return obj\n \n+ def __deepcopy__(self, memo):\n+ return self.__class__(**self.as_dict())\n+\n def __new__(cls, **props):\n \"\"\" Overridden to support oneOf, where we need to\n instantiate a different class depending on what\ndiff --git a/tox.ini b/tox.ini\nindex dccf043..d1fc67c 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -1,6 +1,7 @@\n \n [tox]\n-envlist = py{27,35,36,37}-jsonschema{23,24,25,26,30}-markdown{2,3}\n+envlist = py{35,36,37}-jsonschema{23,24,25,26,30}-markdown{2,3}\n+skip_missing_interpreters = true\n \n [testenv]\n ;install_command = pip install {opts} {packages}\n", "test_patch": "diff --git a/test/test_regression_185.py b/test/test_regression_185.py\nnew file mode 100644\nindex 0000000..67145f3\n--- /dev/null\n+++ b/test/test_regression_185.py\n@@ -0,0 +1,45 @@\n+import pytest\n+import python_jsonschema_objects as pjs\n+import jsonschema\n+\n+import json\n+import copy\n+import pprint\n+\n+pp = pprint.PrettyPrinter(indent=2)\n+\n+lpid_class_schema = {\n+ \"$id\": \"https://example.com/schema-repository/lpid\",\n+ \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n+ \"type\": \"object\",\n+ \"title\": \"Logical Process ID\",\n+ \"properties\": {\"lpid_str\": {\"type\": \"string\"}},\n+ \"required\": [\"lpid_str\"],\n+ \"additionalProperties\": True,\n+}\n+\n+\n+class A(object):\n+ a_str = None\n+\n+ def __init__(self, a_str):\n+ self.a_str = a_str\n+\n+\n+def test_regression_185_deepcopy():\n+ # Class building and instantiation work great and round-trip.\n+ lpid_class_builder = pjs.ObjectBuilder(lpid_class_schema)\n+ LPID = lpid_class_builder.classes.LogicalProcessId\n+ lpid = LPID(lpid_str=\"foobaz\")\n+ instance = json.loads(lpid.serialize())\n+ jsonschema.validate(lpid_class_schema, instance)\n+\n+ # Deep-copying seems to work with instances of normal popos.\n+ a = A(a_str=\"barqux\")\n+ assert a\n+ a_2 = copy.deepcopy(a)\n+ assert a_2\n+\n+ # But deep-copying with objects of generated classes doesn't terminate.\n+ lpid_2 = copy.deepcopy(lpid)\n+ assert repr(lpid_2) == repr(lpid)\n", "FAIL_TO_PASS": ["test/test_regression_185.py::test_regression_185_deepcopy"]}], "all_FAIL_TO_PASS": ["test/test_feature_151.py::test_simple_array_oneOf", "test/test_regression_185.py::test_regression_185_deepcopy"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "canonical__operator-900_x2", "level": 2, "source": "swerebench", "repo": "canonical/operator", "image": "swerebench/sweb.eval.x86_64.canonical_1776_operator-900:latest", "base_commit": "e33ad4f221dd34cba5c81d3fd9eee868a6d866a7", "num_bugs": 2, "bugs": [{"instance_id": "canonical__operator-900", "base_commit": "e33ad4f221dd34cba5c81d3fd9eee868a6d866a7", "gold_patch": "diff --git a/ops/framework.py b/ops/framework.py\nindex 0ba99e1..c9da35e 100755\n--- a/ops/framework.py\n+++ b/ops/framework.py\n@@ -549,7 +549,7 @@ _event_regex = r'^(|.*/)on/[a-zA-Z_]+\\[\\d+\\]$'\n \n \n class Framework(Object):\n- \"\"\"Main interface to from the Charm to the Operator Framework internals.\"\"\"\n+ \"\"\"Main interface from the Charm to the Operator Framework internals.\"\"\"\n \n on = FrameworkEvents()\n \ndiff --git a/ops/model.py b/ops/model.py\nindex 7bf5576..141bd4f 100644\n--- a/ops/model.py\n+++ b/ops/model.py\n@@ -2926,7 +2926,7 @@ class _ModelBackend:\n args = [] # type: List[str]\n if id is not None:\n args.append(id)\n- if label is not None:\n+ elif label is not None: # elif because Juju secret-info-get doesn't allow id and label\n args.extend(['--label', label])\n result = self._run_for_secret('secret-info-get', *args, return_output=True, use_json=True)\n info_dicts = typing.cast(Dict[str, 'JsonObject'], result)\n", "test_patch": "diff --git a/ops/testing.py b/ops/testing.py\nindex 7082976..cf8912a 100755\n--- a/ops/testing.py\n+++ b/ops/testing.py\n@@ -1116,7 +1116,7 @@ class Harness(Generic[CharmType]):\n self._charm.on.leader_elected.emit()\n \n def set_planned_units(self, num_units: int) -> None:\n- \"\"\"Set the number of \"planned\" units that \"Application.planned_units\" should return.\n+ \"\"\"Set the number of \"planned\" units that \"Application.planned_units\" should return.\n \n In real world circumstances, this number will be the number of units in the\n application. E.g., this number will be the number of peers this unit has, plus one, as we\ndiff --git a/test/test_model.py b/test/test_model.py\nindex 7859feb..976fb77 100755\n--- a/test/test_model.py\n+++ b/test/test_model.py\n@@ -2993,14 +2993,34 @@ class TestSecretClass(unittest.TestCase):\n def test_get_info(self):\n fake_script(self, 'secret-info-get', \"\"\"echo '{\"x\": {\"label\": \"y\", \"revision\": 7}}'\"\"\")\n \n+ # Secret with ID only\n+ secret = self.make_secret(id='x')\n+ info = secret.get_info()\n+ self.assertEqual(info.id, 'secret:x')\n+ self.assertEqual(info.label, 'y')\n+ self.assertEqual(info.revision, 7)\n+\n+ # Secret with label only\n+ secret = self.make_secret(label='y')\n+ info = secret.get_info()\n+ self.assertEqual(info.id, 'secret:x')\n+ self.assertEqual(info.label, 'y')\n+ self.assertEqual(info.revision, 7)\n+\n+ # Secret with ID and label\n secret = self.make_secret(id='x', label='y')\n info = secret.get_info()\n self.assertEqual(info.id, 'secret:x')\n self.assertEqual(info.label, 'y')\n self.assertEqual(info.revision, 7)\n \n- self.assertEqual(fake_script_calls(self, clear=True),\n- [['secret-info-get', 'secret:x', '--label', 'y', '--format=json']])\n+ self.assertEqual(\n+ fake_script_calls(self, clear=True),\n+ [\n+ ['secret-info-get', 'secret:x', '--format=json'],\n+ ['secret-info-get', '--label', 'y', '--format=json'],\n+ ['secret-info-get', 'secret:x', '--format=json'],\n+ ])\n \n def test_set_content(self):\n fake_script(self, 'secret-set', \"\"\"exit 0\"\"\")\n", "FAIL_TO_PASS": ["test/test_model.py::TestSecretClass::test_get_info"]}, {"instance_id": "canonical__operator-903", "base_commit": "2cbee00aa38919d52525a143303332745e3de40c", "gold_patch": "diff --git a/ops/model.py b/ops/model.py\nindex 141bd4f..2ab4ff8 100644\n--- a/ops/model.py\n+++ b/ops/model.py\n@@ -276,6 +276,9 @@ class Model:\n \"\"\"\n if not (id or label):\n raise TypeError('Must provide an id or label, or both')\n+ if id is not None:\n+ # Canonicalize to \"secret:\" form for consistency in backend calls.\n+ id = Secret._canonicalize_id(id)\n try:\n content = self._backend.secret_get(id=id, label=label)\n return Secret(self._backend, id=id, label=label, content=content)\n", "test_patch": "diff --git a/test/test_model.py b/test/test_model.py\nindex 976fb77..35df7ea 100755\n--- a/test/test_model.py\n+++ b/test/test_model.py\n@@ -2841,7 +2841,18 @@ class TestSecrets(unittest.TestCase):\n self.assertEqual(secret.get_content(), {'foo': 'g'})\n \n self.assertEqual(fake_script_calls(self, clear=True),\n- [['secret-get', '123', '--format=json']])\n+ [['secret-get', 'secret:123', '--format=json']])\n+\n+ def test_get_secret_label(self):\n+ fake_script(self, 'secret-get', \"\"\"echo '{\"foo\": \"g\"}'\"\"\")\n+\n+ secret = self.model.get_secret(label='lbl')\n+ self.assertIsNone(secret.id)\n+ self.assertEqual(secret.label, 'lbl')\n+ self.assertEqual(secret.get_content(), {'foo': 'g'})\n+\n+ self.assertEqual(fake_script_calls(self, clear=True),\n+ [['secret-get', '--label', 'lbl', '--format=json']])\n \n def test_get_secret_id_and_label(self):\n fake_script(self, 'secret-get', \"\"\"echo '{\"foo\": \"h\"}'\"\"\")\n@@ -2852,7 +2863,7 @@ class TestSecrets(unittest.TestCase):\n self.assertEqual(secret.get_content(), {'foo': 'h'})\n \n self.assertEqual(fake_script_calls(self, clear=True),\n- [['secret-get', '123', '--label', 'l', '--format=json']])\n+ [['secret-get', 'secret:123', '--label', 'l', '--format=json']])\n \n def test_get_secret_no_args(self):\n with self.assertRaises(TypeError):\n", "FAIL_TO_PASS": ["test/test_model.py::TestSecrets::test_get_secret_id", "test/test_model.py::TestSecrets::test_get_secret_id_and_label"]}], "all_FAIL_TO_PASS": ["test/test_model.py::TestSecretClass::test_get_info", "test/test_model.py::TestSecrets::test_get_secret_id", "test/test_model.py::TestSecrets::test_get_secret_id_and_label"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "bear__python-twitter-416_x2", "level": 2, "source": "swerebench", "repo": "bear/python-twitter", "image": "swerebench/sweb.eval.x86_64.bear_1776_python-twitter-416:latest", "base_commit": "ae88240b902d857ba099dfd17f820e640c67557d", "num_bugs": 2, "bugs": [{"instance_id": "bear__python-twitter-416", "base_commit": "ae88240b902d857ba099dfd17f820e640c67557d", "gold_patch": "diff --git a/twitter/__init__.py b/twitter/__init__.py\nindex 87bb718..0534776 100644\n--- a/twitter/__init__.py\n+++ b/twitter/__init__.py\n@@ -23,7 +23,7 @@ __author__ = 'The Python-Twitter Developers'\n __email__ = 'python-twitter@googlegroups.com'\n __copyright__ = 'Copyright (c) 2007-2016 The Python-Twitter Developers'\n __license__ = 'Apache License 2.0'\n-__version__ = '3.2'\n+__version__ = '3.2.1'\n __url__ = 'https://github.com/bear/python-twitter'\n __download_url__ = 'https://pypi.python.org/pypi/python-twitter'\n __description__ = 'A Python wrapper around the Twitter API'\ndiff --git a/twitter/twitter_utils.py b/twitter/twitter_utils.py\nindex 081d1ed..0b2af5b 100644\n--- a/twitter/twitter_utils.py\n+++ b/twitter/twitter_utils.py\n@@ -161,12 +161,13 @@ def calc_expected_status_length(status, short_url_length=23):\n Expected length of the status message as an integer.\n \n \"\"\"\n- replaced_chars = 0\n- status_length = len(status)\n- match = re.findall(URL_REGEXP, status)\n- if len(match) >= 1:\n- replaced_chars = len(''.join(match))\n- status_length = status_length - replaced_chars + (short_url_length * len(match))\n+ status_length = 0\n+ for word in re.split(r'\\s', status):\n+ if is_url(word):\n+ status_length += short_url_length\n+ else:\n+ status_length += len(word)\n+ status_length += len(re.findall(r'\\s', status))\n return status_length\n \n \n", "test_patch": "diff --git a/tests/test_twitter_utils.py b/tests/test_twitter_utils.py\nindex 3ca619f..b021e34 100644\n--- a/tests/test_twitter_utils.py\n+++ b/tests/test_twitter_utils.py\n@@ -5,6 +5,7 @@ import unittest\n import twitter\n \n from twitter.twitter_utils import (\n+ calc_expected_status_length,\n parse_media_file\n )\n \n@@ -58,3 +59,18 @@ class ApiTest(unittest.TestCase):\n self.assertRaises(\n twitter.TwitterError,\n lambda: twitter.twitter_utils.enf_type('test', int, 'hi'))\n+\n+ def test_calc_expected_status_length(self):\n+ status = 'hi a tweet there'\n+ len_status = calc_expected_status_length(status)\n+ self.assertEqual(len_status, 16)\n+\n+ def test_calc_expected_status_length_with_url(self):\n+ status = 'hi a tweet there example.com'\n+ len_status = calc_expected_status_length(status)\n+ self.assertEqual(len_status, 40)\n+\n+ def test_calc_expected_status_length_with_url_and_extra_spaces(self):\n+ status = 'hi a tweet there example.com'\n+ len_status = calc_expected_status_length(status)\n+ self.assertEqual(len_status, 63)\n", "FAIL_TO_PASS": ["tests/test_twitter_utils.py::ApiTest::test_calc_expected_status_length_with_url", "tests/test_twitter_utils.py::ApiTest::test_calc_expected_status_length_with_url_and_extra_spaces"]}, {"instance_id": "bear__python-twitter-439", "base_commit": "c28e9fb02680f30c9c56019f6836c2b47fa1d73a", "gold_patch": "diff --git a/twitter/api.py b/twitter/api.py\nindex 94ec354..d41a648 100644\n--- a/twitter/api.py\n+++ b/twitter/api.py\n@@ -1026,6 +1026,7 @@ class Api(object):\n parameters['attachment_url'] = attachment_url\n \n if media:\n+ chunked_types = ['video/mp4', 'video/quicktime', 'image/gif']\n media_ids = []\n if isinstance(media, int):\n media_ids.append(media)\n@@ -1041,9 +1042,8 @@ class Api(object):\n _, _, file_size, media_type = parse_media_file(media_file)\n if media_type == 'image/gif' or media_type == 'video/mp4':\n raise TwitterError(\n- 'You cannot post more than 1 GIF or 1 video in a '\n- 'single status.')\n- if file_size > self.chunk_size:\n+ 'You cannot post more than 1 GIF or 1 video in a single status.')\n+ if file_size > self.chunk_size or media_type in chunked_types:\n media_id = self.UploadMediaChunked(\n media=media_file,\n additional_owners=media_additional_owners,\n@@ -1055,13 +1055,11 @@ class Api(object):\n media_category=media_category)\n media_ids.append(media_id)\n else:\n- _, _, file_size, _ = parse_media_file(media)\n- if file_size > self.chunk_size:\n- media_ids.append(\n- self.UploadMediaChunked(media, media_additional_owners))\n+ _, _, file_size, media_type = parse_media_file(media)\n+ if file_size > self.chunk_size or media_type in chunked_types:\n+ media_ids.append(self.UploadMediaChunked(media, media_additional_owners))\n else:\n- media_ids.append(\n- self.UploadMediaSimple(media, media_additional_owners))\n+ media_ids.append(self.UploadMediaSimple(media, media_additional_owners))\n parameters['media_ids'] = ','.join([str(mid) for mid in media_ids])\n \n if latitude is not None and longitude is not None:\n@@ -1263,7 +1261,7 @@ class Api(object):\n \n try:\n media_fp.close()\n- except:\n+ except Exception as e:\n pass\n \n return True\ndiff --git a/twitter/twitter_utils.py b/twitter/twitter_utils.py\nindex 0b2af5b..66ce8b2 100644\n--- a/twitter/twitter_utils.py\n+++ b/twitter/twitter_utils.py\n@@ -223,8 +223,8 @@ def parse_media_file(passed_media):\n # Otherwise, if a file object was passed in the first place,\n # create the standard reference to media_file (i.e., rename it to fp).\n else:\n- if passed_media.mode != 'rb':\n- raise TwitterError({'message': 'File mode must be \"rb\".'})\n+ if passed_media.mode not in ['rb', 'rb+', 'w+b']:\n+ raise TwitterError('File mode must be \"rb\" or \"rb+\"')\n filename = os.path.basename(passed_media.name)\n data_file = passed_media\n \n@@ -233,7 +233,7 @@ def parse_media_file(passed_media):\n \n try:\n data_file.seek(0)\n- except:\n+ except Exception as e:\n pass\n \n media_type = mimetypes.guess_type(os.path.basename(filename))[0]\n", "test_patch": "diff --git a/tests/test_api_30.py b/tests/test_api_30.py\nindex b966c70..67d7b33 100644\n--- a/tests/test_api_30.py\n+++ b/tests/test_api_30.py\n@@ -2,9 +2,15 @@\n from __future__ import unicode_literals, print_function\n \n import json\n+import os\n import re\n import sys\n+from tempfile import NamedTemporaryFile\n import unittest\n+try:\n+ from unittest.mock import patch\n+except ImportError:\n+ from mock import patch\n import warnings\n \n import twitter\n@@ -1713,3 +1719,16 @@ class ApiTest(unittest.TestCase):\n with warnings.catch_warnings(record=True) as w:\n resp = self.api.UpdateBackgroundImage(image='testdata/168NQ.jpg')\n self.assertTrue(issubclass(w[0].category, DeprecationWarning))\n+\n+ @responses.activate\n+ @patch('twitter.api.Api.UploadMediaChunked')\n+ def test_UploadSmallVideoUsesChunkedData(self, mocker):\n+ responses.add(POST, DEFAULT_URL, body='{}')\n+ video = NamedTemporaryFile(suffix='.mp4')\n+ video.write(b'10' * 1024)\n+ video.seek(0, 0)\n+\n+ resp = self.api.PostUpdate('test', media=video)\n+ assert os.path.getsize(video.name) <= 1024 * 1024\n+ assert isinstance(resp, twitter.Status)\n+ assert twitter.api.Api.UploadMediaChunked.called\n", "FAIL_TO_PASS": ["tests/test_api_30.py::ApiTest::test_UploadSmallVideoUsesChunkedData"]}], "all_FAIL_TO_PASS": ["tests/test_twitter_utils.py::ApiTest::test_calc_expected_status_length_with_url", "tests/test_twitter_utils.py::ApiTest::test_calc_expected_status_length_with_url_and_extra_spaces", "tests/test_api_30.py::ApiTest::test_UploadSmallVideoUsesChunkedData"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "EvoluxBR__greenswitch-83_x2", "level": 2, "source": "swerebench", "repo": "EvoluxBR/greenswitch", "image": "swerebench/sweb.eval.x86_64.evoluxbr_1776_greenswitch-83:latest", "base_commit": "eb210f31ff723bba75d83b09d898f7e1273eb63b", "num_bugs": 2, "bugs": [{"instance_id": "EvoluxBR__greenswitch-83", "base_commit": "eb210f31ff723bba75d83b09d898f7e1273eb63b", "gold_patch": "diff --git a/greenswitch/esl.py b/greenswitch/esl.py\nindex ef9a397..6c25f29 100644\n--- a/greenswitch/esl.py\n+++ b/greenswitch/esl.py\n@@ -217,7 +217,7 @@ class ESLProtocol(object):\n if self.connected:\n try:\n self.send('exit')\n- except (NotConnectedError, socket.error):\n+ except (NotConnectedError, socket.error, OutboundSessionHasGoneAway):\n pass\n self._run = False\n if self._receive_events_greenlet:\n", "test_patch": "diff --git a/tests/test_outbound_session.py b/tests/test_outbound_session.py\nindex ed4086c..69205b3 100644\n--- a/tests/test_outbound_session.py\n+++ b/tests/test_outbound_session.py\n@@ -68,3 +68,13 @@ class TestWhileConnectedMethod(unittest.TestCase):\n with self.assertRaises(ValueError):\n with self.outbound_session.while_connected():\n raise ValueError(\"http exception\")\n+\n+ def test_raising_OutboundSessionHasGoneAway_in_session_stop_will_pass(self):\n+ # make outbound_session.send raise OutboundSessionHasGoneAway\n+ self.outbound_session.send = mock.MagicMock(side_effect=esl.OutboundSessionHasGoneAway)\n+ # mock sock.close\n+ self.outbound_session.sock.close = mock.MagicMock()\n+\n+ # stop and assert sock.close is called\n+ self.outbound_session.stop()\n+ assert self.outbound_session.sock.close.called\n", "FAIL_TO_PASS": ["tests/test_outbound_session.py::TestWhileConnectedMethod::test_raising_OutboundSessionHasGoneAway_in_session_stop_will_pass"]}, {"instance_id": "EvoluxBR__greenswitch-85", "base_commit": "169a419103712c813f4b531480184a7e228bafe4", "gold_patch": "diff --git a/greenswitch/esl.py b/greenswitch/esl.py\nindex 6c25f29..9f9bdaf 100644\n--- a/greenswitch/esl.py\n+++ b/greenswitch/esl.py\n@@ -359,7 +359,12 @@ class OutboundSession(ESLProtocol):\n if self._outbound_connected:\n return self.session_data\n \n- resp = self.send('connect')\n+ try:\n+ resp = self.send('connect')\n+ except OutboundSessionHasGoneAway as e:\n+ # cleanup before raising exception\n+ self.stop()\n+ raise e\n self.session_data = resp.headers\n self._outbound_connected = True\n \n", "test_patch": "diff --git a/tests/test_outbound_session.py b/tests/test_outbound_session.py\nindex 69205b3..dc5a863 100644\n--- a/tests/test_outbound_session.py\n+++ b/tests/test_outbound_session.py\n@@ -25,6 +25,23 @@ class TestOutboundSession(unittest.TestCase):\n with self.assertRaises(esl.OutboundSessionHasGoneAway):\n self.outbound_session.raise_if_disconnected()\n \n+ def test_raising_OutboundSessionHasGoneAway_in_session_connect_will_call_sock_close(self):\n+ # Here we are socket connected, but not freeswitch connected\n+ # So any exception raised in session.connect should call sock.close\n+ self.outbound_session.connected = False\n+\n+ # make outbound_session.send raise OutboundSessionHasGoneAway\n+ self.outbound_session.send = mock.MagicMock(side_effect=esl.OutboundSessionHasGoneAway)\n+\n+ # mock sock.close\n+ self.outbound_session.sock.close = mock.MagicMock()\n+\n+ # attempt to connect and assert sock.close is called\n+ with self.assertRaises(esl.OutboundSessionHasGoneAway):\n+ self.outbound_session.connect()\n+\n+ assert self.outbound_session.sock.close.called\n+\n \n @pytest.mark.usefixtures(\"outbound_session\")\n @pytest.mark.usefixtures(\"disconnect_event\")\n", "FAIL_TO_PASS": ["tests/test_outbound_session.py::TestOutboundSession::test_raising_OutboundSessionHasGoneAway_in_session_connect_will_call_sock_close"]}], "all_FAIL_TO_PASS": ["tests/test_outbound_session.py::TestWhileConnectedMethod::test_raising_OutboundSessionHasGoneAway_in_session_stop_will_pass", "tests/test_outbound_session.py::TestOutboundSession::test_raising_OutboundSessionHasGoneAway_in_session_connect_will_call_sock_close"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "encode__httpx-377_x2", "level": 2, "source": "swerebench", "repo": "encode/httpx", "image": "swerebench/sweb.eval.x86_64.encode_1776_httpx-377:latest", "base_commit": "e62e5c3758b10a8830c751acbe588d7b572a9957", "num_bugs": 2, "bugs": [{"instance_id": "encode__httpx-377", "base_commit": "e62e5c3758b10a8830c751acbe588d7b572a9957", "gold_patch": "diff --git a/httpx/client.py b/httpx/client.py\nindex 30beeb7..73b3069 100644\n--- a/httpx/client.py\n+++ b/httpx/client.py\n@@ -107,13 +107,6 @@ class BaseClient:\n else:\n self.base_url = URL(base_url)\n \n- if proxies is None and trust_env:\n- proxies = typing.cast(ProxiesTypes, get_environment_proxies())\n-\n- self.proxies: typing.Dict[str, AsyncDispatcher] = _proxies_to_dispatchers(\n- proxies\n- )\n-\n if params is None:\n params = {}\n \n@@ -125,6 +118,20 @@ class BaseClient:\n self.dispatch = async_dispatch\n self.concurrency_backend = backend\n \n+ if proxies is None and trust_env:\n+ proxies = typing.cast(ProxiesTypes, get_environment_proxies())\n+\n+ self.proxies: typing.Dict[str, AsyncDispatcher] = _proxies_to_dispatchers(\n+ proxies,\n+ verify=verify,\n+ cert=cert,\n+ timeout=timeout,\n+ http_versions=http_versions,\n+ pool_limits=pool_limits,\n+ backend=backend,\n+ trust_env=trust_env,\n+ )\n+\n @property\n def headers(self) -> Headers:\n return self._headers\n@@ -196,16 +203,11 @@ class BaseClient:\n cert: CertTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n if request.url.scheme not in (\"http\", \"https\"):\n raise InvalidURL('URL scheme must be \"http\" or \"https\".')\n \n- if proxies is not None:\n- dispatch_proxies = _proxies_to_dispatchers(proxies)\n- else:\n- dispatch_proxies = self.proxies\n- dispatch = self._dispatcher_for_request(request, dispatch_proxies)\n+ dispatch = self._dispatcher_for_request(request, self.proxies)\n \n async def get_response(request: AsyncRequest) -> AsyncResponse:\n try:\n@@ -351,7 +353,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self.request(\n \"GET\",\n@@ -366,7 +367,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def options(\n@@ -383,7 +383,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self.request(\n \"OPTIONS\",\n@@ -398,7 +397,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def head(\n@@ -415,7 +413,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self.request(\n \"HEAD\",\n@@ -430,7 +427,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def post(\n@@ -450,7 +446,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self.request(\n \"POST\",\n@@ -468,7 +463,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def put(\n@@ -488,7 +482,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self.request(\n \"PUT\",\n@@ -506,7 +499,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def patch(\n@@ -526,7 +518,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self.request(\n \"PATCH\",\n@@ -544,7 +535,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def delete(\n@@ -564,7 +554,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self.request(\n \"DELETE\",\n@@ -582,7 +571,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def request(\n@@ -603,7 +591,6 @@ class AsyncClient(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n request = self.build_request(\n method=method,\n@@ -624,7 +611,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n return response\n \n@@ -639,7 +625,6 @@ class AsyncClient(BaseClient):\n cert: CertTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> AsyncResponse:\n return await self._get_response(\n request=request,\n@@ -650,7 +635,6 @@ class AsyncClient(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n async def close(self) -> None:\n@@ -729,7 +713,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n request = self.build_request(\n method=method,\n@@ -750,7 +733,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n return response\n \n@@ -765,7 +747,6 @@ class Client(BaseClient):\n cert: CertTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n concurrency_backend = self.concurrency_backend\n \n@@ -779,7 +760,6 @@ class Client(BaseClient):\n \"cert\": cert,\n \"timeout\": timeout,\n \"trust_env\": trust_env,\n- \"proxies\": proxies,\n }\n async_response = concurrency_backend.run(coroutine, *args, **kwargs)\n \n@@ -824,7 +804,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n return self.request(\n \"GET\",\n@@ -839,7 +818,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n def options(\n@@ -856,7 +834,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n return self.request(\n \"OPTIONS\",\n@@ -871,7 +848,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n def head(\n@@ -888,7 +864,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n return self.request(\n \"HEAD\",\n@@ -903,7 +878,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n def post(\n@@ -923,7 +897,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n return self.request(\n \"POST\",\n@@ -941,7 +914,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n def put(\n@@ -961,7 +933,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n return self.request(\n \"PUT\",\n@@ -979,7 +950,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n def patch(\n@@ -999,7 +969,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n return self.request(\n \"PATCH\",\n@@ -1017,7 +986,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n def delete(\n@@ -1037,7 +1005,6 @@ class Client(BaseClient):\n verify: VerifyTypes = None,\n timeout: TimeoutTypes = None,\n trust_env: bool = None,\n- proxies: ProxiesTypes = None,\n ) -> Response:\n return self.request(\n \"DELETE\",\n@@ -1055,7 +1022,6 @@ class Client(BaseClient):\n cert=cert,\n timeout=timeout,\n trust_env=trust_env,\n- proxies=proxies,\n )\n \n def close(self) -> None:\n@@ -1074,16 +1040,32 @@ class Client(BaseClient):\n self.close()\n \n \n-def _proxy_from_url(url: URLTypes) -> AsyncDispatcher:\n- url = URL(url)\n- if url.scheme in (\"http\", \"https\"):\n- return HTTPProxy(url)\n- raise ValueError(f\"Unknown proxy for {url!r}\")\n-\n-\n def _proxies_to_dispatchers(\n- proxies: typing.Optional[ProxiesTypes]\n+ proxies: typing.Optional[ProxiesTypes],\n+ verify: VerifyTypes,\n+ cert: typing.Optional[CertTypes],\n+ timeout: TimeoutTypes,\n+ http_versions: typing.Optional[HTTPVersionTypes],\n+ pool_limits: PoolLimits,\n+ backend: ConcurrencyBackend,\n+ trust_env: bool,\n ) -> typing.Dict[str, AsyncDispatcher]:\n+ def _proxy_from_url(url: URLTypes) -> AsyncDispatcher:\n+ nonlocal verify, cert, timeout, http_versions, pool_limits, backend, trust_env\n+ url = URL(url)\n+ if url.scheme in (\"http\", \"https\"):\n+ return HTTPProxy(\n+ url,\n+ verify=verify,\n+ cert=cert,\n+ timeout=timeout,\n+ pool_limits=pool_limits,\n+ backend=backend,\n+ trust_env=trust_env,\n+ http_versions=http_versions,\n+ )\n+ raise ValueError(f\"Unknown proxy for {url!r}\")\n+\n if proxies is None:\n return {}\n elif isinstance(proxies, (str, URL)):\ndiff --git a/httpx/concurrency/asyncio.py b/httpx/concurrency/asyncio.py\nindex 696e32c..5d35014 100644\n--- a/httpx/concurrency/asyncio.py\n+++ b/httpx/concurrency/asyncio.py\n@@ -81,6 +81,12 @@ class TCPStream(BaseTCPStream):\n except asyncio.TimeoutError:\n if should_raise:\n raise ReadTimeout() from None\n+ # FIX(py3.6): yield control back to the event loop to give it a chance\n+ # to cancel `.read(n)` before we retry.\n+ # This prevents concurrent `.read()` calls, which asyncio\n+ # doesn't seem to allow on 3.6.\n+ # See: https://github.com/encode/httpx/issues/382\n+ await asyncio.sleep(0)\n \n return data\n \ndiff --git a/httpx/config.py b/httpx/config.py\nindex b7c5ee6..f0f694f 100644\n--- a/httpx/config.py\n+++ b/httpx/config.py\n@@ -6,7 +6,7 @@ from pathlib import Path\n import certifi\n \n from .__version__ import __version__\n-from .utils import get_ca_bundle_from_env\n+from .utils import get_ca_bundle_from_env, get_logger\n \n CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]\n VerifyTypes = typing.Union[str, bool, ssl.SSLContext]\n@@ -40,6 +40,9 @@ DEFAULT_CIPHERS = \":\".join(\n )\n \n \n+logger = get_logger(__name__)\n+\n+\n class SSLConfig:\n \"\"\"\n SSL Configuration.\n@@ -91,6 +94,14 @@ class SSLConfig:\n ) -> ssl.SSLContext:\n http_versions = HTTPVersionConfig() if http_versions is None else http_versions\n \n+ logger.debug(\n+ f\"load_ssl_context \"\n+ f\"verify={self.verify!r} \"\n+ f\"cert={self.cert!r} \"\n+ f\"trust_env={self.trust_env!r} \"\n+ f\"http_versions={http_versions!r}\"\n+ )\n+\n if self.ssl_context is None:\n self.ssl_context = (\n self.load_ssl_context_verify(http_versions=http_versions)\n@@ -152,8 +163,10 @@ class SSLConfig:\n pass\n \n if ca_bundle_path.is_file():\n+ logger.debug(f\"load_verify_locations cafile={ca_bundle_path!s}\")\n context.load_verify_locations(cafile=str(ca_bundle_path))\n elif ca_bundle_path.is_dir():\n+ logger.debug(f\"load_verify_locations capath={ca_bundle_path!s}\")\n context.load_verify_locations(capath=str(ca_bundle_path))\n \n self._load_client_certs(context)\ndiff --git a/httpx/dispatch/proxy_http.py b/httpx/dispatch/proxy_http.py\nindex fe8bbd3..be2e289 100644\n--- a/httpx/dispatch/proxy_http.py\n+++ b/httpx/dispatch/proxy_http.py\n@@ -7,6 +7,7 @@ from ..config import (\n DEFAULT_POOL_LIMITS,\n DEFAULT_TIMEOUT_CONFIG,\n CertTypes,\n+ HTTPVersionTypes,\n PoolLimits,\n SSLConfig,\n TimeoutTypes,\n@@ -51,8 +52,10 @@ class HTTPProxy(ConnectionPool):\n proxy_mode: HTTPProxyMode = HTTPProxyMode.DEFAULT,\n verify: VerifyTypes = True,\n cert: CertTypes = None,\n+ trust_env: bool = None,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,\n+ http_versions: HTTPVersionTypes = None,\n backend: ConcurrencyBackend = None,\n ):\n \n@@ -62,6 +65,8 @@ class HTTPProxy(ConnectionPool):\n timeout=timeout,\n pool_limits=pool_limits,\n backend=backend,\n+ trust_env=trust_env,\n+ http_versions=http_versions,\n )\n \n self.proxy_url = URL(proxy_url)\ndiff --git a/noxfile.py b/noxfile.py\nindex 64dae62..c7ada4f 100644\n--- a/noxfile.py\n+++ b/noxfile.py\n@@ -20,12 +20,15 @@ def lint(session):\n @nox.session(reuse_venv=True)\n def check(session):\n session.install(\n- \"black\", \"flake8\", \"flake8-bugbear\", \"flake8-comprehensions\", \"mypy\"\n+ \"black\", \"flake8\", \"flake8-bugbear\", \"flake8-comprehensions\", \"isort\", \"mypy\"\n )\n \n session.run(\"black\", \"--check\", \"--diff\", \"--target-version=py36\", *source_files)\n session.run(\"flake8\", *source_files)\n session.run(\"mypy\", \"httpx\")\n+ session.run(\n+ \"isort\", \"--check\", \"--diff\", \"--project=httpx\", \"--recursive\", *source_files\n+ )\n \n \n @nox.session(reuse_venv=True)\n", "test_patch": "diff --git a/tests/client/test_proxies.py b/tests/client/test_proxies.py\nindex 19521b7..ba59677 100644\n--- a/tests/client/test_proxies.py\n+++ b/tests/client/test_proxies.py\n@@ -27,3 +27,22 @@ def test_proxies_parameter(proxies, expected_proxies):\n assert client.proxies[proxy_key].proxy_url == url\n \n assert len(expected_proxies) == len(client.proxies)\n+\n+\n+def test_proxies_has_same_properties_as_dispatch():\n+ client = httpx.AsyncClient(proxies=\"http://127.0.0.1\")\n+ pool = client.dispatch\n+ proxy = client.proxies[\"all\"]\n+\n+ assert isinstance(pool, httpx.ConnectionPool)\n+ assert isinstance(proxy, httpx.HTTPProxy)\n+\n+ for prop in [\n+ \"verify\",\n+ \"cert\",\n+ \"timeout\",\n+ \"pool_limits\",\n+ \"http_versions\",\n+ \"backend\",\n+ ]:\n+ assert getattr(pool, prop) == getattr(proxy, prop)\ndiff --git a/tests/test_timeouts.py b/tests/test_timeouts.py\nindex 8dc1e08..ff5273b 100644\n--- a/tests/test_timeouts.py\n+++ b/tests/test_timeouts.py\n@@ -2,6 +2,7 @@ import pytest\n \n from httpx import (\n AsyncClient,\n+ Client,\n ConnectTimeout,\n PoolLimits,\n PoolTimeout,\n@@ -47,3 +48,13 @@ async def test_pool_timeout(server, backend):\n await client.get(\"http://localhost:8000/\")\n \n await response.read()\n+\n+\n+def test_sync_infinite_timeout(server):\n+ \"\"\"Regression test for a bug that occurred under Python 3.6.\n+\n+ See: https://github.com/encode/httpx/issues/382\n+ \"\"\"\n+ no_timeout = TimeoutConfig()\n+ with Client(timeout=no_timeout) as client:\n+ client.get(server.url.copy_with(path=\"/slow_response/50\"))\n", "FAIL_TO_PASS": ["tests/client/test_proxies.py::test_proxies_has_same_properties_as_dispatch"]}, {"instance_id": "encode__httpx-386", "base_commit": "31730e709597baaa7b2364fee041dfa985169789", "gold_patch": "diff --git a/httpx/models.py b/httpx/models.py\nindex f70fdf4..136aa41 100644\n--- a/httpx/models.py\n+++ b/httpx/models.py\n@@ -32,6 +32,7 @@ from .exceptions import (\n from .multipart import multipart_encode\n from .status_codes import StatusCode\n from .utils import (\n+ flatten_queryparams,\n guess_json_utf,\n is_known_encoding,\n normalize_header_key,\n@@ -51,7 +52,7 @@ URLTypes = typing.Union[\"URL\", str]\n \n QueryParamTypes = typing.Union[\n \"QueryParams\",\n- typing.Mapping[str, PrimitiveData],\n+ typing.Mapping[str, typing.Union[PrimitiveData, typing.Sequence[PrimitiveData]]],\n typing.List[typing.Tuple[str, PrimitiveData]],\n str,\n ]\n@@ -311,14 +312,15 @@ class QueryParams(typing.Mapping[str, str]):\n \n value = args[0] if args else kwargs\n \n+ items: typing.Sequence[typing.Tuple[str, PrimitiveData]]\n if isinstance(value, str):\n items = parse_qsl(value)\n elif isinstance(value, QueryParams):\n items = value.multi_items()\n elif isinstance(value, list):\n- items = value # type: ignore\n+ items = value\n else:\n- items = value.items() # type: ignore\n+ items = flatten_queryparams(value)\n \n self._list = [(str(k), str_query_param(v)) for k, v in items]\n self._dict = {str(k): str_query_param(v) for k, v in items}\ndiff --git a/httpx/utils.py b/httpx/utils.py\nindex c8fcb1e..8aea5e7 100644\n--- a/httpx/utils.py\n+++ b/httpx/utils.py\n@@ -1,4 +1,5 @@\n import codecs\n+import collections\n import logging\n import netrc\n import os\n@@ -11,6 +12,9 @@ from time import perf_counter\n from types import TracebackType\n from urllib.request import getproxies\n \n+if typing.TYPE_CHECKING: # pragma: no cover\n+ from .models import PrimitiveData\n+\n \n def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:\n \"\"\"\n@@ -30,7 +34,7 @@ def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:\n return value.encode(encoding or \"ascii\")\n \n \n-def str_query_param(value: typing.Optional[typing.Union[str, int, float, bool]]) -> str:\n+def str_query_param(value: \"PrimitiveData\") -> str:\n \"\"\"\n Coerce a primitive data type into a string value for query params.\n \n@@ -256,6 +260,31 @@ def unquote(value: str) -> str:\n return value[1:-1] if value[0] == value[-1] == '\"' else value\n \n \n+def flatten_queryparams(\n+ queryparams: typing.Mapping[\n+ str, typing.Union[\"PrimitiveData\", typing.Sequence[\"PrimitiveData\"]]\n+ ]\n+) -> typing.List[typing.Tuple[str, \"PrimitiveData\"]]:\n+ \"\"\"\n+ Convert a mapping of query params into a flat list of two-tuples\n+ representing each item.\n+\n+ Example:\n+ >>> flatten_queryparams_values({\"q\": \"httpx\", \"tag\": [\"python\", \"dev\"]})\n+ [(\"q\", \"httpx), (\"tag\", \"python\"), (\"tag\", \"dev\")]\n+ \"\"\"\n+ items = []\n+\n+ for k, v in queryparams.items():\n+ if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):\n+ for u in v:\n+ items.append((k, u))\n+ else:\n+ items.append((k, typing.cast(\"PrimitiveData\", v)))\n+\n+ return items\n+\n+\n class ElapsedTimer:\n def __init__(self) -> None:\n self.start: float = perf_counter()\n", "test_patch": "diff --git a/tests/models/test_queryparams.py b/tests/models/test_queryparams.py\nindex 8c4df49..1303170 100644\n--- a/tests/models/test_queryparams.py\n+++ b/tests/models/test_queryparams.py\n@@ -1,8 +1,18 @@\n+import pytest\n+\n from httpx import QueryParams\n \n \n-def test_queryparams():\n- q = QueryParams(\"a=123&a=456&b=789\")\n+@pytest.mark.parametrize(\n+ \"source\",\n+ [\n+ \"a=123&a=456&b=789\",\n+ {\"a\": [\"123\", \"456\"], \"b\": 789},\n+ {\"a\": (\"123\", \"456\"), \"b\": 789},\n+ ],\n+)\n+def test_queryparams(source):\n+ q = QueryParams(source)\n assert \"a\" in q\n assert \"A\" not in q\n assert \"c\" not in q\n", "FAIL_TO_PASS": ["tests/models/test_queryparams.py::test_queryparams[source1]", "tests/models/test_queryparams.py::test_queryparams[source2]"]}], "all_FAIL_TO_PASS": ["tests/client/test_proxies.py::test_proxies_has_same_properties_as_dispatch", "tests/models/test_queryparams.py::test_queryparams[source1]", "tests/models/test_queryparams.py::test_queryparams[source2]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "doccano__doccano-1557_x2", "level": 2, "source": "swerebench", "repo": "doccano/doccano", "image": "swerebench/sweb.eval.x86_64.doccano_1776_doccano-1557:latest", "base_commit": "217cc85348972fcf38f3c58284dd2168db2bd3bb", "num_bugs": 2, "bugs": [{"instance_id": "doccano__doccano-1557", "base_commit": "217cc85348972fcf38f3c58284dd2168db2bd3bb", "gold_patch": "diff --git a/backend/api/views/download/data.py b/backend/api/views/download/data.py\nindex 68978184..79bfe7e8 100644\n--- a/backend/api/views/download/data.py\n+++ b/backend/api/views/download/data.py\n@@ -1,3 +1,4 @@\n+import json\n from typing import Any, Dict, List\n \n \n@@ -16,4 +17,10 @@ class Record:\n self.metadata = metadata\n \n def __str__(self):\n- return f'{self.data}\\t{self.label}'\n+ return json.dumps({\n+ 'id': self.id,\n+ 'data': self.data,\n+ 'label': self.label,\n+ 'user': self.user,\n+ 'metadata': self.metadata\n+ })\ndiff --git a/backend/api/views/download/writer.py b/backend/api/views/download/writer.py\nindex dd0e88b4..5de1264e 100644\n--- a/backend/api/views/download/writer.py\n+++ b/backend/api/views/download/writer.py\n@@ -90,7 +90,7 @@ class CsvWriter(BaseWriter):\n \n def create_header(self, records: List[Record]) -> Iterable[str]:\n header = ['id', 'data', 'label']\n- header += list(itertools.chain(*[r.metadata.keys() for r in records]))\n+ header += sorted(set(itertools.chain(*[r.metadata.keys() for r in records])))\n return header\n \n \n", "test_patch": "diff --git a/backend/api/tests/download/__init__.py b/backend/api/tests/download/__init__.py\nnew file mode 100644\nindex 00000000..e69de29b\ndiff --git a/backend/api/tests/download/test_writer.py b/backend/api/tests/download/test_writer.py\nnew file mode 100644\nindex 00000000..2c48cb92\n--- /dev/null\n+++ b/backend/api/tests/download/test_writer.py\n@@ -0,0 +1,53 @@\n+import unittest\n+from unittest.mock import call, patch\n+\n+from ...views.download.data import Record\n+from ...views.download.writer import CsvWriter\n+\n+\n+class TestCSVWriter(unittest.TestCase):\n+\n+ def setUp(self):\n+ self.records = [\n+ Record(id=0, data='exampleA', label=['labelA'], user='admin', metadata={'hidden': 'secretA'}),\n+ Record(id=1, data='exampleB', label=['labelB'], user='admin', metadata={'hidden': 'secretB'}),\n+ Record(id=2, data='exampleC', label=['labelC'], user='admin', metadata={'meta': 'secretC'})\n+ ]\n+\n+ def test_create_header(self):\n+ writer = CsvWriter('.')\n+ header = writer.create_header(self.records)\n+ expected = ['id', 'data', 'label', 'hidden', 'meta']\n+ self.assertEqual(header, expected)\n+\n+ def test_create_line(self):\n+ writer = CsvWriter('.')\n+ record = self.records[0]\n+ line = writer.create_line(record)\n+ expected = {\n+ 'id': record.id,\n+ 'data': record.data,\n+ 'label': record.label[0],\n+ 'hidden': 'secretA'\n+ }\n+ self.assertEqual(line, expected)\n+\n+ @patch('os.remove')\n+ @patch('zipfile.ZipFile')\n+ @patch('csv.DictWriter.writerow')\n+ @patch('builtins.open')\n+ def test_dump(self, mock_open_file, csv_io, zip_io, mock_remove_file):\n+ writer = CsvWriter('.')\n+ writer.write(self.records)\n+\n+ self.assertEqual(mock_open_file.call_count, 1)\n+ mock_open_file.assert_called_with('./admin.csv', mode='a', encoding='utf-8')\n+\n+ self.assertEqual(csv_io.call_count, len(self.records) + 1) # +1 is for a header\n+ calls = [\n+ call({'id': 'id', 'data': 'data', 'label': 'label', 'hidden': 'hidden', 'meta': 'meta'}),\n+ call({'id': 0, 'data': 'exampleA', 'label': 'labelA', 'hidden': 'secretA'}),\n+ call({'id': 1, 'data': 'exampleB', 'label': 'labelB', 'hidden': 'secretB'}),\n+ call({'id': 2, 'data': 'exampleC', 'label': 'labelC', 'meta': 'secretC'})\n+ ]\n+ csv_io.assert_has_calls(calls)\n", "FAIL_TO_PASS": ["backend/api/tests/download/test_writer.py::TestCSVWriter::test_create_header"]}, {"instance_id": "doccano__doccano-1558", "base_commit": "0d7bf054e619c144ec84fcf18f9457af8822a204", "gold_patch": "diff --git a/backend/api/views/download/writer.py b/backend/api/views/download/writer.py\nindex 5de1264e..a4d5293a 100644\n--- a/backend/api/views/download/writer.py\n+++ b/backend/api/views/download/writer.py\n@@ -84,7 +84,7 @@ class CsvWriter(BaseWriter):\n return {\n 'id': record.id,\n 'data': record.data,\n- 'label': '#'.join(record.label),\n+ 'label': '#'.join(sorted(record.label)),\n **record.metadata\n }\n \n@@ -144,6 +144,7 @@ class FastTextWriter(LineWriter):\n \n def create_line(self, record):\n line = [f'__label__{label}' for label in record.label]\n+ line.sort()\n line.append(record.data)\n line = ' '.join(line)\n return line\n", "test_patch": "diff --git a/backend/api/tests/download/test_writer.py b/backend/api/tests/download/test_writer.py\nindex 2c48cb92..720244dd 100644\n--- a/backend/api/tests/download/test_writer.py\n+++ b/backend/api/tests/download/test_writer.py\n@@ -32,6 +32,16 @@ class TestCSVWriter(unittest.TestCase):\n }\n self.assertEqual(line, expected)\n \n+ def test_label_order(self):\n+ writer = CsvWriter('.')\n+ record1 = Record(id=0, data='', label=['labelA', 'labelB'], user='', metadata={})\n+ record2 = Record(id=0, data='', label=['labelB', 'labelA'], user='', metadata={})\n+ line1 = writer.create_line(record1)\n+ line2 = writer.create_line(record2)\n+ expected = 'labelA#labelB'\n+ self.assertEqual(line1['label'], expected)\n+ self.assertEqual(line2['label'], expected)\n+\n @patch('os.remove')\n @patch('zipfile.ZipFile')\n @patch('csv.DictWriter.writerow')\n", "FAIL_TO_PASS": ["backend/api/tests/download/test_writer.py::TestCSVWriter::test_label_order"]}], "all_FAIL_TO_PASS": ["backend/api/tests/download/test_writer.py::TestCSVWriter::test_create_header", "backend/api/tests/download/test_writer.py::TestCSVWriter::test_label_order"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "hazelcast__hazelcast-python-client-385_x2", "level": 2, "source": "swerebench", "repo": "hazelcast/hazelcast-python-client", "image": "swerebench/sweb.eval.x86_64.hazelcast_1776_hazelcast-python-client-385:latest", "base_commit": "ea1058ec914e6861ec8d09e4f632c64eb2d6b1e1", "num_bugs": 2, "bugs": [{"instance_id": "hazelcast__hazelcast-python-client-385", "base_commit": "ea1058ec914e6861ec8d09e4f632c64eb2d6b1e1", "gold_patch": "diff --git a/hazelcast/cp.py b/hazelcast/cp.py\nindex b131c7b..d1dd2c0 100644\n--- a/hazelcast/cp.py\n+++ b/hazelcast/cp.py\n@@ -155,6 +155,7 @@ class CPSubsystem(object):\n \n \n _DEFAULT_GROUP_NAME = \"default\"\n+_METADATA_CP_GROUP_NAME = \"metadata\"\n \n \n def _without_default_group_name(name):\n@@ -165,7 +166,11 @@ def _without_default_group_name(name):\n \n check_true(name.find(\"@\", idx + 1) == -1, \"Custom group name must be specified at most once\")\n group_name = name[idx + 1 :].strip()\n- if group_name == _DEFAULT_GROUP_NAME:\n+ check_true(\n+ group_name.lower() != _METADATA_CP_GROUP_NAME,\n+ \"CP data structures cannot run on the METADATA CP group!\",\n+ )\n+ if group_name.lower() == _DEFAULT_GROUP_NAME:\n return name[:idx]\n return name\n \ndiff --git a/hazelcast/util.py b/hazelcast/util.py\nindex 732759f..6accedf 100644\n--- a/hazelcast/util.py\n+++ b/hazelcast/util.py\n@@ -1,7 +1,12 @@\n import random\n import threading\n import time\n-from collections import Sequence, Iterable\n+\n+try:\n+ from collections.abc import Sequence, Iterable\n+except ImportError:\n+ # Compatibility for Python2\n+ from collections import Sequence, Iterable\n \n from hazelcast import six\n \n", "test_patch": "diff --git a/tests/integration/backward_compatible/client_test.py b/tests/integration/backward_compatible/client_test.py\nindex ac933a7..788186d 100644\n--- a/tests/integration/backward_compatible/client_test.py\n+++ b/tests/integration/backward_compatible/client_test.py\n@@ -4,7 +4,7 @@ from tests.base import HazelcastTestCase\n from hazelcast.client import HazelcastClient\n from hazelcast.lifecycle import LifecycleState\n from tests.hzrc.ttypes import Lang\n-from tests.integration.backward_compatible.util import get_current_timestamp\n+from tests.util import get_current_timestamp\n \n \n class ClientTest(HazelcastTestCase):\ndiff --git a/tests/integration/backward_compatible/proxy/cp/atomic_long_test.py b/tests/integration/backward_compatible/proxy/cp/atomic_long_test.py\nindex 5b1bf93..416358b 100644\n--- a/tests/integration/backward_compatible/proxy/cp/atomic_long_test.py\n+++ b/tests/integration/backward_compatible/proxy/cp/atomic_long_test.py\n@@ -1,7 +1,7 @@\n from hazelcast.errors import DistributedObjectDestroyedError\n from hazelcast.serialization.api import IdentifiedDataSerializable\n from tests.integration.backward_compatible.proxy.cp import CPTestCase\n-from tests.util import set_attr\n+from tests.util import mark_server_version_at_least\n \n \n class Multiplication(IdentifiedDataSerializable):\n@@ -106,30 +106,30 @@ class AtomicLongTest(CPTestCase):\n self.assertIsNone(self.atomic_long.set(42))\n self.assertEqual(42, self.atomic_long.get())\n \n- @set_attr(min_server_version=\"4.1\")\n def test_alter(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.atomic_long.set(2)\n self.assertIsNone(self.atomic_long.alter(Multiplication(5)))\n self.assertEqual(10, self.atomic_long.get())\n \n- @set_attr(min_server_version=\"4.1\")\n def test_alter_and_get(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.atomic_long.set(-3)\n self.assertEqual(-9, self.atomic_long.alter_and_get(Multiplication(3)))\n self.assertEqual(-9, self.atomic_long.get())\n \n- @set_attr(min_server_version=\"4.1\")\n def test_get_and_alter(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.atomic_long.set(123)\n self.assertEqual(123, self.atomic_long.get_and_alter(Multiplication(-1)))\n self.assertEqual(-123, self.atomic_long.get())\n \n- @set_attr(min_server_version=\"4.1\")\n def test_apply(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.atomic_long.set(42)\n self.assertEqual(84, self.atomic_long.apply(Multiplication(2)))\n self.assertEqual(42, self.atomic_long.get())\ndiff --git a/tests/integration/backward_compatible/proxy/cp/atomic_reference_test.py b/tests/integration/backward_compatible/proxy/cp/atomic_reference_test.py\nindex 2d36070..fa99523 100644\n--- a/tests/integration/backward_compatible/proxy/cp/atomic_reference_test.py\n+++ b/tests/integration/backward_compatible/proxy/cp/atomic_reference_test.py\n@@ -3,7 +3,7 @@ from hazelcast.serialization.api import IdentifiedDataSerializable\n \n from tests.integration.backward_compatible.util import write_string_to_output\n from tests.integration.backward_compatible.proxy.cp import CPTestCase\n-from tests.util import set_attr\n+from tests.util import mark_server_version_at_least\n \n \n class AppendString(IdentifiedDataSerializable):\n@@ -108,37 +108,37 @@ class AtomicReferenceTest(CPTestCase):\n self.assertFalse(self.ref.contains(\"42\"))\n self.assertTrue(self.ref.contains(None))\n \n- @set_attr(min_server_version=\"4.1\")\n def test_alter(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.ref.set(\"hey\")\n self.assertIsNone(self.ref.alter(AppendString(\"123\")))\n self.assertEqual(\"hey123\", self.ref.get())\n \n- @set_attr(min_server_version=\"4.1\")\n def test_alter_with_incompatible_types(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.ref.set(42)\n with self.assertRaises(ClassCastError):\n self.ref.alter(AppendString(\".\"))\n \n- @set_attr(min_server_version=\"4.1\")\n def test_alter_and_get(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.ref.set(\"123\")\n self.assertEqual(\"123...\", self.ref.alter_and_get(AppendString(\"...\")))\n self.assertEqual(\"123...\", self.ref.get())\n \n- @set_attr(min_server_version=\"4.1\")\n def test_get_and_alter(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.ref.set(\"hell\")\n self.assertEqual(\"hell\", self.ref.get_and_alter(AppendString(\"o\")))\n self.assertEqual(\"hello\", self.ref.get())\n \n- @set_attr(min_server_version=\"4.1\")\n def test_apply(self):\n # the class is defined in the 4.1 JAR\n+ mark_server_version_at_least(self, self.client, \"4.1\")\n self.ref.set(\"hell\")\n self.assertEqual(\"hello\", self.ref.apply(AppendString(\"o\")))\n self.assertEqual(\"hell\", self.ref.get())\ndiff --git a/tests/integration/backward_compatible/proxy/cp/count_down_latch_test.py b/tests/integration/backward_compatible/proxy/cp/count_down_latch_test.py\nindex 1268048..b81229a 100644\n--- a/tests/integration/backward_compatible/proxy/cp/count_down_latch_test.py\n+++ b/tests/integration/backward_compatible/proxy/cp/count_down_latch_test.py\n@@ -4,8 +4,7 @@ from hazelcast.errors import DistributedObjectDestroyedError, OperationTimeoutEr\n from hazelcast.future import ImmediateExceptionFuture\n from hazelcast.util import AtomicInteger\n from tests.integration.backward_compatible.proxy.cp import CPTestCase\n-from tests.integration.backward_compatible.util import get_current_timestamp\n-from tests.util import random_string\n+from tests.util import get_current_timestamp, random_string\n \n \n inf = 2 ** 31 - 1\ndiff --git a/tests/integration/backward_compatible/proxy/cp/semaphore_test.py b/tests/integration/backward_compatible/proxy/cp/semaphore_test.py\nindex 595b14f..2e67053 100644\n--- a/tests/integration/backward_compatible/proxy/cp/semaphore_test.py\n+++ b/tests/integration/backward_compatible/proxy/cp/semaphore_test.py\n@@ -9,8 +9,7 @@ from hazelcast.errors import (\n IllegalStateError,\n )\n from tests.integration.backward_compatible.proxy.cp import CPTestCase\n-from tests.integration.backward_compatible.util import get_current_timestamp\n-from tests.util import random_string\n+from tests.util import get_current_timestamp, random_string\n \n SEMAPHORE_TYPES = [\n \"sessionless\",\ndiff --git a/tests/integration/backward_compatible/statistics_test.py b/tests/integration/backward_compatible/statistics_test.py\nindex e85e15d..6d67117 100644\n--- a/tests/integration/backward_compatible/statistics_test.py\n+++ b/tests/integration/backward_compatible/statistics_test.py\n@@ -6,8 +6,7 @@ from hazelcast.core import CLIENT_TYPE\n from hazelcast.statistics import Statistics\n from tests.base import HazelcastTestCase\n from tests.hzrc.ttypes import Lang\n-from tests.integration.backward_compatible.util import get_current_timestamp\n-from tests.util import random_string\n+from tests.util import get_current_timestamp, random_string\n \n \n class StatisticsTest(HazelcastTestCase):\ndiff --git a/tests/integration/backward_compatible/util.py b/tests/integration/backward_compatible/util.py\nindex dc78e3f..534a149 100644\n--- a/tests/integration/backward_compatible/util.py\n+++ b/tests/integration/backward_compatible/util.py\n@@ -1,11 +1,3 @@\n-import time\n-\n-try:\n- from tests.util import get_current_timestamp\n-except ImportError:\n- get_current_timestamp = time.time\n-\n-\n def read_string_from_input(inp):\n if hasattr(inp, \"read_string\"):\n return inp.read_string()\ndiff --git a/tests/unit/proxy/cp/cp_proxy_manager_test.py b/tests/unit/proxy/cp/cp_proxy_manager_test.py\nindex 4b1b792..e0d1b29 100644\n--- a/tests/unit/proxy/cp/cp_proxy_manager_test.py\n+++ b/tests/unit/proxy/cp/cp_proxy_manager_test.py\n@@ -6,12 +6,20 @@ from hazelcast.cp import _without_default_group_name, _get_object_name_for_proxy\n class CPProxyManagerTest(unittest.TestCase):\n def test_without_default_group_name(self):\n self.assertEqual(\"test\", _without_default_group_name(\"test@default\"))\n+ self.assertEqual(\"test\", _without_default_group_name(\"test@DEFAULT\"))\n self.assertEqual(\"test@custom\", _without_default_group_name(\"test@custom\"))\n \n def test_without_default_group_name_with_multiple_group_names(self):\n with self.assertRaises(AssertionError):\n _without_default_group_name(\"test@default@@default\")\n \n+ def test_without_default_group_name_with_metadata_group_name(self):\n+ with self.assertRaises(AssertionError):\n+ _without_default_group_name(\"test@METADATA\")\n+\n+ with self.assertRaises(AssertionError):\n+ _without_default_group_name(\"test@metadata\")\n+\n def test_get_object_name_for_proxy(self):\n self.assertEqual(\"test\", _get_object_name_for_proxy(\"test@default\"))\n self.assertEqual(\"test\", _get_object_name_for_proxy(\"test@custom\"))\ndiff --git a/tests/util.py b/tests/util.py\nindex 58f8517..909b7c0 100644\n--- a/tests/util.py\n+++ b/tests/util.py\n@@ -3,6 +3,7 @@ import time\n \n from uuid import uuid4\n from hazelcast.config import SSLProtocol\n+from hazelcast.util import calculate_version\n \n # time.monotonic() is more consistent since it uses cpu clock rather than system clock. Use it if available.\n if hasattr(time, \"monotonic\"):\n@@ -88,6 +89,14 @@ def set_attr(*args, **kwargs):\n return wrap_ob\n \n \n+def mark_server_version_at_least(test, client, expected_version):\n+ connection = client._connection_manager.get_random_connection()\n+ server_version = connection.server_version\n+ expected_version = calculate_version(expected_version)\n+ if server_version < expected_version:\n+ test.skipTest(\"Expected a newer server\")\n+\n+\n def open_connection_to_address(client, uuid):\n key = generate_key_owned_by_instance(client, uuid)\n m = client.get_map(random_string()).blocking()\n", "FAIL_TO_PASS": ["tests/unit/proxy/cp/cp_proxy_manager_test.py::CPProxyManagerTest::test_without_default_group_name", "tests/unit/proxy/cp/cp_proxy_manager_test.py::CPProxyManagerTest::test_without_default_group_name_with_metadata_group_name"]}, {"instance_id": "hazelcast__hazelcast-python-client-387", "base_commit": "d63e83d3379633bf310e52ae3c0bc8b226460b22", "gold_patch": "diff --git a/hazelcast/serialization/portable/classdef.py b/hazelcast/serialization/portable/classdef.py\nindex a043eda..3b74583 100644\n--- a/hazelcast/serialization/portable/classdef.py\n+++ b/hazelcast/serialization/portable/classdef.py\n@@ -132,6 +132,16 @@ class ClassDefinition(object):\n \n \n class ClassDefinitionBuilder(object):\n+ \"\"\"Builder class to construct :class:`ClassDefinition` of\n+ :class:`hazelcast.serialization.api.Portable` objects.\n+\n+ One must make sure that the order of the fields added to this\n+ builder is consistent across all the usages of the Portable\n+ object such as the write order of the fields of the\n+ :func:`Portable.write_portable `\n+ method.\n+ \"\"\"\n+\n def __init__(self, factory_id, class_id, version=0):\n self.factory_id = factory_id\n self.class_id = class_id\n@@ -140,8 +150,25 @@ class ClassDefinitionBuilder(object):\n self._index = 0\n self._done = False\n self._field_defs = list()\n+ self._field_names = set()\n \n def add_portable_field(self, field_name, class_def):\n+ \"\"\"Adds the field with the Portable type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+ class_def (ClassDefinition): Class definition\n+ of the nested Portable.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n if class_def.class_id is None or class_def.class_id == 0:\n raise ValueError(\"Portable class id cannot be zero!\")\n self._add_field_by_type(\n@@ -154,43 +181,182 @@ class ClassDefinitionBuilder(object):\n return self\n \n def add_byte_field(self, field_name):\n+ \"\"\"Adds the field with the byte type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.BYTE, self.version)\n return self\n \n def add_boolean_field(self, field_name):\n+ \"\"\"Adds the field with the boolean type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.BOOLEAN, self.version)\n return self\n \n def add_char_field(self, field_name):\n+ \"\"\"Adds the field with the char type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.CHAR, self.version)\n return self\n \n def add_short_field(self, field_name):\n+ \"\"\"Adds the field with the short type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.SHORT, self.version)\n return self\n \n def add_int_field(self, field_name):\n+ \"\"\"Adds the field with the int type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.INT, self.version)\n return self\n \n def add_long_field(self, field_name):\n+ \"\"\"Adds the field with the long type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.LONG, self.version)\n return self\n \n def add_float_field(self, field_name):\n+ \"\"\"Adds the field with the float type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.FLOAT, self.version)\n return self\n \n def add_double_field(self, field_name):\n+ \"\"\"Adds the field with the double type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.DOUBLE, self.version)\n return self\n \n def add_string_field(self, field_name):\n+ \"\"\"Adds the field with the string type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.STRING, self.version)\n return self\n \n def add_utf_field(self, field_name):\n- \"\"\"\n+ \"\"\"Adds the field with the string type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+\n .. deprecated:: 4.1\n This method is deprecated and will be removed in the\n next major version. Use :func:`add_string_field` instead.\n@@ -198,6 +364,22 @@ class ClassDefinitionBuilder(object):\n return self.add_string_field(field_name)\n \n def add_portable_array_field(self, field_name, class_def):\n+ \"\"\"Adds the field with the Portable array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+ class_def (ClassDefinition): Class definition\n+ of the nested Portable.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n if class_def.class_id is None or class_def.class_id == 0:\n raise ValueError(\"Portable class id cannot be zero!\")\n self._add_field_by_type(\n@@ -210,43 +392,182 @@ class ClassDefinitionBuilder(object):\n return self\n \n def add_byte_array_field(self, field_name):\n+ \"\"\"Adds the field with the byte array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.BYTE_ARRAY, self.version)\n return self\n \n def add_boolean_array_field(self, field_name):\n+ \"\"\"Adds the field with the boolean array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.BOOLEAN_ARRAY, self.version)\n return self\n \n def add_char_array_field(self, field_name):\n+ \"\"\"Adds the field with the char array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.CHAR_ARRAY, self.version)\n return self\n \n def add_short_array_field(self, field_name):\n+ \"\"\"Adds the field with the short array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.SHORT_ARRAY, self.version)\n return self\n \n def add_int_array_field(self, field_name):\n+ \"\"\"Adds the field with the int array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.INT_ARRAY, self.version)\n return self\n \n def add_long_array_field(self, field_name):\n+ \"\"\"Adds the field with the long array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.LONG_ARRAY, self.version)\n return self\n \n def add_float_array_field(self, field_name):\n+ \"\"\"Adds the field with the float array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.FLOAT_ARRAY, self.version)\n return self\n \n def add_double_array_field(self, field_name):\n+ \"\"\"Adds the field with the double array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.DOUBLE_ARRAY, self.version)\n return self\n \n def add_string_array_field(self, field_name):\n+ \"\"\"Adds the field with the string array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+ \"\"\"\n self._add_field_by_type(field_name, FieldType.STRING_ARRAY, self.version)\n return self\n \n def add_utf_array_field(self, field_name):\n- \"\"\"\n+ \"\"\"Adds the field with the string array type to the\n+ class definition.\n+\n+ Args:\n+ field_name (str): Name of the field to add.\n+\n+ Returns:\n+ ClassDefinitionBuilder: Itself for chaining.\n+\n+ Raises:\n+ HazelcastSerializationError: If this method is called\n+ after :func:`build` or a field with the same\n+ name is already registered.\n+\n .. deprecated:: 4.1\n This method is deprecated and will be removed in the\n next major version. Use :func:`add_string_array_field` instead.\n@@ -254,14 +575,25 @@ class ClassDefinitionBuilder(object):\n return self.add_string_array_field(field_name)\n \n def add_field_def(self, field_def):\n- self._check()\n+ \"\"\"\n+ Warnings:\n+ This method is not intended for public usage.\n+ It might be removed from the public API on the\n+ next major version.\n+ \"\"\"\n if self._index != field_def.index:\n raise ValueError(\"Invalid field index\")\n+ self._check(field_def.field_name)\n self._index += 1\n self._field_defs.append(field_def)\n return self\n \n def build(self):\n+ \"\"\"Builds and returns the class definition.\n+\n+ Returns:\n+ ClassDefinition:\n+ \"\"\"\n self._done = True\n cd = ClassDefinition(self.factory_id, self.class_id, self.version)\n for field_def in self._field_defs:\n@@ -269,12 +601,16 @@ class ClassDefinitionBuilder(object):\n return cd\n \n def _add_field_by_type(self, field_name, field_type, version, factory_id=0, class_id=0):\n- self._check()\n+ self._check(field_name)\n fd = FieldDefinition(self._index, field_name, field_type, version, factory_id, class_id)\n self._field_defs.append(fd)\n self._index += 1\n \n- def _check(self):\n+ def _check(self, field_name):\n+ if field_name in self._field_names:\n+ raise HazelcastSerializationError(\"Field with the name %s already exists\" % field_name)\n+ self._field_names.add(field_name)\n+\n if self._done:\n raise HazelcastSerializationError(\n \"ClassDefinition is already built for %s\" % self.class_id\n", "test_patch": "diff --git a/tests/unit/serialization/portable_test.py b/tests/unit/serialization/portable_test.py\nindex 529a06f..6953ff7 100644\n--- a/tests/unit/serialization/portable_test.py\n+++ b/tests/unit/serialization/portable_test.py\n@@ -515,3 +515,11 @@ class PortableSerializationTestCase(unittest.TestCase):\n portable2 = MyPortable2(1)\n data2 = ss.to_data(portable2)\n self.assertEqual(portable2, ss.to_object(data2))\n+\n+ def test_class_definition_with_duplicate_fields(self):\n+ with self.assertRaises(HazelcastSerializationError):\n+ ClassDefinitionBuilder(1, 1).add_string_field(\"name\").add_string_field(\"name\")\n+\n+ def test_class_definition_with_duplicate_field_names_with_different_types(self):\n+ with self.assertRaises(HazelcastSerializationError):\n+ ClassDefinitionBuilder(1, 1).add_string_field(\"name\").add_int_field(\"name\")\n", "FAIL_TO_PASS": ["tests/unit/serialization/portable_test.py::PortableSerializationTestCase::test_class_definition_with_duplicate_field_names_with_different_types", "tests/unit/serialization/portable_test.py::PortableSerializationTestCase::test_class_definition_with_duplicate_fields"]}], "all_FAIL_TO_PASS": ["tests/unit/proxy/cp/cp_proxy_manager_test.py::CPProxyManagerTest::test_without_default_group_name", "tests/unit/proxy/cp/cp_proxy_manager_test.py::CPProxyManagerTest::test_without_default_group_name_with_metadata_group_name", "tests/unit/serialization/portable_test.py::PortableSerializationTestCase::test_class_definition_with_duplicate_field_names_with_different_types", "tests/unit/serialization/portable_test.py::PortableSerializationTestCase::test_class_definition_with_duplicate_fields"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "briancurtin__deprecation-14_x2", "level": 2, "source": "swerebench", "repo": "briancurtin/deprecation", "image": "swerebench/sweb.eval.x86_64.briancurtin_1776_deprecation-14:latest", "base_commit": "3ad94c2de7c313d0ca20a8ce4c9247a0faaa8018", "num_bugs": 2, "bugs": [{"instance_id": "briancurtin__deprecation-14", "base_commit": "3ad94c2de7c313d0ca20a8ce4c9247a0faaa8018", "gold_patch": "diff --git a/deprecation.py b/deprecation.py\nindex 00598db..a64b5b7 100644\n--- a/deprecation.py\n+++ b/deprecation.py\n@@ -9,6 +9,7 @@\n # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n # License for the specific language governing permissions and limitations\n # under the License.\n+import collections\n import functools\n import textwrap\n import warnings\n@@ -51,9 +52,22 @@ class DeprecatedWarning(DeprecationWarning):\n super(DeprecatedWarning, self).__init__()\n \n def __str__(self):\n- return (\"%s is deprecated as of %s and will \"\n- \"be removed in %s. %s\" % (self.function, self.deprecated_in,\n- self.removed_in, self.details))\n+ # Use a defaultdict to give us the empty string\n+ # when a part isn't included.\n+ parts = collections.defaultdict(str)\n+ parts[\"function\"] = self.function\n+\n+ if self.deprecated_in:\n+ parts[\"deprecated\"] = \" as of %s\" % self.deprecated_in\n+ if self.removed_in:\n+ parts[\"removed\"] = \" and will be removed in %s\" % self.removed_in\n+ if any([self.deprecated_in, self.removed_in, self.details]):\n+ parts[\"period\"] = \".\"\n+ if self.details:\n+ parts[\"details\"] = \" %s\" % self.details\n+\n+ return (\"%(function)s is deprecated%(deprecated)s%(removed)s\"\n+ \"%(period)s%(details)s\" % (parts))\n \n \n class UnsupportedWarning(DeprecatedWarning):\n@@ -67,9 +81,15 @@ class UnsupportedWarning(DeprecatedWarning):\n \"\"\"\n \n def __str__(self):\n- return (\"%s is unsupported as of %s. %s\" % (self.function,\n- self.removed_in,\n- self.details))\n+ parts = collections.defaultdict(str)\n+ parts[\"function\"] = self.function\n+ parts[\"removed\"] = self.removed_in\n+\n+ if self.details:\n+ parts[\"details\"] = \" %s\" % self.details\n+\n+ return (\"%(function)s is unsupported as of %(removed)s.\"\n+ \"%(details)s\" % (parts))\n \n \n def deprecated(deprecated_in=None, removed_in=None, current_version=None,\n", "test_patch": "diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py\nindex cf9d420..55e05bd 100644\n--- a/tests/test_deprecation.py\n+++ b/tests/test_deprecation.py\n@@ -71,14 +71,33 @@ class Test_deprecated(unittest2.TestCase):\n ret_val = \"lololol\"\n \n for test in [{\"args\": {}, # No args just means deprecated\n- \"warning\": deprecation.DeprecatedWarning},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated\"},\n+ {\"args\": {\"details\": \"do something else.\"},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated. do something else.\"},\n {\"args\": {\"deprecated_in\": \"1.0\",\n \"current_version\": \"2.0\"},\n- \"warning\": deprecation.DeprecatedWarning},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated as of 1.0.\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\",\n+ \"removed_in\": \"3.0\",\n+ \"current_version\": \"2.0\"},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": (\"method is deprecated as of 1.0 \"\n+ \"and will be removed in 3.0.\")},\n {\"args\": {\"deprecated_in\": \"1.0\",\n \"removed_in\": \"2.0\",\n \"current_version\": \"2.0\"},\n- \"warning\": deprecation.UnsupportedWarning}]:\n+ \"warning\": deprecation.UnsupportedWarning,\n+ \"message\": \"method is unsupported as of 2.0.\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\",\n+ \"removed_in\": \"2.0\",\n+ \"current_version\": \"2.0\",\n+ \"details\": \"do something else.\"},\n+ \"warning\": deprecation.UnsupportedWarning,\n+ \"message\": (\"method is unsupported as of 2.0. \"\n+ \"do something else.\")}]:\n with self.subTest(**test):\n class Test(object):\n @deprecation.deprecated(**test[\"args\"])\n@@ -93,6 +112,8 @@ class Test_deprecated(unittest2.TestCase):\n \n self.assertEqual(len(caught_warnings), 1)\n self.assertEqual(caught_warnings[0].category, test[\"warning\"])\n+ self.assertEqual(str(caught_warnings[0].message),\n+ test[\"message\"])\n \n def test_DeprecatedWarning_not_raised(self):\n ret_val = \"lololol\"\n", "FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_warning_raised"]}, {"instance_id": "briancurtin__deprecation-37", "base_commit": "c9f228e5900f1875ba304f7da57fedf39ecd2dab", "gold_patch": "diff --git a/deprecation.py b/deprecation.py\nindex 7a80adc..dbeb39e 100644\n--- a/deprecation.py\n+++ b/deprecation.py\n@@ -56,7 +56,8 @@ class DeprecatedWarning(DeprecationWarning):\n self.deprecated_in = deprecated_in\n self.removed_in = removed_in\n self.details = details\n- super(DeprecatedWarning, self).__init__()\n+ super(DeprecatedWarning, self).__init__(function, deprecated_in,\n+ removed_in, details)\n \n def __str__(self):\n # Use a defaultdict to give us the empty string\n", "test_patch": "diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py\nindex 7e4318e..4d294ba 100644\n--- a/tests/test_deprecation.py\n+++ b/tests/test_deprecation.py\n@@ -20,6 +20,11 @@ import deprecation\n \n class Test_deprecated(unittest2.TestCase):\n \n+ def test_args_set_on_base_class(self):\n+ args = (1, 2, 3, 4)\n+ dw = deprecation.DeprecatedWarning(*args)\n+ self.assertEqual(dw.args, args)\n+\n def test_removing_without_deprecating(self):\n self.assertRaises(TypeError, deprecation.deprecated,\n deprecated_in=None, removed_in=\"1.0\")\n", "FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_args_set_on_base_class"]}], "all_FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_warning_raised", "tests/test_deprecation.py::Test_deprecated::test_args_set_on_base_class"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "twisted__towncrier-166_x3", "level": 3, "source": "swerebench", "repo": "twisted/towncrier", "image": "swerebench/sweb.eval.x86_64.twisted_1776_towncrier-166:latest", "base_commit": "1a38b3354a8b4029cd8f7b5cfe835ee2436f7fa4", "num_bugs": 3, "bugs": [{"instance_id": "twisted__towncrier-166", "base_commit": "1a38b3354a8b4029cd8f7b5cfe835ee2436f7fa4", "gold_patch": "diff --git a/.gitignore b/.gitignore\nindex 45ecce4..0bf4874 100644\n--- a/.gitignore\n+++ b/.gitignore\n@@ -21,4 +21,5 @@ apidocs/\n .tox/\n .coverage.*\n .vscode\n+.idea\n .python-version\n\\ No newline at end of file\ndiff --git a/README.rst b/README.rst\nindex 9cf5013..a424a8e 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -32,7 +32,7 @@ Install from PyPI::\n .. note::\n \n ``towncrier``, as a command line tool, works on Python 3.5+ only.\n- It is usable by projects written in other languages, provided you give it the version of the project when invoking it.\n+ It is usable by projects written in other languages, provided you specify the project version either in the configuration file or on the command line.\n For Python 2/3 compatible projects, the version can be discovered automatically.\n \n In your project root, add a ``pyproject.toml`` file.\n@@ -64,13 +64,21 @@ Using the above example, your news fragments would be ``src/myproject/newsfragme\n \n This will keep the folder around, but otherwise \"empty\".\n \n-``towncrier`` needs to know what version your project is, and there are two ways you can give it:\n+``towncrier`` needs to know what version your project is, and there are three ways you can give it:\n \n - For Python 2/3 compatible projects, a ``__version__`` in the top level package.\n This can be either a string literal, a tuple, or an `Incremental `_ version.\n \n - Manually passing ``--version=`` when interacting with ``towncrier``.\n \n+- Definining a ``version`` option in a configuration file:\n+\n+.. code-block:: ini\n+\n+ [tool.towncrier]\n+ # ...\n+ version = \"1.2.3\" # project version if maintained separately\n+\n To create a new news fragment, use the ``towncrier create`` command.\n For example::\n \n@@ -123,6 +131,8 @@ Towncrier has the following global options, which can be specified in the toml f\n single_file = true # if false, filename is formatted like `title_format`.\n filename = \"NEWS.rst\"\n directory = \"directory/of/news/fragments\"\n+ version = \"1.2.3\" # project version if maintained separately\n+ name = \"arbitrary project name\"\n template = \"path/to/template.rst\"\n start_line = \"start of generated content\"\n title_format = \"{name} {version} ({project_date})\" # or false if template includes title\ndiff --git a/src/towncrier/_settings.py b/src/towncrier/_settings.py\nindex 57ab2d3..f84dcb9 100644\n--- a/src/towncrier/_settings.py\n+++ b/src/towncrier/_settings.py\n@@ -144,6 +144,8 @@ def parse_toml(base_path, config):\n \"single_file\": single_file,\n \"filename\": config.get(\"filename\", \"NEWS.rst\"),\n \"directory\": config.get(\"directory\"),\n+ \"version\": config.get(\"version\"),\n+ \"name\": config.get(\"name\"),\n \"sections\": sections,\n \"types\": types,\n \"template\": template,\ndiff --git a/src/towncrier/build.py b/src/towncrier/build.py\nindex d1f87b8..2824598 100644\n--- a/src/towncrier/build.py\n+++ b/src/towncrier/build.py\n@@ -119,20 +119,24 @@ def __main(\n )\n \n if project_version is None:\n- project_version = get_version(\n- os.path.join(base_directory, config[\"package_dir\"]), config[\"package\"]\n- ).strip()\n+ project_version = config.get('version')\n+ if project_version is None:\n+ project_version = get_version(\n+ os.path.join(base_directory, config[\"package_dir\"]), config[\"package\"]\n+ ).strip()\n \n if project_name is None:\n- package = config.get(\"package\")\n- if package:\n- project_name = get_project_name(\n- os.path.abspath(os.path.join(base_directory, config[\"package_dir\"])),\n- package,\n- )\n- else:\n- # Can't determine a project_name, but maybe it is not needed.\n- project_name = \"\"\n+ project_name = config.get('name')\n+ if not project_name:\n+ package = config.get(\"package\")\n+ if package:\n+ project_name = get_project_name(\n+ os.path.abspath(os.path.join(base_directory, config[\"package_dir\"])),\n+ package,\n+ )\n+ else:\n+ # Can't determine a project_name, but maybe it is not needed.\n+ project_name = \"\"\n \n if project_date is None:\n project_date = _get_date().strip()\ndiff --git a/src/towncrier/newsfragments/165.feature.rst b/src/towncrier/newsfragments/165.feature.rst\nnew file mode 100644\nindex 0000000..3a8deb6\n--- /dev/null\n+++ b/src/towncrier/newsfragments/165.feature.rst\n@@ -0,0 +1,2 @@\n+Allow definition of the project ``version`` and ``name`` in the configuration file.\n+This allows use of towncrier seamlessly with non-Python projects.\n", "test_patch": "diff --git a/src/towncrier/test/test_build.py b/src/towncrier/test/test_build.py\nindex bee1ca1..3e59445 100644\n--- a/src/towncrier/test/test_build.py\n+++ b/src/towncrier/test/test_build.py\n@@ -343,6 +343,90 @@ class TestCli(TestCase):\n ).lstrip(),\n )\n \n+ def test_version_in_config(self):\n+ \"\"\"The calling towncrier with version defined in configfile.\n+\n+ Specifying a version in toml file will be helpful if version\n+ is maintained by i.e. bumpversion and it's not a python project.\n+ \"\"\"\n+ runner = CliRunner()\n+\n+ with runner.isolated_filesystem():\n+ with open(\"pyproject.toml\", \"w\") as f:\n+ f.write(\"[tool.towncrier]\\n\" 'version = \"7.8.9\"\\n')\n+ os.mkdir(\"newsfragments\")\n+ with open(\"newsfragments/123.feature\", \"w\") as f:\n+ f.write(\"Adds levitation\")\n+\n+ result = runner.invoke(\n+ _main, [\"--date\", \"01-01-2001\", \"--draft\"]\n+ )\n+\n+ self.assertEqual(0, result.exit_code, result.output)\n+ self.assertEqual(\n+ result.output,\n+ dedent(\n+ \"\"\"\n+ Loading template...\n+ Finding news fragments...\n+ Rendering news fragments...\n+ Draft only -- nothing has been written.\n+ What is seen below is what would be written.\n+\n+ 7.8.9 (01-01-2001)\n+ ==================\n+\n+ Features\n+ --------\n+\n+ - Adds levitation (#123)\n+\n+ \"\"\"\n+ ).lstrip(),\n+ )\n+\n+ def test_project_name_in_config(self):\n+ \"\"\"The calling towncrier with project name defined in configfile.\n+\n+ Specifying a project name in toml file will be helpful to keep the\n+ project name consistent as part of the towncrier configuration, not call.\n+ \"\"\"\n+ runner = CliRunner()\n+\n+ with runner.isolated_filesystem():\n+ with open(\"pyproject.toml\", \"w\") as f:\n+ f.write(\"[tool.towncrier]\\n\" 'name = \"ImGoProject\"\\n')\n+ os.mkdir(\"newsfragments\")\n+ with open(\"newsfragments/123.feature\", \"w\") as f:\n+ f.write(\"Adds levitation\")\n+\n+ result = runner.invoke(\n+ _main, [\"--version\", \"7.8.9\", \"--date\", \"01-01-2001\", \"--draft\"]\n+ )\n+\n+ self.assertEqual(0, result.exit_code, result.output)\n+ self.assertEqual(\n+ result.output,\n+ dedent(\n+ \"\"\"\n+ Loading template...\n+ Finding news fragments...\n+ Rendering news fragments...\n+ Draft only -- nothing has been written.\n+ What is seen below is what would be written.\n+\n+ ImGoProject 7.8.9 (01-01-2001)\n+ ==============================\n+\n+ Features\n+ --------\n+\n+ - Adds levitation (#123)\n+\n+ \"\"\"\n+ ).lstrip(),\n+ )\n+\n def test_no_package_changelog(self):\n \"\"\"The calling towncrier with any package argument.\n \n", "FAIL_TO_PASS": ["src/towncrier/test/test_build.py::TestCli::test_project_name_in_config", "src/towncrier/test/test_build.py::TestCli::test_version_in_config"]}, {"instance_id": "twisted__towncrier-276", "base_commit": "96178dc0ffe63ff4eba88c9a1b9c2d87ebdaf4de", "gold_patch": "diff --git a/src/towncrier/_builder.py b/src/towncrier/_builder.py\nindex 90988ac..e8ca9ba 100644\n--- a/src/towncrier/_builder.py\n+++ b/src/towncrier/_builder.py\n@@ -224,6 +224,7 @@ def render_issue(issue_format, issue):\n def render_fragments(\n template,\n issue_format,\n+ top_line,\n fragments,\n definitions,\n underlines,\n@@ -288,6 +289,7 @@ def render_fragments(\n return u\"\"\n \n res = jinja_template.render(\n+ top_line=top_line,\n sections=data,\n definitions=definitions,\n underlines=underlines,\ndiff --git a/src/towncrier/build.py b/src/towncrier/build.py\nindex e4952ed..18b606c 100644\n--- a/src/towncrier/build.py\n+++ b/src/towncrier/build.py\n@@ -141,7 +141,6 @@ def __main(\n top_line = config[\"title_format\"].format(\n name=project_name, version=project_version, project_date=project_date\n )\n- top_line += u\"\\n\" + (config[\"underlines\"][0] * len(top_line)) + u\"\\n\"\n else:\n top_line = \"\"\n \n@@ -149,6 +148,7 @@ def __main(\n # The 0th underline is used for the top line\n template,\n config[\"issue_format\"],\n+ top_line,\n fragments,\n definitions,\n config[\"underlines\"][1:],\n@@ -164,10 +164,7 @@ def __main(\n \"What is seen below is what would be written.\\n\",\n err=to_err,\n )\n- if top_line:\n- click.echo(\"\\n%s\\n%s\" % (top_line, rendered))\n- else:\n- click.echo(rendered)\n+ click.echo(rendered)\n else:\n click.echo(\"Writing to newsfile...\", err=to_err)\n start_line = config[\"start_line\"]\ndiff --git a/src/towncrier/newsfragments/180.bugfix b/src/towncrier/newsfragments/180.bugfix\nnew file mode 100644\nindex 0000000..580d960\n--- /dev/null\n+++ b/src/towncrier/newsfragments/180.bugfix\n@@ -0,0 +1,1 @@\n+Specifying ``title_format`` disables default top line creation to avoid duplication.\ndiff --git a/src/towncrier/templates/default.rst b/src/towncrier/templates/default.rst\nindex 362d8e1..ac551df 100644\n--- a/src/towncrier/templates/default.rst\n+++ b/src/towncrier/templates/default.rst\n@@ -1,4 +1,7 @@\n-{% if versiondata.name %}\n+{% if top_line %}\n+{{ top_line }}\n+{{ top_underline * ((top_line)|length)}}\n+{% elif versiondata.name %}\n {{ versiondata.name }} {{ versiondata.version }} ({{ versiondata.date }})\n {{ top_underline * ((versiondata.name + versiondata.version + versiondata.date)|length + 4)}}\n {% else %}\n", "test_patch": "diff --git a/src/towncrier/test/test_format.py b/src/towncrier/test/test_format.py\nindex 26caa05..c0bbf7f 100644\n--- a/src/towncrier/test/test_format.py\n+++ b/src/towncrier/test/test_format.py\n@@ -3,6 +3,8 @@\n \n from __future__ import absolute_import, division\n \n+from textwrap import dedent\n+\n import pkg_resources\n \n from twisted.trial.unittest import TestCase\n@@ -129,6 +131,7 @@ Bugfixes\n output = render_fragments(\n template,\n None,\n+ \"\",\n fragments,\n definitions,\n [\"-\", \"~\"],\n@@ -173,6 +176,7 @@ Bugfixes\n output = render_fragments(\n template,\n None,\n+ \"\",\n fragments,\n definitions,\n [\"*\", \"^\"],\n@@ -218,6 +222,7 @@ Misc\n output = render_fragments(\n template,\n u\"xx{issue}\",\n+ \"\",\n fragments,\n definitions,\n [\"-\", \"~\"],\n@@ -276,6 +281,7 @@ Features\n output = render_fragments(\n template,\n None,\n+ \"\",\n fragments,\n definitions,\n [\"-\", \"~\"],\n@@ -327,6 +333,7 @@ Features\n output = render_fragments(\n template,\n None,\n+ \"\",\n fragments,\n definitions,\n [\"-\", \"~\"],\n@@ -334,3 +341,30 @@ Features\n versiondata={\"name\": \"MyProject\", \"version\": \"1.0\", \"date\": \"never\"},\n )\n self.assertEqual(output, expected_output)\n+\n+ def test_title_format_specified(self):\n+ \"\"\"\n+ Title format replaces default top line rendering.\n+ \"\"\"\n+ template = pkg_resources.resource_string(\n+ \"towncrier\", \"templates/default.rst\"\n+ ).decode(\"utf8\")\n+\n+ fragments = split_fragments(fragments={}, definitions=OrderedDict())\n+ output = render_fragments(\n+ template=template,\n+ issue_format=None,\n+ top_line=\"A custom top line\",\n+ fragments=fragments,\n+ definitions=OrderedDict(),\n+ underlines=[\"-\", \"~\"],\n+ wrap=False,\n+ versiondata={\"name\": \"MyProject\", \"version\": \"1.0\", \"date\": \"never\"},\n+ )\n+\n+ expected_output = dedent(u\"\"\"\\\n+ A custom top line\n+ =================\n+ \"\"\")\n+\n+ self.assertEqual(expected_output, output)\ndiff --git a/src/towncrier/test/test_write.py b/src/towncrier/test/test_write.py\nindex 37bbd10..7ad4853 100644\n--- a/src/towncrier/test/test_write.py\n+++ b/src/towncrier/test/test_write.py\n@@ -98,6 +98,7 @@ Old text.\n render_fragments(\n template,\n None,\n+ \"\",\n fragments,\n definitions,\n [\"-\", \"~\"],\n@@ -212,6 +213,7 @@ Old text.\n render_fragments(\n template,\n None,\n+ \"\",\n fragments,\n definitions,\n [\"-\", \"~\"],\n", "FAIL_TO_PASS": ["src/towncrier/test/test_format.py::FormatterTests::test_basic", "src/towncrier/test/test_format.py::FormatterTests::test_issue_format", "src/towncrier/test/test_format.py::FormatterTests::test_line_wrapping", "src/towncrier/test/test_format.py::FormatterTests::test_line_wrapping_disabled", "src/towncrier/test/test_format.py::FormatterTests::test_title_format_specified", "src/towncrier/test/test_write.py::WritingTests::test_append_at_top", "src/towncrier/test/test_write.py::WritingTests::test_append_at_top_with_hint"]}, {"instance_id": "twisted__towncrier-278", "base_commit": "15644ca294d566a557b5484c358ee1adfeeeca95", "gold_patch": "diff --git a/src/towncrier/_builder.py b/src/towncrier/_builder.py\nindex 6135df8..2a8f0b2 100644\n--- a/src/towncrier/_builder.py\n+++ b/src/towncrier/_builder.py\n@@ -11,6 +11,15 @@ from collections import OrderedDict\n from jinja2 import Template\n \n \n+def strip_if_integer_string(s):\n+ try:\n+ i = int(s)\n+ except ValueError:\n+ return s\n+\n+ return str(i)\n+\n+\n # Returns ticket, category and counter or (None, None, None) if the basename\n # could not be parsed or doesn't contain a valid category.\n def parse_newfragment_basename(basename, definitions):\n@@ -21,6 +30,7 @@ def parse_newfragment_basename(basename, definitions):\n return invalid\n if len(parts) == 2:\n ticket, category = parts\n+ ticket = strip_if_integer_string(ticket)\n return (ticket, category, 0) if category in definitions else invalid\n \n # There are at least 3 parts. Search for a valid category from the second\n@@ -35,7 +45,7 @@ def parse_newfragment_basename(basename, definitions):\n # NOTE: This allows news fragment names like fix-1.2.3.feature or\n # something-cool.feature.ext for projects that don't use ticket\n # numbers in news fragment names.\n- ticket = parts[i-1]\n+ ticket = strip_if_integer_string(parts[i-1])\n counter = 0\n # Use the following part as the counter if it exists and is a valid\n # digit.\ndiff --git a/src/towncrier/newsfragments/126.feature b/src/towncrier/newsfragments/126.feature\nnew file mode 100644\nindex 0000000..be6e633\n--- /dev/null\n+++ b/src/towncrier/newsfragments/126.feature\n@@ -0,0 +1,1 @@\n+Ticket number from file names will be stripped down to avoid ticket links such as ``#007``.\n\\ No newline at end of file\n", "test_patch": "diff --git a/src/towncrier/test/test_builder.py b/src/towncrier/test/test_builder.py\nindex e6d0ed0..7f48a2e 100644\n--- a/src/towncrier/test/test_builder.py\n+++ b/src/towncrier/test/test_builder.py\n@@ -66,3 +66,18 @@ class TestParseNewsfragmentBasename(TestCase):\n parse_newfragment_basename(\"baz.1.2.feature.3\", [\"feature\"]),\n (\"2\", \"feature\", 3),\n )\n+\n+ def test_strip(self):\n+ \"\"\"Leading spaces and subsequent leading zeros are stripped\n+ when parsing newsfragment names into ticket numbers etc.\n+ \"\"\"\n+ self.assertEqual(\n+ parse_newfragment_basename(\" 007.feature\", [\"feature\"]),\n+ (\"7\", \"feature\", 0)\n+ )\n+\n+ def test_strip_with_counter(self):\n+ self.assertEqual(\n+ parse_newfragment_basename(\" 007.feature.3\", [\"feature\"]),\n+ (\"7\", \"feature\", 3)\n+ )\n", "FAIL_TO_PASS": ["src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip_with_counter"]}], "all_FAIL_TO_PASS": ["src/towncrier/test/test_build.py::TestCli::test_project_name_in_config", "src/towncrier/test/test_build.py::TestCli::test_version_in_config", "src/towncrier/test/test_format.py::FormatterTests::test_basic", "src/towncrier/test/test_format.py::FormatterTests::test_issue_format", "src/towncrier/test/test_format.py::FormatterTests::test_line_wrapping", "src/towncrier/test/test_format.py::FormatterTests::test_line_wrapping_disabled", "src/towncrier/test/test_format.py::FormatterTests::test_title_format_specified", "src/towncrier/test/test_write.py::WritingTests::test_append_at_top", "src/towncrier/test/test_write.py::WritingTests::test_append_at_top_with_hint", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip_with_counter"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-2297_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-2297:latest", "base_commit": "f1b6546b463b2a6aa075bf31f54d3aa8a59b748f", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-2297", "base_commit": "f1b6546b463b2a6aa075bf31f54d3aa8a59b748f", "gold_patch": "diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py\nindex 655e92a6..a4278707 100644\n--- a/sqlglot/dialects/hive.py\n+++ b/sqlglot/dialects/hive.py\n@@ -111,7 +111,7 @@ def _array_sort_sql(self: Hive.Generator, expression: exp.ArraySort) -> str:\n \n \n def _property_sql(self: Hive.Generator, expression: exp.Property) -> str:\n- return f\"'{expression.name}'={self.sql(expression, 'value')}\"\n+ return f\"{self.property_name(expression, string_key=True)}={self.sql(expression, 'value')}\"\n \n \n def _str_to_unix_sql(self: Hive.Generator, expression: exp.StrToUnix) -> str:\ndiff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex ae73fd3f..554241d9 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -520,7 +520,7 @@ class MySQL(Dialect):\n \n return self.expression(exp.SetItem, this=charset, collate=collate, kind=\"NAMES\")\n \n- def _parse_type(self) -> t.Optional[exp.Expression]:\n+ def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:\n # mysql binary is special and can work anywhere, even in order by operations\n # it operates like a no paren func\n if self._match(TokenType.BINARY, advance=False):\n@@ -529,7 +529,7 @@ class MySQL(Dialect):\n if isinstance(data_type, exp.DataType):\n return self.expression(exp.Cast, this=self._parse_column(), to=data_type)\n \n- return super()._parse_type()\n+ return super()._parse_type(parse_interval=parse_interval)\n \n class Generator(generator.Generator):\n LOCKING_READS_SUPPORTED = True\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 37343332..ae143531 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -1175,7 +1175,7 @@ class Column(Condition):\n if self.args.get(part)\n ]\n \n- def to_dot(self) -> Dot:\n+ def to_dot(self) -> Dot | Identifier:\n \"\"\"Converts the column into a dot expression.\"\"\"\n parts = self.parts\n parent = self.parent\n@@ -1185,7 +1185,7 @@ class Column(Condition):\n parts.append(parent.expression)\n parent = parent.parent\n \n- return Dot.build(deepcopy(parts))\n+ return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]\n \n \n class ColumnPosition(Expression):\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex f3b77219..b1ee7838 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -3,6 +3,7 @@ from __future__ import annotations\n import logging\n import typing as t\n from collections import defaultdict\n+from functools import reduce\n \n from sqlglot import exp\n from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages\n@@ -1084,10 +1085,15 @@ class Generator:\n \n return properties_locs\n \n+ def property_name(self, expression: exp.Property, string_key: bool = False) -> str:\n+ if isinstance(expression.this, exp.Dot):\n+ return self.sql(expression, \"this\")\n+ return f\"'{expression.name}'\" if string_key else expression.name\n+\n def property_sql(self, expression: exp.Property) -> str:\n property_cls = expression.__class__\n if property_cls == exp.Property:\n- return f\"{expression.name}={self.sql(expression, 'value')}\"\n+ return f\"{self.property_name(expression)}={self.sql(expression, 'value')}\"\n \n property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)\n if not property_name:\n@@ -1418,9 +1424,10 @@ class Generator:\n \n # Converts `VALUES...` expression into a series of select unions.\n expression = expression.copy()\n- column_names = expression.alias and expression.args[\"alias\"].columns\n+ alias_node = expression.args.get(\"alias\")\n+ column_names = alias_node and alias_node.columns\n \n- selects = []\n+ selects: t.List[exp.Subqueryable] = []\n \n for i, tup in enumerate(expression.expressions):\n row = tup.expressions\n@@ -1436,16 +1443,12 @@ class Generator:\n # This may result in poor performance for large-cardinality `VALUES` tables, due to\n # the deep nesting of the resulting exp.Unions. If this is a problem, either increase\n # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.\n- subquery_expression: exp.Select | exp.Union = selects[0]\n- if len(selects) > 1:\n- for select in selects[1:]:\n- subquery_expression = exp.union(\n- subquery_expression, select, distinct=False, copy=False\n- )\n-\n- return self.subquery_sql(subquery_expression.subquery(expression.alias, copy=False))\n+ subqueryable = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)\n+ return self.subquery_sql(\n+ subqueryable.subquery(alias_node and alias_node.this, copy=False)\n+ )\n \n- alias = f\" AS {expression.alias}\" if expression.alias else \"\"\n+ alias = f\" AS {self.sql(alias_node, 'this')}\" if alias_node else \"\"\n unions = \" UNION ALL \".join(self.sql(select) for select in selects)\n return f\"({unions}){alias}\"\n \ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 0ce24e36..84b26394 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1290,7 +1290,14 @@ class Parser(metaclass=_Parser):\n else:\n begin = self._match(TokenType.BEGIN)\n return_ = self._match_text_seq(\"RETURN\")\n- expression = self._parse_statement()\n+\n+ if self._match(TokenType.STRING, advance=False):\n+ # Takes care of BigQuery's JavaScript UDF definitions that end in an OPTIONS property\n+ # # https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_function_statement\n+ expression = self._parse_string()\n+ extend_props(self._parse_properties())\n+ else:\n+ expression = self._parse_statement()\n \n if return_:\n expression = self.expression(exp.Return, this=expression)\n@@ -1410,20 +1417,18 @@ class Parser(metaclass=_Parser):\n if self._match_text_seq(\"SQL\", \"SECURITY\"):\n return self.expression(exp.SqlSecurityProperty, definer=self._match_text_seq(\"DEFINER\"))\n \n- assignment = self._match_pair(\n- TokenType.VAR, TokenType.EQ, advance=False\n- ) or self._match_pair(TokenType.STRING, TokenType.EQ, advance=False)\n+ index = self._index\n+ key = self._parse_column()\n \n- if assignment:\n- key = self._parse_var_or_string()\n- self._match(TokenType.EQ)\n- return self.expression(\n- exp.Property,\n- this=key,\n- value=self._parse_column() or self._parse_var(any_token=True),\n- )\n+ if not self._match(TokenType.EQ):\n+ self._retreat(index)\n+ return None\n \n- return None\n+ return self.expression(\n+ exp.Property,\n+ this=key.to_dot() if isinstance(key, exp.Column) else key,\n+ value=self._parse_column() or self._parse_var(any_token=True),\n+ )\n \n def _parse_stored(self) -> exp.FileFormatProperty:\n self._match(TokenType.ALIAS)\n@@ -3249,8 +3254,8 @@ class Parser(metaclass=_Parser):\n return self.UNARY_PARSERS[self._prev.token_type](self)\n return self._parse_at_time_zone(self._parse_type())\n \n- def _parse_type(self) -> t.Optional[exp.Expression]:\n- interval = self._parse_interval()\n+ def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:\n+ interval = parse_interval and self._parse_interval()\n if interval:\n return interval\n \n@@ -3426,7 +3431,7 @@ class Parser(metaclass=_Parser):\n return this\n \n def _parse_struct_types(self) -> t.Optional[exp.Expression]:\n- this = self._parse_type() or self._parse_id_var()\n+ this = self._parse_type(parse_interval=False) or self._parse_id_var()\n self._match(TokenType.COLON)\n return self._parse_column_def(this)\n \n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 33d34a6a..1f5f9028 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -721,6 +721,10 @@ WHERE\n self.validate_identity(\n \"CREATE TABLE FUNCTION a(x INT64) RETURNS TABLE AS SELECT s, t\"\n )\n+ self.validate_identity(\n+ '''CREATE TEMPORARY FUNCTION string_length_0(strings ARRAY) RETURNS FLOAT64 LANGUAGE js AS \"\"\"'use strict'; function string_length(strings) { return _.sum(_.map(strings, ((x) => x.length))); } return string_length(strings);\"\"\" OPTIONS (library=['gs://ibis-testing-libraries/lodash.min.js'])''',\n+ \"CREATE TEMPORARY FUNCTION string_length_0(strings ARRAY) RETURNS FLOAT64 LANGUAGE js OPTIONS (library=['gs://ibis-testing-libraries/lodash.min.js']) AS '\\\\'use strict\\\\'; function string_length(strings) { return _.sum(_.map(strings, ((x) => x.length))); } return string_length(strings);'\",\n+ )\n \n def test_group_concat(self):\n self.validate_all(\ndiff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py\nindex d06e0f17..3df968b0 100644\n--- a/tests/dialects/test_databricks.py\n+++ b/tests/dialects/test_databricks.py\n@@ -5,6 +5,9 @@ class TestDatabricks(Validator):\n dialect = \"databricks\"\n \n def test_databricks(self):\n+ self.validate_identity(\"CREATE TABLE t (c STRUCT)\")\n+ self.validate_identity(\"CREATE TABLE my_table () TBLPROPERTIES (a.b=15)\")\n+ self.validate_identity(\"CREATE TABLE my_table () TBLPROPERTIES ('a.b'=15)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO HOUR)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO MINUTE)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO SECOND)\")\ndiff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py\nindex 5bf07e81..c75654c8 100644\n--- a/tests/dialects/test_redshift.py\n+++ b/tests/dialects/test_redshift.py\n@@ -312,9 +312,9 @@ FROM (\n },\n )\n self.validate_all(\n- \"SELECT a, b FROM (VALUES (1, 2), (3, 4)) AS t (a, b)\",\n+ 'SELECT a, b FROM (VALUES (1, 2), (3, 4)) AS \"t\" (a, b)',\n write={\n- \"redshift\": \"SELECT a, b FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3, 4) AS t\",\n+ \"redshift\": 'SELECT a, b FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3, 4) AS \"t\"',\n },\n )\n self.validate_all(\n@@ -341,6 +341,16 @@ FROM (\n \"redshift\": \"INSERT INTO t (a, b) VALUES (1, 2), (3, 4)\",\n },\n )\n+ self.validate_identity(\n+ 'SELECT * FROM (VALUES (1)) AS \"t\"(a)',\n+ '''SELECT\n+ *\n+FROM (\n+ SELECT\n+ 1 AS a\n+) AS \"t\"''',\n+ pretty=True,\n+ )\n \n def test_create_table_like(self):\n self.validate_all(\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_user_defined_functions", "tests/dialects/test_databricks.py::TestDatabricks::test_databricks", "tests/dialects/test_redshift.py::TestRedshift::test_values"]}, {"instance_id": "tobymao__sqlglot-2305", "base_commit": "e1cbff4a180bea06ea22f41f26d0021b7b9df28f", "gold_patch": "diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py\nindex 1349c568..ef6cf711 100644\n--- a/sqlglot/dialects/bigquery.py\n+++ b/sqlglot/dialects/bigquery.py\n@@ -419,6 +419,7 @@ class BigQuery(Dialect):\n RENAME_TABLE_WITH_DB = False\n NVL2_SUPPORTED = False\n UNNEST_WITH_ORDINALITY = False\n+ CLONE_KEYWORD = \"COPY\"\n \n TRANSFORMS = {\n **generator.Generator.TRANSFORMS,\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex b1ee7838..eb3ac434 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -204,6 +204,9 @@ class Generator:\n # Whether or not session variables / parameters are supported, e.g. @x in T-SQL\n SUPPORTS_PARAMETERS = True\n \n+ # The keyword used to clone a table in a DDL statement\n+ CLONE_KEYWORD = \"CLONE\"\n+\n TYPE_MAPPING = {\n exp.DataType.Type.NCHAR: \"CHAR\",\n exp.DataType.Type.NVARCHAR: \"VARCHAR\",\n@@ -817,7 +820,7 @@ class Generator:\n def clone_sql(self, expression: exp.Clone) -> str:\n this = self.sql(expression, \"this\")\n shallow = \"SHALLOW \" if expression.args.get(\"shallow\") else \"\"\n- this = f\"{shallow}CLONE {this}\"\n+ this = f\"{shallow}{self.CLONE_KEYWORD} {this}\"\n when = self.sql(expression, \"when\")\n \n if when:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 84b26394..7b12fa76 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -847,6 +847,7 @@ class Parser(metaclass=_Parser):\n \n INSERT_ALTERNATIVES = {\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"}\n \n+ CLONE_KEYWORDS = {\"CLONE\", \"COPY\"}\n CLONE_KINDS = {\"TIMESTAMP\", \"OFFSET\", \"STATEMENT\"}\n \n TABLE_INDEX_HINT_TOKENS = {TokenType.FORCE, TokenType.IGNORE, TokenType.USE}\n@@ -1344,7 +1345,7 @@ class Parser(metaclass=_Parser):\n \n shallow = self._match_text_seq(\"SHALLOW\")\n \n- if self._match_text_seq(\"CLONE\"):\n+ if self._match_texts(self.CLONE_KEYWORDS):\n clone = self._parse_table(schema=True)\n when = self._match_texts({\"AT\", \"BEFORE\"}) and self._prev.text.upper()\n clone_kind = (\n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 1f5f9028..73efe862 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -122,6 +122,10 @@ class TestBigQuery(Validator):\n \"\"\"SELECT JSON '\"foo\"' AS json_data\"\"\",\n \"\"\"SELECT PARSE_JSON('\"foo\"') AS json_data\"\"\",\n )\n+ self.validate_identity(\n+ \"CREATE OR REPLACE TABLE `a.b.c` copy `a.b.d`\",\n+ \"CREATE OR REPLACE TABLE a.b.c COPY a.b.d\",\n+ )\n \n self.validate_all(\"SELECT SPLIT(foo)\", write={\"bigquery\": \"SELECT SPLIT(foo, ',')\"})\n self.validate_all(\"SELECT 1 AS hash\", write={\"bigquery\": \"SELECT 1 AS `hash`\"})\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery"]}, {"instance_id": "tobymao__sqlglot-2306", "base_commit": "8ed0a810ef4ec36ca648ad55b7a873ce04b8da30", "gold_patch": "diff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py\nindex 9d4a1abe..2eaa2ae9 100644\n--- a/sqlglot/dialects/spark.py\n+++ b/sqlglot/dialects/spark.py\n@@ -54,6 +54,14 @@ class Spark(Spark2):\n FUNCTION_PARSERS = Spark2.Parser.FUNCTION_PARSERS.copy()\n FUNCTION_PARSERS.pop(\"ANY_VALUE\")\n \n+ def _parse_generated_as_identity(\n+ self,\n+ ) -> exp.GeneratedAsIdentityColumnConstraint | exp.ComputedColumnConstraint:\n+ this = super()._parse_generated_as_identity()\n+ if this.expression:\n+ return self.expression(exp.ComputedColumnConstraint, this=this.expression)\n+ return this\n+\n class Generator(Spark2.Generator):\n TYPE_MAPPING = {\n **Spark2.Generator.TYPE_MAPPING,\n@@ -73,6 +81,9 @@ class Spark(Spark2):\n TRANSFORMS.pop(exp.DateDiff)\n TRANSFORMS.pop(exp.Group)\n \n+ def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:\n+ return f\"GENERATED ALWAYS AS ({self.sql(expression, 'this')})\"\n+\n def anyvalue_sql(self, expression: exp.AnyValue) -> str:\n return self.function_fallback_sql(expression)\n \ndiff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py\nindex fa62e789..48017fe1 100644\n--- a/sqlglot/dialects/tsql.py\n+++ b/sqlglot/dialects/tsql.py\n@@ -14,6 +14,7 @@ from sqlglot.dialects.dialect import (\n parse_date_delta,\n rename_func,\n timestrtotime_sql,\n+ ts_or_ds_to_date_sql,\n )\n from sqlglot.expressions import DataType\n from sqlglot.helper import seq_get\n@@ -590,6 +591,7 @@ class TSQL(Dialect):\n NVL2_SUPPORTED = False\n ALTER_TABLE_ADD_COLUMN_KEYWORD = False\n LIMIT_FETCH = \"FETCH\"\n+ COMPUTED_COLUMN_WITH_TYPE = False\n \n TYPE_MAPPING = {\n **generator.Generator.TYPE_MAPPING,\n@@ -630,6 +632,7 @@ class TSQL(Dialect):\n exp.TemporaryProperty: lambda self, e: \"\",\n exp.TimeStrToTime: timestrtotime_sql,\n exp.TimeToStr: _format_sql,\n+ exp.TsOrDsToDate: ts_or_ds_to_date_sql(\"tsql\"),\n }\n \n TRANSFORMS.pop(exp.ReturnsProperty)\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex eb3ac434..20049ba2 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -207,6 +207,9 @@ class Generator:\n # The keyword used to clone a table in a DDL statement\n CLONE_KEYWORD = \"CLONE\"\n \n+ # Whether or not to include the type of a computed column in the CREATE DDL\n+ COMPUTED_COLUMN_WITH_TYPE = True\n+\n TYPE_MAPPING = {\n exp.DataType.Type.NCHAR: \"CHAR\",\n exp.DataType.Type.NVARCHAR: \"VARCHAR\",\n@@ -652,6 +655,9 @@ class Generator:\n position = self.sql(expression, \"position\")\n position = f\" {position}\" if position else \"\"\n \n+ if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:\n+ kind = \"\"\n+\n return f\"{exists}{column}{kind}{constraints}{position}\"\n \n def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 7b12fa76..7d9198fb 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3761,7 +3761,9 @@ class Parser(metaclass=_Parser):\n \n return self.expression(exp.CompressColumnConstraint, this=self._parse_bitwise())\n \n- def _parse_generated_as_identity(self) -> exp.GeneratedAsIdentityColumnConstraint:\n+ def _parse_generated_as_identity(\n+ self,\n+ ) -> exp.GeneratedAsIdentityColumnConstraint | exp.ComputedColumnConstraint:\n if self._match_text_seq(\"BY\", \"DEFAULT\"):\n on_null = self._match_pair(TokenType.ON, TokenType.NULL)\n this = self.expression(\n", "test_patch": "diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py\nindex 3df968b0..21382000 100644\n--- a/tests/dialects/test_databricks.py\n+++ b/tests/dialects/test_databricks.py\n@@ -32,6 +32,7 @@ class TestDatabricks(Validator):\n \"CREATE TABLE foo (x INT GENERATED ALWAYS AS (YEAR(y)))\",\n write={\n \"databricks\": \"CREATE TABLE foo (x INT GENERATED ALWAYS AS (YEAR(TO_DATE(y))))\",\n+ \"tsql\": \"CREATE TABLE foo (x AS YEAR(CAST(y AS DATE)))\",\n },\n )\n \n", "FAIL_TO_PASS": ["tests/dialects/test_databricks.py::TestDatabricks::test_databricks"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_user_defined_functions", "tests/dialects/test_databricks.py::TestDatabricks::test_databricks", "tests/dialects/test_redshift.py::TestRedshift::test_values", "tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery", "tests/dialects/test_databricks.py::TestDatabricks::test_databricks"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-2293_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-2293:latest", "base_commit": "06e0869e7aa5714d77e6ec763da38d6a422965fa", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-2293", "base_commit": "06e0869e7aa5714d77e6ec763da38d6a422965fa", "gold_patch": "diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py\nindex 3dd5c3f4..1349c568 100644\n--- a/sqlglot/dialects/bigquery.py\n+++ b/sqlglot/dialects/bigquery.py\n@@ -178,6 +178,7 @@ class BigQuery(Dialect):\n UNNEST_COLUMN_ONLY = True\n SUPPORTS_USER_DEFINED_TYPES = False\n SUPPORTS_SEMI_ANTI_JOIN = False\n+ LOG_BASE_FIRST = False\n \n # https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#case_sensitivity\n RESOLVES_IDENTIFIERS_AS_UPPERCASE = None\n@@ -265,7 +266,6 @@ class BigQuery(Dialect):\n class Parser(parser.Parser):\n PREFIXED_PIVOT_COLUMNS = True\n \n- LOG_BASE_FIRST = False\n LOG_DEFAULTS_TO_LN = True\n \n FUNCTIONS = {\ndiff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py\nindex bf4ab305..fa62e789 100644\n--- a/sqlglot/dialects/tsql.py\n+++ b/sqlglot/dialects/tsql.py\n@@ -208,6 +208,7 @@ class TSQL(Dialect):\n NULL_ORDERING = \"nulls_are_small\"\n TIME_FORMAT = \"'yyyy-mm-dd hh:mm:ss'\"\n SUPPORTS_SEMI_ANTI_JOIN = False\n+ LOG_BASE_FIRST = False\n \n TIME_MAPPING = {\n \"year\": \"%Y\",\n@@ -400,7 +401,6 @@ class TSQL(Dialect):\n TokenType.END: lambda self: self._parse_command(),\n }\n \n- LOG_BASE_FIRST = False\n LOG_DEFAULTS_TO_LN = True\n \n CONCAT_NULL_OUTPUTS_STRING = True\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 1ddcb2e4..f3b77219 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -99,6 +99,9 @@ class Generator:\n exp.WithJournalTableProperty: lambda self, e: f\"WITH JOURNAL TABLE={self.sql(e, 'this')}\",\n }\n \n+ # Whether the base comes first\n+ LOG_BASE_FIRST = True\n+\n # Whether or not null ordering is supported in order by\n NULL_ORDERING_SUPPORTED = True\n \n@@ -2524,6 +2527,12 @@ class Generator:\n def trycast_sql(self, expression: exp.TryCast) -> str:\n return self.cast_sql(expression, safe_prefix=\"TRY_\")\n \n+ def log_sql(self, expression: exp.Log) -> str:\n+ args = list(expression.args.values())\n+ if not self.LOG_BASE_FIRST:\n+ args.reverse()\n+ return self.func(\"LOG\", *args)\n+\n def use_sql(self, expression: exp.Use) -> str:\n kind = self.sql(expression, \"kind\")\n kind = f\" {kind}\" if kind else \"\"\n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 1da3da29..33d34a6a 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -710,6 +710,8 @@ WHERE\n pretty=True,\n )\n \n+ self.validate_identity(\"LOG(n, b)\")\n+\n def test_user_defined_functions(self):\n self.validate_identity(\n \"CREATE TEMPORARY FUNCTION a(x FLOAT64, y FLOAT64) RETURNS FLOAT64 NOT DETERMINISTIC LANGUAGE js AS 'return x*y;'\"\ndiff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py\nindex f5b43bb6..f76894d6 100644\n--- a/tests/dialects/test_tsql.py\n+++ b/tests/dialects/test_tsql.py\n@@ -198,6 +198,7 @@ class TestTSQL(Validator):\n },\n )\n self.validate_identity(\"HASHBYTES('MD2', 'x')\")\n+ self.validate_identity(\"LOG(n, b)\")\n \n def test_types(self):\n self.validate_identity(\"CAST(x AS XML)\")\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery", "tests/dialects/test_tsql.py::TestTSQL::test_tsql"]}, {"instance_id": "tobymao__sqlglot-2295", "base_commit": "79fc4d1a990cd4b86d55e5a1ce8c37ce5556765c", "gold_patch": "diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex ae73fd3f..554241d9 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -520,7 +520,7 @@ class MySQL(Dialect):\n \n return self.expression(exp.SetItem, this=charset, collate=collate, kind=\"NAMES\")\n \n- def _parse_type(self) -> t.Optional[exp.Expression]:\n+ def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:\n # mysql binary is special and can work anywhere, even in order by operations\n # it operates like a no paren func\n if self._match(TokenType.BINARY, advance=False):\n@@ -529,7 +529,7 @@ class MySQL(Dialect):\n if isinstance(data_type, exp.DataType):\n return self.expression(exp.Cast, this=self._parse_column(), to=data_type)\n \n- return super()._parse_type()\n+ return super()._parse_type(parse_interval=parse_interval)\n \n class Generator(generator.Generator):\n LOCKING_READS_SUPPORTED = True\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 609a0830..37343332 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -752,12 +752,14 @@ class Expression(metaclass=_Expression):\n return klass(this=other, expression=this)\n return klass(this=this, expression=other)\n \n- def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):\n+ def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]) -> Bracket:\n return Bracket(\n this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]\n )\n \n- def __iter__(self):\n+ def __iter__(self) -> t.Iterator:\n+ if \"expressions\" in self.arg_types:\n+ return iter(self.args.get(\"expressions\") or [])\n # We define this because __getitem__ converts Expression into an iterable, which is\n # problematic because one can hit infinite loops if they do \"for x in some_expr: ...\"\n # See: https://peps.python.org/pep-0234/\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 0ce24e36..51dbcd34 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3249,8 +3249,8 @@ class Parser(metaclass=_Parser):\n return self.UNARY_PARSERS[self._prev.token_type](self)\n return self._parse_at_time_zone(self._parse_type())\n \n- def _parse_type(self) -> t.Optional[exp.Expression]:\n- interval = self._parse_interval()\n+ def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:\n+ interval = parse_interval and self._parse_interval()\n if interval:\n return interval\n \n@@ -3426,7 +3426,7 @@ class Parser(metaclass=_Parser):\n return this\n \n def _parse_struct_types(self) -> t.Optional[exp.Expression]:\n- this = self._parse_type() or self._parse_id_var()\n+ this = self._parse_type(parse_interval=False) or self._parse_id_var()\n self._match(TokenType.COLON)\n return self._parse_column_def(this)\n \n", "test_patch": "diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py\nindex d06e0f17..239b8510 100644\n--- a/tests/dialects/test_databricks.py\n+++ b/tests/dialects/test_databricks.py\n@@ -5,6 +5,7 @@ class TestDatabricks(Validator):\n dialect = \"databricks\"\n \n def test_databricks(self):\n+ self.validate_identity(\"CREATE TABLE t (c STRUCT)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO HOUR)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO MINUTE)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO SECOND)\")\ndiff --git a/tests/test_expressions.py b/tests/test_expressions.py\nindex 9456a19c..b1b53601 100644\n--- a/tests/test_expressions.py\n+++ b/tests/test_expressions.py\n@@ -15,8 +15,10 @@ class TestExpressions(unittest.TestCase):\n self.assertEqual(parse_one(\"x(1)\").find(exp.Literal).depth, 1)\n \n def test_iter(self):\n+ self.assertEqual([exp.Literal.number(1), exp.Literal.number(2)], list(parse_one(\"[1, 2]\")))\n+\n with self.assertRaises(TypeError):\n- for x in parse_one(\"SELECT 1\"):\n+ for x in parse_one(\"1\"):\n pass\n \n def test_eq(self):\n", "FAIL_TO_PASS": ["tests/dialects/test_databricks.py::TestDatabricks::test_databricks", "tests/test_expressions.py::TestExpressions::test_iter"]}, {"instance_id": "tobymao__sqlglot-2296", "base_commit": "44f732d56eafb93880790955862bac454edf800f", "gold_patch": "diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py\nindex 655e92a6..a4278707 100644\n--- a/sqlglot/dialects/hive.py\n+++ b/sqlglot/dialects/hive.py\n@@ -111,7 +111,7 @@ def _array_sort_sql(self: Hive.Generator, expression: exp.ArraySort) -> str:\n \n \n def _property_sql(self: Hive.Generator, expression: exp.Property) -> str:\n- return f\"'{expression.name}'={self.sql(expression, 'value')}\"\n+ return f\"{self.property_name(expression, string_key=True)}={self.sql(expression, 'value')}\"\n \n \n def _str_to_unix_sql(self: Hive.Generator, expression: exp.StrToUnix) -> str:\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 37343332..ae143531 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -1175,7 +1175,7 @@ class Column(Condition):\n if self.args.get(part)\n ]\n \n- def to_dot(self) -> Dot:\n+ def to_dot(self) -> Dot | Identifier:\n \"\"\"Converts the column into a dot expression.\"\"\"\n parts = self.parts\n parent = self.parent\n@@ -1185,7 +1185,7 @@ class Column(Condition):\n parts.append(parent.expression)\n parent = parent.parent\n \n- return Dot.build(deepcopy(parts))\n+ return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]\n \n \n class ColumnPosition(Expression):\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex f3b77219..0d99fb20 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1084,10 +1084,15 @@ class Generator:\n \n return properties_locs\n \n+ def property_name(self, expression: exp.Property, string_key: bool = False) -> str:\n+ if isinstance(expression.this, exp.Dot):\n+ return self.sql(expression, \"this\")\n+ return f\"'{expression.name}'\" if string_key else expression.name\n+\n def property_sql(self, expression: exp.Property) -> str:\n property_cls = expression.__class__\n if property_cls == exp.Property:\n- return f\"{expression.name}={self.sql(expression, 'value')}\"\n+ return f\"{self.property_name(expression)}={self.sql(expression, 'value')}\"\n \n property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)\n if not property_name:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 51dbcd34..09cf86b8 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1410,20 +1410,18 @@ class Parser(metaclass=_Parser):\n if self._match_text_seq(\"SQL\", \"SECURITY\"):\n return self.expression(exp.SqlSecurityProperty, definer=self._match_text_seq(\"DEFINER\"))\n \n- assignment = self._match_pair(\n- TokenType.VAR, TokenType.EQ, advance=False\n- ) or self._match_pair(TokenType.STRING, TokenType.EQ, advance=False)\n+ index = self._index\n+ key = self._parse_column()\n \n- if assignment:\n- key = self._parse_var_or_string()\n- self._match(TokenType.EQ)\n- return self.expression(\n- exp.Property,\n- this=key,\n- value=self._parse_column() or self._parse_var(any_token=True),\n- )\n+ if not self._match(TokenType.EQ):\n+ self._retreat(index)\n+ return None\n \n- return None\n+ return self.expression(\n+ exp.Property,\n+ this=key.to_dot() if isinstance(key, exp.Column) else key,\n+ value=self._parse_column() or self._parse_var(any_token=True),\n+ )\n \n def _parse_stored(self) -> exp.FileFormatProperty:\n self._match(TokenType.ALIAS)\n", "test_patch": "diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py\nindex 239b8510..3df968b0 100644\n--- a/tests/dialects/test_databricks.py\n+++ b/tests/dialects/test_databricks.py\n@@ -6,6 +6,8 @@ class TestDatabricks(Validator):\n \n def test_databricks(self):\n self.validate_identity(\"CREATE TABLE t (c STRUCT)\")\n+ self.validate_identity(\"CREATE TABLE my_table () TBLPROPERTIES (a.b=15)\")\n+ self.validate_identity(\"CREATE TABLE my_table () TBLPROPERTIES ('a.b'=15)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO HOUR)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO MINUTE)\")\n self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO SECOND)\")\n", "FAIL_TO_PASS": ["tests/dialects/test_databricks.py::TestDatabricks::test_databricks"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery", "tests/dialects/test_tsql.py::TestTSQL::test_tsql", "tests/dialects/test_databricks.py::TestDatabricks::test_databricks", "tests/test_expressions.py::TestExpressions::test_iter", "tests/dialects/test_databricks.py::TestDatabricks::test_databricks"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "omni-us__jsonargparse-560_x3", "level": 3, "source": "swerebench", "repo": "omni-us/jsonargparse", "image": "swerebench/sweb.eval.x86_64.omni-us_1776_jsonargparse-560:latest", "base_commit": "c634a88f120b96d87f80e079417f0138aabe466f", "num_bugs": 3, "bugs": [{"instance_id": "omni-us__jsonargparse-560", "base_commit": "c634a88f120b96d87f80e079417f0138aabe466f", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex e531ed7..7fc944c 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -19,6 +19,8 @@ Fixed\n ^^^^^\n - ``dict`` types not correctly forwarding previous nested values when parsing\n (`#559 `__).\n+- ``List`` type incorrectly using defaults from previous item (`#560\n+ `__).\n \n \n v4.32.0 (2024-07-19)\ndiff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py\nindex 4c90a74..98b79c3 100644\n--- a/jsonargparse/_typehints.py\n+++ b/jsonargparse/_typehints.py\n@@ -871,10 +871,11 @@ def adapt_typehints(\n elif not isinstance(val, list):\n raise_unexpected_value(f\"Expected a {typehint_origin}\", val)\n if subtypehints is not None:\n- adapt_kwargs_n = adapt_kwargs\n for n, v in enumerate(val):\n if isinstance(prev_val, list) and len(prev_val) == len(val):\n- adapt_kwargs_n = {**adapt_kwargs, \"prev_val\": prev_val[n]}\n+ adapt_kwargs_n = {**deepcopy(adapt_kwargs), \"prev_val\": prev_val[n]}\n+ else:\n+ adapt_kwargs_n = deepcopy(adapt_kwargs)\n val[n] = adapt_typehints(v, subtypehints[0], list_item=True, **adapt_kwargs_n)\n \n # Dict, Mapping\n", "test_patch": "diff --git a/jsonargparse_tests/test_dataclass_like.py b/jsonargparse_tests/test_dataclass_like.py\nindex 963eeaf..818eb3b 100644\n--- a/jsonargparse_tests/test_dataclass_like.py\n+++ b/jsonargparse_tests/test_dataclass_like.py\n@@ -203,6 +203,18 @@ def test_list_nested_optional_dataclass(parser):\n assert cfg.b == [Namespace(a=Namespace(x=1))]\n \n \n+@dataclasses.dataclass\n+class ItemData:\n+ x: int = 1\n+ y: str = \"one\"\n+\n+\n+def test_list_append_defaults(parser):\n+ parser.add_argument(\"--list\", type=List[ItemData])\n+ cfg = parser.parse_args([\"--list+={}\", '--list+={\"x\":2,\"y\":\"two\"}', '--list+={\"x\":3}'])\n+ assert cfg.list == [Namespace(x=1, y=\"one\"), Namespace(x=2, y=\"two\"), Namespace(x=3, y=\"one\")]\n+\n+\n def test_add_argument_dataclass_type(parser):\n parser.add_argument(\"--b\", type=DataClassB, default=DataClassB(b1=7.0))\n cfg = parser.get_defaults()\n", "FAIL_TO_PASS": ["jsonargparse_tests/test_dataclass_like.py::test_list_append_defaults"]}, {"instance_id": "omni-us__jsonargparse-562", "base_commit": "f7aa49f434115f721a16a373c598d5fb9aaa2d5f", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 7fc944c..28d4c38 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -21,6 +21,8 @@ Fixed\n (`#559 `__).\n - ``List`` type incorrectly using defaults from previous item (`#560\n `__).\n+- ``--print_shtab`` not adding file completer for ``_ActionConfigLoad`` (`#562\n+ `__).\n \n \n v4.32.0 (2024-07-19)\ndiff --git a/jsonargparse/_completions.py b/jsonargparse/_completions.py\nindex ee722e5..15e6b36 100644\n--- a/jsonargparse/_completions.py\n+++ b/jsonargparse/_completions.py\n@@ -12,7 +12,7 @@ from importlib.util import find_spec\n from subprocess import PIPE, Popen\n from typing import List, Union\n \n-from ._actions import ActionConfigFile, _ActionHelpClassPath, remove_actions\n+from ._actions import ActionConfigFile, _ActionConfigLoad, _ActionHelpClassPath, remove_actions\n from ._parameter_resolvers import get_signature_parameters\n from ._typehints import (\n ActionTypeHint,\n@@ -142,7 +142,7 @@ def shtab_prepare_action(action, parser) -> None:\n return\n \n complete = None\n- if isinstance(action, ActionConfigFile):\n+ if isinstance(action, (ActionConfigFile, _ActionConfigLoad)):\n complete = shtab.FILE\n elif isinstance(action, ActionTypeHint):\n typehint = action._typehint\n", "test_patch": "diff --git a/jsonargparse_tests/test_shtab.py b/jsonargparse_tests/test_shtab.py\nindex ae463a9..9802357 100644\n--- a/jsonargparse_tests/test_shtab.py\n+++ b/jsonargparse_tests/test_shtab.py\n@@ -194,6 +194,12 @@ class Base:\n pass\n \n \n+def test_bash_class_config(parser):\n+ parser.add_class_arguments(Base, \"class\")\n+ shtab_script = get_shtab_script(parser, \"bash\")\n+ assert \"_class_COMPGEN=_shtab_compgen_files\" in shtab_script\n+\n+\n class SubA(Base):\n def __init__(self, p1: int, p2: AXEnum):\n pass\n", "FAIL_TO_PASS": ["jsonargparse_tests/test_shtab.py::test_bash_class_config"]}, {"instance_id": "omni-us__jsonargparse-564", "base_commit": "54ff57e6f22c3502fc478238714e8b8ba646fe01", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 28d4c38..614018b 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -23,6 +23,8 @@ Fixed\n `__).\n - ``--print_shtab`` not adding file completer for ``_ActionConfigLoad`` (`#562\n `__).\n+- ``parser_mode`` not inherited by nested parsers (`#564\n+ `__).\n \n \n v4.32.0 (2024-07-19)\ndiff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py\nindex 98b79c3..aeaaad2 100644\n--- a/jsonargparse/_typehints.py\n+++ b/jsonargparse/_typehints.py\n@@ -615,7 +615,7 @@ class ActionTypeHint(Action):\n if skip_args:\n kwargs.setdefault(\"skip\", set()).add(skip_args)\n parser = parent_parser.get()\n- parser = type(parser)(exit_on_error=False, logger=parser.logger)\n+ parser = type(parser)(exit_on_error=False, logger=parser.logger, parser_mode=parser.parser_mode)\n remove_actions(parser, (ActionConfigFile, _ActionPrintConfig))\n if inspect.isclass(val_class):\n parser.add_class_arguments(val_class, **kwargs)\n", "test_patch": "diff --git a/jsonargparse_tests/test_loaders_dumpers.py b/jsonargparse_tests/test_loaders_dumpers.py\nindex bbeedfc..692a473 100644\n--- a/jsonargparse_tests/test_loaders_dumpers.py\n+++ b/jsonargparse_tests/test_loaders_dumpers.py\n@@ -1,6 +1,7 @@\n from __future__ import annotations\n \n import os\n+from dataclasses import dataclass\n from typing import List\n from unittest.mock import patch\n \n@@ -129,6 +130,39 @@ def test_load_value_dash():\n assert \" - \" == load_value(\" - \")\n \n \n+@dataclass\n+class CustomData:\n+ fn: dict\n+\n+\n+class CustomContainer:\n+ def __init__(self, data: CustomData):\n+ self.data = data\n+\n+\n+def custom_loader(data):\n+ data = yaml.safe_load(data)\n+ if isinstance(data, dict) and \"fn\" in data:\n+ data[\"fn\"] = {k: custom_loader for k in data[\"fn\"]}\n+ return data\n+\n+\n+def custom_dumper(data):\n+ if \"data\" in data and \"fn\" in data[\"data\"]:\n+ data[\"data\"][\"fn\"] = {k: \"dumped\" for k in data[\"data\"][\"fn\"]}\n+ return yaml_dump(data)\n+\n+\n+def test_nested_parser_mode(parser):\n+ set_loader(\"custom\", custom_loader)\n+ set_dumper(\"custom\", custom_dumper)\n+ parser.parser_mode = \"custom\"\n+ parser.add_argument(\"--custom\", type=CustomContainer)\n+ cfg = parser.parse_args(['--custom.data={\"fn\": {\"key\": \"value\"}}'])\n+ dump = yaml.safe_load(parser.dump(cfg))\n+ assert dump[\"custom\"][\"init_args\"][\"data\"] == {\"fn\": {\"key\": \"dumped\"}}\n+\n+\n @pytest.mark.skipif(\n not (omegaconf_support and \"JSONARGPARSE_OMEGACONF_FULL_TEST\" in os.environ),\n reason=\"only for omegaconf as the yaml loader\",\n", "FAIL_TO_PASS": ["jsonargparse_tests/test_loaders_dumpers.py::test_nested_parser_mode"]}], "all_FAIL_TO_PASS": ["jsonargparse_tests/test_dataclass_like.py::test_list_append_defaults", "jsonargparse_tests/test_shtab.py::test_bash_class_config", "jsonargparse_tests/test_loaders_dumpers.py::test_nested_parser_mode"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "matthewwithanm__python-markdownify-169_x3", "level": 3, "source": "swerebench", "repo": "matthewwithanm/python-markdownify", "image": "swerebench/sweb.eval.x86_64.matthewwithanm_1776_python-markdownify-169:latest", "base_commit": "6258f5c38b97ab443b4ddf03e6676ce29b392d06", "num_bugs": 3, "bugs": [{"instance_id": "matthewwithanm__python-markdownify-169", "base_commit": "6258f5c38b97ab443b4ddf03e6676ce29b392d06", "gold_patch": "diff --git a/README.rst b/README.rst\nindex 98473c6..af87f51 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -143,6 +143,7 @@ wrap, wrap_width\n If ``wrap`` is set to ``True``, all text paragraphs are wrapped at\n ``wrap_width`` characters. Defaults to ``False`` and ``80``.\n Use with ``newline_style=BACKSLASH`` to keep line breaks in paragraphs.\n+ A `wrap_width` value of `None` reflows lines to unlimited line length.\n \n Options may be specified as kwargs to the ``markdownify`` function, or as a\n nested ``Options`` class in ``MarkdownConverter`` subclasses.\ndiff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex 3272ce5..b70a0e5 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -264,6 +264,8 @@ class MarkdownConverter(object):\n return '\\n\\n%s\\n%s\\n\\n' % (text, pad_char * len(text)) if text else ''\n \n def convert_a(self, el, text, convert_as_inline):\n+ if el.find_parent(['pre', 'code', 'kbd', 'samp']):\n+ return text\n prefix, suffix, text = chomp(text)\n if not text:\n return ''\n@@ -398,18 +400,19 @@ class MarkdownConverter(object):\n # Preserve newlines (and preceding whitespace) resulting\n # from
tags. Newlines in the input have already been\n # replaced by spaces.\n- lines = text.split('\\n')\n- new_lines = []\n- for line in lines:\n- line = line.lstrip()\n- line_no_trailing = line.rstrip()\n- trailing = line[len(line_no_trailing):]\n- line = fill(line,\n- width=self.options['wrap_width'],\n- break_long_words=False,\n- break_on_hyphens=False)\n- new_lines.append(line + trailing)\n- text = '\\n'.join(new_lines)\n+ if self.options['wrap_width'] is not None:\n+ lines = text.split('\\n')\n+ new_lines = []\n+ for line in lines:\n+ line = line.lstrip()\n+ line_no_trailing = line.rstrip()\n+ trailing = line[len(line_no_trailing):]\n+ line = fill(line,\n+ width=self.options['wrap_width'],\n+ break_long_words=False,\n+ break_on_hyphens=False)\n+ new_lines.append(line + trailing)\n+ text = '\\n'.join(new_lines)\n return '\\n\\n%s\\n\\n' % text if text else ''\n \n def convert_pre(self, el, text, convert_as_inline):\n@@ -442,7 +445,7 @@ class MarkdownConverter(object):\n return '\\n\\n' + text + '\\n'\n \n def convert_caption(self, el, text, convert_as_inline):\n- return text + '\\n'\n+ return text + '\\n\\n'\n \n def convert_figcaption(self, el, text, convert_as_inline):\n return '\\n\\n' + text + '\\n\\n'\n", "test_patch": "diff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex 2283c29..01f8b91 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -39,6 +39,11 @@ def test_a_no_autolinks():\n assert md('
https://google.com', autolinks=False) == '[https://google.com](https://google.com)'\n \n \n+def test_a_in_code():\n+ assert md('Google') == '`Google`'\n+ assert md('
Google
') == '\\n```\\nGoogle\\n```\\n'\n+\n+\n def test_b():\n assert md('Hello') == '**Hello**'\n \n@@ -219,6 +224,7 @@ def test_p():\n assert md('

123456789 123456789

') == '\\n\\n123456789 123456789\\n\\n'\n assert md('

123456789\\n\\n\\n123456789

') == '\\n\\n123456789\\n123456789\\n\\n'\n assert md('

123456789\\n\\n\\n123456789

', wrap=True, wrap_width=80) == '\\n\\n123456789 123456789\\n\\n'\n+ assert md('

123456789\\n\\n\\n123456789

', wrap=True, wrap_width=None) == '\\n\\n123456789 123456789\\n\\n'\n assert md('

123456789 123456789

', wrap=True, wrap_width=10) == '\\n\\n123456789\\n123456789\\n\\n'\n assert md('

Some long link

', wrap=True, wrap_width=10) == '\\n\\n[Some long\\nlink](https://example.com)\\n\\n'\n assert md('

12345
67890

', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '\\n\\n12345\\\\\\n67890\\n\\n'\ndiff --git a/tests/test_tables.py b/tests/test_tables.py\nindex fc6eee6..dcf9ad7 100644\n--- a/tests/test_tables.py\n+++ b/tests/test_tables.py\n@@ -249,6 +249,6 @@ def test_table():\n assert md(table_missing_text) == '\\n\\n| | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_missing_head) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_body) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n- assert md(table_with_caption) == 'TEXT\\n\\nCaption\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n\\n'\n+ assert md(table_with_caption) == 'TEXT\\n\\nCaption\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n\\n'\n assert md(table_with_colspan) == '\\n\\n| Name | | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_with_undefined_colspan) == '\\n\\n| Name | Age |\\n| --- | --- |\\n| Jill | Smith |\\n\\n'\n", "FAIL_TO_PASS": ["tests/test_conversions.py::test_a_in_code", "tests/test_conversions.py::test_p", "tests/test_tables.py::test_table"]}, {"instance_id": "matthewwithanm__python-markdownify-171", "base_commit": "600f77d2444233b1c5e838b69390cbbf92bde1e1", "gold_patch": "diff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex b70a0e5..fd03569 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -5,7 +5,7 @@ import six\n \n \n convert_heading_re = re.compile(r'convert_h(\\d+)')\n-line_beginning_re = re.compile(r'^', re.MULTILINE)\n+line_with_content_re = re.compile(r'^(.*)', flags=re.MULTILINE)\n whitespace_re = re.compile(r'[\\t ]+')\n all_whitespace_re = re.compile(r'[\\t \\r\\n]+')\n newline_whitespace_re = re.compile(r'[\\t \\r\\n]*[\\r\\n][\\t \\r\\n]*')\n@@ -256,9 +256,6 @@ class MarkdownConverter(object):\n text = text.replace('_', r'\\_')\n return text\n \n- def indent(self, text, columns):\n- return line_beginning_re.sub(' ' * columns, text) if text else ''\n-\n def underline(self, text, pad_char):\n text = (text or '').rstrip()\n return '\\n\\n%s\\n%s\\n\\n' % (text, pad_char * len(text)) if text else ''\n@@ -286,11 +283,20 @@ class MarkdownConverter(object):\n convert_b = abstract_inline_conversion(lambda self: 2 * self.options['strong_em_symbol'])\n \n def convert_blockquote(self, el, text, convert_as_inline):\n-\n+ # handle some early-exit scenarios\n+ text = (text or '').strip()\n if convert_as_inline:\n- return ' ' + text.strip() + ' '\n+ return ' ' + text + ' '\n+ if not text:\n+ return \"\\n\"\n+\n+ # indent lines with blockquote marker\n+ def _indent_for_blockquote(match):\n+ line_content = match.group(1)\n+ return '> ' + line_content if line_content else '>'\n+ text = line_with_content_re.sub(_indent_for_blockquote, text)\n \n- return '\\n' + (line_beginning_re.sub('> ', text.strip()) + '\\n\\n') if text else ''\n+ return '\\n' + text + '\\n\\n'\n \n def convert_br(self, el, text, convert_as_inline):\n if convert_as_inline:\n@@ -371,6 +377,12 @@ class MarkdownConverter(object):\n convert_ol = convert_list\n \n def convert_li(self, el, text, convert_as_inline):\n+ # handle some early-exit scenarios\n+ text = (text or '').strip()\n+ if not text:\n+ return \"\\n\"\n+\n+ # determine list item bullet character to use\n parent = el.parent\n if parent is not None and parent.name == 'ol':\n if parent.get(\"start\") and str(parent.get(\"start\")).isnumeric():\n@@ -387,10 +399,18 @@ class MarkdownConverter(object):\n bullets = self.options['bullets']\n bullet = bullets[depth % len(bullets)]\n bullet = bullet + ' '\n- text = (text or '').strip()\n- text = self.indent(text, len(bullet))\n- if text:\n- text = bullet + text[len(bullet):]\n+ bullet_width = len(bullet)\n+ bullet_indent = ' ' * bullet_width\n+\n+ # indent content lines by bullet width\n+ def _indent_for_li(match):\n+ line_content = match.group(1)\n+ return bullet_indent + line_content if line_content else ''\n+ text = line_with_content_re.sub(_indent_for_li, text)\n+\n+ # insert bullet into first-line indent whitespace\n+ text = bullet + text[bullet_width:]\n+\n return '%s\\n' % text\n \n def convert_p(self, el, text, convert_as_inline):\n", "test_patch": "diff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex 01f8b91..868db7c 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -62,7 +62,7 @@ def test_blockquote():\n \n def test_blockquote_with_nested_paragraph():\n assert md('

Hello

') == '\\n> Hello\\n\\n'\n- assert md('

Hello

Hello again

') == '\\n> Hello\\n> \\n> Hello again\\n\\n'\n+ assert md('

Hello

Hello again

') == '\\n> Hello\\n>\\n> Hello again\\n\\n'\n \n \n def test_blockquote_with_paragraph():\ndiff --git a/tests/test_lists.py b/tests/test_lists.py\nindex a660778..ce54a87 100644\n--- a/tests/test_lists.py\n+++ b/tests/test_lists.py\n@@ -47,7 +47,7 @@ def test_ol():\n assert md('
  1. a
  2. b
') == '\\n\\n1. a\\n2. b\\n'\n assert md('
  1. a
  2. b
') == '\\n\\n1. a\\n2. b\\n'\n assert md('
  1. a
  2. b
') == '\\n\\n1. a\\n2. b\\n'\n- assert md('
  1. first para

    second para

  2. third para

    fourth para

') == '\\n\\n1234. first para\\n \\n second para\\n1235. third para\\n \\n fourth para\\n'\n+ assert md('
  1. first para

    second para

  2. third para

    fourth para

') == '\\n\\n1234. first para\\n\\n second para\\n1235. third para\\n\\n fourth para\\n'\n \n \n def test_nested_ols():\n@@ -64,7 +64,7 @@ def test_ul():\n
  • c\n
  • \n \"\"\") == '\\n\\n* a\\n* b\\n* c\\n'\n- assert md('
    • first para

      second para

    • third para

      fourth para

    ') == '\\n\\n* first para\\n \\n second para\\n* third para\\n \\n fourth para\\n'\n+ assert md('
    • first para

      second para

    • third para

      fourth para

    ') == '\\n\\n* first para\\n\\n second para\\n* third para\\n\\n fourth para\\n'\n \n \n def test_inline_ul():\n", "FAIL_TO_PASS": ["tests/test_conversions.py::test_blockquote_with_nested_paragraph", "tests/test_lists.py::test_ol", "tests/test_lists.py::test_ul"]}, {"instance_id": "matthewwithanm__python-markdownify-173", "base_commit": "f73a4353150c2bb99f3dc8c733cb997cb45a6ac7", "gold_patch": "diff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex fd03569..ac53077 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -319,6 +319,38 @@ class MarkdownConverter(object):\n \n convert_kbd = convert_code\n \n+ def convert_dd(self, el, text, convert_as_inline):\n+ text = (text or '').strip()\n+ if convert_as_inline:\n+ return ' ' + text + ' '\n+ if not text:\n+ return '\\n'\n+\n+ # indent definition content lines by four spaces\n+ def _indent_for_dd(match):\n+ line_content = match.group(1)\n+ return ' ' + line_content if line_content else ''\n+ text = line_with_content_re.sub(_indent_for_dd, text)\n+\n+ # insert definition marker into first-line indent whitespace\n+ text = ':' + text[1:]\n+\n+ return '%s\\n' % text\n+\n+ def convert_dt(self, el, text, convert_as_inline):\n+ # remove newlines from term text\n+ text = (text or '').strip()\n+ text = all_whitespace_re.sub(' ', text)\n+ if convert_as_inline:\n+ return ' ' + text + ' '\n+ if not text:\n+ return '\\n'\n+\n+ # TODO - format consecutive
    elements as directly adjacent lines):\n+ # https://michelf.ca/projects/php-markdown/extra/#def-list\n+\n+ return '\\n%s\\n' % text\n+\n def _convert_hn(self, n, el, text, convert_as_inline):\n \"\"\" Method name prefixed with _ to prevent to call this \"\"\"\n if convert_as_inline:\n", "test_patch": "diff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex 868db7c..cc5ebc7 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -104,6 +104,16 @@ def test_code():\n assert md('foobarbaz', sub_symbol='^') == '`foobarbaz`'\n \n \n+def test_dl():\n+ assert md('
    term
    definition
    ') == '\\nterm\\n: definition\\n'\n+ assert md('

    te

    rm

    definition
    ') == '\\nte rm\\n: definition\\n'\n+ assert md('
    term

    definition-p1

    definition-p2

    ') == '\\nterm\\n: definition-p1\\n\\n definition-p2\\n'\n+ assert md('
    term

    definition 1

    definition 2

    ') == '\\nterm\\n: definition 1\\n: definition 2\\n'\n+ assert md('
    term 1
    definition 1
    term 2
    definition 2
    ') == '\\nterm 1\\n: definition 1\\nterm 2\\n: definition 2\\n'\n+ assert md('
    term

    line 1

    line 2

    ') == '\\nterm\\n: > line 1\\n >\\n > line 2\\n'\n+ assert md('
    term
    1. 1

      • 2a
      • 2b
    2. 3

    ') == '\\nterm\\n: 1. 1\\n\\n * 2a\\n * 2b\\n 2. 3\\n'\n+\n+\n def test_del():\n inline_tests('del', '~~')\n \n", "FAIL_TO_PASS": ["tests/test_conversions.py::test_dl"]}], "all_FAIL_TO_PASS": ["tests/test_conversions.py::test_a_in_code", "tests/test_conversions.py::test_p", "tests/test_tables.py::test_table", "tests/test_conversions.py::test_blockquote_with_nested_paragraph", "tests/test_lists.py::test_ol", "tests/test_lists.py::test_ul", "tests/test_conversions.py::test_dl"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ipython__ipykernel-1049_x3", "level": 3, "source": "swerebench", "repo": "ipython/ipykernel", "image": "swerebench/sweb.eval.x86_64.ipython_1776_ipykernel-1049:latest", "base_commit": "4dc303364ca73b5185685807de41c7fe4b4a4dc7", "num_bugs": 3, "bugs": [{"instance_id": "ipython__ipykernel-1049", "base_commit": "4dc303364ca73b5185685807de41c7fe4b4a4dc7", "gold_patch": "diff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex f1fb0c8..c06d233 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -71,6 +71,9 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def __init__(self, *args, **kwargs):\n # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n+ for name in self.trait_names():\n+ if name in kwargs:\n+ kwargs.pop(name)\n BaseComm.__init__(self, *args, **kwargs)\n \n \ndiff --git a/ipykernel/ipkernel.py b/ipykernel/ipkernel.py\nindex f86f304..4dfe59c 100644\n--- a/ipykernel/ipkernel.py\n+++ b/ipykernel/ipkernel.py\n@@ -5,6 +5,7 @@ import builtins\n import getpass\n import signal\n import sys\n+import threading\n import typing as t\n from contextlib import contextmanager\n from functools import partial\n@@ -46,9 +47,19 @@ def _create_comm(*args, **kwargs):\n return BaseComm(*args, **kwargs)\n \n \n+# there can only be one comm manager in a ipykernel process\n+_comm_lock = threading.Lock()\n+_comm_manager: t.Optional[CommManager] = None\n+\n+\n def _get_comm_manager(*args, **kwargs):\n \"\"\"Create a new CommManager.\"\"\"\n- return CommManager(*args, **kwargs)\n+ global _comm_manager\n+ if _comm_manager is None:\n+ with _comm_lock:\n+ if _comm_manager is None:\n+ _comm_manager = CommManager(*args, **kwargs)\n+ return _comm_manager\n \n \n comm.create_comm = _create_comm\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 33c0546..f1e536d 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -27,8 +27,8 @@ requires-python = \">=3.8\"\n dependencies = [\n \"debugpy>=1.0\",\n \"ipython>=7.23.1\",\n- \"comm>=0.1\",\n- \"traitlets>=5.1.0\",\n+ \"comm>=0.1.1\",\n+ \"traitlets>=5.4.0\",\n \"jupyter_client>=6.1.12\",\n \"tornado>=6.1\",\n \"matplotlib-inline>=0.1\",\n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex 3ab1e5c..9dd49f8 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -1,7 +1,87 @@\n-from ipykernel.comm import Comm\n+from ipykernel.comm import Comm, CommManager\n+from ipykernel.ipkernel import IPythonKernel\n \n \n-async def test_comm(kernel):\n- c = Comm()\n- c.kernel = kernel # type:ignore\n+def test_comm(kernel):\n+ manager = CommManager(kernel=kernel)\n+ kernel.comm_manager = manager\n+\n+ c = Comm(kernel=kernel)\n+ msgs = []\n+\n+ def on_close(msg):\n+ msgs.append(msg)\n+\n+ def on_message(msg):\n+ msgs.append(msg)\n+\n c.publish_msg(\"foo\")\n+ c.open({})\n+ c.on_msg(on_message)\n+ c.on_close(on_close)\n+ c.handle_msg({})\n+ c.handle_close({})\n+ c.close()\n+ assert len(msgs) == 2\n+\n+\n+def test_comm_manager(kernel):\n+ manager = CommManager(kernel=kernel)\n+ msgs = []\n+\n+ def foo(comm, msg):\n+ msgs.append(msg)\n+ comm.close()\n+\n+ def fizz(comm, msg):\n+ raise RuntimeError('hi')\n+\n+ def on_close(msg):\n+ msgs.append(msg)\n+\n+ def on_msg(msg):\n+ msgs.append(msg)\n+\n+ manager.register_target(\"foo\", foo)\n+ manager.register_target(\"fizz\", fizz)\n+\n+ kernel.comm_manager = manager\n+ comm = Comm()\n+ comm.on_msg(on_msg)\n+ comm.on_close(on_close)\n+ manager.register_comm(comm)\n+\n+ assert manager.get_comm(comm.comm_id) == comm\n+ assert manager.get_comm('foo') is None\n+\n+ msg = dict(content=dict(comm_id=comm.comm_id, target_name='foo'))\n+ manager.comm_open(None, None, msg)\n+ assert len(msgs) == 1\n+ msg['content']['target_name'] = 'bar'\n+ manager.comm_open(None, None, msg)\n+ assert len(msgs) == 1\n+ msg = dict(content=dict(comm_id=comm.comm_id, target_name='fizz'))\n+ manager.comm_open(None, None, msg)\n+ assert len(msgs) == 1\n+\n+ manager.register_comm(comm)\n+ assert manager.get_comm(comm.comm_id) == comm\n+ msg = dict(content=dict(comm_id=comm.comm_id))\n+ manager.comm_msg(None, None, msg)\n+ assert len(msgs) == 2\n+ msg['content']['comm_id'] = 'foo'\n+ manager.comm_msg(None, None, msg)\n+ assert len(msgs) == 2\n+\n+ manager.register_comm(comm)\n+ assert manager.get_comm(comm.comm_id) == comm\n+ msg = dict(content=dict(comm_id=comm.comm_id))\n+ manager.comm_close(None, None, msg)\n+ assert len(msgs) == 3\n+\n+ assert comm._closed\n+\n+\n+def test_comm_in_manager(ipkernel: IPythonKernel) -> None:\n+ comm = Comm()\n+ assert comm.comm_id in ipkernel.comm_manager.comms\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm", "ipykernel/tests/test_comm.py::test_comm_in_manager"]}, {"instance_id": "ipython__ipykernel-1051", "base_commit": "b13c46ac5fa800359748386c64f89402ac0e204e", "gold_patch": "diff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex c06d233..295232e 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -71,9 +71,8 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def __init__(self, *args, **kwargs):\n # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n- for name in self.trait_names():\n- if name in kwargs:\n- kwargs.pop(name)\n+ # drop arguments not in BaseComm\n+ kwargs.pop(\"kernel\", None)\n BaseComm.__init__(self, *args, **kwargs)\n \n \n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex 9dd49f8..f8b0764 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -6,7 +6,7 @@ def test_comm(kernel):\n manager = CommManager(kernel=kernel)\n kernel.comm_manager = manager\n \n- c = Comm(kernel=kernel)\n+ c = Comm(kernel=kernel, target_name=\"bar\")\n msgs = []\n \n def on_close(msg):\n@@ -23,6 +23,7 @@ def test_comm(kernel):\n c.handle_close({})\n c.close()\n assert len(msgs) == 2\n+ assert c.target_name == \"bar\"\n \n \n def test_comm_manager(kernel):\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm"]}, {"instance_id": "ipython__ipykernel-1056", "base_commit": "04e1d753e328194be391b62ffd22662f0fe6dc56", "gold_patch": "diff --git a/.github/workflows/downstream.yml b/.github/workflows/downstream.yml\nindex ab1f103..57c8561 100644\n--- a/.github/workflows/downstream.yml\n+++ b/.github/workflows/downstream.yml\n@@ -84,6 +84,41 @@ jobs:\n pip install -e \".[test]\"\n python test_ipykernel.py\n \n+ qtconsole:\n+ runs-on: ubuntu-latest\n+ timeout-minutes: 20\n+ steps:\n+ - name: Checkout\n+ uses: actions/checkout@v3\n+\n+ - name: Setup Python\n+ uses: actions/setup-python@v4\n+ with:\n+ python-version: \"3.9\"\n+ architecture: \"x64\"\n+\n+ - name: Install System Packages\n+ run: |\n+ sudo apt-get update\n+ sudo apt-get install -y --no-install-recommends '^libxcb.*-dev' libx11-xcb-dev libglu1-mesa-dev libxrender-dev libxi-dev libxkbcommon-dev libxkbcommon-x11-dev\n+ - name: Install qtconsole dependencies\n+ shell: bash -l {0}\n+ run: |\n+ cd ${GITHUB_WORKSPACE}/..\n+ git clone https://github.com/jupyter/qtconsole.git\n+ cd qtconsole\n+ ${pythonLocation}/bin/python -m pip install -e \".[test]\"\n+ ${pythonLocation}/bin/python -m pip install pyqt5\n+ - name: Install Jupyter-Client changes\n+ shell: bash -l {0}\n+ run: ${pythonLocation}/bin/python -m pip install -e .\n+\n+ - name: Test qtconsole\n+ shell: bash -l {0}\n+ run: |\n+ cd ${GITHUB_WORKSPACE}/../qtconsole\n+ xvfb-run --auto-servernum ${pythonLocation}/bin/python -m pytest -x -vv -s --full-trace --color=yes qtconsole\n+\n downstream_check: # This job does nothing and is only used for the branch protection\n if: always()\n needs:\n@@ -92,6 +127,7 @@ jobs:\n - jupyter_client\n - ipyparallel\n - jupyter_kernel_test\n+ - qtconsole\n runs-on: ubuntu-latest\n steps:\n - name: Decide whether the needed jobs succeeded or failed\ndiff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex 295232e..77f9f07 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -42,7 +42,7 @@ class BaseComm(comm.base_comm.BaseComm):\n \n \n # but for backwards compatibility, we need to inherit from LoggingConfigurable\n-class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n+class Comm(BaseComm, traitlets.config.LoggingConfigurable):\n \"\"\"Class for communicating between a Frontend and a Kernel\"\"\"\n \n kernel = Instance(\"ipykernel.kernelbase.Kernel\", allow_none=True) # type:ignore[assignment]\n@@ -68,12 +68,16 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def _default_comm_id(self):\n return uuid.uuid4().hex\n \n- def __init__(self, *args, **kwargs):\n- # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n+ def __init__(self, target_name='', data=None, metadata=None, buffers=None, **kwargs):\n+ # Handle differing arguments between base classes.\n+ kernel = kwargs.pop('kernel', None)\n+ if target_name:\n+ kwargs['target_name'] = target_name\n+ BaseComm.__init__(\n+ self, data=data, metadata=metadata, buffers=buffers, **kwargs\n+ ) # type:ignore[call-arg]\n+ kwargs['kernel'] = kernel\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n- # drop arguments not in BaseComm\n- kwargs.pop(\"kernel\", None)\n- BaseComm.__init__(self, *args, **kwargs)\n \n \n __all__ = [\"Comm\"]\ndiff --git a/ipykernel/comm/manager.py b/ipykernel/comm/manager.py\nindex 6bf73ad..c11b562 100644\n--- a/ipykernel/comm/manager.py\n+++ b/ipykernel/comm/manager.py\n@@ -9,7 +9,7 @@ import traitlets\n import traitlets.config\n \n \n-class CommManager(traitlets.config.LoggingConfigurable, comm.base_comm.CommManager):\n+class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable):\n \n kernel = traitlets.Instance(\"ipykernel.kernelbase.Kernel\")\n comms = traitlets.Dict()\n@@ -17,5 +17,5 @@ class CommManager(traitlets.config.LoggingConfigurable, comm.base_comm.CommManag\n \n def __init__(self, **kwargs):\n # CommManager doesn't take arguments, so we explicitly forward arguments\n- traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n comm.base_comm.CommManager.__init__(self)\n+ traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex f8b0764..405841f 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -1,3 +1,5 @@\n+import unittest.mock\n+\n from ipykernel.comm import Comm, CommManager\n from ipykernel.ipkernel import IPythonKernel\n \n@@ -47,10 +49,12 @@ def test_comm_manager(kernel):\n manager.register_target(\"fizz\", fizz)\n \n kernel.comm_manager = manager\n- comm = Comm()\n- comm.on_msg(on_msg)\n- comm.on_close(on_close)\n- manager.register_comm(comm)\n+ with unittest.mock.patch.object(Comm, \"publish_msg\") as publish_msg:\n+ comm = Comm()\n+ comm.on_msg(on_msg)\n+ comm.on_close(on_close)\n+ manager.register_comm(comm)\n+ assert publish_msg.call_count == 1\n \n assert manager.get_comm(comm.comm_id) == comm\n assert manager.get_comm('foo') is None\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm_manager"]}], "all_FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm", "ipykernel/tests/test_comm.py::test_comm_in_manager", "ipykernel/tests/test_comm.py::test_comm", "ipykernel/tests/test_comm.py::test_comm_manager"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "GenericMappingTools__pygmt-574_x3", "level": 3, "source": "swerebench", "repo": "GenericMappingTools/pygmt", "image": "swerebench/sweb.eval.x86_64.genericmappingtools_1776_pygmt-574:latest", "base_commit": "4856d64e441434e395c5b8e7874022052c76f9af", "num_bugs": 3, "bugs": [{"instance_id": "GenericMappingTools__pygmt-574", "base_commit": "4856d64e441434e395c5b8e7874022052c76f9af", "gold_patch": "diff --git a/pygmt/modules.py b/pygmt/modules.py\nindex 73392410..94512ec3 100644\n--- a/pygmt/modules.py\n+++ b/pygmt/modules.py\n@@ -1,6 +1,7 @@\n \"\"\"\n Non-plot GMT modules.\n \"\"\"\n+import numpy as np\n import xarray as xr\n \n from .clib import Session\n@@ -55,7 +56,7 @@ def grdinfo(grid, **kwargs):\n \n @fmt_docstring\n @use_alias(C=\"per_column\", I=\"spacing\", T=\"nearest_multiple\")\n-def info(fname, **kwargs):\n+def info(table, **kwargs):\n \"\"\"\n Get information about data tables.\n \n@@ -74,8 +75,9 @@ def info(fname, **kwargs):\n \n Parameters\n ----------\n- fname : str\n- The file name of the input data table file.\n+ table : pandas.DataFrame or np.ndarray or str\n+ Either a pandas dataframe, a 1D/2D numpy.ndarray or a file name to an\n+ ASCII data table.\n per_column : bool\n Report the min/max values per column in separate columns.\n spacing : str\n@@ -88,14 +90,25 @@ def info(fname, **kwargs):\n Report the min/max of the first (0'th) column to the nearest multiple\n of dz and output this as the string *-Tzmin/zmax/dz*.\n \"\"\"\n- if not isinstance(fname, str):\n- raise GMTInvalidInput(\"'info' only accepts file names.\")\n+ kind = data_kind(table)\n+ with Session() as lib:\n+ if kind == \"file\":\n+ file_context = dummy_context(table)\n+ elif kind == \"matrix\":\n+ _table = np.asanyarray(table)\n+ if table.ndim == 1: # 1D arrays need to be 2D and transposed\n+ _table = np.transpose(np.atleast_2d(_table))\n+ file_context = lib.virtualfile_from_matrix(_table)\n+ else:\n+ raise GMTInvalidInput(f\"Unrecognized data type: {type(table)}\")\n \n- with GMTTempFile() as tmpfile:\n- arg_str = \" \".join([fname, build_arg_string(kwargs), \"->\" + tmpfile.name])\n- with Session() as lib:\n- lib.call_module(\"info\", arg_str)\n- return tmpfile.read()\n+ with GMTTempFile() as tmpfile:\n+ with file_context as fname:\n+ arg_str = \" \".join(\n+ [fname, build_arg_string(kwargs), \"->\" + tmpfile.name]\n+ )\n+ lib.call_module(\"info\", arg_str)\n+ return tmpfile.read()\n \n \n @fmt_docstring\n", "test_patch": "diff --git a/pygmt/tests/test_info.py b/pygmt/tests/test_info.py\nindex 3e9da3ab..b7eadc53 100644\n--- a/pygmt/tests/test_info.py\n+++ b/pygmt/tests/test_info.py\n@@ -4,7 +4,9 @@ Tests for gmtinfo\n import os\n \n import numpy as np\n+import pandas as pd\n import pytest\n+import xarray as xr\n \n from .. import info\n from ..exceptions import GMTInvalidInput\n@@ -14,8 +16,8 @@ POINTS_DATA = os.path.join(TEST_DATA_DIR, \"points.txt\")\n \n \n def test_info():\n- \"Make sure info works\"\n- output = info(fname=POINTS_DATA)\n+ \"Make sure info works on file name inputs\"\n+ output = info(table=POINTS_DATA)\n expected_output = (\n f\"{POINTS_DATA}: N = 20 \"\n \"<11.5309/61.7074> \"\n@@ -25,33 +27,61 @@ def test_info():\n assert output == expected_output\n \n \n+def test_info_dataframe():\n+ \"Make sure info works on pandas.DataFrame inputs\"\n+ table = pd.read_csv(POINTS_DATA, sep=\" \", header=None)\n+ output = info(table=table)\n+ expected_output = (\n+ \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n+ )\n+ assert output == expected_output\n+\n+\n+def test_info_2d_array():\n+ \"Make sure info works on 2D numpy.ndarray inputs\"\n+ table = np.loadtxt(POINTS_DATA)\n+ output = info(table=table)\n+ expected_output = (\n+ \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n+ )\n+ assert output == expected_output\n+\n+\n+def test_info_1d_array():\n+ \"Make sure info works on 1D numpy.ndarray inputs\"\n+ output = info(table=np.arange(20))\n+ expected_output = \": N = 20 <0/19>\\n\"\n+ assert output == expected_output\n+\n+\n def test_info_per_column():\n \"Make sure the per_column option works\"\n- output = info(fname=POINTS_DATA, per_column=True)\n+ output = info(table=POINTS_DATA, per_column=True)\n assert output == \"11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338\\n\"\n \n \n def test_info_spacing():\n \"Make sure the spacing option works\"\n- output = info(fname=POINTS_DATA, spacing=0.1)\n+ output = info(table=POINTS_DATA, spacing=0.1)\n assert output == \"-R11.5/61.8/-3/7.9\\n\"\n \n \n def test_info_per_column_spacing():\n \"Make sure the per_column and spacing options work together\"\n- output = info(fname=POINTS_DATA, per_column=True, spacing=0.1)\n+ output = info(table=POINTS_DATA, per_column=True, spacing=0.1)\n assert output == \"11.5 61.8 -3 7.9 0.1412 0.9338\\n\"\n \n \n def test_info_nearest_multiple():\n \"Make sure the nearest_multiple option works\"\n- output = info(fname=POINTS_DATA, nearest_multiple=0.1)\n+ output = info(table=POINTS_DATA, nearest_multiple=0.1)\n assert output == \"-T11.5/61.8/0.1\\n\"\n \n \n def test_info_fails():\n- \"Make sure info raises an exception if not given a file name\"\n- with pytest.raises(GMTInvalidInput):\n- info(fname=21)\n+ \"\"\"\n+ Make sure info raises an exception if not given either a file name, pandas\n+ DataFrame, or numpy ndarray\n+ \"\"\"\n with pytest.raises(GMTInvalidInput):\n- info(fname=np.arange(20))\n+ info(table=xr.DataArray(21))\n", "FAIL_TO_PASS": ["pygmt/tests/test_info.py::test_info", "pygmt/tests/test_info.py::test_info_dataframe", "pygmt/tests/test_info.py::test_info_2d_array", "pygmt/tests/test_info.py::test_info_1d_array", "pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple", "pygmt/tests/test_info.py::test_info_fails"]}, {"instance_id": "GenericMappingTools__pygmt-575", "base_commit": "89857c32c7e61c57fb1f03993cfb090c76366783", "gold_patch": "diff --git a/pygmt/modules.py b/pygmt/modules.py\nindex 94512ec3..1cacf67d 100644\n--- a/pygmt/modules.py\n+++ b/pygmt/modules.py\n@@ -60,14 +60,17 @@ def info(table, **kwargs):\n \"\"\"\n Get information about data tables.\n \n- Reads from files and finds the extreme values in each of the columns.\n- It recognizes NaNs and will print warnings if the number of columns vary\n- from record to record. As an option, it will find the extent of the first\n- n columns rounded up and down to the nearest multiple of the supplied\n- increments. By default, this output will be in the form *-Rw/e/s/n*,\n- or the output will be in column form for as many columns as there are\n- increments provided. The *nearest_multiple* option will provide a\n- *-Tzmin/zmax/dz* string for makecpt.\n+ Reads from files and finds the extreme values in each of the columns\n+ reported as min/max pairs. It recognizes NaNs and will print warnings if\n+ the number of columns vary from record to record. As an option, it will\n+ find the extent of the first two columns rounded up and down to the nearest\n+ multiple of the supplied increments given by *spacing*. Such output will be\n+ in a numpy.ndarray form ``[w, e, s, n]``, which can be used directly as the\n+ *region* argument for other modules (hence only dx and dy are needed). If\n+ the *per_column* option is combined with *spacing*, then the numpy.ndarray\n+ output will be rounded up/down for as many columns as there are increments\n+ provided in *spacing*. A similar option *nearest_multiple* option will\n+ provide a numpy.ndarray in the form of ``[zmin, zmax, dz]`` for makecpt.\n \n Full option list at :gmt-docs:`gmtinfo.html`\n \n@@ -83,12 +86,21 @@ def info(table, **kwargs):\n spacing : str\n ``'[b|p|f|s]dx[/dy[/dz...]]'``.\n Report the min/max of the first n columns to the nearest multiple of\n- the provided increments and output results in the form *-Rw/e/s/n*\n- (unless *per_column* is set).\n+ the provided increments and output results in the form\n+ ``[w, e, s, n]``.\n nearest_multiple : str\n ``'dz[+ccol]'``\n Report the min/max of the first (0'th) column to the nearest multiple\n- of dz and output this as the string *-Tzmin/zmax/dz*.\n+ of dz and output this in the form ``[zmin, zmax, dz]``.\n+\n+ Returns\n+ -------\n+ output : np.ndarray or str\n+ Return type depends on whether any of the 'per_column', 'spacing', or\n+ 'nearest_multiple' parameters are set.\n+\n+ - np.ndarray if either of the above parameters are used.\n+ - str if none of the above parameters are used.\n \"\"\"\n kind = data_kind(table)\n with Session() as lib:\n@@ -108,7 +120,16 @@ def info(table, **kwargs):\n [fname, build_arg_string(kwargs), \"->\" + tmpfile.name]\n )\n lib.call_module(\"info\", arg_str)\n- return tmpfile.read()\n+ result = tmpfile.read()\n+\n+ if any(arg in kwargs for arg in [\"C\", \"I\", \"T\"]):\n+ # Converts certain output types into a numpy array\n+ # instead of a raw string that is less useful.\n+ if result.startswith((\"-R\", \"-T\")): # e.g. -R0/1/2/3 or -T0/9/1\n+ result = result[2:].replace(\"/\", \" \")\n+ result = np.loadtxt(result.splitlines())\n+\n+ return result\n \n \n @fmt_docstring\n", "test_patch": "diff --git a/pygmt/tests/test_info.py b/pygmt/tests/test_info.py\nindex b7eadc53..142b56dc 100644\n--- a/pygmt/tests/test_info.py\n+++ b/pygmt/tests/test_info.py\n@@ -4,6 +4,7 @@ Tests for gmtinfo\n import os\n \n import numpy as np\n+import numpy.testing as npt\n import pandas as pd\n import pytest\n import xarray as xr\n@@ -57,25 +58,42 @@ def test_info_1d_array():\n def test_info_per_column():\n \"Make sure the per_column option works\"\n output = info(table=POINTS_DATA, per_column=True)\n- assert output == \"11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338\\n\"\n+ npt.assert_allclose(\n+ actual=output, desired=[11.5309, 61.7074, -2.9289, 7.8648, 0.1412, 0.9338]\n+ )\n \n \n def test_info_spacing():\n \"Make sure the spacing option works\"\n output = info(table=POINTS_DATA, spacing=0.1)\n- assert output == \"-R11.5/61.8/-3/7.9\\n\"\n+ npt.assert_allclose(actual=output, desired=[11.5, 61.8, -3, 7.9])\n+\n+\n+def test_info_spacing_bounding_box():\n+ \"Make sure the spacing option for writing a bounding box works\"\n+ output = info(table=POINTS_DATA, spacing=\"b\")\n+ npt.assert_allclose(\n+ actual=output,\n+ desired=[\n+ [11.5309, -2.9289],\n+ [61.7074, -2.9289],\n+ [61.7074, 7.8648],\n+ [11.5309, 7.8648],\n+ [11.5309, -2.9289],\n+ ],\n+ )\n \n \n def test_info_per_column_spacing():\n \"Make sure the per_column and spacing options work together\"\n output = info(table=POINTS_DATA, per_column=True, spacing=0.1)\n- assert output == \"11.5 61.8 -3 7.9 0.1412 0.9338\\n\"\n+ npt.assert_allclose(actual=output, desired=[11.5, 61.8, -3, 7.9, 0.1412, 0.9338])\n \n \n def test_info_nearest_multiple():\n \"Make sure the nearest_multiple option works\"\n output = info(table=POINTS_DATA, nearest_multiple=0.1)\n- assert output == \"-T11.5/61.8/0.1\\n\"\n+ npt.assert_allclose(actual=output, desired=[11.5, 61.8, 0.1])\n \n \n def test_info_fails():\n", "FAIL_TO_PASS": ["pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_spacing_bounding_box", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple"]}, {"instance_id": "GenericMappingTools__pygmt-619", "base_commit": "9e0a8688afafefff970a2c5901322ddf3c5a2c6a", "gold_patch": "diff --git a/pygmt/modules.py b/pygmt/modules.py\nindex 1cacf67d..477bc992 100644\n--- a/pygmt/modules.py\n+++ b/pygmt/modules.py\n@@ -78,9 +78,10 @@ def info(table, **kwargs):\n \n Parameters\n ----------\n- table : pandas.DataFrame or np.ndarray or str\n- Either a pandas dataframe, a 1D/2D numpy.ndarray or a file name to an\n- ASCII data table.\n+ table : str or np.ndarray or pandas.DataFrame or xarray.Dataset\n+ Pass in either a file name to an ASCII data table, a 1D/2D numpy array,\n+ a pandas dataframe, or an xarray dataset made up of 1D xarray.DataArray\n+ data variables.\n per_column : bool\n Report the min/max values per column in separate columns.\n spacing : str\n@@ -107,10 +108,13 @@ def info(table, **kwargs):\n if kind == \"file\":\n file_context = dummy_context(table)\n elif kind == \"matrix\":\n- _table = np.asanyarray(table)\n- if table.ndim == 1: # 1D arrays need to be 2D and transposed\n- _table = np.transpose(np.atleast_2d(_table))\n- file_context = lib.virtualfile_from_matrix(_table)\n+ try:\n+ # pandas.DataFrame and xarray.Dataset types\n+ arrays = [array for _, array in table.items()]\n+ except AttributeError:\n+ # Python lists, tuples, and numpy ndarray types\n+ arrays = np.atleast_2d(np.asanyarray(table).T)\n+ file_context = lib.virtualfile_from_vectors(*arrays)\n else:\n raise GMTInvalidInput(f\"Unrecognized data type: {type(table)}\")\n \n", "test_patch": "diff --git a/pygmt/tests/test_info.py b/pygmt/tests/test_info.py\nindex 142b56dc..92e7616a 100644\n--- a/pygmt/tests/test_info.py\n+++ b/pygmt/tests/test_info.py\n@@ -8,13 +8,17 @@ import numpy.testing as npt\n import pandas as pd\n import pytest\n import xarray as xr\n+from packaging.version import Version\n \n-from .. import info\n+from .. import clib, info\n from ..exceptions import GMTInvalidInput\n \n TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), \"data\")\n POINTS_DATA = os.path.join(TEST_DATA_DIR, \"points.txt\")\n \n+with clib.Session() as _lib:\n+ gmt_version = Version(_lib.info[\"version\"])\n+\n \n def test_info():\n \"Make sure info works on file name inputs\"\n@@ -33,7 +37,48 @@ def test_info_dataframe():\n table = pd.read_csv(POINTS_DATA, sep=\" \", header=None)\n output = info(table=table)\n expected_output = (\n- \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n+ \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n+ )\n+ assert output == expected_output\n+\n+\n+@pytest.mark.xfail(\n+ condition=gmt_version <= Version(\"6.1.1\"),\n+ reason=\"UNIX timestamps returned instead of ISO datetime, should work on GMT 6.2.0 \"\n+ \"after https://github.com/GenericMappingTools/gmt/issues/4241 is resolved\",\n+)\n+def test_info_pandas_dataframe_time_column():\n+ \"Make sure info works on pandas.DataFrame inputs with a time column\"\n+ table = pd.DataFrame(\n+ data={\n+ \"z\": [10, 13, 12, 15, 14],\n+ \"time\": pd.date_range(start=\"2020-01-01\", periods=5),\n+ }\n+ )\n+ output = info(table=table)\n+ expected_output = (\n+ \": N = 5 <10/15> <2020-01-01T00:00:00/2020-01-05T00:00:00>\\n\"\n+ )\n+ assert output == expected_output\n+\n+\n+@pytest.mark.xfail(\n+ condition=gmt_version <= Version(\"6.1.1\"),\n+ reason=\"UNIX timestamp returned instead of ISO datetime, should work on GMT 6.2.0 \"\n+ \"after https://github.com/GenericMappingTools/gmt/issues/4241 is resolved\",\n+)\n+def test_info_xarray_dataset_time_column():\n+ \"Make sure info works on xarray.Dataset 1D inputs with a time column\"\n+ table = xr.Dataset(\n+ coords={\"index\": [0, 1, 2, 3, 4]},\n+ data_vars={\n+ \"z\": (\"index\", [10, 13, 12, 15, 14]),\n+ \"time\": (\"index\", pd.date_range(start=\"2020-01-01\", periods=5)),\n+ },\n+ )\n+ output = info(table=table)\n+ expected_output = (\n+ \": N = 5 <10/15> <2020-01-01T00:00:00/2020-01-05T00:00:00>\\n\"\n )\n assert output == expected_output\n \n@@ -43,7 +88,7 @@ def test_info_2d_array():\n table = np.loadtxt(POINTS_DATA)\n output = info(table=table)\n expected_output = (\n- \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n+ \": N = 20 <11.5309/61.7074> <-2.9289/7.8648> <0.1412/0.9338>\\n\"\n )\n assert output == expected_output\n \n@@ -51,7 +96,7 @@ def test_info_2d_array():\n def test_info_1d_array():\n \"Make sure info works on 1D numpy.ndarray inputs\"\n output = info(table=np.arange(20))\n- expected_output = \": N = 20 <0/19>\\n\"\n+ expected_output = \": N = 20 <0/19>\\n\"\n assert output == expected_output\n \n \n", "FAIL_TO_PASS": ["pygmt/tests/test_info.py::test_info_dataframe", "pygmt/tests/test_info.py::test_info_2d_array", "pygmt/tests/test_info.py::test_info_1d_array"]}], "all_FAIL_TO_PASS": ["pygmt/tests/test_info.py::test_info", "pygmt/tests/test_info.py::test_info_dataframe", "pygmt/tests/test_info.py::test_info_2d_array", "pygmt/tests/test_info.py::test_info_1d_array", "pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple", "pygmt/tests/test_info.py::test_info_fails", "pygmt/tests/test_info.py::test_info_per_column", "pygmt/tests/test_info.py::test_info_spacing", "pygmt/tests/test_info.py::test_info_spacing_bounding_box", "pygmt/tests/test_info.py::test_info_per_column_spacing", "pygmt/tests/test_info.py::test_info_nearest_multiple", "pygmt/tests/test_info.py::test_info_dataframe", "pygmt/tests/test_info.py::test_info_2d_array", "pygmt/tests/test_info.py::test_info_1d_array"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "horejsek__python-fastjsonschema-88_x3", "level": 3, "source": "swerebench", "repo": "horejsek/python-fastjsonschema", "image": "swerebench/sweb.eval.x86_64.horejsek_1776_python-fastjsonschema-88:latest", "base_commit": "e845f622d6340703342a58318d94a295d86bbfaf", "num_bugs": 3, "bugs": [{"instance_id": "horejsek__python-fastjsonschema-88", "base_commit": "e845f622d6340703342a58318d94a295d86bbfaf", "gold_patch": "diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py\nindex 01cc07e..6c50a21 100644\n--- a/fastjsonschema/draft04.py\n+++ b/fastjsonschema/draft04.py\n@@ -11,7 +11,7 @@ JSON_TYPE_TO_PYTHON_TYPE = {\n 'number': 'int, float',\n 'integer': 'int',\n 'string': 'str',\n- 'array': 'list',\n+ 'array': 'list, tuple',\n 'object': 'dict',\n }\n \ndiff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py\nindex fc5b4b1..17cebd6 100644\n--- a/fastjsonschema/generator.py\n+++ b/fastjsonschema/generator.py\n@@ -281,7 +281,7 @@ class CodeGenerator:\n if variable_name in self._variables:\n return\n self._variables.add(variable_name)\n- self.l('{variable}_is_list = isinstance({variable}, list)')\n+ self.l('{variable}_is_list = isinstance({variable}, (list, tuple))')\n \n def create_variable_is_dict(self):\n \"\"\"\n", "test_patch": "diff --git a/tests/test_array.py b/tests/test_array.py\nindex 33f6a06..3d77435 100644\n--- a/tests/test_array.py\n+++ b/tests/test_array.py\n@@ -134,3 +134,35 @@ def test_different_items_without_additional_items(asserter, value, expected):\n ],\n 'additionalItems': False,\n }, value, expected)\n+\n+\n+@pytest.mark.parametrize('value, expected', [\n+ ((), ()),\n+ (('a',), ('a',)),\n+ (('a', 'b'), ('a', 'b')),\n+ (('a', 'b', 3), JsonSchemaException('data[2] must be string', value=3, name='data[2]',\n+ definition={'type': 'string'}, rule='type')),\n+])\n+def test_tuples_as_arrays(asserter, value, expected):\n+ asserter({\n+ '$schema': 'http://json-schema.org/draft-06/schema',\n+ 'type': 'array',\n+ 'items':\n+ {'type': 'string'},\n+\n+ }, value, expected)\n+\n+\n+@pytest.mark.parametrize('value, expected', [\n+ ({'a': [], 'b': ()}, {'a': [], 'b': ()}),\n+ ({'a': (1, 2), 'b': (3, 4)}, {'a': (1, 2), 'b': (3, 4)}),\n+])\n+def test_mixed_arrays(asserter, value, expected):\n+ asserter({\n+ 'type': 'object',\n+ 'properties': {\n+ 'a': {'type': 'array'},\n+ 'b': {'type': 'array'},\n+ },\n+ }, value, expected)\n+\ndiff --git a/tests/test_integration.py b/tests/test_integration.py\nindex 5ea2c08..27135f9 100644\n--- a/tests/test_integration.py\n+++ b/tests/test_integration.py\n@@ -52,6 +52,10 @@ definition = {\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'd': 'd'}, 42, 3],\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'abc', 'd': 'd'}, 42, 3],\n ),\n+ (\n+ (9, 'world', (1,), {'a': 'a', 'b': 'b', 'd': 'd'}, 42, 3),\n+ (9, 'world', (1,), {'a': 'a', 'b': 'b', 'c': 'abc', 'd': 'd'}, 42, 3),\n+ ),\n (\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'xy'}, 42, 3],\n [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'xy'}, 42, 3],\n", "FAIL_TO_PASS": ["tests/test_array.py::test_tuples_as_arrays[value0-expected0]", "tests/test_array.py::test_tuples_as_arrays[value1-expected1]", "tests/test_array.py::test_tuples_as_arrays[value2-expected2]", "tests/test_array.py::test_tuples_as_arrays[value3-expected3]", "tests/test_array.py::test_mixed_arrays[value0-expected0]", "tests/test_array.py::test_mixed_arrays[value1-expected1]", "tests/test_integration.py::test_integration[value2-expected2]"]}, {"instance_id": "horejsek__python-fastjsonschema-112", "base_commit": "4b0d76cb07d78f047813c6bcda01879ee0a0216c", "gold_patch": "diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py\nindex 5c40de7..b79b1f9 100644\n--- a/fastjsonschema/draft04.py\n+++ b/fastjsonschema/draft04.py\n@@ -349,8 +349,16 @@ class CodeGeneratorDraft04(CodeGenerator):\n \"\"\"\n self.create_variable_is_list()\n with self.l('if {variable}_is_list:'):\n+ self.l(\n+ 'def fn(var): '\n+ 'return frozenset(dict((k, fn(v)) '\n+ 'for k, v in var.items()).items()) '\n+ 'if hasattr(var, \"items\") else tuple(fn(v) '\n+ 'for v in var) '\n+ 'if isinstance(var, (dict, list)) else str(var) '\n+ 'if isinstance(var, bool) else var')\n self.create_variable_with_length()\n- with self.l('if {variable}_len > len(set(str({variable}_x) for {variable}_x in {variable})):'):\n+ with self.l('if {variable}_len > len(set(fn({variable}_x) for {variable}_x in {variable})):'):\n self.exc('{name} must contain unique items', rule='uniqueItems')\n \n def generate_items(self):\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 756429e..de91132 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -13,6 +13,11 @@ from fastjsonschema import JsonSchemaException, compile\n from fastjsonschema.draft07 import CodeGeneratorDraft07\n \n \n+def pytest_configure(config):\n+ config.addinivalue_line(\"markers\", \"none\")\n+ config.addinivalue_line(\"markers\", \"benchmark\")\n+\n+\n @pytest.fixture\n def asserter():\n def f(definition, value, expected, formats={}):\ndiff --git a/tests/test_array.py b/tests/test_array.py\nindex 3d77435..19289ab 100644\n--- a/tests/test_array.py\n+++ b/tests/test_array.py\n@@ -51,6 +51,20 @@ def test_min_items(asserter, value, expected):\n ([1], [1]),\n ([1, 1], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n ([1, 2, 3], [1, 2, 3]),\n+ ([True, False], [True, False]),\n+ ([True, True], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ (['abc', 'bce', 'hhh'], ['abc', 'bce', 'hhh']),\n+ (['abc', 'abc'], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': 'a'}, {'b': 'b'}], [{'a': 'a'}, {'b': 'b'}]),\n+ ([{'a': 'a'}, {'a': 'a'}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': 'a', 'b': 'b'}, {'b': 'b', 'c': 'c'}], [{'a': 'a', 'b': 'b'}, {'b': 'b', 'c': 'c'}]),\n+ ([{'a': 'a', 'b': 'b'}, {'b': 'b', 'a': 'a'}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([1, '1'], [1, '1']),\n+ ([{'a': 'b'}, \"{'a': 'b'}\"], [{'a': 'b'}, \"{'a': 'b'}\"]),\n+ ([[1, 2], [2, 1]], [[1, 2], [2, 1]]),\n+ ([[1, 2], [1, 2]], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': {'b': {'c': [1, 2]}}}, {'a': {'b': {'c': [1, 2]}}}], JsonSchemaException('data must contain unique items', value='{data}', name='data', definition='{definition}', rule='uniqueItems')),\n+ ([{'a': {'b': {'c': [2, 1]}}}, {'a': {'b': {'c': [1, 2]}}}], [{'a': {'b': {'c': [2, 1]}}}, {'a': {'b': {'c': [1, 2]}}}]),\n ])\n def test_unique_items(asserter, value, expected):\n asserter({\n", "FAIL_TO_PASS": ["tests/test_array.py::test_unique_items[value11-expected11]", "tests/test_array.py::test_unique_items[value12-expected12]", "tests/test_array.py::test_unique_items[value13-expected13]"]}, {"instance_id": "horejsek__python-fastjsonschema-116", "base_commit": "32476cfd4d97f92cae52d686eb471361503bf4ba", "gold_patch": "diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py\nindex a5b132b..394f263 100644\n--- a/fastjsonschema/draft04.py\n+++ b/fastjsonschema/draft04.py\n@@ -26,7 +26,7 @@ class CodeGeneratorDraft04(CodeGenerator):\n # vs. 9 ms with a regex! Other modules are also ineffective or not available in standard\n # library. Some regexps are not 100% precise but good enough, fast and without dependencies.\n FORMAT_REGEXS = {\n- 'date-time': r'^\\d{4}-[01]\\d-[0-3]\\d(t|T)[0-2]\\d:[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:[+-][0-2]\\d:[0-5]\\d|z|Z)\\Z',\n+ 'date-time': r'^\\d{4}-[01]\\d-[0-3]\\d(t|T)[0-2]\\d:[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:[+-][0-2]\\d:[0-5]\\d|[+-][0-2]\\d[0-5]\\d|z|Z)\\Z',\n 'email': r'^[^@]+@[^@]+\\.[^@]+\\Z',\n 'hostname': r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]{0,61}[A-Za-z0-9])\\Z',\n 'ipv4': r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\Z',\n", "test_patch": "diff --git a/tests/test_format.py b/tests/test_format.py\nindex f742344..c43abc5 100644\n--- a/tests/test_format.py\n+++ b/tests/test_format.py\n@@ -14,6 +14,7 @@ exc = JsonSchemaValueException('data must be date-time', value='{data}', name='d\n ('2018-02-05T14:17:10.00Z\\n', exc),\n ('2018-02-05T14:17:10.00Z', '2018-02-05T14:17:10.00Z'),\n ('2018-02-05T14:17:10Z', '2018-02-05T14:17:10Z'),\n+ ('2020-09-09T01:01:01+0100', '2020-09-09T01:01:01+0100'),\n ])\n def test_datetime(asserter, value, expected):\n asserter({'type': 'string', 'format': 'date-time'}, value, expected)\n", "FAIL_TO_PASS": ["tests/test_format.py::test_datetime[2020-09-09T01:01:01+0100-2020-09-09T01:01:01+0100]"]}], "all_FAIL_TO_PASS": ["tests/test_array.py::test_tuples_as_arrays[value0-expected0]", "tests/test_array.py::test_tuples_as_arrays[value1-expected1]", "tests/test_array.py::test_tuples_as_arrays[value2-expected2]", "tests/test_array.py::test_tuples_as_arrays[value3-expected3]", "tests/test_array.py::test_mixed_arrays[value0-expected0]", "tests/test_array.py::test_mixed_arrays[value1-expected1]", "tests/test_integration.py::test_integration[value2-expected2]", "tests/test_array.py::test_unique_items[value11-expected11]", "tests/test_array.py::test_unique_items[value12-expected12]", "tests/test_array.py::test_unique_items[value13-expected13]", "tests/test_format.py::test_datetime[2020-09-09T01:01:01+0100-2020-09-09T01:01:01+0100]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3937_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3937:latest", "base_commit": "f4c34d37c5773c37a13437c7e0e7eb27b4e98877", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3937", "base_commit": "f4c34d37c5773c37a13437c7e0e7eb27b4e98877", "gold_patch": "diff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex acd4c096..67400514 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -2909,11 +2909,13 @@ class Generator(metaclass=_Generator):\n \n def pivotalias_sql(self, expression: exp.PivotAlias) -> str:\n alias = expression.args[\"alias\"]\n+\n identifier_alias = isinstance(alias, exp.Identifier)\n+ literal_alias = isinstance(alias, exp.Literal)\n \n if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n alias.replace(exp.Literal.string(alias.output_name))\n- elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n+ elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n alias.replace(exp.to_identifier(alias.output_name))\n \n return self.alias_sql(expression)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 6171580c..fb78d1ab 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3776,8 +3776,10 @@ class Parser(metaclass=_Parser):\n this = self._parse_select_or_expression()\n \n self._match(TokenType.ALIAS)\n- alias = self._parse_field()\n+ alias = self._parse_bitwise()\n if alias:\n+ if isinstance(alias, exp.Column) and not alias.db:\n+ alias = alias.this\n return self.expression(exp.PivotAlias, this=this, alias=alias)\n \n return this\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 79b8a024..4a570721 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -44,6 +44,9 @@ class TestOracle(Validator):\n self.validate_identity(\"SELECT COUNT(*) * 10 FROM orders SAMPLE (10) SEED (1)\")\n self.validate_identity(\"SELECT * FROM V$SESSION\")\n self.validate_identity(\"SELECT TO_DATE('January 15, 1989, 11:00 A.M.')\")\n+ self.validate_identity(\n+ \"SELECT * FROM test UNPIVOT INCLUDE NULLS (value FOR Description IN (col AS 'PREFIX ' || CHR(38) || ' SUFFIX'))\"\n+ )\n self.validate_identity(\n \"SELECT last_name, employee_id, manager_id, LEVEL FROM employees START WITH employee_id = 100 CONNECT BY PRIOR employee_id = manager_id ORDER SIBLINGS BY last_name\"\n )\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-3954", "base_commit": "6a5f6199f6da0053fa4564e71a17e3b9f91f0496", "gold_patch": "diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py\nindex ff5dcb64..53fad5ae 100644\n--- a/sqlglot/dialects/oracle.py\n+++ b/sqlglot/dialects/oracle.py\n@@ -107,8 +107,10 @@ class Oracle(Dialect):\n \"TO_CHAR\": _build_timetostr_or_tochar,\n \"TO_TIMESTAMP\": build_formatted_time(exp.StrToTime, \"oracle\"),\n \"TO_DATE\": build_formatted_time(exp.StrToDate, \"oracle\"),\n+ \"NVL\": lambda args: exp.Coalesce(\n+ this=seq_get(args, 0), expressions=args[1:], is_nvl=True\n+ ),\n }\n- FUNCTIONS.pop(\"NVL\")\n \n NO_PAREN_FUNCTION_PARSERS = {\n **parser.Parser.NO_PAREN_FUNCTION_PARSERS,\n@@ -313,3 +315,7 @@ class Oracle(Dialect):\n value = f\" CONSTRAINT {value}\" if value else \"\"\n \n return f\"{option}{value}\"\n+\n+ def coalesce_sql(self, expression: exp.Coalesce) -> str:\n+ func_name = \"NVL\" if expression.args.get(\"is_nvl\") else \"COALESCE\"\n+ return rename_func(func_name)(self, expression)\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 00a54a04..faf85b0c 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5087,7 +5087,7 @@ class Ceil(Func):\n \n \n class Coalesce(Func):\n- arg_types = {\"this\": True, \"expressions\": False}\n+ arg_types = {\"this\": True, \"expressions\": False, \"is_nvl\": False}\n is_var_len_args = True\n _sql_names = [\"COALESCE\", \"IFNULL\", \"NVL\"]\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 9a099104..cdc631ee 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1302,7 +1302,7 @@ class Generator(metaclass=_Generator):\n def fetch_sql(self, expression: exp.Fetch) -> str:\n direction = expression.args.get(\"direction\")\n direction = f\" {direction}\" if direction else \"\"\n- count = expression.args.get(\"count\")\n+ count = self.sql(expression, \"count\")\n count = f\" {count}\" if count else \"\"\n if expression.args.get(\"percent\"):\n count = f\"{count} PERCENT\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex d20c2406..55552840 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -222,6 +222,7 @@ class Parser(metaclass=_Parser):\n \"UNNEST\": lambda args: exp.Unnest(expressions=ensure_list(seq_get(args, 0))),\n \"UPPER\": build_upper,\n \"VAR_MAP\": build_var_map,\n+ \"COALESCE\": lambda args: exp.Coalesce(this=seq_get(args, 0), expressions=args[1:]),\n }\n \n NO_PAREN_FUNCTIONS = {\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 594aee5c..4813a495 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -89,7 +89,6 @@ class TestOracle(Validator):\n self.validate_identity(\n \"SELECT * FROM T ORDER BY I OFFSET NVL(:variable1, 10) ROWS FETCH NEXT NVL(:variable2, 10) ROWS ONLY\",\n )\n- self.validate_identity(\"NVL(x, y)\").assert_is(exp.Anonymous)\n self.validate_identity(\n \"SELECT * FROM t SAMPLE (.25)\",\n \"SELECT * FROM t SAMPLE (0.25)\",\n@@ -253,6 +252,15 @@ class TestOracle(Validator):\n \"\"\"SELECT * FROM t ORDER BY a ASC, b ASC NULLS FIRST, c DESC NULLS LAST, d DESC\"\"\",\n )\n \n+ self.validate_all(\n+ \"NVL(NULL, 1)\",\n+ write={\n+ \"oracle\": \"NVL(NULL, 1)\",\n+ \"\": \"COALESCE(NULL, 1)\",\n+ \"clickhouse\": \"COALESCE(NULL, 1)\",\n+ },\n+ )\n+\n def test_join_marker(self):\n self.validate_identity(\"SELECT e1.x, e2.x FROM e e1, e e2 WHERE e1.y (+) = e2.y\")\n \n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-3971", "base_commit": "378500f4493083c9d111c2cba2efbf46abdd1099", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex d43c2e22..7cc4e656 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5441,6 +5441,11 @@ class IsInf(Func):\n _sql_names = [\"IS_INF\", \"ISINF\"]\n \n \n+# https://www.postgresql.org/docs/current/functions-json.html\n+class JSON(Expression):\n+ arg_types = {\"this\": False, \"with\": False, \"unique\": False}\n+\n+\n class JSONPath(Expression):\n arg_types = {\"expressions\": True}\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 7796d239..97aaf4b0 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -4136,3 +4136,20 @@ class Generator(metaclass=_Generator):\n expr = exp.AtTimeZone(this=timestamp, zone=target_tz)\n \n return self.sql(expr)\n+\n+ def json_sql(self, expression: exp.JSON) -> str:\n+ this = self.sql(expression, \"this\")\n+ this = f\" {this}\" if this else \"\"\n+\n+ _with = expression.args.get(\"with\")\n+\n+ if _with is None:\n+ with_sql = \"\"\n+ elif not _with:\n+ with_sql = \" WITHOUT\"\n+ else:\n+ with_sql = \" WITH\"\n+\n+ unique_sql = \" UNIQUE KEYS\" if expression.args.get(\"unique\") else \"\"\n+\n+ return f\"JSON{this}{with_sql}{unique_sql}\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 7644313b..0896677b 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1252,6 +1252,8 @@ class Parser(metaclass=_Parser):\n \n COPY_INTO_VARLEN_OPTIONS = {\"FILE_FORMAT\", \"COPY_OPTIONS\", \"FORMAT_OPTIONS\", \"CREDENTIAL\"}\n \n+ IS_JSON_PREDICATE_KIND = {\"VALUE\", \"SCALAR\", \"ARRAY\", \"OBJECT\"}\n+\n STRICT_CAST = True\n \n PREFIXED_PIVOT_COLUMNS = False\n@@ -4288,10 +4290,26 @@ class Parser(metaclass=_Parser):\n klass = exp.NullSafeEQ if negate else exp.NullSafeNEQ\n return self.expression(klass, this=this, expression=self._parse_bitwise())\n \n- expression = self._parse_null() or self._parse_boolean()\n- if not expression:\n- self._retreat(index)\n- return None\n+ if self._match(TokenType.JSON):\n+ kind = self._match_texts(self.IS_JSON_PREDICATE_KIND) and self._prev.text.upper()\n+\n+ if self._match_text_seq(\"WITH\"):\n+ _with = True\n+ elif self._match_text_seq(\"WITHOUT\"):\n+ _with = False\n+ else:\n+ _with = None\n+\n+ unique = self._match(TokenType.UNIQUE)\n+ self._match_text_seq(\"KEYS\")\n+ expression: t.Optional[exp.Expression] = self.expression(\n+ exp.JSON, **{\"this\": kind, \"with\": _with, \"unique\": unique}\n+ )\n+ else:\n+ expression = self._parse_null() or self._parse_boolean()\n+ if not expression:\n+ self._retreat(index)\n+ return None\n \n this = self.expression(exp.Is, this=this, expression=expression)\n return self.expression(exp.Not, this=this) if negate else this\n", "test_patch": "diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex c681bcff..c628db46 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -788,6 +788,13 @@ class TestPostgres(Validator):\n },\n )\n \n+ self.validate_identity(\n+ 'SELECT js, js IS JSON AS \"json?\", js IS JSON VALUE AS \"scalar?\", js IS JSON SCALAR AS \"scalar?\", js IS JSON OBJECT AS \"object?\", js IS JSON ARRAY AS \"array?\" FROM t'\n+ )\n+ self.validate_identity(\n+ 'SELECT js, js IS JSON ARRAY WITH UNIQUE KEYS AS \"array w. UK?\", js IS JSON ARRAY WITHOUT UNIQUE KEYS AS \"array w/o UK?\", js IS JSON ARRAY UNIQUE KEYS AS \"array w UK 2?\" FROM t'\n+ )\n+\n def test_ddl(self):\n # Checks that user-defined types are parsed into DataType instead of Identifier\n self.parse_one(\"CREATE TABLE t (a udt)\").this.expressions[0].args[\"kind\"].assert_is(\n", "FAIL_TO_PASS": ["tests/dialects/test_postgres.py::TestPostgres::test_postgres"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_postgres.py::TestPostgres::test_postgres"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-4130_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-4130:latest", "base_commit": "4506b3b58fde8e8fe711df8fd0c9c245a98ca86b", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-4130", "base_commit": "4506b3b58fde8e8fe711df8fd0c9c245a98ca86b", "gold_patch": "diff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 23b19b48..f0b13763 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -4323,6 +4323,13 @@ class Generator(metaclass=_Generator):\n parent_cond = parent.expression.this\n parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))\n else:\n- array_agg = f\"{array_agg} FILTER(WHERE {self.sql(expression, 'this')} IS NOT NULL)\"\n+ # DISTINCT is already present in the agg function, do not propagate it to FILTER as well\n+ this = expression.this\n+ this_sql = (\n+ self.expressions(this)\n+ if isinstance(this, exp.Distinct)\n+ else self.sql(expression, \"this\")\n+ )\n+ array_agg = f\"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)\"\n \n return array_agg\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex a47ca8eb..a2180357 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4343,6 +4343,9 @@ class Parser(metaclass=_Parser):\n )\n \n while self._match_set(self.ASSIGNMENT):\n+ if isinstance(this, exp.Column) and len(this.parts) == 1:\n+ this = this.this\n+\n this = self.expression(\n self.ASSIGNMENT[self._prev.token_type],\n this=this,\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 2887dd0f..ad503ae9 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -295,6 +295,9 @@ class TestDuckDB(Validator):\n self.validate_identity(\"SUMMARIZE tbl\").assert_is(exp.Summarize)\n self.validate_identity(\"SUMMARIZE SELECT * FROM tbl\").assert_is(exp.Summarize)\n self.validate_identity(\"CREATE TABLE tbl_summary AS SELECT * FROM (SUMMARIZE tbl)\")\n+ self.validate_identity(\"UNION_VALUE(k1 := 1)\").find(exp.PropertyEQ).this.assert_is(\n+ exp.Identifier\n+ )\n self.validate_identity(\n \"SELECT species, island, COUNT(*) FROM t GROUP BY GROUPING SETS (species), GROUPING SETS (island)\"\n )\ndiff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 40413c82..1e412b04 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -755,6 +755,8 @@ WHERE\n write={\n \"spark\": \"SELECT COLLECT_LIST(DISTINCT a)\",\n \"snowflake\": \"SELECT ARRAY_AGG(DISTINCT a)\",\n+ \"duckdb\": \"SELECT ARRAY_AGG(DISTINCT a) FILTER(WHERE a IS NOT NULL)\",\n+ \"presto\": \"SELECT ARRAY_AGG(DISTINCT a) FILTER(WHERE a IS NOT NULL)\",\n },\n )\n self.validate_all(\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-4141", "base_commit": "8822d6c1b3b62cfd76fd481db473bf8ea1c12b1a", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex ec1984e9..c8671f69 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -756,6 +756,26 @@ class ClickHouse(Dialect):\n def _parse_constraint(self) -> t.Optional[exp.Expression]:\n return super()._parse_constraint() or self._parse_projection_def()\n \n+ def _parse_alias(\n+ self, this: t.Optional[exp.Expression], explicit: bool = False\n+ ) -> t.Optional[exp.Expression]:\n+ # In clickhouse \"SELECT APPLY(...)\" is a query modifier,\n+ # so \"APPLY\" shouldn't be parsed as 's alias. However, \"SELECT apply\" is a valid alias\n+ if self._match_pair(TokenType.APPLY, TokenType.L_PAREN, advance=False):\n+ return this\n+\n+ return super()._parse_alias(this=this, explicit=explicit)\n+\n+ def _parse_expression(self) -> t.Optional[exp.Expression]:\n+ this = super()._parse_expression()\n+\n+ # Clickhouse allows \"SELECT [APPLY(func)] [...]]\" modifier\n+ while self._match_pair(TokenType.APPLY, TokenType.L_PAREN):\n+ this = exp.Apply(this=this, expression=self._parse_var(any_token=True))\n+ self._match(TokenType.R_PAREN)\n+\n+ return this\n+\n class Generator(generator.Generator):\n QUERY_HINTS = False\n STRUCT_DELIMITER = (\"(\", \")\")\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex d44b2c3d..95f3c01c 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -4922,6 +4922,10 @@ class ApproxDistinct(AggFunc):\n _sql_names = [\"APPROX_DISTINCT\", \"APPROX_COUNT_DISTINCT\"]\n \n \n+class Apply(Func):\n+ arg_types = {\"this\": True, \"expression\": True}\n+\n+\n class Array(Func):\n arg_types = {\"expressions\": False, \"bracket_notation\": False}\n is_var_len_args = True\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 80c86288..e2029313 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -4336,3 +4336,9 @@ class Generator(metaclass=_Generator):\n array_agg = f\"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)\"\n \n return array_agg\n+\n+ def apply_sql(self, expression: exp.Apply) -> str:\n+ this = self.sql(expression, \"this\")\n+ expr = self.sql(expression, \"expression\")\n+\n+ return f\"{this} APPLY({expr})\"\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex d203141d..aa6c4f1b 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -519,6 +519,14 @@ class TestClickhouse(Validator):\n self.validate_identity(\"SELECT TRIM(LEADING '(' FROM '( Hello, world! )')\")\n self.validate_identity(\"current_timestamp\").assert_is(exp.Column)\n \n+ self.validate_identity(\"SELECT * APPLY(sum) FROM columns_transformers\")\n+ self.validate_identity(\"SELECT COLUMNS('[jk]') APPLY(toString) FROM columns_transformers\")\n+ self.validate_identity(\n+ \"SELECT COLUMNS('[jk]') APPLY(toString) APPLY(length) APPLY(max) FROM columns_transformers\"\n+ )\n+ self.validate_identity(\"SELECT * APPLY(sum), COLUMNS('col') APPLY(sum) APPLY(avg) FROM t\")\n+ self.validate_identity(\"SELECT col apply\", \"SELECT col AS apply\")\n+\n def test_clickhouse_values(self):\n values = exp.select(\"*\").from_(\n exp.values([exp.tuple_(1, 2, 3)], alias=\"subq\", columns=[\"a\", \"b\", \"c\"])\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"]}, {"instance_id": "tobymao__sqlglot-4148", "base_commit": "be0a4a85d41bfb617360bd9a59aa9e631e4d6d6c", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 95f3c01c..de48a8a4 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -4123,6 +4123,7 @@ class DataType(Expression):\n NUMRANGE = auto()\n NVARCHAR = auto()\n OBJECT = auto()\n+ RANGE = auto()\n ROWVERSION = auto()\n SERIAL = auto()\n SET = auto()\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 96df5c01..a9fc38e5 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -269,6 +269,7 @@ class Parser(metaclass=_Parser):\n TokenType.LOWCARDINALITY,\n TokenType.MAP,\n TokenType.NULLABLE,\n+ TokenType.RANGE,\n *STRUCT_TYPE_TOKENS,\n }\n \n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 2c6a6076..e2adfeab 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -1962,3 +1962,26 @@ OPTIONS (\n \"duckdb\": \"WITH Races AS (SELECT '800M' AS race) SELECT race, participant FROM Races AS r CROSS JOIN (SELECT UNNEST([{'name': 'Rudisha', 'laps': [23.4, 26.3, 26.4, 26.1]}], max_depth => 2)) AS participant\",\n },\n )\n+\n+ def test_range_type(self):\n+ for type, value in (\n+ (\"RANGE\", \"'[2020-01-01, 2020-12-31)'\"),\n+ (\"RANGE\", \"'[UNBOUNDED, 2020-12-31)'\"),\n+ (\"RANGE\", \"'[2020-01-01 12:00:00, 2020-12-31 12:00:00)'\"),\n+ (\"RANGE\", \"'[2020-10-01 12:00:00+08, 2020-12-31 12:00:00+08)'\"),\n+ ):\n+ with self.subTest(f\"Testing BigQuery's RANGE type: {type} {value}\"):\n+ self.validate_identity(f\"SELECT {type} {value}\", f\"SELECT CAST({value} AS {type})\")\n+\n+ self.assertEqual(self.parse_one(type), exp.DataType.build(type, dialect=\"bigquery\"))\n+\n+ self.validate_identity(\n+ \"SELECT RANGE(CAST('2022-12-01' AS DATE), CAST('2022-12-31' AS DATE))\"\n+ )\n+ self.validate_identity(\"SELECT RANGE(NULL, CAST('2022-12-31' AS DATE))\")\n+ self.validate_identity(\n+ \"SELECT RANGE(CAST('2022-10-01 14:53:27' AS DATETIME), CAST('2022-10-01 16:00:00' AS DATETIME))\"\n+ )\n+ self.validate_identity(\n+ \"SELECT RANGE(CAST('2022-10-01 14:53:27 America/Los_Angeles' AS TIMESTAMP), CAST('2022-10-01 16:00:00 America/Los_Angeles' AS TIMESTAMP))\"\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_range_type"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_bigquery.py::TestBigQuery::test_range_type"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NREL__hescore-hpxml-139_x3", "level": 3, "source": "swerebench", "repo": "NREL/hescore-hpxml", "image": "swerebench/sweb.eval.x86_64.nrel_1776_hescore-hpxml-139:latest", "base_commit": "1bd1dd87237c00280c2150d96df6a33919659836", "num_bugs": 3, "bugs": [{"instance_id": "NREL__hescore-hpxml-139", "base_commit": "1bd1dd87237c00280c2150d96df6a33919659836", "gold_patch": "diff --git a/docs/source/translation/zone_window.rst b/docs/source/translation/zone_window.rst\nindex 2275a2c5..22a50602 100644\n--- a/docs/source/translation/zone_window.rst\n+++ b/docs/source/translation/zone_window.rst\n@@ -36,7 +36,9 @@ window properties be assigned to each direction, the\n windows will be specified separately. \n \n Skylights in HEScore do not have an orientation that can be set, therefore\n-orientation/azimuth information about skylights is ignored.\n+orientation/azimuth information about skylights is ignored. Use `AttachedToRoof`\n+to specify which HPXML roof each skylight is attached to. If not specified, skylights\n+will be assigned to the first hescore roof.\n \n .. _window-prop:\n \ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 3dc254f5..07959248 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -758,9 +758,9 @@ class HPXMLtoHEScoreTranslatorBase(object):\n bldg['zone']['zone_floor'] = self.get_building_zone_floor(b, bldg['about'])\n footprint_area = self.get_footprint_area(bldg)\n bldg['zone']['zone_roof'] = self.get_building_zone_roof(b, footprint_area)\n- bldg['zone']['zone_roof'][0]['zone_skylight'] = self.get_skylights(b)\n- for zone_roof in bldg['zone']['zone_roof'][1:]:\n- zone_roof['zone_skylight'] = {'skylight_area': 0}\n+ skylights = self.get_skylights(b, bldg['zone']['zone_roof'])\n+ for roof_num in range(len(bldg['zone']['zone_roof'])):\n+ bldg['zone']['zone_roof'][roof_num]['zone_skylight'] = skylights[roof_num]\n bldg['zone']['wall_construction_same'] = False\n bldg['zone']['window_construction_same'] = False\n bldg['zone']['zone_wall'] = self.get_building_zone_wall(b, bldg['about'])\n@@ -1155,9 +1155,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n del atticd['roof_absorptance']\n \n # ids of hpxml roofs along for the ride\n- atticd['_roofid'] = ''\n- for attic_roofs_dict in attic_roof_ls:\n- atticd['_roofid'] += attic_roofs_dict['roof_id']\n+ atticd['_roofid'] = set([attic_roofs_dict['roof_id'] for attic_roofs_dict in attic_roof_ls])\n \n # Calculate roof area weighted center of cavity R-value for attic,\n # might be combined later by averaging again\n@@ -1194,7 +1192,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n raise TranslationError('There are no Attic elements in this building.')\n elif len(atticds) <= 2:\n for atticd in atticds:\n- atticd['_roofids'] = {atticd['_roofid']}\n+ atticd['_roofids'] = atticd['_roofid']\n del atticd['_roofid']\n elif len(atticds) > 2:\n # If there are more than two attics, combine and average by rooftype.\n@@ -1224,7 +1222,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n combined_atticd[attic_key] = max(roof_area_by_cat, key=lambda x: roof_area_by_cat[x])\n \n # ids of hpxml roofs along for the ride\n- combined_atticd['_roofids'] = set([atticd['_roofid'] for atticd in atticds])\n+ combined_atticd['_roofids'] = set().union(*[atticd['_roofid'] for atticd in atticds])\n \n # Calculate roof area weighted center of cavity R-value\n combined_atticd['roof_coc_rvalue'] = \\\n@@ -1274,70 +1272,102 @@ class HPXMLtoHEScoreTranslatorBase(object):\n \n return zone_roof\n \n- def get_skylights(self, b):\n+ def get_skylights(self, b, zone_roof):\n ns = self.ns\n xpath = self.xpath\n skylights = b.xpath('descendant::h:Skylight', namespaces=ns)\n \n- zone_skylight = OrderedDict()\n-\n- if len(skylights) == 0:\n- zone_skylight['skylight_area'] = 0\n- return zone_skylight\n-\n- # Get areas, u-factors, and shgcs if they exist\n- uvalues, shgcs, areas = map(list, zip(*[[xpath(skylight, 'h:%s/text()' % x)\n- for x in ('UFactor', 'SHGC', 'Area')]\n- for skylight in skylights]))\n- if None in areas:\n- raise TranslationError('Every skylight needs an area.')\n- areas = list(map(float, areas))\n- zone_skylight['skylight_area'] = sum(areas)\n-\n- # Remove skylights from the calculation where a uvalue or shgc isn't set.\n- idxstoremove = set()\n- for i, uvalue in enumerate(uvalues):\n- if uvalue is None:\n- idxstoremove.add(i)\n- for i, shgc in enumerate(shgcs):\n- if shgc is None:\n- idxstoremove.add(i)\n- for i in sorted(idxstoremove, reverse=True):\n- uvalues.pop(i)\n- shgcs.pop(i)\n- areas.pop(i)\n- assert len(uvalues) == len(shgcs)\n- uvalues = list(map(float, uvalues))\n- shgcs = list(map(float, shgcs))\n-\n- if len(uvalues) > 0:\n- # Use an area weighted average of the uvalues, shgcs\n- zone_skylight['skylight_method'] = 'custom'\n- zone_skylight['skylight_u_value'] = old_div(sum(\n- [uvalue * area for (uvalue, area) in zip(uvalues, areas)]), sum(areas))\n- zone_skylight['skylight_shgc'] = sum([shgc * area for (shgc, area) in zip(shgcs, areas)]) / sum(areas)\n- else:\n- # use a construction code\n- skylight_type_areas = {}\n+ skylight_by_roof_id = {}\n+ skylight_by_roof_num = {}\n+ for i in range(len(zone_roof)):\n+ skylight_by_roof_num[i] = []\n+\n+ for skylight in skylights:\n+ if xpath(skylight, 'h:AttachedToRoof/@idref') is None:\n+ # No roof attached, attach to the first roof\n+ skylight_by_roof_num[0].append(skylight)\n+ else:\n+ try:\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')].append(skylight)\n+ except KeyError:\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')] = []\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')].append(skylight)\n+\n+ for roof_id, skylights in list(skylight_by_roof_id.items()):\n+ # roof_found = False\n+ for i in range(len(zone_roof)):\n+ if roof_id in zone_roof[i]['_roofids']:\n+ # roof_found = True\n+ for skylight in skylights:\n+ skylight_by_roof_num[i].append(skylight)\n+ break\n+ # if not roof_found:\n+ # The roof attached is not simulated, should we: 1. attach to the first roof or 2. discard the skylight?\n+ # for skylight in skylights:\n+ # skylight_by_roof_num[0].append(skylight)\n+\n+ # combine skylights by roof_num\n+ zone_skylight = []\n+ for roof_num, skylights in list(skylight_by_roof_num.items()):\n+ skylight_d = OrderedDict()\n+ zone_skylight.append(skylight_d)\n+\n+ if len(skylights) == 0:\n+ skylight_d['skylight_area'] = 0\n+ continue\n+ # Get areas, u-factors, and shgcs if they exist\n+ uvalues, shgcs, areas = map(list, zip(*[[xpath(skylight, 'h:%s/text()' % x)\n+ for x in ('UFactor', 'SHGC', 'Area')]\n+ for skylight in skylights]))\n+ if None in areas:\n+ raise TranslationError('Every skylight needs an area.')\n+ areas = list(map(float, areas))\n+ skylight_d['skylight_area'] = sum(areas)\n+\n+ # Remove skylights from the calculation where a uvalue or shgc isn't set.\n+ idxstoremove = set()\n+ for i, uvalue in enumerate(uvalues):\n+ if uvalue is None:\n+ idxstoremove.add(i)\n+ for i, shgc in enumerate(shgcs):\n+ if shgc is None:\n+ idxstoremove.add(i)\n+ for i in sorted(idxstoremove, reverse=True):\n+ uvalues.pop(i)\n+ shgcs.pop(i)\n+ areas.pop(i)\n+ assert len(uvalues) == len(shgcs)\n+ uvalues = list(map(float, uvalues))\n+ shgcs = list(map(float, shgcs))\n+\n+ if len(uvalues) > 0:\n+ # Use an area weighted average of the uvalues, shgcs\n+ skylight_d['skylight_method'] = 'custom'\n+ skylight_d['skylight_u_value'] = old_div(sum(\n+ [uvalue * area for (uvalue, area) in zip(uvalues, areas)]), sum(areas))\n+ skylight_d['skylight_shgc'] = sum([shgc * area for (shgc, area) in zip(shgcs, areas)]) / sum(areas)\n+ else:\n+ # use a construction code\n+ skylight_type_areas = {}\n+ for skylight in skylights:\n+ area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n+ skylight_code = self.get_window_code(skylight)\n+ try:\n+ skylight_type_areas[skylight_code] += area\n+ except KeyError:\n+ skylight_type_areas[skylight_code] = area\n+ skylight_d['skylight_method'] = 'code'\n+ skylight_d['skylight_code'] = max(list(skylight_type_areas.items()), key=lambda x: x[1])[0]\n+ skylight_sunscreen_areas = {}\n for skylight in skylights:\n+ solar_screen = self.get_sunscreen(skylight)\n area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n- skylight_code = self.get_window_code(skylight)\n try:\n- skylight_type_areas[skylight_code] += area\n+ skylight_sunscreen_areas[solar_screen] += area\n except KeyError:\n- skylight_type_areas[skylight_code] = area\n- zone_skylight['skylight_method'] = 'code'\n- zone_skylight['skylight_code'] = max(list(skylight_type_areas.items()), key=lambda x: x[1])[0]\n- skylight_sunscreen_areas = {}\n- for skylight in skylights:\n- solar_screen = self.get_sunscreen(skylight)\n- area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n- try:\n- skylight_sunscreen_areas[solar_screen] += area\n- except KeyError:\n- skylight_sunscreen_areas[solar_screen] = area\n+ skylight_sunscreen_areas[solar_screen] = area\n \n- zone_skylight['solar_screen'] = max(list(skylight_sunscreen_areas.items()), key=lambda x: x[1])[0]\n+ skylight_d['solar_screen'] = max(list(skylight_sunscreen_areas.items()), key=lambda x: x[1])[0]\n \n return zone_skylight\n \n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 50571e69..b59531b7 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -2669,6 +2669,45 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n self.assertEqual(d_4['building']['systems']['hvac'], d_4_v3['building']['systems']['hvac'])\n \n \n+class TestHEScore2021Updates(unittest.TestCase, ComparatorBase):\n+\n+ def test_skylight_assignment(self):\n+ tr = self._load_xmlfile('house4_v3')\n+ attach_roof = etree.Element(tr.addns('h:AttachedToRoof'))\n+ attach_roof.attrib['idref'] = \"roof2\"\n+ glass_type = self.xpath('//h:Skylight/h:GlassType')\n+ glass_type.addnext(attach_roof)\n+ res = tr.hpxml_to_hescore()\n+ # Skylight attached to the second roof\n+ self.assertEqual(res['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 12.0)\n+ self.assertEqual(res['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+ skylight = self.xpath('//h:Skylight')\n+ skylight_2 = deepcopy(skylight)\n+ skylight.addnext(skylight_2)\n+ tr.xpath(skylight_2, 'h:SystemIdentifier').attrib['id'] = \"skylight2\"\n+ tr.xpath(skylight_2, 'h:AttachedToRoof').attrib['idref'] = \"roof1\"\n+ tr.xpath(skylight_2, 'h:Area').text = \"15\"\n+ res2 = tr.hpxml_to_hescore()\n+ # Skylight attached to the first and second roof\n+ self.assertEqual(res2['building']['zone']['zone_roof'][0]['zone_skylight']['skylight_area'], 15.0)\n+ self.assertEqual(res2['building']['zone']['zone_roof'][0]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res2['building']['zone']['zone_roof'][0]['zone_skylight']['solar_screen'])\n+ self.assertEqual(res2['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 12.0)\n+ self.assertEqual(res2['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res2['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+ tr.xpath(skylight_2, 'h:AttachedToRoof').attrib['idref'] = \"roof2\"\n+ tr.xpath(skylight_2, 'h:Area').text = \"10\"\n+ tr.xpath(skylight_2, 'h:GlassType').text = \"low-e\"\n+ # skylight1 dominates the properties\n+ res3 = tr.hpxml_to_hescore()\n+ self.assertEqual(res3['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 22.0)\n+ self.assertEqual(res3['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res3['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+\n class TestHEScoreV3(unittest.TestCase, ComparatorBase):\n \n def test_attic_with_multiple_roofs(self):\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestHEScore2021Updates::test_skylight_assignment"]}, {"instance_id": "NREL__hescore-hpxml-149", "base_commit": "e5af84582b4524ad92bac0a9f153051f2d39f5eb", "gold_patch": "diff --git a/docs/source/translation/about.rst b/docs/source/translation/about.rst\nindex c083c764..6eebb65c 100644\n--- a/docs/source/translation/about.rst\n+++ b/docs/source/translation/about.rst\n@@ -10,15 +10,6 @@ HEScore requires an assessment date. If a date is stored in the element\n ``Building/ProjectStatus/Date``, that date is used. If not, the current date is\n used.\n \n-External Building ID\n-********************\n-\n-The value of ``Building/extension/HESExternalID`` or\n-``Building/BuildingID/SendingSystemIdentifierValue``, if present, is copied into the\n-``building.about.external_building_id`` field in HEScore.\n-Preference is given to the `extension` element if both are present.\n-This is optional, but may be useful for those wanting to pass an additional building identifier for their own tracking purposes.\n-\n Building Shape\n **************\n \ndiff --git a/docs/source/translation/building_address.rst b/docs/source/translation/building_address.rst\nindex 2937502f..33449491 100644\n--- a/docs/source/translation/building_address.rst\n+++ b/docs/source/translation/building_address.rst\n@@ -91,3 +91,12 @@ element in the ``extension`` of ``Building/ProjectStatus``:\n \n Upon finding this ``HEScoreMentorAssessment`` element, the HEScore assessment\n type will be set to \"mentor\" regardless of the mapping :ref:`above `.\n+\n+External Building ID\n+********************\n+\n+The value of ``Building/extension/HESExternalID`` or\n+``Building/BuildingID/SendingSystemIdentifierValue``, if present, is copied into the\n+``building_address.external_building_id`` field in HEScore.\n+Preference is given to the `extension` element if both are present.\n+This is optional, but may be useful for those wanting to pass an additional building identifier for their own tracking purposes.\ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 0c9b2559..4f3a4544 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -828,6 +828,17 @@ class HPXMLtoHEScoreTranslatorBase(object):\n else:\n assert transaction_type == 'update'\n bldgaddr['assessment_type'] = 'corrected'\n+\n+ ext_id_xpath_exprs = (\n+ 'h:extension/h:HESExternalID/text()',\n+ 'h:BuildingID/h:SendingSystemIdentifierValue/text()'\n+ )\n+ for ext_id_xpath_expr in ext_id_xpath_exprs:\n+ external_id_value = xpath(b, ext_id_xpath_expr)\n+ if external_id_value is not None:\n+ bldgaddr['external_building_id'] = external_id_value\n+ break\n+\n return bldgaddr\n \n def get_hpwes(self, p, c):\n@@ -869,16 +880,6 @@ class HPXMLtoHEScoreTranslatorBase(object):\n ns = self.ns\n bldg_about = OrderedDict()\n \n- ext_id_xpath_exprs = (\n- 'h:extension/h:HESExternalID/text()',\n- 'h:BuildingID/h:SendingSystemIdentifierValue/text()'\n- )\n- for ext_id_xpath_expr in ext_id_xpath_exprs:\n- external_id_value = xpath(b, ext_id_xpath_expr)\n- if external_id_value is not None:\n- bldg_about['external_building_id'] = external_id_value\n- break\n-\n project_status_date_el = b.find('h:ProjectStatus/h:Date', namespaces=ns)\n if project_status_date_el is None:\n bldg_about['assessment_date'] = dt.date.today()\n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 47a0e703..8287a01b 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -1056,7 +1056,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n myid = uuid.uuid4().hex\n el.text = myid\n res = tr.hpxml_to_hescore()\n- self.assertEqual(myid, res['building']['about'].get('external_building_id'))\n+ self.assertEqual(myid, res['building_address'].get('external_building_id'))\n \n def test_external_id_extension_passthru(self):\n tr = self._load_xmlfile('hescore_min')\n@@ -1069,7 +1069,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = etree.SubElement(self.xpath('//h:Building/h:BuildingID'), tr.addns('h:SendingSystemIdentifierValue'))\n el.text = uuid.uuid4().hex\n res = tr.hpxml_to_hescore()\n- self.assertEqual(myid, res['building']['about'].get('external_building_id'))\n+ self.assertEqual(myid, res['building_address'].get('external_building_id'))\n \n def test_preconstruction_event_type(self):\n tr = self._load_xmlfile('hescore_min')\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestOtherHouses::test_external_id_extension_passthru", "tests/test_translation.py::TestOtherHouses::test_external_id_passthru"]}, {"instance_id": "NREL__hescore-hpxml-152", "base_commit": "9a069f2b34e5de5352673c96461afbbbbe75c2ae", "gold_patch": "diff --git a/hescorehpxml/hpxml3.py b/hescorehpxml/hpxml3.py\nindex 9a227e76..2c84e53c 100644\n--- a/hescorehpxml/hpxml3.py\n+++ b/hescorehpxml/hpxml3.py\n@@ -66,10 +66,11 @@ class HPXML3toHEScoreTranslator(HPXMLtoHEScoreTranslatorBase):\n wall = self.xpath(\n b,\n '//h:Wall[h:SystemIdentifier/@id=$kneewallid][h:AtticWallType=\"knee wall\"]',\n- raise_err=True,\n+ raise_err=False,\n kneewallid=kneewall_idref\n )\n- knee_walls.append(wall)\n+ if wall is not None:\n+ knee_walls.append(wall)\n \n return knee_walls\n \n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 8287a01b..dab1f7eb 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -6,6 +6,7 @@ import os\n import unittest\n import datetime as dt\n from lxml import etree, objectify\n+from lxml.builder import ElementMaker\n from hescorehpxml import HPXMLtoHEScoreTranslator, main\n from hescorehpxml.exceptions import TranslationError, InputOutOfBounds, ElementNotFoundError\n import io\n@@ -65,8 +66,7 @@ class ComparatorBase(object):\n return self.translator.xpath(self.translator.hpxmldoc, xpathexpr, *args, **kwargs)\n \n def element_maker(self):\n- E = objectify.ElementMaker(\n- annotate=False,\n+ E = ElementMaker(\n namespace=self.translator.ns['h'],\n nsmap=self.translator.ns\n )\n@@ -939,6 +939,30 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n self.assertEqual(resp['building']['zone']['zone_roof'][0]['ceiling_assembly_code'], 'ecwf00')\n self.assertAlmostEqual(resp['building']['zone']['zone_roof'][0]['roof_area'], 1400.0)\n \n+ def test_gable_wall_ignore(self):\n+ tr = self._load_xmlfile('hescore_min_v3')\n+ E = self.element_maker()\n+ wall1 = self.xpath('//h:Wall[1]')\n+ wall2 = deepcopy(wall1)\n+ wall1type = wall1.find(tr.addns('h:WallType'))\n+ wall1type.addnext(E.Area('100'))\n+ wall2type = wall2.find(tr.addns('h:WallType'))\n+ wall2type.addnext(E.Area('20'))\n+ # change the system id\n+ sysid = wall2.find(tr.addns('h:SystemIdentifier'))\n+ sysid.attrib['id'] = 'wall2'\n+ # and the insulation id\n+ ins_sysid = wall2.xpath('h:Insulation/h:SystemIdentifier', namespaces=tr.ns)[0]\n+ ins_sysid.attrib['id'] = 'wall2ins'\n+ wall1.addnext(wall2)\n+ sysid.addnext(E.InteriorAdjacentTo('attic - vented'))\n+ sysid.addnext(E.ExteriorAdjacentTo('outside'))\n+ att_to_roof = self.xpath('//h:Attic/h:AttachedToRoof')\n+ att_to_roof.addnext(E.AttachedToWall(idref='wall2'))\n+\n+ resp = tr.hpxml_to_hescore()\n+ assert resp['building']['zone']['zone_roof'][0]['roof_area'] == 1200\n+\n def test_wall_construction_ps_low_r(self):\n \"\"\"\n Unit test for #47\n@@ -2485,11 +2509,11 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n \n window3_frametype = self.xpath('//h:Window[h:SystemIdentifier/@id=\"window3\"]/h:FrameType')\n window3_frametype.clear()\n- window3_frametype.append(E.Aluminum(E.ThermalBreak(True)))\n+ window3_frametype.append(E.Aluminum(E.ThermalBreak(\"true\")))\n \n window4_frametype = self.xpath('//h:Window[h:SystemIdentifier/@id=\"window4\"]/h:FrameType')\n window4_frametype.clear()\n- window4_frametype.append(E.Aluminum(E.ThermalBreak(True)))\n+ window4_frametype.append(E.Aluminum(E.ThermalBreak(\"true\")))\n window4_frametype.getparent().append(E.GlassType('low-e'))\n \n d = tr.hpxml_to_hescore()\n@@ -2519,11 +2543,11 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n \n window3_frametype = self.xpath('//h:Window[h:SystemIdentifier/@id=\"window3\"]/h:FrameType')\n window3_frametype.clear()\n- window3_frametype.append(E.Aluminum(E.ThermalBreak(True)))\n+ window3_frametype.append(E.Aluminum(E.ThermalBreak(\"true\")))\n \n window4_frametype = self.xpath('//h:Window[h:SystemIdentifier/@id=\"window4\"]/h:FrameType')\n window4_frametype.clear()\n- window4_frametype.append(E.Aluminum(E.ThermalBreak(True)))\n+ window4_frametype.append(E.Aluminum(E.ThermalBreak(\"true\")))\n window4_frametype.getparent().append(E.GlassType('low-e'))\n \n d_v3 = tr_v3.hpxml_to_hescore()\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestOtherHouses::test_gable_wall_ignore"]}], "all_FAIL_TO_PASS": ["tests/test_translation.py::TestHEScore2021Updates::test_skylight_assignment", "tests/test_translation.py::TestOtherHouses::test_external_id_extension_passthru", "tests/test_translation.py::TestOtherHouses::test_external_id_passthru", "tests/test_translation.py::TestOtherHouses::test_gable_wall_ignore"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "peterbe__hashin-109_x3", "level": 3, "source": "swerebench", "repo": "peterbe/hashin", "image": "swerebench/sweb.eval.x86_64.peterbe_1776_hashin-109:latest", "base_commit": "ad75a2338bb1aa5ce6a56ac5288ad582fcbad65d", "num_bugs": 3, "bugs": [{"instance_id": "peterbe__hashin-109", "base_commit": "ad75a2338bb1aa5ce6a56ac5288ad582fcbad65d", "gold_patch": "diff --git a/README.rst b/README.rst\nindex 7f63630..3aefe28 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -270,8 +270,12 @@ put it directly into ``pip``.\n Version History\n ===============\n \n+0.14.4\n+ * Bugfix for new ``--index-url`` option feature in version 0.14.3.\n+ See https://github.com/peterbe/hashin/issues/108\n+\n 0.14.3\n- * New parameterr ``--index-url`` which allows to override the default which\n+ * New parameter ``--index-url`` which allows to override the default which\n is ``https://pypi.org``. Thanks @nmacinnis\n See https://github.com/peterbe/hashin/pull/107\n \ndiff --git a/hashin.py b/hashin.py\nindex a296359..cbc998c 100755\n--- a/hashin.py\n+++ b/hashin.py\n@@ -47,6 +47,7 @@ else:\n DEFAULT_ALGORITHM = \"sha256\"\n \n DEFAULT_INDEX_URL = os.environ.get(\"INDEX_URL\", \"https://pypi.org/\")\n+assert DEFAULT_INDEX_URL\n \n MAX_WORKERS = None\n \n@@ -159,6 +160,7 @@ def run_packages(\n synchronous=False,\n index_url=DEFAULT_INDEX_URL,\n ):\n+ assert index_url\n assert isinstance(specs, list), type(specs)\n all_new_lines = []\n first_interactive = True\n@@ -754,7 +756,7 @@ def get_parser():\n parser.add_argument(\n \"--index-url\",\n help=\"alternate package index url (default {0})\".format(DEFAULT_INDEX_URL),\n- default=None,\n+ default=DEFAULT_INDEX_URL,\n )\n return parser\n \ndiff --git a/setup.py b/setup.py\nindex 417cf50..e42b8ab 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -14,7 +14,7 @@ except ImportError:\n \n setup(\n name=\"hashin\",\n- version=\"0.14.3\",\n+ version=\"0.14.4\",\n description=\"Edits your requirements.txt by hashing them in\",\n long_description=open(path.join(_here, \"README.rst\")).read(),\n author=\"Peter Bengtsson\",\n", "test_patch": "diff --git a/tests/test_arg_parse.py b/tests/test_arg_parse.py\nindex 23288db..ae52330 100644\n--- a/tests/test_arg_parse.py\n+++ b/tests/test_arg_parse.py\n@@ -1,6 +1,6 @@\n import argparse\n \n-from hashin import get_parser\n+from hashin import get_parser, DEFAULT_INDEX_URL\n \n \n def test_everything():\n@@ -85,6 +85,6 @@ def test_minimal():\n update_all=False,\n interactive=False,\n synchronous=False,\n- index_url=None,\n+ index_url=DEFAULT_INDEX_URL,\n )\n assert args == (expected, [])\n", "FAIL_TO_PASS": ["tests/test_arg_parse.py::test_minimal"]}, {"instance_id": "peterbe__hashin-110", "base_commit": "90f2804dc624a52cd9283bd62fead99b837a3c1f", "gold_patch": "diff --git a/hashin.py b/hashin.py\nindex cbc998c..a43390e 100755\n--- a/hashin.py\n+++ b/hashin.py\n@@ -246,7 +246,7 @@ def run_packages(\n maybe_restriction = \"\" if not restriction else \"; {0}\".format(restriction)\n new_lines = \"{0}=={1}{2} \\\\\\n\".format(req, data[\"version\"], maybe_restriction)\n padding = \" \" * 4\n- for i, release in enumerate(data[\"hashes\"]):\n+ for i, release in enumerate(sorted(data[\"hashes\"], key=lambda r: r[\"hash\"])):\n new_lines += \"{0}--hash={1}:{2}\".format(padding, algorithm, release[\"hash\"])\n if i != len(data[\"hashes\"]) - 1:\n new_lines += \" \\\\\"\n", "test_patch": "diff --git a/tests/test_cli.py b/tests/test_cli.py\nindex 459694f..e494a33 100644\n--- a/tests/test_cli.py\n+++ b/tests/test_cli.py\n@@ -461,7 +461,7 @@ autocompeter==1.2.3 \\\\\n assert result == new_lines[2]\n \n \n-def test_amend_requirements_content_replacement_amonst_others():\n+def test_amend_requirements_content_replacement_amongst_others():\n previous = (\n \"\"\"\n otherpackage==1.0.0 --hash=sha256:cHay6ATFKumO3svU3B-8qBMYb-f1_dYlR4OgClWntEI\n@@ -489,7 +489,7 @@ autocompeter==1.2.3 \\\\\n assert result == previous + new_lines[2]\n \n \n-def test_amend_requirements_content_replacement_amonst_others_2():\n+def test_amend_requirements_content_replacement_amongst_others_2():\n previous = (\n \"https://github.com/rhelmer/pyinotify/archive/9ff352f.zip\"\n \"#egg=pyinotify \"\n@@ -609,7 +609,6 @@ def test_run(murlopen, tmpfile, capsys):\n # Now check the verbose output\n captured = capsys.readouterr()\n out_lines = captured.out.splitlines()\n- # out_lines = my_stdout.getvalue().splitlines()\n assert \"https://pypi.org/pypi/hashin/json\" in out_lines[0], out_lines[0]\n # url to download\n assert \"hashin-0.10-py2-none-any.whl\" in out_lines[1], out_lines[1]\n@@ -647,6 +646,60 @@ def test_run(murlopen, tmpfile, capsys):\n ) in lines\n \n \n+def test_canonical_list_of_hashes(murlopen, tmpfile, capsys):\n+ \"\"\"When hashes are written down, after the package spec, write down the hashes\n+ in a canonical way. Essentially, in lexicographic order. But when comparing\n+ existing hashes ignore any order.\n+ \"\"\"\n+\n+ def mocked_get(url, **options):\n+ if url == \"https://pypi.org/pypi/hashin/json\":\n+ return _Response(\n+ {\n+ \"info\": {\"version\": \"0.10\", \"name\": \"hashin\"},\n+ \"releases\": {\n+ # NOTE that the order of list is different from\n+ # the order you'd get of `sorted(x.digest for x in releases)`\n+ \"0.10\": [\n+ {\n+ \"url\": \"https://pypi.org/packages/source/p/hashin/hashin-0.10.tar.gz\",\n+ \"digests\": {\"sha256\": \"ccccc\"},\n+ },\n+ {\n+ \"url\": \"https://pypi.org/packages/2.7/p/hashin/hashin-0.10-py2-none-any.whl\",\n+ \"digests\": {\"sha256\": \"aaaaa\"},\n+ },\n+ {\n+ \"url\": \"https://pypi.org/packages/3.3/p/hashin/hashin-0.10-py3-none-any.whl\",\n+ \"digests\": {\"sha256\": \"bbbbb\"},\n+ },\n+ ]\n+ },\n+ }\n+ )\n+ raise NotImplementedError(url)\n+\n+ murlopen.side_effect = mocked_get\n+\n+ with tmpfile() as filename:\n+ with open(filename, \"w\") as f:\n+ f.write(\"\")\n+\n+ retcode = hashin.run(\"hashin==0.10\", filename, \"sha256\")\n+\n+ assert retcode == 0\n+ with open(filename) as f:\n+ output = f.read()\n+ assert output\n+ assert output.endswith(\"\\n\")\n+ lines = output.splitlines()\n+\n+ assert lines[0] == \"hashin==0.10 \\\\\"\n+ assert lines[1] == \" --hash=sha256:aaaaa \\\\\"\n+ assert lines[2] == \" --hash=sha256:bbbbb \\\\\"\n+ assert lines[3] == \" --hash=sha256:ccccc\"\n+\n+\n def test_run_atomic_not_write_with_error_on_last_package(murlopen, tmpfile):\n def mocked_get(url, **options):\n \n@@ -1623,7 +1676,7 @@ def test_run_comments_with_package_spec_patterns(murlopen, tmpfile, capsys):\n \n \n def test_run_dry(murlopen, tmpfile, capsys):\n- \"\"\"dry run should edit the requirements.txt file and print\n+ \"\"\"dry run should not edit the requirements file and print\n hashes and package name in the console\n \"\"\"\n \n", "FAIL_TO_PASS": ["tests/test_cli.py::test_canonical_list_of_hashes"]}, {"instance_id": "peterbe__hashin-111", "base_commit": "23840376aaf09746264a99545526fe4bbec93e17", "gold_patch": "diff --git a/hashin.py b/hashin.py\nindex a43390e..427079f 100755\n--- a/hashin.py\n+++ b/hashin.py\n@@ -773,6 +773,23 @@ def main():\n parser = get_parser()\n args = parser.parse_args()\n \n+ if (\n+ args.update_all\n+ and args.packages\n+ and len(args.packages) == 1\n+ and os.path.isfile(args.packages[0])\n+ and args.packages[0].endswith(\".txt\")\n+ ):\n+ # It's totally common to make the mistake of using the `--update-all` flag\n+ # and specifying the requirements file as the first argument. E.g.\n+ #\n+ # $ hashin --update-all --interactive myproject/reqs.txt\n+ #\n+ # The user intention is clear any non-keyed flags get interpreted as a\n+ # list of \"packages\". Let's fix that for the user.\n+ args.requirements_file = args.packages[0]\n+ args.packages = []\n+\n if args.update_all:\n if args.packages:\n print(\n", "test_patch": "diff --git a/tests/test_cli.py b/tests/test_cli.py\nindex e494a33..8c60ba0 100644\n--- a/tests/test_cli.py\n+++ b/tests/test_cli.py\n@@ -182,6 +182,36 @@ def test_packages_and_update_all(capsys, mock_get_parser):\n )\n \n \n+def test_packages_and_update_all_with_requirements_file(\n+ capsys, mock_get_parser, tmpfile\n+):\n+ with tmpfile() as filename:\n+ with open(filename, \"w\") as f:\n+ f.write(\"\")\n+\n+ def mock_parse_args(*a, **k):\n+ return argparse.Namespace(\n+ packages=[filename], # Note!\n+ algorithm=\"sha256\",\n+ python_version=\"3.8\",\n+ verbose=False,\n+ include_prereleases=False,\n+ dry_run=False,\n+ update_all=True,\n+ interactive=False,\n+ synchronous=False,\n+ index_url=\"anything\",\n+ )\n+\n+ mock_get_parser().parse_args.side_effect = mock_parse_args\n+\n+ error = hashin.main()\n+ assert error == 0\n+ # Because the requirements file is empty, the update-all command\n+ # won't find anything to query the internet about so we don't\n+ # need to mock murlopen in this test.\n+\n+\n def test_no_packages_and_not_update_all(capsys, mock_get_parser):\n def mock_parse_args(*a, **k):\n return argparse.Namespace(\n", "FAIL_TO_PASS": ["tests/test_cli.py::test_packages_and_update_all_with_requirements_file"]}], "all_FAIL_TO_PASS": ["tests/test_arg_parse.py::test_minimal", "tests/test_cli.py::test_canonical_list_of_hashes", "tests/test_cli.py::test_packages_and_update_all_with_requirements_file"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pytorch__ignite-734_x3", "level": 3, "source": "swerebench", "repo": "pytorch/ignite", "image": "swerebench/sweb.eval.x86_64.pytorch_1776_ignite-734:latest", "base_commit": "feff57f42454905e7566d114bcf5c1324ab9e56c", "num_bugs": 3, "bugs": [{"instance_id": "pytorch__ignite-734", "base_commit": "feff57f42454905e7566d114bcf5c1324ab9e56c", "gold_patch": "diff --git a/ignite/handlers/checkpoint.py b/ignite/handlers/checkpoint.py\nindex db893d6f..d58860f5 100644\n--- a/ignite/handlers/checkpoint.py\n+++ b/ignite/handlers/checkpoint.py\n@@ -31,7 +31,7 @@ class Checkpoint:\n score_function (callable, optional): If not None, it should be a function taking a single argument,\n :class:`~ignite.engine.Engine` object, and returning a score (`float`). Objects with highest scores will be\n retained.\n- score_name (str, optional): If `score_function` not None, it is possible to store its absolute value using\n+ score_name (str, optional): If `score_function` not None, it is possible to store its value using\n `score_name`. See Notes for more details.\n n_saved (int, optional): Number of objects that should be kept on disk. Older files will be removed. If set to\n `None`, all objects are kept.\n@@ -61,11 +61,11 @@ class Checkpoint:\n The filename will be `{filename_prefix}_{name}_{global_step}_{score}.pth`.\n \n If defined `score_function` and `score_name`, then the filename will\n- be `{filename_prefix}_{name}_{score_name}={abs(score)}.{ext}`. If `global_step_transform` is provided, then\n- the filename will be `{filename_prefix}_{name}_{global_step}_{score_name}={abs(score)}.{ext}`\n+ be `{filename_prefix}_{name}_{score_name}={score}.{ext}`. If `global_step_transform` is provided, then\n+ the filename will be `{filename_prefix}_{name}_{global_step}_{score_name}={score}.{ext}`\n \n- For example, `score_name=\"val_loss\"` and `score_function` that returns `-loss` (as objects with\n- highest scores will be retained), then saved filename will be `{filename_prefix}_{name}_val_loss=0.1234.pth`.\n+ For example, `score_name=\"neg_val_loss\"` and `score_function` that returns `-loss` (as objects with highest\n+ scores will be retained), then saved filename will be `{filename_prefix}_{name}_neg_val_loss=-0.1234.pth`.\n \n To get the last stored filename, handler exposes attribute `last_checkpoint`:\n \n@@ -183,11 +183,11 @@ class Checkpoint:\n if self._score_name is not None:\n if len(suffix) > 0:\n suffix += \"_\"\n- suffix = \"{}{}={}\".format(suffix, self._score_name, priority)\n+ suffix = \"{}{}={:.4f}\".format(suffix, self._score_name, priority)\n elif self._score_function is not None:\n if len(suffix) > 0:\n suffix += \"_\"\n- suffix = \"{}{}\".format(suffix, priority)\n+ suffix = \"{}{:.4f}\".format(suffix, priority)\n elif len(suffix) == 0:\n suffix = \"{}\".format(priority)\n \n@@ -325,7 +325,7 @@ class ModelCheckpoint(Checkpoint):\n score_function (callable, optional): if not None, it should be a function taking a single argument, an\n :class:`~ignite.engine.Engine` object, and return a score (`float`). Objects with highest scores will be\n retained.\n- score_name (str, optional): if `score_function` not None, it is possible to store its absolute value using\n+ score_name (str, optional): if `score_function` not None, it is possible to store its value using\n `score_name`. See Notes for more details.\n n_saved (int, optional): Number of objects that should be kept on disk. Older files will be removed. If set to\n `None`, all objects are kept.\n", "test_patch": "diff --git a/tests/ignite/contrib/engines/test_common.py b/tests/ignite/contrib/engines/test_common.py\nindex 3be8692e..55ec279c 100644\n--- a/tests/ignite/contrib/engines/test_common.py\n+++ b/tests/ignite/contrib/engines/test_common.py\n@@ -127,7 +127,7 @@ def test_save_best_model_by_val_score(dirname, capsys):\n data = [0, ]\n trainer.run(data, max_epochs=len(acc_scores))\n \n- assert set(os.listdir(dirname)) == set(['best_model_8_val_acc=0.61.pth', 'best_model_9_val_acc=0.7.pth'])\n+ assert set(os.listdir(dirname)) == set(['best_model_8_val_acc=0.6100.pth', 'best_model_9_val_acc=0.7000.pth'])\n \n \n def test_add_early_stopping_by_val_score():\ndiff --git a/tests/ignite/handlers/test_checkpoint.py b/tests/ignite/handlers/test_checkpoint.py\nindex f11e9a6f..5844bb13 100644\n--- a/tests/ignite/handlers/test_checkpoint.py\n+++ b/tests/ignite/handlers/test_checkpoint.py\n@@ -137,7 +137,7 @@ def test_checkpoint_with_score_function():\n checkpointer(trainer)\n assert save_handler.call_count == 1\n \n- save_handler.assert_called_with(obj, \"{}_0.77.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_0.7700.pth\".format(name))\n \n trainer.state.epoch = 12\n trainer.state.iteration = 1234\n@@ -145,10 +145,10 @@ def test_checkpoint_with_score_function():\n \n checkpointer(trainer)\n assert save_handler.call_count == 2\n- save_handler.assert_called_with(obj, \"{}_0.78.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_0.7800.pth\".format(name))\n assert save_handler.remove.call_count == 1\n- save_handler.remove.assert_called_with(\"{}_0.77.pth\".format(name))\n- assert checkpointer.last_checkpoint == \"{}_0.78.pth\".format(name)\n+ save_handler.remove.assert_called_with(\"{}_0.7700.pth\".format(name))\n+ assert checkpointer.last_checkpoint == \"{}_0.7800.pth\".format(name)\n \n model = DummyModel()\n to_save = {'model': model}\n@@ -176,7 +176,7 @@ def test_checkpoint_with_score_name_and_function():\n checkpointer(trainer)\n assert save_handler.call_count == 1\n \n- save_handler.assert_called_with(obj, \"{}_loss=-0.77.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_loss=-0.7700.pth\".format(name))\n \n trainer.state.epoch = 12\n trainer.state.iteration = 1234\n@@ -184,10 +184,10 @@ def test_checkpoint_with_score_name_and_function():\n \n checkpointer(trainer)\n assert save_handler.call_count == 2\n- save_handler.assert_called_with(obj, \"{}_loss=-0.76.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_loss=-0.7600.pth\".format(name))\n assert save_handler.remove.call_count == 1\n- save_handler.remove.assert_called_with(\"{}_loss=-0.77.pth\".format(name))\n- assert checkpointer.last_checkpoint == \"{}_loss=-0.76.pth\".format(name)\n+ save_handler.remove.assert_called_with(\"{}_loss=-0.7700.pth\".format(name))\n+ assert checkpointer.last_checkpoint == \"{}_loss=-0.7600.pth\".format(name)\n \n model = DummyModel()\n to_save = {'model': model}\n@@ -218,17 +218,17 @@ def test_checkpoint_with_score_function_and_trainer_epoch():\n checkpointer(evaluator)\n assert save_handler.call_count == 1\n \n- save_handler.assert_called_with(obj, \"{}_11_0.77.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_11_0.7700.pth\".format(name))\n \n trainer.state.epoch = 12\n evaluator.state.metrics['val_acc'] = 0.78\n \n checkpointer(evaluator)\n assert save_handler.call_count == 2\n- save_handler.assert_called_with(obj, \"{}_12_0.78.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_12_0.7800.pth\".format(name))\n assert save_handler.remove.call_count == 1\n- save_handler.remove.assert_called_with(\"{}_11_0.77.pth\".format(name))\n- assert checkpointer.last_checkpoint == \"{}_12_0.78.pth\".format(name)\n+ save_handler.remove.assert_called_with(\"{}_11_0.7700.pth\".format(name))\n+ assert checkpointer.last_checkpoint == \"{}_12_0.7800.pth\".format(name)\n \n model = DummyModel()\n to_save = {'model': model}\n@@ -256,17 +256,17 @@ def test_checkpoint_with_score_name_and_function_and_trainer_epoch():\n checkpointer(evaluator)\n assert save_handler.call_count == 1\n \n- save_handler.assert_called_with(obj, \"{}_11_val_acc=0.77.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_11_val_acc=0.7700.pth\".format(name))\n \n trainer.state.epoch = 12\n evaluator.state.metrics['val_acc'] = 0.78\n \n checkpointer(evaluator)\n assert save_handler.call_count == 2\n- save_handler.assert_called_with(obj, \"{}_12_val_acc=0.78.pth\".format(name))\n+ save_handler.assert_called_with(obj, \"{}_12_val_acc=0.7800.pth\".format(name))\n assert save_handler.remove.call_count == 1\n- save_handler.remove.assert_called_with(\"{}_11_val_acc=0.77.pth\".format(name))\n- assert checkpointer.last_checkpoint == \"{}_12_val_acc=0.78.pth\".format(name)\n+ save_handler.remove.assert_called_with(\"{}_11_val_acc=0.7700.pth\".format(name))\n+ assert checkpointer.last_checkpoint == \"{}_12_val_acc=0.7800.pth\".format(name)\n \n model = DummyModel()\n to_save = {'model': model}\n@@ -440,7 +440,7 @@ def test_best_k(dirname):\n for _ in range(4):\n h(engine, to_save)\n \n- expected = ['{}_{}_{}.pth'.format(_PREFIX, 'model', i) for i in [1.2, 3.1]]\n+ expected = ['{}_{}_{:.4f}.pth'.format(_PREFIX, 'model', i) for i in [1.2, 3.1]]\n \n assert sorted(os.listdir(dirname)) == expected\n \n@@ -464,7 +464,7 @@ def test_best_k_with_suffix(dirname):\n engine.state.epoch += 1\n h(engine, to_save)\n \n- expected = ['{}_{}_val_loss={:.7}.pth'.format(_PREFIX, 'model', scores[e - 1]) for e in [1, 3]]\n+ expected = ['{}_{}_val_loss={:.4}.pth'.format(_PREFIX, 'model', scores[e - 1]) for e in [1, 3]]\n \n assert sorted(os.listdir(dirname)) == expected\n \n", "FAIL_TO_PASS": ["tests/ignite/contrib/engines/test_common.py::test_save_best_model_by_val_score", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_function", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_name_and_function", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_function_and_trainer_epoch", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_name_and_function_and_trainer_epoch", "tests/ignite/handlers/test_checkpoint.py::test_best_k", "tests/ignite/handlers/test_checkpoint.py::test_best_k_with_suffix"]}, {"instance_id": "pytorch__ignite-758", "base_commit": "08ec3286dc9b8c24f618942f9834b8d16fe8715d", "gold_patch": "diff --git a/ignite/handlers/checkpoint.py b/ignite/handlers/checkpoint.py\nindex 43c0b992..4f806cd5 100644\n--- a/ignite/handlers/checkpoint.py\n+++ b/ignite/handlers/checkpoint.py\n@@ -1,5 +1,6 @@\n import os\n import tempfile\n+import numbers\n \n from collections import namedtuple\n import collections.abc as collections\n@@ -177,21 +178,26 @@ class Checkpoint:\n \n if self._score_function is not None:\n priority = self._score_function(engine)\n+ if not isinstance(priority, numbers.Number):\n+ raise ValueError(\"Output of score_function should be a number\")\n else:\n priority = engine.state.get_event_attrib_value(Events.ITERATION_COMPLETED)\n \n if self._check_lt_n_saved() or self._saved[0].priority < priority:\n \n+ priority_str = \"{}\".format(priority) if isinstance(priority, numbers.Integral) \\\n+ else \"{:.4f}\".format(priority)\n+\n if self._score_name is not None:\n if len(suffix) > 0:\n suffix += \"_\"\n- suffix = \"{}{}={:.4f}\".format(suffix, self._score_name, priority)\n+ suffix = \"{}{}={}\".format(suffix, self._score_name, priority_str)\n elif self._score_function is not None:\n if len(suffix) > 0:\n suffix += \"_\"\n- suffix = \"{}{:.4f}\".format(suffix, priority)\n+ suffix = \"{}{}\".format(suffix, priority_str)\n elif len(suffix) == 0:\n- suffix = \"{}\".format(priority)\n+ suffix = \"{}\".format(priority_str)\n \n checkpoint = self._setup_checkpoint()\n \n", "test_patch": "diff --git a/tests/ignite/handlers/test_checkpoint.py b/tests/ignite/handlers/test_checkpoint.py\nindex b36d5fc1..208698bc 100644\n--- a/tests/ignite/handlers/test_checkpoint.py\n+++ b/tests/ignite/handlers/test_checkpoint.py\n@@ -47,6 +47,17 @@ def test_checkpoint_wrong_input():\n Checkpoint(to_save, lambda x: x, score_function=lambda e: 123, score_name=\"acc\", global_step_transform=123)\n \n \n+def test_checkpoint_score_function_wrong_output():\n+ model = DummyModel()\n+ to_save = {'model': model}\n+\n+ checkpointer = Checkpoint(to_save, lambda x: x, score_function=lambda e: {\"1\": 1}, score_name=\"acc\")\n+ trainer = Engine(lambda e, b: None)\n+ trainer.state = State(epoch=0, iteration=0)\n+ with pytest.raises(ValueError, match=r\"Output of score_function should be a number\"):\n+ checkpointer(trainer)\n+\n+\n def test_checkpoint_default():\n \n def _test(to_save, obj, name):\n@@ -199,6 +210,51 @@ def test_checkpoint_with_score_name_and_function():\n _test(to_save, {'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, 'checkpoint')\n \n \n+def test_checkpoint_with_int_score():\n+\n+ def _test(to_save, obj, name, score_name=None):\n+ save_handler = MagicMock()\n+ save_handler.remove = MagicMock()\n+\n+ checkpointer = Checkpoint(to_save, save_handler=save_handler,\n+ score_name=score_name,\n+ score_function=lambda e: e.state.epoch)\n+\n+ if score_name is None:\n+ score_name = \"\"\n+ else:\n+ score_name += \"=\"\n+\n+ trainer = Engine(lambda e, b: None)\n+ trainer.state = State(epoch=1, iteration=1)\n+\n+ checkpointer(trainer)\n+ assert save_handler.call_count == 1\n+\n+ save_handler.assert_called_with(obj, \"{}_{}1.pth\".format(name, score_name))\n+\n+ trainer.state.epoch = 12\n+ trainer.state.iteration = 1234\n+\n+ checkpointer(trainer)\n+ assert save_handler.call_count == 2\n+ save_handler.assert_called_with(obj, \"{}_{}12.pth\".format(name, score_name))\n+ assert save_handler.remove.call_count == 1\n+ save_handler.remove.assert_called_with(\"{}_{}1.pth\".format(name, score_name))\n+ assert checkpointer.last_checkpoint == \"{}_{}12.pth\".format(name, score_name)\n+\n+ model = DummyModel()\n+ to_save = {'model': model}\n+ _test(to_save, model.state_dict(), 'model')\n+ _test(to_save, model.state_dict(), 'model', \"epoch\")\n+\n+ model = DummyModel()\n+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)\n+ to_save = {'model': model, 'optimizer': optimizer}\n+ _test(to_save, {'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, 'checkpoint')\n+ _test(to_save, {'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, 'checkpoint', \"epoch\")\n+\n+\n def test_checkpoint_with_score_function_and_trainer_epoch():\n \n def _test(to_save, obj, name):\n", "FAIL_TO_PASS": ["tests/ignite/handlers/test_checkpoint.py::test_checkpoint_score_function_wrong_output", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_int_score"]}, {"instance_id": "pytorch__ignite-772", "base_commit": "f996ebda8320c823c90fed2f16f0b7e0218ae028", "gold_patch": "diff --git a/ignite/handlers/checkpoint.py b/ignite/handlers/checkpoint.py\nindex 4f806cd5..6e66a2b8 100644\n--- a/ignite/handlers/checkpoint.py\n+++ b/ignite/handlers/checkpoint.py\n@@ -236,11 +236,20 @@ class Checkpoint:\n Args:\n to_load (Mapping): a dictionary with objects, e.g. `{\"model\": model, \"optimizer\": optimizer, ...}`\n checkpoint (Mapping): a dictionary with state_dicts to load, e.g. `{\"model\": model_state_dict,\n- \"optimizer\": opt_state_dict}`\n+ \"optimizer\": opt_state_dict}`. If `to_load` contains a single key, then checkpoint can contain directly\n+ corresponding state_dict.\n \"\"\"\n Checkpoint._check_objects(to_load, \"load_state_dict\")\n if not isinstance(checkpoint, collections.Mapping):\n raise TypeError(\"Argument checkpoint should be a dictionary, but given {}\".format(type(checkpoint)))\n+ if len(to_load) == 1:\n+ # single object and checkpoint is directly a state_dict\n+ key, obj = list(to_load.items())[0]\n+ if key not in checkpoint:\n+ obj.load_state_dict(checkpoint)\n+ return\n+\n+ # multiple objects to load\n for k, obj in to_load.items():\n if k not in checkpoint:\n raise ValueError(\"Object labeled by '{}' from `to_load` is not found in the checkpoint\".format(k))\n", "test_patch": "diff --git a/tests/ignite/handlers/test_checkpoint.py b/tests/ignite/handlers/test_checkpoint.py\nindex 208698bc..a853df7c 100644\n--- a/tests/ignite/handlers/test_checkpoint.py\n+++ b/tests/ignite/handlers/test_checkpoint.py\n@@ -700,7 +700,7 @@ def test_checkpoint_load_objects():\n Checkpoint.load_objects({\"a\": None}, {\"a\": None})\n \n model = DummyModel()\n- to_load = {'model': model}\n+ to_load = {'model': model, 'another_model': model}\n \n with pytest.raises(ValueError, match=r\"from `to_load` is not found in the checkpoint\"):\n Checkpoint.load_objects(to_load, {})\n@@ -714,6 +714,52 @@ def test_checkpoint_load_objects():\n assert model.state_dict() == model2.state_dict()\n \n \n+def test_checkpoint_load_objects_from_saved_file(dirname):\n+\n+ def _get_single_obj_to_save():\n+ model = DummyModel()\n+ to_save = {\n+ \"model\": model,\n+ }\n+ return to_save\n+\n+ def _get_multiple_objs_to_save():\n+ model = DummyModel()\n+ optim = torch.optim.SGD(model.parameters(), lr=0.001)\n+ lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=0.5)\n+ to_save = {\n+ \"model\": model,\n+ \"optimizer\": optim,\n+ \"lr_scheduler\": lr_scheduler,\n+ }\n+ return to_save\n+\n+ handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1)\n+ trainer = Engine(lambda e, b: None)\n+ trainer.state = State(epoch=0, iteration=0)\n+ # case: multiple objects\n+ to_save = _get_multiple_objs_to_save()\n+ handler(trainer, to_save)\n+ fname = handler.last_checkpoint\n+ assert isinstance(fname, str)\n+ assert os.path.join(dirname, _PREFIX) in fname\n+ assert os.path.exists(fname)\n+ loaded_objects = torch.load(fname)\n+ Checkpoint.load_objects(to_save, loaded_objects)\n+ os.remove(fname)\n+\n+ # case: single object\n+ handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1)\n+ to_save = _get_single_obj_to_save()\n+ handler(trainer, to_save)\n+ fname = handler.last_checkpoint\n+ assert isinstance(fname, str)\n+ assert os.path.join(dirname, _PREFIX) in fname\n+ assert os.path.exists(fname)\n+ loaded_objects = torch.load(fname)\n+ Checkpoint.load_objects(to_save, loaded_objects)\n+\n+\n def test_disksaver_wrong_input(dirname):\n \n with pytest.raises(ValueError, match=r\"Directory path '\\S+' is not found\"):\n", "FAIL_TO_PASS": ["tests/ignite/handlers/test_checkpoint.py::test_checkpoint_load_objects_from_saved_file"]}], "all_FAIL_TO_PASS": ["tests/ignite/contrib/engines/test_common.py::test_save_best_model_by_val_score", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_function", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_name_and_function", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_function_and_trainer_epoch", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_name_and_function_and_trainer_epoch", "tests/ignite/handlers/test_checkpoint.py::test_best_k", "tests/ignite/handlers/test_checkpoint.py::test_best_k_with_suffix", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_score_function_wrong_output", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_int_score", "tests/ignite/handlers/test_checkpoint.py::test_checkpoint_load_objects_from_saved_file"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ilevkivskyi__typing_inspect-71_x3", "level": 3, "source": "swerebench", "repo": "ilevkivskyi/typing_inspect", "image": "swerebench/sweb.eval.x86_64.ilevkivskyi_1776_typing_inspect-71:latest", "base_commit": "6dd6b38bc12bcbaf814fb0c69a801365b81e3611", "num_bugs": 3, "bugs": [{"instance_id": "ilevkivskyi__typing_inspect-71", "base_commit": "6dd6b38bc12bcbaf814fb0c69a801365b81e3611", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex 1fb80e9..6cf3061 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -5,6 +5,7 @@ matrix:\n fast_finish: true\n include:\n - python: 3.9\n+ - python: 3.9.1\n - python: 3.8\n - python: 3.7\n - python: 3.6\ndiff --git a/typing_inspect.py b/typing_inspect.py\nindex d3a0604..c11b856 100644\n--- a/typing_inspect.py\n+++ b/typing_inspect.py\n@@ -8,10 +8,14 @@ Example usage::\n # NOTE: This module must support Python 2.7 in addition to Python 3.x\n \n import sys\n+import types\n+\n from mypy_extensions import _TypedDictMeta as _TypedDictMeta_Mypy\n-if sys.version_info[:3] >= (3, 4, 0) and sys.version_info[:3] < (3, 9, 0):\n+\n+# See comments in typing_extensions source on why the switch is at 3.9.2\n+if (3, 4, 0) <= sys.version_info[:3] < (3, 9, 2):\n from typing_extensions import _TypedDictMeta as _TypedDictMeta_TE\n-elif sys.version_info[:3] >= (3, 9, 0):\n+elif sys.version_info[:3] >= (3, 9, 2):\n # typing_extensions.TypedDict is a re-export from typing.\n from typing import _TypedDictMeta as _TypedDictMeta_TE\n else:\n@@ -35,7 +39,7 @@ if NEW_TYPING:\n from typing_extensions import Final, Literal\n if sys.version_info[:3] >= (3, 9, 0):\n from typing import _SpecialGenericAlias\n- typingGenericAlias = (_GenericAlias, _SpecialGenericAlias)\n+ typingGenericAlias = (_GenericAlias, _SpecialGenericAlias, types.GenericAlias)\n else:\n typingGenericAlias = (_GenericAlias,)\n else:\n@@ -463,7 +467,7 @@ def get_args(tp, evaluate=None):\n if NEW_TYPING:\n if evaluate is not None and not evaluate:\n raise ValueError('evaluate can only be True in Python >= 3.7')\n- if isinstance(tp, _GenericAlias):\n+ if isinstance(tp, typingGenericAlias):\n res = tp.__args__\n if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:\n res = (list(res[:-1]), res[-1])\n@@ -485,7 +489,7 @@ def get_args(tp, evaluate=None):\n # backport of union's subs_tree\n tree = _union_subs_tree(tp)\n elif is_generic_type(tp):\n- # backport of genericmeta's subs_tree\n+ # backport of GenericMeta's subs_tree\n tree = _generic_subs_tree(tp)\n elif is_tuple_type(tp):\n # ad-hoc (inspired by union)\n", "test_patch": "diff --git a/test_typing_inspect.py b/test_typing_inspect.py\nindex c5fc753..58a03ee 100644\n--- a/test_typing_inspect.py\n+++ b/test_typing_inspect.py\n@@ -115,6 +115,7 @@ class Other(dict):\n \"\"\"\n \n PY36 = sys.version_info[:3] >= (3, 6, 0)\n+PY39 = sys.version_info[:3] >= (3, 9, 0)\n if PY36:\n exec(PY36_TESTS)\n \n@@ -131,6 +132,8 @@ class IsUtilityTestCase(TestCase):\n T = TypeVar('T')\n samples = [Generic, Generic[T], Iterable[int], Mapping,\n MutableMapping[T, List[int]], Sequence[Union[str, bytes]]]\n+ if PY39:\n+ samples.extend([list[int], dict[str, list[int]]])\n nonsamples = [int, Union[int, str], Union[int, T], Callable[..., T],\n Optional, bytes, list] + CLASSVAR_GENERIC\n self.sample_test(is_generic_type, samples, nonsamples)\n@@ -149,6 +152,8 @@ class IsUtilityTestCase(TestCase):\n \n def test_tuple(self):\n samples = [Tuple, Tuple[str, int], Tuple[Iterable, ...]]\n+ if PY39:\n+ samples.append(tuple[int, str])\n nonsamples = [int, tuple, 42, List[int], NamedTuple('N', [('x', int)])]\n self.sample_test(is_tuple_type, samples, nonsamples)\n if SUBCLASSABLE_TUPLES:\n@@ -301,6 +306,8 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_origin(ClassVar[int]), None)\n self.assertEqual(get_origin(Generic), Generic)\n self.assertEqual(get_origin(Generic[T]), Generic)\n+ if PY39:\n+ self.assertEqual(get_origin(list[int]), list)\n if GENERIC_TUPLE_PARAMETRIZABLE:\n tp = List[Tuple[T, T]][int]\n self.assertEqual(get_origin(tp), list if NEW_TYPING else List)\n@@ -323,6 +330,8 @@ class GetUtilityTestCase(TestCase):\n if EXISTING_UNIONS_SUBSCRIPTABLE:\n self.assertEqual(get_parameters(Union[S_co, Tuple[T, T]][int, U]), (U,))\n self.assertEqual(get_parameters(Mapping[T, Tuple[S_co, T]]), (T, S_co))\n+ if PY39:\n+ self.assertEqual(get_parameters(dict[int, T]), (T,))\n \n @skipIf(NEW_TYPING, \"Not supported in Python 3.7\")\n def test_last_args(self):\n@@ -389,6 +398,11 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_args(Literal[\"value\"], evaluate=True), (\"value\",))\n self.assertEqual(get_args(Literal[1, 2, 3], evaluate=True), (1, 2, 3))\n \n+ if PY39:\n+ self.assertEqual(get_args(list[int]), (int,))\n+ self.assertEqual(get_args(tuple[int, str]), (int, str))\n+ self.assertEqual(get_args(list[list[int]]), (list[int],))\n+\n def test_bound(self):\n T = TypeVar('T')\n TB = TypeVar('TB', bound=int)\n", "FAIL_TO_PASS": ["test_typing_inspect.py::IsUtilityTestCase::test_generic", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_parameters"]}, {"instance_id": "ilevkivskyi__typing_inspect-74", "base_commit": "d1d46f4c2429dd0a60f902fa7b728d67bb2d1582", "gold_patch": "diff --git a/typing_inspect.py b/typing_inspect.py\nindex c11b856..4c765e3 100644\n--- a/typing_inspect.py\n+++ b/typing_inspect.py\n@@ -467,7 +467,8 @@ def get_args(tp, evaluate=None):\n if NEW_TYPING:\n if evaluate is not None and not evaluate:\n raise ValueError('evaluate can only be True in Python >= 3.7')\n- if isinstance(tp, typingGenericAlias):\n+ # Note special aliases on Python 3.9 don't have __args__.\n+ if isinstance(tp, typingGenericAlias) and hasattr(tp, '__args__'):\n res = tp.__args__\n if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:\n res = (list(res[:-1]), res[-1])\n", "test_patch": "diff --git a/test_typing_inspect.py b/test_typing_inspect.py\nindex 58a03ee..7e9d432 100644\n--- a/test_typing_inspect.py\n+++ b/test_typing_inspect.py\n@@ -402,6 +402,8 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_args(list[int]), (int,))\n self.assertEqual(get_args(tuple[int, str]), (int, str))\n self.assertEqual(get_args(list[list[int]]), (list[int],))\n+ # This would return (~T,) before Python 3.9.\n+ self.assertEqual(get_args(List), ())\n \n def test_bound(self):\n T = TypeVar('T')\n", "FAIL_TO_PASS": ["test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated"]}, {"instance_id": "ilevkivskyi__typing_inspect-94", "base_commit": "b24da20b0f137e00cd8c511843ff52cb92dcf470", "gold_patch": "diff --git a/typing_inspect.py b/typing_inspect.py\nindex d786e96..0268b16 100644\n--- a/typing_inspect.py\n+++ b/typing_inspect.py\n@@ -408,7 +408,11 @@ def get_parameters(tp):\n else:\n return ()\n elif NEW_TYPING:\n- if (isinstance(tp, typingGenericAlias) or\n+ if (\n+ (\n+ isinstance(tp, typingGenericAlias) and\n+ hasattr(tp, '__parameters__')\n+ ) or\n isinstance(tp, type) and issubclass(tp, Generic) and\n tp is not Generic):\n return tp.__parameters__\n", "test_patch": "diff --git a/test_typing_inspect.py b/test_typing_inspect.py\nindex 9f6be56..eaea460 100644\n--- a/test_typing_inspect.py\n+++ b/test_typing_inspect.py\n@@ -14,6 +14,7 @@ from typing import (\n Union, Callable, Optional, TypeVar, Sequence, AnyStr, Mapping,\n MutableMapping, Iterable, Generic, List, Any, Dict, Tuple, NamedTuple,\n )\n+from typing import T as typing_T\n \n from mypy_extensions import TypedDict as METypedDict\n from typing_extensions import TypedDict as TETypedDict\n@@ -354,6 +355,10 @@ class GetUtilityTestCase(TestCase):\n self.assertEqual(get_parameters(Union), ())\n if not LEGACY_TYPING:\n self.assertEqual(get_parameters(List[int]), ())\n+ if PY39:\n+ self.assertEqual(get_parameters(List), ())\n+ else:\n+ self.assertEqual(get_parameters(List), (typing_T,))\n else:\n # in 3.5.3 a list has no __args__ and instead they are used in __parameters__\n # in 3.5.1 the behaviour is normal again.\n", "FAIL_TO_PASS": ["test_typing_inspect.py::GetUtilityTestCase::test_parameters"]}], "all_FAIL_TO_PASS": ["test_typing_inspect.py::IsUtilityTestCase::test_generic", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_parameters", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_parameters"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Fatal1ty__mashumaro-122_x3", "level": 3, "source": "swerebench", "repo": "Fatal1ty/mashumaro", "image": "swerebench/sweb.eval.x86_64.fatal1ty_1776_mashumaro-122:latest", "base_commit": "41b90d2a0505c2a5d463150d880df8cf917227a8", "num_bugs": 3, "bugs": [{"instance_id": "Fatal1ty__mashumaro-122", "base_commit": "41b90d2a0505c2a5d463150d880df8cf917227a8", "gold_patch": "diff --git a/mashumaro/jsonschema/schema.py b/mashumaro/jsonschema/schema.py\nindex 90fa19f..65c3ec3 100644\n--- a/mashumaro/jsonschema/schema.py\n+++ b/mashumaro/jsonschema/schema.py\n@@ -154,7 +154,7 @@ class Instance:\n self.__builder = CodeBuilder(self.origin_type, type_args)\n self.__builder.reset()\n \n- def fields(self) -> Iterable[Tuple[str, Type, Any]]:\n+ def fields(self) -> Iterable[Tuple[str, Type, bool, Any]]:\n for f_name, f_type in self._builder.get_field_types(\n include_extras=True\n ).items():\n@@ -166,7 +166,12 @@ class Instance:\n f_default = self._builder.namespace.get(f_name, MISSING)\n if f_default is not MISSING:\n f_default = _default(f_type, f_default)\n- yield f_name, f_type, f_default\n+\n+ has_default = (\n+ f.default is not MISSING or f.default_factory is not MISSING\n+ )\n+\n+ yield f_name, f_type, has_default, f_default\n \n def get_overridden_serialization_method(\n self,\n@@ -289,7 +294,7 @@ def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:\n field_schema_overrides = instance.get_config().json_schema.get(\n \"properties\", {}\n )\n- for f_name, f_type, f_default in instance.fields():\n+ for f_name, f_type, has_default, f_default in instance.fields():\n override = field_schema_overrides.get(f_name)\n f_instance = instance.copy(type=f_type, name=f_name)\n if override:\n@@ -301,8 +306,10 @@ def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:\n f_name = f_instance.alias\n if f_default is not MISSING:\n f_schema.default = f_default\n- else:\n+\n+ if not has_default:\n required.append(f_name)\n+\n properties[f_name] = f_schema\n if properties:\n schema.properties = properties\n", "test_patch": "diff --git a/tests/test_jsonschema/test_jsonschema_generation.py b/tests/test_jsonschema/test_jsonschema_generation.py\nindex 875d719..626f977 100644\n--- a/tests/test_jsonschema/test_jsonschema_generation.py\n+++ b/tests/test_jsonschema/test_jsonschema_generation.py\n@@ -126,6 +126,7 @@ def test_jsonschema_for_dataclass():\n c: Optional[int] = field(default=None, metadata={\"alias\": \"cc\"})\n d: str = \"\"\n e: int = field(init=False)\n+ f: List[int] = field(default_factory=list)\n \n class Config:\n aliases = {\"a\": \"aa\", \"d\": \"dd\"}\n@@ -143,6 +144,9 @@ def test_jsonschema_for_dataclass():\n default=None,\n ),\n \"dd\": JSONSchema(type=JSONSchemaInstanceType.STRING, default=\"\"),\n+ \"f\": JSONArraySchema(\n+ items=JSONSchema(type=JSONSchemaInstanceType.INTEGER)\n+ ),\n },\n additionalProperties=False,\n required=[\"aa\"],\n", "FAIL_TO_PASS": ["tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass"]}, {"instance_id": "Fatal1ty__mashumaro-127", "base_commit": "73a937aebf8383da558cac3e71978cc1f8e6a0c7", "gold_patch": "diff --git a/README.md b/README.md\nindex d1287b9..96a1ff2 100644\n--- a/README.md\n+++ b/README.md\n@@ -2364,7 +2364,7 @@ For simple one-time cases it's recommended to start from using a configurable\n serialized to json or to dict:\n \n ```python\n-from dataclasses import dataclass\n+from dataclasses import dataclass, field\n from typing import List\n from uuid import UUID\n \n@@ -2374,7 +2374,7 @@ from mashumaro.jsonschema import build_json_schema\n @dataclass\n class User:\n id: UUID\n- name: str\n+ name: str = field(metadata={\"description\": \"User name\"})\n \n \n print(build_json_schema(List[User]).to_json())\n@@ -2395,7 +2395,8 @@ print(build_json_schema(List[User]).to_json())\n \"format\": \"uuid\"\n },\n \"name\": {\n- \"type\": \"string\"\n+ \"type\": \"string\",\n+ \"description\": \"User name\"\n }\n },\n \"additionalProperties\": false,\ndiff --git a/mashumaro/jsonschema/schema.py b/mashumaro/jsonschema/schema.py\nindex 65c3ec3..7779aa6 100644\n--- a/mashumaro/jsonschema/schema.py\n+++ b/mashumaro/jsonschema/schema.py\n@@ -306,6 +306,9 @@ def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:\n f_name = f_instance.alias\n if f_default is not MISSING:\n f_schema.default = f_default\n+ description = f_instance.metadata.get(\"description\")\n+ if description:\n+ f_schema.description = description\n \n if not has_default:\n required.append(f_name)\n", "test_patch": "diff --git a/tests/test_jsonschema/test_jsonschema_generation.py b/tests/test_jsonschema/test_jsonschema_generation.py\nindex 626f977..5bf61a6 100644\n--- a/tests/test_jsonschema/test_jsonschema_generation.py\n+++ b/tests/test_jsonschema/test_jsonschema_generation.py\n@@ -126,7 +126,9 @@ def test_jsonschema_for_dataclass():\n c: Optional[int] = field(default=None, metadata={\"alias\": \"cc\"})\n d: str = \"\"\n e: int = field(init=False)\n- f: List[int] = field(default_factory=list)\n+ f: List[int] = field(\n+ default_factory=list, metadata={\"description\": \"description for f\"}\n+ )\n \n class Config:\n aliases = {\"a\": \"aa\", \"d\": \"dd\"}\n@@ -145,7 +147,8 @@ def test_jsonschema_for_dataclass():\n ),\n \"dd\": JSONSchema(type=JSONSchemaInstanceType.STRING, default=\"\"),\n \"f\": JSONArraySchema(\n- items=JSONSchema(type=JSONSchemaInstanceType.INTEGER)\n+ items=JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ description=\"description for f\",\n ),\n },\n additionalProperties=False,\n", "FAIL_TO_PASS": ["tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass"]}, {"instance_id": "Fatal1ty__mashumaro-128", "base_commit": "73a937aebf8383da558cac3e71978cc1f8e6a0c7", "gold_patch": "diff --git a/README.md b/README.md\nindex d1287b9..f6e11e6 100644\n--- a/README.md\n+++ b/README.md\n@@ -2698,7 +2698,9 @@ Object constraints:\n ### Extending JSON Schema\n \n Using a `Config` class it is possible to override some parts of the schema.\n-Currently, it works for dataclass fields via \"properties\" key:\n+Currently, you can do the following:\n+* override some field schemas using the \"properties\" key\n+* change `additionalProperties` using the \"additionalProperties\" key\n \n ```python\n from dataclasses import dataclass\n@@ -2716,7 +2718,8 @@ class FooBar:\n \"type\": \"string\",\n \"description\": \"bar\"\n }\n- }\n+ },\n+ \"additionalProperties\": True,\n }\n \n print(build_json_schema(FooBar).to_json())\n@@ -2738,7 +2741,7 @@ print(build_json_schema(FooBar).to_json())\n \"type\": \"integer\"\n }\n },\n- \"additionalProperties\": false,\n+ \"additionalProperties\": true,\n \"required\": [\n \"foo\",\n \"bar\"\n@@ -2747,6 +2750,9 @@ print(build_json_schema(FooBar).to_json())\n ```\n
    \n \n+You can also change the \"additionalProperties\" key to a specific schema\n+by passing it a `JSONSchema` instance instead of a bool value.\n+\n ### JSON Schema and custom serialization methods\n \n Mashumaro provides different ways to override default serialization methods for\ndiff --git a/mashumaro/jsonschema/schema.py b/mashumaro/jsonschema/schema.py\nindex 65c3ec3..9bce042 100644\n--- a/mashumaro/jsonschema/schema.py\n+++ b/mashumaro/jsonschema/schema.py\n@@ -285,15 +285,16 @@ def override_field_instance_type_if_needed(\n def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:\n # TODO: Self references might not work\n if is_dataclass(instance.origin_type):\n+ jsonschema_config = instance.get_config().json_schema\n schema = JSONObjectSchema(\n title=instance.origin_type.__name__,\n- additionalProperties=False,\n+ additionalProperties=jsonschema_config.get(\n+ \"additionalProperties\", False\n+ ),\n )\n properties: Dict[str, JSONSchema] = {}\n required = []\n- field_schema_overrides = instance.get_config().json_schema.get(\n- \"properties\", {}\n- )\n+ field_schema_overrides = jsonschema_config.get(\"properties\", {})\n for f_name, f_type, has_default, f_default in instance.fields():\n override = field_schema_overrides.get(f_name)\n f_instance = instance.copy(type=f_type, name=f_name)\n", "test_patch": "diff --git a/tests/test_jsonschema/test_jsonschema_generation.py b/tests/test_jsonschema/test_jsonschema_generation.py\nindex 626f977..0b08833 100644\n--- a/tests/test_jsonschema/test_jsonschema_generation.py\n+++ b/tests/test_jsonschema/test_jsonschema_generation.py\n@@ -1051,3 +1051,45 @@ def test_jsonschema_with_ref_prefix():\n .items.to_dict()\n == schema\n )\n+\n+\n+def test_jsonschema_with_additional_properties_true():\n+ @dataclass\n+ class DataClass:\n+ x: int\n+\n+ class Config(BaseConfig):\n+ json_schema = {\"additionalProperties\": True}\n+\n+ schema = JSONObjectSchema(\n+ title=\"DataClass\",\n+ properties={\n+ \"x\": JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ },\n+ additionalProperties=True,\n+ required=[\"x\"],\n+ )\n+ assert build_json_schema(DataClass) == schema\n+\n+\n+def test_jsonschema_with_additional_properties_schema():\n+ @dataclass\n+ class DataClass:\n+ x: int\n+\n+ class Config(BaseConfig):\n+ json_schema = {\n+ \"additionalProperties\": JSONSchema(\n+ type=JSONSchemaInstanceType.INTEGER\n+ )\n+ }\n+\n+ schema = JSONObjectSchema(\n+ title=\"DataClass\",\n+ properties={\n+ \"x\": JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ },\n+ additionalProperties=JSONSchema(type=JSONSchemaInstanceType.INTEGER),\n+ required=[\"x\"],\n+ )\n+ assert build_json_schema(DataClass) == schema\n", "FAIL_TO_PASS": ["tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_true", "tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_schema"]}], "all_FAIL_TO_PASS": ["tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass", "tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass", "tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_true", "tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_schema"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "reata__sqllineage-38_x3", "level": 3, "source": "swerebench", "repo": "reata/sqllineage", "image": "swerebench/sweb.eval.x86_64.reata_1776_sqllineage-38:latest", "base_commit": "d79057f068fa8d2e3c8c121355eb9af2a026d899", "num_bugs": 3, "bugs": [{"instance_id": "reata__sqllineage-38", "base_commit": "d79057f068fa8d2e3c8c121355eb9af2a026d899", "gold_patch": "diff --git a/sqllineage/core.py b/sqllineage/core.py\nindex 231aa26..5b010e2 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -3,13 +3,13 @@ import sys\n from typing import List, Set\n \n import sqlparse\n-from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList\n+from sqlparse.sql import Comment, Function, Identifier, Parenthesis, Statement, TokenList\n from sqlparse.tokens import Keyword, Token\n \n SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN',\n 'FULL OUTER JOIN', 'CROSS JOIN')\n TARGET_TABLE_TOKENS = ('INTO', 'OVERWRITE', 'TABLE')\n-TEMP_TABLE_TOKENS = ('WITH', )\n+TEMP_TABLE_TOKENS = ('WITH',)\n \n \n class LineageParser(object):\n@@ -53,7 +53,7 @@ Target Tables:\n def target_tables(self) -> Set[str]:\n return self._target_tables\n \n- def _extract_from_token(self, token: Token):\n+ def _extract_from_token(self, token: Token) -> None:\n source_table_token_flag = target_table_token_flag = temp_table_token_flag = False\n for sub_token in token.tokens:\n if isinstance(sub_token, TokenList):\n@@ -72,7 +72,7 @@ Target Tables:\n self._target_tables.add(sub_token.get_alias())\n continue\n if source_table_token_flag:\n- if sub_token.is_whitespace:\n+ if self.__token_negligible_before_tablename(sub_token):\n continue\n else:\n assert isinstance(sub_token, Identifier)\n@@ -85,7 +85,7 @@ Target Tables:\n self._source_tables.add(sub_token.get_real_name())\n source_table_token_flag = False\n elif target_table_token_flag:\n- if sub_token.is_whitespace:\n+ if self.__token_negligible_before_tablename(sub_token):\n continue\n elif isinstance(sub_token, Function):\n # insert into tab (col1, col2), tab (col1, col2) will be parsed as Function\n@@ -98,7 +98,7 @@ Target Tables:\n self._target_tables.add(sub_token.get_real_name())\n target_table_token_flag = False\n elif temp_table_token_flag:\n- if sub_token.is_whitespace:\n+ if self.__token_negligible_before_tablename(sub_token):\n continue\n else:\n assert isinstance(sub_token, Identifier)\n@@ -107,6 +107,10 @@ Target Tables:\n self._extract_from_token(sub_token)\n temp_table_token_flag = False\n \n+ @classmethod\n+ def __token_negligible_before_tablename(cls, token: Token) -> bool:\n+ return token.is_whitespace or isinstance(token, Comment)\n+\n \n def main():\n parser = argparse.ArgumentParser(prog='sqllineage', description='SQL Lineage Parser.')\n", "test_patch": "diff --git a/tests/test_select.py b/tests/test_select.py\nindex 8837091..69b6133 100644\n--- a/tests/test_select.py\n+++ b/tests/test_select.py\n@@ -30,6 +30,14 @@ def test_select_with_comment():\n helper(\"SELECT -- comment1\\n col1 FROM tab1\", {\"tab1\"})\n \n \n+def test_select_with_comment_after_from():\n+ helper(\"SELECT col1\\nFROM -- comment\\ntab1\", {\"tab1\"})\n+\n+\n+def test_select_with_comment_after_join():\n+ helper(\"select * from tab1 join --comment\\ntab2 on tab1.x = tab2.x\", {\"tab1\", \"tab2\"})\n+\n+\n def test_select_keyword_as_column_alias():\n # here `as` is the column alias\n helper(\"SELECT 1 `as` FROM tab1\", {\"tab1\"})\n", "FAIL_TO_PASS": ["tests/test_select.py::test_select_with_comment_after_from", "tests/test_select.py::test_select_with_comment_after_join"]}, {"instance_id": "reata__sqllineage-40", "base_commit": "d80f93bcdcdd4d4b9120ba8c6a0159b7e0e8ba26", "gold_patch": "diff --git a/sqllineage/core.py b/sqllineage/core.py\nindex 5b010e2..0d7c505 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -1,4 +1,5 @@\n import argparse\n+import re\n import sys\n from typing import List, Set\n \n@@ -6,8 +7,9 @@ import sqlparse\n from sqlparse.sql import Comment, Function, Identifier, Parenthesis, Statement, TokenList\n from sqlparse.tokens import Keyword, Token\n \n-SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN',\n- 'FULL OUTER JOIN', 'CROSS JOIN')\n+SOURCE_TABLE_TOKENS = (r'FROM',\n+ # inspired by https://github.com/andialbrecht/sqlparse/blob/master/sqlparse/keywords.py\n+ r'((LEFT\\s+|RIGHT\\s+|FULL\\s+)?(INNER\\s+|OUTER\\s+|STRAIGHT\\s+)?|(CROSS\\s+|NATURAL\\s+)?)?JOIN')\n TARGET_TABLE_TOKENS = ('INTO', 'OVERWRITE', 'TABLE')\n TEMP_TABLE_TOKENS = ('WITH',)\n \n@@ -59,7 +61,7 @@ Target Tables:\n if isinstance(sub_token, TokenList):\n self._extract_from_token(sub_token)\n if sub_token.ttype in Keyword:\n- if sub_token.normalized in SOURCE_TABLE_TOKENS:\n+ if any(re.match(regex, sub_token.normalized) for regex in SOURCE_TABLE_TOKENS):\n source_table_token_flag = True\n elif sub_token.normalized in TARGET_TABLE_TOKENS:\n target_table_token_flag = True\n", "test_patch": "diff --git a/tests/test_select.py b/tests/test_select.py\nindex 69b6133..8f31412 100644\n--- a/tests/test_select.py\n+++ b/tests/test_select.py\n@@ -69,6 +69,10 @@ def test_select_left_join():\n helper(\"SELECT * FROM tab1 LEFT JOIN tab2\", {\"tab1\", \"tab2\"})\n \n \n+def test_select_left_join_with_extra_space_in_middle():\n+ helper(\"SELECT * FROM tab1 LEFT JOIN tab2\", {\"tab1\", \"tab2\"})\n+\n+\n def test_select_left_semi_join():\n helper(\"SELECT * FROM tab1 LEFT SEMI JOIN tab2\", {\"tab1\", \"tab2\"})\n \n", "FAIL_TO_PASS": ["tests/test_select.py::test_select_left_join_with_extra_space_in_middle"]}, {"instance_id": "reata__sqllineage-41", "base_commit": "c16243c03e8d619a40afaef7d720ed82834da015", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex eb1e3f6..59abe34 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -4,6 +4,7 @@ python:\n - \"3.5\"\n - \"3.6\"\n - \"3.7\"\n+ - \"3.8\"\n # command to install dependencies\n install:\n - pip install tox-travis codecov\ndiff --git a/sqllineage/core.py b/sqllineage/core.py\nindex 0d7c505..a46e388 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -23,7 +23,8 @@ class LineageParser(object):\n self._stmt = [s for s in sqlparse.parse(sql.strip(), self._encoding) if s.token_first(skip_cm=True)]\n for stmt in self._stmt:\n if stmt.get_type() == \"DROP\":\n- self._target_tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)}\n+ for tables in (self._source_tables, self._target_tables):\n+ tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)}\n else:\n self._extract_from_token(stmt)\n self._tmp_tables = self._source_tables.intersection(self._target_tables)\ndiff --git a/tox.ini b/tox.ini\nindex 0fa8e74..9546285 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -1,5 +1,5 @@\n [tox]\n-envlist = py35,py36,py37\n+envlist = py35,py36,py37,py38\n \n [testenv]\n deps =\n", "test_patch": "diff --git a/tests/test_others.py b/tests/test_others.py\nindex ddc0c30..eabb6d4 100644\n--- a/tests/test_others.py\n+++ b/tests/test_others.py\n@@ -31,6 +31,13 @@ def test_drop_after_create():\n helper(\"CREATE TABLE IF NOT EXISTS tab1 (col1 STRING);DROP TABLE IF EXISTS tab1\", None, None)\n \n \n+def test_drop_tmp_tab_after_create():\n+ sql = \"\"\"create table tab_a as select * from tab_b;\n+insert overwrite table tab_c select * from tab_a;\n+drop table tab_a;\"\"\"\n+ helper(sql, {\"tab_b\"}, {\"tab_c\"})\n+\n+\n def test_create_select():\n helper(\"CREATE TABLE tab1 SELECT * FROM tab2\", {\"tab2\"}, {\"tab1\"})\n \n", "FAIL_TO_PASS": ["tests/test_others.py::test_drop_tmp_tab_after_create"]}], "all_FAIL_TO_PASS": ["tests/test_select.py::test_select_with_comment_after_from", "tests/test_select.py::test_select_with_comment_after_join", "tests/test_select.py::test_select_left_join_with_extra_space_in_middle", "tests/test_others.py::test_drop_tmp_tab_after_create"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "reata__sqllineage-493_x3", "level": 3, "source": "swerebench", "repo": "reata/sqllineage", "image": "swerebench/sweb.eval.x86_64.reata_1776_sqllineage-493:latest", "base_commit": "843ab2eb58e3e8f4d68c5e67afc7f69341c3ade7", "num_bugs": 3, "bugs": [{"instance_id": "reata__sqllineage-493", "base_commit": "843ab2eb58e3e8f4d68c5e67afc7f69341c3ade7", "gold_patch": "diff --git a/sqllineage/core/parser/sqlfluff/extractors/select.py b/sqllineage/core/parser/sqlfluff/extractors/select.py\nindex 72c1eda..5c9fe72 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/select.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/select.py\n@@ -75,7 +75,14 @@ class SelectExtractor(BaseExtractor, SourceHandlerMixin):\n \n # By recursively extracting each subquery of the parent and merge, we're doing Depth-first search\n for sq in subqueries:\n- holder |= SelectExtractor(self.dialect).extract(\n+ from .cte import CteExtractor\n+\n+ extractor_cls = (\n+ CteExtractor\n+ if sq.query.get_child(\"with_compound_statement\")\n+ else SelectExtractor\n+ )\n+ holder |= extractor_cls(self.dialect).extract(\n sq.query, AnalyzerContext(cte=holder.cte, write={sq})\n )\n \ndiff --git a/sqllineage/core/parser/sqlfluff/utils.py b/sqllineage/core/parser/sqlfluff/utils.py\nindex b17c29c..406b17d 100644\n--- a/sqllineage/core/parser/sqlfluff/utils.py\n+++ b/sqllineage/core/parser/sqlfluff/utils.py\n@@ -36,7 +36,9 @@ def is_subquery(segment: BaseSegment) -> bool:\n segment if segment.type == \"bracketed\" else segment.segments[0]\n )\n # check if innermost parenthesis contains SELECT\n- if token.get_child(\"select_statement\", \"set_expression\"):\n+ if token.get_child(\n+ \"select_statement\", \"set_expression\", \"with_compound_statement\"\n+ ):\n return True\n elif expression := token.get_child(\"expression\"):\n if expression.get_child(\"select_statement\"):\n@@ -152,7 +154,6 @@ def list_subqueries(segment: BaseSegment) -> List[SubQueryTuple]:\n elif segment.type == \"from_expression_element\":\n as_segment, target = extract_as_and_target_segment(segment)\n if is_subquery(target):\n- as_segment, target = extract_as_and_target_segment(segment)\n subquery = [\n SubQueryTuple(\n extract_innermost_bracketed(target)\n", "test_patch": "diff --git a/tests/sql/table/test_cte.py b/tests/sql/table/test_cte.py\nindex 422ddde..fa41670 100644\n--- a/tests/sql/table/test_cte.py\n+++ b/tests/sql/table/test_cte.py\n@@ -85,3 +85,15 @@ SELECT col3 from tab3\"\"\"\n sql,\n {\"tab1\", \"tab2\", \"tab3\"},\n )\n+\n+\n+def test_cte_within_subquery():\n+ sql = \"\"\"SELECT sq.col1\n+FROM (WITH cte1 AS (SELECT col1 FROM tab1)\n+ SELECT col1\n+ FROM cte1\n+ INNER JOIN tab2 ON cte1.col1 = tab2.col1) AS sq\"\"\"\n+ assert_table_lineage_equal(\n+ sql,\n+ {\"tab1\", \"tab2\"},\n+ )\n", "FAIL_TO_PASS": ["tests/sql/table/test_cte.py::test_cte_within_subquery"]}, {"instance_id": "reata__sqllineage-494", "base_commit": "a2b03449ab6d8722eeb3cd9869d89a2af1b7c098", "gold_patch": "diff --git a/sqllineage/core/parser/sqlfluff/extractors/base.py b/sqllineage/core/parser/sqlfluff/extractors/base.py\nindex 74ad8bc..86c9a53 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/base.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/base.py\n@@ -101,6 +101,25 @@ class BaseExtractor:\n \"\"\"\n return extractor_cls(self.dialect).extract(segment, context)\n \n+ def extract_subquery(\n+ self, subqueries: List[SubQuery], holder: SubQueryLineageHolder\n+ ):\n+ \"\"\"\n+ extract subqueries collected from statement-level segment\n+ \"\"\"\n+ from .cte import CteExtractor\n+ from .select import SelectExtractor\n+\n+ for sq in subqueries:\n+ extractor_cls = (\n+ CteExtractor\n+ if sq.query.get_child(\"with_compound_statement\")\n+ else SelectExtractor\n+ )\n+ holder |= extractor_cls(self.dialect).extract(\n+ sq.query, AnalyzerContext(cte=holder.cte, write={sq})\n+ )\n+\n @staticmethod\n def _init_holder(context: AnalyzerContext) -> SubQueryLineageHolder:\n \"\"\"\ndiff --git a/sqllineage/core/parser/sqlfluff/extractors/cte.py b/sqllineage/core/parser/sqlfluff/extractors/cte.py\nindex 0427a3b..4356dcd 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/cte.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/cte.py\n@@ -59,11 +59,6 @@ class CteExtractor(BaseExtractor):\n if segment_has_alias:\n holder.add_cte(SqlFluffSubQuery.of(sub_segment, identifier))\n \n- # By recursively extracting each extractor of the parent and merge, we're doing Depth-first search\n- for sq in subqueries:\n- holder |= SelectExtractor(self.dialect).extract(\n- sq.query,\n- AnalyzerContext(cte=holder.cte, write={sq}),\n- )\n+ self.extract_subquery(subqueries, holder)\n \n return holder\ndiff --git a/sqllineage/core/parser/sqlfluff/extractors/select.py b/sqllineage/core/parser/sqlfluff/extractors/select.py\nindex 5c9fe72..24dcc61 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/select.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/select.py\n@@ -70,21 +70,9 @@ class SelectExtractor(BaseExtractor, SourceHandlerMixin):\n subqueries.append(sq)\n self._handle_table(seg, holder)\n self._handle_column(seg)\n-\n self.end_of_query_cleanup(holder)\n \n- # By recursively extracting each subquery of the parent and merge, we're doing Depth-first search\n- for sq in subqueries:\n- from .cte import CteExtractor\n-\n- extractor_cls = (\n- CteExtractor\n- if sq.query.get_child(\"with_compound_statement\")\n- else SelectExtractor\n- )\n- holder |= extractor_cls(self.dialect).extract(\n- sq.query, AnalyzerContext(cte=holder.cte, write={sq})\n- )\n+ self.extract_subquery(subqueries, holder)\n \n return holder\n \n", "test_patch": "diff --git a/tests/sql/table/test_cte.py b/tests/sql/table/test_cte.py\nindex fa41670..c9ab271 100644\n--- a/tests/sql/table/test_cte.py\n+++ b/tests/sql/table/test_cte.py\n@@ -97,3 +97,15 @@ FROM (WITH cte1 AS (SELECT col1 FROM tab1)\n sql,\n {\"tab1\", \"tab2\"},\n )\n+\n+\n+def test_cte_within_cte():\n+ sql = \"\"\"WITH cte1 AS\n+ (WITH cte2 AS\n+ (SELECT id\n+ FROM tab1)\n+ SELECT id\n+ FROM cte2)\n+SELECT id\n+FROM cte1\"\"\"\n+ assert_table_lineage_equal(sql, {\"tab1\"})\n", "FAIL_TO_PASS": ["tests/sql/table/test_cte.py::test_cte_within_cte"]}, {"instance_id": "reata__sqllineage-495", "base_commit": "b66274eb702d81afb0b7f2a6478e349e66979adc", "gold_patch": "diff --git a/sqllineage/core/parser/sqlfluff/extractors/cte.py b/sqllineage/core/parser/sqlfluff/extractors/cte.py\nindex 4356dcd..656d893 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/cte.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/cte.py\n@@ -6,6 +6,7 @@ from sqllineage.core.parser.sqlfluff.extractors.create_insert import (\n CreateInsertExtractor,\n )\n from sqllineage.core.parser.sqlfluff.extractors.select import SelectExtractor\n+from sqllineage.core.parser.sqlfluff.extractors.update import UpdateExtractor\n from sqllineage.core.parser.sqlfluff.models import SqlFluffSubQuery\n from sqllineage.core.parser.sqlfluff.utils import list_child_segments\n from sqllineage.utils.entities import AnalyzerContext\n@@ -40,6 +41,10 @@ class CteExtractor(BaseExtractor):\n holder |= self.delegate_to(\n CreateInsertExtractor, segment, AnalyzerContext(cte=holder.cte)\n )\n+ elif segment.type == \"update_statement\":\n+ holder |= self.delegate_to(\n+ UpdateExtractor, segment, AnalyzerContext(cte=holder.cte)\n+ )\n elif segment.type == \"common_table_expression\":\n identifier = None\n segment_has_alias = any(\ndiff --git a/sqllineage/core/parser/sqlfluff/extractors/update.py b/sqllineage/core/parser/sqlfluff/extractors/update.py\nindex 64a8eae..a5c78ad 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/update.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/update.py\n@@ -1,10 +1,11 @@\n-from typing import Optional\n+from typing import Optional, Union\n \n from sqlfluff.core.parser import BaseSegment\n \n-from sqllineage.core.holders import StatementLineageHolder\n-from sqllineage.core.models import Table\n+from sqllineage.core.holders import SubQueryLineageHolder\n+from sqllineage.core.models import SubQuery, Table\n from sqllineage.core.parser.sqlfluff.extractors.base import BaseExtractor\n+from sqllineage.core.parser.sqlfluff.models import SqlFluffSubQuery\n from sqllineage.core.parser.sqlfluff.utils import (\n find_from_expression_element,\n find_table_identifier,\n@@ -23,19 +24,19 @@ class UpdateExtractor(BaseExtractor):\n \n def extract(\n self, statement: BaseSegment, context: AnalyzerContext\n- ) -> StatementLineageHolder:\n- holder = StatementLineageHolder()\n+ ) -> SubQueryLineageHolder:\n+ holder = self._init_holder(context)\n tgt_flag = False\n for segment in list_child_segments(statement):\n if segment.type == \"from_expression\":\n- # UPDATE with JOIN\n+ # UPDATE with JOIN, mysql only syntax\n if table := self.find_table_from_from_expression_or_join_clause(\n- segment\n+ segment, holder\n ):\n holder.add_write(table)\n for join_clause in list_join_clause(statement):\n if table := self.find_table_from_from_expression_or_join_clause(\n- join_clause\n+ join_clause, holder\n ):\n holder.add_read(table)\n \n@@ -48,13 +49,25 @@ class UpdateExtractor(BaseExtractor):\n holder.add_write(table)\n tgt_flag = False\n \n+ if segment.type == \"from_clause\":\n+ # UPDATE FROM, ansi syntax\n+ if from_expression := segment.get_child(\"from_expression\"):\n+ if table := self.find_table_from_from_expression_or_join_clause(\n+ from_expression, holder\n+ ):\n+ holder.add_read(table)\n+\n return holder\n \n def find_table_from_from_expression_or_join_clause(\n- self, segment\n- ) -> Optional[Table]:\n- table = None\n+ self, segment, holder\n+ ) -> Optional[Union[Table, SubQuery]]:\n+ table: Optional[Union[Table, SubQuery]] = None\n if from_expression_element := find_from_expression_element(segment):\n if table_identifier := find_table_identifier(from_expression_element):\n- table = self.find_table(table_identifier)\n+ cte_dict = {c.alias: c for c in holder.cte}\n+ if cte := cte_dict.get(table_identifier.raw):\n+ table = SqlFluffSubQuery.of(cte.query, table_identifier.raw)\n+ else:\n+ table = self.find_table(table_identifier)\n return table\n", "test_patch": "diff --git a/tests/sql/table/test_cte.py b/tests/sql/table/test_cte.py\nindex c9ab271..b9ddede 100644\n--- a/tests/sql/table/test_cte.py\n+++ b/tests/sql/table/test_cte.py\n@@ -48,7 +48,7 @@ def test_with_select_join_table_with_same_name():\n )\n \n \n-def test_with_insert():\n+def test_cte_insert():\n assert_table_lineage_equal(\n \"WITH tab1 AS (SELECT * FROM tab2) INSERT INTO tab3 SELECT * FROM tab1\",\n {\"tab2\"},\n@@ -56,7 +56,7 @@ def test_with_insert():\n )\n \n \n-def test_with_insert_in_query():\n+def test_cte_insert_cte_in_query():\n assert_table_lineage_equal(\n \"INSERT INTO tab3 WITH tab1 AS (SELECT * FROM tab2) SELECT * FROM tab1\",\n {\"tab2\"},\n@@ -64,6 +64,17 @@ def test_with_insert_in_query():\n )\n \n \n+def test_cte_update_from():\n+ assert_table_lineage_equal(\n+ \"\"\"WITH cte1 AS (SELECT col1, col2 FROM tab1)\n+UPDATE tab2\n+SET tab2.col2 = cte1.col2 FROM cte1\n+WHERE tab2.col1 = cte1.col1;\"\"\",\n+ {\"tab1\"},\n+ {\"tab2\"},\n+ )\n+\n+\n def test_cte_and_union():\n sql = \"\"\"WITH cte_1 AS (select col1 from tab1)\n SELECT col2 from tab2\ndiff --git a/tests/sql/table/test_update.py b/tests/sql/table/test_update.py\nindex ef5887a..7736e7e 100644\n--- a/tests/sql/table/test_update.py\n+++ b/tests/sql/table/test_update.py\n@@ -5,3 +5,13 @@ def test_update():\n assert_table_lineage_equal(\n \"UPDATE tab1 SET col1='val1' WHERE col2='val2'\", None, {\"tab1\"}\n )\n+\n+\n+def test_update_from():\n+ assert_table_lineage_equal(\n+ \"\"\"UPDATE tab2\n+SET tab2.col2 = tab1.col2 FROM tab1\n+WHERE tab2.col1 = tab1.col1\"\"\",\n+ {\"tab1\"},\n+ {\"tab2\"},\n+ )\n", "FAIL_TO_PASS": ["tests/sql/table/test_cte.py::test_cte_update_from", "tests/sql/table/test_update.py::test_update_from"]}], "all_FAIL_TO_PASS": ["tests/sql/table/test_cte.py::test_cte_within_subquery", "tests/sql/table/test_cte.py::test_cte_within_cte", "tests/sql/table/test_cte.py::test_cte_update_from", "tests/sql/table/test_update.py::test_update_from"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "matthewwithanm__python-markdownify-150_x3", "level": 3, "source": "swerebench", "repo": "matthewwithanm/python-markdownify", "image": "swerebench/sweb.eval.x86_64.matthewwithanm_1776_python-markdownify-150:latest", "base_commit": "964d89fa8ace65181402f69ca2482d83b84600f8", "num_bugs": 3, "bugs": [{"instance_id": "matthewwithanm__python-markdownify-150", "base_commit": "964d89fa8ace65181402f69ca2482d83b84600f8", "gold_patch": "diff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex cd66a39..a37f870 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -7,7 +7,8 @@ import six\n convert_heading_re = re.compile(r'convert_h(\\d+)')\n line_beginning_re = re.compile(r'^', re.MULTILINE)\n whitespace_re = re.compile(r'[\\t ]+')\n-all_whitespace_re = re.compile(r'[\\s]+')\n+all_whitespace_re = re.compile(r'[\\t \\r\\n]+')\n+newline_whitespace_re = re.compile(r'[\\t \\r\\n]*[\\r\\n][\\t \\r\\n]*')\n html_heading_re = re.compile(r'h[1-6]')\n \n \n@@ -148,7 +149,13 @@ class MarkdownConverter(object):\n elif isinstance(el, NavigableString):\n text += self.process_text(el)\n else:\n- text += self.process_tag(el, convert_children_as_inline)\n+ text_strip = text.rstrip('\\n')\n+ newlines_left = len(text) - len(text_strip)\n+ next_text = self.process_tag(el, convert_children_as_inline)\n+ next_text_strip = next_text.lstrip('\\n')\n+ newlines_right = len(next_text) - len(next_text_strip)\n+ newlines = '\\n' * max(newlines_left, newlines_right)\n+ text = text_strip + newlines + next_text_strip\n \n if not children_only:\n convert_fn = getattr(self, 'convert_%s' % node.name, None)\n@@ -162,7 +169,11 @@ class MarkdownConverter(object):\n \n # normalize whitespace if we're not inside a preformatted element\n if not el.find_parent('pre'):\n- text = whitespace_re.sub(' ', text)\n+ if self.options['wrap']:\n+ text = all_whitespace_re.sub(' ', text)\n+ else:\n+ text = newline_whitespace_re.sub('\\n', text)\n+ text = whitespace_re.sub(' ', text)\n \n # escape special characters if we're not inside a preformatted or code element\n if not el.find_parent(['pre', 'code', 'kbd', 'samp']):\n@@ -221,7 +232,7 @@ class MarkdownConverter(object):\n \n def underline(self, text, pad_char):\n text = (text or '').rstrip()\n- return '%s\\n%s\\n\\n' % (text, pad_char * len(text)) if text else ''\n+ return '\\n\\n%s\\n%s\\n\\n' % (text, pad_char * len(text)) if text else ''\n \n def convert_a(self, el, text, convert_as_inline):\n prefix, suffix, text = chomp(text)\n@@ -280,10 +291,11 @@ class MarkdownConverter(object):\n if style == UNDERLINED and n <= 2:\n line = '=' if n == 1 else '-'\n return self.underline(text, line)\n+ text = all_whitespace_re.sub(' ', text)\n hashes = '#' * n\n if style == ATX_CLOSED:\n- return '%s %s %s\\n\\n' % (hashes, text, hashes)\n- return '%s %s\\n\\n' % (hashes, text)\n+ return '\\n%s %s %s\\n\\n' % (hashes, text, hashes)\n+ return '\\n%s %s\\n\\n' % (hashes, text)\n \n def convert_hr(self, el, text, convert_as_inline):\n return '\\n\\n---\\n\\n'\n@@ -318,7 +330,7 @@ class MarkdownConverter(object):\n if nested:\n # remove trailing newline if nested\n return '\\n' + self.indent(text, 1).rstrip()\n- return text + ('\\n' if before_paragraph else '')\n+ return '\\n\\n' + text + ('\\n' if before_paragraph else '')\n \n convert_ul = convert_list\n convert_ol = convert_list\n@@ -345,11 +357,22 @@ class MarkdownConverter(object):\n if convert_as_inline:\n return text\n if self.options['wrap']:\n- text = fill(text,\n- width=self.options['wrap_width'],\n- break_long_words=False,\n- break_on_hyphens=False)\n- return '%s\\n\\n' % text if text else ''\n+ # Preserve newlines (and preceding whitespace) resulting\n+ # from
    tags. Newlines in the input have already been\n+ # replaced by spaces.\n+ lines = text.split('\\n')\n+ new_lines = []\n+ for line in lines:\n+ line = line.lstrip()\n+ line_no_trailing = line.rstrip()\n+ trailing = line[len(line_no_trailing):]\n+ line = fill(line,\n+ width=self.options['wrap_width'],\n+ break_long_words=False,\n+ break_on_hyphens=False)\n+ new_lines.append(line + trailing)\n+ text = '\\n'.join(new_lines)\n+ return '\\n\\n%s\\n\\n' % text if text else ''\n \n def convert_pre(self, el, text, convert_as_inline):\n if not text:\n", "test_patch": "diff --git a/tests/test_advanced.py b/tests/test_advanced.py\nindex 14bf3cd..a3a5fda 100644\n--- a/tests/test_advanced.py\n+++ b/tests/test_advanced.py\n@@ -14,7 +14,7 @@ def test_chomp():\n \n def test_nested():\n text = md('

    This is an example link.

    ')\n- assert text == 'This is an [example link](http://example.com/).\\n\\n'\n+ assert text == '\\n\\nThis is an [example link](http://example.com/).\\n\\n'\n \n \n def test_ignore_comments():\ndiff --git a/tests/test_basic.py b/tests/test_basic.py\nindex bf25ee0..66f8b6c 100644\n--- a/tests/test_basic.py\n+++ b/tests/test_basic.py\n@@ -11,3 +11,4 @@ def test_soup():\n \n def test_whitespace():\n assert md(' a b \\t\\t c ') == ' a b c '\n+ assert md(' a b \\n\\n c ') == ' a b\\nc '\ndiff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex a35b982..9c1edc3 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -1,4 +1,4 @@\n-from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCORE\n+from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, SPACES, UNDERSCORE\n \n \n def inline_tests(tag, markup):\n@@ -112,36 +112,39 @@ def test_em():\n \n \n def test_header_with_space():\n- assert md('

    \\n\\nHello

    ') == '### Hello\\n\\n'\n- assert md('

    \\n\\nHello

    ') == '#### Hello\\n\\n'\n- assert md('
    \\n\\nHello
    ') == '##### Hello\\n\\n'\n- assert md('
    \\n\\nHello\\n\\n
    ') == '##### Hello\\n\\n'\n- assert md('
    \\n\\nHello \\n\\n
    ') == '##### Hello\\n\\n'\n+ assert md('

    \\n\\nHello

    ') == '\\n### Hello\\n\\n'\n+ assert md('

    Hello\\n\\n\\nWorld

    ') == '\\n### Hello World\\n\\n'\n+ assert md('

    \\n\\nHello

    ') == '\\n#### Hello\\n\\n'\n+ assert md('
    \\n\\nHello
    ') == '\\n##### Hello\\n\\n'\n+ assert md('
    \\n\\nHello\\n\\n
    ') == '\\n##### Hello\\n\\n'\n+ assert md('
    \\n\\nHello \\n\\n
    ') == '\\n##### Hello\\n\\n'\n \n \n def test_h1():\n- assert md('

    Hello

    ') == 'Hello\\n=====\\n\\n'\n+ assert md('

    Hello

    ') == '\\n\\nHello\\n=====\\n\\n'\n \n \n def test_h2():\n- assert md('

    Hello

    ') == 'Hello\\n-----\\n\\n'\n+ assert md('

    Hello

    ') == '\\n\\nHello\\n-----\\n\\n'\n \n \n def test_hn():\n- assert md('

    Hello

    ') == '### Hello\\n\\n'\n- assert md('

    Hello

    ') == '#### Hello\\n\\n'\n- assert md('
    Hello
    ') == '##### Hello\\n\\n'\n- assert md('
    Hello
    ') == '###### Hello\\n\\n'\n+ assert md('

    Hello

    ') == '\\n### Hello\\n\\n'\n+ assert md('

    Hello

    ') == '\\n#### Hello\\n\\n'\n+ assert md('
    Hello
    ') == '\\n##### Hello\\n\\n'\n+ assert md('
    Hello
    ') == '\\n###### Hello\\n\\n'\n \n \n def test_hn_chained():\n- assert md('

    First

    \\n

    Second

    \\n

    Third

    ', heading_style=ATX) == '# First\\n\\n\\n## Second\\n\\n\\n### Third\\n\\n'\n- assert md('X

    First

    ', heading_style=ATX) == 'X# First\\n\\n'\n+ assert md('

    First

    \\n

    Second

    \\n

    Third

    ', heading_style=ATX) == '\\n# First\\n\\n\\n## Second\\n\\n\\n### Third\\n\\n'\n+ assert md('X

    First

    ', heading_style=ATX) == 'X\\n# First\\n\\n'\n+ assert md('X

    First

    ', heading_style=ATX_CLOSED) == 'X\\n# First #\\n\\n'\n+ assert md('X

    First

    ') == 'X\\n\\nFirst\\n=====\\n\\n'\n \n \n def test_hn_nested_tag_heading_style():\n- assert md('

    A

    P

    C

    ', heading_style=ATX_CLOSED) == '# A P C #\\n\\n'\n- assert md('

    A

    P

    C

    ', heading_style=ATX) == '# A P C\\n\\n'\n+ assert md('

    A

    P

    C

    ', heading_style=ATX_CLOSED) == '\\n# A P C #\\n\\n'\n+ assert md('

    A

    P

    C

    ', heading_style=ATX) == '\\n# A P C\\n\\n'\n \n \n def test_hn_nested_simple_tag():\n@@ -157,12 +160,12 @@ def test_hn_nested_simple_tag():\n ]\n \n for tag, markdown in tag_to_markdown:\n- assert md('

    A <' + tag + '>' + tag + ' B

    ') == '### A ' + markdown + ' B\\n\\n'\n+ assert md('

    A <' + tag + '>' + tag + ' B

    ') == '\\n### A ' + markdown + ' B\\n\\n'\n \n- assert md('

    A
    B

    ', heading_style=ATX) == '### A B\\n\\n'\n+ assert md('

    A
    B

    ', heading_style=ATX) == '\\n### A B\\n\\n'\n \n # Nested lists not supported\n- # assert md('

    A
    • li1
    • l2

    ', heading_style=ATX) == '### A li1 li2 B\\n\\n'\n+ # assert md('

    A
    • li1
    • l2

    ', heading_style=ATX) == '\\n### A li1 li2 B\\n\\n'\n \n \n def test_hn_nested_img():\n@@ -172,18 +175,18 @@ def test_hn_nested_img():\n (\"alt='Alt Text' title='Optional title'\", \"Alt Text\", \" \\\"Optional title\\\"\"),\n ]\n for image_attributes, markdown, title in image_attributes_to_markdown:\n- assert md('

    A B

    ') == '### A ' + markdown + ' B\\n\\n'\n- assert md('

    A B

    ', keep_inline_images_in=['h3']) == '### A ![' + markdown + '](/path/to/img.jpg' + title + ') B\\n\\n'\n+ assert md('

    A B

    ') == '\\n### A' + (' ' + markdown + ' ' if markdown else ' ') + 'B\\n\\n'\n+ assert md('

    A B

    ', keep_inline_images_in=['h3']) == '\\n### A ![' + markdown + '](/path/to/img.jpg' + title + ') B\\n\\n'\n \n \n def test_hn_atx_headings():\n- assert md('

    Hello

    ', heading_style=ATX) == '# Hello\\n\\n'\n- assert md('

    Hello

    ', heading_style=ATX) == '## Hello\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX) == '\\n# Hello\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX) == '\\n## Hello\\n\\n'\n \n \n def test_hn_atx_closed_headings():\n- assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '# Hello #\\n\\n'\n- assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '## Hello ##\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '\\n# Hello #\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '\\n## Hello ##\\n\\n'\n \n \n def test_head():\n@@ -193,7 +196,7 @@ def test_head():\n def test_hr():\n assert md('Hello
    World') == 'Hello\\n\\n---\\n\\nWorld'\n assert md('Hello
    World') == 'Hello\\n\\n---\\n\\nWorld'\n- assert md('

    Hello

    \\n
    \\n

    World

    ') == 'Hello\\n\\n\\n\\n\\n---\\n\\n\\nWorld\\n\\n'\n+ assert md('

    Hello

    \\n
    \\n

    World

    ') == '\\n\\nHello\\n\\n\\n---\\n\\n\\nWorld\\n\\n'\n \n \n def test_i():\n@@ -210,12 +213,23 @@ def test_kbd():\n \n \n def test_p():\n- assert md('

    hello

    ') == 'hello\\n\\n'\n- assert md('

    123456789 123456789

    ') == '123456789 123456789\\n\\n'\n- assert md('

    123456789 123456789

    ', wrap=True, wrap_width=10) == '123456789\\n123456789\\n\\n'\n- assert md('

    Some long link

    ', wrap=True, wrap_width=10) == '[Some long\\nlink](https://example.com)\\n\\n'\n- assert md('

    12345
    67890

    ', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345\\\\\\n67890\\n\\n'\n- assert md('

    12345678901
    12345

    ', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345678901\\\\\\n12345\\n\\n'\n+ assert md('

    hello

    ') == '\\n\\nhello\\n\\n'\n+ assert md('

    123456789 123456789

    ') == '\\n\\n123456789 123456789\\n\\n'\n+ assert md('

    123456789\\n\\n\\n123456789

    ') == '\\n\\n123456789\\n123456789\\n\\n'\n+ assert md('

    123456789\\n\\n\\n123456789

    ', wrap=True, wrap_width=80) == '\\n\\n123456789 123456789\\n\\n'\n+ assert md('

    123456789 123456789

    ', wrap=True, wrap_width=10) == '\\n\\n123456789\\n123456789\\n\\n'\n+ assert md('

    Some long link

    ', wrap=True, wrap_width=10) == '\\n\\n[Some long\\nlink](https://example.com)\\n\\n'\n+ assert md('

    12345
    67890

    ', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '\\n\\n12345\\\\\\n67890\\n\\n'\n+ assert md('

    12345
    67890

    ', wrap=True, wrap_width=50, newline_style=BACKSLASH) == '\\n\\n12345\\\\\\n67890\\n\\n'\n+ assert md('

    12345
    67890

    ', wrap=True, wrap_width=10, newline_style=SPACES) == '\\n\\n12345 \\n67890\\n\\n'\n+ assert md('

    12345
    67890

    ', wrap=True, wrap_width=50, newline_style=SPACES) == '\\n\\n12345 \\n67890\\n\\n'\n+ assert md('

    12345678901
    12345

    ', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '\\n\\n12345678901\\\\\\n12345\\n\\n'\n+ assert md('

    12345678901
    12345

    ', wrap=True, wrap_width=50, newline_style=BACKSLASH) == '\\n\\n12345678901\\\\\\n12345\\n\\n'\n+ assert md('

    12345678901
    12345

    ', wrap=True, wrap_width=10, newline_style=SPACES) == '\\n\\n12345678901 \\n12345\\n\\n'\n+ assert md('

    12345678901
    12345

    ', wrap=True, wrap_width=50, newline_style=SPACES) == '\\n\\n12345678901 \\n12345\\n\\n'\n+ assert md('

    1234 5678 9012
    67890

    ', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '\\n\\n1234 5678\\n9012\\\\\\n67890\\n\\n'\n+ assert md('

    1234 5678 9012
    67890

    ', wrap=True, wrap_width=10, newline_style=SPACES) == '\\n\\n1234 5678\\n9012 \\n67890\\n\\n'\n+ assert md('First

    Second

    Third

    Fourth') == 'First\\n\\nSecond\\n\\nThird\\n\\nFourth'\n \n \n def test_pre():\ndiff --git a/tests/test_lists.py b/tests/test_lists.py\nindex 35eee13..ecc1a65 100644\n--- a/tests/test_lists.py\n+++ b/tests/test_lists.py\n@@ -41,19 +41,20 @@ nested_ols = \"\"\"\n \n \n def test_ol():\n- assert md('
    1. a
    2. b
    ') == '1. a\\n2. b\\n'\n- assert md('
    1. a
    2. b
    ') == '3. a\\n4. b\\n'\n- assert md('
    1. a
    2. b
    ') == '1. a\\n2. b\\n'\n- assert md('
    1. a
    2. b
    ') == '1. a\\n2. b\\n'\n- assert md('
    1. a
    2. b
    ') == '1. a\\n2. b\\n'\n+ assert md('
    1. a
    2. b
    ') == '\\n\\n1. a\\n2. b\\n'\n+ assert md('
    1. a
    2. b
    ') == '\\n\\n3. a\\n4. b\\n'\n+ assert md('foo
    1. a
    2. b
    bar') == 'foo\\n\\n3. a\\n4. b\\n\\nbar'\n+ assert md('
    1. a
    2. b
    ') == '\\n\\n1. a\\n2. b\\n'\n+ assert md('
    1. a
    2. b
    ') == '\\n\\n1. a\\n2. b\\n'\n+ assert md('
    1. a
    2. b
    ') == '\\n\\n1. a\\n2. b\\n'\n \n \n def test_nested_ols():\n- assert md(nested_ols) == '\\n1. 1\\n\\t1. a\\n\\t\\t1. I\\n\\t\\t2. II\\n\\t\\t3. III\\n\\t2. b\\n\\t3. c\\n2. 2\\n3. 3\\n'\n+ assert md(nested_ols) == '\\n\\n1. 1\\n\\t1. a\\n\\t\\t1. I\\n\\t\\t2. II\\n\\t\\t3. III\\n\\t2. b\\n\\t3. c\\n2. 2\\n3. 3\\n'\n \n \n def test_ul():\n- assert md('
    • a
    • b
    ') == '* a\\n* b\\n'\n+ assert md('
    • a
    • b
    ') == '\\n\\n* a\\n* b\\n'\n assert md(\"\"\"
      \n
    • \n a\n@@ -61,11 +62,12 @@ def test_ul():\n
    • b
    • \n
    • c\n
    • \n-
    \"\"\") == '* a\\n* b\\n* c\\n'\n+ \"\"\") == '\\n\\n* a\\n* b\\n* c\\n'\n \n \n def test_inline_ul():\n- assert md('

    foo

    • a
    • b

    bar

    ') == 'foo\\n\\n* a\\n* b\\n\\nbar\\n\\n'\n+ assert md('

    foo

    • a
    • b

    bar

    ') == '\\n\\nfoo\\n\\n* a\\n* b\\n\\nbar\\n\\n'\n+ assert md('foo
    • bar
    baz') == 'foo\\n\\n* bar\\n\\nbaz'\n \n \n def test_nested_uls():\n@@ -73,12 +75,12 @@ def test_nested_uls():\n Nested ULs should alternate bullet characters.\n \n \"\"\"\n- assert md(nested_uls) == '\\n* 1\\n\\t+ a\\n\\t\\t- I\\n\\t\\t- II\\n\\t\\t- III\\n\\t+ b\\n\\t+ c\\n* 2\\n* 3\\n'\n+ assert md(nested_uls) == '\\n\\n* 1\\n\\t+ a\\n\\t\\t- I\\n\\t\\t- II\\n\\t\\t- III\\n\\t+ b\\n\\t+ c\\n* 2\\n* 3\\n'\n \n \n def test_bullets():\n- assert md(nested_uls, bullets='-') == '\\n- 1\\n\\t- a\\n\\t\\t- I\\n\\t\\t- II\\n\\t\\t- III\\n\\t- b\\n\\t- c\\n- 2\\n- 3\\n'\n+ assert md(nested_uls, bullets='-') == '\\n\\n- 1\\n\\t- a\\n\\t\\t- I\\n\\t\\t- II\\n\\t\\t- III\\n\\t- b\\n\\t- c\\n- 2\\n- 3\\n'\n \n \n def test_li_text():\n- assert md('
    • foo bar
    • foo bar
    • foo bar space.
    ') == '* foo [bar](#)\\n* foo bar\\n* foo **bar** *space*.\\n'\n+ assert md('
    • foo bar
    • foo bar
    • foo bar space.
    ') == '\\n\\n* foo [bar](#)\\n* foo bar\\n* foo **bar** *space*.\\n'\ndiff --git a/tests/test_tables.py b/tests/test_tables.py\nindex 594e5bf..fc6eee6 100644\n--- a/tests/test_tables.py\n+++ b/tests/test_tables.py\n@@ -242,7 +242,7 @@ def test_table():\n assert md(table) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_with_html_content) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| **Jill** | *Smith* | [50](#) |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_with_paragraphs) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n- assert md(table_with_linebreaks) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith Jackson | 50 |\\n| Eve | Jackson Smith | 94 |\\n\\n'\n+ assert md(table_with_linebreaks) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith Jackson | 50 |\\n| Eve | Jackson Smith | 94 |\\n\\n'\n assert md(table_with_header_column) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_head_body) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_head_body_missing_head) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n", "FAIL_TO_PASS": ["tests/test_advanced.py::test_nested", "tests/test_basic.py::test_whitespace", "tests/test_conversions.py::test_header_with_space", "tests/test_conversions.py::test_h1", "tests/test_conversions.py::test_h2", "tests/test_conversions.py::test_hn", "tests/test_conversions.py::test_hn_chained", "tests/test_conversions.py::test_hn_nested_tag_heading_style", "tests/test_conversions.py::test_hn_nested_simple_tag", "tests/test_conversions.py::test_hn_nested_img", "tests/test_conversions.py::test_hn_atx_headings", "tests/test_conversions.py::test_hn_atx_closed_headings", "tests/test_conversions.py::test_hr", "tests/test_conversions.py::test_p", "tests/test_lists.py::test_ol", "tests/test_lists.py::test_nested_ols", "tests/test_lists.py::test_ul", "tests/test_lists.py::test_inline_ul", "tests/test_lists.py::test_nested_uls", "tests/test_lists.py::test_bullets", "tests/test_lists.py::test_li_text", "tests/test_tables.py::test_table"]}, {"instance_id": "matthewwithanm__python-markdownify-165", "base_commit": "6258f5c38b97ab443b4ddf03e6676ce29b392d06", "gold_patch": "diff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex 3272ce5..0fbb7a5 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -264,6 +264,8 @@ class MarkdownConverter(object):\n return '\\n\\n%s\\n%s\\n\\n' % (text, pad_char * len(text)) if text else ''\n \n def convert_a(self, el, text, convert_as_inline):\n+ if el.find_parent(['pre', 'code', 'kbd', 'samp']):\n+ return text\n prefix, suffix, text = chomp(text)\n if not text:\n return ''\n", "test_patch": "diff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex 2283c29..55702e3 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -39,6 +39,11 @@ def test_a_no_autolinks():\n assert md('https://google.com', autolinks=False) == '[https://google.com](https://google.com)'\n \n \n+def test_a_in_code():\n+ assert md('Google') == '`Google`'\n+ assert md('
    Google
    ') == '\\n```\\nGoogle\\n```\\n'\n+\n+\n def test_b():\n assert md('Hello') == '**Hello**'\n \n", "FAIL_TO_PASS": ["tests/test_conversions.py::test_a_in_code"]}, {"instance_id": "matthewwithanm__python-markdownify-167", "base_commit": "6258f5c38b97ab443b4ddf03e6676ce29b392d06", "gold_patch": "diff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex 3272ce5..cadd2bd 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -442,7 +442,7 @@ class MarkdownConverter(object):\n return '\\n\\n' + text + '\\n'\n \n def convert_caption(self, el, text, convert_as_inline):\n- return text + '\\n'\n+ return text + '\\n\\n'\n \n def convert_figcaption(self, el, text, convert_as_inline):\n return '\\n\\n' + text + '\\n\\n'\n", "test_patch": "diff --git a/tests/test_tables.py b/tests/test_tables.py\nindex fc6eee6..dcf9ad7 100644\n--- a/tests/test_tables.py\n+++ b/tests/test_tables.py\n@@ -249,6 +249,6 @@ def test_table():\n assert md(table_missing_text) == '\\n\\n| | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_missing_head) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_body) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n- assert md(table_with_caption) == 'TEXT\\n\\nCaption\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n\\n'\n+ assert md(table_with_caption) == 'TEXT\\n\\nCaption\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n\\n'\n assert md(table_with_colspan) == '\\n\\n| Name | | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_with_undefined_colspan) == '\\n\\n| Name | Age |\\n| --- | --- |\\n| Jill | Smith |\\n\\n'\n", "FAIL_TO_PASS": ["tests/test_tables.py::test_table"]}], "all_FAIL_TO_PASS": ["tests/test_advanced.py::test_nested", "tests/test_basic.py::test_whitespace", "tests/test_conversions.py::test_header_with_space", "tests/test_conversions.py::test_h1", "tests/test_conversions.py::test_h2", "tests/test_conversions.py::test_hn", "tests/test_conversions.py::test_hn_chained", "tests/test_conversions.py::test_hn_nested_tag_heading_style", "tests/test_conversions.py::test_hn_nested_simple_tag", "tests/test_conversions.py::test_hn_nested_img", "tests/test_conversions.py::test_hn_atx_headings", "tests/test_conversions.py::test_hn_atx_closed_headings", "tests/test_conversions.py::test_hr", "tests/test_conversions.py::test_p", "tests/test_lists.py::test_ol", "tests/test_lists.py::test_nested_ols", "tests/test_lists.py::test_ul", "tests/test_lists.py::test_inline_ul", "tests/test_lists.py::test_nested_uls", "tests/test_lists.py::test_bullets", "tests/test_lists.py::test_li_text", "tests/test_tables.py::test_table", "tests/test_conversions.py::test_a_in_code", "tests/test_tables.py::test_table"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3935_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3935:latest", "base_commit": "f9a1efd42361767bb2f867f827048c3a059b3188", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3935", "base_commit": "f9a1efd42361767bb2f867f827048c3a059b3188", "gold_patch": "diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py\nindex 3acabb94..2562422c 100644\n--- a/sqlglot/dialects/oracle.py\n+++ b/sqlglot/dialects/oracle.py\n@@ -90,7 +90,6 @@ class Oracle(Dialect):\n \"ORDER SIBLINGS BY\": TokenType.ORDER_SIBLINGS_BY,\n \"SAMPLE\": TokenType.TABLE_SAMPLE,\n \"START\": TokenType.BEGIN,\n- \"SYSDATE\": TokenType.CURRENT_TIMESTAMP,\n \"TOP\": TokenType.TOP,\n \"VARCHAR2\": TokenType.VARCHAR,\n }\n@@ -109,6 +108,11 @@ class Oracle(Dialect):\n }\n FUNCTIONS.pop(\"NVL\")\n \n+ NO_PAREN_FUNCTION_PARSERS = {\n+ **parser.Parser.NO_PAREN_FUNCTION_PARSERS,\n+ \"SYSDATE\": lambda self: self.expression(exp.CurrentTimestamp, sysdate=True),\n+ }\n+\n FUNCTION_PARSERS: t.Dict[str, t.Callable] = {\n **parser.Parser.FUNCTION_PARSERS,\n \"JSON_ARRAY\": lambda self: self._parse_json_array(\n@@ -275,6 +279,9 @@ class Oracle(Dialect):\n }\n \n def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:\n+ if expression.args.get(\"sysdate\"):\n+ return \"SYSDATE\"\n+\n this = expression.this\n return self.func(\"CURRENT_TIMESTAMP\", this) if this else \"CURRENT_TIMESTAMP\"\n \ndiff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py\nindex 0b12df12..694af28a 100644\n--- a/sqlglot/dialects/redshift.py\n+++ b/sqlglot/dialects/redshift.py\n@@ -80,7 +80,7 @@ class Redshift(Postgres):\n NO_PAREN_FUNCTION_PARSERS = {\n **Postgres.Parser.NO_PAREN_FUNCTION_PARSERS,\n \"APPROXIMATE\": lambda self: self._parse_approximate_count(),\n- \"SYSDATE\": lambda self: self.expression(exp.CurrentTimestamp, transaction=True),\n+ \"SYSDATE\": lambda self: self.expression(exp.CurrentTimestamp, sysdate=True),\n }\n \n SUPPORTS_IMPLICIT_UNNEST = True\n@@ -180,7 +180,7 @@ class Redshift(Postgres):\n exp.ApproxDistinct: lambda self,\n e: f\"APPROXIMATE COUNT(DISTINCT {self.sql(e, 'this')})\",\n exp.CurrentTimestamp: lambda self, e: (\n- \"SYSDATE\" if e.args.get(\"transaction\") else \"GETDATE()\"\n+ \"SYSDATE\" if e.args.get(\"sysdate\") else \"GETDATE()\"\n ),\n exp.DateAdd: date_delta_sql(\"DATEADD\"),\n exp.DateDiff: date_delta_sql(\"DATEDIFF\"),\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 404162d4..8a720486 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5133,7 +5133,7 @@ class CurrentTime(Func):\n \n \n class CurrentTimestamp(Func):\n- arg_types = {\"this\": False, \"transaction\": False}\n+ arg_types = {\"this\": False, \"sysdate\": False}\n \n \n class CurrentUser(Func):\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 7f743d39..79b8a024 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -15,6 +15,7 @@ class TestOracle(Validator):\n )\n self.parse_one(\"ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol\").assert_is(exp.Alter)\n \n+ self.validate_identity(\"SYSDATE\")\n self.validate_identity(\"CREATE GLOBAL TEMPORARY TABLE t AS SELECT * FROM orders\")\n self.validate_identity(\"CREATE PRIVATE TEMPORARY TABLE t AS SELECT * FROM orders\")\n self.validate_identity(\"REGEXP_REPLACE('source', 'search')\")\n@@ -72,10 +73,6 @@ class TestOracle(Validator):\n \"SELECT JSON_OBJECTAGG(KEY department_name VALUE department_id) FROM dep WHERE id <= 30\",\n \"SELECT JSON_OBJECTAGG(department_name: department_id) FROM dep WHERE id <= 30\",\n )\n- self.validate_identity(\n- \"SYSDATE\",\n- \"CURRENT_TIMESTAMP\",\n- )\n self.validate_identity(\n \"SELECT last_name, department_id, salary, MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) \"\n 'OVER (PARTITION BY department_id) AS \"Worst\", MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) '\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-3937", "base_commit": "f4c34d37c5773c37a13437c7e0e7eb27b4e98877", "gold_patch": "diff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex acd4c096..67400514 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -2909,11 +2909,13 @@ class Generator(metaclass=_Generator):\n \n def pivotalias_sql(self, expression: exp.PivotAlias) -> str:\n alias = expression.args[\"alias\"]\n+\n identifier_alias = isinstance(alias, exp.Identifier)\n+ literal_alias = isinstance(alias, exp.Literal)\n \n if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n alias.replace(exp.Literal.string(alias.output_name))\n- elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n+ elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n alias.replace(exp.to_identifier(alias.output_name))\n \n return self.alias_sql(expression)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 6171580c..fb78d1ab 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3776,8 +3776,10 @@ class Parser(metaclass=_Parser):\n this = self._parse_select_or_expression()\n \n self._match(TokenType.ALIAS)\n- alias = self._parse_field()\n+ alias = self._parse_bitwise()\n if alias:\n+ if isinstance(alias, exp.Column) and not alias.db:\n+ alias = alias.this\n return self.expression(exp.PivotAlias, this=this, alias=alias)\n \n return this\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 79b8a024..4a570721 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -44,6 +44,9 @@ class TestOracle(Validator):\n self.validate_identity(\"SELECT COUNT(*) * 10 FROM orders SAMPLE (10) SEED (1)\")\n self.validate_identity(\"SELECT * FROM V$SESSION\")\n self.validate_identity(\"SELECT TO_DATE('January 15, 1989, 11:00 A.M.')\")\n+ self.validate_identity(\n+ \"SELECT * FROM test UNPIVOT INCLUDE NULLS (value FOR Description IN (col AS 'PREFIX ' || CHR(38) || ' SUFFIX'))\"\n+ )\n self.validate_identity(\n \"SELECT last_name, employee_id, manager_id, LEVEL FROM employees START WITH employee_id = 100 CONNECT BY PRIOR employee_id = manager_id ORDER SIBLINGS BY last_name\"\n )\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-3954", "base_commit": "6a5f6199f6da0053fa4564e71a17e3b9f91f0496", "gold_patch": "diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py\nindex ff5dcb64..53fad5ae 100644\n--- a/sqlglot/dialects/oracle.py\n+++ b/sqlglot/dialects/oracle.py\n@@ -107,8 +107,10 @@ class Oracle(Dialect):\n \"TO_CHAR\": _build_timetostr_or_tochar,\n \"TO_TIMESTAMP\": build_formatted_time(exp.StrToTime, \"oracle\"),\n \"TO_DATE\": build_formatted_time(exp.StrToDate, \"oracle\"),\n+ \"NVL\": lambda args: exp.Coalesce(\n+ this=seq_get(args, 0), expressions=args[1:], is_nvl=True\n+ ),\n }\n- FUNCTIONS.pop(\"NVL\")\n \n NO_PAREN_FUNCTION_PARSERS = {\n **parser.Parser.NO_PAREN_FUNCTION_PARSERS,\n@@ -313,3 +315,7 @@ class Oracle(Dialect):\n value = f\" CONSTRAINT {value}\" if value else \"\"\n \n return f\"{option}{value}\"\n+\n+ def coalesce_sql(self, expression: exp.Coalesce) -> str:\n+ func_name = \"NVL\" if expression.args.get(\"is_nvl\") else \"COALESCE\"\n+ return rename_func(func_name)(self, expression)\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 00a54a04..faf85b0c 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5087,7 +5087,7 @@ class Ceil(Func):\n \n \n class Coalesce(Func):\n- arg_types = {\"this\": True, \"expressions\": False}\n+ arg_types = {\"this\": True, \"expressions\": False, \"is_nvl\": False}\n is_var_len_args = True\n _sql_names = [\"COALESCE\", \"IFNULL\", \"NVL\"]\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 9a099104..cdc631ee 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1302,7 +1302,7 @@ class Generator(metaclass=_Generator):\n def fetch_sql(self, expression: exp.Fetch) -> str:\n direction = expression.args.get(\"direction\")\n direction = f\" {direction}\" if direction else \"\"\n- count = expression.args.get(\"count\")\n+ count = self.sql(expression, \"count\")\n count = f\" {count}\" if count else \"\"\n if expression.args.get(\"percent\"):\n count = f\"{count} PERCENT\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex d20c2406..55552840 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -222,6 +222,7 @@ class Parser(metaclass=_Parser):\n \"UNNEST\": lambda args: exp.Unnest(expressions=ensure_list(seq_get(args, 0))),\n \"UPPER\": build_upper,\n \"VAR_MAP\": build_var_map,\n+ \"COALESCE\": lambda args: exp.Coalesce(this=seq_get(args, 0), expressions=args[1:]),\n }\n \n NO_PAREN_FUNCTIONS = {\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 594aee5c..4813a495 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -89,7 +89,6 @@ class TestOracle(Validator):\n self.validate_identity(\n \"SELECT * FROM T ORDER BY I OFFSET NVL(:variable1, 10) ROWS FETCH NEXT NVL(:variable2, 10) ROWS ONLY\",\n )\n- self.validate_identity(\"NVL(x, y)\").assert_is(exp.Anonymous)\n self.validate_identity(\n \"SELECT * FROM t SAMPLE (.25)\",\n \"SELECT * FROM t SAMPLE (0.25)\",\n@@ -253,6 +252,15 @@ class TestOracle(Validator):\n \"\"\"SELECT * FROM t ORDER BY a ASC, b ASC NULLS FIRST, c DESC NULLS LAST, d DESC\"\"\",\n )\n \n+ self.validate_all(\n+ \"NVL(NULL, 1)\",\n+ write={\n+ \"oracle\": \"NVL(NULL, 1)\",\n+ \"\": \"COALESCE(NULL, 1)\",\n+ \"clickhouse\": \"COALESCE(NULL, 1)\",\n+ },\n+ )\n+\n def test_join_marker(self):\n self.validate_identity(\"SELECT e1.x, e2.x FROM e e1, e e2 WHERE e1.y (+) = e2.y\")\n \n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_oracle.py::TestOracle::test_oracle"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "Duke-GCB__bespin-cli-15_x3", "level": 3, "source": "swerebench", "repo": "Duke-GCB/bespin-cli", "image": "swerebench/sweb.eval.x86_64.duke-gcb_1776_bespin-cli-15:latest", "base_commit": "70450d7b00c477580d6851b8aaa65433a54cf415", "num_bugs": 3, "bugs": [{"instance_id": "Duke-GCB__bespin-cli-15", "base_commit": "70450d7b00c477580d6851b8aaa65433a54cf415", "gold_patch": "diff --git a/bespin/argparser.py b/bespin/argparser.py\nindex 5fc8fa3..f97d735 100644\n--- a/bespin/argparser.py\n+++ b/bespin/argparser.py\n@@ -40,6 +40,8 @@ class ArgParser(object):\n jobs_subparser = jobs_parser.add_subparsers()\n \n list_jobs_parser = jobs_subparser.add_parser('list', description='list workflows')\n+ list_jobs_parser.add_argument('-a', '--all', action='store_true',\n+ help='show all workflow versions instead of just the most recent.')\n list_jobs_parser.set_defaults(func=self._run_list_workflows)\n \n def _create_job_parser(self, subparsers):\n@@ -79,8 +81,8 @@ class ArgParser(object):\n def _run_list_jobs(self, _):\n self.target_object.jobs_list()\n \n- def _run_list_workflows(self, _):\n- self.target_object.workflows_list()\n+ def _run_list_workflows(self, args):\n+ self.target_object.workflows_list(all_versions=args.all)\n \n def _run_init_job(self, args):\n self.target_object.init_job(args.tag, args.outfile)\ndiff --git a/bespin/commands.py b/bespin/commands.py\nindex 8f7271d..c8c1fb6 100644\n--- a/bespin/commands.py\n+++ b/bespin/commands.py\n@@ -44,6 +44,7 @@ USER_PLACEHOLDER_DICT = {\n }\n }\n \n+\n class Commands(object):\n \"\"\"\n Commands run based on command line input.\n@@ -61,12 +62,13 @@ class Commands(object):\n config = ConfigFile().read_or_create_config()\n return BespinApi(config, user_agent_str=self.user_agent_str)\n \n- def workflows_list(self):\n+ def workflows_list(self, all_versions):\n \"\"\"\n Print out a table of workflows/questionnaires\n+ :param all_versions: bool: when true show all versions otherwise show most recent\n \"\"\"\n api = self._create_api()\n- workflow_data = WorkflowDetails(api)\n+ workflow_data = WorkflowDetails(api, all_versions)\n print(Table(workflow_data.column_names, workflow_data.get_column_data()))\n \n def jobs_list(self):\n@@ -167,10 +169,11 @@ class WorkflowDetails(object):\n \"\"\"\n Creates column data based on workflows/questionnaires\n \"\"\"\n- TAG_COLUMN_NAME = \"latest version tag\"\n+ TAG_COLUMN_NAME = \"version tag\"\n \n- def __init__(self, api):\n+ def __init__(self, api, all_versions):\n self.api = api\n+ self.all_versions = all_versions\n self.column_names = [\"id\", \"name\", self.TAG_COLUMN_NAME]\n \n def get_column_data(self):\n@@ -181,10 +184,13 @@ class WorkflowDetails(object):\n data = []\n for workflow in self.api.workflows_list():\n if len(workflow['versions']):\n- latest_version = workflow['versions'][-1]\n- for questionnaire in self.api.questionnaires_list(workflow_version=latest_version):\n- workflow[self.TAG_COLUMN_NAME] = questionnaire['tag']\n- data.append(workflow)\n+ versions = workflow['versions']\n+ if not self.all_versions:\n+ versions = versions[-1:]\n+ for version in versions:\n+ for questionnaire in self.api.questionnaires_list(workflow_version=version):\n+ workflow[self.TAG_COLUMN_NAME] = questionnaire['tag']\n+ data.append(dict(workflow))\n return data\n \n \n", "test_patch": "diff --git a/bespin/test_argparse.py b/bespin/test_argparse.py\nindex 1f1cd6e..1af15be 100644\n--- a/bespin/test_argparse.py\n+++ b/bespin/test_argparse.py\n@@ -10,9 +10,17 @@ class ArgParserTestCase(TestCase):\n self.target_object = Mock()\n self.arg_parser = ArgParser(version_str='1.0', target_object=self.target_object)\n \n- def test_workflows_list(self):\n+ def test_workflows_list_current_versions(self):\n self.arg_parser.parse_and_run_commands([\"workflows\", \"list\"])\n- self.target_object.workflows_list.assert_called()\n+ self.target_object.workflows_list.assert_called_with(all_versions=False)\n+\n+ def test_workflows_list_all_versions(self):\n+ self.arg_parser.parse_and_run_commands([\"workflows\", \"list\", \"--all\"])\n+ self.target_object.workflows_list.assert_called_with(all_versions=True)\n+\n+ def test_workflows_list_all_versions_short_flag(self):\n+ self.arg_parser.parse_and_run_commands([\"workflows\", \"list\", \"-a\"])\n+ self.target_object.workflows_list.assert_called_with(all_versions=True)\n \n def test_init_job(self):\n self.arg_parser.parse_and_run_commands([\"jobs\", \"init\", \"--tag\", \"exome/v1/human\"])\ndiff --git a/bespin/test_commands.py b/bespin/test_commands.py\nindex e3756c8..5bd78a8 100644\n--- a/bespin/test_commands.py\n+++ b/bespin/test_commands.py\n@@ -18,13 +18,30 @@ class CommandsTestCase(TestCase):\n @patch('bespin.commands.WorkflowDetails')\n @patch('bespin.commands.Table')\n @patch('bespin.commands.print')\n- def test_workflows_list(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api, mock_config_file):\n+ def test_workflows_list_latest_versions(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api,\n+ mock_config_file):\n commands = Commands(self.version_str, self.user_agent_str)\n- commands.workflows_list()\n+ commands.workflows_list(all_versions=False)\n workflow_details = mock_workflow_details.return_value\n mock_table.assert_called_with(workflow_details.column_names,\n workflow_details.get_column_data.return_value)\n mock_print.assert_called_with(mock_table.return_value)\n+ mock_workflow_details.assert_called_with(mock_bespin_api.return_value, False)\n+\n+ @patch('bespin.commands.ConfigFile')\n+ @patch('bespin.commands.BespinApi')\n+ @patch('bespin.commands.WorkflowDetails')\n+ @patch('bespin.commands.Table')\n+ @patch('bespin.commands.print')\n+ def test_workflows_list_all_versions(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api,\n+ mock_config_file):\n+ commands = Commands(self.version_str, self.user_agent_str)\n+ commands.workflows_list(all_versions=True)\n+ workflow_details = mock_workflow_details.return_value\n+ mock_table.assert_called_with(workflow_details.column_names,\n+ workflow_details.get_column_data.return_value)\n+ mock_print.assert_called_with(mock_table.return_value)\n+ mock_workflow_details.assert_called_with(mock_bespin_api.return_value, True)\n \n @patch('bespin.commands.ConfigFile')\n @patch('bespin.commands.BespinApi')\n@@ -156,9 +173,9 @@ class WorkflowDetailsTestCase(TestCase):\n mock_api.questionnaires_list.return_value = [\n {'tag': 'exome/v2/human'}\n ]\n- details = WorkflowDetails(mock_api)\n+ details = WorkflowDetails(mock_api, all_versions=False)\n expected_data = [{'id': 1,\n- 'latest version tag': 'exome/v2/human',\n+ 'version tag': 'exome/v2/human',\n 'name': 'exome',\n 'versions': [1, 2]}]\n column_data = details.get_column_data()\n@@ -166,12 +183,50 @@ class WorkflowDetailsTestCase(TestCase):\n self.assertEqual(column_data, expected_data)\n mock_api.questionnaires_list.assert_called_with(workflow_version=2)\n \n- def test_ignores_workflows_without_versions(self):\n+ mock_api.questionnaires_list.reset_mock()\n+ mock_api.questionnaires_list.side_effect = [\n+ [{'tag': 'exome/v1/human'}],\n+ [{'tag': 'exome/v2/human'}]\n+ ]\n+ details = WorkflowDetails(mock_api, all_versions=True)\n+ expected_data = [\n+ {\n+ 'id': 1,\n+ 'version tag': 'exome/v1/human',\n+ 'name': 'exome',\n+ 'versions': [1, 2]\n+ },\n+ {\n+ 'id': 1,\n+ 'version tag': 'exome/v2/human',\n+ 'name': 'exome',\n+ 'versions': [1, 2]\n+ },\n+ ]\n+ column_data = details.get_column_data()\n+ self.assertEqual(len(column_data), 2)\n+ self.assertEqual(column_data, expected_data)\n+ mock_api.questionnaires_list.assert_has_calls([\n+ call(workflow_version=1),\n+ call(workflow_version=2),\n+ ])\n+\n+ def test_ignores_workflows_without_versions_when_latest(self):\n+ mock_api = Mock()\n+ mock_api.workflows_list.return_value = [\n+ {'id': 1, 'name': 'no-versions', 'versions': []},\n+ ]\n+ details = WorkflowDetails(mock_api, all_versions=False)\n+ column_data = details.get_column_data()\n+ self.assertEqual(len(column_data), 0)\n+ mock_api.questionnaires_list.assert_not_called()\n+\n+ def test_ignores_workflows_without_versions_when_all(self):\n mock_api = Mock()\n mock_api.workflows_list.return_value = [\n {'id': 1, 'name': 'no-versions', 'versions': []},\n ]\n- details = WorkflowDetails(mock_api)\n+ details = WorkflowDetails(mock_api, all_versions=True)\n column_data = details.get_column_data()\n self.assertEqual(len(column_data), 0)\n mock_api.questionnaires_list.assert_not_called()\n", "FAIL_TO_PASS": ["bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions_short_flag", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_current_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_all_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_latest_versions", "bespin/test_commands.py::WorkflowDetailsTestCase::test_get_column_data", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_all", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_latest"]}, {"instance_id": "Duke-GCB__bespin-cli-16", "base_commit": "471cd4df56c852bee11fcb4725dc6b4e9053e08c", "gold_patch": "diff --git a/bespin/api.py b/bespin/api.py\nindex 5558ccd..dad9652 100644\n--- a/bespin/api.py\n+++ b/bespin/api.py\n@@ -103,7 +103,7 @@ class BespinApi(object):\n return self._post_request('/job-file-stage-groups/', {})\n \n def dds_job_input_files_post(self, project_id, file_id, destination_path, sequence_group, sequence,\n- dds_user_credentials, stage_group_id):\n+ dds_user_credentials, stage_group_id, size):\n data = {\n \"project_id\": project_id,\n \"file_id\": file_id,\n@@ -111,7 +111,8 @@ class BespinApi(object):\n \"sequence_group\": sequence_group,\n \"sequence\": sequence,\n \"dds_user_credentials\": dds_user_credentials,\n- \"stage_group\": stage_group_id\n+ \"stage_group\": stage_group_id,\n+ \"size\": size,\n }\n return self._post_request('/dds-job-input-files/', data)\n \ndiff --git a/bespin/commands.py b/bespin/commands.py\nindex c8c1fb6..e30d252 100644\n--- a/bespin/commands.py\n+++ b/bespin/commands.py\n@@ -288,8 +288,10 @@ class JobFile(object):\n dds_project_ids = set()\n sequence = 0\n for dds_file, path in self.get_dds_files_details():\n+ file_size = dds_file.current_version['upload']['size']\n api.dds_job_input_files_post(dds_file.project_id, dds_file.id, path, 0, sequence,\n- dds_user_credential['id'], stage_group_id=stage_group['id'])\n+ dds_user_credential['id'], stage_group_id=stage_group['id'],\n+ size=file_size)\n sequence += 1\n dds_project_ids.add(dds_file.project_id)\n user_job_order_json = self.create_user_job_order_json()\ndiff --git a/bespin/dukeds.py b/bespin/dukeds.py\nindex 8753d3f..47816e2 100644\n--- a/bespin/dukeds.py\n+++ b/bespin/dukeds.py\n@@ -8,6 +8,7 @@ INVALID_DUKEDS_FILE_PATH_MSG = \"Invalid DukeDS file path ({})\"\n DUKEDS_FILE_PATH_MISSING_PREFIX = INVALID_DUKEDS_FILE_PATH_MSG.format(\"missing prefix\")\n DUKEDS_FILE_PATH_MISSING_SLASH = INVALID_DUKEDS_FILE_PATH_MSG.format(\"missing / between project and file path\")\n \n+\n class DDSFileUtil(object):\n def __init__(self):\n self.client = Client()\n", "test_patch": "diff --git a/bespin/test_api.py b/bespin/test_api.py\nindex 99ad636..30f1804 100644\n--- a/bespin/test_api.py\n+++ b/bespin/test_api.py\n@@ -145,7 +145,8 @@ class BespinApiTestCase(TestCase):\n api = BespinApi(config=self.mock_config, user_agent_str=self.mock_user_agent_str)\n dds_input_file = api.dds_job_input_files_post(project_id='123', file_id='456', destination_path='data.txt',\n sequence_group=1, sequence=2,\n- dds_user_credentials=4, stage_group_id=5)\n+ dds_user_credentials=4, stage_group_id=5,\n+ size=1000)\n \n self.assertEqual(dds_input_file, 'dds-job-input-file1')\n expected_json = {\n@@ -155,7 +156,8 @@ class BespinApiTestCase(TestCase):\n 'sequence_group': 1,\n 'sequence': 2,\n 'dds_user_credentials': 4,\n- 'stage_group': 5\n+ 'stage_group': 5,\n+ 'size': 1000,\n }\n mock_requests.post.assert_called_with('someurl/dds-job-input-files/', headers=self.expected_headers,\n json=expected_json)\ndiff --git a/bespin/test_commands.py b/bespin/test_commands.py\nindex 5bd78a8..486bf81 100644\n--- a/bespin/test_commands.py\n+++ b/bespin/test_commands.py\n@@ -336,14 +336,15 @@ class JobFileTestCase(TestCase):\n 'myint': 555\n })\n job_file.get_dds_files_details = Mock()\n- mock_file = Mock(project_id=666)\n+ mock_file = Mock(project_id=666, current_version={'upload': {'size': 4002}})\n mock_file.id = 777\n job_file.get_dds_files_details.return_value = [[mock_file, 'somepath']]\n \n job_file.create_job(mock_api)\n \n mock_api.questionnaires_list.assert_called_with(tag='sometag')\n- mock_api.dds_job_input_files_post.assert_called_with(666, 777, 'somepath', 0, 0, 111, stage_group_id=333)\n+ mock_api.dds_job_input_files_post.assert_called_with(666, 777, 'somepath', 0, 0, 111, stage_group_id=333,\n+ size=4002)\n json_payload = '{\"myfile\": {\"class\": \"File\", \"path\": \"dds_project_somepath.txt\"}, \"myint\": 555}'\n mock_api.job_answer_set_post.assert_called_with('myjob', '001', json_payload, 222, 333)\n mock_api.job_answer_set_create_job.assert_called_with(444)\n", "FAIL_TO_PASS": ["bespin/test_api.py::BespinApiTestCase::test_dds_job_input_files_post", "bespin/test_commands.py::JobFileTestCase::test_create_job"]}, {"instance_id": "Duke-GCB__bespin-cli-18", "base_commit": "3cb0cf75ca821e051ea48d4b1a990f34acedd98d", "gold_patch": "diff --git a/bespin/commands.py b/bespin/commands.py\nindex e30d252..1766e96 100644\n--- a/bespin/commands.py\n+++ b/bespin/commands.py\n@@ -3,6 +3,7 @@ from bespin.config import ConfigFile\n from bespin.api import BespinApi\n from bespin.exceptions import IncompleteJobFileException\n from bespin.dukeds import DDSFileUtil\n+from bespin.dukeds import PATH_PREFIX as DUKEDS_PATH_PREFIX\n from tabulate import tabulate\n import yaml\n import json\n@@ -411,8 +412,8 @@ class JobOrderWalker(object):\n :param path: str: format dds:///\n :return: str: file path to be used for staging data when running the workflow\n \"\"\"\n- if path.startswith(\"dds://\"):\n- return path.replace(\"dds://\", \"dds_\").replace(\"/\", \"_\").replace(\":\", \"_\")\n+ if path.startswith(DUKEDS_PATH_PREFIX):\n+ return path.replace(DUKEDS_PATH_PREFIX, \"dds_\").replace(\"/\", \"_\").replace(\":\", \"_\")\n return path\n \n \n@@ -421,8 +422,10 @@ class JobOrderPlaceholderCheck(JobOrderWalker):\n self.keys_with_placeholders = set()\n \n def on_class_value(self, top_level_key, value):\n- if value['class'] == 'File' and value['path'] in USER_PLACEHOLDER_VALUES:\n- self.keys_with_placeholders.add(top_level_key)\n+ if value['class'] == 'File':\n+ path = value.get('path')\n+ if path and path in USER_PLACEHOLDER_VALUES:\n+ self.keys_with_placeholders.add(top_level_key)\n \n def on_simple_value(self, top_level_key, value):\n if value in USER_PLACEHOLDER_VALUES:\n@@ -432,7 +435,9 @@ class JobOrderPlaceholderCheck(JobOrderWalker):\n class JobOrderFormatFiles(JobOrderWalker):\n def on_class_value(self, top_level_key, value):\n if value['class'] == 'File':\n- value['path'] = self.format_file_path(value['path'])\n+ path = value.get('path')\n+ if path:\n+ value['path'] = self.format_file_path(path)\n \n \n class JobOrderFileDetails(JobOrderWalker):\n@@ -442,6 +447,7 @@ class JobOrderFileDetails(JobOrderWalker):\n \n def on_class_value(self, top_level_key, value):\n if value['class'] == 'File':\n- path = value['path']\n- dds_file = self.dds_file_util.find_file_for_path(path)\n- self.dds_files.append((dds_file, self.format_file_path(path)))\n+ path = value.get('path')\n+ if path and path.startswith(DUKEDS_PATH_PREFIX):\n+ dds_file = self.dds_file_util.find_file_for_path(path)\n+ self.dds_files.append((dds_file, self.format_file_path(path)))\n", "test_patch": "diff --git a/bespin/test_commands.py b/bespin/test_commands.py\nindex 486bf81..c03c245 100644\n--- a/bespin/test_commands.py\n+++ b/bespin/test_commands.py\n@@ -250,6 +250,14 @@ class JobFileTestCase(TestCase):\n 'class': 'File',\n 'path': 'dds://project/somepath.txt'\n },\n+ 'my_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'my_url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n 'myint': 123,\n 'myfileary': [\n {\n@@ -298,6 +306,14 @@ class JobFileTestCase(TestCase):\n 'path': 'dds_myproject_rawData_SAAAA_R2_001.fastq.gz'\n },\n 'name': 'Sample1'}])\n+ self.assertEqual(user_job_order['my_path_file'], {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ }, \"Plain file paths should not be modified.\")\n+ self.assertEqual(user_job_order['my_url_file'], {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ }, \"URL file paths should not be modified.\")\n \n @patch('bespin.commands.DDSFileUtil')\n def test_get_dds_files_details(self, mock_dds_file_util):\n@@ -529,7 +545,15 @@ class JobOrderWalkerTestCase(TestCase):\n 'class': 'File',\n 'path': 'somepath3'\n }]\n- }\n+ },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n })\n \n walker.on_simple_value.assert_has_calls([\n@@ -592,6 +616,14 @@ class JobOrderPlaceholderCheckTestCase(TestCase):\n 'path': FILE_PLACEHOLDER,\n }\n },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n }\n expected_keys = [\n 'bad_str', 'bad_int', 'bad_file', 'bad_str_ary', 'bad_file_ary', 'bad_file_dict',\n@@ -623,6 +655,14 @@ class JobOrderFormatFilesTestCase(TestCase):\n 'path': 'dds://project3/data/other/somepath.txt',\n }\n },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n }\n \n formatter = JobOrderFormatFiles()\n@@ -661,6 +701,14 @@ class JobOrderFileDetailsTestCase(TestCase):\n 'path': 'dds://project3/data/other/somepath.txt',\n }\n },\n+ 'plain_path_file': {\n+ 'class': 'File',\n+ 'path': '/tmp/data.txt'\n+ },\n+ 'url_file': {\n+ 'class': 'File',\n+ 'location': 'https://github.com/datafile1.dat'\n+ },\n }\n expected_dds_file_info = [\n ('ddsfiledata', 'dds_project1_data_somepath.txt'),\n", "FAIL_TO_PASS": ["bespin/test_commands.py::JobFileTestCase::test_create_user_job_order_json", "bespin/test_commands.py::JobOrderPlaceholderCheckTestCase::test_walk", "bespin/test_commands.py::JobOrderFormatFilesTestCase::test_walk", "bespin/test_commands.py::JobOrderFileDetailsTestCase::test_walk"]}], "all_FAIL_TO_PASS": ["bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions_short_flag", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_current_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_all_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_latest_versions", "bespin/test_commands.py::WorkflowDetailsTestCase::test_get_column_data", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_all", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_latest", "bespin/test_api.py::BespinApiTestCase::test_dds_job_input_files_post", "bespin/test_commands.py::JobFileTestCase::test_create_job", "bespin/test_commands.py::JobFileTestCase::test_create_user_job_order_json", "bespin/test_commands.py::JobOrderPlaceholderCheckTestCase::test_walk", "bespin/test_commands.py::JobOrderFormatFilesTestCase::test_walk", "bespin/test_commands.py::JobOrderFileDetailsTestCase::test_walk"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-550_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-550:latest", "base_commit": "37ced1337e801d3a8dfd921ea4b416fe5ae42010", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-550", "base_commit": "37ced1337e801d3a8dfd921ea4b416fe5ae42010", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 34b6df14..6a141a1a 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -1,10 +1,16 @@\n from sqlglot import exp\n from sqlglot.dialects.dialect import Dialect, inline_array_sql, var_map_sql\n from sqlglot.generator import Generator\n+from sqlglot.helper import csv\n from sqlglot.parser import Parser, parse_var_map\n from sqlglot.tokens import Tokenizer, TokenType\n \n \n+def _lower_func(sql):\n+ index = sql.index(\"(\")\n+ return sql[:index].lower() + sql[index:]\n+\n+\n class ClickHouse(Dialect):\n normalize_functions = None\n null_ordering = \"nulls_are_last\"\n@@ -51,9 +57,10 @@ class ClickHouse(Dialect):\n TRANSFORMS = {\n **Generator.TRANSFORMS,\n exp.Array: inline_array_sql,\n+ exp.StrPosition: lambda self, e: f\"position({csv(self.sql(e, 'this'), self.sql(e, 'substr'), self.sql(e, 'position'))})\",\n exp.Final: lambda self, e: f\"{self.sql(e, 'this')} FINAL\",\n- exp.Map: var_map_sql,\n- exp.VarMap: var_map_sql,\n+ exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),\n+ exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),\n }\n \n EXPLICIT_UNION = True\ndiff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex fb2d9006..770240af 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -164,6 +164,7 @@ class Snowflake(Dialect):\n exp.StrToTime: lambda self, e: f\"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})\",\n exp.UnixToTime: _unix_to_time,\n exp.Array: inline_array_sql,\n+ exp.StrPosition: rename_func(\"POSITION\"),\n exp.PartitionedByProperty: lambda self, e: f\"PARTITION BY {self.sql(e, 'value')}\",\n }\n \ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 256f45ad..bc6beaa1 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2459,7 +2459,7 @@ class Substring(Func):\n \n \n class StrPosition(Func):\n- arg_types = {\"this\": True, \"substr\": True, \"position\": False}\n+ arg_types = {\"substr\": True, \"this\": True, \"position\": False}\n \n \n class StrToDate(Func):\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex c74532f1..1323ae04 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -2044,10 +2044,16 @@ class Parser:\n return self.expression(exp.Cast, this=this, to=to)\n \n def _parse_position(self):\n- substr = self._parse_bitwise()\n+ args = self._parse_csv(self._parse_bitwise)\n+\n if self._match(TokenType.IN):\n- string = self._parse_bitwise()\n- return self.expression(exp.StrPosition, this=string, substr=substr)\n+ args.append(self._parse_bitwise())\n+\n+ # Note: we're parsing in order needle, haystack, position\n+ this = exp.StrPosition.from_arg_list(args)\n+ self.validate_expression(this, args)\n+\n+ return this\n \n def _parse_substring(self):\n # Postgres supports the form: substring(string [from int] [for int])\n", "test_patch": "diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py\nindex 6d7578d6..b103ecda 100644\n--- a/tests/dialects/test_dialect.py\n+++ b/tests/dialects/test_dialect.py\n@@ -858,15 +858,28 @@ class TestDialect(Validator):\n \"postgres\": \"STRPOS(x, ' ')\",\n \"presto\": \"STRPOS(x, ' ')\",\n \"spark\": \"LOCATE(' ', x)\",\n+ \"clickhouse\": \"position(x, ' ')\",\n+ \"snowflake\": \"POSITION(' ', x)\",\n },\n )\n self.validate_all(\n- \"STR_POSITION(x, 'a')\",\n+ \"STR_POSITION('a', x)\",\n write={\n \"duckdb\": \"STRPOS(x, 'a')\",\n \"postgres\": \"STRPOS(x, 'a')\",\n \"presto\": \"STRPOS(x, 'a')\",\n \"spark\": \"LOCATE('a', x)\",\n+ \"clickhouse\": \"position(x, 'a')\",\n+ \"snowflake\": \"POSITION('a', x)\",\n+ },\n+ )\n+ self.validate_all(\n+ \"POSITION('a', x, 3)\",\n+ write={\n+ \"presto\": \"STRPOS(SUBSTR(x, 3), 'a') + 3 - 1\",\n+ \"spark\": \"LOCATE('a', x, 3)\",\n+ \"clickhouse\": \"position(x, 'a', 3)\",\n+ \"snowflake\": \"POSITION('a', x, 3)\",\n },\n )\n self.validate_all(\ndiff --git a/tests/dialects/test_hive.py b/tests/dialects/test_hive.py\nindex 4e8b4af5..acb3be9a 100644\n--- a/tests/dialects/test_hive.py\n+++ b/tests/dialects/test_hive.py\n@@ -452,7 +452,7 @@ class TestHive(Validator):\n \"MAP(a, b, c, d)\",\n read={\n \"\": \"VAR_MAP(a, b, c, d)\",\n- \"clickhouse\": \"MAP(a, b, c, d)\",\n+ \"clickhouse\": \"map(a, b, c, d)\",\n \"duckdb\": \"MAP(LIST_VALUE(a, c), LIST_VALUE(b, d))\",\n \"hive\": \"MAP(a, b, c, d)\",\n \"presto\": \"MAP(ARRAY[a, c], ARRAY[b, d])\",\n@@ -460,7 +460,7 @@ class TestHive(Validator):\n },\n write={\n \"\": \"MAP(ARRAY(a, c), ARRAY(b, d))\",\n- \"clickhouse\": \"MAP(a, b, c, d)\",\n+ \"clickhouse\": \"map(a, b, c, d)\",\n \"duckdb\": \"MAP(LIST_VALUE(a, c), LIST_VALUE(b, d))\",\n \"presto\": \"MAP(ARRAY[a, c], ARRAY[b, d])\",\n \"hive\": \"MAP(a, b, c, d)\",\n", "FAIL_TO_PASS": ["tests/dialects/test_dialect.py::TestDialect::test_operators", "tests/dialects/test_hive.py::TestHive::test_hive"]}, {"instance_id": "tobymao__sqlglot-552", "base_commit": "17521c1664643384bb99e184e2e7e84343c67c7f", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 6a141a1a..f25f6dac 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -52,6 +52,9 @@ class ClickHouse(Dialect):\n **Generator.TYPE_MAPPING,\n exp.DataType.Type.NULLABLE: \"Nullable\",\n exp.DataType.Type.DATETIME: \"DateTime64\",\n+ exp.DataType.Type.MAP: \"Map\",\n+ exp.DataType.Type.ARRAY: \"Array\",\n+ exp.DataType.Type.STRUCT: \"Tuple\",\n }\n \n TRANSFORMS = {\n", "test_patch": "diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py\nindex b103ecda..d31d0f6c 100644\n--- a/tests/dialects/test_dialect.py\n+++ b/tests/dialects/test_dialect.py\n@@ -81,6 +81,24 @@ class TestDialect(Validator):\n \"starrocks\": \"CAST(a AS STRING)\",\n },\n )\n+ self.validate_all(\n+ \"CAST(MAP('a', '1') AS MAP(TEXT, TEXT))\",\n+ write={\n+ \"clickhouse\": \"CAST(map('a', '1') AS Map(TEXT, TEXT))\",\n+ },\n+ )\n+ self.validate_all(\n+ \"CAST(ARRAY(1, 2) AS ARRAY)\",\n+ write={\n+ \"clickhouse\": \"CAST([1, 2] AS Array(TINYINT))\",\n+ },\n+ )\n+ self.validate_all(\n+ \"CAST((1, 2) AS STRUCT)\",\n+ write={\n+ \"clickhouse\": \"CAST((1, 2) AS Tuple(a TINYINT, b TINYINT))\",\n+ },\n+ )\n self.validate_all(\n \"CAST(a AS DATETIME)\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_dialect.py::TestDialect::test_cast"]}, {"instance_id": "tobymao__sqlglot-555", "base_commit": "d486eab830a13572f3c13d7b508279df0a3802cb", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 39ce0af0..53951bff 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2074,7 +2074,7 @@ class Distinct(Expression):\n \n \n class In(Predicate):\n- arg_types = {\"this\": True, \"expressions\": False, \"query\": False, \"unnest\": False}\n+ arg_types = {\"this\": True, \"expressions\": False, \"query\": False, \"unnest\": False, \"field\": False}\n \n \n class TimeUnit(Expression):\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 0bd71755..974934e5 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -945,10 +945,13 @@ class Generator:\n def in_sql(self, expression):\n query = expression.args.get(\"query\")\n unnest = expression.args.get(\"unnest\")\n+ field = expression.args.get(\"field\")\n if query:\n in_sql = self.wrap(query)\n elif unnest:\n in_sql = self.in_unnest_op(unnest)\n+ elif field:\n+ in_sql = self.sql(field)\n else:\n in_sql = f\"({self.expressions(expression, flat=True)})\"\n return f\"{self.sql(expression, 'this')} IN {in_sql}\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 1323ae04..8dd68271 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1504,8 +1504,7 @@ class Parser:\n unnest = self._parse_unnest()\n if unnest:\n this = self.expression(exp.In, this=this, unnest=unnest)\n- else:\n- self._match_l_paren()\n+ elif self._match(TokenType.L_PAREN):\n expressions = self._parse_csv(self._parse_select_or_expression)\n \n if len(expressions) == 1 and isinstance(expressions[0], exp.Subqueryable):\n@@ -1514,6 +1513,9 @@ class Parser:\n this = self.expression(exp.In, this=this, expressions=expressions)\n \n self._match_r_paren()\n+ else:\n+ this = self.expression(exp.In, this=this, field=self._parse_field())\n+\n return this\n \n def _parse_between(self, this):\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex 725b27c8..cf51acb9 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -8,6 +8,7 @@ class TestClickhouse(Validator):\n self.validate_identity(\"dictGet(x, 'y')\")\n self.validate_identity(\"SELECT * FROM x FINAL\")\n self.validate_identity(\"SELECT * FROM x AS y FINAL\")\n+ self.validate_identity(\"'a' IN mapKeys(map('a', 1, 'b', 2))\")\n \n self.validate_all(\n \"SELECT fname, lname, age FROM person ORDER BY age DESC NULLS FIRST, fname ASC NULLS LAST, lname\",\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_dialect.py::TestDialect::test_operators", "tests/dialects/test_hive.py::TestHive::test_hive", "tests/dialects/test_dialect.py::TestDialect::test_cast", "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-1627_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-1627:latest", "base_commit": "9c3cd2cabe39a683832c0fbad26714c31b41bc76", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-1627", "base_commit": "9c3cd2cabe39a683832c0fbad26714c31b41bc76", "gold_patch": "diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 27acb27a..84bf0a47 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -52,8 +52,12 @@ def _snowflake_to_timestamp(args: t.Sequence) -> t.Union[exp.StrToTime, exp.Unix\n \n return exp.UnixToTime(this=first_arg, scale=timescale)\n \n+ from sqlglot.optimizer.simplify import simplify_literals\n+\n+ # The first argument might be an expression like 40 * 365 * 86400, so we try to\n+ # reduce it using `simplify_literals` first and then check if it's a Literal.\n first_arg = seq_get(args, 0)\n- if not isinstance(first_arg, Literal):\n+ if not isinstance(simplify_literals(first_arg, root=True), Literal):\n # case: \n return format_time_lambda(exp.StrToTime, \"snowflake\", default=True)(args)\n \ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 953c0fd2..048dc55a 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -949,6 +949,17 @@ class Create(Expression):\n \"indexes\": False,\n \"no_schema_binding\": False,\n \"begin\": False,\n+ \"clone\": False,\n+ }\n+\n+\n+# https://docs.snowflake.com/en/sql-reference/sql/create-clone\n+class Clone(Expression):\n+ arg_types = {\n+ \"this\": True,\n+ \"when\": False,\n+ \"kind\": False,\n+ \"expression\": False,\n }\n \n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 3001a548..84fa74ae 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -725,9 +725,23 @@ class Generator:\n \" WITH NO SCHEMA BINDING\" if expression.args.get(\"no_schema_binding\") else \"\"\n )\n \n- expression_sql = f\"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}\"\n+ clone = self.sql(expression, \"clone\")\n+ clone = f\" {clone}\" if clone else \"\"\n+\n+ expression_sql = f\"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}\"\n return self.prepend_ctes(expression, expression_sql)\n \n+ def clone_sql(self, expression: exp.Clone) -> str:\n+ this = self.sql(expression, \"this\")\n+ when = self.sql(expression, \"when\")\n+\n+ if when:\n+ kind = self.sql(expression, \"kind\")\n+ expr = self.sql(expression, \"expression\")\n+ return f\"CLONE {this} {when} ({kind} => {expr})\"\n+\n+ return f\"CLONE {this}\"\n+\n def describe_sql(self, expression: exp.Describe) -> str:\n return f\"DESCRIBE {self.sql(expression, 'this')}\"\n \ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 19352f8b..b6c99bd7 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -768,6 +768,8 @@ class Parser(metaclass=_Parser):\n \n INSERT_ALTERNATIVES = {\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"}\n \n+ CLONE_KINDS = {\"TIMESTAMP\", \"OFFSET\", \"STATEMENT\"}\n+\n WINDOW_ALIAS_TOKENS = ID_VAR_TOKENS - {TokenType.ROWS}\n WINDOW_BEFORE_PAREN_TOKENS = {TokenType.OVER}\n \n@@ -1152,6 +1154,7 @@ class Parser(metaclass=_Parser):\n indexes = None\n no_schema_binding = None\n begin = None\n+ clone = None\n \n if create_token.token_type in (TokenType.FUNCTION, TokenType.PROCEDURE):\n this = self._parse_user_defined_function(kind=create_token.token_type)\n@@ -1234,6 +1237,20 @@ class Parser(metaclass=_Parser):\n if self._match_text_seq(\"WITH\", \"NO\", \"SCHEMA\", \"BINDING\"):\n no_schema_binding = True\n \n+ if self._match_text_seq(\"CLONE\"):\n+ clone = self._parse_table(schema=True)\n+ when = self._match_texts({\"AT\", \"BEFORE\"}) and self._prev.text.upper()\n+ clone_kind = (\n+ self._match(TokenType.L_PAREN)\n+ and self._match_texts(self.CLONE_KINDS)\n+ and self._prev.text.upper()\n+ )\n+ clone_expression = self._match(TokenType.FARROW) and self._parse_bitwise()\n+ self._match(TokenType.R_PAREN)\n+ clone = self.expression(\n+ exp.Clone, this=clone, when=when, kind=clone_kind, expression=clone_expression\n+ )\n+\n return self.expression(\n exp.Create,\n this=this,\n@@ -1246,6 +1263,7 @@ class Parser(metaclass=_Parser):\n indexes=indexes,\n no_schema_binding=no_schema_binding,\n begin=begin,\n+ clone=clone,\n )\n \n def _parse_property_before(self) -> t.Optional[exp.Expression]:\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 7b00c60b..baf83bed 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -555,10 +555,22 @@ class TestSnowflake(Validator):\n )\n \n def test_ddl(self):\n+ self.validate_identity(\"CREATE MATERIALIZED VIEW a COMMENT='...' AS SELECT 1 FROM x\")\n+ self.validate_identity(\"CREATE DATABASE mytestdb_clone CLONE mytestdb\")\n+ self.validate_identity(\"CREATE SCHEMA mytestschema_clone CLONE testschema\")\n+ self.validate_identity(\"CREATE TABLE orders_clone CLONE orders\")\n+ self.validate_identity(\n+ \"CREATE TABLE orders_clone_restore CLONE orders AT (TIMESTAMP => TO_TIMESTAMP_TZ('04/05/2013 01:02:03', 'mm/dd/yyyy hh24:mi:ss'))\"\n+ )\n+ self.validate_identity(\n+ \"CREATE TABLE orders_clone_restore CLONE orders BEFORE (STATEMENT => '8e5d0ca9-005e-44e6-b858-a8f5b37c5726')\"\n+ )\n self.validate_identity(\n \"CREATE TABLE a (x DATE, y BIGINT) WITH (PARTITION BY (x), integration='q', auto_refresh=TRUE, file_format=(type = parquet))\"\n )\n- self.validate_identity(\"CREATE MATERIALIZED VIEW a COMMENT='...' AS SELECT 1 FROM x\")\n+ self.validate_identity(\n+ \"CREATE SCHEMA mytestschema_clone_restore CLONE testschema BEFORE (TIMESTAMP => TO_TIMESTAMP(40 * 365 * 86400))\"\n+ )\n \n self.validate_all(\n \"CREATE OR REPLACE TRANSIENT TABLE a (id INT)\",\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_ddl"]}, {"instance_id": "tobymao__sqlglot-1640", "base_commit": "5a51d216b73b4dfa2e1d511fcbed47558e97db61", "gold_patch": "diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py\nindex 491b299f..cdf25347 100644\n--- a/sqlglot/dialects/bigquery.py\n+++ b/sqlglot/dialects/bigquery.py\n@@ -138,7 +138,6 @@ class BigQuery(Dialect):\n \"BEGIN TRANSACTION\": TokenType.BEGIN,\n \"CURRENT_DATETIME\": TokenType.CURRENT_DATETIME,\n \"DECLARE\": TokenType.COMMAND,\n- \"GEOGRAPHY\": TokenType.GEOGRAPHY,\n \"FLOAT64\": TokenType.DOUBLE,\n \"INT64\": TokenType.BIGINT,\n \"BYTES\": TokenType.BINARY,\ndiff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py\nindex 09ddf644..eebe3029 100644\n--- a/sqlglot/dialects/redshift.py\n+++ b/sqlglot/dialects/redshift.py\n@@ -58,8 +58,6 @@ class Redshift(Postgres):\n \n KEYWORDS = {\n **Postgres.Tokenizer.KEYWORDS, # type: ignore\n- \"GEOMETRY\": TokenType.GEOMETRY,\n- \"GEOGRAPHY\": TokenType.GEOGRAPHY,\n \"HLLSKETCH\": TokenType.HLLSKETCH,\n \"SUPER\": TokenType.SUPER,\n \"SYSDATE\": TokenType.CURRENT_TIMESTAMP,\ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex 53e79d40..5ba47395 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -551,6 +551,8 @@ class Tokenizer(metaclass=_Tokenizer):\n \"FOREIGN KEY\": TokenType.FOREIGN_KEY,\n \"FORMAT\": TokenType.FORMAT,\n \"FROM\": TokenType.FROM,\n+ \"GEOGRAPHY\": TokenType.GEOGRAPHY,\n+ \"GEOMETRY\": TokenType.GEOMETRY,\n \"GLOB\": TokenType.GLOB,\n \"GROUP BY\": TokenType.GROUP_BY,\n \"GROUPING SETS\": TokenType.GROUPING_SETS,\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex c2d4a3cd..46f27e3b 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -6,6 +6,7 @@ class TestSnowflake(Validator):\n dialect = \"snowflake\"\n \n def test_snowflake(self):\n+ self.validate_identity(\"CAST(x AS GEOMETRY)\")\n self.validate_identity(\"OBJECT_CONSTRUCT(*)\")\n self.validate_identity(\"SELECT TO_DATE('2019-02-28') + INTERVAL '1 day, 1 year'\")\n self.validate_identity(\"SELECT CAST('2021-01-01' AS DATE) + INTERVAL '1 DAY'\")\n@@ -558,6 +559,7 @@ class TestSnowflake(Validator):\n )\n \n def test_ddl(self):\n+ self.validate_identity(\"CREATE TABLE geospatial_table (id INT, g GEOGRAPHY)\")\n self.validate_identity(\"CREATE MATERIALIZED VIEW a COMMENT='...' AS SELECT 1 FROM x\")\n self.validate_identity(\"CREATE DATABASE mytestdb_clone CLONE mytestdb\")\n self.validate_identity(\"CREATE SCHEMA mytestschema_clone CLONE testschema\")\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-1642", "base_commit": "ef428827ab3b68160f1f635ce7fa581a74ded8f5", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 5aa09f1e..6f6831ef 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2162,7 +2162,7 @@ QUERY_MODIFIERS = {\n \"order\": False,\n \"limit\": False,\n \"offset\": False,\n- \"lock\": False,\n+ \"locks\": False,\n \"sample\": False,\n \"settings\": False,\n \"format\": False,\n@@ -2343,10 +2343,10 @@ class Schema(Expression):\n arg_types = {\"this\": False, \"expressions\": False}\n \n \n-# Used to represent the FOR UPDATE and FOR SHARE locking read types.\n-# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html\n+# https://dev.mysql.com/doc/refman/8.0/en/select.html\n+# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html\n class Lock(Expression):\n- arg_types = {\"update\": True}\n+ arg_types = {\"update\": True, \"expressions\": False, \"wait\": False}\n \n \n class Select(Subqueryable):\n@@ -2922,7 +2922,7 @@ class Select(Subqueryable):\n \"\"\"\n \n inst = _maybe_copy(self, copy)\n- inst.set(\"lock\", Lock(update=update))\n+ inst.set(\"locks\", [Lock(update=update)])\n \n return inst\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex bde289bb..1184c095 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1382,12 +1382,22 @@ class Generator:\n return f\"PRAGMA {self.sql(expression, 'this')}\"\n \n def lock_sql(self, expression: exp.Lock) -> str:\n- if self.LOCKING_READS_SUPPORTED:\n- lock_type = \"UPDATE\" if expression.args[\"update\"] else \"SHARE\"\n- return self.seg(f\"FOR {lock_type}\")\n+ if not self.LOCKING_READS_SUPPORTED:\n+ self.unsupported(\"Locking reads using 'FOR UPDATE/SHARE' are not supported\")\n+ return \"\"\n \n- self.unsupported(\"Locking reads using 'FOR UPDATE/SHARE' are not supported\")\n- return \"\"\n+ lock_type = \"FOR UPDATE\" if expression.args[\"update\"] else \"FOR SHARE\"\n+ expressions = self.expressions(expression, flat=True)\n+ expressions = f\" OF {expressions}\" if expressions else \"\"\n+ wait = expression.args.get(\"wait\")\n+\n+ if wait is not None:\n+ if isinstance(wait, exp.Literal):\n+ wait = f\" WAIT {self.sql(wait)}\"\n+ else:\n+ wait = \" NOWAIT\" if wait else \" SKIP LOCKED\"\n+\n+ return f\"{lock_type}{expressions}{wait or ''}\"\n \n def literal_sql(self, expression: exp.Literal) -> str:\n text = expression.this or \"\"\n@@ -1529,10 +1539,9 @@ class Generator:\n ]\n \n def after_limit_modifiers(self, expression):\n- return [\n- self.sql(expression, \"lock\"),\n- self.sql(expression, \"sample\"),\n- ]\n+ locks = self.expressions(expression, key=\"locks\", sep=\" \")\n+ locks = f\" {locks}\" if locks else \"\"\n+ return [locks, self.sql(expression, \"sample\")]\n \n def select_sql(self, expression: exp.Select) -> str:\n hint = self.sql(expression, \"hint\")\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex f56829f3..3c4547cd 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -287,6 +287,7 @@ class Parser(metaclass=_Parser):\n TokenType.APPLY,\n TokenType.FULL,\n TokenType.LEFT,\n+ TokenType.LOCK,\n TokenType.NATURAL,\n TokenType.OFFSET,\n TokenType.RIGHT,\n@@ -738,7 +739,7 @@ class Parser(metaclass=_Parser):\n \"order\": lambda self: self._parse_order(),\n \"limit\": lambda self: self._parse_limit(),\n \"offset\": lambda self: self._parse_offset(),\n- \"lock\": lambda self: self._parse_lock(),\n+ \"locks\": lambda self: self._parse_locks(),\n \"sample\": lambda self: self._parse_table_sample(as_modifier=True),\n }\n \n@@ -2652,13 +2653,37 @@ class Parser(metaclass=_Parser):\n self._match_set((TokenType.ROW, TokenType.ROWS))\n return self.expression(exp.Offset, this=this, expression=count)\n \n- def _parse_lock(self) -> t.Optional[exp.Expression]:\n- if self._match_text_seq(\"FOR\", \"UPDATE\"):\n- return self.expression(exp.Lock, update=True)\n- if self._match_text_seq(\"FOR\", \"SHARE\"):\n- return self.expression(exp.Lock, update=False)\n+ def _parse_locks(self) -> t.List[exp.Expression]:\n+ # Lists are invariant, so we need to use a type hint here\n+ locks: t.List[exp.Expression] = []\n \n- return None\n+ while True:\n+ if self._match_text_seq(\"FOR\", \"UPDATE\"):\n+ update = True\n+ elif self._match_text_seq(\"FOR\", \"SHARE\") or self._match_text_seq(\n+ \"LOCK\", \"IN\", \"SHARE\", \"MODE\"\n+ ):\n+ update = False\n+ else:\n+ break\n+\n+ expressions = None\n+ if self._match_text_seq(\"OF\"):\n+ expressions = self._parse_csv(lambda: self._parse_table(schema=True))\n+\n+ wait: t.Optional[bool | exp.Expression] = None\n+ if self._match_text_seq(\"NOWAIT\"):\n+ wait = True\n+ elif self._match_text_seq(\"WAIT\"):\n+ wait = self._parse_primary()\n+ elif self._match_text_seq(\"SKIP\", \"LOCKED\"):\n+ wait = False\n+\n+ locks.append(\n+ self.expression(exp.Lock, update=update, expressions=expressions, wait=wait)\n+ )\n+\n+ return locks\n \n def _parse_set_operations(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]:\n if not self._match_set(self.SET_OPERATIONS):\ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex 5ba47395..956fafdf 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -231,6 +231,7 @@ class TokenType(AutoName):\n LIMIT = auto()\n LOAD_DATA = auto()\n LOCAL = auto()\n+ LOCK = auto()\n MAP = auto()\n MATCH_RECOGNIZE = auto()\n MATERIALIZED = auto()\n@@ -580,6 +581,7 @@ class Tokenizer(metaclass=_Tokenizer):\n \"LIMIT\": TokenType.LIMIT,\n \"LOAD DATA\": TokenType.LOAD_DATA,\n \"LOCAL\": TokenType.LOCAL,\n+ \"LOCK\": TokenType.LOCK,\n \"MATERIALIZED\": TokenType.MATERIALIZED,\n \"MERGE\": TokenType.MERGE,\n \"NATURAL\": TokenType.NATURAL,\n", "test_patch": "diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py\nindex f31b1b96..be7887e8 100644\n--- a/tests/dialects/test_mysql.py\n+++ b/tests/dialects/test_mysql.py\n@@ -47,8 +47,11 @@ class TestMySQL(Validator):\n self.validate_identity(\"SELECT TRIM(BOTH 'bla' FROM ' XXX ')\")\n self.validate_identity(\"SELECT TRIM('bla' FROM ' XXX ')\")\n self.validate_identity(\"@@GLOBAL.max_connections\")\n-\n self.validate_identity(\"CREATE TABLE A LIKE B\")\n+ self.validate_identity(\"SELECT * FROM t1, t2 FOR SHARE OF t1, t2 SKIP LOCKED\")\n+ self.validate_identity(\n+ \"SELECT * FROM t1, t2, t3 FOR SHARE OF t1 NOWAIT FOR UPDATE OF t2, t3 SKIP LOCKED\"\n+ )\n \n # SET Commands\n self.validate_identity(\"SET @var_name = expr\")\n@@ -368,6 +371,9 @@ class TestMySQL(Validator):\n self.validate_identity(\"TIME_STR_TO_UNIX(x)\", \"UNIX_TIMESTAMP(x)\")\n \n def test_mysql(self):\n+ self.validate_all(\n+ \"SELECT * FROM t LOCK IN SHARE MODE\", write={\"mysql\": \"SELECT * FROM t FOR SHARE\"}\n+ )\n self.validate_all(\n \"SELECT DATE(DATE_SUB(`dt`, INTERVAL DAYOFMONTH(`dt`) - 1 DAY)) AS __timestamp FROM tableT\",\n write={\ndiff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 58b3fdcd..12ff6994 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -5,6 +5,13 @@ class TestOracle(Validator):\n dialect = \"oracle\"\n \n def test_oracle(self):\n+ self.validate_identity(\"SELECT * FROM t FOR UPDATE\")\n+ self.validate_identity(\"SELECT * FROM t FOR UPDATE WAIT 5\")\n+ self.validate_identity(\"SELECT * FROM t FOR UPDATE NOWAIT\")\n+ self.validate_identity(\"SELECT * FROM t FOR UPDATE SKIP LOCKED\")\n+ self.validate_identity(\"SELECT * FROM t FOR UPDATE OF s.t.c, s.t.v\")\n+ self.validate_identity(\"SELECT * FROM t FOR UPDATE OF s.t.c, s.t.v NOWAIT\")\n+ self.validate_identity(\"SELECT * FROM t FOR UPDATE OF s.t.c, s.t.v SKIP LOCKED\")\n self.validate_identity(\"SELECT STANDARD_HASH('hello')\")\n self.validate_identity(\"SELECT STANDARD_HASH('hello', 'MD5')\")\n self.validate_identity(\"SELECT CAST(NULL AS VARCHAR2(2328 CHAR)) AS COL1\")\n", "FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_identity", "tests/dialects/test_mysql.py::TestMySQL::test_mysql", "tests/dialects/test_oracle.py::TestOracle::test_oracle"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_mysql.py::TestMySQL::test_identity", "tests/dialects/test_mysql.py::TestMySQL::test_mysql", "tests/dialects/test_oracle.py::TestOracle::test_oracle"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ipython__ipykernel-1051_x3", "level": 3, "source": "swerebench", "repo": "ipython/ipykernel", "image": "swerebench/sweb.eval.x86_64.ipython_1776_ipykernel-1051:latest", "base_commit": "b13c46ac5fa800359748386c64f89402ac0e204e", "num_bugs": 3, "bugs": [{"instance_id": "ipython__ipykernel-1051", "base_commit": "b13c46ac5fa800359748386c64f89402ac0e204e", "gold_patch": "diff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex c06d233..295232e 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -71,9 +71,8 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def __init__(self, *args, **kwargs):\n # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n- for name in self.trait_names():\n- if name in kwargs:\n- kwargs.pop(name)\n+ # drop arguments not in BaseComm\n+ kwargs.pop(\"kernel\", None)\n BaseComm.__init__(self, *args, **kwargs)\n \n \n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex 9dd49f8..f8b0764 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -6,7 +6,7 @@ def test_comm(kernel):\n manager = CommManager(kernel=kernel)\n kernel.comm_manager = manager\n \n- c = Comm(kernel=kernel)\n+ c = Comm(kernel=kernel, target_name=\"bar\")\n msgs = []\n \n def on_close(msg):\n@@ -23,6 +23,7 @@ def test_comm(kernel):\n c.handle_close({})\n c.close()\n assert len(msgs) == 2\n+ assert c.target_name == \"bar\"\n \n \n def test_comm_manager(kernel):\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm"]}, {"instance_id": "ipython__ipykernel-1056", "base_commit": "04e1d753e328194be391b62ffd22662f0fe6dc56", "gold_patch": "diff --git a/.github/workflows/downstream.yml b/.github/workflows/downstream.yml\nindex ab1f103..57c8561 100644\n--- a/.github/workflows/downstream.yml\n+++ b/.github/workflows/downstream.yml\n@@ -84,6 +84,41 @@ jobs:\n pip install -e \".[test]\"\n python test_ipykernel.py\n \n+ qtconsole:\n+ runs-on: ubuntu-latest\n+ timeout-minutes: 20\n+ steps:\n+ - name: Checkout\n+ uses: actions/checkout@v3\n+\n+ - name: Setup Python\n+ uses: actions/setup-python@v4\n+ with:\n+ python-version: \"3.9\"\n+ architecture: \"x64\"\n+\n+ - name: Install System Packages\n+ run: |\n+ sudo apt-get update\n+ sudo apt-get install -y --no-install-recommends '^libxcb.*-dev' libx11-xcb-dev libglu1-mesa-dev libxrender-dev libxi-dev libxkbcommon-dev libxkbcommon-x11-dev\n+ - name: Install qtconsole dependencies\n+ shell: bash -l {0}\n+ run: |\n+ cd ${GITHUB_WORKSPACE}/..\n+ git clone https://github.com/jupyter/qtconsole.git\n+ cd qtconsole\n+ ${pythonLocation}/bin/python -m pip install -e \".[test]\"\n+ ${pythonLocation}/bin/python -m pip install pyqt5\n+ - name: Install Jupyter-Client changes\n+ shell: bash -l {0}\n+ run: ${pythonLocation}/bin/python -m pip install -e .\n+\n+ - name: Test qtconsole\n+ shell: bash -l {0}\n+ run: |\n+ cd ${GITHUB_WORKSPACE}/../qtconsole\n+ xvfb-run --auto-servernum ${pythonLocation}/bin/python -m pytest -x -vv -s --full-trace --color=yes qtconsole\n+\n downstream_check: # This job does nothing and is only used for the branch protection\n if: always()\n needs:\n@@ -92,6 +127,7 @@ jobs:\n - jupyter_client\n - ipyparallel\n - jupyter_kernel_test\n+ - qtconsole\n runs-on: ubuntu-latest\n steps:\n - name: Decide whether the needed jobs succeeded or failed\ndiff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex 295232e..77f9f07 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -42,7 +42,7 @@ class BaseComm(comm.base_comm.BaseComm):\n \n \n # but for backwards compatibility, we need to inherit from LoggingConfigurable\n-class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n+class Comm(BaseComm, traitlets.config.LoggingConfigurable):\n \"\"\"Class for communicating between a Frontend and a Kernel\"\"\"\n \n kernel = Instance(\"ipykernel.kernelbase.Kernel\", allow_none=True) # type:ignore[assignment]\n@@ -68,12 +68,16 @@ class Comm(traitlets.config.LoggingConfigurable, BaseComm):\n def _default_comm_id(self):\n return uuid.uuid4().hex\n \n- def __init__(self, *args, **kwargs):\n- # Comm takes positional arguments, LoggingConfigurable does not, so we explicitly forward arguments\n+ def __init__(self, target_name='', data=None, metadata=None, buffers=None, **kwargs):\n+ # Handle differing arguments between base classes.\n+ kernel = kwargs.pop('kernel', None)\n+ if target_name:\n+ kwargs['target_name'] = target_name\n+ BaseComm.__init__(\n+ self, data=data, metadata=metadata, buffers=buffers, **kwargs\n+ ) # type:ignore[call-arg]\n+ kwargs['kernel'] = kernel\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n- # drop arguments not in BaseComm\n- kwargs.pop(\"kernel\", None)\n- BaseComm.__init__(self, *args, **kwargs)\n \n \n __all__ = [\"Comm\"]\ndiff --git a/ipykernel/comm/manager.py b/ipykernel/comm/manager.py\nindex 6bf73ad..c11b562 100644\n--- a/ipykernel/comm/manager.py\n+++ b/ipykernel/comm/manager.py\n@@ -9,7 +9,7 @@ import traitlets\n import traitlets.config\n \n \n-class CommManager(traitlets.config.LoggingConfigurable, comm.base_comm.CommManager):\n+class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable):\n \n kernel = traitlets.Instance(\"ipykernel.kernelbase.Kernel\")\n comms = traitlets.Dict()\n@@ -17,5 +17,5 @@ class CommManager(traitlets.config.LoggingConfigurable, comm.base_comm.CommManag\n \n def __init__(self, **kwargs):\n # CommManager doesn't take arguments, so we explicitly forward arguments\n- traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n comm.base_comm.CommManager.__init__(self)\n+ traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex f8b0764..405841f 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -1,3 +1,5 @@\n+import unittest.mock\n+\n from ipykernel.comm import Comm, CommManager\n from ipykernel.ipkernel import IPythonKernel\n \n@@ -47,10 +49,12 @@ def test_comm_manager(kernel):\n manager.register_target(\"fizz\", fizz)\n \n kernel.comm_manager = manager\n- comm = Comm()\n- comm.on_msg(on_msg)\n- comm.on_close(on_close)\n- manager.register_comm(comm)\n+ with unittest.mock.patch.object(Comm, \"publish_msg\") as publish_msg:\n+ comm = Comm()\n+ comm.on_msg(on_msg)\n+ comm.on_close(on_close)\n+ manager.register_comm(comm)\n+ assert publish_msg.call_count == 1\n \n assert manager.get_comm(comm.comm_id) == comm\n assert manager.get_comm('foo') is None\n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm_manager"]}, {"instance_id": "ipython__ipykernel-1061", "base_commit": "2c66b2de835856b19b25c6a890d9665902dda907", "gold_patch": "diff --git a/ipykernel/comm/comm.py b/ipykernel/comm/comm.py\nindex 77f9f07..6ec6ff3 100644\n--- a/ipykernel/comm/comm.py\n+++ b/ipykernel/comm/comm.py\n@@ -70,13 +70,16 @@ class Comm(BaseComm, traitlets.config.LoggingConfigurable):\n \n def __init__(self, target_name='', data=None, metadata=None, buffers=None, **kwargs):\n # Handle differing arguments between base classes.\n+ had_kernel = 'kernel' in kwargs\n kernel = kwargs.pop('kernel', None)\n if target_name:\n kwargs['target_name'] = target_name\n BaseComm.__init__(\n self, data=data, metadata=metadata, buffers=buffers, **kwargs\n ) # type:ignore[call-arg]\n- kwargs['kernel'] = kernel\n+ # only re-add kernel if explicitly provided\n+ if had_kernel:\n+ kwargs['kernel'] = kernel\n traitlets.config.LoggingConfigurable.__init__(self, **kwargs)\n \n \n", "test_patch": "diff --git a/ipykernel/tests/test_comm.py b/ipykernel/tests/test_comm.py\nindex 405841f..5ec0d45 100644\n--- a/ipykernel/tests/test_comm.py\n+++ b/ipykernel/tests/test_comm.py\n@@ -2,15 +2,18 @@ import unittest.mock\n \n from ipykernel.comm import Comm, CommManager\n from ipykernel.ipkernel import IPythonKernel\n+from ipykernel.kernelbase import Kernel\n \n \n-def test_comm(kernel):\n+def test_comm(kernel: Kernel) -> None:\n manager = CommManager(kernel=kernel)\n- kernel.comm_manager = manager\n+ kernel.comm_manager = manager # type:ignore\n \n c = Comm(kernel=kernel, target_name=\"bar\")\n msgs = []\n \n+ assert kernel is c.kernel # type:ignore\n+\n def on_close(msg):\n msgs.append(msg)\n \n@@ -28,7 +31,7 @@ def test_comm(kernel):\n assert c.target_name == \"bar\"\n \n \n-def test_comm_manager(kernel):\n+def test_comm_manager(kernel: Kernel) -> None:\n manager = CommManager(kernel=kernel)\n msgs = []\n \n@@ -48,7 +51,7 @@ def test_comm_manager(kernel):\n manager.register_target(\"foo\", foo)\n manager.register_target(\"fizz\", fizz)\n \n- kernel.comm_manager = manager\n+ kernel.comm_manager = manager # type:ignore\n with unittest.mock.patch.object(Comm, \"publish_msg\") as publish_msg:\n comm = Comm()\n comm.on_msg(on_msg)\n@@ -56,6 +59,11 @@ def test_comm_manager(kernel):\n manager.register_comm(comm)\n assert publish_msg.call_count == 1\n \n+ # make sure that when we don't pass a kernel, the 'default' kernel is taken\n+ Kernel._instance = kernel # type:ignore\n+ assert comm.kernel is kernel # type:ignore\n+ Kernel.clear_instance()\n+\n assert manager.get_comm(comm.comm_id) == comm\n assert manager.get_comm('foo') is None\n \n", "FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm_manager", "ipykernel/tests/test_comm.py::test_comm_in_manager"]}], "all_FAIL_TO_PASS": ["ipykernel/tests/test_comm.py::test_comm", "ipykernel/tests/test_comm.py::test_comm_manager", "ipykernel/tests/test_comm.py::test_comm_manager", "ipykernel/tests/test_comm.py::test_comm_in_manager"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "neovasili__tflens-34_x3", "level": 3, "source": "swerebench", "repo": "neovasili/tflens", "image": "swerebench/sweb.eval.x86_64.neovasili_1776_tflens-34:latest", "base_commit": "8de85543fed8503e823b64b112dbbb292fc90d04", "num_bugs": 3, "bugs": [{"instance_id": "neovasili__tflens-34", "base_commit": "8de85543fed8503e823b64b112dbbb292fc90d04", "gold_patch": "diff --git a/README.md b/README.md\nindex 4c1fad7..3b089dd 100644\n--- a/README.md\n+++ b/README.md\n@@ -76,6 +76,8 @@ optional arguments:\n according to the following pattern: bucket-name/tfstate-key\n -m FILTER_MODULE, --filter-module FILTER_MODULE\n Applies a regular expression to the module field in order to filter the resources list to output\n+ -n FILTER_NAME, --filter-name FILTER_NAME\n+ Applies a regular expression to the name field in order to filter the resources list to output\n ```\n \n ### Examples\n@@ -93,6 +95,16 @@ View table of resources for a tfstate located in the file system in the director\n \n View filtered table of resources for a tfstate located in the file system in the directory:\n \n+```bash\n+\u279c tflens --filter-name \"current\"\n+\n+| provider | type | mode | name | module |\n+|--------------|---------------------|---------|-------------------------------|--------|\n+| provider.aws | aws_caller_identity | data | current_user | test |\n+```\n+\n+Or:\n+\n ```bash\n \u279c tflens --filter-module \"test\"\n \n@@ -101,6 +113,16 @@ View filtered table of resources for a tfstate located in the file system in the\n | provider.aws | aws_caller_identity | data | current_user | test |\n ```\n \n+Or:\n+\n+```bash\n+\u279c tflens --filter-name \"current\" --filter-module \"test\"\n+\n+| provider | type | mode | name | module |\n+|--------------|---------------------|---------|-------------------------------|--------|\n+| provider.aws | aws_caller_identity | data | current_user | test |\n+```\n+\n View table of resources for a tfstate located in the file system in the `dev/terraform.tfstate.json` path:\n \n ```bash\ndiff --git a/tflens/__main__.py b/tflens/__main__.py\nindex 45b72cf..8991726 100644\n--- a/tflens/__main__.py\n+++ b/tflens/__main__.py\n@@ -43,12 +43,21 @@ parser.add_argument('-m', '--filter-module',\n filter the resources list to output\",\n default=\"\")\n \n+parser.add_argument('-n', '--filter-name',\n+ type=str,\n+ action=\"store\",\n+ dest=\"filter_name\",\n+ help=\"Applies a regular expression to the name field in order to \\\n+ filter the resources list to output\",\n+ default=\"\")\n+\n args = parser.parse_args()\n \n ARGS_REMOTE = args.remote\n ARGS_FILE_LOCATION = args.file_location\n ARGS_OUTPUT = args.output\n ARGS_FILTER_MODULE = args.filter_module\n+ARGS_FILTER_NAME = args.filter_name\n \n if not ARGS_FILE_LOCATION:\n ARGS_FILE_LOCATION = \"{}/terraform.tfstate\".format(Path().absolute())\n@@ -61,6 +70,7 @@ def main():\n \n tfstate_controller = remote_router[ARGS_REMOTE](\n file_location=ARGS_FILE_LOCATION,\n+ name_filter_expression=ARGS_FILTER_NAME,\n module_filter_expression=ARGS_FILTER_MODULE\n )\n \ndiff --git a/tflens/controller/tfstate.py b/tflens/controller/tfstate.py\nindex f4a58ec..7f0fec6 100644\n--- a/tflens/controller/tfstate.py\n+++ b/tflens/controller/tfstate.py\n@@ -11,11 +11,17 @@ from tflens.helper.filter import TfStateFilterHelper\n \n class TfStateController():\n \n- def __init__(self, tfstate_content: dict, module_filter_expression: str=None):\n+ def __init__(\n+ self,\n+ tfstate_content: dict,\n+ name_filter_expression: str=None,\n+ module_filter_expression: str=None\n+ ):\n self.__tfstate = TfState(\n content=tfstate_content\n )\n self.__resources = TfStateFilterHelper(\n+ name_filter_expression=name_filter_expression,\n module_filter_expression=module_filter_expression,\n resources=self.__tfstate.get_resources()\n ).apply_filter()\n@@ -43,24 +49,36 @@ class TfStateController():\n \n class LocalTfStateController(TfStateController):\n \n- def __init__(self, file_location: str, module_filter_expression: str=None):\n+ def __init__(\n+ self,\n+ file_location: str,\n+ module_filter_expression: str=None,\n+ name_filter_expression: str=None\n+ ):\n self.__local_tfstate_service = LocalTfStateService(\n file_location=file_location\n )\n \n super().__init__(\n tfstate_content=self.__local_tfstate_service.read_content(),\n+ name_filter_expression=name_filter_expression,\n module_filter_expression=module_filter_expression\n )\n \n class RemoteS3TfStateController(TfStateController):\n \n- def __init__(self, file_location: str, module_filter_expression: str=None):\n+ def __init__(\n+ self,\n+ file_location: str,\n+ module_filter_expression: str=None,\n+ name_filter_expression: str=None\n+ ):\n self.__remote_s3_tfstate_service = RemoteS3TfStateService(\n file_location=file_location\n )\n \n super().__init__(\n tfstate_content=self.__remote_s3_tfstate_service.read_content(),\n+ name_filter_expression=name_filter_expression,\n module_filter_expression=module_filter_expression\n )\ndiff --git a/tflens/helper/filter.py b/tflens/helper/filter.py\nindex 18343e2..d5cd16c 100644\n--- a/tflens/helper/filter.py\n+++ b/tflens/helper/filter.py\n@@ -16,12 +16,26 @@ class ModuleFilterHelper(FilterHelper):\n def __init__(self, filter_expression: str, resource: TfStateResource):\n super().__init__(\n filter_expression=filter_expression,\n- object_attribute_value = resource.get_parent_module()\n+ object_attribute_value=resource.get_parent_module()\n+ )\n+\n+class NameFilterHelper(FilterHelper):\n+\n+ def __init__(self, filter_expression: str, resource: TfStateResource):\n+ super().__init__(\n+ filter_expression=filter_expression,\n+ object_attribute_value=resource.get_name()\n )\n \n class TfStateFilterHelper():\n \n- def __init__(self, module_filter_expression: str=None, resources: list=None):\n+ def __init__(\n+ self,\n+ name_filter_expression: str=None,\n+ module_filter_expression: str=None,\n+ resources: list=None\n+ ):\n+ self.__name_filter_expression = name_filter_expression\n self.__module_filter_expression = module_filter_expression\n self.__resources = resources\n \n@@ -29,13 +43,18 @@ class TfStateFilterHelper():\n filtered_list = list()\n \n for resource in self.__resources or []:\n+ pass_name_filter = True\n pass_module_filter = True\n \n+ if self.__name_filter_expression:\n+ filter_helper = NameFilterHelper(filter_expression=self.__name_filter_expression, resource=resource)\n+ pass_name_filter = filter_helper.check_filter()\n+\n if self.__module_filter_expression:\n filter_helper = ModuleFilterHelper(filter_expression=self.__module_filter_expression, resource=resource)\n pass_module_filter = filter_helper.check_filter()\n \n- if pass_module_filter:\n+ if pass_module_filter and pass_name_filter:\n filtered_list.append(resource)\n \n return filtered_list\ndiff --git a/tflens/model/tfstate_resource.py b/tflens/model/tfstate_resource.py\nindex 09c839f..be6a07a 100644\n--- a/tflens/model/tfstate_resource.py\n+++ b/tflens/model/tfstate_resource.py\n@@ -27,6 +27,9 @@ class TfStateResource():\n self.get_parent_module()\n ]\n \n+ def get_name(self):\n+ return self.__name\n+\n def get_parent_module(self):\n return self.__module.split('.')[1] if self.__module else '-'\n \n", "test_patch": "diff --git a/tests/controllers_test.py b/tests/controllers_test.py\nindex e6925f8..61504b4 100644\n--- a/tests/controllers_test.py\n+++ b/tests/controllers_test.py\n@@ -92,6 +92,28 @@ class TestLocalTfStateController(unittest.TestCase):\n \n self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n \n+ def test_local_show_resources_matching_name_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ name_filter_expression=\"current_user\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), self.print_table_output)\n+\n+ def test_local_show_resources_not_matching_name_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ name_filter_expression=\"Current_user\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n+\n def test_local_create_markdown_file(self):\n local_tfstate_controller = LocalTfStateController(self.existing_file)\n local_tfstate_controller.create_markdown_file()\n", "FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_name_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_name_filter"]}, {"instance_id": "neovasili__tflens-35", "base_commit": "8fed041deb04b1abef816991fe185a7c0821c5ee", "gold_patch": "diff --git a/README.md b/README.md\nindex 3b089dd..b4b09a0 100644\n--- a/README.md\n+++ b/README.md\n@@ -78,6 +78,8 @@ optional arguments:\n Applies a regular expression to the module field in order to filter the resources list to output\n -n FILTER_NAME, --filter-name FILTER_NAME\n Applies a regular expression to the name field in order to filter the resources list to output\n+ -t FILTER_TYPE, --filter-type FILTER_TYPE\n+ Applies a regular expression to the type field in order to filter the resources list to output\n ```\n \n ### Examples\ndiff --git a/tflens/__main__.py b/tflens/__main__.py\nindex 8991726..f7f87a2 100644\n--- a/tflens/__main__.py\n+++ b/tflens/__main__.py\n@@ -51,6 +51,14 @@ parser.add_argument('-n', '--filter-name',\n filter the resources list to output\",\n default=\"\")\n \n+parser.add_argument('-t', '--filter-type',\n+ type=str,\n+ action=\"store\",\n+ dest=\"filter_type\",\n+ help=\"Applies a regular expression to the type field in order to \\\n+ filter the resources list to output\",\n+ default=\"\")\n+\n args = parser.parse_args()\n \n ARGS_REMOTE = args.remote\n@@ -58,6 +66,7 @@ ARGS_FILE_LOCATION = args.file_location\n ARGS_OUTPUT = args.output\n ARGS_FILTER_MODULE = args.filter_module\n ARGS_FILTER_NAME = args.filter_name\n+ARGS_FILTER_TYPE = args.filter_type\n \n if not ARGS_FILE_LOCATION:\n ARGS_FILE_LOCATION = \"{}/terraform.tfstate\".format(Path().absolute())\n@@ -71,6 +80,7 @@ def main():\n tfstate_controller = remote_router[ARGS_REMOTE](\n file_location=ARGS_FILE_LOCATION,\n name_filter_expression=ARGS_FILTER_NAME,\n+ type_filter_expression=ARGS_FILTER_TYPE,\n module_filter_expression=ARGS_FILTER_MODULE\n )\n \ndiff --git a/tflens/controller/tfstate.py b/tflens/controller/tfstate.py\nindex 7f0fec6..478c492 100644\n--- a/tflens/controller/tfstate.py\n+++ b/tflens/controller/tfstate.py\n@@ -15,6 +15,7 @@ class TfStateController():\n self,\n tfstate_content: dict,\n name_filter_expression: str=None,\n+ type_filter_expression: str=None,\n module_filter_expression: str=None\n ):\n self.__tfstate = TfState(\n@@ -22,6 +23,7 @@ class TfStateController():\n )\n self.__resources = TfStateFilterHelper(\n name_filter_expression=name_filter_expression,\n+ type_filter_expression=type_filter_expression,\n module_filter_expression=module_filter_expression,\n resources=self.__tfstate.get_resources()\n ).apply_filter()\n@@ -53,6 +55,7 @@ class LocalTfStateController(TfStateController):\n self,\n file_location: str,\n module_filter_expression: str=None,\n+ type_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__local_tfstate_service = LocalTfStateService(\n@@ -62,6 +65,7 @@ class LocalTfStateController(TfStateController):\n super().__init__(\n tfstate_content=self.__local_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n+ type_filter_expression=type_filter_expression,\n module_filter_expression=module_filter_expression\n )\n \n@@ -71,6 +75,7 @@ class RemoteS3TfStateController(TfStateController):\n self,\n file_location: str,\n module_filter_expression: str=None,\n+ type_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__remote_s3_tfstate_service = RemoteS3TfStateService(\n@@ -80,5 +85,6 @@ class RemoteS3TfStateController(TfStateController):\n super().__init__(\n tfstate_content=self.__remote_s3_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n+ type_filter_expression=type_filter_expression,\n module_filter_expression=module_filter_expression\n )\ndiff --git a/tflens/helper/filter.py b/tflens/helper/filter.py\nindex d5cd16c..f6ce147 100644\n--- a/tflens/helper/filter.py\n+++ b/tflens/helper/filter.py\n@@ -27,15 +27,25 @@ class NameFilterHelper(FilterHelper):\n object_attribute_value=resource.get_name()\n )\n \n+class TypeFilterHelper(FilterHelper):\n+\n+ def __init__(self, filter_expression: str, resource: TfStateResource):\n+ super().__init__(\n+ filter_expression=filter_expression,\n+ object_attribute_value=resource.get_type()\n+ )\n+\n class TfStateFilterHelper():\n \n def __init__(\n self,\n name_filter_expression: str=None,\n+ type_filter_expression: str=None,\n module_filter_expression: str=None,\n resources: list=None\n ):\n self.__name_filter_expression = name_filter_expression\n+ self.__type_filter_expression = type_filter_expression\n self.__module_filter_expression = module_filter_expression\n self.__resources = resources\n \n@@ -45,16 +55,21 @@ class TfStateFilterHelper():\n for resource in self.__resources or []:\n pass_name_filter = True\n pass_module_filter = True\n+ pass_type_filter = True\n \n if self.__name_filter_expression:\n filter_helper = NameFilterHelper(filter_expression=self.__name_filter_expression, resource=resource)\n pass_name_filter = filter_helper.check_filter()\n \n+ if self.__type_filter_expression:\n+ filter_helper = TypeFilterHelper(filter_expression=self.__type_filter_expression, resource=resource)\n+ pass_type_filter = filter_helper.check_filter()\n+\n if self.__module_filter_expression:\n filter_helper = ModuleFilterHelper(filter_expression=self.__module_filter_expression, resource=resource)\n pass_module_filter = filter_helper.check_filter()\n \n- if pass_module_filter and pass_name_filter:\n+ if pass_module_filter and pass_name_filter and pass_type_filter:\n filtered_list.append(resource)\n \n return filtered_list\ndiff --git a/tflens/model/tfstate_resource.py b/tflens/model/tfstate_resource.py\nindex be6a07a..afd3dbf 100644\n--- a/tflens/model/tfstate_resource.py\n+++ b/tflens/model/tfstate_resource.py\n@@ -30,6 +30,9 @@ class TfStateResource():\n def get_name(self):\n return self.__name\n \n+ def get_type(self):\n+ return self.__type\n+\n def get_parent_module(self):\n return self.__module.split('.')[1] if self.__module else '-'\n \n", "test_patch": "diff --git a/tests/controllers_test.py b/tests/controllers_test.py\nindex 61504b4..65f8078 100644\n--- a/tests/controllers_test.py\n+++ b/tests/controllers_test.py\n@@ -114,6 +114,28 @@ class TestLocalTfStateController(unittest.TestCase):\n \n self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n \n+ def test_local_show_resources_matching_type_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ type_filter_expression=\"aws_caller_identity\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), self.print_table_output)\n+\n+ def test_local_show_resources_not_matching_type_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ type_filter_expression=\"Aws_caller_identity\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n+\n def test_local_create_markdown_file(self):\n local_tfstate_controller = LocalTfStateController(self.existing_file)\n local_tfstate_controller.create_markdown_file()\n", "FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_type_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_type_filter"]}, {"instance_id": "neovasili__tflens-36", "base_commit": "ba81fda814f0f1401a79f52365d9ba1d3ca5799d", "gold_patch": "diff --git a/README.md b/README.md\nindex b4b09a0..5676c16 100644\n--- a/README.md\n+++ b/README.md\n@@ -80,6 +80,8 @@ optional arguments:\n Applies a regular expression to the name field in order to filter the resources list to output\n -t FILTER_TYPE, --filter-type FILTER_TYPE\n Applies a regular expression to the type field in order to filter the resources list to output\n+ -p FILTER_PROVIDER, --filter-provider FILTER_PROVIDER\n+ Applies a regular expression to the provider field in order to filter the resources list to output\n ```\n \n ### Examples\ndiff --git a/tflens/__main__.py b/tflens/__main__.py\nindex f7f87a2..fe1ca3d 100644\n--- a/tflens/__main__.py\n+++ b/tflens/__main__.py\n@@ -59,6 +59,14 @@ parser.add_argument('-t', '--filter-type',\n filter the resources list to output\",\n default=\"\")\n \n+parser.add_argument('-p', '--filter-provider',\n+ type=str,\n+ action=\"store\",\n+ dest=\"filter_provider\",\n+ help=\"Applies a regular expression to the provider field in order to \\\n+ filter the resources list to output\",\n+ default=\"\")\n+\n args = parser.parse_args()\n \n ARGS_REMOTE = args.remote\n@@ -67,6 +75,7 @@ ARGS_OUTPUT = args.output\n ARGS_FILTER_MODULE = args.filter_module\n ARGS_FILTER_NAME = args.filter_name\n ARGS_FILTER_TYPE = args.filter_type\n+ARGS_FILTER_PROVIDER = args.filter_provider\n \n if not ARGS_FILE_LOCATION:\n ARGS_FILE_LOCATION = \"{}/terraform.tfstate\".format(Path().absolute())\n@@ -81,6 +90,7 @@ def main():\n file_location=ARGS_FILE_LOCATION,\n name_filter_expression=ARGS_FILTER_NAME,\n type_filter_expression=ARGS_FILTER_TYPE,\n+ provider_filter_expression=ARGS_FILTER_PROVIDER,\n module_filter_expression=ARGS_FILTER_MODULE\n )\n \ndiff --git a/tflens/controller/tfstate.py b/tflens/controller/tfstate.py\nindex 478c492..0f4c7a5 100644\n--- a/tflens/controller/tfstate.py\n+++ b/tflens/controller/tfstate.py\n@@ -16,6 +16,7 @@ class TfStateController():\n tfstate_content: dict,\n name_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n module_filter_expression: str=None\n ):\n self.__tfstate = TfState(\n@@ -24,6 +25,7 @@ class TfStateController():\n self.__resources = TfStateFilterHelper(\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n+ provider_filter_expression=provider_filter_expression,\n module_filter_expression=module_filter_expression,\n resources=self.__tfstate.get_resources()\n ).apply_filter()\n@@ -56,6 +58,7 @@ class LocalTfStateController(TfStateController):\n file_location: str,\n module_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__local_tfstate_service = LocalTfStateService(\n@@ -66,6 +69,7 @@ class LocalTfStateController(TfStateController):\n tfstate_content=self.__local_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n+ provider_filter_expression=provider_filter_expression,\n module_filter_expression=module_filter_expression\n )\n \n@@ -76,6 +80,7 @@ class RemoteS3TfStateController(TfStateController):\n file_location: str,\n module_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__remote_s3_tfstate_service = RemoteS3TfStateService(\n@@ -86,5 +91,6 @@ class RemoteS3TfStateController(TfStateController):\n tfstate_content=self.__remote_s3_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n+ provider_filter_expression=provider_filter_expression,\n module_filter_expression=module_filter_expression\n )\ndiff --git a/tflens/helper/filter.py b/tflens/helper/filter.py\nindex f6ce147..ee86ff3 100644\n--- a/tflens/helper/filter.py\n+++ b/tflens/helper/filter.py\n@@ -35,17 +35,27 @@ class TypeFilterHelper(FilterHelper):\n object_attribute_value=resource.get_type()\n )\n \n+class ProviderFilterHelper(FilterHelper):\n+\n+ def __init__(self, filter_expression: str, resource: TfStateResource):\n+ super().__init__(\n+ filter_expression=filter_expression,\n+ object_attribute_value=resource.get_type()\n+ )\n+\n class TfStateFilterHelper():\n \n def __init__(\n self,\n name_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n module_filter_expression: str=None,\n resources: list=None\n ):\n self.__name_filter_expression = name_filter_expression\n self.__type_filter_expression = type_filter_expression\n+ self.__provider_filter_expression = provider_filter_expression\n self.__module_filter_expression = module_filter_expression\n self.__resources = resources\n \n@@ -56,6 +66,7 @@ class TfStateFilterHelper():\n pass_name_filter = True\n pass_module_filter = True\n pass_type_filter = True\n+ pass_provider_filter = True\n \n if self.__name_filter_expression:\n filter_helper = NameFilterHelper(filter_expression=self.__name_filter_expression, resource=resource)\n@@ -65,11 +76,15 @@ class TfStateFilterHelper():\n filter_helper = TypeFilterHelper(filter_expression=self.__type_filter_expression, resource=resource)\n pass_type_filter = filter_helper.check_filter()\n \n+ if self.__provider_filter_expression:\n+ filter_helper = ProviderFilterHelper(filter_expression=self.__provider_filter_expression, resource=resource)\n+ pass_provider_filter = filter_helper.check_filter()\n+\n if self.__module_filter_expression:\n filter_helper = ModuleFilterHelper(filter_expression=self.__module_filter_expression, resource=resource)\n pass_module_filter = filter_helper.check_filter()\n \n- if pass_module_filter and pass_name_filter and pass_type_filter:\n+ if pass_module_filter and pass_name_filter and pass_type_filter and pass_provider_filter:\n filtered_list.append(resource)\n \n return filtered_list\n", "test_patch": "diff --git a/tests/controllers_test.py b/tests/controllers_test.py\nindex 65f8078..b250a98 100644\n--- a/tests/controllers_test.py\n+++ b/tests/controllers_test.py\n@@ -136,6 +136,28 @@ class TestLocalTfStateController(unittest.TestCase):\n \n self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n \n+ def test_local_show_resources_matching_provider_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ provider_filter_expression=\"aws\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), self.print_table_output)\n+\n+ def test_local_show_resources_not_matching_provider_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ provider_filter_expression=\"Aws\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n+\n def test_local_create_markdown_file(self):\n local_tfstate_controller = LocalTfStateController(self.existing_file)\n local_tfstate_controller.create_markdown_file()\n", "FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_provider_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_provider_filter"]}], "all_FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_name_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_name_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_type_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_type_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_provider_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_provider_filter"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3425_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3425:latest", "base_commit": "5d4f148279d3881e27b041a6772b08cef0e8b3e6", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3425", "base_commit": "5d4f148279d3881e27b041a6772b08cef0e8b3e6", "gold_patch": "diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex 37915c86..66daba15 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -251,7 +251,7 @@ class MySQL(Dialect):\n \"@@\": TokenType.SESSION_PARAMETER,\n }\n \n- COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}\n+ COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.REPLACE} - {TokenType.SHOW}\n \n class Parser(parser.Parser):\n FUNC_TOKENS = {\ndiff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py\nindex 2e8ddf21..dc3424ef 100644\n--- a/sqlglot/dialects/tsql.py\n+++ b/sqlglot/dialects/tsql.py\n@@ -474,6 +474,8 @@ class TSQL(Dialect):\n \"OPTION\": TokenType.OPTION,\n }\n \n+ COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.END}\n+\n class Parser(parser.Parser):\n SET_REQUIRES_ASSIGNMENT_DELIMITER = False\n LOG_DEFAULTS_TO_LN = True\n@@ -524,11 +526,6 @@ class TSQL(Dialect):\n *parser.Parser.TYPE_TOKENS,\n }\n \n- STATEMENT_PARSERS = {\n- **parser.Parser.STATEMENT_PARSERS,\n- TokenType.END: lambda self: self._parse_command(),\n- }\n-\n def _parse_options(self) -> t.Optional[t.List[exp.Expression]]:\n if not self._match(TokenType.OPTION):\n return None\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 51022bbe..229af18a 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1471,7 +1471,7 @@ class Parser(metaclass=_Parser):\n if self._match_set(self.STATEMENT_PARSERS):\n return self.STATEMENT_PARSERS[self._prev.token_type](self)\n \n- if self._match_set(Tokenizer.COMMANDS):\n+ if self._match_set(self.dialect.tokenizer.COMMANDS):\n return self._parse_command()\n \n expression = self._parse_expression()\n", "test_patch": "diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py\nindex 53e2dab8..7bd17290 100644\n--- a/tests/dialects/test_mysql.py\n+++ b/tests/dialects/test_mysql.py\n@@ -148,6 +148,9 @@ class TestMySQL(Validator):\n self.validate_identity(\n \"SELECT * FROM t1, t2, t3 FOR SHARE OF t1 NOWAIT FOR UPDATE OF t2, t3 SKIP LOCKED\"\n )\n+ self.validate_identity(\n+ \"REPLACE INTO table SELECT id FROM table2 WHERE cnt > 100\", check_command_warning=True\n+ )\n self.validate_identity(\n \"\"\"SELECT * FROM foo WHERE 3 MEMBER OF(info->'$.value')\"\"\",\n \"\"\"SELECT * FROM foo WHERE 3 MEMBER OF(JSON_EXTRACT(info, '$.value'))\"\"\",\n", "FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_identity"]}, {"instance_id": "tobymao__sqlglot-3426", "base_commit": "e8014e2a479c37ef75510e7d5ca90ed30522ce60", "gold_patch": "diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 5a45215b..538cb9cb 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -345,6 +345,7 @@ class Snowflake(Dialect):\n \n FUNCTIONS = {\n **parser.Parser.FUNCTIONS,\n+ \"APPROX_PERCENTILE\": exp.ApproxQuantile.from_arg_list,\n \"ARRAYAGG\": exp.ArrayAgg.from_arg_list,\n \"ARRAY_CONSTRUCT\": exp.Array.from_arg_list,\n \"ARRAY_CONTAINS\": lambda args: exp.ArrayContains(\n@@ -1051,3 +1052,11 @@ class Snowflake(Dialect):\n return f\"{option} = ({values})\"\n \n return super().copyparameter_sql(expression)\n+\n+ def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:\n+ if expression.args.get(\"weight\") or expression.args.get(\"accuracy\"):\n+ self.unsupported(\n+ \"APPROX_PERCENTILE with weight and/or accuracy arguments are not supported in Snowflake\"\n+ )\n+\n+ return self.func(\"APPROX_PERCENTILE\", expression.this, expression.args.get(\"quantile\"))\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 62fa5974..d03412ca 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -832,6 +832,18 @@ WHERE\n \"snowflake\": \"SELECT LISTAGG(col1, ', ') WITHIN GROUP (ORDER BY col2) FROM t\",\n },\n )\n+ self.validate_all(\n+ \"SELECT APPROX_PERCENTILE(a, 0.5) FROM t\",\n+ read={\n+ \"trino\": \"SELECT APPROX_PERCENTILE(a, 1, 0.5, 0.001) FROM t\",\n+ \"presto\": \"SELECT APPROX_PERCENTILE(a, 1, 0.5, 0.001) FROM t\",\n+ },\n+ write={\n+ \"trino\": \"SELECT APPROX_PERCENTILE(a, 0.5) FROM t\",\n+ \"presto\": \"SELECT APPROX_PERCENTILE(a, 0.5) FROM t\",\n+ \"snowflake\": \"SELECT APPROX_PERCENTILE(a, 0.5) FROM t\",\n+ },\n+ )\n \n def test_null_treatment(self):\n self.validate_all(\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-3436", "base_commit": "30f9d30d8ab3727a43b1e6f363f28631cbfa7f92", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 229af18a..8f5050ee 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1678,6 +1678,7 @@ class Parser(metaclass=_Parser):\n index = self._index\n \n while self._curr:\n+ self._match(TokenType.COMMA)\n if self._match_text_seq(\"INCREMENT\"):\n self._match_text_seq(\"BY\")\n self._match_text_seq(\"=\")\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex d03412ca..c9150ff3 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -1223,6 +1223,14 @@ WHERE\n \"CREATE OR REPLACE FUNCTION my_udtf(foo BOOLEAN) RETURNS TABLE(col1 ARRAY(INT)) AS $$ WITH t AS (SELECT CAST([1, 2, 3] AS ARRAY(INT)) AS c) SELECT c FROM t $$\",\n \"CREATE OR REPLACE FUNCTION my_udtf(foo BOOLEAN) RETURNS TABLE (col1 ARRAY(INT)) AS ' WITH t AS (SELECT CAST([1, 2, 3] AS ARRAY(INT)) AS c) SELECT c FROM t '\",\n )\n+ self.validate_identity(\n+ \"CREATE SEQUENCE seq1 WITH START=1, INCREMENT=1 ORDER\",\n+ \"CREATE SEQUENCE seq1 START=1 INCREMENT BY 1 ORDER\",\n+ )\n+ self.validate_identity(\n+ \"CREATE SEQUENCE seq1 WITH START=1 INCREMENT=1 ORDER\",\n+ \"CREATE SEQUENCE seq1 START=1 INCREMENT=1 ORDER\",\n+ )\n \n self.validate_all(\n \"CREATE TABLE orders_clone CLONE orders\",\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_ddl"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_identity", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NREL__hescore-hpxml-131_x3", "level": 3, "source": "swerebench", "repo": "NREL/hescore-hpxml", "image": "swerebench/sweb.eval.x86_64.nrel_1776_hescore-hpxml-131:latest", "base_commit": "584a2bdd34ae66c6b0ae9507f30976ec5a222cab", "num_bugs": 3, "bugs": [{"instance_id": "NREL__hescore-hpxml-131", "base_commit": "584a2bdd34ae66c6b0ae9507f30976ec5a222cab", "gold_patch": "diff --git a/.gitignore b/.gitignore\nindex 3ce39c42..58094f71 100644\n--- a/.gitignore\n+++ b/.gitignore\n@@ -10,4 +10,5 @@ docs/build\n hescore_hpxml.egg-info\n dist\n build\n-\n+.env\n+.devcontainer\ndiff --git a/examples/house8.json b/examples/house8.json\nindex b87518e7..7f070bf4 100644\n--- a/examples/house8.json\n+++ b/examples/house8.json\n@@ -27,7 +27,7 @@\n \"roof_assembly_code\": \"rfwf00tg\",\n \"roof_color\": \"medium\",\n \"roof_type\": \"vented_attic\",\n- \"ceiling_assembly_code\": \"ecwf30\",\n+ \"ceiling_assembly_code\": \"ecwf38\",\n \"zone_skylight\": {\n \"skylight_area\": 0\n }\n@@ -63,40 +63,40 @@\n \"window_construction_same\": false,\n \"zone_wall\": [\n {\n- \"side\": \"back\",\n+ \"side\": \"front\",\n \"wall_assembly_code\": \"ewwf00wo\",\n \"zone_window\": {\n- \"window_area\": 220.0,\n+ \"window_area\": 180.0,\n \"window_method\": \"code\",\n \"window_code\": \"dpeaw\",\n \"solar_screen\": false\n }\n },\n {\n- \"side\": \"right\",\n+ \"side\": \"left\",\n \"wall_assembly_code\": \"ewwf00wo\",\n \"zone_window\": {\n- \"window_area\": 40.0,\n+ \"window_area\": 70.0,\n \"window_method\": \"code\",\n \"window_code\": \"dpeaw\",\n \"solar_screen\": false\n }\n },\n {\n- \"side\": \"front\",\n+ \"side\": \"back\",\n \"wall_assembly_code\": \"ewwf00wo\",\n \"zone_window\": {\n- \"window_area\": 180.0,\n+ \"window_area\": 220.0,\n \"window_method\": \"code\",\n \"window_code\": \"dpeaw\",\n \"solar_screen\": false\n }\n },\n {\n- \"side\": \"left\",\n+ \"side\": \"right\",\n \"wall_assembly_code\": \"ewwf00wo\",\n \"zone_window\": {\n- \"window_area\": 70.0,\n+ \"window_area\": 40.0,\n \"window_method\": \"code\",\n \"window_code\": \"dpeaw\",\n \"solar_screen\": false\ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 084ab53b..3dc254f5 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -376,6 +376,32 @@ class HPXMLtoHEScoreTranslatorBase(object):\n 'ground-to-air': 'gchp',\n 'ground-to-water': 'gchp'}\n \n+ def get_attic_knee_wall_rvalue_and_area(self, attic, b):\n+ knee_walls = self.get_attic_knee_walls(attic, b)\n+ if len(knee_walls) == 0:\n+ return 0, 0\n+ if len(knee_walls) == 1:\n+ knee_wall_r = convert_to_type(float, self.xpath(knee_walls[0], 'sum(h:Insulation/h:Layer/h:NominalRValue)'))\n+ knee_wall_area = convert_to_type(float, self.xpath(knee_walls[0], 'h:Area/text()'))\n+ return knee_wall_r, knee_wall_area\n+\n+ knee_wall_dict_ls = []\n+ for knee_wall in knee_walls:\n+ wall_area = convert_to_type(float, self.xpath(knee_wall, 'h:Area/text()'))\n+ if wall_area is None:\n+ raise TranslationError('All attic knee walls need an Area specified')\n+ rvalue = self.xpath(knee_wall, 'sum(h:Insulation/h:Layer/h:NominalRValue)')\n+ knee_wall_dict_ls.append({'area': wall_area, 'rvalue': rvalue})\n+ # Average\n+ knee_wall_area = sum(x['area'] for x in knee_wall_dict_ls)\n+ try:\n+ knee_wall_r = knee_wall_area / \\\n+ sum(x['area'] / x['rvalue'] for x in knee_wall_dict_ls)\n+ except ZeroDivisionError:\n+ knee_wall_r = 0\n+\n+ return knee_wall_r, knee_wall_area\n+\n def add_fuel_type(self, fuel_type):\n # Some fuel types are not included in fuel_type_mapping, throw an error if not mapped.\n try:\n@@ -1153,20 +1179,16 @@ class HPXMLtoHEScoreTranslatorBase(object):\n # attic floor center of cavity R-value\n attic_floor_rvalue = self.get_attic_floor_rvalue(attic, b)\n if knee_walls:\n- try:\n- knee_wall_ua = sum(x['area'] / x['rvalue'] for x in knee_walls)\n- except ZeroDivisionError:\n- knee_wall_ua = float('inf')\n- knee_wall_area = sum([x['area'] for x in knee_walls])\n- try:\n- attic_floor_adj_ua = knee_wall_ua + atticd['roof_area'] / attic_floor_rvalue\n- except ZeroDivisionError:\n- attic_floor_adj_ua = float('inf')\n+ knee_wall_rvalue, knee_wall_area = self.get_attic_knee_wall_rvalue_and_area(attic, b)\n+ knee_wall_coc_rvalue = knee_wall_rvalue + 0.5\n+ knee_wall_ua = knee_wall_area / knee_wall_coc_rvalue\n+\n+ attic_floor_coc_rvalue = attic_floor_rvalue + 0.5\n+ attic_floor_adj_ua = knee_wall_ua + atticd['roof_area'] / attic_floor_coc_rvalue\n attic_floor_adj_area = knee_wall_area + atticd['roof_area']\n- attic_floor_rvalue = attic_floor_adj_area / attic_floor_adj_ua\n+ attic_floor_rvalue = (attic_floor_adj_area / attic_floor_adj_ua) - 0.5\n atticd['roof_area'] = attic_floor_adj_area\n- atticd['attic_floor_coc_rvalue'] = \\\n- min(attic_floor_rvalues, key=lambda x: abs(x - attic_floor_rvalue)) + 0.5\n+ atticd['attic_floor_coc_rvalue'] = attic_floor_rvalue + 0.5\n \n if len(atticds) == 0:\n raise TranslationError('There are no Attic elements in this building.')\ndiff --git a/hescorehpxml/hpxml2.py b/hescorehpxml/hpxml2.py\nindex 2cb15f7c..fc0345f9 100644\n--- a/hescorehpxml/hpxml2.py\n+++ b/hescorehpxml/hpxml2.py\n@@ -54,12 +54,7 @@ class HPXML2toHEScoreTranslator(HPXMLtoHEScoreTranslatorBase):\n raise_err=True,\n kneewallid=kneewall_idref\n )\n- wall_rvalue = self.xpath(wall, 'sum(h:Insulation/h:Layer/h:NominalRValue)')\n- wall_area = self.xpath(wall, 'h:Area/text()')\n- if wall_area is None:\n- raise TranslationError('All attic knee walls need an Area specified')\n- wall_area = float(wall_area)\n- knee_walls.append({'area': wall_area, 'rvalue': wall_rvalue})\n+ knee_walls.append(wall)\n \n return knee_walls\n \ndiff --git a/hescorehpxml/hpxml3.py b/hescorehpxml/hpxml3.py\nindex 44bf7a71..9a227e76 100644\n--- a/hescorehpxml/hpxml3.py\n+++ b/hescorehpxml/hpxml3.py\n@@ -69,12 +69,7 @@ class HPXML3toHEScoreTranslator(HPXMLtoHEScoreTranslatorBase):\n raise_err=True,\n kneewallid=kneewall_idref\n )\n- wall_rvalue = self.xpath(wall, 'sum(h:Insulation/h:Layer/h:NominalRValue)')\n- wall_area = self.xpath(wall, 'h:Area/text()')\n- if wall_area is None:\n- raise TranslationError('All attic knee walls need an Area specified')\n- wall_area = float(wall_area)\n- knee_walls.append({'area': wall_area, 'rvalue': wall_rvalue})\n+ knee_walls.append(wall)\n \n return knee_walls\n \n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 669ae14e..50571e69 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -928,7 +928,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n kneewall_rvalue_el.text = '0'\n # run translation\n resp = tr.hpxml_to_hescore()\n- self.assertEqual(resp['building']['zone']['zone_roof'][0]['ceiling_assembly_code'], 'ecwf00')\n+ self.assertEqual(resp['building']['zone']['zone_roof'][0]['ceiling_assembly_code'], 'ecwf03')\n self.assertAlmostEqual(resp['building']['zone']['zone_roof'][0]['roof_area'], 1400.0)\n # Set kneewall R-value to 11 and attic floor R-value to zero\n kneewall_rvalue_el.text = '11'\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestOtherHouses::test_attic_knee_wall_zero_rvalue"]}, {"instance_id": "NREL__hescore-hpxml-137", "base_commit": "1bd1dd87237c00280c2150d96df6a33919659836", "gold_patch": "diff --git a/examples/house6.xml b/examples/house6.xml\nindex 0ab806c2..fdc7713d 100644\n--- a/examples/house6.xml\n+++ b/examples/house6.xml\n@@ -32,7 +32,7 @@\n single-family detached\n 2\n 8\n- 11\n+ 10\n 2600\n \n \ndiff --git a/examples/house6_v3.xml b/examples/house6_v3.xml\nindex 83d2f02f..c8c2c7d8 100644\n--- a/examples/house6_v3.xml\n+++ b/examples/house6_v3.xml\n@@ -32,7 +32,7 @@\n single-family detached\n 2\n 8\n- 11\n+ 10\n 2600\n \n \ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 3dc254f5..e8c9380b 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -927,8 +927,6 @@ class HPXMLtoHEScoreTranslatorBase(object):\n bldg_cons_el = xpath(b, 'h:BuildingDetails/h:BuildingSummary/h:BuildingConstruction', raise_err=True)\n bldg_about['year_built'] = int(xpath(bldg_cons_el, 'h:YearBuilt/text()', raise_err=True))\n nbedrooms = int(xpath(bldg_cons_el, 'h:NumberofBedrooms/text()', raise_err=True))\n- if nbedrooms > 10:\n- nbedrooms = 10\n bldg_about['number_bedrooms'] = nbedrooms\n bldg_about['num_floor_above_grade'] = int(\n math.ceil(float(xpath(bldg_cons_el, 'h:NumberofConditionedFloorsAboveGrade/text()', raise_err=True))))\n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 50571e69..5dd4fd65 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -1149,6 +1149,14 @@ class TestInputOutOfBounds(unittest.TestCase, ComparatorBase):\n 'num_floor_above_grade is out of bounds',\n tr.hpxml_to_hescore)\n \n+ def test_number_bedrooms(self):\n+ tr = self._load_xmlfile('hescore_min')\n+ el = self.xpath('//h:NumberofBedrooms')\n+ el.text = '25'\n+ self.assertRaisesRegex(InputOutOfBounds,\n+ 'number_bedrooms is out of bounds',\n+ tr.hpxml_to_hescore)\n+\n def test_floor_to_ceiling_height1(self):\n tr = self._load_xmlfile('hescore_min')\n el = self.xpath('//h:AverageCeilingHeight')\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestInputOutOfBounds::test_number_bedrooms"]}, {"instance_id": "NREL__hescore-hpxml-139", "base_commit": "1bd1dd87237c00280c2150d96df6a33919659836", "gold_patch": "diff --git a/docs/source/translation/zone_window.rst b/docs/source/translation/zone_window.rst\nindex 2275a2c5..22a50602 100644\n--- a/docs/source/translation/zone_window.rst\n+++ b/docs/source/translation/zone_window.rst\n@@ -36,7 +36,9 @@ window properties be assigned to each direction, the\n windows will be specified separately. \n \n Skylights in HEScore do not have an orientation that can be set, therefore\n-orientation/azimuth information about skylights is ignored.\n+orientation/azimuth information about skylights is ignored. Use `AttachedToRoof`\n+to specify which HPXML roof each skylight is attached to. If not specified, skylights\n+will be assigned to the first hescore roof.\n \n .. _window-prop:\n \ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 3dc254f5..07959248 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -758,9 +758,9 @@ class HPXMLtoHEScoreTranslatorBase(object):\n bldg['zone']['zone_floor'] = self.get_building_zone_floor(b, bldg['about'])\n footprint_area = self.get_footprint_area(bldg)\n bldg['zone']['zone_roof'] = self.get_building_zone_roof(b, footprint_area)\n- bldg['zone']['zone_roof'][0]['zone_skylight'] = self.get_skylights(b)\n- for zone_roof in bldg['zone']['zone_roof'][1:]:\n- zone_roof['zone_skylight'] = {'skylight_area': 0}\n+ skylights = self.get_skylights(b, bldg['zone']['zone_roof'])\n+ for roof_num in range(len(bldg['zone']['zone_roof'])):\n+ bldg['zone']['zone_roof'][roof_num]['zone_skylight'] = skylights[roof_num]\n bldg['zone']['wall_construction_same'] = False\n bldg['zone']['window_construction_same'] = False\n bldg['zone']['zone_wall'] = self.get_building_zone_wall(b, bldg['about'])\n@@ -1155,9 +1155,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n del atticd['roof_absorptance']\n \n # ids of hpxml roofs along for the ride\n- atticd['_roofid'] = ''\n- for attic_roofs_dict in attic_roof_ls:\n- atticd['_roofid'] += attic_roofs_dict['roof_id']\n+ atticd['_roofid'] = set([attic_roofs_dict['roof_id'] for attic_roofs_dict in attic_roof_ls])\n \n # Calculate roof area weighted center of cavity R-value for attic,\n # might be combined later by averaging again\n@@ -1194,7 +1192,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n raise TranslationError('There are no Attic elements in this building.')\n elif len(atticds) <= 2:\n for atticd in atticds:\n- atticd['_roofids'] = {atticd['_roofid']}\n+ atticd['_roofids'] = atticd['_roofid']\n del atticd['_roofid']\n elif len(atticds) > 2:\n # If there are more than two attics, combine and average by rooftype.\n@@ -1224,7 +1222,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n combined_atticd[attic_key] = max(roof_area_by_cat, key=lambda x: roof_area_by_cat[x])\n \n # ids of hpxml roofs along for the ride\n- combined_atticd['_roofids'] = set([atticd['_roofid'] for atticd in atticds])\n+ combined_atticd['_roofids'] = set().union(*[atticd['_roofid'] for atticd in atticds])\n \n # Calculate roof area weighted center of cavity R-value\n combined_atticd['roof_coc_rvalue'] = \\\n@@ -1274,70 +1272,102 @@ class HPXMLtoHEScoreTranslatorBase(object):\n \n return zone_roof\n \n- def get_skylights(self, b):\n+ def get_skylights(self, b, zone_roof):\n ns = self.ns\n xpath = self.xpath\n skylights = b.xpath('descendant::h:Skylight', namespaces=ns)\n \n- zone_skylight = OrderedDict()\n-\n- if len(skylights) == 0:\n- zone_skylight['skylight_area'] = 0\n- return zone_skylight\n-\n- # Get areas, u-factors, and shgcs if they exist\n- uvalues, shgcs, areas = map(list, zip(*[[xpath(skylight, 'h:%s/text()' % x)\n- for x in ('UFactor', 'SHGC', 'Area')]\n- for skylight in skylights]))\n- if None in areas:\n- raise TranslationError('Every skylight needs an area.')\n- areas = list(map(float, areas))\n- zone_skylight['skylight_area'] = sum(areas)\n-\n- # Remove skylights from the calculation where a uvalue or shgc isn't set.\n- idxstoremove = set()\n- for i, uvalue in enumerate(uvalues):\n- if uvalue is None:\n- idxstoremove.add(i)\n- for i, shgc in enumerate(shgcs):\n- if shgc is None:\n- idxstoremove.add(i)\n- for i in sorted(idxstoremove, reverse=True):\n- uvalues.pop(i)\n- shgcs.pop(i)\n- areas.pop(i)\n- assert len(uvalues) == len(shgcs)\n- uvalues = list(map(float, uvalues))\n- shgcs = list(map(float, shgcs))\n-\n- if len(uvalues) > 0:\n- # Use an area weighted average of the uvalues, shgcs\n- zone_skylight['skylight_method'] = 'custom'\n- zone_skylight['skylight_u_value'] = old_div(sum(\n- [uvalue * area for (uvalue, area) in zip(uvalues, areas)]), sum(areas))\n- zone_skylight['skylight_shgc'] = sum([shgc * area for (shgc, area) in zip(shgcs, areas)]) / sum(areas)\n- else:\n- # use a construction code\n- skylight_type_areas = {}\n+ skylight_by_roof_id = {}\n+ skylight_by_roof_num = {}\n+ for i in range(len(zone_roof)):\n+ skylight_by_roof_num[i] = []\n+\n+ for skylight in skylights:\n+ if xpath(skylight, 'h:AttachedToRoof/@idref') is None:\n+ # No roof attached, attach to the first roof\n+ skylight_by_roof_num[0].append(skylight)\n+ else:\n+ try:\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')].append(skylight)\n+ except KeyError:\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')] = []\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')].append(skylight)\n+\n+ for roof_id, skylights in list(skylight_by_roof_id.items()):\n+ # roof_found = False\n+ for i in range(len(zone_roof)):\n+ if roof_id in zone_roof[i]['_roofids']:\n+ # roof_found = True\n+ for skylight in skylights:\n+ skylight_by_roof_num[i].append(skylight)\n+ break\n+ # if not roof_found:\n+ # The roof attached is not simulated, should we: 1. attach to the first roof or 2. discard the skylight?\n+ # for skylight in skylights:\n+ # skylight_by_roof_num[0].append(skylight)\n+\n+ # combine skylights by roof_num\n+ zone_skylight = []\n+ for roof_num, skylights in list(skylight_by_roof_num.items()):\n+ skylight_d = OrderedDict()\n+ zone_skylight.append(skylight_d)\n+\n+ if len(skylights) == 0:\n+ skylight_d['skylight_area'] = 0\n+ continue\n+ # Get areas, u-factors, and shgcs if they exist\n+ uvalues, shgcs, areas = map(list, zip(*[[xpath(skylight, 'h:%s/text()' % x)\n+ for x in ('UFactor', 'SHGC', 'Area')]\n+ for skylight in skylights]))\n+ if None in areas:\n+ raise TranslationError('Every skylight needs an area.')\n+ areas = list(map(float, areas))\n+ skylight_d['skylight_area'] = sum(areas)\n+\n+ # Remove skylights from the calculation where a uvalue or shgc isn't set.\n+ idxstoremove = set()\n+ for i, uvalue in enumerate(uvalues):\n+ if uvalue is None:\n+ idxstoremove.add(i)\n+ for i, shgc in enumerate(shgcs):\n+ if shgc is None:\n+ idxstoremove.add(i)\n+ for i in sorted(idxstoremove, reverse=True):\n+ uvalues.pop(i)\n+ shgcs.pop(i)\n+ areas.pop(i)\n+ assert len(uvalues) == len(shgcs)\n+ uvalues = list(map(float, uvalues))\n+ shgcs = list(map(float, shgcs))\n+\n+ if len(uvalues) > 0:\n+ # Use an area weighted average of the uvalues, shgcs\n+ skylight_d['skylight_method'] = 'custom'\n+ skylight_d['skylight_u_value'] = old_div(sum(\n+ [uvalue * area for (uvalue, area) in zip(uvalues, areas)]), sum(areas))\n+ skylight_d['skylight_shgc'] = sum([shgc * area for (shgc, area) in zip(shgcs, areas)]) / sum(areas)\n+ else:\n+ # use a construction code\n+ skylight_type_areas = {}\n+ for skylight in skylights:\n+ area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n+ skylight_code = self.get_window_code(skylight)\n+ try:\n+ skylight_type_areas[skylight_code] += area\n+ except KeyError:\n+ skylight_type_areas[skylight_code] = area\n+ skylight_d['skylight_method'] = 'code'\n+ skylight_d['skylight_code'] = max(list(skylight_type_areas.items()), key=lambda x: x[1])[0]\n+ skylight_sunscreen_areas = {}\n for skylight in skylights:\n+ solar_screen = self.get_sunscreen(skylight)\n area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n- skylight_code = self.get_window_code(skylight)\n try:\n- skylight_type_areas[skylight_code] += area\n+ skylight_sunscreen_areas[solar_screen] += area\n except KeyError:\n- skylight_type_areas[skylight_code] = area\n- zone_skylight['skylight_method'] = 'code'\n- zone_skylight['skylight_code'] = max(list(skylight_type_areas.items()), key=lambda x: x[1])[0]\n- skylight_sunscreen_areas = {}\n- for skylight in skylights:\n- solar_screen = self.get_sunscreen(skylight)\n- area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n- try:\n- skylight_sunscreen_areas[solar_screen] += area\n- except KeyError:\n- skylight_sunscreen_areas[solar_screen] = area\n+ skylight_sunscreen_areas[solar_screen] = area\n \n- zone_skylight['solar_screen'] = max(list(skylight_sunscreen_areas.items()), key=lambda x: x[1])[0]\n+ skylight_d['solar_screen'] = max(list(skylight_sunscreen_areas.items()), key=lambda x: x[1])[0]\n \n return zone_skylight\n \n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 50571e69..b59531b7 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -2669,6 +2669,45 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n self.assertEqual(d_4['building']['systems']['hvac'], d_4_v3['building']['systems']['hvac'])\n \n \n+class TestHEScore2021Updates(unittest.TestCase, ComparatorBase):\n+\n+ def test_skylight_assignment(self):\n+ tr = self._load_xmlfile('house4_v3')\n+ attach_roof = etree.Element(tr.addns('h:AttachedToRoof'))\n+ attach_roof.attrib['idref'] = \"roof2\"\n+ glass_type = self.xpath('//h:Skylight/h:GlassType')\n+ glass_type.addnext(attach_roof)\n+ res = tr.hpxml_to_hescore()\n+ # Skylight attached to the second roof\n+ self.assertEqual(res['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 12.0)\n+ self.assertEqual(res['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+ skylight = self.xpath('//h:Skylight')\n+ skylight_2 = deepcopy(skylight)\n+ skylight.addnext(skylight_2)\n+ tr.xpath(skylight_2, 'h:SystemIdentifier').attrib['id'] = \"skylight2\"\n+ tr.xpath(skylight_2, 'h:AttachedToRoof').attrib['idref'] = \"roof1\"\n+ tr.xpath(skylight_2, 'h:Area').text = \"15\"\n+ res2 = tr.hpxml_to_hescore()\n+ # Skylight attached to the first and second roof\n+ self.assertEqual(res2['building']['zone']['zone_roof'][0]['zone_skylight']['skylight_area'], 15.0)\n+ self.assertEqual(res2['building']['zone']['zone_roof'][0]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res2['building']['zone']['zone_roof'][0]['zone_skylight']['solar_screen'])\n+ self.assertEqual(res2['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 12.0)\n+ self.assertEqual(res2['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res2['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+ tr.xpath(skylight_2, 'h:AttachedToRoof').attrib['idref'] = \"roof2\"\n+ tr.xpath(skylight_2, 'h:Area').text = \"10\"\n+ tr.xpath(skylight_2, 'h:GlassType').text = \"low-e\"\n+ # skylight1 dominates the properties\n+ res3 = tr.hpxml_to_hescore()\n+ self.assertEqual(res3['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 22.0)\n+ self.assertEqual(res3['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res3['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+\n class TestHEScoreV3(unittest.TestCase, ComparatorBase):\n \n def test_attic_with_multiple_roofs(self):\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestHEScore2021Updates::test_skylight_assignment"]}], "all_FAIL_TO_PASS": ["tests/test_translation.py::TestOtherHouses::test_attic_knee_wall_zero_rvalue", "tests/test_translation.py::TestInputOutOfBounds::test_number_bedrooms", "tests/test_translation.py::TestHEScore2021Updates::test_skylight_assignment"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-4218_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-4218:latest", "base_commit": "354cfff13ab30d01c6123fca74eed0669d238aa0", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-4218", "base_commit": "354cfff13ab30d01c6123fca74eed0669d238aa0", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 3528d110..77a06740 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -7054,7 +7054,7 @@ def update(\n )\n if with_:\n cte_list = [\n- CTE(this=maybe_parse(qry, dialect=dialect, **opts), alias=alias)\n+ alias_(CTE(this=maybe_parse(qry, dialect=dialect, **opts)), alias, table=True)\n for alias, qry in with_.items()\n ]\n update_expr.set(\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 28a8d4d7..38b7c6dd 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1196,7 +1196,11 @@ class Generator(metaclass=_Generator):\n return f\"WITH {recursive}{sql}\"\n \n def cte_sql(self, expression: exp.CTE) -> str:\n- alias = self.sql(expression, \"alias\")\n+ alias = expression.args.get(\"alias\")\n+ if alias:\n+ alias.add_comments(expression.pop_comments())\n+\n+ alias_sql = self.sql(expression, \"alias\")\n \n materialized = expression.args.get(\"materialized\")\n if materialized is False:\n@@ -1204,7 +1208,7 @@ class Generator(metaclass=_Generator):\n elif materialized:\n materialized = \"MATERIALIZED \"\n \n- return f\"{alias} AS {materialized or ''}{self.wrap(expression)}\"\n+ return f\"{alias_sql} AS {materialized or ''}{self.wrap(expression)}\"\n \n def tablealias_sql(self, expression: exp.TableAlias) -> str:\n alias = self.sql(expression, \"this\")\n@@ -2517,6 +2521,11 @@ class Generator(metaclass=_Generator):\n self.sql(expression, \"from\", comment=False),\n )\n \n+ # If both the CTE and SELECT clauses have comments, generate the latter earlier\n+ if expression.args.get(\"with\"):\n+ sql = self.maybe_comment(sql, expression)\n+ expression.pop_comments()\n+\n sql = self.prepend_ctes(expression, sql)\n \n if not self.SUPPORTS_SELECT_INTO and into:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 87a1579d..b69cfcb7 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3030,15 +3030,20 @@ class Parser(metaclass=_Parser):\n comments = self._prev_comments\n recursive = self._match(TokenType.RECURSIVE)\n \n+ last_comments = None\n expressions = []\n while True:\n expressions.append(self._parse_cte())\n+ if last_comments:\n+ expressions[-1].add_comments(last_comments)\n \n if not self._match(TokenType.COMMA) and not self._match(TokenType.WITH):\n break\n else:\n self._match(TokenType.WITH)\n \n+ last_comments = self._prev_comments\n+\n return self.expression(\n exp.With, comments=comments, expressions=expressions, recursive=recursive\n )\n", "test_patch": "diff --git a/tests/test_transpile.py b/tests/test_transpile.py\nindex 07a915d3..e7f1665f 100644\n--- a/tests/test_transpile.py\n+++ b/tests/test_transpile.py\n@@ -563,7 +563,36 @@ FROM x\"\"\",\n )\n self.validate(\n \"\"\"with a as /* comment */ ( select * from b) select * from a\"\"\",\n- \"\"\"WITH a AS (SELECT * FROM b) /* comment */ SELECT * FROM a\"\"\",\n+ \"\"\"WITH a /* comment */ AS (SELECT * FROM b) SELECT * FROM a\"\"\",\n+ )\n+ self.validate(\n+ \"\"\"\n+ -- comment at the top\n+WITH\n+-- comment for tbl1\n+tbl1 AS (SELECT 1)\n+-- comment for tbl2\n+, tbl2 AS (SELECT 2)\n+-- comment for tbl3\n+, tbl3 AS (SELECT 3)\n+-- comment for final select\n+SELECT * FROM tbl1\"\"\",\n+ \"\"\"/* comment at the top */\n+WITH tbl1 /* comment for tbl1 */ AS (\n+ SELECT\n+ 1\n+), tbl2 /* comment for tbl2 */ AS (\n+ SELECT\n+ 2\n+), tbl3 /* comment for tbl3 */ AS (\n+ SELECT\n+ 3\n+)\n+/* comment for final select */\n+SELECT\n+ *\n+FROM tbl1\"\"\",\n+ pretty=True,\n )\n \n def test_types(self):\n", "FAIL_TO_PASS": ["tests/test_transpile.py::TestTranspile::test_comments"]}, {"instance_id": "tobymao__sqlglot-4239", "base_commit": "b26a3f67b7113802ba1b4b3b211431e98258dc15", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 46f88368..36b13100 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4477,7 +4477,11 @@ class Parser(metaclass=_Parser):\n elif not self._match(TokenType.R_BRACKET, expression=this):\n self.raise_error(\"Expecting ]\")\n else:\n- this = self.expression(exp.In, this=this, field=self._parse_field())\n+ field = self._parse_field()\n+ if isinstance(field, exp.Identifier):\n+ field = exp.Column(this=field)\n+\n+ this = self.expression(exp.In, this=this, field=field)\n \n return this\n \n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 6b58934c..02b58b24 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -256,6 +256,7 @@ class TestDuckDB(Validator):\n parse_one(\"a // b\", read=\"duckdb\").assert_is(exp.IntDiv).sql(dialect=\"duckdb\"), \"a // b\"\n )\n \n+ self.validate_identity(\"'red' IN flags\").args[\"field\"].assert_is(exp.Column)\n self.validate_identity(\"CREATE TABLE tbl1 (u UNION(num INT, str TEXT))\")\n self.validate_identity(\"INSERT INTO x BY NAME SELECT 1 AS y\")\n self.validate_identity(\"SELECT 1 AS x UNION ALL BY NAME SELECT 2 AS x\")\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"]}, {"instance_id": "tobymao__sqlglot-4252", "base_commit": "94013a21ca69b90da78dc47b16cd86503736597a", "gold_patch": "diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py\nindex 2e26cb46..707af0c9 100644\n--- a/sqlglot/dialects/dialect.py\n+++ b/sqlglot/dialects/dialect.py\n@@ -1697,3 +1697,18 @@ def build_regexp_extract(args: t.List, dialect: Dialect) -> exp.RegexpExtract:\n expression=seq_get(args, 1),\n group=seq_get(args, 2) or exp.Literal.number(dialect.REGEXP_EXTRACT_DEFAULT_GROUP),\n )\n+\n+\n+def explode_to_unnest_sql(self: Generator, expression: exp.Lateral) -> str:\n+ if isinstance(expression.this, exp.Explode):\n+ return self.sql(\n+ exp.Join(\n+ this=exp.Unnest(\n+ expressions=[expression.this.this],\n+ alias=expression.args.get(\"alias\"),\n+ offset=isinstance(expression.this, exp.Posexplode),\n+ ),\n+ kind=\"cross\",\n+ )\n+ )\n+ return self.lateral_sql(expression)\ndiff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py\nindex c32dd083..4a2460f5 100644\n--- a/sqlglot/dialects/duckdb.py\n+++ b/sqlglot/dialects/duckdb.py\n@@ -35,6 +35,7 @@ from sqlglot.dialects.dialect import (\n unit_to_str,\n sha256_sql,\n build_regexp_extract,\n+ explode_to_unnest_sql,\n )\n from sqlglot.helper import seq_get\n from sqlglot.tokens import TokenType\n@@ -538,6 +539,7 @@ class DuckDB(Dialect):\n exp.JSONExtract: _arrow_json_extract_sql,\n exp.JSONExtractScalar: _arrow_json_extract_sql,\n exp.JSONFormat: _json_format_sql,\n+ exp.Lateral: explode_to_unnest_sql,\n exp.LogicalOr: rename_func(\"BOOL_OR\"),\n exp.LogicalAnd: rename_func(\"BOOL_AND\"),\n exp.MD5Digest: lambda self, e: self.func(\"UNHEX\", self.func(\"MD5\", e.this)),\ndiff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py\nindex 6cce854b..09607ada 100644\n--- a/sqlglot/dialects/presto.py\n+++ b/sqlglot/dialects/presto.py\n@@ -30,6 +30,7 @@ from sqlglot.dialects.dialect import (\n unit_to_str,\n sequence_sql,\n build_regexp_extract,\n+ explode_to_unnest_sql,\n )\n from sqlglot.dialects.hive import Hive\n from sqlglot.dialects.mysql import MySQL\n@@ -40,21 +41,6 @@ from sqlglot.transforms import unqualify_columns\n DATE_ADD_OR_SUB = t.Union[exp.DateAdd, exp.TimestampAdd, exp.DateSub]\n \n \n-def _explode_to_unnest_sql(self: Presto.Generator, expression: exp.Lateral) -> str:\n- if isinstance(expression.this, exp.Explode):\n- return self.sql(\n- exp.Join(\n- this=exp.Unnest(\n- expressions=[expression.this.this],\n- alias=expression.args.get(\"alias\"),\n- offset=isinstance(expression.this, exp.Posexplode),\n- ),\n- kind=\"cross\",\n- )\n- )\n- return self.lateral_sql(expression)\n-\n-\n def _initcap_sql(self: Presto.Generator, expression: exp.Initcap) -> str:\n regex = r\"(\\w)(\\w*)\"\n return f\"REGEXP_REPLACE({self.sql(expression, 'this')}, '{regex}', x -> UPPER(x[1]) || LOWER(x[2]))\"\n@@ -410,7 +396,7 @@ class Presto(Dialect):\n exp.Last: _first_last_sql,\n exp.LastValue: _first_last_sql,\n exp.LastDay: lambda self, e: self.func(\"LAST_DAY_OF_MONTH\", e.this),\n- exp.Lateral: _explode_to_unnest_sql,\n+ exp.Lateral: explode_to_unnest_sql,\n exp.Left: left_to_substring_sql,\n exp.Levenshtein: rename_func(\"LEVENSHTEIN_DISTANCE\"),\n exp.LogicalAnd: rename_func(\"BOOL_AND\"),\n", "test_patch": "diff --git a/tests/dialects/test_hive.py b/tests/dialects/test_hive.py\nindex 136ea605..e40a85af 100644\n--- a/tests/dialects/test_hive.py\n+++ b/tests/dialects/test_hive.py\n@@ -187,6 +187,7 @@ class TestHive(Validator):\n \"SELECT a, b FROM x LATERAL VIEW EXPLODE(y) t AS a LATERAL VIEW EXPLODE(z) u AS b\",\n write={\n \"presto\": \"SELECT a, b FROM x CROSS JOIN UNNEST(y) AS t(a) CROSS JOIN UNNEST(z) AS u(b)\",\n+ \"duckdb\": \"SELECT a, b FROM x CROSS JOIN UNNEST(y) AS t(a) CROSS JOIN UNNEST(z) AS u(b)\",\n \"hive\": \"SELECT a, b FROM x LATERAL VIEW EXPLODE(y) t AS a LATERAL VIEW EXPLODE(z) u AS b\",\n \"spark\": \"SELECT a, b FROM x LATERAL VIEW EXPLODE(y) t AS a LATERAL VIEW EXPLODE(z) u AS b\",\n },\n@@ -195,6 +196,7 @@ class TestHive(Validator):\n \"SELECT a FROM x LATERAL VIEW EXPLODE(y) t AS a\",\n write={\n \"presto\": \"SELECT a FROM x CROSS JOIN UNNEST(y) AS t(a)\",\n+ \"duckdb\": \"SELECT a FROM x CROSS JOIN UNNEST(y) AS t(a)\",\n \"hive\": \"SELECT a FROM x LATERAL VIEW EXPLODE(y) t AS a\",\n \"spark\": \"SELECT a FROM x LATERAL VIEW EXPLODE(y) t AS a\",\n },\n@@ -211,6 +213,7 @@ class TestHive(Validator):\n \"SELECT a FROM x LATERAL VIEW EXPLODE(ARRAY(y)) t AS a\",\n write={\n \"presto\": \"SELECT a FROM x CROSS JOIN UNNEST(ARRAY[y]) AS t(a)\",\n+ \"duckdb\": \"SELECT a FROM x CROSS JOIN UNNEST([y]) AS t(a)\",\n \"hive\": \"SELECT a FROM x LATERAL VIEW EXPLODE(ARRAY(y)) t AS a\",\n \"spark\": \"SELECT a FROM x LATERAL VIEW EXPLODE(ARRAY(y)) t AS a\",\n },\n", "FAIL_TO_PASS": ["tests/dialects/test_hive.py::TestHive::test_lateral_view"]}], "all_FAIL_TO_PASS": ["tests/test_transpile.py::TestTranspile::test_comments", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_hive.py::TestHive::test_lateral_view"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3745_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3745:latest", "base_commit": "44977e97e4188322b92eb1269aa321aa689f2dcf", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3745", "base_commit": "44977e97e4188322b92eb1269aa321aa689f2dcf", "gold_patch": "diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py\nindex fd03798b..e6fcf356 100644\n--- a/sqlglot/dialects/bigquery.py\n+++ b/sqlglot/dialects/bigquery.py\n@@ -735,6 +735,13 @@ class BigQuery(Dialect):\n exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,\n }\n \n+ # WINDOW comes after QUALIFY\n+ # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#window_clause\n+ AFTER_HAVING_MODIFIER_TRANSFORMS = {\n+ \"qualify\": generator.Generator.AFTER_HAVING_MODIFIER_TRANSFORMS[\"qualify\"],\n+ \"windows\": generator.Generator.AFTER_HAVING_MODIFIER_TRANSFORMS[\"windows\"],\n+ }\n+\n # from: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#reserved_keywords\n RESERVED_KEYWORDS = {\n \"all\",\ndiff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 75217499..3841ea64 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -2,7 +2,7 @@ from __future__ import annotations\n \n import typing as t\n \n-from sqlglot import exp, generator, parser, tokens, transforms\n+from sqlglot import exp, generator, parser, tokens\n from sqlglot.dialects.dialect import (\n Dialect,\n arg_max_or_min_no_count,\n@@ -789,7 +789,6 @@ class ClickHouse(Dialect):\n exp.Quantile: _quantile_sql,\n exp.RegexpLike: lambda self, e: self.func(\"match\", e.this, e.expression),\n exp.Rand: rename_func(\"randCanonical\"),\n- exp.Select: transforms.preprocess([transforms.eliminate_qualify]),\n exp.StartsWith: rename_func(\"startsWith\"),\n exp.StrPosition: lambda self, e: self.func(\n \"position\", e.this, e.args.get(\"substr\"), e.args.get(\"position\")\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex c2a6c557..482e5f34 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -406,13 +406,13 @@ class Generator(metaclass=_Generator):\n AFTER_HAVING_MODIFIER_TRANSFORMS = {\n \"cluster\": lambda self, e: self.sql(e, \"cluster\"),\n \"distribute\": lambda self, e: self.sql(e, \"distribute\"),\n- \"qualify\": lambda self, e: self.sql(e, \"qualify\"),\n \"sort\": lambda self, e: self.sql(e, \"sort\"),\n \"windows\": lambda self, e: (\n self.seg(\"WINDOW \") + self.expressions(e, key=\"windows\", flat=True)\n if e.args.get(\"windows\")\n else \"\"\n ),\n+ \"qualify\": lambda self, e: self.sql(e, \"qualify\"),\n }\n \n TOKEN_MAPPING: t.Dict[TokenType, str] = {}\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex ef84d488..a31cc24a 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -83,6 +83,9 @@ class TestClickhouse(Validator):\n self.validate_identity(\"TRUNCATE TABLE t1 ON CLUSTER test_cluster\")\n self.validate_identity(\"TRUNCATE DATABASE db\")\n self.validate_identity(\"TRUNCATE DATABASE db ON CLUSTER test_cluster\")\n+ self.validate_identity(\n+ \"SELECT number, COUNT() OVER (PARTITION BY number % 3) AS partition_count FROM numbers(10) WINDOW window_name AS (PARTITION BY number) QUALIFY partition_count = 4 ORDER BY number\"\n+ )\n self.validate_identity(\n \"SELECT id, quantileGK(100, 0.95)(reading) OVER (PARTITION BY id ORDER BY id RANGE BETWEEN 30000 PRECEDING AND CURRENT ROW) AS window FROM table\"\n )\ndiff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py\nindex c0afb2f4..44839e9e 100644\n--- a/tests/dialects/test_dialect.py\n+++ b/tests/dialects/test_dialect.py\n@@ -2267,7 +2267,7 @@ SELECT\n write={\n \"duckdb\": \"SELECT * FROM t QUALIFY COUNT(*) OVER () > 1\",\n \"snowflake\": \"SELECT * FROM t QUALIFY COUNT(*) OVER () > 1\",\n- \"clickhouse\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n+ \"clickhouse\": \"SELECT * FROM t QUALIFY COUNT(*) OVER () > 1\",\n \"mysql\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n \"oracle\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) _t WHERE _w > 1\",\n \"postgres\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n@@ -2279,7 +2279,7 @@ SELECT\n write={\n \"duckdb\": 'SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\" FROM t QUALIFY COUNT(*) OVER () > 1',\n \"snowflake\": 'SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\" FROM t QUALIFY COUNT(*) OVER () > 1',\n- \"clickhouse\": 'SELECT \"user id\", some_id, other_id, \"2 nd id\" FROM (SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\", COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1',\n+ \"clickhouse\": 'SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\" FROM t QUALIFY COUNT(*) OVER () > 1',\n \"mysql\": \"SELECT `user id`, some_id, other_id, `2 nd id` FROM (SELECT `user id`, some_id, 1 AS other_id, 2 AS `2 nd id`, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n \"oracle\": 'SELECT \"user id\", some_id, other_id, \"2 nd id\" FROM (SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\", COUNT(*) OVER () AS _w FROM t) _t WHERE _w > 1',\n \"postgres\": 'SELECT \"user id\", some_id, other_id, \"2 nd id\" FROM (SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\", COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1',\ndiff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex e0b0131f..395cbe65 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -361,6 +361,10 @@ class TestDuckDB(Validator):\n self.validate_identity(\n \"SELECT * FROM (PIVOT Cities ON Year USING SUM(Population) GROUP BY Country) AS pivot_alias\"\n )\n+ self.validate_identity(\n+ # QUALIFY comes after WINDOW\n+ \"SELECT schema_name, function_name, ROW_NUMBER() OVER my_window AS function_rank FROM DUCKDB_FUNCTIONS() WINDOW my_window AS (PARTITION BY schema_name ORDER BY function_name) QUALIFY ROW_NUMBER() OVER my_window < 3\"\n+ )\n self.validate_identity(\"DATE_SUB('YEAR', col, '2020-01-01')\").assert_is(exp.Anonymous)\n self.validate_identity(\"DATESUB('YEAR', col, '2020-01-01')\").assert_is(exp.Anonymous)\n \n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_dialect.py::TestDialect::test_qualify", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"]}, {"instance_id": "tobymao__sqlglot-3756", "base_commit": "15ca924ac6e8a72396a882c394856e466cae9ac3", "gold_patch": "diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py\nindex da212869..3ba72ea7 100644\n--- a/sqlglot/dialects/dialect.py\n+++ b/sqlglot/dialects/dialect.py\n@@ -356,6 +356,11 @@ class Dialect(metaclass=_Dialect):\n EXPAND_ALIAS_REFS_EARLY_ONLY_IN_GROUP_BY = False\n \"\"\"Whether alias reference expansion before qualification should only happen for the GROUP BY clause.\"\"\"\n \n+ SUPPORTS_ORDER_BY_ALL = False\n+ \"\"\"\n+ Whether ORDER BY ALL is supported (expands to all the selected columns) as in DuckDB, Spark3/Databricks\n+ \"\"\"\n+\n # --- Autofilled ---\n \n tokenizer_class = Tokenizer\ndiff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py\nindex c8313054..0f3c9ee3 100644\n--- a/sqlglot/dialects/duckdb.py\n+++ b/sqlglot/dialects/duckdb.py\n@@ -172,6 +172,7 @@ class DuckDB(Dialect):\n SAFE_DIVISION = True\n INDEX_OFFSET = 1\n CONCAT_COALESCE = True\n+ SUPPORTS_ORDER_BY_ALL = True\n \n # https://duckdb.org/docs/sql/introduction.html#creating-a-new-table\n NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE\ndiff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py\nindex 2f2ec878..623aaba7 100644\n--- a/sqlglot/dialects/spark.py\n+++ b/sqlglot/dialects/spark.py\n@@ -90,6 +90,8 @@ def _dateadd_sql(self: Spark.Generator, expression: exp.TsOrDsAdd | exp.Timestam\n \n \n class Spark(Spark2):\n+ SUPPORTS_ORDER_BY_ALL = True\n+\n class Tokenizer(Spark2.Tokenizer):\n STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = False\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 482e5f34..c2ad9ade 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -512,6 +512,7 @@ class Generator(metaclass=_Generator):\n \n # Expressions whose comments are separated from them for better formatting\n WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (\n+ exp.Command,\n exp.Create,\n exp.Delete,\n exp.Drop,\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 2718a135..f9ec3fd4 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1478,7 +1478,10 @@ class Parser(metaclass=_Parser):\n def _parse_command(self) -> exp.Command:\n self._warn_unsupported()\n return self.expression(\n- exp.Command, this=self._prev.text.upper(), expression=self._parse_string()\n+ exp.Command,\n+ comments=self._prev_comments,\n+ this=self._prev.text.upper(),\n+ expression=self._parse_string(),\n )\n \n def _try_parse(self, parse_method: t.Callable[[], T], retreat: bool = False) -> t.Optional[T]:\n@@ -3842,6 +3845,9 @@ class Parser(metaclass=_Parser):\n if not this:\n return None\n \n+ if this.name.upper() == \"ALL\" and self.dialect.SUPPORTS_ORDER_BY_ALL:\n+ this = exp.var(\"ALL\")\n+\n asc = self._match(TokenType.ASC)\n desc = self._match(TokenType.DESC) or (asc and False)\n \n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 803ac11a..75be8480 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -1427,6 +1427,12 @@ WHERE\n transpile(\"DATE_ADD(x, day)\", read=\"bigquery\")\n \n def test_warnings(self):\n+ with self.assertLogs(parser_logger) as cm:\n+ self.validate_identity(\n+ \"/* some comment */ DECLARE foo DATE DEFAULT DATE_SUB(current_date, INTERVAL 2 day)\"\n+ )\n+ self.assertIn(\"contains unsupported syntax\", cm.output[0])\n+\n with self.assertLogs(helper_logger) as cm:\n self.validate_identity(\n \"WITH cte(c) AS (SELECT * FROM t) SELECT * FROM cte\",\ndiff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py\nindex 44839e9e..a6ac69a7 100644\n--- a/tests/dialects/test_dialect.py\n+++ b/tests/dialects/test_dialect.py\n@@ -1164,6 +1164,13 @@ class TestDialect(Validator):\n },\n )\n \n+ order_by_all_sql = \"SELECT * FROM t ORDER BY ALL\"\n+ self.validate_identity(order_by_all_sql).find(exp.Ordered).this.assert_is(exp.Column)\n+\n+ for dialect in (\"duckdb\", \"spark\", \"databricks\"):\n+ with self.subTest(f\"Testing ORDER BY ALL in {dialect}\"):\n+ parse_one(order_by_all_sql, read=dialect).find(exp.Ordered).this.assert_is(exp.Var)\n+\n def test_json(self):\n self.validate_all(\n \"\"\"JSON_EXTRACT(x, '$[\"a b\"]')\"\"\",\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_warnings", "tests/dialects/test_dialect.py::TestDialect::test_order_by"]}, {"instance_id": "tobymao__sqlglot-3765", "base_commit": "5df3f5292488df6a8e21abf3b49086c823797e78", "gold_patch": "diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py\nindex e79014d8..44ea12bb 100644\n--- a/sqlglot/dialects/presto.py\n+++ b/sqlglot/dialects/presto.py\n@@ -35,6 +35,8 @@ from sqlglot.helper import apply_index_offset, seq_get\n from sqlglot.tokens import TokenType\n from sqlglot.transforms import unqualify_columns\n \n+DATE_ADD_OR_SUB = t.Union[exp.DateAdd, exp.TimestampAdd, exp.DateSub]\n+\n \n def _explode_to_unnest_sql(self: Presto.Generator, expression: exp.Lateral) -> str:\n if isinstance(expression.this, exp.Explode):\n@@ -223,6 +225,21 @@ def _build_to_char(args: t.List) -> exp.TimeToStr:\n return build_formatted_time(exp.TimeToStr, \"teradata\")(args)\n \n \n+def _date_delta_sql(\n+ name: str, negate_interval: bool = False\n+) -> t.Callable[[Presto.Generator, DATE_ADD_OR_SUB], str]:\n+ def _delta_sql(self: Presto.Generator, expression: DATE_ADD_OR_SUB) -> str:\n+ interval = _to_int(expression.expression)\n+ return self.func(\n+ name,\n+ unit_to_str(expression),\n+ interval * (-1) if negate_interval else interval,\n+ expression.this,\n+ )\n+\n+ return _delta_sql\n+\n+\n class Presto(Dialect):\n INDEX_OFFSET = 1\n NULL_ORDERING = \"nulls_are_last\"\n@@ -385,24 +402,14 @@ class Presto(Dialect):\n exp.BitwiseXor: lambda self, e: self.func(\"BITWISE_XOR\", e.this, e.expression),\n exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]),\n exp.CurrentTimestamp: lambda *_: \"CURRENT_TIMESTAMP\",\n- exp.DateAdd: lambda self, e: self.func(\n- \"DATE_ADD\",\n- unit_to_str(e),\n- _to_int(e.expression),\n- e.this,\n- ),\n+ exp.DateAdd: _date_delta_sql(\"DATE_ADD\"),\n exp.DateDiff: lambda self, e: self.func(\n \"DATE_DIFF\", unit_to_str(e), e.expression, e.this\n ),\n exp.DateStrToDate: datestrtodate_sql,\n exp.DateToDi: lambda self,\n e: f\"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.DATEINT_FORMAT}) AS INT)\",\n- exp.DateSub: lambda self, e: self.func(\n- \"DATE_ADD\",\n- unit_to_str(e),\n- _to_int(e.expression * -1),\n- e.this,\n- ),\n+ exp.DateSub: _date_delta_sql(\"DATE_ADD\", negate_interval=True),\n exp.Decode: lambda self, e: encode_decode_sql(self, e, \"FROM_UTF8\"),\n exp.DiToDate: lambda self,\n e: f\"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.DATEINT_FORMAT}) AS DATE)\",\n@@ -451,6 +458,7 @@ class Presto(Dialect):\n exp.StructExtract: struct_extract_sql,\n exp.Table: transforms.preprocess([_unnest_sequence]),\n exp.Timestamp: no_timestamp_sql,\n+ exp.TimestampAdd: _date_delta_sql(\"DATE_ADD\"),\n exp.TimestampTrunc: timestamptrunc_sql(),\n exp.TimeStrToDate: timestrtotime_sql,\n exp.TimeStrToTime: timestrtotime_sql,\n", "test_patch": "diff --git a/tests/dialects/test_presto.py b/tests/dialects/test_presto.py\nindex dbe3abca..a56d4a83 100644\n--- a/tests/dialects/test_presto.py\n+++ b/tests/dialects/test_presto.py\n@@ -405,6 +405,14 @@ class TestPresto(Validator):\n )\n self.validate_identity(\"DATE_ADD('DAY', 1, y)\")\n \n+ self.validate_all(\n+ \"SELECT DATE_ADD('MINUTE', 30, col)\",\n+ write={\n+ \"presto\": \"SELECT DATE_ADD('MINUTE', 30, col)\",\n+ \"trino\": \"SELECT DATE_ADD('MINUTE', 30, col)\",\n+ },\n+ )\n+\n def test_ddl(self):\n self.validate_all(\n \"CREATE TABLE test WITH (FORMAT = 'PARQUET') AS SELECT 1\",\ndiff --git a/tests/dialects/test_spark.py b/tests/dialects/test_spark.py\nindex 4e62b32e..fc3146f6 100644\n--- a/tests/dialects/test_spark.py\n+++ b/tests/dialects/test_spark.py\n@@ -684,6 +684,8 @@ TBLPROPERTIES (\n write={\n \"spark\": \"SELECT DATE_ADD(MONTH, 20, col)\",\n \"databricks\": \"SELECT DATE_ADD(MONTH, 20, col)\",\n+ \"presto\": \"SELECT DATE_ADD('MONTH', 20, col)\",\n+ \"trino\": \"SELECT DATE_ADD('MONTH', 20, col)\",\n },\n )\n \n", "FAIL_TO_PASS": ["tests/dialects/test_spark.py::TestSpark::test_spark"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_dialect.py::TestDialect::test_qualify", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_bigquery.py::TestBigQuery::test_warnings", "tests/dialects/test_dialect.py::TestDialect::test_order_by", "tests/dialects/test_spark.py::TestSpark::test_spark"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "hgrecco__pint-630_x3", "level": 3, "source": "swerebench", "repo": "hgrecco/pint", "image": "swerebench/sweb.eval.x86_64.hgrecco_1776_pint-630:latest", "base_commit": "90174a33c00a1364fcf2af9c59adf7859b0706b2", "num_bugs": 3, "bugs": [{"instance_id": "hgrecco__pint-630", "base_commit": "90174a33c00a1364fcf2af9c59adf7859b0706b2", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex 800263e..fd6781b 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -1,7 +1,6 @@\n language: python\n \n env:\n- - UNCERTAINTIES=\"N\" PYTHON=\"2.7\" NUMPY_VERSION=1.11.2\n - UNCERTAINTIES=\"N\" PYTHON=\"3.3\" NUMPY_VERSION=1.9.2\n - UNCERTAINTIES=\"N\" PYTHON=\"3.4\" NUMPY_VERSION=1.11.2\n - UNCERTAINTIES=\"N\" PYTHON=\"3.5\" NUMPY_VERSION=1.11.2\n@@ -9,6 +8,12 @@ env:\n - UNCERTAINTIES=\"N\" PYTHON=\"3.6\" NUMPY_VERSION=1.11.2\n - UNCERTAINTIES=\"N\" PYTHON=\"2.7\" NUMPY_VERSION=0\n - UNCERTAINTIES=\"N\" PYTHON=\"3.5\" NUMPY_VERSION=0\n+ # Test with the latest numpy version\n+ - UNCERTAINTIES=\"N\" PYTHON=\"2.7\" NUMPY_VERSION=1.14\n+ - UNCERTAINTIES=\"N\" PYTHON=\"3.4\" NUMPY_VERSION=1.14\n+ - UNCERTAINTIES=\"N\" PYTHON=\"3.5\" NUMPY_VERSION=1.14\n+ - UNCERTAINTIES=\"Y\" PYTHON=\"3.5\" NUMPY_VERSION=1.14\n+ - UNCERTAINTIES=\"N\" PYTHON=\"3.6\" NUMPY_VERSION=1.14\n \n before_install:\n - sudo apt-get update\ndiff --git a/pint/quantity.py b/pint/quantity.py\nindex 8a6599b..88bfdac 100644\n--- a/pint/quantity.py\n+++ b/pint/quantity.py\n@@ -1003,8 +1003,8 @@ class _Quantity(PrettyIPython, SharedRegistryObject):\n raise OffsetUnitCalculusError(self._units)\n \n if getattr(other, 'dimensionless', False):\n- other = other.to_base_units()\n- self._units **= other.magnitude\n+ other = other.to_base_units().magnitude\n+ self._units **= other\n elif not getattr(other, 'dimensionless', True):\n raise DimensionalityError(self._units, 'dimensionless')\n else:\n@@ -1090,6 +1090,20 @@ class _Quantity(PrettyIPython, SharedRegistryObject):\n # We compare to the base class of Quantity because\n # each Quantity class is unique.\n if not isinstance(other, _Quantity):\n+ if _eq(other, 0, True):\n+ # Handle the special case in which we compare to zero\n+ # (or an array of zeros)\n+ if self._is_multiplicative:\n+ # compare magnitude\n+ return _eq(self._magnitude, other, False)\n+ else:\n+ # compare the magnitude after converting the\n+ # non-multiplicative quantity to base units\n+ if self._REGISTRY.autoconvert_offset_to_baseunit:\n+ return _eq(self.to_base_units()._magnitude, other, False)\n+ else:\n+ raise OffsetUnitCalculusError(self._units)\n+\n return (self.dimensionless and\n _eq(self._convert_magnitude(UnitsContainer()), other, False))\n \n@@ -1115,6 +1129,19 @@ class _Quantity(PrettyIPython, SharedRegistryObject):\n if not isinstance(other, self.__class__):\n if self.dimensionless:\n return op(self._convert_magnitude_not_inplace(UnitsContainer()), other)\n+ elif _eq(other, 0, True):\n+ # Handle the special case in which we compare to zero\n+ # (or an array of zeros)\n+ if self._is_multiplicative:\n+ # compare magnitude\n+ return op(self._magnitude, other)\n+ else:\n+ # compare the magnitude after converting the\n+ # non-multiplicative quantity to base units\n+ if self._REGISTRY.autoconvert_offset_to_baseunit:\n+ return op(self.to_base_units()._magnitude, other)\n+ else:\n+ raise OffsetUnitCalculusError(self._units)\n else:\n raise ValueError('Cannot compare Quantity and {}'.format(type(other)))\n \n", "test_patch": "diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py\nindex 54d460a..5c0e22b 100644\n--- a/pint/testsuite/test_quantity.py\n+++ b/pint/testsuite/test_quantity.py\n@@ -1296,3 +1296,107 @@ class TestTimedelta(QuantityTestCase):\n after = 3 * self.ureg.second\n with self.assertRaises(DimensionalityError):\n after -= d\n+\n+\n+class TestCompareZero(QuantityTestCase):\n+ \"\"\"This test case checks the special treatment that the zero value\n+ receives in the comparisons: pint>=0.9 supports comparisons against zero\n+ even for non-dimensionless quantities\n+ \"\"\"\n+\n+ def test_equal_zero(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = False\n+ self.assertTrue(ureg.Quantity(0, ureg.J) == 0)\n+ self.assertFalse(ureg.Quantity(0, ureg.J) == ureg.Quantity(0, ''))\n+ self.assertFalse(ureg.Quantity(5, ureg.J) == 0)\n+\n+ @helpers.requires_numpy()\n+ def test_equal_zero_NP(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = False\n+ aeq = np.testing.assert_array_equal\n+ aeq(ureg.Quantity(0, ureg.J) == np.zeros(3),\n+ np.asarray([True, True, True]))\n+ aeq(ureg.Quantity(5, ureg.J) == np.zeros(3),\n+ np.asarray([False, False, False]))\n+ aeq(ureg.Quantity(np.arange(3), ureg.J) == np.zeros(3),\n+ np.asarray([True, False, False]))\n+ self.assertFalse(ureg.Quantity(np.arange(4), ureg.J) == np.zeros(3))\n+\n+ def test_offset_equal_zero(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = False\n+ q0 = ureg.Quantity(-273.15, 'degC')\n+ q1 = ureg.Quantity(0, 'degC')\n+ q2 = ureg.Quantity(5, 'degC')\n+ self.assertRaises(OffsetUnitCalculusError, q0.__eq__, 0)\n+ self.assertRaises(OffsetUnitCalculusError, q1.__eq__, 0)\n+ self.assertRaises(OffsetUnitCalculusError, q2.__eq__, 0)\n+ self.assertFalse(q0 == ureg.Quantity(0, ''))\n+\n+ def test_offset_autoconvert_equal_zero(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = True\n+ q0 = ureg.Quantity(-273.15, 'degC')\n+ q1 = ureg.Quantity(0, 'degC')\n+ q2 = ureg.Quantity(5, 'degC')\n+ self.assertTrue(q0 == 0)\n+ self.assertFalse(q1 == 0)\n+ self.assertFalse(q2 == 0)\n+ self.assertFalse(q0 == ureg.Quantity(0, ''))\n+\n+ def test_gt_zero(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = False\n+ q0 = ureg.Quantity(0, 'J')\n+ q0m = ureg.Quantity(0, 'm')\n+ q0less = ureg.Quantity(0, '')\n+ qpos = ureg.Quantity(5, 'J')\n+ qneg = ureg.Quantity(-5, 'J')\n+ self.assertTrue(qpos > q0)\n+ self.assertTrue(qpos > 0)\n+ self.assertFalse(qneg > 0)\n+ self.assertRaises(DimensionalityError, qpos.__gt__, q0less)\n+ self.assertRaises(DimensionalityError, qpos.__gt__, q0m)\n+\n+ @helpers.requires_numpy()\n+ def test_gt_zero_NP(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = False\n+ qpos = ureg.Quantity(5, 'J')\n+ qneg = ureg.Quantity(-5, 'J')\n+ aeq = np.testing.assert_array_equal\n+ aeq(qpos > np.zeros(3), np.asarray([True, True, True]))\n+ aeq(qneg > np.zeros(3), np.asarray([False, False, False]))\n+ aeq(ureg.Quantity(np.arange(-1, 2), ureg.J) > np.zeros(3),\n+ np.asarray([False, False, True]))\n+ aeq(ureg.Quantity(np.arange(-1, 2), ureg.J) > np.zeros(3),\n+ np.asarray([False, False, True]))\n+ self.assertRaises(ValueError,\n+ ureg.Quantity(np.arange(-1, 2), ureg.J).__gt__,\n+ np.zeros(4))\n+\n+ def test_offset_gt_zero(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = False\n+ q0 = ureg.Quantity(-273.15, 'degC')\n+ q1 = ureg.Quantity(0, 'degC')\n+ q2 = ureg.Quantity(5, 'degC')\n+ self.assertRaises(OffsetUnitCalculusError, q0.__gt__, 0)\n+ self.assertRaises(OffsetUnitCalculusError, q1.__gt__, 0)\n+ self.assertRaises(OffsetUnitCalculusError, q2.__gt__, 0)\n+ self.assertRaises(DimensionalityError, q1.__gt__,\n+ ureg.Quantity(0, ''))\n+\n+ def test_offset_autoconvert_gt_zero(self):\n+ ureg = self.ureg\n+ ureg.autoconvert_offset_to_baseunit = True\n+ q0 = ureg.Quantity(-273.15, 'degC')\n+ q1 = ureg.Quantity(0, 'degC')\n+ q2 = ureg.Quantity(5, 'degC')\n+ self.assertFalse(q0 > 0)\n+ self.assertTrue(q1 > 0)\n+ self.assertTrue(q2 > 0)\n+ self.assertRaises(DimensionalityError, q1.__gt__,\n+ ureg.Quantity(0, ''))\n\\ No newline at end of file\ndiff --git a/pint/testsuite/test_umath.py b/pint/testsuite/test_umath.py\nindex 0d0c544..589aaa4 100644\n--- a/pint/testsuite/test_umath.py\n+++ b/pint/testsuite/test_umath.py\n@@ -613,7 +613,7 @@ class TestFloatingUfuncs(TestUFuncs):\n (self.q1, self.qm, self.qless))\n \n def test_isfinite(self):\n- self._testn(np.isreal,\n+ self._testn(np.isfinite,\n (self.q1, self.qm, self.qless))\n \n def test_isinf(self):\n", "FAIL_TO_PASS": ["pint/testsuite/test_quantity.py::TestOffsetUnitMath::test_inplace_exponentiation_00007", "pint/testsuite/test_quantity.py::TestOffsetUnitMath::test_inplace_exponentiation_00009", "pint/testsuite/test_quantity.py::TestOffsetUnitMath::test_inplace_exponentiation_00013", "pint/testsuite/test_quantity.py::TestCompareZero::test_equal_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_equal_zero_NP", "pint/testsuite/test_quantity.py::TestCompareZero::test_gt_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_gt_zero_NP", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_autoconvert_equal_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_autoconvert_gt_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_equal_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_gt_zero", "pint/testsuite/test_umath.py::TestFloatingUfuncs::test_isreal"]}, {"instance_id": "hgrecco__pint-652", "base_commit": "0c4a9503b9fe00a62a90c33cb49cb047784766d3", "gold_patch": "diff --git a/docs/wrapping.rst b/docs/wrapping.rst\nindex a4913b3..dd9a39f 100644\n--- a/docs/wrapping.rst\n+++ b/docs/wrapping.rst\n@@ -148,6 +148,37 @@ airmass::\n def solar_position(lat, lon, press, tamb, timestamp):\n return zenith, azimuth, airmass\n \n+Optional arguments\n+------------------\n+\n+For a function with named keywords with optional values, use a tuple for all\n+arguments:\n+\n+.. doctest::\n+\n+ >>> @ureg.wraps(ureg.second, (ureg.meters, ureg.meters/ureg.second**2))\n+ ... def calculate_time_to_fall(height, gravity=Q_(9.8, 'm/s^2'), verbose=False):\n+ ... \"\"\"Calculate time to fall from a height h.\n+ ...\n+ ... By default, the gravity is assumed to be earth gravity,\n+ ... but it can be modified.\n+ ...\n+ ... d = .5 * g * t**2\n+ ... t = sqrt(2 * d / g)\n+ ... \"\"\"\n+ ... t = sqrt(2 * height / gravity)\n+ ... if verbose: print(str(t) + \" seconds to fall\")\n+ ... return t\n+ ...\n+ >>> lunar_module_height = Q_(22, 'feet') + Q_(11, 'inches')\n+ >>> calculate_time_to_fall(lunar_module_height, verbose=True)\n+ 1.1939473204801092 seconds to fall\n+ \n+ >>>\n+ >>> moon_gravity = Q_(1.625, 'm/s^2')\n+ >>> tcalculate_time_to_fall(lunar_module_height, moon_gravity)\n+ \n+\n \n Specifying relations between arguments\n --------------------------------------\n@@ -171,6 +202,19 @@ You can use more than one label:\n ... def some_function(x, y, z):\n ... pass\n \n+With optional arguments\n+\n+.. doctest::\n+\n+ >>> @ureg.wraps('=A*B', ('=A', '=B'))\n+ ... def get_displacement(time, rate=Q_(1, 'm/s')):\n+ ... return time * rate\n+ ...\n+ >>> get_displacement(Q_(2, 's'))\n+ \n+ >>> get_displacement(Q_(2, 's'), Q_(1, 'deg/s'))\n+ \n+\n \n Ignoring an argument or return value\n ------------------------------------\ndiff --git a/pint/registry_helpers.py b/pint/registry_helpers.py\nindex 1105038..4a8b862 100644\n--- a/pint/registry_helpers.py\n+++ b/pint/registry_helpers.py\n@@ -15,6 +15,12 @@ from .compat import string_types, zip_longest\n from .errors import DimensionalityError\n from .util import to_units_container, UnitsContainer\n \n+try:\n+ from inspect import signature\n+except ImportError:\n+ # Python2 does not have the inspect library. Import the backport.\n+ from funcsigs import signature\n+\n \n def _replace_units(original_units, values_by_name):\n \"\"\"Convert a unit compatible type to a UnitsContainer.\n@@ -165,6 +171,19 @@ def wraps(ureg, ret, args, strict=True):\n @functools.wraps(func, assigned=assigned, updated=updated)\n def wrapper(*values, **kw):\n \n+\n+ # Named keywords may have been left blank. Wherever the named keyword is blank,\n+ # fill it in with the default value.\n+ sig = signature(func)\n+ bound_arguments = sig.bind(*values, **kw)\n+\n+ for param in sig.parameters.values():\n+ if param.name not in bound_arguments.arguments:\n+ bound_arguments.arguments[param.name] = param.default\n+\n+ values = [bound_arguments.arguments[key] for key in sig.parameters.keys()]\n+ kw = {}\n+ \n # In principle, the values are used as is\n # When then extract the magnitudes when needed.\n new_values, values_by_name = converter(ureg, values, strict)\ndiff --git a/setup.py b/setup.py\nindex 354a79d..1bcae3c 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -60,4 +60,10 @@ setup(\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n- ])\n+ ],\n+ extras_require={\n+ ':python_version == \"2.7\"': [\n+ 'funcsigs',\n+ ],\n+ },\n+ )\n", "test_patch": "diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py\nindex 158fbe1..0cefce9 100644\n--- a/pint/testsuite/test_issues.py\n+++ b/pint/testsuite/test_issues.py\n@@ -571,3 +571,57 @@ class TestIssuesNP(QuantityTestCase):\n \n self.assertEqual(f(ureg.Quantity(1, '')), 2)\n self.assertRaises(DimensionalityError, f, ureg.Quantity(1, 'm'))\n+\n+ def test_issue625a(self):\n+ try:\n+ from inspect import signature\n+ except ImportError:\n+ # Python2 does not have the inspect library. Import the backport.\n+ from funcsigs import signature\n+\n+ ureg = UnitRegistry()\n+ Q_ = ureg.Quantity\n+ from math import sqrt\n+\n+ @ureg.wraps(ureg.second, (ureg.meters, ureg.meters/ureg.second**2))\n+ def calculate_time_to_fall(height, gravity=Q_(9.8, 'm/s^2')):\n+ \"\"\"Calculate time to fall from a height h with a default gravity.\n+\n+ By default, the gravity is assumed to be earth gravity,\n+ but it can be modified.\n+\n+ d = .5 * g * t**2\n+ t = sqrt(2 * d / g)\n+ \"\"\"\n+ return sqrt(2 * height / gravity)\n+\n+ lunar_module_height = Q_(10, 'm')\n+ t1 = calculate_time_to_fall(lunar_module_height)\n+ print(t1)\n+ self.assertAlmostEqual(t1, Q_(1.4285714285714286, 's'))\n+\n+ moon_gravity = Q_(1.625, 'm/s^2')\n+ t2 = calculate_time_to_fall(lunar_module_height, moon_gravity)\n+ self.assertAlmostEqual(t2, Q_(3.508232077228117, 's'))\n+\n+ def test_issue625b(self):\n+ try:\n+ from inspect import signature\n+ except ImportError:\n+ # Python2 does not have the inspect library. Import the backport.\n+ from funcsigs import signature\n+\n+ ureg = UnitRegistry()\n+ Q_ = ureg.Quantity\n+\n+ @ureg.wraps('=A*B', ('=A', '=B'))\n+ def get_displacement(time, rate=Q_(1, 'm/s')):\n+ \"\"\"Calculates displacement from a duration and default rate.\n+ \"\"\"\n+ return time * rate\n+\n+ d1 = get_displacement(Q_(2, 's'))\n+ self.assertAlmostEqual(d1, Q_(2, 'm'))\n+\n+ d2 = get_displacement(Q_(2, 's'), Q_(1, 'deg/s'))\n+ self.assertAlmostEqual(d2, Q_(2,' deg'))\n", "FAIL_TO_PASS": ["pint/testsuite/test_issues.py::TestIssuesNP::test_issue625a", "pint/testsuite/test_issues.py::TestIssuesNP::test_issue625b"]}, {"instance_id": "hgrecco__pint-658", "base_commit": "ba5cc0e76243c3e1e2b82999a71425ce3c6f3c1e", "gold_patch": "diff --git a/docs/wrapping.rst b/docs/wrapping.rst\nindex dd9a39f..6ce6411 100644\n--- a/docs/wrapping.rst\n+++ b/docs/wrapping.rst\n@@ -246,3 +246,12 @@ In the decorator format:\n ... def pendulum_period(length):\n ... return 2*math.pi*math.sqrt(length/G)\n \n+If you just want to check the dimensionality of a quantity, you can do so with the built-in 'check' function.\n+\n+.. doctest::\n+\n+ >>> distance = 1 * ureg.m\n+ >>> distance.check('[length]')\n+ True\n+ >>> distance.check('[time]')\n+ False\ndiff --git a/pint/quantity.py b/pint/quantity.py\nindex 88bfdac..ef25509 100644\n--- a/pint/quantity.py\n+++ b/pint/quantity.py\n@@ -294,6 +294,11 @@ class _Quantity(PrettyIPython, SharedRegistryObject):\n \n return self._dimensionality\n \n+ def check(self, dimension):\n+ \"\"\"Return true if the quantity's dimension matches passed dimension.\n+ \"\"\"\n+ return self.dimensionality == dimension\n+\n @classmethod\n def from_tuple(cls, tup):\n return cls(tup[0], UnitsContainer(tup[1]))\ndiff --git a/pint/registry_helpers.py b/pint/registry_helpers.py\nindex 4a8b862..5ac0dbd 100644\n--- a/pint/registry_helpers.py\n+++ b/pint/registry_helpers.py\n@@ -130,6 +130,20 @@ def _parse_wrap_args(args, registry=None):\n \n return _converter\n \n+def _apply_defaults(func, args, kwargs):\n+ \"\"\"Apply default keyword arguments.\n+\n+ Named keywords may have been left blank. This function applies the default\n+ values so that every argument is defined.\n+ \"\"\"\n+\n+ sig = signature(func)\n+ bound_arguments = sig.bind(*args)\n+ for param in sig.parameters.values():\n+ if param.name not in bound_arguments.arguments:\n+ bound_arguments.arguments[param.name] = param.default\n+ args = [bound_arguments.arguments[key] for key in sig.parameters.keys()]\n+ return args, {} \n \n def wraps(ureg, ret, args, strict=True):\n \"\"\"Wraps a function to become pint-aware.\n@@ -171,18 +185,7 @@ def wraps(ureg, ret, args, strict=True):\n @functools.wraps(func, assigned=assigned, updated=updated)\n def wrapper(*values, **kw):\n \n-\n- # Named keywords may have been left blank. Wherever the named keyword is blank,\n- # fill it in with the default value.\n- sig = signature(func)\n- bound_arguments = sig.bind(*values, **kw)\n-\n- for param in sig.parameters.values():\n- if param.name not in bound_arguments.arguments:\n- bound_arguments.arguments[param.name] = param.default\n-\n- values = [bound_arguments.arguments[key] for key in sig.parameters.keys()]\n- kw = {}\n+ values, kw = _apply_defaults(func, values, kw)\n \n # In principle, the values are used as is\n # When then extract the magnitudes when needed.\n@@ -228,13 +231,17 @@ def check(ureg, *args):\n \n @functools.wraps(func, assigned=assigned, updated=updated)\n def wrapper(*values, **kwargs):\n- for dim, value in zip_longest(dimensions, values):\n+ values, kwargs = _apply_defaults(func, values, kwargs)\n+ if len(dimensions) > len(values):\n+ raise TypeError(\"%s takes %i parameters, but %i dimensions were passed\"\n+ % (func.__name__, len(values), len(dimensions)))\n+ for dim, value in zip(dimensions, values):\n \n if dim is None:\n continue\n \n- val_dim = ureg.get_dimensionality(value)\n- if val_dim != dim:\n+ if not ureg.Quantity(value).check(dim):\n+ val_dim = ureg.get_dimensionality(value)\n raise DimensionalityError(value, 'a quantity of',\n val_dim, dim)\n return func(*values, **kwargs)\n", "test_patch": "diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py\nindex 0cefce9..4dbcb98 100644\n--- a/pint/testsuite/test_issues.py\n+++ b/pint/testsuite/test_issues.py\n@@ -625,3 +625,38 @@ class TestIssuesNP(QuantityTestCase):\n \n d2 = get_displacement(Q_(2, 's'), Q_(1, 'deg/s'))\n self.assertAlmostEqual(d2, Q_(2,' deg'))\n+\n+ def test_issue655a(self):\n+ ureg = UnitRegistry()\n+ distance = 1 * ureg.m\n+ time = 1 * ureg.s\n+ velocity = distance / time\n+ self.assertEqual(distance.check('[length]'), True)\n+ self.assertEqual(distance.check('[time]'), False)\n+ self.assertEqual(velocity.check('[length] / [time]'), True)\n+ self.assertEqual(velocity.check('1 / [time] * [length]'), True)\n+\n+ def test_issue(self):\n+ import math\n+ try:\n+ from inspect import signature\n+ except ImportError:\n+ # Python2 does not have the inspect library. Import the backport\n+ from funcsigs import signature\n+\n+ ureg = UnitRegistry()\n+ Q_ = ureg.Quantity\n+ @ureg.check('[length]', '[length]/[time]^2')\n+ def pendulum_period(length, G=Q_(1, 'standard_gravity')):\n+ print(length)\n+ return (2*math.pi*(length/G)**.5).to('s')\n+ l = 1 * ureg.m\n+ # Assume earth gravity\n+ t = pendulum_period(l)\n+ self.assertAlmostEqual(t, Q_('2.0064092925890407 second'))\n+ # Use moon gravity\n+ moon_gravity = Q_(1.625, 'm/s^2')\n+ t = pendulum_period(l, moon_gravity)\n+ self.assertAlmostEqual(t, Q_('4.928936075204336 second'))\n+\n+\ndiff --git a/pint/testsuite/test_unit.py b/pint/testsuite/test_unit.py\nindex 0e7b17f..b9e3b06 100644\n--- a/pint/testsuite/test_unit.py\n+++ b/pint/testsuite/test_unit.py\n@@ -437,13 +437,13 @@ class TestRegistry(QuantityTestCase):\n \n g2 = ureg.check('[speed]')(gfunc)\n self.assertRaises(DimensionalityError, g2, 3.0, 1)\n- self.assertRaises(DimensionalityError, g2, 2 * ureg.parsec)\n+ self.assertRaises(TypeError, g2, 2 * ureg.parsec)\n self.assertRaises(DimensionalityError, g2, 2 * ureg.parsec, 1.0)\n self.assertEqual(g2(2.0 * ureg.km / ureg.hour, 2), 1 * ureg.km / ureg.hour)\n \n g3 = ureg.check('[speed]', '[time]', '[mass]')(gfunc)\n- self.assertRaises(DimensionalityError, g3, 1 * ureg.parsec, 1 * ureg.angstrom)\n- self.assertRaises(DimensionalityError, g3, 1 * ureg.parsec, 1 * ureg.angstrom, 1 * ureg.kilogram)\n+ self.assertRaises(TypeError, g3, 1 * ureg.parsec, 1 * ureg.angstrom)\n+ self.assertRaises(TypeError, g3, 1 * ureg.parsec, 1 * ureg.angstrom, 1 * ureg.kilogram)\n \n def test_to_ref_vs_to(self):\n self.ureg.autoconvert_offset_to_baseunit = True\n", "FAIL_TO_PASS": ["pint/testsuite/test_unit.py::TestRegistry::test_check", "pint/testsuite/test_unit.py::TestRegistryWithDefaultRegistry::test_check"]}], "all_FAIL_TO_PASS": ["pint/testsuite/test_quantity.py::TestOffsetUnitMath::test_inplace_exponentiation_00007", "pint/testsuite/test_quantity.py::TestOffsetUnitMath::test_inplace_exponentiation_00009", "pint/testsuite/test_quantity.py::TestOffsetUnitMath::test_inplace_exponentiation_00013", "pint/testsuite/test_quantity.py::TestCompareZero::test_equal_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_equal_zero_NP", "pint/testsuite/test_quantity.py::TestCompareZero::test_gt_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_gt_zero_NP", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_autoconvert_equal_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_autoconvert_gt_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_equal_zero", "pint/testsuite/test_quantity.py::TestCompareZero::test_offset_gt_zero", "pint/testsuite/test_umath.py::TestFloatingUfuncs::test_isreal", "pint/testsuite/test_issues.py::TestIssuesNP::test_issue625a", "pint/testsuite/test_issues.py::TestIssuesNP::test_issue625b", "pint/testsuite/test_unit.py::TestRegistry::test_check", "pint/testsuite/test_unit.py::TestRegistryWithDefaultRegistry::test_check"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "just-work__fffw-64_x3", "level": 3, "source": "swerebench", "repo": "just-work/fffw", "image": "swerebench/sweb.eval.x86_64.just-work_1776_fffw-64:latest", "base_commit": "fefda959ec043f1869b38026fc3c8a9679bf45bc", "num_bugs": 3, "bugs": [{"instance_id": "just-work__fffw-64", "base_commit": "fefda959ec043f1869b38026fc3c8a9679bf45bc", "gold_patch": "diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py\nindex bd06ae6..ff1baa2 100644\n--- a/fffw/encoding/filters.py\n+++ b/fffw/encoding/filters.py\n@@ -1,4 +1,4 @@\n-from dataclasses import dataclass, replace, asdict, field\n+from dataclasses import dataclass, replace, asdict, field, fields\n from typing import Union, List, cast\n \n from fffw.graph import base\n@@ -91,7 +91,8 @@ class Filter(mixins.StreamValidationMixin, base.Node, Params):\n \n Inputs and outputs are not copied.\n \"\"\"\n- kwargs = asdict(self)\n+ skip = [f.name for f in fields(self) if not f.init]\n+ kwargs = {k: v for k, v in asdict(self).items() if k not in skip}\n # noinspection PyArgumentList\n return type(self)(**kwargs) # type: ignore\n \n", "test_patch": "diff --git a/tests/test_vector.py b/tests/test_vector.py\nindex 50794cd..bc4e8c8 100644\n--- a/tests/test_vector.py\n+++ b/tests/test_vector.py\n@@ -1,4 +1,4 @@\n-from dataclasses import dataclass, replace\n+from dataclasses import dataclass, replace, asdict\n from typing import cast, Tuple\n \n from fffw.encoding import *\n@@ -373,3 +373,17 @@ class VectorTestCase(BaseTestCase):\n '-c:a', 'libfdk_aac',\n 'output2.mp5'\n )\n+\n+ def test_clone_filter_with_skipped_params(self):\n+ \"\"\"\n+ A filter with `init=False` param is cloned correctly.\n+ \"\"\"\n+ @dataclass\n+ class MyFilter(filters.VideoFilter):\n+ my_flag: bool = param(init=False, default=True)\n+\n+ f = MyFilter()\n+\n+ cloned = f._clone()\n+\n+ self.assertTrue(asdict(cloned)['my_flag'])\n", "FAIL_TO_PASS": ["tests/test_vector.py::VectorTestCase::test_clone_filter_with_skipped_params"]}, {"instance_id": "just-work__fffw-68", "base_commit": "ec1451b6347ac0c9a8da3947651d7b15ebf0212d", "gold_patch": "diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py\nindex ff1baa2..1ef1505 100644\n--- a/fffw/encoding/filters.py\n+++ b/fffw/encoding/filters.py\n@@ -3,7 +3,7 @@ from typing import Union, List, cast\n \n from fffw.graph import base\n from fffw.encoding import mixins\n-from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO\n+from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO, AudioMeta\n from fffw.graph.meta import StreamType, Device\n from fffw.wrapper.params import Params, param\n \n@@ -330,16 +330,26 @@ class Concat(Filter):\n duration = TS(0)\n scenes = []\n streams: List[str] = []\n+ samples = 0\n+ sampling_rate = None\n for meta in metadata:\n duration += meta.duration\n+ if isinstance(meta, AudioMeta):\n+ samples += meta.samples\n+ if sampling_rate is None:\n+ sampling_rate = meta.sampling_rate\n+ else:\n+ assert sampling_rate == meta.sampling_rate\n scenes.extend(meta.scenes)\n for stream in meta.streams:\n if not streams or streams[-1] != stream:\n # Add all streams for each concatenated metadata and remove\n # contiguous duplicates.\n streams.append(stream)\n- return replace(metadata[0], duration=duration,\n- scenes=scenes, streams=streams)\n+ kwargs = dict(duration=duration, scenes=scenes, streams=streams)\n+ if samples != 0:\n+ kwargs['samples'] = samples\n+ return replace(metadata[0], **kwargs)\n \n \n @dataclass\n", "test_patch": "diff --git a/tests/test_graph.py b/tests/test_graph.py\nindex 5e82f6e..905464c 100644\n--- a/tests/test_graph.py\n+++ b/tests/test_graph.py\n@@ -35,7 +35,10 @@ class FilterGraphTestCase(TestCase):\n par=1.0,\n duration=300.0,\n )\n- self.audio_metadata = audio_meta_data()\n+ self.audio_metadata = audio_meta_data(\n+ duration=200.0,\n+ sampling_rate=48000,\n+ samples_count=200*48000)\n \n self.source = inputs.Input(\n input_file='input.mp4',\n@@ -239,6 +242,25 @@ class FilterGraphTestCase(TestCase):\n self.assertEqual(self.video_metadata.duration + vs.meta.duration,\n vm.duration)\n \n+ def test_concat_audio_metadata(self):\n+ \"\"\"\n+ Concat filter sums samples count for audio streams.\n+ \"\"\"\n+ audio_meta = audio_meta_data(duration=1000.0, sampling_rate=48000,\n+ samples_count=48000 * 1000)\n+ a = inputs.Stream(AUDIO, meta=audio_meta)\n+ self.input_list.append(inputs.input_file('second.mp4', a))\n+ concat = a | Concat(AUDIO)\n+ self.source | concat\n+\n+ concat > self.output\n+\n+ am = cast(AudioMeta, self.output.codecs[-1].get_meta_data())\n+ self.assertEqual(self.audio_metadata.duration + audio_meta.duration,\n+ am.duration)\n+ self.assertEqual(self.audio_metadata.samples + audio_meta.samples,\n+ am.samples)\n+\n def test_trim_metadata(self):\n \"\"\"\n Trim filter sets start and changes stream duration.\n", "FAIL_TO_PASS": ["tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata"]}, {"instance_id": "just-work__fffw-70", "base_commit": "448ed0a0b1dee4640a86e0ecce056f5fb1505c3b", "gold_patch": "diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py\nindex 1ef1505..43ed444 100644\n--- a/fffw/encoding/filters.py\n+++ b/fffw/encoding/filters.py\n@@ -202,6 +202,10 @@ class Split(AutoFilter):\n return ''\n return str(self.output_count)\n \n+ def validate_edge_device(self, edge: base.Edge) -> None:\n+ # Any device is supported\n+ return\n+\n \n @dataclass\n class Trim(AutoFilter):\n@@ -351,6 +355,10 @@ class Concat(Filter):\n kwargs['samples'] = samples\n return replace(metadata[0], **kwargs)\n \n+ def validate_edge_device(self, edge: base.Edge) -> None:\n+ # Any device is supported\n+ return\n+\n \n @dataclass\n class Overlay(VideoFilter):\n", "test_patch": "diff --git a/tests/test_graph.py b/tests/test_graph.py\nindex 905464c..6b9bb4c 100644\n--- a/tests/test_graph.py\n+++ b/tests/test_graph.py\n@@ -305,3 +305,17 @@ class FilterGraphTestCase(TestCase):\n \n cuda = meta.Device(hardware='cuda', name='foo')\n self.source.video | Upload(device=cuda) | ScaleCuda(640, 360)\n+\n+ def test_concat_split_allows_any_hardware(self):\n+ \"\"\"\n+ Concat and split filters allow any hardware acceleration.\n+ \"\"\"\n+ try:\n+ cuda = meta.Device(hardware='cuda', name='foo')\n+ hw = self.source.video | Upload(device=cuda)\n+ split = hw | Split(VIDEO, output_count=2)\n+ concat = Concat(VIDEO, input_count=2)\n+ split | concat\n+ split | concat\n+ except ValueError: # pragma: no cover\n+ self.fail(\"hardware validation unexpectedly failed\")\n", "FAIL_TO_PASS": ["tests/test_graph.py::FilterGraphTestCase::test_concat_split_allows_any_hardware"]}], "all_FAIL_TO_PASS": ["tests/test_vector.py::VectorTestCase::test_clone_filter_with_skipped_params", "tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata", "tests/test_graph.py::FilterGraphTestCase::test_concat_split_allows_any_hardware"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3891_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3891:latest", "base_commit": "2cac14f480dcaf458b1eb36b694770ce24f56e61", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3891", "base_commit": "2cac14f480dcaf458b1eb36b694770ce24f56e61", "gold_patch": "diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 58fdb620..981dba15 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -406,6 +406,26 @@ class Snowflake(Dialect):\n ),\n }\n \n+ def _negate_range(\n+ self, this: t.Optional[exp.Expression] = None\n+ ) -> t.Optional[exp.Expression]:\n+ if not this:\n+ return this\n+\n+ query = this.args.get(\"query\")\n+ if isinstance(this, exp.In) and isinstance(query, exp.Query):\n+ # Snowflake treats `value NOT IN (subquery)` as `VALUE <> ALL (subquery)`, so\n+ # we do this conversion here to avoid parsing it into `NOT value IN (subquery)`\n+ # which can produce different results (most likely a SnowFlake bug).\n+ #\n+ # https://docs.snowflake.com/en/sql-reference/functions/in\n+ # Context: https://github.com/tobymao/sqlglot/issues/3890\n+ return self.expression(\n+ exp.NEQ, this=this.this, expression=exp.All(this=query.unnest())\n+ )\n+\n+ return self.expression(exp.Not, this=this)\n+\n def _parse_with_constraint(self) -> t.Optional[exp.Expression]:\n if self._prev.token_type != TokenType.WITH:\n self._retreat(self._index - 1)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 5d69ced5..12b71a67 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4241,13 +4241,19 @@ class Parser(metaclass=_Parser):\n this = self.expression(exp.Not, this=this)\n \n if negate:\n- this = self.expression(exp.Not, this=this)\n+ this = self._negate_range(this)\n \n if self._match(TokenType.IS):\n this = self._parse_is(this)\n \n return this\n \n+ def _negate_range(self, this: t.Optional[exp.Expression] = None) -> t.Optional[exp.Expression]:\n+ if not this:\n+ return this\n+\n+ return self.expression(exp.Not, this=this)\n+\n def _parse_is(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]:\n index = self._index - 1\n negate = self._match(TokenType.NOT)\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex f62c72b7..e8e86a43 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -138,6 +138,14 @@ WHERE\n self.validate_identity(\n \"SELECT * FROM DATA AS DATA_L ASOF JOIN DATA AS DATA_R MATCH_CONDITION (DATA_L.VAL > DATA_R.VAL) ON DATA_L.ID = DATA_R.ID\"\n )\n+ self.validate_identity(\n+ \"SELECT * FROM s WHERE c NOT IN (1, 2, 3)\",\n+ \"SELECT * FROM s WHERE NOT c IN (1, 2, 3)\",\n+ )\n+ self.validate_identity(\n+ \"SELECT * FROM s WHERE c NOT IN (SELECT * FROM t)\",\n+ \"SELECT * FROM s WHERE c <> ALL (SELECT * FROM t)\",\n+ )\n self.validate_identity(\n \"SELECT * FROM t1 INNER JOIN t2 USING (t1.col)\",\n \"SELECT * FROM t1 INNER JOIN t2 USING (col)\",\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-3935", "base_commit": "f9a1efd42361767bb2f867f827048c3a059b3188", "gold_patch": "diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py\nindex 3acabb94..2562422c 100644\n--- a/sqlglot/dialects/oracle.py\n+++ b/sqlglot/dialects/oracle.py\n@@ -90,7 +90,6 @@ class Oracle(Dialect):\n \"ORDER SIBLINGS BY\": TokenType.ORDER_SIBLINGS_BY,\n \"SAMPLE\": TokenType.TABLE_SAMPLE,\n \"START\": TokenType.BEGIN,\n- \"SYSDATE\": TokenType.CURRENT_TIMESTAMP,\n \"TOP\": TokenType.TOP,\n \"VARCHAR2\": TokenType.VARCHAR,\n }\n@@ -109,6 +108,11 @@ class Oracle(Dialect):\n }\n FUNCTIONS.pop(\"NVL\")\n \n+ NO_PAREN_FUNCTION_PARSERS = {\n+ **parser.Parser.NO_PAREN_FUNCTION_PARSERS,\n+ \"SYSDATE\": lambda self: self.expression(exp.CurrentTimestamp, sysdate=True),\n+ }\n+\n FUNCTION_PARSERS: t.Dict[str, t.Callable] = {\n **parser.Parser.FUNCTION_PARSERS,\n \"JSON_ARRAY\": lambda self: self._parse_json_array(\n@@ -275,6 +279,9 @@ class Oracle(Dialect):\n }\n \n def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:\n+ if expression.args.get(\"sysdate\"):\n+ return \"SYSDATE\"\n+\n this = expression.this\n return self.func(\"CURRENT_TIMESTAMP\", this) if this else \"CURRENT_TIMESTAMP\"\n \ndiff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py\nindex 0b12df12..694af28a 100644\n--- a/sqlglot/dialects/redshift.py\n+++ b/sqlglot/dialects/redshift.py\n@@ -80,7 +80,7 @@ class Redshift(Postgres):\n NO_PAREN_FUNCTION_PARSERS = {\n **Postgres.Parser.NO_PAREN_FUNCTION_PARSERS,\n \"APPROXIMATE\": lambda self: self._parse_approximate_count(),\n- \"SYSDATE\": lambda self: self.expression(exp.CurrentTimestamp, transaction=True),\n+ \"SYSDATE\": lambda self: self.expression(exp.CurrentTimestamp, sysdate=True),\n }\n \n SUPPORTS_IMPLICIT_UNNEST = True\n@@ -180,7 +180,7 @@ class Redshift(Postgres):\n exp.ApproxDistinct: lambda self,\n e: f\"APPROXIMATE COUNT(DISTINCT {self.sql(e, 'this')})\",\n exp.CurrentTimestamp: lambda self, e: (\n- \"SYSDATE\" if e.args.get(\"transaction\") else \"GETDATE()\"\n+ \"SYSDATE\" if e.args.get(\"sysdate\") else \"GETDATE()\"\n ),\n exp.DateAdd: date_delta_sql(\"DATEADD\"),\n exp.DateDiff: date_delta_sql(\"DATEDIFF\"),\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 404162d4..8a720486 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5133,7 +5133,7 @@ class CurrentTime(Func):\n \n \n class CurrentTimestamp(Func):\n- arg_types = {\"this\": False, \"transaction\": False}\n+ arg_types = {\"this\": False, \"sysdate\": False}\n \n \n class CurrentUser(Func):\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 7f743d39..79b8a024 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -15,6 +15,7 @@ class TestOracle(Validator):\n )\n self.parse_one(\"ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol\").assert_is(exp.Alter)\n \n+ self.validate_identity(\"SYSDATE\")\n self.validate_identity(\"CREATE GLOBAL TEMPORARY TABLE t AS SELECT * FROM orders\")\n self.validate_identity(\"CREATE PRIVATE TEMPORARY TABLE t AS SELECT * FROM orders\")\n self.validate_identity(\"REGEXP_REPLACE('source', 'search')\")\n@@ -72,10 +73,6 @@ class TestOracle(Validator):\n \"SELECT JSON_OBJECTAGG(KEY department_name VALUE department_id) FROM dep WHERE id <= 30\",\n \"SELECT JSON_OBJECTAGG(department_name: department_id) FROM dep WHERE id <= 30\",\n )\n- self.validate_identity(\n- \"SYSDATE\",\n- \"CURRENT_TIMESTAMP\",\n- )\n self.validate_identity(\n \"SELECT last_name, department_id, salary, MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) \"\n 'OVER (PARTITION BY department_id) AS \"Worst\", MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) '\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-3937", "base_commit": "f4c34d37c5773c37a13437c7e0e7eb27b4e98877", "gold_patch": "diff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex acd4c096..67400514 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -2909,11 +2909,13 @@ class Generator(metaclass=_Generator):\n \n def pivotalias_sql(self, expression: exp.PivotAlias) -> str:\n alias = expression.args[\"alias\"]\n+\n identifier_alias = isinstance(alias, exp.Identifier)\n+ literal_alias = isinstance(alias, exp.Literal)\n \n if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n alias.replace(exp.Literal.string(alias.output_name))\n- elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n+ elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:\n alias.replace(exp.to_identifier(alias.output_name))\n \n return self.alias_sql(expression)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 6171580c..fb78d1ab 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3776,8 +3776,10 @@ class Parser(metaclass=_Parser):\n this = self._parse_select_or_expression()\n \n self._match(TokenType.ALIAS)\n- alias = self._parse_field()\n+ alias = self._parse_bitwise()\n if alias:\n+ if isinstance(alias, exp.Column) and not alias.db:\n+ alias = alias.this\n return self.expression(exp.PivotAlias, this=this, alias=alias)\n \n return this\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 79b8a024..4a570721 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -44,6 +44,9 @@ class TestOracle(Validator):\n self.validate_identity(\"SELECT COUNT(*) * 10 FROM orders SAMPLE (10) SEED (1)\")\n self.validate_identity(\"SELECT * FROM V$SESSION\")\n self.validate_identity(\"SELECT TO_DATE('January 15, 1989, 11:00 A.M.')\")\n+ self.validate_identity(\n+ \"SELECT * FROM test UNPIVOT INCLUDE NULLS (value FOR Description IN (col AS 'PREFIX ' || CHR(38) || ' SUFFIX'))\"\n+ )\n self.validate_identity(\n \"SELECT last_name, employee_id, manager_id, LEVEL FROM employees START WITH employee_id = 100 CONNECT BY PRIOR employee_id = manager_id ORDER SIBLINGS BY last_name\"\n )\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_oracle.py::TestOracle::test_oracle"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "reata__sqllineage-492_x3", "level": 3, "source": "swerebench", "repo": "reata/sqllineage", "image": "swerebench/sweb.eval.x86_64.reata_1776_sqllineage-492:latest", "base_commit": "2d912648c14f7010b34026d5a0b1ae53dfe49d9c", "num_bugs": 3, "bugs": [{"instance_id": "reata__sqllineage-492", "base_commit": "2d912648c14f7010b34026d5a0b1ae53dfe49d9c", "gold_patch": "diff --git a/sqllineage/core/parser/sqlfluff/extractors/create_insert.py b/sqllineage/core/parser/sqlfluff/extractors/create_insert.py\nindex 563851a..526d726 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/create_insert.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/create_insert.py\n@@ -122,7 +122,11 @@ class CreateInsertExtractor(BaseExtractor):\n from .cte import CteExtractor\n \n return self.delegate_to(\n- CteExtractor, segment, AnalyzerContext(cte=holder.cte, write=holder.write)\n+ CteExtractor,\n+ segment,\n+ AnalyzerContext(\n+ cte=holder.cte, write=holder.write, write_columns=holder.write_columns\n+ ),\n )\n \n def delegate_to_select(\ndiff --git a/sqllineage/core/parser/sqlfluff/extractors/cte.py b/sqllineage/core/parser/sqlfluff/extractors/cte.py\nindex f05732d..0427a3b 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/cte.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/cte.py\n@@ -30,7 +30,11 @@ class CteExtractor(BaseExtractor):\n holder |= self.delegate_to(\n SelectExtractor,\n segment,\n- AnalyzerContext(cte=holder.cte, write=holder.write),\n+ AnalyzerContext(\n+ cte=holder.cte,\n+ write=holder.write,\n+ write_columns=holder.write_columns,\n+ ),\n )\n elif segment.type == \"insert_statement\":\n holder |= self.delegate_to(\n", "test_patch": "diff --git a/tests/sql/sqlfluff_only/test_dml_specify_column.py b/tests/sql/sqlfluff_only/test_dml_specify_column.py\nindex 5d57e66..6ae4b67 100644\n--- a/tests/sql/sqlfluff_only/test_dml_specify_column.py\n+++ b/tests/sql/sqlfluff_only/test_dml_specify_column.py\n@@ -117,3 +117,19 @@ def test_insert_with_custom_columns():\n ],\n test_sqlparse=False,\n )\n+\n+\n+def test_insert_with_custom_columns_and_cte_within_query():\n+ sql = \"\"\"INSERT INTO tab2 (col1)\n+WITH cte1 AS (SELECT col2 FROM tab1)\n+SELECT col2 FROM cte1\"\"\"\n+ assert_column_lineage_equal(\n+ sql,\n+ [\n+ (\n+ ColumnQualifierTuple(\"col2\", \"tab1\"),\n+ ColumnQualifierTuple(\"col1\", \"tab2\"),\n+ )\n+ ],\n+ test_sqlparse=False,\n+ )\n", "FAIL_TO_PASS": ["tests/sql/sqlfluff_only/test_dml_specify_column.py::test_insert_with_custom_columns_and_cte_within_query"]}, {"instance_id": "reata__sqllineage-493", "base_commit": "843ab2eb58e3e8f4d68c5e67afc7f69341c3ade7", "gold_patch": "diff --git a/sqllineage/core/parser/sqlfluff/extractors/select.py b/sqllineage/core/parser/sqlfluff/extractors/select.py\nindex 72c1eda..5c9fe72 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/select.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/select.py\n@@ -75,7 +75,14 @@ class SelectExtractor(BaseExtractor, SourceHandlerMixin):\n \n # By recursively extracting each subquery of the parent and merge, we're doing Depth-first search\n for sq in subqueries:\n- holder |= SelectExtractor(self.dialect).extract(\n+ from .cte import CteExtractor\n+\n+ extractor_cls = (\n+ CteExtractor\n+ if sq.query.get_child(\"with_compound_statement\")\n+ else SelectExtractor\n+ )\n+ holder |= extractor_cls(self.dialect).extract(\n sq.query, AnalyzerContext(cte=holder.cte, write={sq})\n )\n \ndiff --git a/sqllineage/core/parser/sqlfluff/utils.py b/sqllineage/core/parser/sqlfluff/utils.py\nindex b17c29c..406b17d 100644\n--- a/sqllineage/core/parser/sqlfluff/utils.py\n+++ b/sqllineage/core/parser/sqlfluff/utils.py\n@@ -36,7 +36,9 @@ def is_subquery(segment: BaseSegment) -> bool:\n segment if segment.type == \"bracketed\" else segment.segments[0]\n )\n # check if innermost parenthesis contains SELECT\n- if token.get_child(\"select_statement\", \"set_expression\"):\n+ if token.get_child(\n+ \"select_statement\", \"set_expression\", \"with_compound_statement\"\n+ ):\n return True\n elif expression := token.get_child(\"expression\"):\n if expression.get_child(\"select_statement\"):\n@@ -152,7 +154,6 @@ def list_subqueries(segment: BaseSegment) -> List[SubQueryTuple]:\n elif segment.type == \"from_expression_element\":\n as_segment, target = extract_as_and_target_segment(segment)\n if is_subquery(target):\n- as_segment, target = extract_as_and_target_segment(segment)\n subquery = [\n SubQueryTuple(\n extract_innermost_bracketed(target)\n", "test_patch": "diff --git a/tests/sql/table/test_cte.py b/tests/sql/table/test_cte.py\nindex 422ddde..fa41670 100644\n--- a/tests/sql/table/test_cte.py\n+++ b/tests/sql/table/test_cte.py\n@@ -85,3 +85,15 @@ SELECT col3 from tab3\"\"\"\n sql,\n {\"tab1\", \"tab2\", \"tab3\"},\n )\n+\n+\n+def test_cte_within_subquery():\n+ sql = \"\"\"SELECT sq.col1\n+FROM (WITH cte1 AS (SELECT col1 FROM tab1)\n+ SELECT col1\n+ FROM cte1\n+ INNER JOIN tab2 ON cte1.col1 = tab2.col1) AS sq\"\"\"\n+ assert_table_lineage_equal(\n+ sql,\n+ {\"tab1\", \"tab2\"},\n+ )\n", "FAIL_TO_PASS": ["tests/sql/table/test_cte.py::test_cte_within_subquery"]}, {"instance_id": "reata__sqllineage-494", "base_commit": "a2b03449ab6d8722eeb3cd9869d89a2af1b7c098", "gold_patch": "diff --git a/sqllineage/core/parser/sqlfluff/extractors/base.py b/sqllineage/core/parser/sqlfluff/extractors/base.py\nindex 74ad8bc..86c9a53 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/base.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/base.py\n@@ -101,6 +101,25 @@ class BaseExtractor:\n \"\"\"\n return extractor_cls(self.dialect).extract(segment, context)\n \n+ def extract_subquery(\n+ self, subqueries: List[SubQuery], holder: SubQueryLineageHolder\n+ ):\n+ \"\"\"\n+ extract subqueries collected from statement-level segment\n+ \"\"\"\n+ from .cte import CteExtractor\n+ from .select import SelectExtractor\n+\n+ for sq in subqueries:\n+ extractor_cls = (\n+ CteExtractor\n+ if sq.query.get_child(\"with_compound_statement\")\n+ else SelectExtractor\n+ )\n+ holder |= extractor_cls(self.dialect).extract(\n+ sq.query, AnalyzerContext(cte=holder.cte, write={sq})\n+ )\n+\n @staticmethod\n def _init_holder(context: AnalyzerContext) -> SubQueryLineageHolder:\n \"\"\"\ndiff --git a/sqllineage/core/parser/sqlfluff/extractors/cte.py b/sqllineage/core/parser/sqlfluff/extractors/cte.py\nindex 0427a3b..4356dcd 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/cte.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/cte.py\n@@ -59,11 +59,6 @@ class CteExtractor(BaseExtractor):\n if segment_has_alias:\n holder.add_cte(SqlFluffSubQuery.of(sub_segment, identifier))\n \n- # By recursively extracting each extractor of the parent and merge, we're doing Depth-first search\n- for sq in subqueries:\n- holder |= SelectExtractor(self.dialect).extract(\n- sq.query,\n- AnalyzerContext(cte=holder.cte, write={sq}),\n- )\n+ self.extract_subquery(subqueries, holder)\n \n return holder\ndiff --git a/sqllineage/core/parser/sqlfluff/extractors/select.py b/sqllineage/core/parser/sqlfluff/extractors/select.py\nindex 5c9fe72..24dcc61 100644\n--- a/sqllineage/core/parser/sqlfluff/extractors/select.py\n+++ b/sqllineage/core/parser/sqlfluff/extractors/select.py\n@@ -70,21 +70,9 @@ class SelectExtractor(BaseExtractor, SourceHandlerMixin):\n subqueries.append(sq)\n self._handle_table(seg, holder)\n self._handle_column(seg)\n-\n self.end_of_query_cleanup(holder)\n \n- # By recursively extracting each subquery of the parent and merge, we're doing Depth-first search\n- for sq in subqueries:\n- from .cte import CteExtractor\n-\n- extractor_cls = (\n- CteExtractor\n- if sq.query.get_child(\"with_compound_statement\")\n- else SelectExtractor\n- )\n- holder |= extractor_cls(self.dialect).extract(\n- sq.query, AnalyzerContext(cte=holder.cte, write={sq})\n- )\n+ self.extract_subquery(subqueries, holder)\n \n return holder\n \n", "test_patch": "diff --git a/tests/sql/table/test_cte.py b/tests/sql/table/test_cte.py\nindex fa41670..c9ab271 100644\n--- a/tests/sql/table/test_cte.py\n+++ b/tests/sql/table/test_cte.py\n@@ -97,3 +97,15 @@ FROM (WITH cte1 AS (SELECT col1 FROM tab1)\n sql,\n {\"tab1\", \"tab2\"},\n )\n+\n+\n+def test_cte_within_cte():\n+ sql = \"\"\"WITH cte1 AS\n+ (WITH cte2 AS\n+ (SELECT id\n+ FROM tab1)\n+ SELECT id\n+ FROM cte2)\n+SELECT id\n+FROM cte1\"\"\"\n+ assert_table_lineage_equal(sql, {\"tab1\"})\n", "FAIL_TO_PASS": ["tests/sql/table/test_cte.py::test_cte_within_cte"]}], "all_FAIL_TO_PASS": ["tests/sql/sqlfluff_only/test_dml_specify_column.py::test_insert_with_custom_columns_and_cte_within_query", "tests/sql/table/test_cte.py::test_cte_within_subquery", "tests/sql/table/test_cte.py::test_cte_within_cte"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-4546_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-4546:latest", "base_commit": "931eef6958be87ef88f4ff5311441e7a7004b8c5", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-4546", "base_commit": "931eef6958be87ef88f4ff5311441e7a7004b8c5", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 911e8c51..cc85de01 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -633,7 +633,7 @@ class ClickHouse(Dialect):\n return super()._parse_position(haystack_first=True)\n \n # https://clickhouse.com/docs/en/sql-reference/statements/select/with/\n- def _parse_cte(self) -> exp.CTE:\n+ def _parse_cte(self) -> t.Optional[exp.CTE]:\n # WITH AS \n cte: t.Optional[exp.CTE] = self._try_parse(super()._parse_cte)\n \ndiff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py\nindex 08d99e4e..c84632f2 100644\n--- a/sqlglot/dialects/spark.py\n+++ b/sqlglot/dialects/spark.py\n@@ -102,6 +102,8 @@ class Spark(Spark2):\n ]\n \n class Parser(Spark2.Parser):\n+ OPTIONAL_ALIAS_TOKEN_CTE = True\n+\n FUNCTIONS = {\n **Spark2.Parser.FUNCTIONS,\n \"ANY_VALUE\": _build_with_ignore_nulls(exp.AnyValue),\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 20ca97c4..2fa9ab44 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1379,6 +1379,9 @@ class Parser(metaclass=_Parser):\n # Whether the `name AS expr` schema/column constraint requires parentheses around `expr`\n WRAPPED_TRANSFORM_COLUMN_CONSTRAINT = True\n \n+ # Whether the 'AS' keyword is optional in the CTE definition syntax\n+ OPTIONAL_ALIAS_TOKEN_CTE = False\n+\n __slots__ = (\n \"error_level\",\n \"error_message_context\",\n@@ -3131,12 +3134,17 @@ class Parser(metaclass=_Parser):\n exp.With, comments=comments, expressions=expressions, recursive=recursive\n )\n \n- def _parse_cte(self) -> exp.CTE:\n+ def _parse_cte(self) -> t.Optional[exp.CTE]:\n+ index = self._index\n+\n alias = self._parse_table_alias(self.ID_VAR_TOKENS)\n if not alias or not alias.this:\n self.raise_error(\"Expected CTE to have alias\")\n \n- self._match(TokenType.ALIAS)\n+ if not self._match(TokenType.ALIAS) and not self.OPTIONAL_ALIAS_TOKEN_CTE:\n+ self._retreat(index)\n+ return None\n+\n comments = self._prev_comments\n \n if self._match_text_seq(\"NOT\", \"MATERIALIZED\"):\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex 49705d51..3bff6e22 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -29,6 +29,7 @@ class TestClickhouse(Validator):\n self.assertEqual(expr.sql(dialect=\"clickhouse\"), \"COUNT(x)\")\n self.assertIsNone(expr._meta)\n \n+ self.validate_identity(\"WITH arrayJoin([(1, [2, 3])]) AS arr SELECT arr\")\n self.validate_identity(\"CAST(1 AS Bool)\")\n self.validate_identity(\"SELECT toString(CHAR(104.1, 101, 108.9, 108.9, 111, 32))\")\n self.validate_identity(\"@macro\").assert_is(exp.Parameter).this.assert_is(exp.Var)\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"]}, {"instance_id": "tobymao__sqlglot-4550", "base_commit": "cead7c32bef44c0efaf48c2038976c7c7f2b709c", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 9d65e57e..56a347ab 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2291,6 +2291,7 @@ class OnConflict(Expression):\n \"action\": False,\n \"conflict_keys\": False,\n \"constraint\": False,\n+ \"where\": False,\n }\n \n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex f30472fd..f717e312 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1861,7 +1861,8 @@ class Generator(metaclass=_Generator):\n set_keyword = \"SET \" if self.DUPLICATE_KEY_UPDATE_WITH_SET else \"\"\n expressions = f\" {set_keyword}{expressions}\"\n \n- return f\"{conflict}{constraint}{conflict_keys}{action}{expressions}\"\n+ where = self.sql(expression, \"where\")\n+ return f\"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}\"\n \n def returning_sql(self, expression: exp.Returning) -> str:\n return f\"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 2fa9ab44..0e525e7a 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -2732,6 +2732,8 @@ class Parser(metaclass=_Parser):\n if not is_function\n else self._parse_function()\n )\n+ if isinstance(this, exp.Table) and self._match(TokenType.ALIAS, advance=False):\n+ this.set(\"alias\", self._parse_table_alias())\n \n returning = self._parse_returning()\n \n@@ -2796,6 +2798,7 @@ class Parser(metaclass=_Parser):\n action=action,\n conflict_keys=conflict_keys,\n constraint=constraint,\n+ where=self._parse_where(),\n )\n \n def _parse_returning(self) -> t.Optional[exp.Returning]:\n", "test_patch": "diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex acdb2d4a..019a10e9 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -874,6 +874,9 @@ class TestPostgres(Validator):\n self.validate_identity(\"ALTER TABLE t1 SET ACCESS METHOD method\")\n self.validate_identity(\"ALTER TABLE t1 SET TABLESPACE tablespace\")\n self.validate_identity(\"ALTER TABLE t1 SET (fillfactor = 5, autovacuum_enabled = TRUE)\")\n+ self.validate_identity(\n+ \"INSERT INTO newtable AS t(a, b, c) VALUES (1, 2, 3) ON CONFLICT(c) DO UPDATE SET a = t.a + 1 WHERE t.a < 1\"\n+ )\n self.validate_identity(\n \"ALTER TABLE tested_table ADD CONSTRAINT unique_example UNIQUE (column_name) NOT VALID\"\n )\n", "FAIL_TO_PASS": ["tests/dialects/test_postgres.py::TestPostgres::test_ddl"]}, {"instance_id": "tobymao__sqlglot-4563", "base_commit": "795e7e0e857486417ce98246389849fc09ccb60a", "gold_patch": "diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py\nindex 7aa7a0e2..44909d32 100644\n--- a/sqlglot/dialects/tsql.py\n+++ b/sqlglot/dialects/tsql.py\n@@ -948,6 +948,7 @@ class TSQL(Dialect):\n exp.TsOrDsAdd: date_delta_sql(\"DATEADD\", cast=True),\n exp.TsOrDsDiff: date_delta_sql(\"DATEDIFF\"),\n exp.TimestampTrunc: lambda self, e: self.func(\"DATETRUNC\", e.unit, e.this),\n+ exp.DateFromParts: rename_func(\"DATEFROMPARTS\"),\n }\n \n TRANSFORMS.pop(exp.ReturnsProperty)\n", "test_patch": "diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py\nindex 4c61780d..b3ad79cd 100644\n--- a/tests/dialects/test_tsql.py\n+++ b/tests/dialects/test_tsql.py\n@@ -1220,7 +1220,10 @@ WHERE\n def test_datefromparts(self):\n self.validate_all(\n \"SELECT DATEFROMPARTS('2020', 10, 01)\",\n- write={\"spark\": \"SELECT MAKE_DATE('2020', 10, 01)\"},\n+ write={\n+ \"spark\": \"SELECT MAKE_DATE('2020', 10, 01)\",\n+ \"tsql\": \"SELECT DATEFROMPARTS('2020', 10, 01)\",\n+ },\n )\n \n def test_datename(self):\n", "FAIL_TO_PASS": ["tests/dialects/test_tsql.py::TestTSQL::test_datefromparts"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_tsql.py::TestTSQL::test_datefromparts"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "briancurtin__deprecation-12_x3", "level": 3, "source": "swerebench", "repo": "briancurtin/deprecation", "image": "swerebench/sweb.eval.x86_64.briancurtin_1776_deprecation-12:latest", "base_commit": "70bb27fef996b214d7b698ed3124fb598220eea9", "num_bugs": 3, "bugs": [{"instance_id": "briancurtin__deprecation-12", "base_commit": "70bb27fef996b214d7b698ed3124fb598220eea9", "gold_patch": "diff --git a/deprecation.py b/deprecation.py\nindex 28a21ee..00598db 100644\n--- a/deprecation.py\n+++ b/deprecation.py\n@@ -10,6 +10,7 @@\n # License for the specific language governing permissions and limitations\n # under the License.\n import functools\n+import textwrap\n import warnings\n \n from packaging import version\n@@ -167,8 +168,31 @@ def deprecated(deprecated_in=None, removed_in=None, current_version=None,\n deprecation_note = (\"*Deprecated{deprecated_in}{removed_in}\"\n \"{period}{details}*\".format(**parts))\n \n- function.__doc__ = \"\\n\\n\".join([existing_docstring,\n+ pos = existing_docstring.find(\"\\n\")\n+\n+ if pos != -1:\n+ # With a multi-line docstring, when we modify\n+ # existing_docstring to add our deprecation_note,\n+ # if we're not careful we'll interfere with the\n+ # indentation levels of the contents below the\n+ # first line, or as PEP 257 calls it, the summary\n+ # line. Since the summary line can start on the\n+ # same line as the \"\"\", dedenting the whole thing\n+ # won't help. Split the summary and contents up,\n+ # dedent the contents independently, then join\n+ # summary, dedent'ed contents, and our\n+ # deprecation_note.\n+\n+ summary = existing_docstring[:pos]\n+ contents = existing_docstring[pos:]\n+\n+ function.__doc__ = \"\".join([summary,\n+ textwrap.dedent(contents),\n+ \"\\n\\n\",\n deprecation_note])\n+ else:\n+ function.__doc__ = \"\\n\\n\".join([existing_docstring,\n+ deprecation_note])\n \n @functools.wraps(function)\n def _inner(*args, **kwargs):\ndiff --git a/sample.py b/sample.py\nindex be00938..9373753 100644\n--- a/sample.py\n+++ b/sample.py\n@@ -14,6 +14,19 @@ def won():\n return 1\n \n \n+@deprecation.deprecated(deprecated_in=\"1.0\", removed_in=\"2.0\",\n+ current_version=__version__,\n+ details=\"Use the ``one`` function instead\")\n+def uno():\n+ \"\"\"Esta funci\u00f3n regresa 1\n+\n+ This is Spanish for 'This function returns 1'\n+\n+ This is also here to show that multiline docstrings work\n+ \"\"\"\n+ return 1\n+\n+\n def one():\n \"\"\"This function returns 1\"\"\"\n return 1\ndiff --git a/setup.py b/setup.py\nindex ffe453a..3da8a87 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -28,6 +28,7 @@ setup(name=\"deprecation\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n+ \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n \"Topic :: Software Development :: Libraries :: Python Modules\"]\ndiff --git a/tox.ini b/tox.ini\nindex 3458187..026704c 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -1,5 +1,5 @@\n [tox]\n-envlist = py35,py34,py27,pypy,flake8\n+envlist = py37,py36,py35,py34,py27,pypy3,pypy,flake8\n skipsdist = True\n \n [testenv]\n", "test_patch": "diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py\nindex 3364f9c..cf9d420 100644\n--- a/tests/test_deprecation.py\n+++ b/tests/test_deprecation.py\n@@ -43,6 +43,30 @@ class Test_deprecated(unittest2.TestCase):\n \n self.assertEqual(fn.__doc__, test[\"__doc__\"])\n \n+ def test_multiline_docstring(self):\n+ docstring = \"summary line\\n\\ndetails\\nand more details\\n\"\n+ for test in [{\"args\": {},\n+ \"__doc__\": \"%s\\n\\n*Deprecated*\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\"},\n+ \"__doc__\": \"%s\\n\\n*Deprecated in 1.0.*\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\", \"removed_in\": \"2.0\"},\n+ \"__doc__\": \"%s\\n\\n*Deprecated in 1.0, \"\n+ \"to be removed in 2.0.*\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\", \"removed_in\": \"2.0\",\n+ \"details\": \"some details\"},\n+ \"__doc__\": \"%s\\n\\n*Deprecated in 1.0, \"\n+ \"to be removed in 2.0. some details*\"}]:\n+ with self.subTest(**test):\n+ @deprecation.deprecated(**test[\"args\"])\n+ def fn():\n+ \"\"\"summary line\n+\n+ details\n+ and more details\n+ \"\"\"\n+\n+ self.assertEqual(fn.__doc__, test[\"__doc__\"] % docstring)\n+\n def test_warning_raised(self):\n ret_val = \"lololol\"\n \n", "FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_multiline_docstring"]}, {"instance_id": "briancurtin__deprecation-14", "base_commit": "3ad94c2de7c313d0ca20a8ce4c9247a0faaa8018", "gold_patch": "diff --git a/deprecation.py b/deprecation.py\nindex 00598db..a64b5b7 100644\n--- a/deprecation.py\n+++ b/deprecation.py\n@@ -9,6 +9,7 @@\n # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n # License for the specific language governing permissions and limitations\n # under the License.\n+import collections\n import functools\n import textwrap\n import warnings\n@@ -51,9 +52,22 @@ class DeprecatedWarning(DeprecationWarning):\n super(DeprecatedWarning, self).__init__()\n \n def __str__(self):\n- return (\"%s is deprecated as of %s and will \"\n- \"be removed in %s. %s\" % (self.function, self.deprecated_in,\n- self.removed_in, self.details))\n+ # Use a defaultdict to give us the empty string\n+ # when a part isn't included.\n+ parts = collections.defaultdict(str)\n+ parts[\"function\"] = self.function\n+\n+ if self.deprecated_in:\n+ parts[\"deprecated\"] = \" as of %s\" % self.deprecated_in\n+ if self.removed_in:\n+ parts[\"removed\"] = \" and will be removed in %s\" % self.removed_in\n+ if any([self.deprecated_in, self.removed_in, self.details]):\n+ parts[\"period\"] = \".\"\n+ if self.details:\n+ parts[\"details\"] = \" %s\" % self.details\n+\n+ return (\"%(function)s is deprecated%(deprecated)s%(removed)s\"\n+ \"%(period)s%(details)s\" % (parts))\n \n \n class UnsupportedWarning(DeprecatedWarning):\n@@ -67,9 +81,15 @@ class UnsupportedWarning(DeprecatedWarning):\n \"\"\"\n \n def __str__(self):\n- return (\"%s is unsupported as of %s. %s\" % (self.function,\n- self.removed_in,\n- self.details))\n+ parts = collections.defaultdict(str)\n+ parts[\"function\"] = self.function\n+ parts[\"removed\"] = self.removed_in\n+\n+ if self.details:\n+ parts[\"details\"] = \" %s\" % self.details\n+\n+ return (\"%(function)s is unsupported as of %(removed)s.\"\n+ \"%(details)s\" % (parts))\n \n \n def deprecated(deprecated_in=None, removed_in=None, current_version=None,\n", "test_patch": "diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py\nindex cf9d420..55e05bd 100644\n--- a/tests/test_deprecation.py\n+++ b/tests/test_deprecation.py\n@@ -71,14 +71,33 @@ class Test_deprecated(unittest2.TestCase):\n ret_val = \"lololol\"\n \n for test in [{\"args\": {}, # No args just means deprecated\n- \"warning\": deprecation.DeprecatedWarning},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated\"},\n+ {\"args\": {\"details\": \"do something else.\"},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated. do something else.\"},\n {\"args\": {\"deprecated_in\": \"1.0\",\n \"current_version\": \"2.0\"},\n- \"warning\": deprecation.DeprecatedWarning},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": \"method is deprecated as of 1.0.\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\",\n+ \"removed_in\": \"3.0\",\n+ \"current_version\": \"2.0\"},\n+ \"warning\": deprecation.DeprecatedWarning,\n+ \"message\": (\"method is deprecated as of 1.0 \"\n+ \"and will be removed in 3.0.\")},\n {\"args\": {\"deprecated_in\": \"1.0\",\n \"removed_in\": \"2.0\",\n \"current_version\": \"2.0\"},\n- \"warning\": deprecation.UnsupportedWarning}]:\n+ \"warning\": deprecation.UnsupportedWarning,\n+ \"message\": \"method is unsupported as of 2.0.\"},\n+ {\"args\": {\"deprecated_in\": \"1.0\",\n+ \"removed_in\": \"2.0\",\n+ \"current_version\": \"2.0\",\n+ \"details\": \"do something else.\"},\n+ \"warning\": deprecation.UnsupportedWarning,\n+ \"message\": (\"method is unsupported as of 2.0. \"\n+ \"do something else.\")}]:\n with self.subTest(**test):\n class Test(object):\n @deprecation.deprecated(**test[\"args\"])\n@@ -93,6 +112,8 @@ class Test_deprecated(unittest2.TestCase):\n \n self.assertEqual(len(caught_warnings), 1)\n self.assertEqual(caught_warnings[0].category, test[\"warning\"])\n+ self.assertEqual(str(caught_warnings[0].message),\n+ test[\"message\"])\n \n def test_DeprecatedWarning_not_raised(self):\n ret_val = \"lololol\"\n", "FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_warning_raised"]}, {"instance_id": "briancurtin__deprecation-37", "base_commit": "c9f228e5900f1875ba304f7da57fedf39ecd2dab", "gold_patch": "diff --git a/deprecation.py b/deprecation.py\nindex 7a80adc..dbeb39e 100644\n--- a/deprecation.py\n+++ b/deprecation.py\n@@ -56,7 +56,8 @@ class DeprecatedWarning(DeprecationWarning):\n self.deprecated_in = deprecated_in\n self.removed_in = removed_in\n self.details = details\n- super(DeprecatedWarning, self).__init__()\n+ super(DeprecatedWarning, self).__init__(function, deprecated_in,\n+ removed_in, details)\n \n def __str__(self):\n # Use a defaultdict to give us the empty string\n", "test_patch": "diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py\nindex 7e4318e..4d294ba 100644\n--- a/tests/test_deprecation.py\n+++ b/tests/test_deprecation.py\n@@ -20,6 +20,11 @@ import deprecation\n \n class Test_deprecated(unittest2.TestCase):\n \n+ def test_args_set_on_base_class(self):\n+ args = (1, 2, 3, 4)\n+ dw = deprecation.DeprecatedWarning(*args)\n+ self.assertEqual(dw.args, args)\n+\n def test_removing_without_deprecating(self):\n self.assertRaises(TypeError, deprecation.deprecated,\n deprecated_in=None, removed_in=\"1.0\")\n", "FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_args_set_on_base_class"]}], "all_FAIL_TO_PASS": ["tests/test_deprecation.py::Test_deprecated::test_multiline_docstring", "tests/test_deprecation.py::Test_deprecated::test_warning_raised", "tests/test_deprecation.py::Test_deprecated::test_args_set_on_base_class"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-749_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-749:latest", "base_commit": "a936dd21a396dab3008e11f842673d18d8810f25", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-749", "base_commit": "a936dd21a396dab3008e11f842673d18d8810f25", "gold_patch": "diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py\nindex 4353164a..c4476d98 100644\n--- a/sqlglot/dialects/postgres.py\n+++ b/sqlglot/dialects/postgres.py\n@@ -74,6 +74,12 @@ def _trim_sql(self, expression):\n return f\"TRIM({trim_type}{remove_chars}{from_part}{target}{collation})\"\n \n \n+def _datatype_sql(self, expression):\n+ if expression.this == exp.DataType.Type.ARRAY:\n+ return f\"{self.expressions(expression, flat=True)}[]\"\n+ return self.datatype_sql(expression)\n+\n+\n def _auto_increment_to_serial(expression):\n auto = expression.find(exp.AutoIncrementColumnConstraint)\n \n@@ -191,25 +197,27 @@ class Postgres(Dialect):\n KEYWORDS = {\n **tokens.Tokenizer.KEYWORDS,\n \"ALWAYS\": TokenType.ALWAYS,\n- \"BY DEFAULT\": TokenType.BY_DEFAULT,\n- \"IDENTITY\": TokenType.IDENTITY,\n- \"GENERATED\": TokenType.GENERATED,\n- \"DOUBLE PRECISION\": TokenType.DOUBLE,\n- \"BIGSERIAL\": TokenType.BIGSERIAL,\n- \"SERIAL\": TokenType.SERIAL,\n- \"SMALLSERIAL\": TokenType.SMALLSERIAL,\n- \"UUID\": TokenType.UUID,\n- \"TEMP\": TokenType.TEMPORARY,\n- \"BEGIN TRANSACTION\": TokenType.BEGIN,\n \"BEGIN\": TokenType.COMMAND,\n+ \"BEGIN TRANSACTION\": TokenType.BEGIN,\n+ \"BIGSERIAL\": TokenType.BIGSERIAL,\n+ \"BY DEFAULT\": TokenType.BY_DEFAULT,\n \"COMMENT ON\": TokenType.COMMAND,\n \"DECLARE\": TokenType.COMMAND,\n \"DO\": TokenType.COMMAND,\n+ \"DOUBLE PRECISION\": TokenType.DOUBLE,\n+ \"GENERATED\": TokenType.GENERATED,\n+ \"GRANT\": TokenType.COMMAND,\n+ \"HSTORE\": TokenType.HSTORE,\n+ \"IDENTITY\": TokenType.IDENTITY,\n+ \"JSONB\": TokenType.JSONB,\n \"REFRESH\": TokenType.COMMAND,\n \"REINDEX\": TokenType.COMMAND,\n \"RESET\": TokenType.COMMAND,\n \"REVOKE\": TokenType.COMMAND,\n- \"GRANT\": TokenType.COMMAND,\n+ \"SERIAL\": TokenType.SERIAL,\n+ \"SMALLSERIAL\": TokenType.SMALLSERIAL,\n+ \"TEMP\": TokenType.TEMPORARY,\n+ \"UUID\": TokenType.UUID,\n **{f\"CREATE {kind}\": TokenType.COMMAND for kind in CREATABLES},\n **{f\"DROP {kind}\": TokenType.COMMAND for kind in CREATABLES},\n }\n@@ -265,4 +273,5 @@ class Postgres(Dialect):\n exp.Trim: _trim_sql,\n exp.TryCast: no_trycast_sql,\n exp.UnixToTime: lambda self, e: f\"TO_TIMESTAMP({self.sql(e, 'this')})\",\n+ exp.DataType: _datatype_sql,\n }\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 357d375a..ae26db94 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2020,6 +2020,7 @@ class DataType(Expression):\n DECIMAL = auto()\n BOOLEAN = auto()\n JSON = auto()\n+ JSONB = auto()\n INTERVAL = auto()\n TIMESTAMP = auto()\n TIMESTAMPTZ = auto()\n@@ -2034,6 +2035,7 @@ class DataType(Expression):\n STRUCT = auto()\n NULLABLE = auto()\n HLLSKETCH = auto()\n+ HSTORE = auto()\n SUPER = auto()\n SERIAL = auto()\n SMALLSERIAL = auto()\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 7830f62e..a543ad18 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -104,6 +104,7 @@ class Parser(metaclass=_Parser):\n TokenType.BINARY,\n TokenType.VARBINARY,\n TokenType.JSON,\n+ TokenType.JSONB,\n TokenType.INTERVAL,\n TokenType.TIMESTAMP,\n TokenType.TIMESTAMPTZ,\n@@ -115,6 +116,7 @@ class Parser(metaclass=_Parser):\n TokenType.GEOGRAPHY,\n TokenType.GEOMETRY,\n TokenType.HLLSKETCH,\n+ TokenType.HSTORE,\n TokenType.SUPER,\n TokenType.SERIAL,\n TokenType.SMALLSERIAL,\n@@ -1727,17 +1729,6 @@ class Parser(metaclass=_Parser):\n expressions = None\n maybe_func = False\n \n- if not nested and self._match_pair(TokenType.L_BRACKET, TokenType.R_BRACKET):\n- return exp.DataType(\n- this=exp.DataType.Type.ARRAY,\n- expressions=[exp.DataType.build(type_token.value)],\n- nested=True,\n- )\n-\n- if self._match(TokenType.L_BRACKET):\n- self._retreat(index)\n- return None\n-\n if self._match(TokenType.L_PAREN):\n if is_struct:\n expressions = self._parse_csv(self._parse_struct_kwargs)\n@@ -1753,6 +1744,17 @@ class Parser(metaclass=_Parser):\n self._match_r_paren()\n maybe_func = True\n \n+ if not nested and self._match_pair(TokenType.L_BRACKET, TokenType.R_BRACKET):\n+ return exp.DataType(\n+ this=exp.DataType.Type.ARRAY,\n+ expressions=[exp.DataType.build(type_token.value, expressions=expressions)],\n+ nested=True,\n+ )\n+\n+ if self._match(TokenType.L_BRACKET):\n+ self._retreat(index)\n+ return None\n+\n if nested and self._match(TokenType.LT):\n if is_struct:\n expressions = self._parse_csv(self._parse_struct_kwargs)\ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex 6d447dd7..fa006268 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -81,6 +81,7 @@ class TokenType(AutoName):\n BINARY = auto()\n VARBINARY = auto()\n JSON = auto()\n+ JSONB = auto()\n TIMESTAMP = auto()\n TIMESTAMPTZ = auto()\n TIMESTAMPLTZ = auto()\n@@ -91,6 +92,7 @@ class TokenType(AutoName):\n NULLABLE = auto()\n GEOMETRY = auto()\n HLLSKETCH = auto()\n+ HSTORE = auto()\n SUPER = auto()\n SERIAL = auto()\n SMALLSERIAL = auto()\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 625156b5..06787022 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -89,6 +89,7 @@ class TestDuckDB(Validator):\n \"presto\": \"CAST(COL AS ARRAY(BIGINT))\",\n \"hive\": \"CAST(COL AS ARRAY)\",\n \"spark\": \"CAST(COL AS ARRAY)\",\n+ \"postgres\": \"CAST(COL AS BIGINT[])\",\n },\n )\n \ndiff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex 8294eea7..c41fe01d 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -6,6 +6,9 @@ class TestPostgres(Validator):\n dialect = \"postgres\"\n \n def test_ddl(self):\n+ self.validate_identity(\"CREATE TABLE test (foo HSTORE)\")\n+ self.validate_identity(\"CREATE TABLE test (foo JSONB)\")\n+ self.validate_identity(\"CREATE TABLE test (foo VARCHAR(64)[])\")\n self.validate_all(\n \"CREATE TABLE products (product_no INT UNIQUE, name TEXT, price DECIMAL)\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_postgres.py::TestPostgres::test_ddl"]}, {"instance_id": "tobymao__sqlglot-767", "base_commit": "a9431175e5605270c123f30e737c61f18538bf8e", "gold_patch": "diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py\nindex bf737ea5..cd50979e 100644\n--- a/sqlglot/dialects/redshift.py\n+++ b/sqlglot/dialects/redshift.py\n@@ -18,12 +18,14 @@ class Redshift(Postgres):\n \n KEYWORDS = {\n **Postgres.Tokenizer.KEYWORDS, # type: ignore\n+ \"COPY\": TokenType.COMMAND,\n \"GEOMETRY\": TokenType.GEOMETRY,\n \"GEOGRAPHY\": TokenType.GEOGRAPHY,\n \"HLLSKETCH\": TokenType.HLLSKETCH,\n \"SUPER\": TokenType.SUPER,\n \"TIME\": TokenType.TIMESTAMP,\n \"TIMETZ\": TokenType.TIMESTAMPTZ,\n+ \"UNLOAD\": TokenType.COMMAND,\n \"VARBYTE\": TokenType.VARBINARY,\n \"SIMILAR TO\": TokenType.SIMILAR_TO,\n }\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex be9d8573..0cbe5c35 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -466,7 +466,7 @@ class Parser(metaclass=_Parser):\n TokenType.SCHEMA_COMMENT: lambda self: self._parse_property_assignment(\n exp.SchemaCommentProperty\n ),\n- TokenType.STORED: lambda self: self._parse_stored(),\n+ TokenType.STORED: lambda self: self._parse_property_assignment(exp.FileFormatProperty),\n TokenType.DISTKEY: lambda self: self._parse_distkey(),\n TokenType.DISTSTYLE: lambda self: self._parse_property_assignment(exp.DistStyleProperty),\n TokenType.SORTKEY: lambda self: self._parse_sortkey(),\n@@ -480,7 +480,7 @@ class Parser(metaclass=_Parser):\n ),\n TokenType.USING: lambda self: self._parse_property_assignment(exp.TableFormatProperty),\n TokenType.LANGUAGE: lambda self: self._parse_property_assignment(exp.LanguageProperty),\n- TokenType.EXECUTE: lambda self: self._parse_execute_as(),\n+ TokenType.EXECUTE: lambda self: self._parse_property_assignment(exp.ExecuteAsProperty),\n TokenType.DETERMINISTIC: lambda self: self.expression(\n exp.VolatilityProperty, this=exp.Literal.string(\"IMMUTABLE\")\n ),\n@@ -797,7 +797,7 @@ class Parser(metaclass=_Parser):\n )\n \n def _parse_create(self):\n- replace = self._match(TokenType.OR) and self._match(TokenType.REPLACE)\n+ replace = self._match_pair(TokenType.OR, TokenType.REPLACE)\n temporary = self._match(TokenType.TEMPORARY)\n transient = self._match(TokenType.TRANSIENT)\n unique = self._match(TokenType.UNIQUE)\n@@ -867,6 +867,7 @@ class Parser(metaclass=_Parser):\n \n def _parse_property_assignment(self, exp_class):\n self._match(TokenType.EQ)\n+ self._match(TokenType.ALIAS)\n return self.expression(exp_class, this=self._parse_var_or_string() or self._parse_number())\n \n def _parse_partitioned_by(self):\n@@ -876,11 +877,6 @@ class Parser(metaclass=_Parser):\n this=self._parse_schema() or self._parse_bracket(self._parse_field()),\n )\n \n- def _parse_stored(self):\n- self._match(TokenType.ALIAS)\n- self._match(TokenType.EQ)\n- return self.expression(exp.FileFormatProperty, this=self._parse_var_or_string())\n-\n def _parse_distkey(self):\n return self.expression(exp.DistKeyProperty, this=self._parse_wrapped(self._parse_var))\n \n@@ -926,10 +922,6 @@ class Parser(metaclass=_Parser):\n \n return self.expression(exp.ReturnsProperty, this=value, is_table=is_table)\n \n- def _parse_execute_as(self):\n- self._match(TokenType.ALIAS)\n- return self.expression(exp.ExecuteAsProperty, this=self._parse_var())\n-\n def _parse_properties(self):\n properties = []\n \ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex dda0e012..0eef73a7 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -586,8 +586,8 @@ class Tokenizer(metaclass=_Tokenizer):\n \"TRAILING\": TokenType.TRAILING,\n \"UNBOUNDED\": TokenType.UNBOUNDED,\n \"UNION\": TokenType.UNION,\n- \"UNPIVOT\": TokenType.UNPIVOT,\n \"UNNEST\": TokenType.UNNEST,\n+ \"UNPIVOT\": TokenType.UNPIVOT,\n \"UPDATE\": TokenType.UPDATE,\n \"USE\": TokenType.USE,\n \"USING\": TokenType.USING,\n", "test_patch": "diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py\nindex f9dad397..1943ee38 100644\n--- a/tests/dialects/test_redshift.py\n+++ b/tests/dialects/test_redshift.py\n@@ -74,3 +74,9 @@ class TestRedshift(Validator):\n self.validate_identity(\n \"CREATE TABLE sales (salesid INTEGER NOT NULL) DISTKEY(listid) COMPOUND SORTKEY(listid, sellerid)\"\n )\n+ self.validate_identity(\n+ \"COPY customer FROM 's3://mybucket/customer' IAM_ROLE 'arn:aws:iam::0123456789012:role/MyRedshiftRole'\"\n+ )\n+ self.validate_identity(\n+ \"UNLOAD ('select * from venue') TO 's3://mybucket/unload/' IAM_ROLE 'arn:aws:iam::0123456789012:role/MyRedshiftRole'\"\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_redshift.py::TestRedshift::test_identity"]}, {"instance_id": "tobymao__sqlglot-772", "base_commit": "bb8303c7c1c89f2fad7e90c49c2fbb55a6270756", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex da772032..ab35b1f7 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2447,7 +2447,7 @@ class ArrayFilter(Func):\n \n \n class ArraySize(Func):\n- pass\n+ arg_types = {\"this\": True, \"expression\": False}\n \n \n class ArraySort(Func):\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 06787022..4d605506 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -105,6 +105,10 @@ class TestDuckDB(Validator):\n \"spark\": \"ARRAY(0, 1, 2)\",\n },\n )\n+ self.validate_all(\n+ \"SELECT ARRAY_LENGTH([0], 1) AS x\",\n+ write={\"duckdb\": \"SELECT ARRAY_LENGTH(LIST_VALUE(0), 1) AS x\"},\n+ )\n self.validate_all(\n \"REGEXP_MATCHES(x, y)\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_redshift.py::TestRedshift::test_identity", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3272_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3272:latest", "base_commit": "8dfc2e6cdfc1ab9ba8861ee48e539d29b7fa5496", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3272", "base_commit": "8dfc2e6cdfc1ab9ba8861ee48e539d29b7fa5496", "gold_patch": "diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex d9dc2dab..1d53346e 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -461,7 +461,7 @@ class MySQL(Dialect):\n \n this = self._parse_id_var(any_token=False)\n index_type = self._match(TokenType.USING) and self._advance_any() and self._prev.text\n- schema = self._parse_schema()\n+ expressions = self._parse_wrapped_csv(self._parse_ordered)\n \n options = []\n while True:\n@@ -495,7 +495,7 @@ class MySQL(Dialect):\n return self.expression(\n exp.IndexColumnConstraint,\n this=this,\n- schema=schema,\n+ expressions=expressions,\n kind=kind,\n index_type=index_type,\n options=options,\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex fc7de00f..e79c04bd 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -1669,7 +1669,7 @@ class GeneratedAsRowColumnConstraint(ColumnConstraintKind):\n class IndexColumnConstraint(ColumnConstraintKind):\n arg_types = {\n \"this\": False,\n- \"schema\": False,\n+ \"expressions\": False,\n \"kind\": False,\n \"index_type\": False,\n \"options\": False,\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 0408afab..76d9b5d6 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -3421,11 +3421,11 @@ class Generator(metaclass=_Generator):\n this = f\" {this}\" if this else \"\"\n index_type = self.sql(expression, \"index_type\")\n index_type = f\" USING {index_type}\" if index_type else \"\"\n- schema = self.sql(expression, \"schema\")\n- schema = f\" {schema}\" if schema else \"\"\n+ expressions = self.expressions(expression, flat=True)\n+ expressions = f\" ({expressions})\" if expressions else \"\"\n options = self.expressions(expression, key=\"options\", sep=\" \")\n options = f\" {options}\" if options else \"\"\n- return f\"{kind}{this}{index_type}{schema}{options}\"\n+ return f\"{kind}{this}{index_type}{expressions}{options}\"\n \n def nvl2_sql(self, expression: exp.Nvl2) -> str:\n if self.NVL2_SUPPORTED:\n", "test_patch": "diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py\nindex 49552bf5..7a9d6bf5 100644\n--- a/tests/dialects/test_mysql.py\n+++ b/tests/dialects/test_mysql.py\n@@ -92,6 +92,10 @@ class TestMySQL(Validator):\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC\",\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()) DEFAULT CHARACTER SET=utf8 ROW_FORMAT=DYNAMIC\",\n )\n+ self.validate_identity(\n+ \"CREATE TABLE `foo` (a VARCHAR(10), KEY idx_a (a DESC))\",\n+ \"CREATE TABLE `foo` (a VARCHAR(10), INDEX idx_a (a DESC))\",\n+ )\n \n self.validate_all(\n \"CREATE TABLE z (a INT) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARACTER SET=utf8 COLLATE=utf8_bin COMMENT='x'\",\n", "FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_ddl"]}, {"instance_id": "tobymao__sqlglot-3284", "base_commit": "46fbd8d9b7684d7c1613a264117c1bd5d6571999", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 702aaff6..6e1c2ce0 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2225,6 +2225,13 @@ class Lateral(UDTF):\n }\n \n \n+class MatchRecognizeMeasure(Expression):\n+ arg_types = {\n+ \"this\": True,\n+ \"window_frame\": False,\n+ }\n+\n+\n class MatchRecognize(Expression):\n arg_types = {\n \"partition_by\": False,\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 1cb469aa..6563accb 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -2111,6 +2111,14 @@ class Generator(metaclass=_Generator):\n \n return f\"{this}{sort_order}{nulls_sort_change}{with_fill}\"\n \n+ def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:\n+ window_frame = self.sql(expression, \"window_frame\")\n+ window_frame = f\"{window_frame} \" if window_frame else \"\"\n+\n+ this = self.sql(expression, \"this\")\n+\n+ return f\"{window_frame}{this}\"\n+\n def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:\n partition = self.partition_by_sql(expression)\n order = self.sql(expression, \"order\")\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 5c68be0a..ab91576f 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -2738,6 +2738,13 @@ class Parser(metaclass=_Parser):\n exp.From, comments=self._prev_comments, this=self._parse_table(joins=joins)\n )\n \n+ def _parse_match_recognize_measure(self) -> exp.MatchRecognizeMeasure:\n+ return self.expression(\n+ exp.MatchRecognizeMeasure,\n+ window_frame=self._match_texts((\"FINAL\", \"RUNNING\")) and self._prev.text.upper(),\n+ this=self._parse_expression(),\n+ )\n+\n def _parse_match_recognize(self) -> t.Optional[exp.MatchRecognize]:\n if not self._match(TokenType.MATCH_RECOGNIZE):\n return None\n@@ -2746,7 +2753,12 @@ class Parser(metaclass=_Parser):\n \n partition = self._parse_partition_by()\n order = self._parse_order()\n- measures = self._parse_expressions() if self._match_text_seq(\"MEASURES\") else None\n+\n+ measures = (\n+ self._parse_csv(self._parse_match_recognize_measure)\n+ if self._match_text_seq(\"MEASURES\")\n+ else None\n+ )\n \n if self._match_text_seq(\"ONE\", \"ROW\", \"PER\", \"MATCH\"):\n rows = exp.var(\"ONE ROW PER MATCH\")\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex a41d35a0..a16bd993 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -1575,22 +1575,26 @@ FROM persons AS p, LATERAL FLATTEN(input => p.c, path => 'contact') AS _flattene\n )\n \n def test_match_recognize(self):\n- for row in (\n- \"ONE ROW PER MATCH\",\n- \"ALL ROWS PER MATCH\",\n- \"ALL ROWS PER MATCH SHOW EMPTY MATCHES\",\n- \"ALL ROWS PER MATCH OMIT EMPTY MATCHES\",\n- \"ALL ROWS PER MATCH WITH UNMATCHED ROWS\",\n- ):\n- for after in (\n- \"AFTER MATCH SKIP\",\n- \"AFTER MATCH SKIP PAST LAST ROW\",\n- \"AFTER MATCH SKIP TO NEXT ROW\",\n- \"AFTER MATCH SKIP TO FIRST x\",\n- \"AFTER MATCH SKIP TO LAST x\",\n+ for window_frame in (\"\", \"FINAL \", \"RUNNING \"):\n+ for row in (\n+ \"ONE ROW PER MATCH\",\n+ \"ALL ROWS PER MATCH\",\n+ \"ALL ROWS PER MATCH SHOW EMPTY MATCHES\",\n+ \"ALL ROWS PER MATCH OMIT EMPTY MATCHES\",\n+ \"ALL ROWS PER MATCH WITH UNMATCHED ROWS\",\n ):\n- self.validate_identity(\n- f\"\"\"SELECT\n+ for after in (\n+ \"AFTER MATCH SKIP\",\n+ \"AFTER MATCH SKIP PAST LAST ROW\",\n+ \"AFTER MATCH SKIP TO NEXT ROW\",\n+ \"AFTER MATCH SKIP TO FIRST x\",\n+ \"AFTER MATCH SKIP TO LAST x\",\n+ ):\n+ with self.subTest(\n+ f\"MATCH_RECOGNIZE with window frame {window_frame}, rows {row}, after {after}: \"\n+ ):\n+ self.validate_identity(\n+ f\"\"\"SELECT\n *\n FROM x\n MATCH_RECOGNIZE (\n@@ -1598,15 +1602,15 @@ MATCH_RECOGNIZE (\n ORDER BY\n x DESC\n MEASURES\n- y AS b\n+ {window_frame}y AS b\n {row}\n {after}\n PATTERN (^ S1 S2*? ( {{- S3 -}} S4 )+ | PERMUTE(S1, S2){{1,2}} $)\n DEFINE\n x AS y\n )\"\"\",\n- pretty=True,\n- )\n+ pretty=True,\n+ )\n \n def test_show_users(self):\n self.validate_identity(\"SHOW USERS\")\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize"]}, {"instance_id": "tobymao__sqlglot-3290", "base_commit": "02218fc4f75d22487976572f51bd131170a728e5", "gold_patch": "diff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 6563accb..b3e586c7 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1803,10 +1803,15 @@ class Generator(metaclass=_Generator):\n return f\"{self.seg('FROM')} {self.sql(expression, 'this')}\"\n \n def group_sql(self, expression: exp.Group) -> str:\n- group_by = self.op_expressions(\"GROUP BY\", expression)\n+ group_by_all = expression.args.get(\"all\")\n+ if group_by_all is True:\n+ modifier = \" ALL\"\n+ elif group_by_all is False:\n+ modifier = \" DISTINCT\"\n+ else:\n+ modifier = \"\"\n \n- if expression.args.get(\"all\"):\n- return f\"{group_by} ALL\"\n+ group_by = self.op_expressions(f\"GROUP BY{modifier}\", expression)\n \n grouping_sets = self.expressions(expression, key=\"grouping_sets\", indent=False)\n grouping_sets = (\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex ab91576f..c438a703 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3463,10 +3463,12 @@ class Parser(metaclass=_Parser):\n if not skip_group_by_token and not self._match(TokenType.GROUP_BY):\n return None\n \n- elements = defaultdict(list)\n+ elements: t.Dict[str, t.Any] = defaultdict(list)\n \n if self._match(TokenType.ALL):\n- return self.expression(exp.Group, all=True)\n+ elements[\"all\"] = True\n+ elif self._match(TokenType.DISTINCT):\n+ elements[\"all\"] = False\n \n while True:\n expressions = self._parse_csv(self._parse_conjunction)\n", "test_patch": "diff --git a/tests/dialects/test_presto.py b/tests/dialects/test_presto.py\nindex 5df3d0e8..e1d8c068 100644\n--- a/tests/dialects/test_presto.py\n+++ b/tests/dialects/test_presto.py\n@@ -612,6 +612,15 @@ class TestPresto(Validator):\n self.validate_identity(\n \"SELECT * FROM example.testdb.customer_orders FOR TIMESTAMP AS OF CAST('2022-03-23 09:59:29.803 Europe/Vienna' AS TIMESTAMP)\"\n )\n+ self.validate_identity(\n+ \"SELECT origin_state, destination_state, origin_zip, SUM(package_weight) FROM shipping GROUP BY ALL CUBE (origin_state, destination_state), ROLLUP (origin_state, origin_zip)\"\n+ )\n+ self.validate_identity(\n+ \"SELECT origin_state, destination_state, origin_zip, SUM(package_weight) FROM shipping GROUP BY DISTINCT CUBE (origin_state, destination_state), ROLLUP (origin_state, origin_zip)\"\n+ )\n+ self.validate_identity(\n+ \"SELECT JSON_EXTRACT_SCALAR(CAST(extra AS JSON), '$.value_b'), COUNT(*) FROM table_a GROUP BY DISTINCT (JSON_EXTRACT_SCALAR(CAST(extra AS JSON), '$.value_b'))\"\n+ )\n \n self.validate_all(\n \"SELECT LAST_DAY_OF_MONTH(CAST('2008-11-25' AS DATE))\",\n", "FAIL_TO_PASS": ["tests/dialects/test_presto.py::TestPresto::test_presto"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_presto.py::TestPresto::test_presto"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "matthewwithanm__python-markdownify-171_x3", "level": 3, "source": "swerebench", "repo": "matthewwithanm/python-markdownify", "image": "swerebench/sweb.eval.x86_64.matthewwithanm_1776_python-markdownify-171:latest", "base_commit": "600f77d2444233b1c5e838b69390cbbf92bde1e1", "num_bugs": 3, "bugs": [{"instance_id": "matthewwithanm__python-markdownify-171", "base_commit": "600f77d2444233b1c5e838b69390cbbf92bde1e1", "gold_patch": "diff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex b70a0e5..fd03569 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -5,7 +5,7 @@ import six\n \n \n convert_heading_re = re.compile(r'convert_h(\\d+)')\n-line_beginning_re = re.compile(r'^', re.MULTILINE)\n+line_with_content_re = re.compile(r'^(.*)', flags=re.MULTILINE)\n whitespace_re = re.compile(r'[\\t ]+')\n all_whitespace_re = re.compile(r'[\\t \\r\\n]+')\n newline_whitespace_re = re.compile(r'[\\t \\r\\n]*[\\r\\n][\\t \\r\\n]*')\n@@ -256,9 +256,6 @@ class MarkdownConverter(object):\n text = text.replace('_', r'\\_')\n return text\n \n- def indent(self, text, columns):\n- return line_beginning_re.sub(' ' * columns, text) if text else ''\n-\n def underline(self, text, pad_char):\n text = (text or '').rstrip()\n return '\\n\\n%s\\n%s\\n\\n' % (text, pad_char * len(text)) if text else ''\n@@ -286,11 +283,20 @@ class MarkdownConverter(object):\n convert_b = abstract_inline_conversion(lambda self: 2 * self.options['strong_em_symbol'])\n \n def convert_blockquote(self, el, text, convert_as_inline):\n-\n+ # handle some early-exit scenarios\n+ text = (text or '').strip()\n if convert_as_inline:\n- return ' ' + text.strip() + ' '\n+ return ' ' + text + ' '\n+ if not text:\n+ return \"\\n\"\n+\n+ # indent lines with blockquote marker\n+ def _indent_for_blockquote(match):\n+ line_content = match.group(1)\n+ return '> ' + line_content if line_content else '>'\n+ text = line_with_content_re.sub(_indent_for_blockquote, text)\n \n- return '\\n' + (line_beginning_re.sub('> ', text.strip()) + '\\n\\n') if text else ''\n+ return '\\n' + text + '\\n\\n'\n \n def convert_br(self, el, text, convert_as_inline):\n if convert_as_inline:\n@@ -371,6 +377,12 @@ class MarkdownConverter(object):\n convert_ol = convert_list\n \n def convert_li(self, el, text, convert_as_inline):\n+ # handle some early-exit scenarios\n+ text = (text or '').strip()\n+ if not text:\n+ return \"\\n\"\n+\n+ # determine list item bullet character to use\n parent = el.parent\n if parent is not None and parent.name == 'ol':\n if parent.get(\"start\") and str(parent.get(\"start\")).isnumeric():\n@@ -387,10 +399,18 @@ class MarkdownConverter(object):\n bullets = self.options['bullets']\n bullet = bullets[depth % len(bullets)]\n bullet = bullet + ' '\n- text = (text or '').strip()\n- text = self.indent(text, len(bullet))\n- if text:\n- text = bullet + text[len(bullet):]\n+ bullet_width = len(bullet)\n+ bullet_indent = ' ' * bullet_width\n+\n+ # indent content lines by bullet width\n+ def _indent_for_li(match):\n+ line_content = match.group(1)\n+ return bullet_indent + line_content if line_content else ''\n+ text = line_with_content_re.sub(_indent_for_li, text)\n+\n+ # insert bullet into first-line indent whitespace\n+ text = bullet + text[bullet_width:]\n+\n return '%s\\n' % text\n \n def convert_p(self, el, text, convert_as_inline):\n", "test_patch": "diff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex 01f8b91..868db7c 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -62,7 +62,7 @@ def test_blockquote():\n \n def test_blockquote_with_nested_paragraph():\n assert md('

    Hello

    ') == '\\n> Hello\\n\\n'\n- assert md('

    Hello

    Hello again

    ') == '\\n> Hello\\n> \\n> Hello again\\n\\n'\n+ assert md('

    Hello

    Hello again

    ') == '\\n> Hello\\n>\\n> Hello again\\n\\n'\n \n \n def test_blockquote_with_paragraph():\ndiff --git a/tests/test_lists.py b/tests/test_lists.py\nindex a660778..ce54a87 100644\n--- a/tests/test_lists.py\n+++ b/tests/test_lists.py\n@@ -47,7 +47,7 @@ def test_ol():\n assert md('
    1. a
    2. b
    ') == '\\n\\n1. a\\n2. b\\n'\n assert md('
    1. a
    2. b
    ') == '\\n\\n1. a\\n2. b\\n'\n assert md('
    1. a
    2. b
    ') == '\\n\\n1. a\\n2. b\\n'\n- assert md('
    1. first para

      second para

    2. third para

      fourth para

    ') == '\\n\\n1234. first para\\n \\n second para\\n1235. third para\\n \\n fourth para\\n'\n+ assert md('
    1. first para

      second para

    2. third para

      fourth para

    ') == '\\n\\n1234. first para\\n\\n second para\\n1235. third para\\n\\n fourth para\\n'\n \n \n def test_nested_ols():\n@@ -64,7 +64,7 @@ def test_ul():\n
  • c\n
  • \n \"\"\") == '\\n\\n* a\\n* b\\n* c\\n'\n- assert md('
    • first para

      second para

    • third para

      fourth para

    ') == '\\n\\n* first para\\n \\n second para\\n* third para\\n \\n fourth para\\n'\n+ assert md('
    • first para

      second para

    • third para

      fourth para

    ') == '\\n\\n* first para\\n\\n second para\\n* third para\\n\\n fourth para\\n'\n \n \n def test_inline_ul():\n", "FAIL_TO_PASS": ["tests/test_conversions.py::test_blockquote_with_nested_paragraph", "tests/test_lists.py::test_ol", "tests/test_lists.py::test_ul"]}, {"instance_id": "matthewwithanm__python-markdownify-173", "base_commit": "f73a4353150c2bb99f3dc8c733cb997cb45a6ac7", "gold_patch": "diff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex fd03569..ac53077 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -319,6 +319,38 @@ class MarkdownConverter(object):\n \n convert_kbd = convert_code\n \n+ def convert_dd(self, el, text, convert_as_inline):\n+ text = (text or '').strip()\n+ if convert_as_inline:\n+ return ' ' + text + ' '\n+ if not text:\n+ return '\\n'\n+\n+ # indent definition content lines by four spaces\n+ def _indent_for_dd(match):\n+ line_content = match.group(1)\n+ return ' ' + line_content if line_content else ''\n+ text = line_with_content_re.sub(_indent_for_dd, text)\n+\n+ # insert definition marker into first-line indent whitespace\n+ text = ':' + text[1:]\n+\n+ return '%s\\n' % text\n+\n+ def convert_dt(self, el, text, convert_as_inline):\n+ # remove newlines from term text\n+ text = (text or '').strip()\n+ text = all_whitespace_re.sub(' ', text)\n+ if convert_as_inline:\n+ return ' ' + text + ' '\n+ if not text:\n+ return '\\n'\n+\n+ # TODO - format consecutive
    elements as directly adjacent lines):\n+ # https://michelf.ca/projects/php-markdown/extra/#def-list\n+\n+ return '\\n%s\\n' % text\n+\n def _convert_hn(self, n, el, text, convert_as_inline):\n \"\"\" Method name prefixed with _ to prevent to call this \"\"\"\n if convert_as_inline:\n", "test_patch": "diff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex 868db7c..cc5ebc7 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -104,6 +104,16 @@ def test_code():\n assert md('foobarbaz', sub_symbol='^') == '`foobarbaz`'\n \n \n+def test_dl():\n+ assert md('
    term
    definition
    ') == '\\nterm\\n: definition\\n'\n+ assert md('

    te

    rm

    definition
    ') == '\\nte rm\\n: definition\\n'\n+ assert md('
    term

    definition-p1

    definition-p2

    ') == '\\nterm\\n: definition-p1\\n\\n definition-p2\\n'\n+ assert md('
    term

    definition 1

    definition 2

    ') == '\\nterm\\n: definition 1\\n: definition 2\\n'\n+ assert md('
    term 1
    definition 1
    term 2
    definition 2
    ') == '\\nterm 1\\n: definition 1\\nterm 2\\n: definition 2\\n'\n+ assert md('
    term

    line 1

    line 2

    ') == '\\nterm\\n: > line 1\\n >\\n > line 2\\n'\n+ assert md('
    term
    1. 1

      • 2a
      • 2b
    2. 3

    ') == '\\nterm\\n: 1. 1\\n\\n * 2a\\n * 2b\\n 2. 3\\n'\n+\n+\n def test_del():\n inline_tests('del', '~~')\n \n", "FAIL_TO_PASS": ["tests/test_conversions.py::test_dl"]}, {"instance_id": "matthewwithanm__python-markdownify-178", "base_commit": "1783995cb2ae2f6a9306c5932c7ec145ce76a900", "gold_patch": "diff --git a/README.rst b/README.rst\nindex af87f51..34ed7e0 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -139,6 +139,11 @@ keep_inline_images_in\n that should be allowed to contain inline images, for example ``['td']``.\n Defaults to an empty list.\n \n+table_infer_header\n+ Controls handling of tables with no header row (as indicated by ````\n+ or ````). When set to ``True``, the first body row is used as the header row.\n+ Defaults to ``False``, which leaves the header row empty.\n+\n wrap, wrap_width\n If ``wrap`` is set to ``True``, all text paragraphs are wrapped at\n ``wrap_width`` characters. Defaults to ``False`` and ``80``.\ndiff --git a/markdownify/__init__.py b/markdownify/__init__.py\nindex ac53077..776e75e 100644\n--- a/markdownify/__init__.py\n+++ b/markdownify/__init__.py\n@@ -102,6 +102,7 @@ class MarkdownConverter(object):\n strong_em_symbol = ASTERISK\n sub_symbol = ''\n sup_symbol = ''\n+ table_infer_header = False\n wrap = False\n wrap_width = 80\n \n@@ -123,9 +124,9 @@ class MarkdownConverter(object):\n return self.convert_soup(soup)\n \n def convert_soup(self, soup):\n- return self.process_tag(soup, convert_as_inline=False, children_only=True)\n+ return self.process_tag(soup, convert_as_inline=False)\n \n- def process_tag(self, node, convert_as_inline, children_only=False):\n+ def process_tag(self, node, convert_as_inline):\n text = ''\n \n # markdown headings or cells can't include\n@@ -134,7 +135,7 @@ class MarkdownConverter(object):\n isCell = node.name in ['td', 'th']\n convert_children_as_inline = convert_as_inline\n \n- if not children_only and (isHeading or isCell):\n+ if isHeading or isCell:\n convert_children_as_inline = True\n \n # Remove whitespace-only textnodes just before, after or\n@@ -170,13 +171,18 @@ class MarkdownConverter(object):\n newlines = '\\n' * max(newlines_left, newlines_right)\n text = text_strip + newlines + next_text_strip\n \n- if not children_only:\n- convert_fn = getattr(self, 'convert_%s' % node.name, None)\n- if convert_fn and self.should_convert_tag(node.name):\n- text = convert_fn(node, text, convert_as_inline)\n+ # apply this tag's final conversion function\n+ convert_fn_name = \"convert_%s\" % re.sub(r\"[\\[\\]:-]\", \"_\", node.name)\n+ convert_fn = getattr(self, convert_fn_name, None)\n+ if convert_fn and self.should_convert_tag(node.name):\n+ text = convert_fn(node, text, convert_as_inline)\n \n return text\n \n+ def convert__document_(self, el, text, convert_as_inline):\n+ # for BeautifulSoup objects (where node.name == \"[document]\"), return content results as-is\n+ return text\n+\n def process_text(self, el):\n text = six.text_type(el) or ''\n \n@@ -367,8 +373,8 @@ class MarkdownConverter(object):\n text = all_whitespace_re.sub(' ', text)\n hashes = '#' * n\n if style == ATX_CLOSED:\n- return '\\n%s %s %s\\n\\n' % (hashes, text, hashes)\n- return '\\n%s %s\\n\\n' % (hashes, text)\n+ return '\\n\\n%s %s %s\\n\\n' % (hashes, text, hashes)\n+ return '\\n\\n%s %s\\n\\n' % (hashes, text)\n \n def convert_hr(self, el, text, convert_as_inline):\n return '\\n\\n---\\n\\n'\n@@ -518,13 +524,24 @@ class MarkdownConverter(object):\n cells = el.find_all(['td', 'th'])\n is_headrow = (\n all([cell.name == 'th' for cell in cells])\n- or (not el.previous_sibling and not el.parent.name == 'tbody')\n+ or (el.parent.name == 'thead'\n+ # avoid multiple tr in thead\n+ and len(el.parent.find_all('tr')) == 1)\n+ )\n+ is_head_row_missing = (\n+ (not el.previous_sibling and not el.parent.name == 'tbody')\n or (not el.previous_sibling and el.parent.name == 'tbody' and len(el.parent.parent.find_all(['thead'])) < 1)\n )\n overline = ''\n underline = ''\n- if is_headrow and not el.previous_sibling:\n- # first row and is headline: print headline underline\n+ if ((is_headrow\n+ or (is_head_row_missing\n+ and self.options['table_infer_header']))\n+ and not el.previous_sibling):\n+ # first row and:\n+ # - is headline or\n+ # - headline is missing and header inference is enabled\n+ # print headline underline\n full_colspan = 0\n for cell in cells:\n if 'colspan' in cell.attrs and cell['colspan'].isdigit():\n@@ -532,13 +549,16 @@ class MarkdownConverter(object):\n else:\n full_colspan += 1\n underline += '| ' + ' | '.join(['---'] * full_colspan) + ' |' + '\\n'\n- elif (not el.previous_sibling\n- and (el.parent.name == 'table'\n- or (el.parent.name == 'tbody'\n- and not el.parent.previous_sibling))):\n+ elif ((is_head_row_missing\n+ and not self.options['table_infer_header'])\n+ or (not el.previous_sibling\n+ and (el.parent.name == 'table'\n+ or (el.parent.name == 'tbody'\n+ and not el.parent.previous_sibling)))):\n+ # headline is missing and header inference is disabled or:\n # first row, not headline, and:\n- # - the parent is table or\n- # - the parent is tbody at the beginning of a table.\n+ # - the parent is table or\n+ # - the parent is tbody at the beginning of a table.\n # print empty headline above this row\n overline += '| ' + ' | '.join([''] * len(cells)) + ' |' + '\\n'\n overline += '| ' + ' | '.join(['---'] * len(cells)) + ' |' + '\\n'\ndiff --git a/markdownify/main.py b/markdownify/main.py\nindex 4e1c874..432efb5 100644\n--- a/markdownify/main.py\n+++ b/markdownify/main.py\n@@ -61,6 +61,10 @@ def main(argv=sys.argv[1:]):\n \"should be converted to markdown images instead, this option can \"\n \"be set to a list of parent tags that should be allowed to \"\n \"contain inline images.\")\n+ parser.add_argument('--table-infer-header', dest='table_infer_header',\n+ action='store_true',\n+ help=\"When a table has no header row (as indicated by '' \"\n+ \"or ''), use the first body row as the header row.\")\n parser.add_argument('-w', '--wrap', action='store_true',\n help=\"Wrap all text paragraphs at --wrap-width characters.\")\n parser.add_argument('--wrap-width', type=int, default=80)\n", "test_patch": "diff --git a/tests/test_conversions.py b/tests/test_conversions.py\nindex cc5ebc7..ba8fcd8 100644\n--- a/tests/test_conversions.py\n+++ b/tests/test_conversions.py\n@@ -127,12 +127,12 @@ def test_em():\n \n \n def test_header_with_space():\n- assert md('

    \\n\\nHello

    ') == '\\n### Hello\\n\\n'\n- assert md('

    Hello\\n\\n\\nWorld

    ') == '\\n### Hello World\\n\\n'\n- assert md('

    \\n\\nHello

    ') == '\\n#### Hello\\n\\n'\n- assert md('
    \\n\\nHello
    ') == '\\n##### Hello\\n\\n'\n- assert md('
    \\n\\nHello\\n\\n
    ') == '\\n##### Hello\\n\\n'\n- assert md('
    \\n\\nHello \\n\\n
    ') == '\\n##### Hello\\n\\n'\n+ assert md('

    \\n\\nHello

    ') == '\\n\\n### Hello\\n\\n'\n+ assert md('

    Hello\\n\\n\\nWorld

    ') == '\\n\\n### Hello World\\n\\n'\n+ assert md('

    \\n\\nHello

    ') == '\\n\\n#### Hello\\n\\n'\n+ assert md('
    \\n\\nHello
    ') == '\\n\\n##### Hello\\n\\n'\n+ assert md('
    \\n\\nHello\\n\\n
    ') == '\\n\\n##### Hello\\n\\n'\n+ assert md('
    \\n\\nHello \\n\\n
    ') == '\\n\\n##### Hello\\n\\n'\n \n \n def test_h1():\n@@ -144,24 +144,24 @@ def test_h2():\n \n \n def test_hn():\n- assert md('

    Hello

    ') == '\\n### Hello\\n\\n'\n- assert md('

    Hello

    ') == '\\n#### Hello\\n\\n'\n- assert md('
    Hello
    ') == '\\n##### Hello\\n\\n'\n- assert md('
    Hello
    ') == '\\n###### Hello\\n\\n'\n+ assert md('

    Hello

    ') == '\\n\\n### Hello\\n\\n'\n+ assert md('

    Hello

    ') == '\\n\\n#### Hello\\n\\n'\n+ assert md('
    Hello
    ') == '\\n\\n##### Hello\\n\\n'\n+ assert md('
    Hello
    ') == '\\n\\n###### Hello\\n\\n'\n assert md('Hello') == md('
    Hello
    ')\n assert md('Hello') == md('Hello')\n \n \n def test_hn_chained():\n- assert md('

    First

    \\n

    Second

    \\n

    Third

    ', heading_style=ATX) == '\\n# First\\n\\n## Second\\n\\n### Third\\n\\n'\n- assert md('X

    First

    ', heading_style=ATX) == 'X\\n# First\\n\\n'\n- assert md('X

    First

    ', heading_style=ATX_CLOSED) == 'X\\n# First #\\n\\n'\n+ assert md('

    First

    \\n

    Second

    \\n

    Third

    ', heading_style=ATX) == '\\n\\n# First\\n\\n## Second\\n\\n### Third\\n\\n'\n+ assert md('X

    First

    ', heading_style=ATX) == 'X\\n\\n# First\\n\\n'\n+ assert md('X

    First

    ', heading_style=ATX_CLOSED) == 'X\\n\\n# First #\\n\\n'\n assert md('X

    First

    ') == 'X\\n\\nFirst\\n=====\\n\\n'\n \n \n def test_hn_nested_tag_heading_style():\n- assert md('

    A

    P

    C

    ', heading_style=ATX_CLOSED) == '\\n# A P C #\\n\\n'\n- assert md('

    A

    P

    C

    ', heading_style=ATX) == '\\n# A P C\\n\\n'\n+ assert md('

    A

    P

    C

    ', heading_style=ATX_CLOSED) == '\\n\\n# A P C #\\n\\n'\n+ assert md('

    A

    P

    C

    ', heading_style=ATX) == '\\n\\n# A P C\\n\\n'\n \n \n def test_hn_nested_simple_tag():\n@@ -177,9 +177,9 @@ def test_hn_nested_simple_tag():\n ]\n \n for tag, markdown in tag_to_markdown:\n- assert md('

    A <' + tag + '>' + tag + ' B

    ') == '\\n### A ' + markdown + ' B\\n\\n'\n+ assert md('

    A <' + tag + '>' + tag + ' B

    ') == '\\n\\n### A ' + markdown + ' B\\n\\n'\n \n- assert md('

    A
    B

    ', heading_style=ATX) == '\\n### A B\\n\\n'\n+ assert md('

    A
    B

    ', heading_style=ATX) == '\\n\\n### A B\\n\\n'\n \n # Nested lists not supported\n # assert md('

    A
    • li1
    • l2

    ', heading_style=ATX) == '\\n### A li1 li2 B\\n\\n'\n@@ -192,18 +192,23 @@ def test_hn_nested_img():\n (\"alt='Alt Text' title='Optional title'\", \"Alt Text\", \" \\\"Optional title\\\"\"),\n ]\n for image_attributes, markdown, title in image_attributes_to_markdown:\n- assert md('

    A B

    ') == '\\n### A' + (' ' + markdown + ' ' if markdown else ' ') + 'B\\n\\n'\n- assert md('

    A B

    ', keep_inline_images_in=['h3']) == '\\n### A ![' + markdown + '](/path/to/img.jpg' + title + ') B\\n\\n'\n+ assert md('

    A B

    ') == '\\n\\n### A' + (' ' + markdown + ' ' if markdown else ' ') + 'B\\n\\n'\n+ assert md('

    A B

    ', keep_inline_images_in=['h3']) == '\\n\\n### A ![' + markdown + '](/path/to/img.jpg' + title + ') B\\n\\n'\n \n \n def test_hn_atx_headings():\n- assert md('

    Hello

    ', heading_style=ATX) == '\\n# Hello\\n\\n'\n- assert md('

    Hello

    ', heading_style=ATX) == '\\n## Hello\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX) == '\\n\\n# Hello\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX) == '\\n\\n## Hello\\n\\n'\n \n \n def test_hn_atx_closed_headings():\n- assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '\\n# Hello #\\n\\n'\n- assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '\\n## Hello ##\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '\\n\\n# Hello #\\n\\n'\n+ assert md('

    Hello

    ', heading_style=ATX_CLOSED) == '\\n\\n## Hello ##\\n\\n'\n+\n+\n+def test_hn_newlines():\n+ assert md(\"

    H1-1

    TEXT

    H2-2

    TEXT

    H1-2

    TEXT\", heading_style=ATX) == '\\n\\n# H1-1\\n\\nTEXT\\n\\n## H2-2\\n\\nTEXT\\n\\n# H1-2\\n\\nTEXT'\n+ assert md('

    H1-1

    \\n

    TEXT

    \\n

    H2-2

    \\n

    TEXT

    \\n

    H1-2

    \\n

    TEXT

    ', heading_style=ATX) == '\\n\\n# H1-1\\n\\nTEXT\\n\\n## H2-2\\n\\nTEXT\\n\\n# H1-2\\n\\nTEXT\\n\\n'\n \n \n def test_head():\ndiff --git a/tests/test_custom_converter.py b/tests/test_custom_converter.py\nindex a3e33ac..adc83f7 100644\n--- a/tests/test_custom_converter.py\n+++ b/tests/test_custom_converter.py\n@@ -2,22 +2,29 @@ from markdownify import MarkdownConverter\n from bs4 import BeautifulSoup\n \n \n-class ImageBlockConverter(MarkdownConverter):\n+class UnitTestConverter(MarkdownConverter):\n \"\"\"\n- Create a custom MarkdownConverter that adds two newlines after an image\n+ Create a custom MarkdownConverter for unit tests\n \"\"\"\n def convert_img(self, el, text, convert_as_inline):\n+ \"\"\"Add two newlines after an image\"\"\"\n return super().convert_img(el, text, convert_as_inline) + '\\n\\n'\n \n+ def convert_custom_tag(self, el, text, convert_as_inline):\n+ \"\"\"Ensure conversion function is found for tags with special characters in name\"\"\"\n+ return \"FUNCTION USED: %s\" % text\n \n-def test_img():\n+\n+def test_custom_conversion_functions():\n # Create shorthand method for conversion\n def md(html, **options):\n- return ImageBlockConverter(**options).convert(html)\n+ return UnitTestConverter(**options).convert(html)\n \n assert md('\"Alt') == '![Alt text](/path/to/img.jpg \"Optional title\")\\n\\n'\n assert md('\"Alt') == '![Alt text](/path/to/img.jpg)\\n\\n'\n \n+ assert md(\"text\") == \"FUNCTION USED: text\"\n+\n \n def test_soup():\n html = 'test'\ndiff --git a/tests/test_tables.py b/tests/test_tables.py\nindex dcf9ad7..da4bf53 100644\n--- a/tests/test_tables.py\n+++ b/tests/test_tables.py\n@@ -141,6 +141,33 @@ table_head_body_missing_head = \"\"\"\n \n
    \"\"\"\n \n+table_head_body_multiple_head = \"\"\"\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+
    CreatorEditorServer
    OperatorManagerEngineer
    BobOliverTom
    ThomasLucasEthan
    \"\"\"\n+\n table_missing_text = \"\"\"\n \n \n@@ -245,10 +272,28 @@ def test_table():\n assert md(table_with_linebreaks) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith Jackson | 50 |\\n| Eve | Jackson Smith | 94 |\\n\\n'\n assert md(table_with_header_column) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_head_body) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_head_body_multiple_head) == '\\n\\n| | | |\\n| --- | --- | --- |\\n| Creator | Editor | Server |\\n| Operator | Manager | Engineer |\\n| Bob | Oliver | Tom |\\n| Thomas | Lucas | Ethan |\\n\\n'\n assert md(table_head_body_missing_head) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_missing_text) == '\\n\\n| | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n- assert md(table_missing_head) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n- assert md(table_body) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n- assert md(table_with_caption) == 'TEXT\\n\\nCaption\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n\\n'\n+ assert md(table_missing_head) == '\\n\\n| | | |\\n| --- | --- | --- |\\n| Firstname | Lastname | Age |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_body) == '\\n\\n| | | |\\n| --- | --- | --- |\\n| Firstname | Lastname | Age |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_with_caption) == 'TEXT\\n\\nCaption\\n\\n| | | |\\n| --- | --- | --- |\\n| Firstname | Lastname | Age |\\n\\n'\n assert md(table_with_colspan) == '\\n\\n| Name | | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n assert md(table_with_undefined_colspan) == '\\n\\n| Name | Age |\\n| --- | --- |\\n| Jill | Smith |\\n\\n'\n+\n+\n+def test_table_infer_header():\n+ assert md(table, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_with_html_content, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| **Jill** | *Smith* | [50](#) |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_with_paragraphs, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_with_linebreaks, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith Jackson | 50 |\\n| Eve | Jackson Smith | 94 |\\n\\n'\n+ assert md(table_with_header_column, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_head_body, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_head_body_multiple_head, table_infer_header=True) == '\\n\\n| Creator | Editor | Server |\\n| --- | --- | --- |\\n| Operator | Manager | Engineer |\\n| Bob | Oliver | Tom |\\n| Thomas | Lucas | Ethan |\\n\\n'\n+ assert md(table_head_body_missing_head, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_missing_text, table_infer_header=True) == '\\n\\n| | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_missing_head, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_body, table_infer_header=True) == '\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_with_caption, table_infer_header=True) == 'TEXT\\n\\nCaption\\n\\n| Firstname | Lastname | Age |\\n| --- | --- | --- |\\n\\n'\n+ assert md(table_with_colspan, table_infer_header=True) == '\\n\\n| Name | | Age |\\n| --- | --- | --- |\\n| Jill | Smith | 50 |\\n| Eve | Jackson | 94 |\\n\\n'\n+ assert md(table_with_undefined_colspan, table_infer_header=True) == '\\n\\n| Name | Age |\\n| --- | --- |\\n| Jill | Smith |\\n\\n'\n", "FAIL_TO_PASS": ["tests/test_conversions.py::test_header_with_space", "tests/test_conversions.py::test_hn", "tests/test_conversions.py::test_hn_chained", "tests/test_conversions.py::test_hn_nested_tag_heading_style", "tests/test_conversions.py::test_hn_nested_simple_tag", "tests/test_conversions.py::test_hn_nested_img", "tests/test_conversions.py::test_hn_atx_headings", "tests/test_conversions.py::test_hn_atx_closed_headings", "tests/test_conversions.py::test_hn_newlines", "tests/test_custom_converter.py::test_custom_conversion_functions", "tests/test_tables.py::test_table"]}], "all_FAIL_TO_PASS": ["tests/test_conversions.py::test_blockquote_with_nested_paragraph", "tests/test_lists.py::test_ol", "tests/test_lists.py::test_ul", "tests/test_conversions.py::test_dl", "tests/test_conversions.py::test_header_with_space", "tests/test_conversions.py::test_hn", "tests/test_conversions.py::test_hn_chained", "tests/test_conversions.py::test_hn_nested_tag_heading_style", "tests/test_conversions.py::test_hn_nested_simple_tag", "tests/test_conversions.py::test_hn_nested_img", "tests/test_conversions.py::test_hn_atx_headings", "tests/test_conversions.py::test_hn_atx_closed_headings", "tests/test_conversions.py::test_hn_newlines", "tests/test_custom_converter.py::test_custom_conversion_functions", "tests/test_tables.py::test_table"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "larq__zookeeper-228_x3", "level": 3, "source": "swerebench", "repo": "larq/zookeeper", "image": "swerebench/sweb.eval.x86_64.larq_1776_zookeeper-228:latest", "base_commit": "52b97b05f09cf8f29d65cc82f1be1ce2fd6dfdc4", "num_bugs": 3, "bugs": [{"instance_id": "larq__zookeeper-228", "base_commit": "52b97b05f09cf8f29d65cc82f1be1ce2fd6dfdc4", "gold_patch": "diff --git a/zookeeper/core/component.py b/zookeeper/core/component.py\nindex e3fde1f..63b0ee6 100644\n--- a/zookeeper/core/component.py\n+++ b/zookeeper/core/component.py\n@@ -484,6 +484,14 @@ def configure_component_instance(\n conf_field_value = subclass()\n break\n \n+ # If this isn't the case, then it's a user type error, but we don't\n+ # throw here and instead let the run-time type-checking take care of\n+ # it (which will provide a better error message).\n+ if utils.is_component_instance(conf_field_value):\n+ # Set the component parent so that field value inheritence will\n+ # work correctly.\n+ conf_field_value.__component_parent__ = instance\n+\n # Set the value on the instance.\n instance.__component_configured_field_values__[\n field.name\n", "test_patch": "diff --git a/zookeeper/core/component_test.py b/zookeeper/core/component_test.py\nindex 1caf4fb..120557a 100644\n--- a/zookeeper/core/component_test.py\n+++ b/zookeeper/core/component_test.py\n@@ -809,3 +809,21 @@ def test_base_hasattr():\n \n assert not hasattr(instance, \"missing_attribute\")\n assert base_hasattr(instance, \"missing_attribute\")\n+\n+\n+def test_component_configure_component_passed_as_config():\n+ @component\n+ class Child:\n+ x: int = Field() # Inherited from parent\n+\n+ @component\n+ class Parent:\n+ x: int = Field(7)\n+ child: Child = ComponentField(Child)\n+\n+ instance = Parent()\n+ new_child_instance = Child()\n+ configure(instance, {\"child\": new_child_instance})\n+ assert instance.child is new_child_instance\n+ assert instance.child.__component_parent__ is instance\n+ assert instance.child.x == 7 # This value should be correctly inherited.\n", "FAIL_TO_PASS": ["zookeeper/core/component_test.py::test_component_configure_component_passed_as_config"]}, {"instance_id": "larq__zookeeper-241", "base_commit": "60ee7890ca7d8af30e480ef35096b96911265b80", "gold_patch": "diff --git a/zookeeper/core/component.py b/zookeeper/core/component.py\nindex 9d5d455..b16b97e 100644\n--- a/zookeeper/core/component.py\n+++ b/zookeeper/core/component.py\n@@ -78,7 +78,7 @@ print(c)\n \n import functools\n import inspect\n-from typing import AbstractSet, Any, Dict, Iterator, List, Optional, Type\n+from typing import AbstractSet, Any, Dict, Iterator, List, Optional, Tuple, Type\n \n from zookeeper.core import utils\n from zookeeper.core.factory_registry import FACTORY_REGISTRY\n@@ -303,6 +303,84 @@ def _wrap_dir(component_cls: Type) -> None:\n component_cls.__dir__ = wrapped_fn\n \n \n+######################################\n+# Implement the `ItemsView` protocol #\n+######################################\n+\n+# Implementing these three methods makes `dict(component_instance)`,\n+# `list(component_instance)`, et cetera be something sensible.\n+#\n+# In particular, `dict(component_instance)` has field names as keys and field\n+# values as values, giving a flattened view of the entire component tree\n+# including all sub-components. This dictionary is precisely the configuration\n+# that is required to completely re-create the component, including all\n+# sub-components, i.e. `configure(new_instance, dict(old_instance))`.\n+\n+\n+def __component_len__(instance) -> int:\n+ return len(list(iter(instance)))\n+\n+\n+def __component_contains__(instance, key: str) -> bool:\n+ if not isinstance(key, str):\n+ return False\n+\n+ if \".\" not in key:\n+ # The base case is whether or not this is a component field defined\n+ # on this class, that also has a value in scope (which excludes the\n+ # `allow_missing` fields without a configured value).\n+ return (\n+ key in instance.__component_fields__\n+ and key in instance.__component_fields_with_values_in_scope__\n+ )\n+\n+ # The recusive case is to split the key and check the sub-component.\n+ key_prefix = key.split(\".\")[0]\n+ if isinstance(instance.__component_fields__.get(key_prefix, None), ComponentField):\n+ try:\n+ sub_component = base_getattr(instance, key_prefix)\n+ if utils.is_component_instance(sub_component):\n+ return key[len(key_prefix) + 1 :] in sub_component\n+ except AttributeError:\n+ pass\n+\n+ return False\n+\n+\n+def __component_iter__(instance) -> Iterator[Tuple[str, Any]]:\n+ for field_name, field in instance.__component_fields__.items():\n+ # Get the field value. If there's an attribute error (possible\n+ # because of `allow_missing`), just skip.\n+ try:\n+ field_value = base_getattr(instance, field_name)\n+ except AttributeError:\n+ continue\n+\n+ # Check if the value is inherited and if so skip.\n+ parent_instance = next(\n+ utils.generate_component_ancestors_with_field(instance, field_name),\n+ None,\n+ )\n+ if (\n+ parent_instance is not None\n+ and base_getattr(parent_instance, field_name) is field_value\n+ ):\n+ continue\n+\n+ # If this is *not* a sub-component, yield the value directly.\n+ if not isinstance(field, ComponentField) or not utils.is_component_instance(\n+ field_value\n+ ):\n+ yield field_name, field_value\n+\n+ # Otherwise, yield the name of the sub-component class and\n+ # recursively yield from the sub-component.\n+ else:\n+ yield field_name, field_value.__class__.__qualname__\n+ for sub_field_name, sub_field_value in iter(field_value):\n+ yield f\"{field_name}.{sub_field_name}\", sub_field_value\n+\n+\n #################################\n # Pretty string representations #\n #################################\n@@ -495,7 +573,7 @@ def configure_component_instance(\n # If the field explicitly allows values to be missing, there's no need\n # to do anything.\n elif field.allow_missing:\n- pass\n+ continue\n \n # If there is only one concrete component subclass of the annotated\n # type, we assume the user must intend to use that subclass, and so\n@@ -706,6 +784,19 @@ def component(cls: Type):\n _wrap_delattr(cls)\n _wrap_dir(cls)\n \n+ # Implement the `ItemsView` protocol\n+ if hasattr(cls, \"__len__\") and cls.__len__ != __component_len__:\n+ raise TypeError(\"Component classes must not define a custom `__len__` method.\")\n+ cls.__len__ = __component_len__\n+ if hasattr(cls, \"__contains__\") and cls.__contains__ != __component_contains__:\n+ raise TypeError(\n+ \"Component classes must not define a custom `__contains__` method.\"\n+ )\n+ cls.__contains__ = __component_contains__\n+ if hasattr(cls, \"__iter__\") and cls.__iter__ != __component_iter__:\n+ raise TypeError(\"Component classes must not define a custom `__iter__` method.\")\n+ cls.__iter__ = __component_iter__\n+\n # Components should have nice `__str__` and `__repr__` methods.\n cls.__str__ = __component_str__\n cls.__repr__ = __component_repr__\n", "test_patch": "diff --git a/zookeeper/core/component_test.py b/zookeeper/core/component_test.py\nindex 120557a..fc4fce6 100644\n--- a/zookeeper/core/component_test.py\n+++ b/zookeeper/core/component_test.py\n@@ -262,6 +262,159 @@ def test_configure_interactive_prompt_for_subcomponent_choice():\n prompt.assert_called_once()\n \n \n+def test_len():\n+ with pytest.raises(\n+ TypeError, match=\"Component classes must not define a custom `__len__` method.\"\n+ ):\n+\n+ @component\n+ class InvalidComponent:\n+ def __len__():\n+ return\n+\n+ @component\n+ class Component:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ c: str = Field(allow_missing=True)\n+\n+ instance = Component()\n+ configure(instance, {\"a\": 10})\n+ # When a field is `allow_missing` it should not be counted.\n+ assert len(instance) == 2\n+\n+ instance = Component()\n+ configure(instance, {\"a\": 10, \"c\": \"foo\"})\n+ # But when the `allow_missing` field gets assigned a value it should be\n+ # counted.\n+ assert len(instance) == 3\n+\n+\n+def test_contains():\n+ with pytest.raises(\n+ TypeError,\n+ match=\"Component classes must not define a custom `__contains__` method.\",\n+ ):\n+\n+ @component\n+ class InvalidComponent:\n+ def __contains__():\n+ return\n+\n+ @component\n+ class Child:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field()\n+ c: str = Field(allow_missing=True)\n+\n+ @component\n+ class Parent:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ child: Child = ComponentField()\n+\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0)})\n+ assert \"a\" in instance\n+ assert \"b\" in instance\n+ assert \"child\" in instance\n+ assert \"child.a\" in instance\n+ assert \"child.b\" in instance\n+ assert \"child.c\" not in instance\n+\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0), \"child.c\": \"foo\"})\n+ assert \"a\" in instance\n+ assert \"b\" in instance\n+ assert \"child\" in instance\n+ assert \"child.a\" in instance\n+ assert \"child.b\" in instance\n+ assert \"child.c\" in instance\n+\n+\n+def test_iter():\n+ with pytest.raises(\n+ TypeError, match=\"Component classes must not define a custom `__iter__` method.\"\n+ ):\n+\n+ @component\n+ class InvalidComponent:\n+ def __iter__():\n+ return\n+\n+ @component\n+ class Child:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field()\n+ c: str = Field(allow_missing=True)\n+\n+ @component\n+ class Parent:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ child: Child = ComponentField()\n+\n+ # When no configured value is provided for `child.c`, there should be four\n+ # values in the iterator: `a` and `b` and `child` on the parent, and `b` on\n+ # the child. Notice that the `a` on the child (i.e. `child.a`) is not\n+ # included, because that value is inherited from the parent.\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0)})\n+ assert list(iter(instance)) == [\n+ (\"a\", 10),\n+ (\"b\", (5, -42.3)),\n+ (\"child\", \"test_iter..Child\"),\n+ (\"child.b\", (-1, 0.0)),\n+ ]\n+\n+ # The only difference from the above is that `child.c` should be included.\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0), \"child.c\": \"foo\"})\n+ assert list(iter(instance)) == [\n+ (\"a\", 10),\n+ (\"b\", (5, -42.3)),\n+ (\"child\", \"test_iter..Child\"),\n+ (\"child.b\", (-1, 0.0)),\n+ (\"child.c\", \"foo\"),\n+ ]\n+\n+\n+def test_itemsview_protocol():\n+ @component\n+ class Child:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field()\n+ c: str = Field(allow_missing=True)\n+\n+ @component\n+ class Parent:\n+ a: int = Field()\n+ b: Tuple[int, float] = Field((5, -42.3))\n+ child: Child = ComponentField()\n+\n+ instance = Parent()\n+ configure(instance, {\"a\": 10, \"child.b\": (-1, 0.0)})\n+\n+ instance_dict = dict(instance)\n+\n+ # Check it's what we expect\n+ assert instance_dict == {\n+ \"a\": 10,\n+ \"b\": (5, -42.3),\n+ \"child\": \"test_itemsview_protocol..Child\",\n+ \"child.b\": (-1, 0.0),\n+ }\n+\n+ # Check that, using the old config, we can instantiate and configure an\n+ # identical component tree.\n+ new_instance = Parent()\n+ configure(new_instance, instance_dict)\n+ assert new_instance.a == instance.a\n+ assert new_instance.b == instance.b\n+ assert new_instance.child.a == instance.child.a\n+ assert new_instance.child.b == instance.child.b\n+\n+\n def test_str_and_repr():\n \"\"\"`__str__` and `__repr__` should give formatted strings that represent nested\n components nicely.\"\"\"\n", "FAIL_TO_PASS": ["zookeeper/core/component_test.py::test_len", "zookeeper/core/component_test.py::test_contains", "zookeeper/core/component_test.py::test_iter", "zookeeper/core/component_test.py::test_itemsview_protocol"]}, {"instance_id": "larq__zookeeper-275", "base_commit": "f9a2c19d429bf61a3bc64dc51ba942872b22c5a1", "gold_patch": "diff --git a/zookeeper/core/component.py b/zookeeper/core/component.py\nindex b16b97e..dccfa79 100644\n--- a/zookeeper/core/component.py\n+++ b/zookeeper/core/component.py\n@@ -694,6 +694,8 @@ def configure_component_instance(\n if hasattr(instance.__class__, \"__post_configure__\"):\n instance.__post_configure__()\n \n+ return conf\n+\n \n ######################\n # Exported functions #\n@@ -852,7 +854,7 @@ def configure(\n if current_instance.__component_configured__:\n continue\n \n- configure_component_instance(\n+ current_conf = configure_component_instance(\n current_instance,\n conf=current_conf,\n name=current_name,\n", "test_patch": "diff --git a/zookeeper/core/component_test.py b/zookeeper/core/component_test.py\nindex fc4fce6..46187bf 100644\n--- a/zookeeper/core/component_test.py\n+++ b/zookeeper/core/component_test.py\n@@ -821,6 +821,25 @@ def test_component_pre_configure():\n configure(instance, {\"x\": 7})\n assert instance.x == 14\n \n+ @component\n+ class Child:\n+ a: int = Field(4)\n+\n+ @component\n+ class Parent:\n+ a: int = Field(2)\n+ child: Child = ComponentField()\n+\n+ def __pre_configure__(self, conf):\n+ if \"a\" in conf:\n+ return {\"child.a\": conf[\"a\"] * 7, **conf}\n+ return conf\n+\n+ parent = Parent()\n+ configure(parent, {\"a\": 6})\n+ assert parent.a == 6\n+ assert parent.child.a == 42\n+\n \n def test_component_pre_configure_setattr():\n @component\n", "FAIL_TO_PASS": ["zookeeper/core/component_test.py::test_component_pre_configure"]}], "all_FAIL_TO_PASS": ["zookeeper/core/component_test.py::test_component_configure_component_passed_as_config", "zookeeper/core/component_test.py::test_len", "zookeeper/core/component_test.py::test_contains", "zookeeper/core/component_test.py::test_iter", "zookeeper/core/component_test.py::test_itemsview_protocol", "zookeeper/core/component_test.py::test_component_pre_configure"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "lidatong__dataclasses-json-394_x3", "level": 3, "source": "swerebench", "repo": "lidatong/dataclasses-json", "image": "swerebench/sweb.eval.x86_64.lidatong_1776_dataclasses-json-394:latest", "base_commit": "39b4c2f4462282576d72a72ade048ef49e2133bb", "num_bugs": 3, "bugs": [{"instance_id": "lidatong__dataclasses-json-394", "base_commit": "39b4c2f4462282576d72a72ade048ef49e2133bb", "gold_patch": "diff --git a/dataclasses_json/core.py b/dataclasses_json/core.py\nindex 529e153..ae1e99b 100644\n--- a/dataclasses_json/core.py\n+++ b/dataclasses_json/core.py\n@@ -93,7 +93,12 @@ def _user_overrides_or_exts(cls):\n \n def _encode_json_type(value, default=_ExtendedEncoder().default):\n if isinstance(value, Json.__args__): # type: ignore\n- return value\n+ if isinstance(value, list):\n+ return [_encode_json_type(i) for i in value]\n+ elif isinstance(value, dict):\n+ return {k: _encode_json_type(v) for k, v in value.items()}\n+ else:\n+ return value\n return default(value)\n \n \n", "test_patch": "diff --git a/tests/test_enum.py b/tests/test_enum.py\nindex 6d0ce82..f4848ed 100644\n--- a/tests/test_enum.py\n+++ b/tests/test_enum.py\n@@ -1,9 +1,9 @@\n import json\n from enum import Enum\n-from typing import Dict, List\n+from typing import Dict, List, Optional\n import pytest\n \n-from dataclasses import dataclass\n+from dataclasses import dataclass, field\n \n from dataclasses_json import dataclass_json\n \n@@ -27,19 +27,25 @@ class MyStrEnum(str, Enum):\n class DataWithEnum:\n name: str\n my_enum: MyEnum = MyEnum.STR3\n+ enum_list: List[MyEnum] = field(default_factory=list)\n+ nested: Dict[str, List[MyEnum]] = field(default_factory=dict)\n \n \n d1 = DataWithEnum('name1', MyEnum.STR1)\n-d1_json = '{\"name\": \"name1\", \"my_enum\": \"str1\"}'\n+d1_json = '{\"name\": \"name1\", \"my_enum\": \"str1\", \"enum_list\": [], \"nested\": {}}'\n \n # Make sure the enum is set to the default value defined by MyEnum\n d2_using_default_value = DataWithEnum('name2')\n-d2_json = '{\"name\": \"name2\", \"my_enum\": \"str3\"}'\n+d2_json = '{\"name\": \"name2\", \"my_enum\": \"str3\", \"enum_list\": [], \"nested\": {}}'\n \n d3_int = DataWithEnum('name1', MyEnum.INT1)\n-d3_int_json = '{\"name\": \"name1\", \"my_enum\": 1}'\n+d3_int_json = '{\"name\": \"name1\", \"my_enum\": 1, \"enum_list\": [], \"nested\": {}}'\n+\n d4_float = DataWithEnum('name1', MyEnum.FLOAT1)\n-d4_float_json = '{\"name\": \"name1\", \"my_enum\": 1.23}'\n+d4_float_json = '{\"name\": \"name1\", \"my_enum\": 1.23, \"enum_list\": [], \"nested\": {}}'\n+\n+d5_list = DataWithEnum('name1', MyEnum.STR1, [MyEnum.STR2, MyEnum.STR3], nested={'enum_val': [MyEnum.STR1]})\n+d5_list_json = '{\"name\": \"name1\", \"my_enum\": \"str1\", \"enum_list\": [\"str2\", \"str3\"], \"nested\": {\"enum_val\": [\"str1\"]}}'\n \n \n @dataclass_json\n@@ -82,6 +88,10 @@ class TestEncoder:\n def test_collection_with_enum(self):\n assert container.to_json() == container_json\n \n+ def test_enum_with_list(self):\n+ assert d5_list.to_json() == d5_list_json, f'Actual: {d5_list.to_json()}, Expected: {d5_list_json}'\n+ assert d5_list.to_dict(encode_json=True) == json.loads(d5_list_json), f'Actual: {d5_list.to_dict()}, Expected: {json.loads(d5_list_json)}'\n+\n \n class TestDecoder:\n def test_data_with_enum(self):\n", "FAIL_TO_PASS": ["tests/test_enum.py::TestEncoder::test_enum_with_list"]}, {"instance_id": "lidatong__dataclasses-json-426", "base_commit": "38d8123f9f990ecd088f5d8f42768685de975644", "gold_patch": "diff --git a/dataclasses_json/core.py b/dataclasses_json/core.py\nindex fb7f0e6..d34e51d 100644\n--- a/dataclasses_json/core.py\n+++ b/dataclasses_json/core.py\n@@ -281,10 +281,12 @@ def _decode_generic(type_, value, infer_missing):\n \n # get the constructor if using corresponding generic type in `typing`\n # otherwise fallback on constructing using type_ itself\n+ materialize_type = type_\n try:\n- res = _get_type_cons(type_)(xs)\n+ materialize_type = _get_type_cons(type_)\n except (TypeError, AttributeError):\n- res = type_(xs)\n+ pass\n+ res = materialize_type(xs)\n else: # Optional or Union\n _args = _get_type_args(type_)\n if _args is _NO_ARGS:\n", "test_patch": "diff --git a/tests/entities.py b/tests/entities.py\nindex 6c0db90..61b8af2 100644\n--- a/tests/entities.py\n+++ b/tests/entities.py\n@@ -264,6 +264,19 @@ class DataClassWithConfigHelper:\n id: float = field(metadata=config(encoder=str))\n \n \n+@dataclass_json\n+@dataclass\n+class DataClassWithErroneousDecode:\n+ # Accepts no arguments, so passing in a single argument will result in a TypeError.\n+ id: float = field(metadata=config(decoder=lambda: None))\n+\n+\n+@dataclass_json\n+@dataclass\n+class DataClassMappingBadDecode:\n+ map: Dict[str, DataClassWithErroneousDecode]\n+\n+\n @dataclass_json(letter_case=LetterCase.CAMEL)\n @dataclass\n class DataClassWithConfigDecorator:\ndiff --git a/tests/test_nested.py b/tests/test_nested.py\nindex 56dc9ba..69c6456 100644\n--- a/tests/test_nested.py\n+++ b/tests/test_nested.py\n@@ -1,4 +1,6 @@\n-from tests.entities import (DataClassWithDataClass,\n+import pytest\n+from tests.entities import (DataClassMappingBadDecode,\n+ DataClassWithDataClass,\n DataClassWithList,\n DataClassWithNestedDictWithTupleKeys,\n DataClassX,\n@@ -25,6 +27,10 @@ class TestDecoder:\n assert (DataClassXs.from_json('{\"xs\": [{\"x\": 0}, {\"x\": 1}]}') ==\n DataClassXs([DataClassX(0), DataClassX(1)]))\n \n+ def test_nested_mapping_of_dataclasses(self):\n+ with pytest.raises(TypeError, match=\"positional arguments\"):\n+ DataClassMappingBadDecode.from_dict(dict(map=dict(test=dict(id=\"irrelevant\"))))\n+\n \n class TestNested:\n def test_tuple_dict_key(self):\n", "FAIL_TO_PASS": ["tests/test_nested.py::TestDecoder::test_nested_mapping_of_dataclasses"]}, {"instance_id": "lidatong__dataclasses-json-435", "base_commit": "bc83017e26493a67bccb46ace6caecb00e9fde99", "gold_patch": "diff --git a/dataclasses_json/core.py b/dataclasses_json/core.py\nindex 3118036..acb5a47 100644\n--- a/dataclasses_json/core.py\n+++ b/dataclasses_json/core.py\n@@ -23,7 +23,7 @@ from dataclasses_json.utils import (_get_type_cons, _get_type_origin,\n _get_type_arg_param,\n _get_type_args,\n _NO_ARGS,\n- _issubclass_safe)\n+ _issubclass_safe, _is_tuple)\n \n Json = Union[dict, list, str, int, float, bool, None]\n \n@@ -278,9 +278,10 @@ def _decode_generic(type_, value, infer_missing):\n ks = _decode_dict_keys(k_type, value.keys(), infer_missing)\n vs = _decode_items(v_type, value.values(), infer_missing)\n xs = zip(ks, vs)\n+ elif _is_tuple(type_):\n+ xs = _decode_items(_get_type_args(type_) or _NO_ARGS, value, infer_missing)\n else:\n- xs = _decode_items(_get_type_arg_param(type_, 0),\n- value, infer_missing)\n+ xs = _decode_items(_get_type_arg_param(type_, 0), value, infer_missing)\n \n # get the constructor if using corresponding generic type in `typing`\n # otherwise fallback on constructing using type_ itself\n@@ -335,7 +336,7 @@ def _decode_dict_keys(key_type, xs, infer_missing):\n return map(decode_function, _decode_items(key_type, xs, infer_missing))\n \n \n-def _decode_items(type_arg, xs, infer_missing):\n+def _decode_items(type_args, xs, infer_missing):\n \"\"\"\n This is a tricky situation where we need to check both the annotated\n type info (which is usually a type from `typing`) and check the\n@@ -345,14 +346,16 @@ def _decode_items(type_arg, xs, infer_missing):\n type_arg is a typevar we need to extract the reified type information\n hence the check of `is_dataclass(vs)`\n \"\"\"\n- if is_dataclass(type_arg) or is_dataclass(xs):\n- items = (_decode_dataclass(type_arg, x, infer_missing)\n- for x in xs)\n- elif _is_supported_generic(type_arg):\n- items = (_decode_generic(type_arg, x, infer_missing) for x in xs)\n- else:\n- items = xs\n- return items\n+ def _decode_item(type_arg, x):\n+ if is_dataclass(type_arg) or is_dataclass(xs):\n+ return _decode_dataclass(type_arg, x, infer_missing)\n+ if _is_supported_generic(type_arg):\n+ return _decode_generic(type_arg, x, infer_missing)\n+ return x\n+\n+ if _isinstance_safe(type_args, Collection) and not _issubclass_safe(type_args, Enum):\n+ return list(_decode_item(type_arg, x) for type_arg, x in zip(type_args, xs))\n+ return list(_decode_item(type_args, x) for x in xs)\n \n \n def _asdict(obj, encode_json=False):\ndiff --git a/dataclasses_json/utils.py b/dataclasses_json/utils.py\nindex 355e690..0927cd0 100644\n--- a/dataclasses_json/utils.py\n+++ b/dataclasses_json/utils.py\n@@ -150,6 +150,10 @@ def _is_collection(type_):\n return _issubclass_safe(_get_type_origin(type_), Collection)\n \n \n+def _is_tuple(type_):\n+ return _issubclass_safe(_get_type_origin(type_), Tuple)\n+\n+\n def _is_nonstr_collection(type_):\n return (_issubclass_safe(_get_type_origin(type_), Collection)\n and not _issubclass_safe(type_, str))\n", "test_patch": "diff --git a/tests/test_enum.py b/tests/test_enum.py\nindex f4848ed..4313c27 100644\n--- a/tests/test_enum.py\n+++ b/tests/test_enum.py\n@@ -1,6 +1,6 @@\n import json\n from enum import Enum\n-from typing import Dict, List, Optional\n+from typing import Dict, List\n import pytest\n \n from dataclasses import dataclass, field\ndiff --git a/tests/test_tuples.py b/tests/test_tuples.py\nnew file mode 100644\nindex 0000000..44e3574\n--- /dev/null\n+++ b/tests/test_tuples.py\n@@ -0,0 +1,57 @@\n+import json\n+from enum import Enum\n+from typing import Tuple\n+\n+from dataclasses import dataclass\n+\n+from dataclasses_json import dataclass_json\n+\n+\n+class MyEnum(Enum):\n+ STR1 = \"str1\"\n+ STR2 = \"str2\"\n+ STR3 = \"str3\"\n+ INT1 = 1\n+ FLOAT1 = 1.23\n+\n+\n+@dataclass_json\n+@dataclass\n+class DataWithHeterogeneousTuple:\n+ my_tuple: Tuple[MyEnum, str, float]\n+\n+\n+hetero_tuple_json = '{\"my_tuple\": [\"str1\", \"str2\", 1.23]}'\n+hetero_tuple_data = DataWithHeterogeneousTuple(my_tuple=(MyEnum.STR1, \"str2\", 1.23))\n+\n+\n+@dataclass_json\n+@dataclass\n+class DataWithNestedTuple:\n+ my_tuple: Tuple[Tuple[int, str], Tuple[MyEnum, int], int]\n+\n+\n+nested_tuple_json = '{\"my_tuple\": [[1, \"str1\"], [\"str2\", 1], 1]}'\n+nested_tuple_data = DataWithNestedTuple(my_tuple=((1, \"str1\"), (MyEnum.STR2, 1), 1))\n+\n+\n+class TestEncoder:\n+ def test_enum_with_tuple(self):\n+ assert hetero_tuple_data.to_json() == hetero_tuple_json, f'Actual: {hetero_tuple_data.to_json()}, Expected: {hetero_tuple_json}'\n+ assert hetero_tuple_data.to_dict(encode_json=True) == json.loads(hetero_tuple_json), f'Actual: {hetero_tuple_data.to_dict()}, Expected: {json.loads(hetero_tuple_json)}'\n+\n+ def test_nested_tuple(self):\n+ assert nested_tuple_data.to_json() == nested_tuple_json, f'Actual: {nested_tuple_data.to_json()}, Expected: {nested_tuple_json}'\n+ assert nested_tuple_data.to_dict(encode_json=True) == json.loads(nested_tuple_json), f'Actual: {nested_tuple_data.to_dict()}, Expected: {json.loads(nested_tuple_json)}'\n+\n+\n+class TestDecoder:\n+ def test_enum_with_tuple(self):\n+ tuple_data_from_json = DataWithHeterogeneousTuple.from_json(hetero_tuple_json)\n+ assert hetero_tuple_data == tuple_data_from_json\n+ assert tuple_data_from_json.to_json() == hetero_tuple_json\n+\n+ def test_nested_tuple(self):\n+ tuple_data_from_json = DataWithNestedTuple.from_json(nested_tuple_json)\n+ assert nested_tuple_data == tuple_data_from_json\n+ assert tuple_data_from_json.to_json() == nested_tuple_json\n", "FAIL_TO_PASS": ["tests/test_tuples.py::TestDecoder::test_enum_with_tuple", "tests/test_tuples.py::TestDecoder::test_nested_tuple"]}], "all_FAIL_TO_PASS": ["tests/test_enum.py::TestEncoder::test_enum_with_list", "tests/test_nested.py::TestDecoder::test_nested_mapping_of_dataclasses", "tests/test_tuples.py::TestDecoder::test_enum_with_tuple", "tests/test_tuples.py::TestDecoder::test_nested_tuple"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "hhatto__autopep8-450_x3", "level": 3, "source": "swerebench", "repo": "hhatto/autopep8", "image": "swerebench/sweb.eval.x86_64.hhatto_1776_autopep8-450:latest", "base_commit": "4343c41ca3d52e75af5e95f6b86a6053bcbd9a57", "num_bugs": 3, "bugs": [{"instance_id": "hhatto__autopep8-450", "base_commit": "4343c41ca3d52e75af5e95f6b86a6053bcbd9a57", "gold_patch": "diff --git a/autopep8.py b/autopep8.py\nindex 53a8446..e30b4eb 100755\n--- a/autopep8.py\n+++ b/autopep8.py\n@@ -1363,7 +1363,7 @@ def get_w605_position(tokens):\n 'N', 'u', 'U',\n ]\n \n- for token_type, text, start, end, line in tokens:\n+ for token_type, text, start_pos, end_pos, line in tokens:\n if token_type == tokenize.STRING:\n quote = text[-3:] if text[-3:] in ('\"\"\"', \"'''\") else text[-1]\n # Extract string modifiers (e.g. u or r)\n@@ -1378,7 +1378,8 @@ def get_w605_position(tokens):\n pos += 1\n if string[pos] not in valid:\n yield (\n- line.find(text),\n+ # No need to search line, token stores position\n+ start_pos[1],\n \"W605 invalid escape sequence '\\\\%s'\" %\n string[pos],\n )\n", "test_patch": "diff --git a/test/test_autopep8.py b/test/test_autopep8.py\nindex 03e3084..cfb80d4 100755\n--- a/test/test_autopep8.py\n+++ b/test/test_autopep8.py\n@@ -4734,6 +4734,25 @@ raise ValueError(\"error\")\n with autopep8_context(line, options=['--aggressive']) as result:\n self.assertEqual(fixed, result)\n \n+ def test_w605_identical_token(self):\n+ # ***NOTE***: The --pep8-passes option is requred to prevent an infinite loop in\n+ # the old, failing code. DO NOT REMOVE.\n+ line = \"escape = foo('\\.bar', '\\.kilroy')\\n\"\n+ fixed = \"escape = foo(r'\\.bar', r'\\.kilroy')\\n\"\n+ with autopep8_context(line, options=['--aggressive', '--pep8-passes', '5']) as result:\n+ self.assertEqual(fixed, result, \"Two tokens get r added\")\n+\n+ line = \"escape = foo('\\.bar', r'\\.kilroy')\\n\"\n+ fixed = \"escape = foo(r'\\.bar', r'\\.kilroy')\\n\"\n+ with autopep8_context(line, options=['--aggressive', '--pep8-passes', '5']) as result:\n+ self.assertEqual(fixed, result, \"r not added if already there\")\n+\n+ # Test Case to catch bad behavior reported in Issue #449\n+ line = \"escape = foo('\\.bar', '\\.bar')\\n\"\n+ fixed = \"escape = foo(r'\\.bar', r'\\.bar')\\n\"\n+ with autopep8_context(line, options=['--aggressive', '--pep8-passes', '5']) as result:\n+ self.assertEqual(fixed, result)\n+\n def test_trailing_whitespace_in_multiline_string(self):\n line = 'x = \"\"\" \\nhello\"\"\" \\n'\n fixed = 'x = \"\"\" \\nhello\"\"\"\\n'\n", "FAIL_TO_PASS": ["test/test_autopep8.py::SystemTests::test_w605_identical_token"]}, {"instance_id": "hhatto__autopep8-464", "base_commit": "40bcf6f126f11f6957f7b2c31d880245843b2242", "gold_patch": "diff --git a/autopep8.py b/autopep8.py\nindex d07f74c..258f30c 100755\n--- a/autopep8.py\n+++ b/autopep8.py\n@@ -1313,14 +1313,15 @@ class FixPEP8(object):\n old = []\n for t in tts:\n if tokenize.COMMENT == t[0] and old:\n- comment_index = old[3][1]\n+ comment_row, comment_index = old[3]\n break\n old = t\n break\n if not operator_position:\n return\n target_operator = target[operator_position[0]:operator_position[1]]\n- if comment_index:\n+\n+ if comment_index and comment_row == 1:\n self.source[line_index] = '{}{}'.format(\n target[:operator_position[0]].rstrip(),\n target[comment_index:])\n@@ -1329,6 +1330,7 @@ class FixPEP8(object):\n target[:operator_position[0]].rstrip(),\n target[operator_position[1]:].lstrip(),\n target[operator_position[1]:])\n+\n next_line = self.source[line_index + 1]\n next_line_indent = 0\n m = re.match(r'\\s*', next_line)\n", "test_patch": "diff --git a/test/test_autopep8.py b/test/test_autopep8.py\nindex d1c6e3a..aa502d1 100755\n--- a/test/test_autopep8.py\n+++ b/test/test_autopep8.py\n@@ -4425,6 +4425,24 @@ b = (1 +\n with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n self.assertEqual(fixed, result)\n \n+ def test_w504_comment_on_first_line(self):\n+ line = 'x = (1 | # test\\n2)\\n'\n+ fixed = 'x = (1 # test\\n| 2)\\n'\n+ with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n+ self.assertEqual(fixed, result)\n+\n+ def test_w504_comment_on_second_line(self):\n+ line = 'x = (1 |\\n2) # test\\n'\n+ fixed = 'x = (1\\n| 2) # test\\n'\n+ with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n+ self.assertEqual(fixed, result)\n+\n+ def test_w504_comment_on_each_lines(self):\n+ line = 'x = (1 |# test\\n2 |# test\\n3) # test\\n'\n+ fixed = 'x = (1# test\\n| 2# test\\n| 3) # test\\n'\n+ with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n+ self.assertEqual(fixed, result)\n+\n def test_w504_with_e265_ignore_option(self):\n line = '(width == 0 +\\n height == 0)\\n'\n with autopep8_context(line, options=['--ignore=E265']) as result:\n", "FAIL_TO_PASS": ["test/test_autopep8.py::SystemTests::test_w504_comment_on_second_line"]}, {"instance_id": "hhatto__autopep8-466", "base_commit": "89886b439f35778ac1edefbc93ad9aa411d889d1", "gold_patch": "diff --git a/autopep8.py b/autopep8.py\nindex 8fc548a..3a55a01 100755\n--- a/autopep8.py\n+++ b/autopep8.py\n@@ -100,6 +100,9 @@ SHORTEN_OPERATOR_GROUPS = frozenset([\n \n DEFAULT_IGNORE = 'E226,E24,W50,W690' # TODO: use pycodestyle.DEFAULT_IGNORE\n DEFAULT_INDENT_SIZE = 4\n+# these fixes conflict with each other, if the `--ignore` setting causes both\n+# to be enabled, disable both of them\n+CONFLICTING_CODES = ('W503', 'W504')\n \n SELECTED_GLOBAL_FIXED_METHOD_CODES = ['W602', ]\n \n@@ -3662,6 +3665,14 @@ def parse_args(arguments, apply_config=False):\n \n if args.ignore:\n args.ignore = _split_comma_separated(args.ignore)\n+ if not all(\n+ any(\n+ conflicting_code.startswith(ignore_code)\n+ for ignore_code in args.ignore\n+ )\n+ for conflicting_code in CONFLICTING_CODES\n+ ):\n+ args.ignore.update(CONFLICTING_CODES)\n elif not args.select:\n if args.aggressive:\n # Enable everything by default if aggressive.\n", "test_patch": "diff --git a/test/test_autopep8.py b/test/test_autopep8.py\nindex 14981e8..a35d318 100755\n--- a/test/test_autopep8.py\n+++ b/test/test_autopep8.py\n@@ -4475,6 +4475,24 @@ if True:\n with autopep8_context(line, options=['--select=W504', '--ignore=E']) as result:\n self.assertEqual(fixed, result)\n \n+ def test_w504_not_applied_by_default_when_modifying_with_ignore(self):\n+ line = \"\"\"\\\n+q = 1\n+\n+\n+\n+\n+def x(y, z):\n+ if (\n+ y and\n+ z\n+ ):\n+ pass\n+\"\"\"\n+ fixed = line.replace('\\n\\n\\n\\n', '\\n\\n')\n+ with autopep8_context(line, options=['--ignore=E265']) as result:\n+ self.assertEqual(fixed, result)\n+\n def test_w601(self):\n line = 'a = {0: 1}\\na.has_key(0)\\n'\n fixed = 'a = {0: 1}\\n0 in a\\n'\n", "FAIL_TO_PASS": ["test/test_autopep8.py::SystemTests::test_w504_not_applied_by_default_when_modifying_with_ignore"]}], "all_FAIL_TO_PASS": ["test/test_autopep8.py::SystemTests::test_w605_identical_token", "test/test_autopep8.py::SystemTests::test_w504_comment_on_second_line", "test/test_autopep8.py::SystemTests::test_w504_not_applied_by_default_when_modifying_with_ignore"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ncclient__ncclient-404_x3", "level": 3, "source": "swerebench", "repo": "ncclient/ncclient", "image": "swerebench/sweb.eval.x86_64.ncclient_1776_ncclient-404:latest", "base_commit": "1f8697150508175aa6a7452e4f035ed7de38ae5f", "num_bugs": 3, "bugs": [{"instance_id": "ncclient__ncclient-404", "base_commit": "1f8697150508175aa6a7452e4f035ed7de38ae5f", "gold_patch": "diff --git a/ncclient/xml_.py b/ncclient/xml_.py\nindex 84dbff0..8e81c81 100644\n--- a/ncclient/xml_.py\n+++ b/ncclient/xml_.py\n@@ -223,11 +223,15 @@ class NCElement(object):\n parser=self.__parser)\n return self.__root\n \n+def parent_ns(node):\n+ if node.prefix:\n+ return node.nsmap[node.prefix]\n+ return None\n \n new_ele = lambda tag, attrs={}, **extra: etree.Element(qualify(tag), attrs, **extra)\n \n new_ele_ns = lambda tag, ns, attrs={}, **extra: etree.Element(qualify(tag,ns), attrs, **extra)\n \n-sub_ele = lambda parent, tag, attrs={}, **extra: etree.SubElement(parent, qualify(tag), attrs, **extra)\n+sub_ele = lambda parent, tag, attrs={}, **extra: etree.SubElement(parent, qualify(tag, parent_ns(parent)), attrs, **extra)\n \n sub_ele_ns = lambda parent, tag, ns, attrs={}, **extra: etree.SubElement(parent, qualify(tag, ns), attrs, **extra)\n", "test_patch": "diff --git a/test/unit/test_xml_.py b/test/unit/test_xml_.py\nindex cbdc125..742e851 100644\n--- a/test/unit/test_xml_.py\n+++ b/test/unit/test_xml_.py\n@@ -176,3 +176,16 @@ class TestXML(unittest.TestCase):\n result_xml = result.data_xml\n self.assertRaises(XMLError,\n validated_element, result_xml, tags=[\"rpc\"])\n+\n+ def test_sub_ele_inherit_parent_namespace(self):\n+ device_params = {'name': 'junos'}\n+ device_handler = manager.make_device_handler(device_params)\n+ transform_reply = device_handler.transform_reply()\n+ result = NCElement(self.reply, transform_reply)\n+ ele = new_ele_ns(result.find(\"./cli\").tag, \"http://www.xxx.org\")\n+ child = sub_ele(ele, \"child\")\n+ sibling = sub_ele(ele, \"sibling\")\n+ grandchild = sub_ele(child, \"grandchild\")\n+ self.assertEqual(child.tag, \"{http://www.xxx.org}child\")\n+ self.assertEqual(sibling.tag, \"{http://www.xxx.org}sibling\")\n+ self.assertEqual(grandchild.tag, \"{http://www.xxx.org}grandchild\")\n", "FAIL_TO_PASS": ["test/unit/test_xml_.py::TestXML::test_sub_ele_inherit_parent_namespace"]}, {"instance_id": "ncclient__ncclient-405", "base_commit": "70d2a3287361d50bce6e867ba6f31b9aa16dc357", "gold_patch": "diff --git a/ncclient/operations/util.py b/ncclient/operations/util.py\nindex b1bd733..0d1bb38 100755\n--- a/ncclient/operations/util.py\n+++ b/ncclient/operations/util.py\n@@ -49,10 +49,12 @@ def build_filter(spec, capcheck=None):\n type = None\n if isinstance(spec, tuple):\n type, criteria = spec\n- rep = new_ele(\"filter\", type=type)\n if type == \"xpath\":\n- rep.attrib[\"select\"] = criteria\n+ ns, select = criteria\n+ rep = new_ele_nsmap(\"filter\", ns, type=type)\n+ rep.attrib[\"select\"] = select\n elif type == \"subtree\":\n+ rep = new_ele(\"filter\", type=type)\n rep.append(to_ele(criteria))\n else:\n raise OperationError(\"Invalid filter type\")\ndiff --git a/ncclient/xml_.py b/ncclient/xml_.py\nindex 8e81c81..adcc742 100644\n--- a/ncclient/xml_.py\n+++ b/ncclient/xml_.py\n@@ -228,6 +228,8 @@ def parent_ns(node):\n return node.nsmap[node.prefix]\n return None\n \n+new_ele_nsmap = lambda tag, nsmap, attrs={}, **extra: etree.Element(qualify(tag), attrs, nsmap, **extra)\n+\n new_ele = lambda tag, attrs={}, **extra: etree.Element(qualify(tag), attrs, **extra)\n \n new_ele_ns = lambda tag, ns, attrs={}, **extra: etree.Element(qualify(tag,ns), attrs, **extra)\n", "test_patch": "diff --git a/test/unit/operations/test_utils.py b/test/unit/operations/test_utils.py\nindex 7cad8ab..45adbd3 100644\n--- a/test/unit/operations/test_utils.py\n+++ b/test/unit/operations/test_utils.py\n@@ -58,12 +58,14 @@ class TestUtils(unittest.TestCase):\n self.assertEqual(call, ElementTree.tostring(to_ele(xml)))\n \n def test_build_filter_2(self):\n- criteria = \"configuration/system\"\n+ select = \"configuration/system\"\n+ ns = {\"ns0\": \"http://www.xxx.org\"}\n+ criteria = (ns, select)\n filter = (\"xpath\", criteria)\n reply = build_filter(filter)\n call = ElementTree.tostring(reply)\n- node = new_ele(\"filter\", type=\"xpath\")\n- node.attrib[\"select\"] = criteria\n+ node = new_ele_nsmap(\"filter\", ns, type=\"xpath\")\n+ node.attrib[\"select\"] = select\n self.assertEqual(call, ElementTree.tostring(node))\n \n def test_build_filter_3(self):\n", "FAIL_TO_PASS": ["test/unit/operations/test_utils.py::TestUtils::test_build_filter_2"]}, {"instance_id": "ncclient__ncclient-412", "base_commit": "3255200588c27efbd12e30a5d0ab4f7ad003dd3f", "gold_patch": "diff --git a/ncclient/operations/edit.py b/ncclient/operations/edit.py\nindex 05d7e05..8cfda3f 100644\n--- a/ncclient/operations/edit.py\n+++ b/ncclient/operations/edit.py\n@@ -39,7 +39,7 @@ class EditConfig(RPC):\n \n *default_operation* if specified must be one of { `\"merge\"`, `\"replace\"`, or `\"none\"` }\n \n- *test_option* if specified must be one of { `\"test_then_set\"`, `\"set\"` }\n+ *test_option* if specified must be one of { `\"test-then-set\"`, `\"set\"`, `\"test-only\"` }\n \n *error_option* if specified must be one of { `\"stop-on-error\"`, `\"continue-on-error\"`, `\"rollback-on-error\"` }\n \n@@ -47,13 +47,17 @@ class EditConfig(RPC):\n \"\"\"\n node = new_ele(\"edit-config\")\n node.append(util.datastore_or_url(\"target\", target, self._assert))\n- if default_operation is not None:\n- # TODO: check if it is a valid default-operation\n+ if (default_operation is not None\n+ and util.validate_args('default_operation', default_operation, [\"merge\", \"replace\", \"none\"]) is True):\n sub_ele(node, \"default-operation\").text = default_operation\n- if test_option is not None:\n+ if (test_option is not None\n+ and util.validate_args('test_option', test_option, [\"test-then-set\", \"set\", \"test-only\"]) is True):\n self._assert(':validate')\n+ if test_option == 'test-only':\n+ self._assert(':validate:1.1')\n sub_ele(node, \"test-option\").text = test_option\n- if error_option is not None:\n+ if (error_option is not None\n+ and util.validate_args('error_option', error_option, [\"stop-on-error\", \"continue-on-error\", \"rollback-on-error\"]) is True):\n if error_option == \"rollback-on-error\":\n self._assert(\":rollback-on-error\")\n sub_ele(node, \"error-option\").text = error_option\ndiff --git a/ncclient/operations/util.py b/ncclient/operations/util.py\nindex b760fd1..b1bd733 100755\n--- a/ncclient/operations/util.py\n+++ b/ncclient/operations/util.py\n@@ -71,3 +71,9 @@ def build_filter(spec, capcheck=None):\n if type == \"xpath\" and capcheck is not None:\n capcheck(\":xpath\")\n return rep\n+\n+def validate_args(arg_name, value, args_list):\n+ # this is a common method, which used to check whether a value is in args_list\n+ if value not in args_list:\n+ raise OperationError('Invalid value \"%s\" in \"%s\" element' % (value, arg_name))\n+ return True\n", "test_patch": "diff --git a/test/unit/operations/test_edit.py b/test/unit/operations/test_edit.py\nindex 548e400..6e13691 100644\n--- a/test/unit/operations/test_edit.py\n+++ b/test/unit/operations/test_edit.py\n@@ -52,12 +52,16 @@ class TestEdit(unittest.TestCase):\n host-name foo-bar;\n }\n \"\"\"\n- obj.request(copy.deepcopy(root), format=\"text\", target=\"running\", error_option=\"rollback-on-error\",\n- default_operation=\"default\", test_option=\"test\")\n+ obj.request(copy.deepcopy(root),\n+ format=\"text\",\n+ target=\"running\",\n+ error_option=\"rollback-on-error\",\n+ default_operation=\"merge\",\n+ test_option=\"test-then-set\")\n node = new_ele(\"edit-config\")\n node.append(util.datastore_or_url(\"target\", \"running\"))\n- sub_ele(node, \"default-operation\").text = \"default\"\n- sub_ele(node, \"test-option\").text = \"test\"\n+ sub_ele(node, \"default-operation\").text = \"merge\"\n+ sub_ele(node, \"test-option\").text = \"test-then-set\"\n sub_ele(node, \"error-option\").text = \"rollback-on-error\"\n config_text = sub_ele(node, \"config-text\")\n sub_ele(config_text, \"configuration-text\").text = root\n@@ -66,6 +70,63 @@ class TestEdit(unittest.TestCase):\n call = ElementTree.tostring(call)\n self.assertEqual(call, xml)\n \n+ def test_edit_config_invalid_arguments_exception(self):\n+ session = ncclient.transport.SSHSession(self.device_handler)\n+ session._server_capabilities = [\":rollback-on-error\", \":validate\", \":validate:1.1\"]\n+ obj = EditConfig(\n+ session,\n+ self.device_handler,\n+ raise_mode=RaiseMode.ALL)\n+ root = \"\"\"\n+ system {\n+ host-name foo-bar;\n+ }\n+ \"\"\"\n+ #invalid argument \"default_operation\"\n+ self.assertRaises(OperationError, obj.request,\n+ copy.deepcopy(root),\n+ format=\"xml\",\n+ target=\"running\",\n+ error_option=\"stop-on-error\",\n+ default_operation=\"create\",\n+ test_option=\"test-then-set\")\n+ #invalid argument \"error_option\"\n+ self.assertRaises(OperationError, obj.request,\n+ copy.deepcopy(root),\n+ format=\"xml\",\n+ target=\"running\",\n+ error_option=\"commit-on-error\",\n+ default_operation=\"merge\",\n+ test_option=\"test-then-set\")\n+ #invalid argument \"test_option\"\n+ self.assertRaises(OperationError, obj.request,\n+ copy.deepcopy(root),\n+ format=\"xml\",\n+ target=\"running\",\n+ error_option=\"stop-on-error\",\n+ default_operation=\"merge\",\n+ test_option=\"test\")\n+\n+ def test_edit_config_validate_capability_exception(self):\n+ session = ncclient.transport.SSHSession(self.device_handler)\n+ session._server_capabilities = [\":validate\"]\n+ obj = EditConfig(\n+ session,\n+ self.device_handler,\n+ raise_mode=RaiseMode.ALL)\n+ root = \"\"\"\n+ system {\n+ host-name foo-bar;\n+ }\n+ \"\"\"\n+ self.assertRaises(MissingCapabilityError, obj.request,\n+ copy.deepcopy(root),\n+ format=\"xml\",\n+ target=\"running\",\n+ error_option=\"stop-on-error\",\n+ default_operation=\"merge\",\n+ test_option=\"test-only\")\n+\n @patch('ncclient.operations.RPC._request')\n def test_delete_config(self, mock_request):\n session = ncclient.transport.SSHSession(self.device_handler)\n", "FAIL_TO_PASS": ["test/unit/operations/test_edit.py::TestEdit::test_edit_config_invalid_arguments_exception", "test/unit/operations/test_edit.py::TestEdit::test_edit_config_validate_capability_exception"]}], "all_FAIL_TO_PASS": ["test/unit/test_xml_.py::TestXML::test_sub_ele_inherit_parent_namespace", "test/unit/operations/test_utils.py::TestUtils::test_build_filter_2", "test/unit/operations/test_edit.py::TestEdit::test_edit_config_invalid_arguments_exception", "test/unit/operations/test_edit.py::TestEdit::test_edit_config_validate_capability_exception"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3230_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3230:latest", "base_commit": "163c85c8ed327150a6e5c79f1a4b52a8848d4408", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3230", "base_commit": "163c85c8ed327150a6e5c79f1a4b52a8848d4408", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex be0b1084..fae0177a 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1728,7 +1728,7 @@ class Parser(metaclass=_Parser):\n return self.expression(\n exp.Property,\n this=key.to_dot() if isinstance(key, exp.Column) else key,\n- value=self._parse_column() or self._parse_var(any_token=True),\n+ value=self._parse_bitwise() or self._parse_var(any_token=True),\n )\n \n def _parse_stored(self) -> exp.FileFormatProperty:\n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 1cad1a7d..f4af3f53 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -184,6 +184,10 @@ class TestBigQuery(Validator):\n self.validate_identity(\n \"CREATE OR REPLACE VIEW test (tenant_id OPTIONS (description='Test description on table creation')) AS SELECT 1 AS tenant_id, 1 AS customer_id\",\n )\n+ self.validate_identity(\n+ \"CREATE VIEW `d.v` OPTIONS (expiration_timestamp=TIMESTAMP '2020-01-02T04:05:06.007Z') AS SELECT 1 AS c\",\n+ \"CREATE VIEW `d.v` OPTIONS (expiration_timestamp=CAST('2020-01-02T04:05:06.007Z' AS TIMESTAMP)) AS SELECT 1 AS c\",\n+ )\n self.validate_identity(\n \"SELECT ARRAY(SELECT AS STRUCT 1 a, 2 b)\",\n \"SELECT ARRAY(SELECT AS STRUCT 1 AS a, 2 AS b)\",\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery"]}, {"instance_id": "tobymao__sqlglot-3238", "base_commit": "647611e16bdb5ecfc2eec30111cc6689200836b7", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 5ca0d5d2..742dfcea 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -1839,7 +1839,7 @@ class Check(Expression):\n \n # https://docs.snowflake.com/en/sql-reference/constructs/connect-by\n class Connect(Expression):\n- arg_types = {\"start\": False, \"connect\": True}\n+ arg_types = {\"start\": False, \"connect\": True, \"nocycle\": False}\n \n \n class Prior(Expression):\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 99a3f120..caec78d8 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1846,8 +1846,9 @@ class Generator(metaclass=_Generator):\n def connect_sql(self, expression: exp.Connect) -> str:\n start = self.sql(expression, \"start\")\n start = self.seg(f\"START WITH {start}\") if start else \"\"\n+ nocycle = \" NOCYCLE\" if expression.args.get(\"nocycle\") else \"\"\n connect = self.sql(expression, \"connect\")\n- connect = self.seg(f\"CONNECT BY {connect}\")\n+ connect = self.seg(f\"CONNECT BY{nocycle} {connect}\")\n return start + connect\n \n def prior_sql(self, expression: exp.Prior) -> str:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 01d13346..b380875f 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3505,6 +3505,7 @@ class Parser(metaclass=_Parser):\n return None\n \n self._match(TokenType.CONNECT_BY)\n+ nocycle = self._match_text_seq(\"NOCYCLE\")\n self.NO_PAREN_FUNCTION_PARSERS[\"PRIOR\"] = lambda self: self.expression(\n exp.Prior, this=self._parse_bitwise()\n )\n@@ -3514,7 +3515,7 @@ class Parser(metaclass=_Parser):\n if not start and self._match(TokenType.START_WITH):\n start = self._parse_conjunction()\n \n- return self.expression(exp.Connect, start=start, connect=connect)\n+ return self.expression(exp.Connect, start=start, connect=connect, nocycle=nocycle)\n \n def _parse_name_as_expression(self) -> exp.Alias:\n return self.expression(\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex d1033e47..526b0b5a 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -94,6 +94,9 @@ class TestOracle(Validator):\n \"SELECT * FROM t SAMPLE (0.25)\",\n )\n self.validate_identity(\"SELECT TO_CHAR(-100, 'L99', 'NL_CURRENCY = '' AusDollars '' ')\")\n+ self.validate_identity(\n+ \"SELECT * FROM t START WITH col CONNECT BY NOCYCLE PRIOR col1 = col2\"\n+ )\n \n self.validate_all(\n \"CURRENT_TIMESTAMP BETWEEN TO_DATE(f.C_SDATE, 'yyyy/mm/dd') AND TO_DATE(f.C_EDATE, 'yyyy/mm/dd')\",\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-3242", "base_commit": "59f1d13bc5e37ebe6636b05e0381facc9725f7b0", "gold_patch": "diff --git a/sqlglot/dialects/sqlite.py b/sqlglot/dialects/sqlite.py\nindex 63540a8e..ef7d9aa1 100644\n--- a/sqlglot/dialects/sqlite.py\n+++ b/sqlglot/dialects/sqlite.py\n@@ -33,6 +33,14 @@ def _json_extract_sql(self: SQLite.Generator, expression: exp.JSONExtract) -> st\n return arrow_json_extract_sql(self, expression)\n \n \n+def _build_strftime(args: t.List) -> exp.Anonymous | exp.TimeToStr:\n+ if len(args) == 1:\n+ args.append(exp.CurrentTimestamp())\n+ if len(args) == 2:\n+ return exp.TimeToStr(this=exp.TsOrDsToTimestamp(this=args[1]), format=args[0])\n+ return exp.Anonymous(this=\"STRFTIME\", expressions=args)\n+\n+\n def _transform_create(expression: exp.Expression) -> exp.Expression:\n \"\"\"Move primary key to a column and enforce auto_increment on primary keys.\"\"\"\n schema = expression.this\n@@ -82,6 +90,7 @@ class SQLite(Dialect):\n FUNCTIONS = {\n **parser.Parser.FUNCTIONS,\n \"EDITDIST3\": exp.Levenshtein.from_arg_list,\n+ \"STRFTIME\": _build_strftime,\n }\n STRING_ALIASES = True\n \n@@ -152,7 +161,9 @@ class SQLite(Dialect):\n ),\n exp.TableSample: no_tablesample_sql,\n exp.TimeStrToTime: lambda self, e: self.sql(e, \"this\"),\n+ exp.TimeToStr: lambda self, e: self.func(\"STRFTIME\", e.args.get(\"format\"), e.this),\n exp.TryCast: no_trycast_sql,\n+ exp.TsOrDsToTimestamp: lambda self, e: self.sql(e, \"this\"),\n }\n \n # SQLite doesn't generally support CREATE TABLE .. properties\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 742dfcea..75751444 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5687,6 +5687,10 @@ class TsOrDsToTime(Func):\n pass\n \n \n+class TsOrDsToTimestamp(Func):\n+ pass\n+\n+\n class TsOrDiToDi(Func):\n pass\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex caec78d8..a67c7003 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -3516,6 +3516,13 @@ class Generator(metaclass=_Generator):\n \n return self.sql(exp.cast(this, \"time\"))\n \n+ def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:\n+ this = expression.this\n+ if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):\n+ return self.sql(this)\n+\n+ return self.sql(exp.cast(this, \"timestamp\"))\n+\n def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:\n this = expression.this\n time_format = self.format_time(expression)\n", "test_patch": "diff --git a/tests/dialects/test_sqlite.py b/tests/dialects/test_sqlite.py\nindex e935c194..f3cde0b6 100644\n--- a/tests/dialects/test_sqlite.py\n+++ b/tests/dialects/test_sqlite.py\n@@ -6,62 +6,6 @@ from sqlglot.helper import logger as helper_logger\n class TestSQLite(Validator):\n dialect = \"sqlite\"\n \n- def test_ddl(self):\n- for conflict_action in (\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"):\n- with self.subTest(f\"ON CONFLICT {conflict_action}\"):\n- self.validate_identity(\"CREATE TABLE a (b, c, UNIQUE (b, c) ON CONFLICT IGNORE)\")\n-\n- self.validate_identity(\"INSERT OR ABORT INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR FAIL INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR IGNORE INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR REPLACE INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR ROLLBACK INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"CREATE TABLE foo (id INTEGER PRIMARY KEY ASC)\")\n- self.validate_identity(\"CREATE TEMPORARY TABLE foo (id INTEGER)\")\n-\n- self.validate_all(\n- \"\"\"\n- CREATE TABLE \"Track\"\n- (\n- CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n- FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n- \"AlbumId\"\n- ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n- FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n- FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n- )\n- \"\"\",\n- write={\n- \"sqlite\": \"\"\"CREATE TABLE \"Track\" (\n- CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n- FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n- \"AlbumId\"\n- ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n- FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n- FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n-)\"\"\",\n- },\n- pretty=True,\n- )\n- self.validate_all(\n- \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n- read={\n- \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n- },\n- write={\n- \"sqlite\": \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n- \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n- \"postgres\": \"CREATE TABLE z (a INT GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE PRIMARY KEY)\",\n- },\n- )\n- self.validate_all(\n- \"\"\"CREATE TABLE \"x\" (\"Name\" NVARCHAR(200) NOT NULL)\"\"\",\n- write={\n- \"sqlite\": \"\"\"CREATE TABLE \"x\" (\"Name\" TEXT(200) NOT NULL)\"\"\",\n- \"mysql\": \"CREATE TABLE `x` (`Name` VARCHAR(200) NOT NULL)\",\n- },\n- )\n-\n def test_sqlite(self):\n self.validate_identity(\"SELECT DATE()\")\n self.validate_identity(\"SELECT DATE('now', 'start of month', '+1 month', '-1 day')\")\n@@ -69,7 +13,6 @@ class TestSQLite(Validator):\n self.validate_identity(\"SELECT DATETIME(1092941466, 'auto')\")\n self.validate_identity(\"SELECT DATETIME(1092941466, 'unixepoch', 'localtime')\")\n self.validate_identity(\"SELECT UNIXEPOCH()\")\n- self.validate_identity(\"SELECT STRFTIME('%s')\")\n self.validate_identity(\"SELECT JULIANDAY('now') - JULIANDAY('1776-07-04')\")\n self.validate_identity(\"SELECT UNIXEPOCH() - UNIXEPOCH('2004-01-01 02:34:56')\")\n self.validate_identity(\"SELECT DATE('now', 'start of year', '+9 months', 'weekday 2')\")\n@@ -149,6 +92,29 @@ class TestSQLite(Validator):\n write={\"snowflake\": \"LEAST(x, y, z)\"},\n )\n \n+ def test_strftime(self):\n+ self.validate_identity(\"SELECT STRFTIME('%Y/%m/%d', 'now')\")\n+ self.validate_identity(\"SELECT STRFTIME('%Y-%m-%d', '2016-10-16', 'start of month')\")\n+ self.validate_identity(\n+ \"SELECT STRFTIME('%s')\",\n+ \"SELECT STRFTIME('%s', CURRENT_TIMESTAMP)\",\n+ )\n+\n+ self.validate_all(\n+ \"SELECT STRFTIME('%Y-%m-%d', '2020-01-01 12:05:03')\",\n+ write={\n+ \"duckdb\": \"SELECT STRFTIME(CAST('2020-01-01 12:05:03' AS TIMESTAMP), '%Y-%m-%d')\",\n+ \"sqlite\": \"SELECT STRFTIME('%Y-%m-%d', '2020-01-01 12:05:03')\",\n+ },\n+ )\n+ self.validate_all(\n+ \"SELECT STRFTIME('%Y-%m-%d', CURRENT_TIMESTAMP)\",\n+ write={\n+ \"duckdb\": \"SELECT STRFTIME(CAST(CURRENT_TIMESTAMP AS TIMESTAMP), '%Y-%m-%d')\",\n+ \"sqlite\": \"SELECT STRFTIME('%Y-%m-%d', CURRENT_TIMESTAMP)\",\n+ },\n+ )\n+\n def test_datediff(self):\n self.validate_all(\n \"DATEDIFF(a, b, 'day')\",\n@@ -194,3 +160,59 @@ class TestSQLite(Validator):\n )\n \n self.assertIn(\"Named columns are not supported in table alias.\", cm.output[0])\n+\n+ def test_ddl(self):\n+ for conflict_action in (\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"):\n+ with self.subTest(f\"ON CONFLICT {conflict_action}\"):\n+ self.validate_identity(\"CREATE TABLE a (b, c, UNIQUE (b, c) ON CONFLICT IGNORE)\")\n+\n+ self.validate_identity(\"INSERT OR ABORT INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR FAIL INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR IGNORE INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR REPLACE INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR ROLLBACK INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"CREATE TABLE foo (id INTEGER PRIMARY KEY ASC)\")\n+ self.validate_identity(\"CREATE TEMPORARY TABLE foo (id INTEGER)\")\n+\n+ self.validate_all(\n+ \"\"\"\n+ CREATE TABLE \"Track\"\n+ (\n+ CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n+ FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n+ \"AlbumId\"\n+ ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n+ )\n+ \"\"\",\n+ write={\n+ \"sqlite\": \"\"\"CREATE TABLE \"Track\" (\n+ CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n+ FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n+ \"AlbumId\"\n+ ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n+)\"\"\",\n+ },\n+ pretty=True,\n+ )\n+ self.validate_all(\n+ \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n+ read={\n+ \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n+ },\n+ write={\n+ \"sqlite\": \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n+ \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n+ \"postgres\": \"CREATE TABLE z (a INT GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE PRIMARY KEY)\",\n+ },\n+ )\n+ self.validate_all(\n+ \"\"\"CREATE TABLE \"x\" (\"Name\" NVARCHAR(200) NOT NULL)\"\"\",\n+ write={\n+ \"sqlite\": \"\"\"CREATE TABLE \"x\" (\"Name\" TEXT(200) NOT NULL)\"\"\",\n+ \"mysql\": \"CREATE TABLE `x` (`Name` VARCHAR(200) NOT NULL)\",\n+ },\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_sqlite.py::TestSQLite::test_strftime"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery", "tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_sqlite.py::TestSQLite::test_strftime"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-4141_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-4141:latest", "base_commit": "8822d6c1b3b62cfd76fd481db473bf8ea1c12b1a", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-4141", "base_commit": "8822d6c1b3b62cfd76fd481db473bf8ea1c12b1a", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex ec1984e9..c8671f69 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -756,6 +756,26 @@ class ClickHouse(Dialect):\n def _parse_constraint(self) -> t.Optional[exp.Expression]:\n return super()._parse_constraint() or self._parse_projection_def()\n \n+ def _parse_alias(\n+ self, this: t.Optional[exp.Expression], explicit: bool = False\n+ ) -> t.Optional[exp.Expression]:\n+ # In clickhouse \"SELECT APPLY(...)\" is a query modifier,\n+ # so \"APPLY\" shouldn't be parsed as 's alias. However, \"SELECT apply\" is a valid alias\n+ if self._match_pair(TokenType.APPLY, TokenType.L_PAREN, advance=False):\n+ return this\n+\n+ return super()._parse_alias(this=this, explicit=explicit)\n+\n+ def _parse_expression(self) -> t.Optional[exp.Expression]:\n+ this = super()._parse_expression()\n+\n+ # Clickhouse allows \"SELECT [APPLY(func)] [...]]\" modifier\n+ while self._match_pair(TokenType.APPLY, TokenType.L_PAREN):\n+ this = exp.Apply(this=this, expression=self._parse_var(any_token=True))\n+ self._match(TokenType.R_PAREN)\n+\n+ return this\n+\n class Generator(generator.Generator):\n QUERY_HINTS = False\n STRUCT_DELIMITER = (\"(\", \")\")\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex d44b2c3d..95f3c01c 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -4922,6 +4922,10 @@ class ApproxDistinct(AggFunc):\n _sql_names = [\"APPROX_DISTINCT\", \"APPROX_COUNT_DISTINCT\"]\n \n \n+class Apply(Func):\n+ arg_types = {\"this\": True, \"expression\": True}\n+\n+\n class Array(Func):\n arg_types = {\"expressions\": False, \"bracket_notation\": False}\n is_var_len_args = True\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 80c86288..e2029313 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -4336,3 +4336,9 @@ class Generator(metaclass=_Generator):\n array_agg = f\"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)\"\n \n return array_agg\n+\n+ def apply_sql(self, expression: exp.Apply) -> str:\n+ this = self.sql(expression, \"this\")\n+ expr = self.sql(expression, \"expression\")\n+\n+ return f\"{this} APPLY({expr})\"\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex d203141d..aa6c4f1b 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -519,6 +519,14 @@ class TestClickhouse(Validator):\n self.validate_identity(\"SELECT TRIM(LEADING '(' FROM '( Hello, world! )')\")\n self.validate_identity(\"current_timestamp\").assert_is(exp.Column)\n \n+ self.validate_identity(\"SELECT * APPLY(sum) FROM columns_transformers\")\n+ self.validate_identity(\"SELECT COLUMNS('[jk]') APPLY(toString) FROM columns_transformers\")\n+ self.validate_identity(\n+ \"SELECT COLUMNS('[jk]') APPLY(toString) APPLY(length) APPLY(max) FROM columns_transformers\"\n+ )\n+ self.validate_identity(\"SELECT * APPLY(sum), COLUMNS('col') APPLY(sum) APPLY(avg) FROM t\")\n+ self.validate_identity(\"SELECT col apply\", \"SELECT col AS apply\")\n+\n def test_clickhouse_values(self):\n values = exp.select(\"*\").from_(\n exp.values([exp.tuple_(1, 2, 3)], alias=\"subq\", columns=[\"a\", \"b\", \"c\"])\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"]}, {"instance_id": "tobymao__sqlglot-4148", "base_commit": "be0a4a85d41bfb617360bd9a59aa9e631e4d6d6c", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 95f3c01c..de48a8a4 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -4123,6 +4123,7 @@ class DataType(Expression):\n NUMRANGE = auto()\n NVARCHAR = auto()\n OBJECT = auto()\n+ RANGE = auto()\n ROWVERSION = auto()\n SERIAL = auto()\n SET = auto()\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 96df5c01..a9fc38e5 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -269,6 +269,7 @@ class Parser(metaclass=_Parser):\n TokenType.LOWCARDINALITY,\n TokenType.MAP,\n TokenType.NULLABLE,\n+ TokenType.RANGE,\n *STRUCT_TYPE_TOKENS,\n }\n \n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 2c6a6076..e2adfeab 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -1962,3 +1962,26 @@ OPTIONS (\n \"duckdb\": \"WITH Races AS (SELECT '800M' AS race) SELECT race, participant FROM Races AS r CROSS JOIN (SELECT UNNEST([{'name': 'Rudisha', 'laps': [23.4, 26.3, 26.4, 26.1]}], max_depth => 2)) AS participant\",\n },\n )\n+\n+ def test_range_type(self):\n+ for type, value in (\n+ (\"RANGE\", \"'[2020-01-01, 2020-12-31)'\"),\n+ (\"RANGE\", \"'[UNBOUNDED, 2020-12-31)'\"),\n+ (\"RANGE\", \"'[2020-01-01 12:00:00, 2020-12-31 12:00:00)'\"),\n+ (\"RANGE\", \"'[2020-10-01 12:00:00+08, 2020-12-31 12:00:00+08)'\"),\n+ ):\n+ with self.subTest(f\"Testing BigQuery's RANGE type: {type} {value}\"):\n+ self.validate_identity(f\"SELECT {type} {value}\", f\"SELECT CAST({value} AS {type})\")\n+\n+ self.assertEqual(self.parse_one(type), exp.DataType.build(type, dialect=\"bigquery\"))\n+\n+ self.validate_identity(\n+ \"SELECT RANGE(CAST('2022-12-01' AS DATE), CAST('2022-12-31' AS DATE))\"\n+ )\n+ self.validate_identity(\"SELECT RANGE(NULL, CAST('2022-12-31' AS DATE))\")\n+ self.validate_identity(\n+ \"SELECT RANGE(CAST('2022-10-01 14:53:27' AS DATETIME), CAST('2022-10-01 16:00:00' AS DATETIME))\"\n+ )\n+ self.validate_identity(\n+ \"SELECT RANGE(CAST('2022-10-01 14:53:27 America/Los_Angeles' AS TIMESTAMP), CAST('2022-10-01 16:00:00 America/Los_Angeles' AS TIMESTAMP))\"\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_range_type"]}, {"instance_id": "tobymao__sqlglot-4151", "base_commit": "044481926d4b008027a2c7fb20501514ef507811", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex c8671f69..b682fa3f 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -918,9 +918,10 @@ class ClickHouse(Dialect):\n \n PROPERTIES_LOCATION = {\n **generator.Generator.PROPERTIES_LOCATION,\n- exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,\n- exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,\n exp.OnCluster: exp.Properties.Location.POST_NAME,\n+ exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,\n+ exp.ToTableProperty: exp.Properties.Location.POST_NAME,\n+ exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,\n }\n \n # There's no list in docs, but it can be found in Clickhouse code\n@@ -1089,7 +1090,9 @@ class ClickHouse(Dialect):\n [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]\n )\n this_schema = self.schema_columns_sql(expression.this)\n- return f\"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}\"\n+ this_schema = f\"{self.sep()}{this_schema}\" if this_schema else \"\"\n+\n+ return f\"{this_name}{self.sep()}{this_properties}{this_schema}\"\n \n return super().createable_sql(expression, locations)\n \n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex aa6c4f1b..bc5a4a43 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -139,10 +139,10 @@ class TestClickhouse(Validator):\n \"CREATE MATERIALIZED VIEW test_view ON CLUSTER cl1 (id UInt8) ENGINE=AggregatingMergeTree() ORDER BY tuple() AS SELECT * FROM test_data\"\n )\n self.validate_identity(\n- \"CREATE MATERIALIZED VIEW test_view ON CLUSTER cl1 (id UInt8) TO table1 AS SELECT * FROM test_data\"\n+ \"CREATE MATERIALIZED VIEW test_view ON CLUSTER cl1 TO table1 AS SELECT * FROM test_data\"\n )\n self.validate_identity(\n- \"CREATE MATERIALIZED VIEW test_view (id UInt8) TO db.table1 AS SELECT * FROM test_data\"\n+ \"CREATE MATERIALIZED VIEW test_view TO db.table1 (id UInt8) AS SELECT * FROM test_data\"\n )\n self.validate_identity(\n \"CREATE TABLE t (foo String CODEC(LZ4HC(9), ZSTD, DELTA), size String ALIAS formatReadableSize(size_bytes), INDEX idx1 a TYPE bloom_filter(0.001) GRANULARITY 1, INDEX idx2 a TYPE set(100) GRANULARITY 2, INDEX idx3 a TYPE minmax GRANULARITY 3)\"\n@@ -678,6 +678,7 @@ class TestClickhouse(Validator):\n \"CREATE TABLE foo ENGINE=Memory AS (SELECT * FROM db.other_table) COMMENT 'foo'\",\n )\n \n+ self.validate_identity(\"CREATE MATERIALIZED VIEW a.b TO a.c (c Int32) AS SELECT * FROM a.d\")\n self.validate_identity(\"\"\"CREATE TABLE ip_data (ip4 IPv4, ip6 IPv6) ENGINE=TinyLog()\"\"\")\n self.validate_identity(\"\"\"CREATE TABLE dates (dt1 Date32) ENGINE=TinyLog()\"\"\")\n self.validate_identity(\"CREATE TABLE named_tuples (a Tuple(select String, i Int64))\")\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_clickhouse.py::TestClickhouse::test_ddl"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_bigquery.py::TestBigQuery::test_range_type", "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_clickhouse.py::TestClickhouse::test_ddl"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-4545_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-4545:latest", "base_commit": "810d9352ab158994b534ae58040606f05b0092a9", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-4545", "base_commit": "810d9352ab158994b534ae58040606f05b0092a9", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 2be42854..9d65e57e 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -4244,6 +4244,7 @@ class Pivot(Expression):\n \"columns\": False,\n \"include_nulls\": False,\n \"default_on_null\": False,\n+ \"into\": False,\n }\n \n @property\n@@ -4251,6 +4252,12 @@ class Pivot(Expression):\n return bool(self.args.get(\"unpivot\"))\n \n \n+# https://duckdb.org/docs/sql/statements/unpivot#simplified-unpivot-syntax\n+# UNPIVOT ... INTO [NAME VALUE ][...,]\n+class UnpivotColumns(Expression):\n+ arg_types = {\"this\": True, \"expressions\": True}\n+\n+\n class Window(Condition):\n arg_types = {\n \"this\": True,\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex d7e8b0e6..f30472fd 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1988,6 +1988,7 @@ class Generator(metaclass=_Generator):\n \n def pivot_sql(self, expression: exp.Pivot) -> str:\n expressions = self.expressions(expression, flat=True)\n+ direction = \"UNPIVOT\" if expression.unpivot else \"PIVOT\"\n \n if expression.this:\n this = self.sql(expression, \"this\")\n@@ -1995,14 +1996,15 @@ class Generator(metaclass=_Generator):\n return f\"UNPIVOT {this}\"\n \n on = f\"{self.seg('ON')} {expressions}\"\n+ into = self.sql(expression, \"into\")\n+ into = f\"{self.seg('INTO')} {into}\" if into else \"\"\n using = self.expressions(expression, key=\"using\", flat=True)\n using = f\"{self.seg('USING')} {using}\" if using else \"\"\n group = self.sql(expression, \"group\")\n- return f\"PIVOT {this}{on}{using}{group}\"\n+ return f\"{direction} {this}{on}{into}{using}{group}\"\n \n alias = self.sql(expression, \"alias\")\n alias = f\" AS {alias}\" if alias else \"\"\n- direction = self.seg(\"UNPIVOT\" if expression.unpivot else \"PIVOT\")\n \n field = self.sql(expression, \"field\")\n \n@@ -2014,7 +2016,7 @@ class Generator(metaclass=_Generator):\n \n default_on_null = self.sql(expression, \"default_on_null\")\n default_on_null = f\" DEFAULT ON NULL ({default_on_null})\" if default_on_null else \"\"\n- return f\"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}\"\n+ return f\"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}\"\n \n def version_sql(self, expression: exp.Version) -> str:\n this = f\"FOR {expression.name}\"\n@@ -4637,3 +4639,9 @@ class Generator(metaclass=_Generator):\n every.this.replace(exp.Literal.number(every.name))\n \n return f\"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}\"\n+\n+ def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:\n+ name = self.sql(expression, \"this\")\n+ values = self.expressions(expression, flat=True)\n+\n+ return f\"NAME {name} VALUE {values}\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 4cbaf89a..20ca97c4 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -809,6 +809,7 @@ class Parser(metaclass=_Parser):\n TokenType.SET: lambda self: self._parse_set(),\n TokenType.TRUNCATE: lambda self: self._parse_truncate_table(),\n TokenType.UNCACHE: lambda self: self._parse_uncache(),\n+ TokenType.UNPIVOT: lambda self: self._parse_simplified_pivot(is_unpivot=True),\n TokenType.UPDATE: lambda self: self._parse_update(),\n TokenType.USE: lambda self: self.expression(\n exp.Use,\n@@ -3056,8 +3057,10 @@ class Parser(metaclass=_Parser):\n \n this = self._parse_query_modifiers(this)\n elif (table or nested) and self._match(TokenType.L_PAREN):\n- if self._match(TokenType.PIVOT):\n- this = self._parse_simplified_pivot()\n+ if self._match_set((TokenType.PIVOT, TokenType.UNPIVOT)):\n+ this = self._parse_simplified_pivot(\n+ is_unpivot=self._prev.token_type == TokenType.UNPIVOT\n+ )\n elif self._match(TokenType.FROM):\n this = exp.select(\"*\").from_(\n t.cast(exp.From, self._parse_from(skip_from_token=True))\n@@ -4000,20 +4003,46 @@ class Parser(metaclass=_Parser):\n def _parse_joins(self) -> t.Iterator[exp.Join]:\n return iter(self._parse_join, None)\n \n+ def _parse_unpivot_columns(self) -> t.Optional[exp.UnpivotColumns]:\n+ if not self._match(TokenType.INTO):\n+ return None\n+\n+ return self.expression(\n+ exp.UnpivotColumns,\n+ this=self._match_text_seq(\"NAME\") and self._parse_column(),\n+ expressions=self._match_text_seq(\"VALUE\") and self._parse_csv(self._parse_column),\n+ )\n+\n # https://duckdb.org/docs/sql/statements/pivot\n- def _parse_simplified_pivot(self) -> exp.Pivot:\n+ def _parse_simplified_pivot(self, is_unpivot: t.Optional[bool] = None) -> exp.Pivot:\n def _parse_on() -> t.Optional[exp.Expression]:\n this = self._parse_bitwise()\n- return self._parse_in(this) if self._match(TokenType.IN) else this\n+\n+ if self._match(TokenType.IN):\n+ # PIVOT ... ON col IN (row_val1, row_val2)\n+ return self._parse_in(this)\n+ if self._match(TokenType.ALIAS, advance=False):\n+ # UNPIVOT ... ON (col1, col2, col3) AS row_val\n+ return self._parse_alias(this)\n+\n+ return this\n \n this = self._parse_table()\n expressions = self._match(TokenType.ON) and self._parse_csv(_parse_on)\n+ into = self._parse_unpivot_columns()\n using = self._match(TokenType.USING) and self._parse_csv(\n lambda: self._parse_alias(self._parse_function())\n )\n group = self._parse_group()\n+\n return self.expression(\n- exp.Pivot, this=this, expressions=expressions, using=using, group=group\n+ exp.Pivot,\n+ this=this,\n+ expressions=expressions,\n+ using=using,\n+ group=group,\n+ unpivot=is_unpivot,\n+ into=into,\n )\n \n def _parse_pivot_in(self) -> exp.In | exp.PivotAny:\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 09f0134d..62db3800 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -276,12 +276,6 @@ class TestDuckDB(Validator):\n self.validate_identity(\"SELECT UNNEST(col, recursive := TRUE) FROM t\")\n self.validate_identity(\"VAR_POP(a)\")\n self.validate_identity(\"SELECT * FROM foo ASOF LEFT JOIN bar ON a = b\")\n- self.validate_identity(\"PIVOT Cities ON Year USING SUM(Population)\")\n- self.validate_identity(\"PIVOT Cities ON Year USING FIRST(Population)\")\n- self.validate_identity(\"PIVOT Cities ON Year USING SUM(Population) GROUP BY Country\")\n- self.validate_identity(\"PIVOT Cities ON Country, Name USING SUM(Population)\")\n- self.validate_identity(\"PIVOT Cities ON Country || '_' || Name USING SUM(Population)\")\n- self.validate_identity(\"PIVOT Cities ON Year USING SUM(Population) GROUP BY Country, Name\")\n self.validate_identity(\"SELECT {'a': 1} AS x\")\n self.validate_identity(\"SELECT {'a': {'b': {'c': 1}}, 'd': {'e': 2}} AS x\")\n self.validate_identity(\"SELECT {'x': 1, 'y': 2, 'z': 3}\")\n@@ -1415,3 +1409,28 @@ class TestDuckDB(Validator):\n self.validate_identity(\"DETACH IF EXISTS file\")\n \n self.validate_identity(\"DETACH DATABASE db\", \"DETACH db\")\n+\n+ def test_simplified_pivot_unpivot(self):\n+ self.validate_identity(\"PIVOT Cities ON Year USING SUM(Population)\")\n+ self.validate_identity(\"PIVOT Cities ON Year USING FIRST(Population)\")\n+ self.validate_identity(\"PIVOT Cities ON Year USING SUM(Population) GROUP BY Country\")\n+ self.validate_identity(\"PIVOT Cities ON Country, Name USING SUM(Population)\")\n+ self.validate_identity(\"PIVOT Cities ON Country || '_' || Name USING SUM(Population)\")\n+ self.validate_identity(\"PIVOT Cities ON Year USING SUM(Population) GROUP BY Country, Name\")\n+\n+ self.validate_identity(\"UNPIVOT (SELECT 1 AS col1, 2 AS col2) ON foo, bar\")\n+ self.validate_identity(\n+ \"UNPIVOT monthly_sales ON jan, feb, mar, apr, may, jun INTO NAME month VALUE sales\"\n+ )\n+ self.validate_identity(\n+ \"UNPIVOT monthly_sales ON COLUMNS(* EXCLUDE (empid, dept)) INTO NAME month VALUE sales\"\n+ )\n+ self.validate_identity(\n+ \"UNPIVOT monthly_sales ON (jan, feb, mar) AS q1, (apr, may, jun) AS q2 INTO NAME quarter VALUE month_1_sales, month_2_sales, month_3_sales\"\n+ )\n+ self.validate_identity(\n+ \"WITH unpivot_alias AS (UNPIVOT monthly_sales ON COLUMNS(* EXCLUDE (empid, dept)) INTO NAME month VALUE sales) SELECT * FROM unpivot_alias\"\n+ )\n+ self.validate_identity(\n+ \"SELECT * FROM (UNPIVOT monthly_sales ON COLUMNS(* EXCLUDE (empid, dept)) INTO NAME month VALUE sales) AS unpivot_alias\"\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_simplified_pivot_unpivot"]}, {"instance_id": "tobymao__sqlglot-4546", "base_commit": "931eef6958be87ef88f4ff5311441e7a7004b8c5", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 911e8c51..cc85de01 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -633,7 +633,7 @@ class ClickHouse(Dialect):\n return super()._parse_position(haystack_first=True)\n \n # https://clickhouse.com/docs/en/sql-reference/statements/select/with/\n- def _parse_cte(self) -> exp.CTE:\n+ def _parse_cte(self) -> t.Optional[exp.CTE]:\n # WITH AS \n cte: t.Optional[exp.CTE] = self._try_parse(super()._parse_cte)\n \ndiff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py\nindex 08d99e4e..c84632f2 100644\n--- a/sqlglot/dialects/spark.py\n+++ b/sqlglot/dialects/spark.py\n@@ -102,6 +102,8 @@ class Spark(Spark2):\n ]\n \n class Parser(Spark2.Parser):\n+ OPTIONAL_ALIAS_TOKEN_CTE = True\n+\n FUNCTIONS = {\n **Spark2.Parser.FUNCTIONS,\n \"ANY_VALUE\": _build_with_ignore_nulls(exp.AnyValue),\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 20ca97c4..2fa9ab44 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1379,6 +1379,9 @@ class Parser(metaclass=_Parser):\n # Whether the `name AS expr` schema/column constraint requires parentheses around `expr`\n WRAPPED_TRANSFORM_COLUMN_CONSTRAINT = True\n \n+ # Whether the 'AS' keyword is optional in the CTE definition syntax\n+ OPTIONAL_ALIAS_TOKEN_CTE = False\n+\n __slots__ = (\n \"error_level\",\n \"error_message_context\",\n@@ -3131,12 +3134,17 @@ class Parser(metaclass=_Parser):\n exp.With, comments=comments, expressions=expressions, recursive=recursive\n )\n \n- def _parse_cte(self) -> exp.CTE:\n+ def _parse_cte(self) -> t.Optional[exp.CTE]:\n+ index = self._index\n+\n alias = self._parse_table_alias(self.ID_VAR_TOKENS)\n if not alias or not alias.this:\n self.raise_error(\"Expected CTE to have alias\")\n \n- self._match(TokenType.ALIAS)\n+ if not self._match(TokenType.ALIAS) and not self.OPTIONAL_ALIAS_TOKEN_CTE:\n+ self._retreat(index)\n+ return None\n+\n comments = self._prev_comments\n \n if self._match_text_seq(\"NOT\", \"MATERIALIZED\"):\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex 49705d51..3bff6e22 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -29,6 +29,7 @@ class TestClickhouse(Validator):\n self.assertEqual(expr.sql(dialect=\"clickhouse\"), \"COUNT(x)\")\n self.assertIsNone(expr._meta)\n \n+ self.validate_identity(\"WITH arrayJoin([(1, [2, 3])]) AS arr SELECT arr\")\n self.validate_identity(\"CAST(1 AS Bool)\")\n self.validate_identity(\"SELECT toString(CHAR(104.1, 101, 108.9, 108.9, 111, 32))\")\n self.validate_identity(\"@macro\").assert_is(exp.Parameter).this.assert_is(exp.Var)\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"]}, {"instance_id": "tobymao__sqlglot-4550", "base_commit": "cead7c32bef44c0efaf48c2038976c7c7f2b709c", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 9d65e57e..56a347ab 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2291,6 +2291,7 @@ class OnConflict(Expression):\n \"action\": False,\n \"conflict_keys\": False,\n \"constraint\": False,\n+ \"where\": False,\n }\n \n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex f30472fd..f717e312 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1861,7 +1861,8 @@ class Generator(metaclass=_Generator):\n set_keyword = \"SET \" if self.DUPLICATE_KEY_UPDATE_WITH_SET else \"\"\n expressions = f\" {set_keyword}{expressions}\"\n \n- return f\"{conflict}{constraint}{conflict_keys}{action}{expressions}\"\n+ where = self.sql(expression, \"where\")\n+ return f\"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}\"\n \n def returning_sql(self, expression: exp.Returning) -> str:\n return f\"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 2fa9ab44..0e525e7a 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -2732,6 +2732,8 @@ class Parser(metaclass=_Parser):\n if not is_function\n else self._parse_function()\n )\n+ if isinstance(this, exp.Table) and self._match(TokenType.ALIAS, advance=False):\n+ this.set(\"alias\", self._parse_table_alias())\n \n returning = self._parse_returning()\n \n@@ -2796,6 +2798,7 @@ class Parser(metaclass=_Parser):\n action=action,\n conflict_keys=conflict_keys,\n constraint=constraint,\n+ where=self._parse_where(),\n )\n \n def _parse_returning(self) -> t.Optional[exp.Returning]:\n", "test_patch": "diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex acdb2d4a..019a10e9 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -874,6 +874,9 @@ class TestPostgres(Validator):\n self.validate_identity(\"ALTER TABLE t1 SET ACCESS METHOD method\")\n self.validate_identity(\"ALTER TABLE t1 SET TABLESPACE tablespace\")\n self.validate_identity(\"ALTER TABLE t1 SET (fillfactor = 5, autovacuum_enabled = TRUE)\")\n+ self.validate_identity(\n+ \"INSERT INTO newtable AS t(a, b, c) VALUES (1, 2, 3) ON CONFLICT(c) DO UPDATE SET a = t.a + 1 WHERE t.a < 1\"\n+ )\n self.validate_identity(\n \"ALTER TABLE tested_table ADD CONSTRAINT unique_example UNIQUE (column_name) NOT VALID\"\n )\n", "FAIL_TO_PASS": ["tests/dialects/test_postgres.py::TestPostgres::test_ddl"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_simplified_pivot_unpivot", "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_postgres.py::TestPostgres::test_ddl"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "codalab__codalab-worksheets-3076_x3", "level": 3, "source": "swerebench", "repo": "codalab/codalab-worksheets", "image": "swerebench/sweb.eval.x86_64.codalab_1776_codalab-worksheets-3076:latest", "base_commit": "ae54f808964ec5bf7cc300fe09b10aa153249ae8", "num_bugs": 3, "bugs": [{"instance_id": "codalab__codalab-worksheets-3076", "base_commit": "ae54f808964ec5bf7cc300fe09b10aa153249ae8", "gold_patch": "diff --git a/codalab/lib/interactive_session.py b/codalab/lib/interactive_session.py\nindex 445d4368..9ee96254 100644\n--- a/codalab/lib/interactive_session.py\n+++ b/codalab/lib/interactive_session.py\n@@ -31,7 +31,7 @@ class InteractiveSession:\n 9. Stop and remove the interactive session container.\n \"\"\"\n \n- _BASH_HISTORY_CONTAINER_PATH = '/root/.bash_history'\n+ _BASH_HISTORY_CONTAINER_PATH = \"/usr/sbin/.bash_history\"\n _CHOOSE_COMMAND_INSTRUCTIONS = (\n \"\\n\\n#\\n\"\n \"# Choose the commands to use for cl run:\\n\"\n@@ -80,10 +80,15 @@ class InteractiveSession:\n self._stderr = stderr\n \n def start(self):\n- self._bundle_path = os.path.join(\n+ self._host_bundle_path = os.path.join(\n self._manager.codalab_home, 'local_bundles', self._session_uuid\n )\n- os.makedirs(self._bundle_path)\n+ os.makedirs(self._host_bundle_path)\n+\n+ # Create a blank file which will be used as the bash history file that will later be\n+ # mounted and populated during the interactive session.\n+ self._host_bash_history_path = os.path.join(self._host_bundle_path, \".bash_history\")\n+ open(self._host_bash_history_path, 'w').close()\n \n run_command = self.get_docker_run_command()\n \n@@ -91,11 +96,13 @@ class InteractiveSession:\n print('\\nStarting an interactive session...', file=self._stdout)\n print('%s\\n' % run_command, file=self._stdout)\n print('=' * 150, file=self._stdout)\n- print('Session UUID:', self._session_uuid, file=self._stdout)\n- print('CodaLab instance:', self._manager.current_client().address, file=self._stdout)\n- print('Container name:', self._get_container_name(), file=self._stdout)\n- print('Container Docker image:', self._docker_image, file=self._stdout)\n- print('You can find local bundle contents at:', self._bundle_path, file=self._stdout)\n+ print('Session UUID: ', self._session_uuid, file=self._stdout)\n+ print('CodaLab instance: ', self._manager.current_client().address, file=self._stdout)\n+ print('Container name: ', self._get_container_name(), file=self._stdout)\n+ print('Container Docker image: ', self._docker_image, file=self._stdout)\n+ print(\n+ 'You can find local bundle contents at: ', self._host_bundle_path, file=self._stdout\n+ )\n print('=' * 150 + '\\n', file=self._stdout)\n \n self._container = self._start_session(run_command)\n@@ -136,7 +143,15 @@ class InteractiveSession:\n volumes[get_docker_path(key)] = dependency_local_path\n \n name = self._get_container_name()\n- command = ['docker run', '-it', f'--name {name}', f'-w {os.path.sep}{self._session_uuid}']\n+ # Start a container as a non-root user. Root (id = 0) is the default user within a container.\n+ # When passing a numeric ID, the user does not have to exist in the container.\n+ command = [\n+ 'docker run',\n+ '-it',\n+ f'--name {name}',\n+ f'-w {os.path.sep}{self._session_uuid}',\n+ '-u 1',\n+ ]\n command.extend(\n [\n # Example: -v local_path/some_folder:/0x707e903500e54bcf9b072ac7e3f5ed36_dependencies/foo:ro\n@@ -144,6 +159,11 @@ class InteractiveSession:\n for docker_path, local_path in volumes.items()\n ]\n )\n+ command.append(\n+ '-v {}:{}:rw'.format(\n+ self._host_bash_history_path, InteractiveSession._BASH_HISTORY_CONTAINER_PATH\n+ )\n+ )\n command.append(self._docker_image)\n command.append('bash')\n return ' '.join(command)\n@@ -154,7 +174,7 @@ class InteractiveSession:\n \n self._container.stop()\n self._container.remove()\n- shutil.rmtree(self._bundle_path, ignore_errors=True)\n+ shutil.rmtree(self._host_bundle_path, ignore_errors=True)\n if self._verbose:\n print('Done.\\n', file=self._stdout)\n \n@@ -175,10 +195,11 @@ class InteractiveSession:\n def _construct_final_command(self):\n try:\n candidate_commands = self._get_bash_history()\n- except Exception:\n+ except Exception as e:\n print(\n- 'The history of bash commands could not be retrieved at path: %s'\n- % InteractiveSession._BASH_HISTORY_CONTAINER_PATH,\n+ 'The history of bash commands could not be retrieved at path {}: {}'.format(\n+ InteractiveSession._BASH_HISTORY_CONTAINER_PATH, e\n+ ),\n file=self._stderr,\n )\n return ''\n@@ -188,7 +209,7 @@ class InteractiveSession:\n candidate_commands.insert(0, self._initial_command + '\\n')\n \n # Write out the commands to choose from and the instructions out to a file\n- path = os.path.join(self._bundle_path, 'edit_commands.txt')\n+ path = os.path.join(self._host_bundle_path, 'edit_commands.txt')\n with open(path, 'w') as f:\n for command in candidate_commands:\n f.write(command)\n@@ -210,17 +231,9 @@ class InteractiveSession:\n return final_command\n \n def _get_bash_history(self):\n- # Copies out .bash_history from the container to bundle_path\n- path = os.path.join(self._bundle_path, '.bash_history')\n- f = open(path, 'wb')\n- stream, _ = self._container.get_archive(InteractiveSession._BASH_HISTORY_CONTAINER_PATH)\n- for chunk in stream:\n- f.write(chunk)\n- f.close()\n-\n # Extract out a list of commands from .bash_history\n commands = []\n- with open(path) as f:\n+ with open(self._host_bash_history_path) as f:\n for i, line in enumerate(f):\n command = (\n line.rstrip(InteractiveSession._NULL_BYTE)\n", "test_patch": "diff --git a/tests/unit/lib/interactive_session_test.py b/tests/unit/lib/interactive_session_test.py\nindex fa5eb0fa..584e7873 100644\n--- a/tests/unit/lib/interactive_session_test.py\n+++ b/tests/unit/lib/interactive_session_test.py\n@@ -12,10 +12,11 @@ class InteractiveSessionTest(unittest.TestCase):\n session = InteractiveSession(\n 'some-docker-image', dependencies=targets, bundle_locations=bundle_locations\n )\n+ session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -u 1 -v '\n '[\\s\\S]{0,100}local\\/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n- 'some-docker-image bash'\n+ '-v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw some-docker-image bash'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n@@ -28,10 +29,11 @@ class InteractiveSessionTest(unittest.TestCase):\n session = InteractiveSession(\n 'some-docker-image', dependencies=targets, bundle_locations=bundle_locations\n )\n+ session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -u 1 -v '\n '[\\s\\S]{0,100}local\\/path1/sub/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2/sub/path2'\n- ':\\/0x[a-z0-9]{32}\\/key2:ro some-docker-image bash'\n+ ':\\/0x[a-z0-9]{32}\\/key2:ro -v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw some-docker-image bash'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n", "FAIL_TO_PASS": ["tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths"]}, {"instance_id": "codalab__codalab-worksheets-3343", "base_commit": "e900111cf4b3a86960907f3e60e258b440dda335", "gold_patch": "diff --git a/codalab/lib/interactive_session.py b/codalab/lib/interactive_session.py\nindex 9ee96254..73b252be 100644\n--- a/codalab/lib/interactive_session.py\n+++ b/codalab/lib/interactive_session.py\n@@ -31,7 +31,7 @@ class InteractiveSession:\n 9. Stop and remove the interactive session container.\n \"\"\"\n \n- _BASH_HISTORY_CONTAINER_PATH = \"/usr/sbin/.bash_history\"\n+ _BASH_HISTORY_CONTAINER_PATH = \"/root/.bash_history\"\n _CHOOSE_COMMAND_INSTRUCTIONS = (\n \"\\n\\n#\\n\"\n \"# Choose the commands to use for cl run:\\n\"\n@@ -143,14 +143,14 @@ class InteractiveSession:\n volumes[get_docker_path(key)] = dependency_local_path\n \n name = self._get_container_name()\n- # Start a container as a non-root user. Root (id = 0) is the default user within a container.\n- # When passing a numeric ID, the user does not have to exist in the container.\n+ # Start a container as a root user. Root (id = 0) is the default user within a container.\n command = [\n 'docker run',\n '-it',\n f'--name {name}',\n f'-w {os.path.sep}{self._session_uuid}',\n- '-u 1',\n+ # TODO: figure out a way to run as a non-root user and be able to save the bash_history on any machine\n+ # '-u 1',\n ]\n command.extend(\n [\ndiff --git a/codalab/rest/bundles.py b/codalab/rest/bundles.py\nindex 2f001e26..711463a8 100644\n--- a/codalab/rest/bundles.py\n+++ b/codalab/rest/bundles.py\n@@ -403,7 +403,7 @@ def _fetch_locations():\n bundle_uuids = query_get_list('uuids')\n bundle_link_urls = local.model.get_bundle_metadata(bundle_uuids, \"link_url\")\n uuids_to_locations = {\n- uuid: bundle_link_urls.get(\"uuid\") or local.bundle_store.get_bundle_location(uuid)\n+ uuid: bundle_link_urls.get(uuid) or local.bundle_store.get_bundle_location(uuid)\n for uuid in bundle_uuids\n }\n return dict(data=uuids_to_locations)\n", "test_patch": "diff --git a/tests/unit/lib/interactive_session_test.py b/tests/unit/lib/interactive_session_test.py\nindex 584e7873..f5c5ab6d 100644\n--- a/tests/unit/lib/interactive_session_test.py\n+++ b/tests/unit/lib/interactive_session_test.py\n@@ -14,9 +14,9 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -u 1 -v '\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n '[\\s\\S]{0,100}local\\/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n- '-v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw some-docker-image bash'\n+ '-v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n@@ -31,9 +31,9 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -u 1 -v '\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n '[\\s\\S]{0,100}local\\/path1/sub/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2/sub/path2'\n- ':\\/0x[a-z0-9]{32}\\/key2:ro -v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw some-docker-image bash'\n+ ':\\/0x[a-z0-9]{32}\\/key2:ro -v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n", "FAIL_TO_PASS": ["tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths"]}, {"instance_id": "codalab__codalab-worksheets-3393", "base_commit": "4fa4d6cd844bbb25f41813f35dc355de476b914a", "gold_patch": "diff --git a/codalab/lib/interactive_session.py b/codalab/lib/interactive_session.py\nindex 73b252be..2164e2c9 100644\n--- a/codalab/lib/interactive_session.py\n+++ b/codalab/lib/interactive_session.py\n@@ -6,6 +6,7 @@ import docker\n import os\n import shutil\n import sys\n+from typing import Dict, List\n \n \n class InteractiveSession:\n@@ -23,7 +24,7 @@ class InteractiveSession:\n 3. Mount the dependencies as read-only.\n 4. Set working directory to some arbitrary path: `/`\n 5. The user will interact with this container and try out different commands. Once satisfied the user will\n- exit the bash session. All the commands the user tried out will be stored at path `/root/.bash_history`\n+ exit the bash session. All the commands the user tried out will be stored at path `/usr/sbin/.bash_history`\n in the container.\n 6. Copy `.bash_history` out to the host machine.\n 7. Open an editor and allow the user to select and edit commands for the official run.\n@@ -31,7 +32,7 @@ class InteractiveSession:\n 9. Stop and remove the interactive session container.\n \"\"\"\n \n- _BASH_HISTORY_CONTAINER_PATH = \"/root/.bash_history\"\n+ _BASH_HISTORY_CONTAINER_PATH = \"/usr/sbin/.bash_history\"\n _CHOOSE_COMMAND_INSTRUCTIONS = (\n \"\\n\\n#\\n\"\n \"# Choose the commands to use for cl run:\\n\"\n@@ -74,15 +75,15 @@ class InteractiveSession:\n \n self._docker_client = docker.from_env(timeout=InteractiveSession._MAX_SESSION_TIMEOUT)\n self._session_uuid = generate_uuid()\n+ self._host_bundle_path: str = os.path.join(\n+ self._manager.codalab_home, 'local_bundles', self._session_uuid\n+ )\n \n self._verbose = verbose\n self._stdout = stdout\n self._stderr = stderr\n \n def start(self):\n- self._host_bundle_path = os.path.join(\n- self._manager.codalab_home, 'local_bundles', self._session_uuid\n- )\n os.makedirs(self._host_bundle_path)\n \n # Create a blank file which will be used as the bash history file that will later be\n@@ -123,7 +124,7 @@ class InteractiveSession:\n return os.path.sep + os.path.join(self._session_uuid, sub_path)\n \n # Use a dict to keep track of volumes to mount. The key is the path on Docker and the value is the local path.\n- volumes = {}\n+ volumes: Dict[str, str] = {}\n for key, bundle_target in self._dependencies:\n dependency_local_path = os.path.realpath(\n os.path.join(\n@@ -142,30 +143,34 @@ class InteractiveSession:\n else:\n volumes[get_docker_path(key)] = dependency_local_path\n \n- name = self._get_container_name()\n- # Start a container as a root user. Root (id = 0) is the default user within a container.\n- command = [\n+ name: str = self._get_container_name()\n+ container_working_directory: str = f'{os.path.sep}{self._session_uuid}'\n+\n+ # Start a container as a non-root user\n+ command: List[str] = [\n 'docker run',\n '-it',\n f'--name {name}',\n- f'-w {os.path.sep}{self._session_uuid}',\n- # TODO: figure out a way to run as a non-root user and be able to save the bash_history on any machine\n- # '-u 1',\n+ f'-w {container_working_directory}',\n+ f'-e HOME={container_working_directory}',\n+ f'-e HISTFILE={InteractiveSession._BASH_HISTORY_CONTAINER_PATH}',\n+ '-e PROMPT_COMMAND=\"history -a\"',\n+ '-u $(id -u):$(id -g)',\n ]\n command.extend(\n [\n # Example: -v local_path/some_folder:/0x707e903500e54bcf9b072ac7e3f5ed36_dependencies/foo:ro\n- '-v {}:{}:ro'.format(local_path, docker_path)\n+ f'-v {local_path}:{docker_path}:ro'\n for docker_path, local_path in volumes.items()\n ]\n )\n- command.append(\n- '-v {}:{}:rw'.format(\n- self._host_bash_history_path, InteractiveSession._BASH_HISTORY_CONTAINER_PATH\n- )\n+ command.extend(\n+ [\n+ f'-v {self._host_bash_history_path}:{InteractiveSession._BASH_HISTORY_CONTAINER_PATH}:rw',\n+ f'-v {self._host_bundle_path}:{container_working_directory}:rw',\n+ ]\n )\n command.append(self._docker_image)\n- command.append('bash')\n return ' '.join(command)\n \n def cleanup(self):\n@@ -175,6 +180,7 @@ class InteractiveSession:\n self._container.stop()\n self._container.remove()\n shutil.rmtree(self._host_bundle_path, ignore_errors=True)\n+\n if self._verbose:\n print('Done.\\n', file=self._stdout)\n \n", "test_patch": "diff --git a/tests/unit/lib/interactive_session_test.py b/tests/unit/lib/interactive_session_test.py\nindex f5c5ab6d..6fb78c06 100644\n--- a/tests/unit/lib/interactive_session_test.py\n+++ b/tests/unit/lib/interactive_session_test.py\n@@ -14,9 +14,10 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n- '[\\s\\S]{0,100}local\\/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n- '-v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} '\n+ '-e HOME=\\/0x[a-z0-9]{32} -e HISTFILE=\\/usr\\/sbin\\/\\.bash_history -e PROMPT_COMMAND=\"history -a\" -u \\$\\(id -u\\):\\$\\(id -g\\) '\n+ '-v [\\s\\S]{0,100}local\\/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n+ '-v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw -v [\\s\\S]{0,100}\\/0x[a-z0-9]{32}:\\/0x[a-z0-9]{32}:rw some-docker-image'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n@@ -31,9 +32,10 @@ class InteractiveSessionTest(unittest.TestCase):\n )\n session._host_bash_history_path = \".bash_history\"\n expected_regex = (\n- 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} -v '\n- '[\\s\\S]{0,100}local\\/path1/sub/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2/sub/path2'\n- ':\\/0x[a-z0-9]{32}\\/key2:ro -v \\.bash_history:\\/root\\/.bash_history:rw some-docker-image bash'\n+ 'docker run -it --name interactive-session-0x[a-z0-9]{32} -w \\/0x[a-z0-9]{32} '\n+ '-e HOME=\\/0x[a-z0-9]{32} -e HISTFILE=\\/usr\\/sbin\\/\\.bash_history -e PROMPT_COMMAND=\"history -a\" -u \\$\\(id -u\\):\\$\\(id -g\\) '\n+ '-v [\\s\\S]{0,100}local\\/path1/sub/path1:\\/0x[a-z0-9]{32}\\/key:ro -v [\\s\\S]{0,100}local\\/path2/sub/path2:\\/0x[a-z0-9]{32}\\/key2:ro '\n+ '-v \\.bash_history:\\/usr\\/sbin\\/\\.bash_history:rw -v [\\s\\S]{0,100}\\/0x[a-z0-9]{32}:\\/0x[a-z0-9]{32}:rw some-docker-image'\n )\n self.assertTrue(re.match(expected_regex, session.get_docker_run_command()))\n \n", "FAIL_TO_PASS": ["tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths"]}], "all_FAIL_TO_PASS": ["tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command", "tests/unit/lib/interactive_session_test.py::InteractiveSessionTest::test_get_docker_run_command_with_subpaths"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "reata__sqllineage-17_x3", "level": 3, "source": "swerebench", "repo": "reata/sqllineage", "image": "swerebench/sweb.eval.x86_64.reata_1776_sqllineage-17:latest", "base_commit": "b613ec49de0b613cfaa74b37282f410659dcbc06", "num_bugs": 3, "bugs": [{"instance_id": "reata__sqllineage-17", "base_commit": "b613ec49de0b613cfaa74b37282f410659dcbc06", "gold_patch": "diff --git a/sqllineage/core.py b/sqllineage/core.py\nindex 301c818..2f5e0b6 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -3,7 +3,7 @@ import sys\n from typing import List, Set\n \n import sqlparse\n-from sqlparse.sql import Function, Identifier, IdentifierList, Statement, TokenList\n+from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList\n from sqlparse.tokens import Keyword, Token, Whitespace\n \n SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN',\n@@ -51,11 +51,9 @@ Target Tables:\n return self._target_tables\n \n def _extract_from_token(self, token: Token):\n- if not isinstance(token, TokenList):\n- return\n source_table_token_flag = target_table_token_flag = temp_table_token_flag = False\n for sub_token in token.tokens:\n- if isinstance(token, TokenList) and not isinstance(sub_token, (Identifier, IdentifierList)):\n+ if isinstance(sub_token, TokenList):\n self._extract_from_token(sub_token)\n if sub_token.ttype in Keyword:\n if sub_token.normalized in SOURCE_TABLE_TOKENS:\n@@ -75,7 +73,13 @@ Target Tables:\n continue\n else:\n assert isinstance(sub_token, Identifier)\n- self._source_tables.add(sub_token.get_real_name())\n+ if isinstance(sub_token.token_first(), Parenthesis):\n+ # SELECT col1 FROM (SELECT col2 FROM tab1) dt, the subquery will be parsed as Identifier\n+ # and this Identifier's get_real_name method would return alias name dt\n+ # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information\n+ pass\n+ else:\n+ self._source_tables.add(sub_token.get_real_name())\n source_table_token_flag = False\n elif target_table_token_flag:\n if sub_token.ttype == Whitespace:\n", "test_patch": "diff --git a/tests/test_select.py b/tests/test_select.py\nindex cea96ef..49fe323 100644\n--- a/tests/test_select.py\n+++ b/tests/test_select.py\n@@ -40,6 +40,10 @@ def test_select_count():\n helper(\"SELECT COUNT(*) FROM tab1\", {\"tab1\"})\n \n \n+def test_select_subquery():\n+ helper(\"SELECT col1 FROM (SELECT col2 FROM tab1) dt\", {\"tab1\"})\n+\n+\n def test_select_inner_join():\n helper(\"SELECT * FROM tab1 INNER JOIN tab2\", {\"tab1\", \"tab2\"})\n \n", "FAIL_TO_PASS": ["tests/test_select.py::test_select_subquery"]}, {"instance_id": "reata__sqllineage-19", "base_commit": "2901dd193c45e4ae0aab792ac0aaa11a04a2de1b", "gold_patch": "diff --git a/sqllineage/core.py b/sqllineage/core.py\nindex 2f5e0b6..fbf17f2 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -4,7 +4,7 @@ from typing import List, Set\n \n import sqlparse\n from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList\n-from sqlparse.tokens import Keyword, Token, Whitespace\n+from sqlparse.tokens import Keyword, Token\n \n SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN',\n 'FULL OUTER JOIN', 'CROSS JOIN')\n@@ -69,7 +69,7 @@ Target Tables:\n self._target_tables.add(sub_token.get_alias())\n continue\n if source_table_token_flag:\n- if sub_token.ttype == Whitespace:\n+ if sub_token.is_whitespace:\n continue\n else:\n assert isinstance(sub_token, Identifier)\n@@ -82,7 +82,7 @@ Target Tables:\n self._source_tables.add(sub_token.get_real_name())\n source_table_token_flag = False\n elif target_table_token_flag:\n- if sub_token.ttype == Whitespace:\n+ if sub_token.is_whitespace:\n continue\n elif isinstance(sub_token, Function):\n # insert into tab (col1, col2), tab (col1, col2) will be parsed as Function\n@@ -95,7 +95,7 @@ Target Tables:\n self._target_tables.add(sub_token.get_real_name())\n target_table_token_flag = False\n elif temp_table_token_flag:\n- if sub_token.ttype == Whitespace:\n+ if sub_token.is_whitespace:\n continue\n else:\n assert isinstance(sub_token, Identifier)\n", "test_patch": "diff --git a/tests/test_select.py b/tests/test_select.py\nindex 49fe323..8837091 100644\n--- a/tests/test_select.py\n+++ b/tests/test_select.py\n@@ -5,6 +5,11 @@ def test_select():\n helper(\"SELECT col1 FROM tab1\", {\"tab1\"})\n \n \n+def test_select_multi_line():\n+ helper(\"\"\"SELECT col1 FROM\n+tab1\"\"\", {\"tab1\"})\n+\n+\n def test_select_asterisk():\n helper(\"SELECT * FROM tab1\", {\"tab1\"})\n \n", "FAIL_TO_PASS": ["tests/test_select.py::test_select_multi_line"]}, {"instance_id": "reata__sqllineage-22", "base_commit": "95cc52fb0e425a8aa68ba6f4297f4a9490583cac", "gold_patch": "diff --git a/sqllineage/core.py b/sqllineage/core.py\nindex fbf17f2..74c178d 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -4,7 +4,7 @@ from typing import List, Set\n \n import sqlparse\n from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList\n-from sqlparse.tokens import Keyword, Token\n+from sqlparse.tokens import DDL, Keyword, Token\n \n SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN',\n 'FULL OUTER JOIN', 'CROSS JOIN')\n@@ -20,7 +20,10 @@ class LineageParser(object):\n self._target_tables = set()\n self._stmt = sqlparse.parse(sql, self._encoding)\n for stmt in self._stmt:\n- self._extract_from_token(stmt)\n+ if stmt.token_first().ttype == DDL and stmt.token_first().normalized == \"DROP\":\n+ self._target_tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)}\n+ else:\n+ self._extract_from_token(stmt)\n self._tmp_tables = self._source_tables.intersection(self._target_tables)\n self._source_tables -= self._tmp_tables\n self._target_tables -= self._tmp_tables\n", "test_patch": "diff --git a/tests/test_others.py b/tests/test_others.py\nindex a6f8472..6fc57c9 100644\n--- a/tests/test_others.py\n+++ b/tests/test_others.py\n@@ -6,6 +6,26 @@ def test_use():\n helper(\"USE db1\")\n \n \n+def test_create():\n+ helper(\"CREATE TABLE tab1 (col1 STRING)\", None, {\"tab1\"})\n+\n+\n+def test_create_if_not_exist():\n+ helper(\"CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)\", None, {\"tab1\"})\n+\n+\n+def test_create_after_drop():\n+ helper(\"DROP TABLE IF EXISTS tab1; CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)\", None, {\"tab1\"})\n+\n+\n+def test_drop():\n+ helper(\"DROP TABLE IF EXISTS tab1\", None, None)\n+\n+\n+def test_drop_after_create():\n+ helper(\"CREATE TABLE IF NOT EXISTS tab1 (col1 STRING);DROP TABLE IF EXISTS tab1\", None, None)\n+\n+\n def test_create_select():\n helper(\"CREATE TABLE tab1 SELECT * FROM tab2\", {\"tab2\"}, {\"tab1\"})\n \n", "FAIL_TO_PASS": ["tests/test_others.py::test_drop", "tests/test_others.py::test_drop_after_create"]}], "all_FAIL_TO_PASS": ["tests/test_select.py::test_select_subquery", "tests/test_select.py::test_select_multi_line", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_after_create"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "macbre__sql-metadata-316_x3", "level": 3, "source": "swerebench", "repo": "macbre/sql-metadata", "image": "swerebench/sweb.eval.x86_64.macbre_1776_sql-metadata-316:latest", "base_commit": "fbf93ee1f748225cbb0bfab7d22b4d01b9e7a2d3", "num_bugs": 3, "bugs": [{"instance_id": "macbre__sql-metadata-316", "base_commit": "fbf93ee1f748225cbb0bfab7d22b4d01b9e7a2d3", "gold_patch": "diff --git a/sql_metadata/keywords_lists.py b/sql_metadata/keywords_lists.py\nindex b20e12d..3414f1c 100644\n--- a/sql_metadata/keywords_lists.py\n+++ b/sql_metadata/keywords_lists.py\n@@ -76,6 +76,7 @@ class QueryType(str, Enum):\n SELECT = \"SELECT\"\n CREATE = \"CREATE TABLE\"\n ALTER = \"ALTER TABLE\"\n+ DROP = \"DROP TABLE\"\n \n \n class TokenType(str, Enum):\n@@ -102,6 +103,7 @@ SUPPORTED_QUERY_TYPES = {\n \"WITH\": QueryType.SELECT,\n \"CREATETABLE\": QueryType.CREATE,\n \"ALTERTABLE\": QueryType.ALTER,\n+ \"DROPTABLE\": QueryType.DROP,\n }\n \n # all the keywords we care for - rest is ignored in assigning\ndiff --git a/sql_metadata/parser.py b/sql_metadata/parser.py\nindex 03f72d8..d4fd473 100644\n--- a/sql_metadata/parser.py\n+++ b/sql_metadata/parser.py\n@@ -112,7 +112,7 @@ class Parser: # pylint: disable=R0902\n )\n .position\n )\n- if tokens[index].normalized in [\"CREATE\", \"ALTER\"]:\n+ if tokens[index].normalized in [\"CREATE\", \"ALTER\", \"DROP\"]:\n switch = tokens[index].normalized + tokens[index + 1].normalized\n else:\n switch = tokens[index].normalized\n", "test_patch": "diff --git a/test/test_drop_table.py b/test/test_drop_table.py\nnew file mode 100644\nindex 0000000..8764020\n--- /dev/null\n+++ b/test/test_drop_table.py\n@@ -0,0 +1,9 @@\n+from sql_metadata import Parser\n+from sql_metadata.keywords_lists import QueryType\n+\n+\n+def test_drop_table():\n+ parser = Parser(\"DROP TABLE foo\")\n+ assert parser.query_type == QueryType.DROP\n+ assert parser.tables == [\"foo\"]\n+ assert parser.columns == []\ndiff --git a/test/test_query_type.py b/test/test_query_type.py\nindex 15f9fae..44b8f33 100644\n--- a/test/test_query_type.py\n+++ b/test/test_query_type.py\n@@ -38,6 +38,16 @@ def test_delete_query():\n assert \"DELETE\" == Parser(query.format(comment)).query_type\n \n \n+def test_drop_table_query():\n+ queries = [\n+ \"{0}DROP TABLE foo;{0}\",\n+ ]\n+\n+ for query in queries:\n+ for comment in [\"\", \"/* foo */\", \"\\n--foo\\n\", \"\\n# foo\\n\"]:\n+ assert \"DROP TABLE\" == Parser(query.format(comment)).query_type\n+\n+\n def test_unsupported_query():\n queries = [\n \"FOO BAR\",\n", "FAIL_TO_PASS": ["test/test_drop_table.py::test_drop_table", "test/test_query_type.py::test_drop_table_query"]}, {"instance_id": "macbre__sql-metadata-387", "base_commit": "e5cc1c9c9345daa6977c0c4971a1164ad1d8aa5f", "gold_patch": "diff --git a/sql_metadata/parser.py b/sql_metadata/parser.py\nindex ab0a8fc..349f044 100644\n--- a/sql_metadata/parser.py\n+++ b/sql_metadata/parser.py\n@@ -382,8 +382,12 @@ class Parser: # pylint: disable=R0902\n elif token.last_keyword_normalized == \"OFFSET\":\n # OFFSET \n offset = int(token.value)\n- elif token.previous_token.is_punctuation:\n+ elif (\n+ token.previous_token.is_punctuation\n+ and token.last_keyword_normalized == \"LIMIT\"\n+ ):\n # LIMIT ,\n+ # enter this condition only when the limit has already been parsed\n offset = limit\n limit = int(token.value)\n \n", "test_patch": "diff --git a/test/test_limit_and_offset.py b/test/test_limit_and_offset.py\nindex 024e935..1fd6aae 100644\n--- a/test/test_limit_and_offset.py\n+++ b/test/test_limit_and_offset.py\n@@ -45,3 +45,10 @@ def test_comma_separated():\n \"WHERE cl_type = 'page' AND cl_to = 'Spotify/Song' \"\n \"ORDER BY cl_sortkey LIMIT 927600,200\"\n ).limit_and_offset == (200, 927600)\n+\n+\n+def test_with_in_condition():\n+ # https://github.com/macbre/sql-metadata/issues/382\n+ assert Parser(\n+ \"SELECT count(*) FROM aa WHERE userid IN (222,333) LIMIT 50 OFFSET 1000\"\n+ ).limit_and_offset == (50, 1000)\n", "FAIL_TO_PASS": ["test/test_limit_and_offset.py::test_with_in_condition"]}, {"instance_id": "macbre__sql-metadata-388", "base_commit": "1c20ba1785c6ecff89f703eeab9e11361c368b15", "gold_patch": "diff --git a/sql_metadata/parser.py b/sql_metadata/parser.py\nindex 349f044..c422846 100644\n--- a/sql_metadata/parser.py\n+++ b/sql_metadata/parser.py\n@@ -357,6 +357,14 @@ class Parser: # pylint: disable=R0902\n )\n ):\n continue\n+\n+ # handle INSERT INTO ON DUPLICATE KEY UPDATE queries\n+ if (\n+ token.last_keyword_normalized == \"UPDATE\"\n+ and self.query_type == \"INSERT\"\n+ ):\n+ continue\n+\n table_name = str(token.value.strip(\"`\"))\n token.token_type = TokenType.TABLE\n tables.append(table_name)\n", "test_patch": "diff --git a/test/test_getting_tables.py b/test/test_getting_tables.py\nindex 76c8741..d90b0ce 100644\n--- a/test/test_getting_tables.py\n+++ b/test/test_getting_tables.py\n@@ -658,3 +658,11 @@ def test_cross_join_with_subquery():\n assert parser.subqueries == {\n \"foobar\": \"SELECT * FROM bars\",\n }\n+\n+\n+def test_insert_into_on_duplicate_key_ipdate():\n+ assert Parser(\n+ \"INSERT INTO user (id, name, age)\"\n+ \" VALUES ('user1', 'john doe', 20)\"\n+ \" ON DUPLICATE KEY UPDATE name='john doe', age=20\"\n+ ).tables == [\"user\"]\n", "FAIL_TO_PASS": ["test/test_getting_tables.py::test_insert_into_on_duplicate_key_ipdate"]}], "all_FAIL_TO_PASS": ["test/test_drop_table.py::test_drop_table", "test/test_query_type.py::test_drop_table_query", "test/test_limit_and_offset.py::test_with_in_condition", "test/test_getting_tables.py::test_insert_into_on_duplicate_key_ipdate"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-4390_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-4390:latest", "base_commit": "e7b67e0c280179188ce1bca650735978b758dca1", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-4390", "base_commit": "e7b67e0c280179188ce1bca650735978b758dca1", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex a2f118fb..5fa7d1ef 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1738,9 +1738,13 @@ class Parser(metaclass=_Parser):\n \n concurrently = self._match_text_seq(\"CONCURRENTLY\")\n if_exists = exists or self._parse_exists()\n- table = self._parse_table_parts(\n- schema=True, is_db_reference=self._prev.token_type == TokenType.SCHEMA\n- )\n+\n+ if kind == \"COLUMN\":\n+ this = self._parse_column()\n+ else:\n+ this = self._parse_table_parts(\n+ schema=True, is_db_reference=self._prev.token_type == TokenType.SCHEMA\n+ )\n \n cluster = self._parse_on_property() if self._match(TokenType.ON) else None\n \n@@ -1752,7 +1756,7 @@ class Parser(metaclass=_Parser):\n return self.expression(\n exp.Drop,\n exists=if_exists,\n- this=table,\n+ this=this,\n expressions=expressions,\n kind=self.dialect.CREATABLE_KIND_MAPPING.get(kind) or kind,\n temporary=temporary,\n", "test_patch": "diff --git a/tests/test_parser.py b/tests/test_parser.py\nindex ba1240c4..b60d7193 100644\n--- a/tests/test_parser.py\n+++ b/tests/test_parser.py\n@@ -879,3 +879,8 @@ class TestParser(unittest.TestCase):\n expr = parse_one(sql)\n self.assertIsInstance(expr, exp.Insert)\n self.assertIsInstance(expr.expression.expressions[0].expressions[0], cls)\n+\n+ def test_drop_column(self):\n+ ast = parse_one(\"ALTER TABLE tbl DROP COLUMN col\")\n+ self.assertEqual(len(list(ast.find_all(exp.Table))), 1)\n+ self.assertEqual(len(list(ast.find_all(exp.Column))), 1)\n", "FAIL_TO_PASS": ["tests/test_parser.py::TestParser::test_drop_column"]}, {"instance_id": "tobymao__sqlglot-4393", "base_commit": "37c4809dfda48224fd982ea8a48d3dbc5c17f9ae", "gold_patch": "diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 80bd7bd1..97b87908 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -106,11 +106,14 @@ def _build_date_time_add(expr_type: t.Type[E]) -> t.Callable[[t.List], E]:\n \n # https://docs.snowflake.com/en/sql-reference/functions/div0\n def _build_if_from_div0(args: t.List) -> exp.If:\n- cond = exp.EQ(this=seq_get(args, 1), expression=exp.Literal.number(0)).and_(\n- exp.Is(this=seq_get(args, 0), expression=exp.null()).not_()\n+ lhs = exp._wrap(seq_get(args, 0), exp.Binary)\n+ rhs = exp._wrap(seq_get(args, 1), exp.Binary)\n+\n+ cond = exp.EQ(this=rhs, expression=exp.Literal.number(0)).and_(\n+ exp.Is(this=lhs, expression=exp.null()).not_()\n )\n true = exp.Literal.number(0)\n- false = exp.Div(this=seq_get(args, 0), expression=seq_get(args, 1))\n+ false = exp.Div(this=lhs, expression=rhs)\n return exp.If(this=cond, true=true, false=false)\n \n \ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 7bc2f6e4..679a844e 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -6972,7 +6972,15 @@ def _combine(\n return this\n \n \n-def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:\n+@t.overload\n+def _wrap(expression: None, kind: t.Type[Expression]) -> None: ...\n+\n+\n+@t.overload\n+def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren: ...\n+\n+\n+def _wrap(expression: t.Optional[E], kind: t.Type[Expression]) -> t.Optional[E] | Paren:\n return Paren(this=expression) if isinstance(expression, kind) else expression\n \n \n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex e2db661e..515a07c4 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -605,6 +605,17 @@ WHERE\n \"duckdb\": \"CASE WHEN bar = 0 AND NOT foo IS NULL THEN 0 ELSE foo / bar END\",\n },\n )\n+ self.validate_all(\n+ \"DIV0(a - b, c - d)\",\n+ write={\n+ \"snowflake\": \"IFF((c - d) = 0 AND NOT (a - b) IS NULL, 0, (a - b) / (c - d))\",\n+ \"sqlite\": \"IIF((c - d) = 0 AND NOT (a - b) IS NULL, 0, CAST((a - b) AS REAL) / (c - d))\",\n+ \"presto\": \"IF((c - d) = 0 AND NOT (a - b) IS NULL, 0, CAST((a - b) AS DOUBLE) / (c - d))\",\n+ \"spark\": \"IF((c - d) = 0 AND NOT (a - b) IS NULL, 0, (a - b) / (c - d))\",\n+ \"hive\": \"IF((c - d) = 0 AND NOT (a - b) IS NULL, 0, (a - b) / (c - d))\",\n+ \"duckdb\": \"CASE WHEN (c - d) = 0 AND NOT (a - b) IS NULL THEN 0 ELSE (a - b) / (c - d) END\",\n+ },\n+ )\n self.validate_all(\n \"ZEROIFNULL(foo)\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-4415", "base_commit": "122ef5f41c4e29347026a81e6f6460ccf8e910ed", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 5fa7d1ef..6e7b21a6 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -5109,9 +5109,8 @@ class Parser(metaclass=_Parser):\n else:\n field = self._parse_field(any_token=True, anonymous_func=True)\n \n- if isinstance(field, exp.Func) and this:\n- # bigquery allows function calls like x.y.count(...)\n- # SAFE.SUBSTR(...)\n+ if isinstance(field, (exp.Func, exp.Window)) and this:\n+ # BQ & snowflake allow function calls like x.y.count(...), SAFE.SUBSTR(...) etc\n # https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-reference#function_call_rules\n this = exp.replace_tree(\n this,\n@@ -5135,6 +5134,11 @@ class Parser(metaclass=_Parser):\n db=this.args.get(\"table\"),\n catalog=this.args.get(\"db\"),\n )\n+ elif isinstance(field, exp.Window):\n+ # Move the exp.Dot's to the window's function\n+ window_func = self.expression(exp.Dot, this=this, expression=field.this)\n+ field.set(\"this\", window_func)\n+ this = field\n else:\n this = self.expression(exp.Dot, this=this, expression=field)\n \n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 515a07c4..157947df 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -2250,3 +2250,13 @@ SINGLE = TRUE\"\"\",\n self.validate_identity(\n \"GRANT ALL PRIVILEGES ON FUNCTION mydb.myschema.ADD5(number) TO ROLE analyst\"\n )\n+\n+ def test_window_function_arg(self):\n+ query = \"SELECT * FROM TABLE(db.schema.FUNC(a) OVER ())\"\n+\n+ ast = self.parse_one(query)\n+ window = ast.find(exp.Window)\n+\n+ self.assertEqual(ast.sql(\"snowflake\"), query)\n+ self.assertEqual(len(list(ast.find_all(exp.Column))), 1)\n+ self.assertEqual(window.this.sql(\"snowflake\"), \"db.schema.FUNC(a)\")\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_window_function_arg"]}], "all_FAIL_TO_PASS": ["tests/test_parser.py::TestParser::test_drop_column", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_snowflake.py::TestSnowflake::test_window_function_arg"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-4109_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-4109:latest", "base_commit": "b10255eb8b6b73bf5084fdf6bffd5a7fa351b1ec", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-4109", "base_commit": "b10255eb8b6b73bf5084fdf6bffd5a7fa351b1ec", "gold_patch": "diff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 746712b6..7ab3416a 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1917,8 +1917,6 @@ class Generator(metaclass=_Generator):\n direction = self.seg(\"UNPIVOT\" if expression.unpivot else \"PIVOT\")\n \n field = self.sql(expression, \"field\")\n- if field and isinstance(expression.args.get(\"field\"), exp.PivotAny):\n- field = f\"IN ({field})\"\n \n include_nulls = expression.args.get(\"include_nulls\")\n if include_nulls is not None:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 9ea81837..f22de203 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3907,13 +3907,12 @@ class Parser(metaclass=_Parser):\n self.raise_error(\"Expecting IN (\")\n \n if self._match(TokenType.ANY):\n- expr: exp.PivotAny | exp.In = self.expression(exp.PivotAny, this=self._parse_order())\n+ exprs: t.List[exp.Expression] = ensure_list(exp.PivotAny(this=self._parse_order()))\n else:\n- aliased_expressions = self._parse_csv(_parse_aliased_expression)\n- expr = self.expression(exp.In, this=value, expressions=aliased_expressions)\n+ exprs = self._parse_csv(_parse_aliased_expression)\n \n self._match_r_paren()\n- return expr\n+ return self.expression(exp.In, this=value, expressions=exprs)\n \n def _parse_pivot(self) -> t.Optional[exp.Pivot]:\n index = self._index\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex b82f9928..9c036c76 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -107,10 +107,10 @@ WHERE\n \"SELECT * FROM quarterly_sales PIVOT(SUM(amount) FOR quarter IN (SELECT DISTINCT quarter FROM ad_campaign_types_by_quarter WHERE television = TRUE ORDER BY quarter)) ORDER BY empid\"\n )\n self.validate_identity(\n- \"SELECT * FROM quarterly_sales PIVOT(SUM(amount) FOR IN (ANY ORDER BY quarter)) ORDER BY empid\"\n+ \"SELECT * FROM quarterly_sales PIVOT(SUM(amount) FOR quarter IN (ANY ORDER BY quarter)) ORDER BY empid\"\n )\n self.validate_identity(\n- \"SELECT * FROM quarterly_sales PIVOT(SUM(amount) FOR IN (ANY)) ORDER BY empid\"\n+ \"SELECT * FROM quarterly_sales PIVOT(SUM(amount) FOR quarter IN (ANY)) ORDER BY empid\"\n )\n self.validate_identity(\n \"MERGE INTO my_db AS ids USING (SELECT new_id FROM my_model WHERE NOT col IS NULL) AS new_ids ON ids.type = new_ids.type AND ids.source = new_ids.source WHEN NOT MATCHED THEN INSERT VALUES (new_ids.new_id)\"\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-4110", "base_commit": "3cb00417f45624f012e5ce8ababfe3250e813b80", "gold_patch": "diff --git a/sqlglot/dialects/databricks.py b/sqlglot/dialects/databricks.py\nindex 00f63532..0715eb7e 100644\n--- a/sqlglot/dialects/databricks.py\n+++ b/sqlglot/dialects/databricks.py\n@@ -115,3 +115,7 @@ class Databricks(Spark):\n ) -> str:\n expression.set(\"this\", True) # trigger ALWAYS in super class\n return super().generatedasidentitycolumnconstraint_sql(expression)\n+\n+ def jsonpath_sql(self, expression: exp.JSONPath) -> str:\n+ expression.set(\"escape\", None)\n+ return super().jsonpath_sql(expression)\ndiff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py\nindex 78a93593..21e52c91 100644\n--- a/sqlglot/dialects/dialect.py\n+++ b/sqlglot/dialects/dialect.py\n@@ -1595,6 +1595,8 @@ def json_extract_segments(\n if not isinstance(path, exp.JSONPath):\n return rename_func(name)(self, expression)\n \n+ escape = path.args.get(\"escape\")\n+\n segments = []\n for segment in path.expressions:\n path = self.sql(segment)\n@@ -1602,6 +1604,9 @@ def json_extract_segments(\n if isinstance(segment, exp.JSONPathPart) and (\n quoted_index or not isinstance(segment, exp.JSONPathSubscript)\n ):\n+ if escape:\n+ path = self.escape_str(path)\n+\n path = f\"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}\"\n \n segments.append(path)\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex a7bc2ca4..5355aed1 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5523,7 +5523,7 @@ class JSON(Expression):\n \n \n class JSONPath(Expression):\n- arg_types = {\"expressions\": True}\n+ arg_types = {\"expressions\": True, \"escape\": False}\n \n @property\n def output_name(self) -> str:\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 7ab3416a..26c20c80 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -2737,6 +2737,10 @@ class Generator(metaclass=_Generator):\n \n def jsonpath_sql(self, expression: exp.JSONPath) -> str:\n path = self.expressions(expression, sep=\"\", flat=True).lstrip(\".\")\n+\n+ if expression.args.get(\"escape\"):\n+ path = self.escape_str(path)\n+\n if self.QUOTE_JSON_PATH:\n path = f\"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}\"\n \ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex f22de203..5a9b9180 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4960,6 +4960,7 @@ class Parser(metaclass=_Parser):\n ) -> t.Optional[exp.Expression]:\n casts = []\n json_path = []\n+ escape = None\n \n while self._match(TokenType.COLON):\n start_index = self._index\n@@ -4986,25 +4987,25 @@ class Parser(metaclass=_Parser):\n end_token = self._prev\n \n if path:\n- path_sql = self._find_sql(self._tokens[start_index], end_token)\n-\n # Escape single quotes from Snowflake's colon extraction (e.g. col:\"a'b\") as\n # it'll roundtrip to a string literal in GET_PATH\n- if path_sql[0] == '\"':\n- quote_end = self.dialect.QUOTE_END\n- path_sql = path_sql.replace(\n- quote_end, self.dialect.tokenizer_class.STRING_ESCAPES[0] + quote_end\n- )\n+ if isinstance(path, exp.Identifier) and path.quoted:\n+ escape = True\n \n- json_path.append(path_sql)\n+ json_path.append(self._find_sql(self._tokens[start_index], end_token))\n \n # The VARIANT extract in Snowflake/Databricks is parsed as a JSONExtract; Snowflake uses the json_path in GET_PATH() while\n # Databricks transforms it back to the colon/dot notation\n if json_path:\n+ json_path_expr = self.dialect.to_json_path(exp.Literal.string(\".\".join(json_path)))\n+\n+ if json_path_expr:\n+ json_path_expr.set(\"escape\", escape)\n+\n this = self.expression(\n exp.JSONExtract,\n this=this,\n- expression=self.dialect.to_json_path(exp.Literal.string(\".\".join(json_path))),\n+ expression=json_path_expr,\n variant_extract=True,\n )\n \n", "test_patch": "diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py\nindex a46794bb..c2965e83 100644\n--- a/tests/dialects/test_databricks.py\n+++ b/tests/dialects/test_databricks.py\n@@ -142,6 +142,13 @@ class TestDatabricks(Validator):\n \"\"\"SELECT raw:`zip code`, raw:`fb:testid`, raw:store['bicycle'], raw:store[\"zip code\"]\"\"\",\n \"\"\"SELECT raw:[\"zip code\"], raw:[\"fb:testid\"], raw:store.bicycle, raw:store[\"zip code\"]\"\"\",\n )\n+ self.validate_all(\n+ \"SELECT col:`fr'uit`\",\n+ write={\n+ \"databricks\": \"\"\"SELECT col:[\"fr'uit\"]\"\"\",\n+ \"postgres\": \"SELECT JSON_EXTRACT_PATH(col, 'fr''uit')\",\n+ },\n+ )\n \n def test_datediff(self):\n self.validate_all(\ndiff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 9c036c76..40413c82 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -2143,7 +2143,7 @@ SINGLE = TRUE\"\"\",\n \"\"\",\n write={\n \"snowflake\": \"\"\"SELECT GET_PATH(col, '[\"customer\\\\'s department\"]')\"\"\",\n- \"postgres\": \"SELECT JSON_EXTRACT_PATH(col, 'customer\\\\'s department')\",\n+ \"postgres\": \"SELECT JSON_EXTRACT_PATH(col, 'customer''s department')\",\n },\n )\n \n", "FAIL_TO_PASS": ["tests/dialects/test_databricks.py::TestDatabricks::test_json", "tests/dialects/test_snowflake.py::TestSnowflake::test_querying_semi_structured_data"]}, {"instance_id": "tobymao__sqlglot-4127", "base_commit": "4506b3b58fde8e8fe711df8fd0c9c245a98ca86b", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex a47ca8eb..a2180357 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4343,6 +4343,9 @@ class Parser(metaclass=_Parser):\n )\n \n while self._match_set(self.ASSIGNMENT):\n+ if isinstance(this, exp.Column) and len(this.parts) == 1:\n+ this = this.this\n+\n this = self.expression(\n self.ASSIGNMENT[self._prev.token_type],\n this=this,\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 2887dd0f..ad503ae9 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -295,6 +295,9 @@ class TestDuckDB(Validator):\n self.validate_identity(\"SUMMARIZE tbl\").assert_is(exp.Summarize)\n self.validate_identity(\"SUMMARIZE SELECT * FROM tbl\").assert_is(exp.Summarize)\n self.validate_identity(\"CREATE TABLE tbl_summary AS SELECT * FROM (SUMMARIZE tbl)\")\n+ self.validate_identity(\"UNION_VALUE(k1 := 1)\").find(exp.PropertyEQ).this.assert_is(\n+ exp.Identifier\n+ )\n self.validate_identity(\n \"SELECT species, island, COUNT(*) FROM t GROUP BY GROUPING SETS (species), GROUPING SETS (island)\"\n )\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_databricks.py::TestDatabricks::test_json", "tests/dialects/test_snowflake.py::TestSnowflake::test_querying_semi_structured_data", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-2167_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-2167:latest", "base_commit": "da39f1416533490f75171f3e059c35bd2a84e6fb", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-2167", "base_commit": "da39f1416533490f75171f3e059c35bd2a84e6fb", "gold_patch": "diff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py\nindex a4435f66..9d4a1abe 100644\n--- a/sqlglot/dialects/spark.py\n+++ b/sqlglot/dialects/spark.py\n@@ -35,6 +35,13 @@ def _parse_datediff(args: t.List) -> exp.Expression:\n \n \n class Spark(Spark2):\n+ class Tokenizer(Spark2.Tokenizer):\n+ RAW_STRINGS = [\n+ (prefix + q, q)\n+ for q in t.cast(t.List[str], Spark2.Tokenizer.QUOTES)\n+ for prefix in (\"r\", \"R\")\n+ ]\n+\n class Parser(Spark2.Parser):\n FUNCTIONS = {\n **Spark2.Parser.FUNCTIONS,\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 0479da09..e2ee106d 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -3992,16 +3992,11 @@ class TimeUnit(Expression):\n super().__init__(**args)\n \n \n-# https://www.oracletutorial.com/oracle-basics/oracle-interval/\n-# https://trino.io/docs/current/language/types.html#interval-year-to-month\n-class IntervalYearToMonthSpan(Expression):\n- arg_types = {}\n-\n-\n # https://www.oracletutorial.com/oracle-basics/oracle-interval/\n # https://trino.io/docs/current/language/types.html#interval-day-to-second\n-class IntervalDayToSecondSpan(Expression):\n- arg_types = {}\n+# https://docs.databricks.com/en/sql/language-manual/data-types/interval-type.html\n+class IntervalSpan(Expression):\n+ arg_types = {\"this\": True, \"expression\": True}\n \n \n class Interval(TimeUnit):\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 306df812..fd2d132c 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -72,8 +72,7 @@ class Generator:\n exp.ExternalProperty: lambda self, e: \"EXTERNAL\",\n exp.HeapProperty: lambda self, e: \"HEAP\",\n exp.InlineLengthColumnConstraint: lambda self, e: f\"INLINE LENGTH {self.sql(e, 'this')}\",\n- exp.IntervalDayToSecondSpan: \"DAY TO SECOND\",\n- exp.IntervalYearToMonthSpan: \"YEAR TO MONTH\",\n+ exp.IntervalSpan: lambda self, e: f\"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}\",\n exp.LanguageProperty: lambda self, e: self.naked_property(e),\n exp.LocationProperty: lambda self, e: self.naked_property(e),\n exp.LogProperty: lambda self, e: f\"{'NO ' if e.args.get('no') else ''}LOG\",\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex f8690d5d..4e558743 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3325,15 +3325,14 @@ class Parser(metaclass=_Parser):\n elif self._match_text_seq(\"WITHOUT\", \"TIME\", \"ZONE\"):\n maybe_func = False\n elif type_token == TokenType.INTERVAL:\n- if self._match_text_seq(\"YEAR\", \"TO\", \"MONTH\"):\n- span: t.Optional[t.List[exp.Expression]] = [exp.IntervalYearToMonthSpan()]\n- elif self._match_text_seq(\"DAY\", \"TO\", \"SECOND\"):\n- span = [exp.IntervalDayToSecondSpan()]\n+ unit = self._parse_var()\n+\n+ if self._match_text_seq(\"TO\"):\n+ span = [exp.IntervalSpan(this=unit, expression=self._parse_var())]\n else:\n span = None\n \n- unit = not span and self._parse_var()\n- if not unit:\n+ if span or not unit:\n this = self.expression(\n exp.DataType, this=exp.DataType.Type.INTERVAL, expressions=span\n )\n", "test_patch": "diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py\nindex f13d0f2b..d06e0f17 100644\n--- a/tests/dialects/test_databricks.py\n+++ b/tests/dialects/test_databricks.py\n@@ -5,6 +5,12 @@ class TestDatabricks(Validator):\n dialect = \"databricks\"\n \n def test_databricks(self):\n+ self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO HOUR)\")\n+ self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO MINUTE)\")\n+ self.validate_identity(\"SELECT CAST('11 23:4:0' AS INTERVAL DAY TO SECOND)\")\n+ self.validate_identity(\"SELECT CAST('23:00:00' AS INTERVAL HOUR TO MINUTE)\")\n+ self.validate_identity(\"SELECT CAST('23:00:00' AS INTERVAL HOUR TO SECOND)\")\n+ self.validate_identity(\"SELECT CAST('23:00:00' AS INTERVAL MINUTE TO SECOND)\")\n self.validate_identity(\"CREATE TABLE target SHALLOW CLONE source\")\n self.validate_identity(\"INSERT INTO a REPLACE WHERE cond VALUES (1), (2)\")\n self.validate_identity(\"SELECT c1 : price\")\ndiff --git a/tests/dialects/test_spark.py b/tests/dialects/test_spark.py\nindex a892b0f1..becb66a1 100644\n--- a/tests/dialects/test_spark.py\n+++ b/tests/dialects/test_spark.py\n@@ -239,6 +239,14 @@ TBLPROPERTIES (\n self.validate_identity(\"TRIM(LEADING 'SL' FROM 'SSparkSQLS')\")\n self.validate_identity(\"TRIM(TRAILING 'SL' FROM 'SSparkSQLS')\")\n self.validate_identity(\"SPLIT(str, pattern, lim)\")\n+ self.validate_identity(\n+ \"SELECT REGEXP_REPLACE('100-200', r'([^0-9])', '')\",\n+ \"SELECT REGEXP_REPLACE('100-200', '([^0-9])', '')\",\n+ )\n+ self.validate_identity(\n+ \"SELECT REGEXP_REPLACE('100-200', R'([^0-9])', '')\",\n+ \"SELECT REGEXP_REPLACE('100-200', '([^0-9])', '')\",\n+ )\n self.validate_identity(\n \"SELECT STR_TO_MAP('a:1,b:2,c:3')\",\n \"SELECT STR_TO_MAP('a:1,b:2,c:3', ',', ':')\",\n", "FAIL_TO_PASS": ["tests/dialects/test_databricks.py::TestDatabricks::test_databricks", "tests/dialects/test_spark.py::TestSpark::test_spark"]}, {"instance_id": "tobymao__sqlglot-2172", "base_commit": "7e407ba24c3f77a691eb1019f33de2be9732eff8", "gold_patch": "diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex f9249eb7..a3203298 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -555,7 +555,19 @@ class MySQL(Dialect):\n exp.WeekOfYear: rename_func(\"WEEKOFYEAR\"),\n }\n \n- TYPE_MAPPING = generator.Generator.TYPE_MAPPING.copy()\n+ UNSIGNED_TYPE_MAPPING = {\n+ exp.DataType.Type.UBIGINT: \"BIGINT\",\n+ exp.DataType.Type.UINT: \"INT\",\n+ exp.DataType.Type.UMEDIUMINT: \"MEDIUMINT\",\n+ exp.DataType.Type.USMALLINT: \"SMALLINT\",\n+ exp.DataType.Type.UTINYINT: \"TINYINT\",\n+ }\n+\n+ TYPE_MAPPING = {\n+ **generator.Generator.TYPE_MAPPING,\n+ **UNSIGNED_TYPE_MAPPING,\n+ }\n+\n TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)\n TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)\n TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)\n@@ -580,6 +592,13 @@ class MySQL(Dialect):\n exp.DataType.Type.VARCHAR: \"CHAR\",\n }\n \n+ def datatype_sql(self, expression: exp.DataType) -> str:\n+ # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html\n+ result = super().datatype_sql(expression)\n+ if expression.this in self.UNSIGNED_TYPE_MAPPING:\n+ result = f\"{result} UNSIGNED\"\n+ return result\n+\n def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:\n # MySQL requires simple literal values for its LIMIT clause.\n expression = simplify_literal(expression.copy())\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 85f86aca..6a72a638 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -3543,6 +3543,7 @@ class DataType(Expression):\n UINT = auto()\n UINT128 = auto()\n UINT256 = auto()\n+ UMEDIUMINT = auto()\n UNIQUEIDENTIFIER = auto()\n UNKNOWN = auto() # Sentinel value, useful for type annotation\n USERDEFINED = \"USER-DEFINED\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex cc6909cb..09da03fb 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -137,6 +137,7 @@ class Parser(metaclass=_Parser):\n TokenType.INT256,\n TokenType.UINT256,\n TokenType.MEDIUMINT,\n+ TokenType.UMEDIUMINT,\n TokenType.FIXEDSTRING,\n TokenType.FLOAT,\n TokenType.DOUBLE,\n@@ -206,6 +207,14 @@ class Parser(metaclass=_Parser):\n *NESTED_TYPE_TOKENS,\n }\n \n+ SIGNED_TO_UNSIGNED_TYPE_TOKEN = {\n+ TokenType.BIGINT: TokenType.UBIGINT,\n+ TokenType.INT: TokenType.UINT,\n+ TokenType.MEDIUMINT: TokenType.UMEDIUMINT,\n+ TokenType.SMALLINT: TokenType.USMALLINT,\n+ TokenType.TINYINT: TokenType.UTINYINT,\n+ }\n+\n SUBQUERY_PREDICATES = {\n TokenType.ANY: exp.Any,\n TokenType.ALL: exp.All,\n@@ -3359,6 +3368,13 @@ class Parser(metaclass=_Parser):\n self._retreat(index2)\n \n if not this:\n+ if self._match_text_seq(\"UNSIGNED\"):\n+ unsigned_type_token = self.SIGNED_TO_UNSIGNED_TYPE_TOKEN.get(type_token)\n+ if not unsigned_type_token:\n+ self.raise_error(f\"Cannot convert {type_token.value} to unsigned.\")\n+\n+ type_token = unsigned_type_token or type_token\n+\n this = exp.DataType(\n this=exp.DataType.Type[type_token.value],\n expressions=expressions,\ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex 83b97d65..3ba8195e 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -86,6 +86,7 @@ class TokenType(AutoName):\n SMALLINT = auto()\n USMALLINT = auto()\n MEDIUMINT = auto()\n+ UMEDIUMINT = auto()\n INT = auto()\n UINT = auto()\n BIGINT = auto()\n", "test_patch": "diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py\nindex fc63f9f7..b062cda3 100644\n--- a/tests/dialects/test_mysql.py\n+++ b/tests/dialects/test_mysql.py\n@@ -6,6 +6,19 @@ class TestMySQL(Validator):\n dialect = \"mysql\"\n \n def test_ddl(self):\n+ int_types = {\"BIGINT\", \"INT\", \"MEDIUMINT\", \"SMALLINT\", \"TINYINT\"}\n+\n+ for t in int_types:\n+ self.validate_identity(f\"CREATE TABLE t (id {t} UNSIGNED)\")\n+ self.validate_identity(f\"CREATE TABLE t (id {t}(10) UNSIGNED)\")\n+\n+ self.validate_all(\n+ \"CREATE TABLE t (id INT UNSIGNED)\",\n+ write={\n+ \"duckdb\": \"CREATE TABLE t (id UINTEGER)\",\n+ },\n+ )\n+\n self.validate_identity(\"CREATE TABLE foo (id BIGINT)\")\n self.validate_identity(\"CREATE TABLE 00f (1d BIGINT)\")\n self.validate_identity(\"UPDATE items SET items.price = 0 WHERE items.id >= 5 LIMIT 10\")\n", "FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_ddl"]}, {"instance_id": "tobymao__sqlglot-2179", "base_commit": "93b7ba20640a880ceeb63660b796ab94579bb73a", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 6a72a638..877e9fde 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -3710,7 +3710,7 @@ class Rollback(Expression):\n \n \n class AlterTable(Expression):\n- arg_types = {\"this\": True, \"actions\": True, \"exists\": False}\n+ arg_types = {\"this\": True, \"actions\": True, \"exists\": False, \"only\": False}\n \n \n class AddConstraint(Expression):\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex fd2d132c..2f07456e 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -2289,7 +2289,8 @@ class Generator:\n actions = self.expressions(expression, key=\"actions\")\n \n exists = \" IF EXISTS\" if expression.args.get(\"exists\") else \"\"\n- return f\"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}\"\n+ only = \" ONLY\" if expression.args.get(\"only\") else \"\"\n+ return f\"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}\"\n \n def droppartition_sql(self, expression: exp.DropPartition) -> str:\n expressions = self.expressions(expression)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 09da03fb..939303f2 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4785,6 +4785,7 @@ class Parser(metaclass=_Parser):\n return self._parse_as_command(start)\n \n exists = self._parse_exists()\n+ only = self._match_text_seq(\"ONLY\")\n this = self._parse_table(schema=True)\n \n if self._next:\n@@ -4800,7 +4801,9 @@ class Parser(metaclass=_Parser):\n this=this,\n exists=exists,\n actions=actions,\n+ only=only,\n )\n+\n return self._parse_as_command(start)\n \n def _parse_merge(self) -> exp.Merge:\n", "test_patch": "diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex b93cd7f8..21196b7b 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -126,12 +126,17 @@ class TestPostgres(Validator):\n )\n \n def test_postgres(self):\n- self.validate_identity(\"x @@ y\")\n-\n expr = parse_one(\"SELECT * FROM r CROSS JOIN LATERAL UNNEST(ARRAY[1]) AS s(location)\")\n unnest = expr.args[\"joins\"][0].this.this\n unnest.assert_is(exp.Unnest)\n \n+ alter_table_only = \"\"\"ALTER TABLE ONLY \"Album\" ADD CONSTRAINT \"FK_AlbumArtistId\" FOREIGN KEY (\"ArtistId\") REFERENCES \"Artist\" (\"ArtistId\") ON DELETE NO ACTION ON UPDATE NO ACTION\"\"\"\n+ expr = parse_one(alter_table_only)\n+\n+ self.assertIsInstance(expr, exp.AlterTable)\n+ self.assertEqual(expr.sql(dialect=\"postgres\"), alter_table_only)\n+\n+ self.validate_identity(\"x @@ y\")\n self.validate_identity(\"CAST(x AS MONEY)\")\n self.validate_identity(\"CAST(x AS INT4RANGE)\")\n self.validate_identity(\"CAST(x AS INT4MULTIRANGE)\")\n", "FAIL_TO_PASS": ["tests/dialects/test_postgres.py::TestPostgres::test_postgres"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_databricks.py::TestDatabricks::test_databricks", "tests/dialects/test_spark.py::TestSpark::test_spark", "tests/dialects/test_mysql.py::TestMySQL::test_ddl", "tests/dialects/test_postgres.py::TestPostgres::test_postgres"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jackdewinter__pymarkdown-1246_x3", "level": 3, "source": "swerebench", "repo": "jackdewinter/pymarkdown", "image": "swerebench/sweb.eval.x86_64.jackdewinter_1776_pymarkdown-1246:latest", "base_commit": "911e871a488de37a5b90ebaf9e2f489e278848a3", "num_bugs": 3, "bugs": [{"instance_id": "jackdewinter__pymarkdown-1246", "base_commit": "911e871a488de37a5b90ebaf9e2f489e278848a3", "gold_patch": "diff --git a/newdocs/src/changelog.md b/newdocs/src/changelog.md\nindex 39b9359f..be928638 100644\n--- a/newdocs/src/changelog.md\n+++ b/newdocs/src/changelog.md\n@@ -5,12 +5,24 @@\n \n ### Added\n \n-- None\n+- [Issue 1233](https://github.com/jackdewinter/pymarkdown/issues/1233)\n+- [Issue 1234](https://github.com/jackdewinter/pymarkdown/issues/1234)\n+- [Issue 1235](https://github.com/jackdewinter/pymarkdown/issues/1235)\n+ - Adding more comprehensive \"drop X\" tests where multiple levels of\n+ containers are involved, and then dropping one or more of those\n+ containers in a single line.\n \n \n ### Fixed\n \n-- None\n+- [Issue 1233](https://github.com/jackdewinter/pymarkdown/issues/1233)\n+- [Issue 1234](https://github.com/jackdewinter/pymarkdown/issues/1234)\n+- [Issue 1235](https://github.com/jackdewinter/pymarkdown/issues/1235)\n+ - Adding new \"drop_x\" tests and resolve any scan issues with them.\n+- [Issue 1243](https://github.com/jackdewinter/pymarkdown/issues/1243)\n+- [Issue 1245](https://github.com/jackdewinter/pymarkdown/issues/1245)\n+ - Handling leading spaces in `__fix_spacing` function now that data\n+ is present.\n \n \n ### Changed\ndiff --git a/publish/coverage.json b/publish/coverage.json\nindex 7133420f..398dc062 100644\n--- a/publish/coverage.json\n+++ b/publish/coverage.json\n@@ -2,12 +2,12 @@\n \"projectName\": \"pymarkdown\",\n \"reportSource\": \"pytest\",\n \"branchLevel\": {\n- \"totalMeasured\": 5385,\n- \"totalCovered\": 5385\n+ \"totalMeasured\": 5393,\n+ \"totalCovered\": 5392\n },\n \"lineLevel\": {\n- \"totalMeasured\": 21081,\n- \"totalCovered\": 21081\n+ \"totalMeasured\": 21094,\n+ \"totalCovered\": 21093\n }\n }\n \ndiff --git a/pymarkdown/block_quotes/block_quote_count_helper.py b/pymarkdown/block_quotes/block_quote_count_helper.py\nindex f4e30a01..77568df7 100644\n--- a/pymarkdown/block_quotes/block_quote_count_helper.py\n+++ b/pymarkdown/block_quotes/block_quote_count_helper.py\n@@ -328,7 +328,9 @@ class BlockQuoteCountHelper:\n )\n assert parser_state.original_line_to_parse is not None\n if (\n- parser_state.original_line_to_parse[\n+ embedded_list_stack_token.indent_level\n+ >= len(parser_state.original_line_to_parse)\n+ or parser_state.original_line_to_parse[\n start_index : embedded_list_stack_token.indent_level\n ].strip()\n or parser_state.original_line_to_parse[\ndiff --git a/pymarkdown/plugins/rule_md_031.py b/pymarkdown/plugins/rule_md_031.py\nindex ceb970a7..07d958bc 100644\n--- a/pymarkdown/plugins/rule_md_031.py\n+++ b/pymarkdown/plugins/rule_md_031.py\n@@ -359,7 +359,8 @@ class RuleMd031(RulePlugin):\n removed_list_token = cast(\n ListStartMarkdownToken, self.__removed_container_stack_token\n )\n- assert removed_list_token.leading_spaces is not None\n+ if removed_list_token.leading_spaces is None:\n+ return\n split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n split_spaces_length = len(split_spaces)\n if split_spaces_length > 1:\n@@ -461,6 +462,40 @@ class RuleMd031(RulePlugin):\n else 1\n )\n \n+ def __fix_spacing_one_container(\n+ self, context: PluginScanContext, token: MarkdownToken\n+ ) -> bool:\n+ did_special_list_fix = False\n+ if self.__leading_space_index_tracker.get_container_stack_item(\n+ -1\n+ ).is_block_quote_start:\n+ self.__fix_spacing_block_quote(token)\n+ else:\n+ did_special_list_fix = self.__fix_spacing_list(context, token)\n+ return did_special_list_fix\n+\n+ def __fix_spacing_removed_container(\n+ self, context: PluginScanContext, token: MarkdownToken\n+ ) -> None:\n+ _ = token\n+ assert self.__removed_container_stack_token is not None\n+ if self.__removed_container_stack_token.is_list_start:\n+ removed_list_token = cast(\n+ ListStartMarkdownToken, self.__removed_container_stack_token\n+ )\n+ if removed_list_token.leading_spaces is not None:\n+ split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n+ split_spaces.append(\"\")\n+ else:\n+ split_spaces = [\"\"]\n+ self.register_fix_token_request(\n+ context,\n+ self.__removed_container_stack_token,\n+ \"next_token\",\n+ \"leading_spaces\",\n+ \"\\n\".join(split_spaces),\n+ )\n+\n def __fix_spacing(\n self, context: PluginScanContext, token: MarkdownToken, special_case: bool\n ) -> None:\n@@ -469,30 +504,9 @@ class RuleMd031(RulePlugin):\n self.__fix_spacing_special_case(context, token)\n return\n if self.__leading_space_index_tracker.in_at_least_one_container():\n- if self.__leading_space_index_tracker.get_container_stack_item(\n- -1\n- ).is_block_quote_start:\n- self.__fix_spacing_block_quote(token)\n- else:\n- did_special_list_fix = self.__fix_spacing_list(context, token)\n+ did_special_list_fix = self.__fix_spacing_one_container(context, token)\n elif self.__removed_container_stack_token:\n- if self.__removed_container_stack_token.is_list_start:\n- removed_list_token = cast(\n- ListStartMarkdownToken, self.__removed_container_stack_token\n- )\n- assert removed_list_token.leading_spaces is None\n- # if removed_list_token.leading_spaces is not None:\n- # split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n- # split_spaces.append(\"\")\n- # else:\n- split_spaces = [\"\"]\n- self.register_fix_token_request(\n- context,\n- self.__removed_container_stack_token,\n- \"next_token\",\n- \"leading_spaces\",\n- \"\\n\".join(split_spaces),\n- )\n+ self.__fix_spacing_removed_container(context, token)\n \n new_token = copy.deepcopy(token)\n self.__fix_count += 1\ndiff --git a/pymarkdown/transform_markdown/transform_containers.py b/pymarkdown/transform_markdown/transform_containers.py\nindex 9c95cadb..18b20bc9 100644\n--- a/pymarkdown/transform_markdown/transform_containers.py\n+++ b/pymarkdown/transform_markdown/transform_containers.py\n@@ -1435,11 +1435,15 @@ class TransformContainers:\n do_it = True\n if token_stack[-1].is_list_start and removed_tokens[-1].is_list_start:\n removed_list_token = cast(ListStartMarkdownToken, removed_tokens[-1])\n- assert removed_list_token.leading_spaces is not None\n- removed_token_split_spaces = removed_list_token.leading_spaces.split(\"\\n\")\n removed_token_index = removed_token_indices[-1]\n- assert removed_token_index < len(removed_token_split_spaces)\n- removed_token_indices[-1] += 1\n+ if removed_list_token.leading_spaces is None:\n+ assert removed_token_index == 0\n+ else:\n+ removed_token_split_spaces = removed_list_token.leading_spaces.split(\n+ \"\\n\"\n+ )\n+ assert removed_token_index < len(removed_token_split_spaces)\n+ removed_token_indices[-1] += 1\n do_it = False\n block_me = True\n if do_it:\n@@ -1858,13 +1862,14 @@ class TransformContainers:\n if token_stack[-1].is_new_list_item\n else cast(ListStartMarkdownToken, token_stack[-1])\n )\n- assert (\n- prev_list_token.leading_spaces is not None\n- ), \"Leading spaces must be defined by this point.\"\n- split_leading_spaces = prev_list_token.leading_spaces.split(\n- ParserHelper.newline_character\n- )\n- if last_container_token_index < len(split_leading_spaces):\n+ split_leading_spaces = None\n+ if prev_list_token.leading_spaces is not None:\n+ split_leading_spaces = prev_list_token.leading_spaces.split(\n+ ParserHelper.newline_character\n+ )\n+ if split_leading_spaces is not None and last_container_token_index < len(\n+ split_leading_spaces\n+ ):\n POGGER.debug(f\" -->{ParserHelper.make_value_visible(split_leading_spaces)}\")\n POGGER.debug(\n f\" primary-->container_line>:{ParserHelper.make_value_visible(container_line)}:<\"\n", "test_patch": "diff --git a/publish/test-results.json b/publish/test-results.json\nindex cffe29c8..7e2b78aa 100644\n--- a/publish/test-results.json\n+++ b/publish/test-results.json\n@@ -1367,7 +1367,7 @@\n \"totalTests\": 653,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 84,\n+ \"skippedTests\": 62,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\n@@ -1620,10 +1620,10 @@\n },\n {\n \"name\": \"test.test_markdown_extra\",\n- \"totalTests\": 203,\n+ \"totalTests\": 206,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 2,\n+ \"skippedTests\": 3,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\ndiff --git a/test/rules/test_md031.py b/test/rules/test_md031.py\nindex b99e3eef..435a4958 100644\n--- a/test/rules/test_md031.py\n+++ b/test/rules/test_md031.py\n@@ -30,6 +30,8 @@ The value for property 'plugins.md031.list_items' must be of type 'bool'.\"\"\",\n ),\n ]\n \n+skip_fix_asserts = True\n+\n scanTests = [\n pluginRuleTest(\n \"good_both_fenced_with_consistent\",\n@@ -1600,7 +1602,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"+ list\n > inner list\n > couple of lines\n@@ -2678,7 +2679,8 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> > >\n > > > > fourth block 1\n > > > > fourth block 2\n@@ -2788,7 +2790,8 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> > >\n > > > > fourth block 1\n > > > > fourth block 2\n@@ -3156,7 +3159,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3183,8 +3186,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- use_debug=True,\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3390,7 +3391,6 @@ A code block\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -3748,7 +3748,8 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"1. > >\n > > block 3\n > > block 3\n@@ -4032,7 +4033,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > +\n > list 3\n > + list 3\n@@ -4298,7 +4298,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > block 1\n > > > block 2\n@@ -4405,7 +4404,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4510,7 +4508,7 @@ A code block\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4538,7 +4536,7 @@ A code block\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4678,7 +4676,6 @@ A code block\n {temp_source_path}:7:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4735,7 +4732,6 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4796,7 +4792,6 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -5002,7 +4997,6 @@ A code block\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5264,7 +5258,6 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5600,8 +5593,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + list 1\n > > block 2\n > > block 3\n@@ -5683,7 +5674,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + list 1\n > > block 2\n > > block 3\n@@ -5860,7 +5850,6 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + list 1\n > + list 2\n > list 3\n@@ -6264,7 +6253,6 @@ another list\n {temp_source_path}:6:7: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6294,7 +6282,7 @@ another list\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6353,8 +6341,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- use_debug=True,\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6448,7 +6434,8 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6479,7 +6466,8 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6510,8 +6498,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6688,8 +6674,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6753,7 +6737,8 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6786,7 +6771,8 @@ another list\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6819,8 +6805,6 @@ another list\n {temp_source_path}:8:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -7021,8 +7005,6 @@ another list\n {temp_source_path}:6:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7144,8 +7126,6 @@ another list\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n- use_debug=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7242,7 +7222,8 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > + list 1\n > list 2\n@@ -7273,7 +7254,6 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"> + + -----\n > + list 1\n > list 2\n@@ -7578,7 +7558,7 @@ another list\n + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050a0\n \"bad_fenced_block_in_list_in_list_with_previous_inner_block_double_drop\",\n source_file_contents=\"\"\"+ + list 1\n > block 2.1\n@@ -7593,7 +7573,8 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -7798,7 +7779,6 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"+ + list 1\n + + + list 2.1\n list 2.2\n@@ -8194,7 +8174,8 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + > -----\n > > block 1\n > > block 2\n@@ -8470,7 +8451,8 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8780,7 +8762,8 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n > block 1\n > block 2\n@@ -8868,7 +8851,8 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n > block 1\n > block 2\n@@ -9131,7 +9115,7 @@ another list\n + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050b0 test_extra_050b1\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\",\n source_file_contents=\"\"\"+ + + -----\n + list 1\n@@ -9147,7 +9131,9 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_fix_debug=True,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n + list 1\n list 2\n@@ -9176,7 +9162,8 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_asserts,\n+ use_debug=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n + list 1\n list 2\ndiff --git a/test/test_markdown_extra.py b/test/test_markdown_extra.py\nindex eec32ac3..272eec4c 100644\n--- a/test/test_markdown_extra.py\n+++ b/test/test_markdown_extra.py\n@@ -9042,6 +9042,207 @@ def test_extra_049l4a():\n act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=True)\n \n \n+@pytest.mark.gfm\n+@pytest.mark.skip\n+def test_extra_050a0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_with_previous_inner_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + list 1\n+ > block 2.1\n+ > block 2.2\n+ ```block\n+ A code block\n+ ```\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:: \\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: :\\n\\n]\",\n+ \"[para(1,5):]\",\n+ \"[text(1,5):list 1:]\",\n+ \"[end-para:::True]\",\n+ \"[block-quote(2,5): : > \\n > ]\",\n+ \"[para(2,7):\\n]\",\n+ \"[text(2,7):block 2.1\\nblock 2.2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,3):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[para(7,3):]\",\n+ \"[text(7,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(8,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    • \n+
        \n+
      • list 1\n+
        \n+

        block 2.1\n+block 2.2

        \n+
        \n+
      • \n+
      \n+
      A code block\n+
      \n+another list
    • \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050b0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ + list 1\n+ list 2\n+ + list 3\n+ ```block\n+ A code block\n+ ```\n+ + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: : \\n \\n \\n]\",\n+ \"[ulist(1,5):+::6: ]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[ulist(2,7):+::8: : ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,7):8: :]\",\n+ \"[para(4,9):]\",\n+ \"[text(4,9):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,5):`:3:block:::::]\",\n+ \"[text(6,5):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[li(8,3):4: :]\",\n+ \"[para(8,5):]\",\n+ \"[text(8,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(9,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    • \n+
        \n+
      • \n+
          \n+
        • \n+
          \n+
            \n+
          • list 1\n+list 2
          • \n+
          • list 3
          • \n+
          \n+
        • \n+
        \n+
        A code block\n+
        \n+
      • \n+
      • another list
      • \n+
      \n+
    • \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050b1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ + list 1\n+ list 2\n+ + list 3\n+\n+ ```block\n+ A code block\n+ ```\n+\n+ + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: : \\n \\n \\n\\n]\",\n+ \"[ulist(1,5):+::6: ]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[ulist(2,7):+::8: : \\n]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,7):8: :]\",\n+ \"[para(4,9):]\",\n+ \"[text(4,9):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(5,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(6,5):`:3:block:::::]\",\n+ \"[text(7,5):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(9,1):]\",\n+ \"[li(10,3):4: :]\",\n+ \"[para(10,5):]\",\n+ \"[text(10,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(11,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    • \n+
        \n+
      • \n+
          \n+
        • \n+
          \n+
            \n+
          • list 1\n+list 2
          • \n+
          • list 3
          • \n+
          \n+
        • \n+
        \n+
        A code block\n+
        \n+
      • \n+
      • \n+

        another list

        \n+
      • \n+
      \n+
    • \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n @pytest.mark.gfm\n def test_extra_999():\n \"\"\"\n@@ -9100,33 +9301,52 @@ def test_extra_999():\n # bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_double_drop\n # bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\n # bad_fenced_block_in_block_quote_with_previous_inner_list_double_drop\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_block_triple_drop_with_thematics\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_block_quad_drop_with_thematics\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_list_double_drop\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_list_triple_drop\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_triple_drop\n+# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_double_drop\n+# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n \n # Assert\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_list_triple_drop\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_block_double_drop_with_thematics\n-# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop\n-# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_triple_drop\n+\n+# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_triple_drop_with_thematics\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop\n+# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop_with_thematics\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\transform_markdown\\transform_containers.py\", line 424, in __abcd\n+# assert keep_going\n+# AssertionError\n+\n+# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_triple_drop\n+# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_quad_drop\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\transform_markdown\\transform_containers.py\", line 454, in __abcd_final_list\n+# assert removed_token_indices[0] < len(split_bleading_spaces)\n+# AssertionError\n+\n+\n+# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\transform_markdown\\transform_containers.py\", line 503, in __abcd_final\n+# assert container_indices_copy[-1] == len(list_split_spaces) - 1\n+# AssertionError\n+\n+# (probably bad regen after fix)\n # bad_fenced_block_in_list_in_list_with_previous_inner_block_double_drop\n # bad_fenced_block_in_block_quote_in_list_in_list_with_previous_list_triple_drop\n-# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_double_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_block_quad_drop\n # bad_fenced_block_in_block_quote_in_list_in_list_with_previous_block_triple_drop\n-# bad_fenced_block_in_list_in_list_with_previous_inner_list_double_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_block_double_drop_with_thematics\n+# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_block_triple_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_list_double_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_list_triple_drop\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop\n+# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\tokens\\markdown_token.py\", line 599, in adjust_line_number\n+# raise BadPluginFixError(\n+# pymarkdown.plugin_manager.bad_plugin_fix_error.BadPluginFixError: Token 'fcode-block' can only be modified during the token pass in fix mode.\n+\n+# (probably bad regen after fix)\n # bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_blockx_double_drop\n # bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_list_triple_drop_and_thematics\n-# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n-# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_triple_drop_with_thematics\n-# bad_fenced_block_in_block_quote_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n-# bad_fenced_block_in_list_in_block_quote_with_previous_inner_list_double_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_list_quad_drop]\n-# bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_quad_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_quad_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_block_quad_drop\n-# bad_fenced_block_in_block_quote_in_list_with_previous_inner_list_triple_drop\n-# bad_fenced_block_in_block_quote_in_list_with_previous_inner_block_triple_drop\n-# bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_double_drop\n-# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop_with_thematics\n-# bad_fenced_block_in_block_quote_in_block_quote_in_block_quote_with_previous_block_triple_drop\n-# bad_fenced_block_in_list_with_previous_inner_block_double_drop\n+# File \"c:\\enlistments\\pymarkdown\\pymarkdown\\block_quotes\\block_quote_processor.py\", line 698, in __handle_existing_block_quote_fenced_special_part_two\n+# assert sd == \">\"\n+# AssertionError\n", "FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_with_previous_inner_block_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_list_with_previous_inner_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_with_previous_inner_list_double_drop]"]}, {"instance_id": "jackdewinter__pymarkdown-1248", "base_commit": "cee1f3f5575f73b671deb4374c6e7a263fa40df9", "gold_patch": "diff --git a/newdocs/src/changelog.md b/newdocs/src/changelog.md\nindex be928638..9acc115f 100644\n--- a/newdocs/src/changelog.md\n+++ b/newdocs/src/changelog.md\n@@ -23,6 +23,10 @@\n - [Issue 1245](https://github.com/jackdewinter/pymarkdown/issues/1245)\n - Handling leading spaces in `__fix_spacing` function now that data\n is present.\n+- [Issue 1247](https://github.com/jackdewinter/pymarkdown/issues/1247)\n+ - In 3+ drop cases with only lists and no block quotes, indent is\n+ not calculated properly on rehydrate. This in turn causes the\n+ fixed text to be wrong.\n \n \n ### Changed\ndiff --git a/publish/coverage.json b/publish/coverage.json\nindex 398dc062..11801c21 100644\n--- a/publish/coverage.json\n+++ b/publish/coverage.json\n@@ -2,12 +2,12 @@\n \"projectName\": \"pymarkdown\",\n \"reportSource\": \"pytest\",\n \"branchLevel\": {\n- \"totalMeasured\": 5393,\n- \"totalCovered\": 5392\n+ \"totalMeasured\": 5403,\n+ \"totalCovered\": 5401\n },\n \"lineLevel\": {\n- \"totalMeasured\": 21094,\n- \"totalCovered\": 21093\n+ \"totalMeasured\": 21123,\n+ \"totalCovered\": 21122\n }\n }\n \ndiff --git a/pymarkdown/plugins/rule_md_031.py b/pymarkdown/plugins/rule_md_031.py\nindex 07d958bc..c6ebf6fc 100644\n--- a/pymarkdown/plugins/rule_md_031.py\n+++ b/pymarkdown/plugins/rule_md_031.py\n@@ -56,6 +56,7 @@ class RuleMd031(RulePlugin):\n self.__removed_container_adjustments: Optional[\n List[PendingContainerAdjustment]\n ] = None\n+ self.__last_end_container_tokens: List[MarkdownToken] = []\n \n self.__leading_space_index_tracker = LeadingSpaceIndexTracker()\n \n@@ -513,17 +514,26 @@ class RuleMd031(RulePlugin):\n new_token.adjust_line_number(context, self.__fix_count)\n assert self.__last_token is not None\n if token.is_fenced_code_block and self.__last_token.is_list_end:\n+ end_container_index = len(self.__last_end_container_tokens) - 1\n+ while (\n+ end_container_index >= 0\n+ and self.__last_end_container_tokens[end_container_index].is_list_end\n+ ):\n+ end_container_index -= 1\n+ first_token = self.__last_end_container_tokens[end_container_index + 1]\n replacement_tokens: List[MarkdownToken] = [\n BlankLineMarkdownToken(\n extracted_whitespace=\"\",\n position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n column_delta=1,\n- ),\n- self.__last_token,\n- new_token,\n+ )\n ]\n+ replacement_tokens.extend(\n+ self.__last_end_container_tokens[end_container_index + 1 :]\n+ )\n+ replacement_tokens.append(new_token)\n self.register_replace_tokens_request(\n- context, self.__last_token, token, replacement_tokens\n+ context, first_token, token, replacement_tokens\n )\n elif did_special_list_fix:\n assert self.__last_token and self.__last_token.is_block_quote_end\n@@ -755,6 +765,11 @@ class RuleMd031(RulePlugin):\n ):\n self.__last_non_end_token = token\n \n+ if token.is_block_quote_end or token.is_list_end:\n+ self.__last_end_container_tokens.append(token)\n+ else:\n+ self.__last_end_container_tokens.clear()\n+\n self.__second_last_token = self.__last_token\n self.__last_token = token\n self.__removed_container_stack_token = None\ndiff --git a/pymarkdown/transform_markdown/transform_containers.py b/pymarkdown/transform_markdown/transform_containers.py\nindex 18b20bc9..f3d5eb56 100644\n--- a/pymarkdown/transform_markdown/transform_containers.py\n+++ b/pymarkdown/transform_markdown/transform_containers.py\n@@ -426,9 +426,55 @@ class TransformContainers:\n \n # pylint: enable=too-many-arguments, too-many-boolean-expressions\n \n+ @staticmethod\n+ def __abcd_final_list_second_half(\n+ removed_tokens: List[MarkdownToken],\n+ removed_token_indices: List[int],\n+ container_stack: List[MarkdownToken],\n+ possible_prefix: Optional[str],\n+ ) -> Optional[str]:\n+ container_stack_copy: List[MarkdownToken] = container_stack[:]\n+ container_stack_copy.extend(removed_tokens[::-1])\n+ is_only_list_starts_on_stack = not any(\n+ i.is_block_quote_start for i in container_stack_copy\n+ )\n+\n+ prefix = None\n+ if is_only_list_starts_on_stack and possible_prefix is not None:\n+ prefix = possible_prefix\n+ token_index = len(removed_tokens) - 1\n+ while token_index >= 0:\n+ list_token = cast(ListStartMarkdownToken, removed_tokens[token_index])\n+ assert list_token.leading_spaces is None\n+ assert removed_token_indices[token_index] == 0\n+ token_index -= 1\n+ del removed_tokens[0]\n+ del removed_token_indices[0]\n+\n+ list_token = cast(ListStartMarkdownToken, container_stack[-1])\n+ current_indent_level = list_token.indent_level if container_stack else 0\n+ prefix = \" \" * current_indent_level\n+ else:\n+ if removed_tokens[0].is_block_quote_start:\n+ removed_block_quote_token = cast(\n+ BlockQuoteMarkdownToken, removed_tokens[0]\n+ )\n+ assert removed_block_quote_token.bleading_spaces is not None\n+ split_bleading_spaces = removed_block_quote_token.bleading_spaces.split(\n+ \"\\n\"\n+ )\n+ assert removed_token_indices[0] < len(split_bleading_spaces)\n+ prefix = \"\" if possible_prefix is None else possible_prefix\n+ prefix = f\"{split_bleading_spaces[removed_token_indices[0]]}{prefix}\"\n+ del removed_tokens[0]\n+ del removed_token_indices[0]\n+ return prefix\n+\n @staticmethod\n def __abcd_final_list(\n- removed_tokens: List[MarkdownToken], removed_token_indices: List[int]\n+ removed_tokens: List[MarkdownToken],\n+ removed_token_indices: List[int],\n+ container_stack: List[MarkdownToken],\n ) -> Optional[str]:\n removed_list_token = cast(ListStartMarkdownToken, removed_tokens[0])\n assert removed_list_token.leading_spaces is not None\n@@ -437,26 +483,17 @@ class TransformContainers:\n # prefix is None for most cases\n possible_prefix = None\n if (\n- removed_token_indices[0] < len(split_leading_spaces)\n- and split_leading_spaces[removed_token_indices[0]]\n+ removed_token_indices[0]\n+ < len(split_leading_spaces)\n+ # and split_leading_spaces[removed_token_indices[0]]\n ):\n possible_prefix = split_leading_spaces[removed_token_indices[0]]\n del removed_tokens[0]\n del removed_token_indices[0]\n \n- prefix = None\n- if removed_tokens[0].is_block_quote_start:\n- removed_block_quote_token = cast(BlockQuoteMarkdownToken, removed_tokens[0])\n- assert removed_block_quote_token.bleading_spaces is not None\n- split_bleading_spaces = removed_block_quote_token.bleading_spaces.split(\n- \"\\n\"\n- )\n- assert removed_token_indices[0] < len(split_bleading_spaces)\n- prefix = \"\" if possible_prefix is None else possible_prefix\n- prefix = f\"{split_bleading_spaces[removed_token_indices[0]]}{prefix}\"\n- del removed_tokens[0]\n- del removed_token_indices[0]\n- return prefix\n+ return TransformContainers.__abcd_final_list_second_half(\n+ removed_tokens, removed_token_indices, container_stack, possible_prefix\n+ )\n \n @staticmethod\n def __abcd_final(\n@@ -506,7 +543,7 @@ class TransformContainers:\n del removed_token_indices[0]\n else:\n prefix = TransformContainers.__abcd_final_list(\n- removed_tokens, removed_token_indices\n+ removed_tokens, removed_token_indices, container_stack\n )\n return prefix\n \n", "test_patch": "diff --git a/publish/test-results.json b/publish/test-results.json\nindex 7e2b78aa..0fe7cc94 100644\n--- a/publish/test-results.json\n+++ b/publish/test-results.json\n@@ -1367,7 +1367,7 @@\n \"totalTests\": 653,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 62,\n+ \"skippedTests\": 61,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\n@@ -1620,7 +1620,7 @@\n },\n {\n \"name\": \"test.test_markdown_extra\",\n- \"totalTests\": 206,\n+ \"totalTests\": 210,\n \"failedTests\": 0,\n \"errorTests\": 0,\n \"skippedTests\": 3,\ndiff --git a/test/rules/test_md031.py b/test/rules/test_md031.py\nindex 435a4958..d1538cae 100644\n--- a/test/rules/test_md031.py\n+++ b/test/rules/test_md031.py\n@@ -30,6 +30,7 @@ The value for property 'plugins.md031.list_items' must be of type 'bool'.\"\"\",\n ),\n ]\n \n+skip_fix_bad_markdown = True\n skip_fix_asserts = True\n \n scanTests = [\n@@ -810,7 +811,7 @@ A code block\n This is a blank line and some text.\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n scan_expected_return_code=1,\n scan_expected_output=\"\"\"{temp_source_path}:3:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n {temp_source_path}:5:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n@@ -2188,7 +2189,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > > block 3\n > > > block 3\n > > > block 3\n@@ -2469,7 +2470,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + block 3\n > > block 3\n > > + block 3\n@@ -2652,7 +2653,7 @@ A code block\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > > fourth block 1\n > > > > fourth block 2\n@@ -2910,7 +2911,7 @@ A code block\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > + inner list 1\n > > > inner list 2\n@@ -2939,7 +2940,7 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > >\n > > > + inner list 1\n > > > inner list 2\n@@ -3130,7 +3131,7 @@ A code block\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n use_debug=True,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n@@ -3270,7 +3271,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3300,7 +3301,7 @@ A code block\n \"\"\",\n disable_rules=\"md032\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + --------\n > > > block 1\n > > > block 2\n@@ -3419,7 +3420,7 @@ A code block\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -3537,7 +3538,7 @@ ______\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md035\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > + ______\n > > + list 1\n > > list 2\n@@ -4245,7 +4246,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > block 1\n > > > block 2\n@@ -4350,7 +4351,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4377,7 +4378,7 @@ A code block\n {temp_source_path}:6:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + block 1\n > > block 2\n@@ -4480,7 +4481,7 @@ A code block\n \"\"\",\n disable_rules=\"md032,md027\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4822,7 +4823,7 @@ A code block\n {temp_source_path}:8:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4853,7 +4854,7 @@ A code block\n {temp_source_path}:8:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > + list 1\n > list 2\n@@ -4944,7 +4945,7 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5080,7 +5081,7 @@ A code block\n {temp_source_path}:7:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5109,7 +5110,7 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > > inner block 1\n > > > inner block 2\n@@ -5200,7 +5201,7 @@ A code block\n {temp_source_path}:7:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5229,7 +5230,7 @@ A code block\n {temp_source_path}:7:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5317,7 +5318,7 @@ A code block\n {temp_source_path}:8:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5348,7 +5349,7 @@ A code block\n {temp_source_path}:8:4: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > > ----\n > > + list 1\n > > list 2\n@@ -5647,7 +5648,7 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + list 1\n > > block 2\n > > block 3\n@@ -6312,7 +6313,7 @@ another list\n \"\"\",\n disable_rules=\"md032,md027,md007,md023\",\n use_debug=True,\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + > -----\n > > > block 1\n > > > block 2\n@@ -6643,7 +6644,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + > -----\n > > + list 1\n > > list 2\n@@ -6947,7 +6948,7 @@ another list\n {temp_source_path}:6:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -6976,7 +6977,7 @@ another list\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7064,7 +7065,7 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7095,7 +7096,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > > block 1\n > > block 2\n@@ -7347,7 +7348,7 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> + + -----\n > + list 1\n > list 2\n@@ -7657,7 +7658,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -7688,7 +7689,7 @@ A code block\n {temp_source_path}:7:1: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + list 1\n > block 2.1\n > block 2.2\n@@ -8293,7 +8294,7 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > > block 1\n > > block 2\n@@ -8420,7 +8421,7 @@ another list\n {temp_source_path}:7:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8546,7 +8547,7 @@ another list\n {temp_source_path}:8:5: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8579,7 +8580,7 @@ another list\n {temp_source_path}:8:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n+ mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"+ + > -----\n > + list 1\n > list 2\n@@ -8776,7 +8777,7 @@ another list\n another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050c2 test_extra_050c3\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\",\n source_file_contents=\"\"\"+ + + -----\n > block 1\n@@ -8866,7 +8867,7 @@ another list\n + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050c0 test_extra_050c1\n \"bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\",\n source_file_contents=\"\"\"+ + + -----\n > block 1\n@@ -8883,7 +8884,6 @@ another list\n {temp_source_path}:7:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=True,\n fix_expected_file_contents=\"\"\"+ + + -----\n > block 1\n > block 2\ndiff --git a/test/test_markdown_extra.py b/test/test_markdown_extra.py\nindex 272eec4c..191c52c5 100644\n--- a/test/test_markdown_extra.py\n+++ b/test/test_markdown_extra.py\n@@ -9243,6 +9243,279 @@ list 2\n act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n \n \n+@pytest.mark.gfm\n+def test_extra_050c0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+ -----\n+ ```block\n+ A code block\n+ ```\n+ -----\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:: \\n \\n \\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[tbreak(4,3):-::-----]\",\n+ \"[fcode-block(5,3):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(8,3):-::-----]\",\n+ \"[para(9,3):]\",\n+ \"[text(9,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(10,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    • \n+
        \n+
      • \n+
          \n+
        • \n+
          \n+
          \n+

          block 1\n+block 2

          \n+
          \n+
        • \n+
        \n+
      • \n+
      \n+
      \n+
      A code block\n+
      \n+
      \n+another list
    • \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+ -----\n+\n+ ```block\n+ A code block\n+ ```\n+\n+ -----\n+ another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2::\\n \\n \\n \\n\\n \\n \\n]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[tbreak(4,3):-::-----]\",\n+ \"[BLANK(5,1):]\",\n+ \"[fcode-block(6,3):`:3:block:::::]\",\n+ \"[text(7,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(9,1):]\",\n+ \"[tbreak(10,3):-::-----]\",\n+ \"[para(11,3):]\",\n+ \"[text(11,3):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(12,1):]\",\n+ \"[end-ulist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    • \n+
        \n+
      • \n+
          \n+
        • \n+
          \n+
          \n+

          block 1\n+block 2

          \n+
          \n+
        • \n+
        \n+
      • \n+
      \n+
      \n+
      A code block\n+
      \n+
      \n+

      another list

      \n+
    • \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c2():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+```block\n+A code block\n+```\n+-----\n+another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,1):`:3:block:::::]\",\n+ \"[text(5,1):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,1):-::-----]\",\n+ \"[para(8,1):]\",\n+ \"[text(8,1):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(9,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    • \n+
        \n+
      • \n+
          \n+
        • \n+
          \n+
          \n+

          block 1\n+block 2

          \n+
          \n+
        • \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
    A code block\n+
    \n+
    \n+

    another list

    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050c3():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_list_with_previous_block_quad_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"+ + + -----\n+ > block 1\n+ > block 2\n+\n+```block\n+A code block\n+```\n+\n+-----\n+another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[ulist(1,1):+::2:]\",\n+ \"[ulist(1,3):+::4: ]\",\n+ \"[ulist(1,5):+::6: :\\n\\n]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7): : > \\n > \\n]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(4,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,1):`:3:block:::::]\",\n+ \"[text(6,1):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,1):]\",\n+ \"[tbreak(9,1):-::-----]\",\n+ \"[para(10,1):]\",\n+ \"[text(10,1):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(11,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    • \n+
        \n+
      • \n+
          \n+
        • \n+
          \n+
          \n+

          block 1\n+block 2

          \n+
          \n+
        • \n+
        \n+
      • \n+
      \n+
    • \n+
    \n+
    A code block\n+
    \n+
    \n+

    another list

    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n @pytest.mark.gfm\n def test_extra_999():\n \"\"\"\n@@ -9270,9 +9543,9 @@ def test_extra_999():\n \n \n # Fix\n+# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n \n # Bad fix\n-# bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n", "FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics]", "test/test_markdown_extra.py::test_extra_050c0", "test/test_markdown_extra.py::test_extra_050c1"]}, {"instance_id": "jackdewinter__pymarkdown-1251", "base_commit": "50a1e9487d32589015ec920edc987d5d3ba911f8", "gold_patch": "diff --git a/newdocs/src/changelog.md b/newdocs/src/changelog.md\nindex 9acc115f..a2a05616 100644\n--- a/newdocs/src/changelog.md\n+++ b/newdocs/src/changelog.md\n@@ -27,6 +27,9 @@\n - In 3+ drop cases with only lists and no block quotes, indent is\n not calculated properly on rehydrate. This in turn causes the\n fixed text to be wrong.\n+- [Issue 1250](https://github.com/jackdewinter/pymarkdown/issues/1250)\n+ - Batch of fixes for cases when Md031 is trying to properly space\n+ a fenced code block after dropping 2 containers.\n \n \n ### Changed\ndiff --git a/publish/coverage.json b/publish/coverage.json\nindex 11801c21..ef9a15f3 100644\n--- a/publish/coverage.json\n+++ b/publish/coverage.json\n@@ -2,12 +2,12 @@\n \"projectName\": \"pymarkdown\",\n \"reportSource\": \"pytest\",\n \"branchLevel\": {\n- \"totalMeasured\": 5403,\n- \"totalCovered\": 5401\n+ \"totalMeasured\": 5431,\n+ \"totalCovered\": 5428\n },\n \"lineLevel\": {\n- \"totalMeasured\": 21123,\n- \"totalCovered\": 21122\n+ \"totalMeasured\": 21194,\n+ \"totalCovered\": 21193\n }\n }\n \ndiff --git a/pymarkdown/plugins/rule_md_031.py b/pymarkdown/plugins/rule_md_031.py\nindex c6ebf6fc..715cf2ef 100644\n--- a/pymarkdown/plugins/rule_md_031.py\n+++ b/pymarkdown/plugins/rule_md_031.py\n@@ -35,6 +35,7 @@ class PendingContainerAdjustment:\n insert_index: int\n leading_space_to_insert: str\n do_insert: bool = True\n+ do_special: bool = False\n \n \n # pylint: disable=too-many-instance-attributes\n@@ -53,6 +54,9 @@ class RuleMd031(RulePlugin):\n self.__container_adjustments: List[List[PendingContainerAdjustment]] = []\n self.__fix_count = 0\n self.__removed_container_stack_token: Optional[MarkdownToken] = None\n+ self.__x1: List[MarkdownToken] = []\n+ self.__x2: List[List[PendingContainerAdjustment]] = []\n+ self.__x3: List[int] = []\n self.__removed_container_adjustments: Optional[\n List[PendingContainerAdjustment]\n ] = None\n@@ -103,6 +107,9 @@ class RuleMd031(RulePlugin):\n self.__leading_space_index_tracker.clear()\n self.__removed_container_adjustments = None\n self.__removed_container_stack_token = None\n+ self.__x1.clear()\n+ self.__x2.clear()\n+ self.__x3.clear()\n \n def __fix_spacing_special_case(\n self, context: PluginScanContext, token: MarkdownToken\n@@ -123,6 +130,7 @@ class RuleMd031(RulePlugin):\n self.register_replace_tokens_request(\n context, self.__last_token, token, replacement_tokens\n )\n+\n end_token = cast(EndMarkdownToken, self.__last_token)\n block_quote_start_token = cast(\n BlockQuoteMarkdownToken, end_token.start_markdown_token\n@@ -137,7 +145,9 @@ class RuleMd031(RulePlugin):\n )\n )\n \n- def __fix_spacing_block_quote(self, token: MarkdownToken) -> None:\n+ def __fix_spacing_block_quote(\n+ self, token: MarkdownToken, upgrade_kludge: bool\n+ ) -> None:\n leading_space_insert_index = self.__leading_space_index_tracker.get_tokens_block_quote_bleading_space_index(\n token\n )\n@@ -153,12 +163,23 @@ class RuleMd031(RulePlugin):\n )\n assert block_quote_token.bleading_spaces is not None\n split_leading_space = block_quote_token.bleading_spaces.split(\"\\n\")\n- former_item_leading_space = split_leading_space[\n- leading_space_insert_index\n- ].rstrip()\n+\n+ former_item_leading_space = split_leading_space[leading_space_insert_index]\n+ if (\n+ leading_space_insert_index == len(split_leading_space) - 1\n+ and not former_item_leading_space\n+ and leading_space_insert_index\n+ ):\n+ former_item_leading_space = split_leading_space[\n+ leading_space_insert_index - 1\n+ ]\n+ if not upgrade_kludge:\n+ former_item_leading_space = former_item_leading_space.rstrip()\n self.__container_adjustments[container_index].append(\n PendingContainerAdjustment(\n- leading_space_insert_index, former_item_leading_space\n+ leading_space_insert_index,\n+ former_item_leading_space,\n+ do_special=upgrade_kludge,\n )\n )\n \n@@ -464,13 +485,13 @@ class RuleMd031(RulePlugin):\n )\n \n def __fix_spacing_one_container(\n- self, context: PluginScanContext, token: MarkdownToken\n+ self, context: PluginScanContext, token: MarkdownToken, upgrade_kludge: bool\n ) -> bool:\n did_special_list_fix = False\n if self.__leading_space_index_tracker.get_container_stack_item(\n -1\n ).is_block_quote_start:\n- self.__fix_spacing_block_quote(token)\n+ self.__fix_spacing_block_quote(token, upgrade_kludge)\n else:\n did_special_list_fix = self.__fix_spacing_list(context, token)\n return did_special_list_fix\n@@ -497,15 +518,179 @@ class RuleMd031(RulePlugin):\n \"\\n\".join(split_spaces),\n )\n \n+ def __fix_spacing_with_fenced_and_list_end(\n+ self, context: PluginScanContext, token: MarkdownToken, new_token: MarkdownToken\n+ ) -> None:\n+ end_container_index = len(self.__last_end_container_tokens) - 1\n+ while (\n+ end_container_index >= 0\n+ and self.__last_end_container_tokens[end_container_index].is_list_end\n+ ):\n+ end_container_index -= 1\n+ first_token = self.__last_end_container_tokens[end_container_index + 1]\n+ replacement_tokens: List[MarkdownToken] = [\n+ BlankLineMarkdownToken(\n+ extracted_whitespace=\"\",\n+ position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n+ column_delta=1,\n+ )\n+ ]\n+ replacement_tokens.extend(\n+ self.__last_end_container_tokens[end_container_index + 1 :]\n+ )\n+ replacement_tokens.append(new_token)\n+ self.register_replace_tokens_request(\n+ context, first_token, token, replacement_tokens\n+ )\n+\n+ def __fix_spacing_with_special_list_fix(\n+ self, context: PluginScanContext, token: MarkdownToken, new_token: MarkdownToken\n+ ) -> None:\n+ assert self.__last_token and self.__last_token.is_block_quote_end\n+ new_end_token = cast(EndMarkdownToken, copy.copy(self.__last_token))\n+ new_end_token.set_extra_end_data(None)\n+ replacement_tokens = [\n+ BlankLineMarkdownToken(\n+ extracted_whitespace=\"\",\n+ position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n+ column_delta=1,\n+ ),\n+ new_end_token,\n+ new_token,\n+ ]\n+ self.register_replace_tokens_request(\n+ context, self.__last_token, token, replacement_tokens\n+ )\n+\n+ def __fix_spacing_with_else(\n+ self, context: PluginScanContext, token: MarkdownToken, new_token: MarkdownToken\n+ ) -> None:\n+ replacement_tokens = [\n+ BlankLineMarkdownToken(\n+ extracted_whitespace=\"\",\n+ position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n+ column_delta=1,\n+ ),\n+ new_token,\n+ ]\n+ self.register_replace_tokens_request(context, token, token, replacement_tokens)\n+\n+ def __calc_kludge_one(self, at_least_one_container: bool) -> bool:\n+ is_kludge_one = False\n+ if at_least_one_container:\n+ last_stack_token = (\n+ self.__leading_space_index_tracker.get_container_stack_item(-1)\n+ )\n+ if last_stack_token.is_list_start and self.__x1[-1].is_block_quote_start:\n+ is_kludge_one = not any(i.is_block_quote_start for i in self.__x1[:-1])\n+ return is_kludge_one\n+\n+ def __calc_2(self, context: PluginScanContext, did_process_removals: bool) -> bool:\n+\n+ # This will most likely need rewriting for deeper nestings.\n+ if (\n+ not did_process_removals\n+ and len(self.__x1) == 2\n+ and self.__x1[0].is_block_quote_start\n+ and self.__x1[1].is_list_start\n+ ):\n+ did_process_removals = self.__apply_tailing_block_quote_fix(0, context)\n+ return did_process_removals\n+\n+ def __calc_3(\n+ self,\n+ context: PluginScanContext,\n+ did_process_removals: bool,\n+ at_least_one_container: bool,\n+ upgrade_kludge: bool,\n+ ) -> Tuple[bool, bool]:\n+ # This will most likely need rewriting for deeper nestings.\n+ if not did_process_removals and at_least_one_container:\n+ last_stack_token_index = (\n+ self.__leading_space_index_tracker.get_container_stack_size() - 1\n+ )\n+ found_block_quote_token = None\n+ assert last_stack_token_index >= 0\n+ assert (\n+ token_at_index := self.__leading_space_index_tracker.get_container_stack_item(\n+ last_stack_token_index\n+ )\n+ ).is_block_quote_start\n+ found_block_quote_token = token_at_index\n+ # while last_stack_token_index >= 0:\n+ # if (\n+ # token_at_index := self.__leading_space_index_tracker.get_container_stack_item(\n+ # last_stack_token_index\n+ # )\n+ # ).is_block_quote_start:\n+ # found_block_quote_token = token_at_index\n+ # break\n+ # last_stack_token_index -= 1\n+ if (\n+ found_block_quote_token\n+ and len(self.__x1) == 2\n+ and self.__x1[0].is_list_start\n+ and self.__x1[1].is_block_quote_start\n+ ):\n+ did_process_removals = upgrade_kludge = (\n+ self.__apply_tailing_block_quote_fix(1, context)\n+ )\n+ return did_process_removals, upgrade_kludge\n+\n+ def __apply_tailing_block_quote_fix(\n+ self, modify_index: int, context: PluginScanContext\n+ ) -> bool:\n+\n+ assert self.__x1[modify_index].is_block_quote_start\n+ block_quote_token = cast(BlockQuoteMarkdownToken, self.__x1[modify_index])\n+ assert block_quote_token.bleading_spaces is not None\n+ split_spaces = block_quote_token.bleading_spaces.split(\"\\n\")\n+ assert self.__x3[modify_index] == len(split_spaces) - 1\n+ split_spaces[-1] = split_spaces[-1].rstrip()\n+ self.register_fix_token_request(\n+ context,\n+ self.__x1[modify_index],\n+ \"next_token\",\n+ \"bleading_spaces\",\n+ \"\\n\".join(split_spaces),\n+ )\n+ return True\n+\n def __fix_spacing(\n self, context: PluginScanContext, token: MarkdownToken, special_case: bool\n ) -> None:\n- did_special_list_fix = False\n if special_case:\n self.__fix_spacing_special_case(context, token)\n return\n- if self.__leading_space_index_tracker.in_at_least_one_container():\n- did_special_list_fix = self.__fix_spacing_one_container(context, token)\n+ at_least_one_container = (\n+ self.__leading_space_index_tracker.in_at_least_one_container()\n+ )\n+ upgrade_kludge = False\n+ if len(self.__x1) > 1:\n+ # These circumstances are already handled by the zero and single level removals.\n+ all_removals_are_block_quotes = all(\n+ f.is_block_quote_start for f in self.__x1\n+ )\n+ all_removals_are_lists = all(f.is_list_start for f in self.__x1)\n+ was_kludge_one = self.__calc_kludge_one(at_least_one_container)\n+ did_process_removals = (\n+ all_removals_are_block_quotes\n+ or all_removals_are_lists\n+ or was_kludge_one\n+ or not at_least_one_container\n+ )\n+\n+ did_process_removals = self.__calc_2(context, did_process_removals)\n+ did_process_removals, upgrade_kludge = self.__calc_3(\n+ context, did_process_removals, at_least_one_container, upgrade_kludge\n+ )\n+ # assert did_process_removals\n+\n+ did_special_list_fix = False\n+ if at_least_one_container:\n+ did_special_list_fix = self.__fix_spacing_one_container(\n+ context, token, upgrade_kludge\n+ )\n elif self.__removed_container_stack_token:\n self.__fix_spacing_removed_container(context, token)\n \n@@ -514,55 +699,11 @@ class RuleMd031(RulePlugin):\n new_token.adjust_line_number(context, self.__fix_count)\n assert self.__last_token is not None\n if token.is_fenced_code_block and self.__last_token.is_list_end:\n- end_container_index = len(self.__last_end_container_tokens) - 1\n- while (\n- end_container_index >= 0\n- and self.__last_end_container_tokens[end_container_index].is_list_end\n- ):\n- end_container_index -= 1\n- first_token = self.__last_end_container_tokens[end_container_index + 1]\n- replacement_tokens: List[MarkdownToken] = [\n- BlankLineMarkdownToken(\n- extracted_whitespace=\"\",\n- position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n- column_delta=1,\n- )\n- ]\n- replacement_tokens.extend(\n- self.__last_end_container_tokens[end_container_index + 1 :]\n- )\n- replacement_tokens.append(new_token)\n- self.register_replace_tokens_request(\n- context, first_token, token, replacement_tokens\n- )\n+ self.__fix_spacing_with_fenced_and_list_end(context, token, new_token)\n elif did_special_list_fix:\n- assert self.__last_token and self.__last_token.is_block_quote_end\n- new_end_token = cast(EndMarkdownToken, copy.copy(self.__last_token))\n- new_end_token.set_extra_end_data(None)\n- replacement_tokens = [\n- BlankLineMarkdownToken(\n- extracted_whitespace=\"\",\n- position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n- column_delta=1,\n- ),\n- new_end_token,\n- new_token,\n- ]\n- self.register_replace_tokens_request(\n- context, self.__last_token, token, replacement_tokens\n- )\n+ self.__fix_spacing_with_special_list_fix(context, token, new_token)\n else:\n- replacement_tokens = [\n- BlankLineMarkdownToken(\n- extracted_whitespace=\"\",\n- position_marker=PositionMarker(new_token.line_number - 1, 0, \"\"),\n- column_delta=1,\n- ),\n- new_token,\n- ]\n- self.register_replace_tokens_request(\n- context, token, token, replacement_tokens\n- )\n+ self.__fix_spacing_with_else(context, token, new_token)\n \n def __handle_fenced_code_block(\n self, context: PluginScanContext, token: MarkdownToken, special_case: bool\n@@ -677,7 +818,16 @@ class RuleMd031(RulePlugin):\n ), \"Pending containers means this should at least have a newline in it.\"\n split_spaces = list_token.leading_spaces.split(\"\\n\")\n \n+ for i, next_container_adjustment in enumerate(next_container_adjustment_list):\n+ if next_container_adjustment.do_special:\n+ split_spaces.insert(\n+ 0, next_container_adjustment.leading_space_to_insert\n+ )\n+ del next_container_adjustment_list[i]\n+ break\n+\n for next_container_adjustment in next_container_adjustment_list[::-1]:\n+ assert not next_container_adjustment.do_special\n if next_container_adjustment.do_insert:\n split_spaces.insert(\n next_container_adjustment.insert_index,\n@@ -706,10 +856,22 @@ class RuleMd031(RulePlugin):\n context, next_container_adjustment_list\n )\n \n+ if self.__leading_space_index_tracker.get_container_stack_item(\n+ -1\n+ ).is_block_quote_start:\n+ leading_space_insert_index = self.__leading_space_index_tracker.get_tokens_block_quote_bleading_space_index(\n+ token\n+ )\n+ else:\n+ leading_space_insert_index = -10\n+ self.__x3.append(leading_space_insert_index)\n+\n self.__removed_container_stack_token = (\n self.__leading_space_index_tracker.process_container_end(token)\n )\n+ self.__x1.append(self.__removed_container_stack_token)\n self.__removed_container_adjustments = self.__container_adjustments[-1]\n+ self.__x2.append(self.__removed_container_adjustments)\n del self.__container_adjustments[-1]\n \n def __calculate_special_case(\n@@ -773,7 +935,10 @@ class RuleMd031(RulePlugin):\n self.__second_last_token = self.__last_token\n self.__last_token = token\n self.__removed_container_stack_token = None\n+ self.__x1.clear()\n self.__removed_container_adjustments = None\n+ self.__x2.clear()\n+ self.__x3.clear()\n \n \n # pylint: enable=too-many-instance-attributes\n", "test_patch": "diff --git a/publish/test-results.json b/publish/test-results.json\nindex 0fe7cc94..979e1298 100644\n--- a/publish/test-results.json\n+++ b/publish/test-results.json\n@@ -1367,7 +1367,7 @@\n \"totalTests\": 653,\n \"failedTests\": 0,\n \"errorTests\": 0,\n- \"skippedTests\": 61,\n+ \"skippedTests\": 59,\n \"elapsedTimeInMilliseconds\": 0\n },\n {\n@@ -1620,7 +1620,7 @@\n },\n {\n \"name\": \"test.test_markdown_extra\",\n- \"totalTests\": 210,\n+ \"totalTests\": 220,\n \"failedTests\": 0,\n \"errorTests\": 0,\n \"skippedTests\": 3,\ndiff --git a/test/rules/test_md031.py b/test/rules/test_md031.py\nindex d1538cae..79045e92 100644\n--- a/test/rules/test_md031.py\n+++ b/test/rules/test_md031.py\n@@ -2174,7 +2174,7 @@ A code block\n > > ```\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050g0 test_extra_050g1\n \"bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\",\n source_file_contents=\"\"\"> > > block 3\n > > > block 3\n@@ -2189,6 +2189,7 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n+ use_fix_debug=True,\n mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"> > > block 3\n > > > block 3\n@@ -2455,7 +2456,7 @@ A code block\n > > --------\n \"\"\",\n ),\n- pluginRuleTest( # test_extra_049l0\n+ pluginRuleTest( # test_extra_049l0 test_extra_050h0 test_extra_050h1\n \"bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop\",\n source_file_contents=\"\"\"> > + block 3\n > > block 3\n@@ -2470,7 +2471,8 @@ A code block\n {temp_source_path}:6:3: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032\",\n- mark_fix_as_skipped=skip_fix_bad_markdown,\n+ # mark_fix_as_skipped=skip_fix_bad_markdown,\n+ # use_fix_debug=True,\n fix_expected_file_contents=\"\"\"> > + block 3\n > > block 3\n > > + block 3\n@@ -4465,7 +4467,7 @@ A code block\n > ----\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050e0 test_extra_050e1\n \"bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop\",\n source_file_contents=\"\"\"1. > + ----\n > > block 1\n@@ -4480,8 +4482,6 @@ A code block\n {temp_source_path}:6:6: MD031: Fenced code blocks should be surrounded by blank lines (blanks-around-fences)\n \"\"\",\n disable_rules=\"md032,md027\",\n- use_debug=True,\n- mark_fix_as_skipped=skip_fix_bad_markdown,\n fix_expected_file_contents=\"\"\"1. > + ----\n > > block 1\n > > block 2\n@@ -4689,7 +4689,7 @@ A code block\n > ----\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050f0 test_extra_050f1\n \"bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_triple_drop\",\n source_file_contents=\"\"\"1. > + ----\n > + list 1\n@@ -6932,7 +6932,7 @@ another list\n > + another list\n \"\"\",\n ),\n- pluginRuleTest(\n+ pluginRuleTest( # test_extra_050d0 test_extra_050d1\n \"bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\",\n source_file_contents=\"\"\"> + + -----\n > > block 1\ndiff --git a/test/test_markdown_extra.py b/test/test_markdown_extra.py\nindex 191c52c5..5095eb63 100644\n--- a/test/test_markdown_extra.py\n+++ b/test/test_markdown_extra.py\n@@ -9516,6 +9516,608 @@ block 2

    \n act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n \n \n+@pytest.mark.gfm\n+def test_extra_050d0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> + + -----\n+> > block 1\n+> > block 2\n+> ```block\n+> A code block\n+> ```\n+> -----\n+> + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n> \\n> \\n> ]\",\n+ \"[ulist(1,3):+::4:: \\n \\n \\n]\",\n+ \"[ulist(1,5):+::6: :\\n\\n \u00fe]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7)::> > \\n> > \\n> ]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::False]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,5):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,5):-::-----]\",\n+ \"[li(8,3):4::]\",\n+ \"[para(8,5):]\",\n+ \"[text(8,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(9,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
      A code block\n+
      \n+
      \n+
    • \n+
    • another list
    • \n+
    \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050d1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> + + -----\n+> > block 1\n+> > block 2\n+>\n+> ```block\n+> A code block\n+> ```\n+>\n+> -----\n+> + another list\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n> \\n> \\n>\\n> \\n> ]\",\n+ \"[ulist(1,3):+::4:: \\n \\n\\n \\n]\",\n+ \"[ulist(1,5):+::6: :\\n\\n\\n ]\",\n+ \"[tbreak(1,7):-::-----]\",\n+ \"[block-quote(2,7)::> > \\n> > \\n>]\",\n+ \"[para(2,9):\\n]\",\n+ \"[text(2,9):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,2):]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,5):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,2):]\",\n+ \"[tbreak(9,5):-::-----]\",\n+ \"[li(10,3):4::]\",\n+ \"[para(10,5):]\",\n+ \"[text(10,5):another list:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(11,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
      \n+
    • \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
      A code block\n+
      \n+
      \n+
    • \n+
    • \n+

      another list

      \n+
    • \n+
    \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050e0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > > block 1\n+ > > block 2\n+ > ```block\n+ > A code block\n+ > ```\n+ > ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3::\\n\\n\\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > \\n > \\n]\",\n+ \"[ulist(1,6):+::7::\\n\\n]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[block-quote(2,8)::> \\n > > \\n > ]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::False]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(4,6):`:3:block:::::]\",\n+ \"[text(5,6):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,6):-::----]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(8,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    1. \n+
      \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
      A code block\n+
      \n+
      \n+
      \n+
    2. \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=True)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050e1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > > block 1\n+ > > block 2\n+ >\n+ > ```block\n+ > A code block\n+ > ```\n+ >\n+ > ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3::\\n\\n\\n\\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > \\n > \\n >\\n > \\n]\",\n+ \"[ulist(1,6):+::7::\\n\\n\\n]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[block-quote(2,8)::> \\n > > \\n >]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):block 1\\nblock 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,5):]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[fcode-block(5,6):`:3:block:::::]\",\n+ \"[text(6,6):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,5):]\",\n+ \"[tbreak(9,6):-::----]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(10,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    1. \n+
      \n+
        \n+
      • \n+
        \n+
        \n+

        block 1\n+block 2

        \n+
        \n+
      • \n+
      \n+
      A code block\n+
      \n+
      \n+
      \n+
    2. \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050f0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_triple_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > + list 1\n+ > list 2\n+ > + list 3\n+ ```block\n+ A code block\n+ ```\n+ ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3:: \\n \\n \\n \\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > ]\",\n+ \"[ulist(1,6):+::7:]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[ulist(2,8):+::9: : ]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,8):9: :]\",\n+ \"[para(4,10):]\",\n+ \"[text(4,10):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(5,4):`:3:block:::::]\",\n+ \"[text(6,4):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(8,4):-::----]\",\n+ \"[BLANK(9,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    1. \n+
      \n+
        \n+
      • \n+
        \n+
          \n+
        • list 1\n+list 2
        • \n+
        • list 3
        • \n+
        \n+
      • \n+
      \n+
      \n+
      A code block\n+
      \n+
      \n+
    2. \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050f1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_triple_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"1. > + ----\n+ > + list 1\n+ > list 2\n+ > + list 3\n+\n+ ```block\n+ A code block\n+ ```\n+\n+ ----\n+\"\"\"\n+ expected_tokens = [\n+ \"[olist(1,1):.:1:3:: \\n \\n \\n\\n \\n]\",\n+ \"[block-quote(1,4): : > \\n > \\n > \\n > ]\",\n+ \"[ulist(1,6):+::7:]\",\n+ \"[tbreak(1,8):-::----]\",\n+ \"[ulist(2,8):+::9: : \\n]\",\n+ \"[para(2,10):\\n]\",\n+ \"[text(2,10):list 1\\nlist 2::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(4,8):9: :]\",\n+ \"[para(4,10):]\",\n+ \"[text(4,10):list 3:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(5,1):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(6,4):`:3:block:::::]\",\n+ \"[text(7,4):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(9,1):]\",\n+ \"[tbreak(10,4):-::----]\",\n+ \"[BLANK(11,1):]\",\n+ \"[end-olist:::True]\",\n+ ]\n+ expected_gfm = \"\"\"
      \n+
    1. \n+
      \n+
        \n+
      • \n+
        \n+
          \n+
        • list 1\n+list 2
        • \n+
        • list 3
        • \n+
        \n+
      • \n+
      \n+
      \n+
      A code block\n+
      \n+
      \n+
    2. \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050g0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > > block 3\n+> > > block 3\n+> > > block 3\n+> ```block\n+> A code block\n+> ```\n+> text\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n]\",\n+ \"[block-quote(1,3)::]\",\n+ \"[block-quote(1,5)::> > > \\n> > > \\n> > > \\n> ]\",\n+ \"[para(1,7):\\n\\n]\",\n+ \"[text(1,7):block 3\\nblock 3\\nblock 3::\\n\\n]\",\n+ \"[end-para:::False]\",\n+ \"[end-block-quote::> :True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(4,3):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[para(7,3):]\",\n+ \"[text(7,3):text:]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(8,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
    \n+
    \n+

    block 3\n+block 3\n+block 3

    \n+
    \n+
    \n+
    A code block\n+
    \n+

    text

    \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050g1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_double_drop_with_previous_inner_block\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > > block 3\n+> > > block 3\n+> > > block 3\n+>\n+> ```block\n+> A code block\n+> ```\n+>\n+> text\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n>\\n> \\n]\",\n+ \"[block-quote(1,3)::]\",\n+ \"[block-quote(1,5)::> > > \\n> > > \\n> > > \\n>]\",\n+ \"[para(1,7):\\n\\n]\",\n+ \"[text(1,7):block 3\\nblock 3\\nblock 3::\\n\\n]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,2):]\",\n+ \"[end-block-quote:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(5,3):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,2):]\",\n+ \"[para(9,3):]\",\n+ \"[text(9,3):text:]\",\n+ \"[end-para:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(10,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
    \n+
    \n+

    block 3\n+block 3\n+block 3

    \n+
    \n+
    \n+
    A code block\n+
    \n+

    text

    \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050h0():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > + block 3\n+> > block 3\n+> > + block 3\n+> ```block\n+> A code block\n+> ```\n+> --------\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n]\",\n+ \"[block-quote(1,3)::> > \\n> > \\n> > \\n> ]\",\n+ \"[ulist(1,5):+::6:: \\n]\",\n+ \"[para(1,7):\\n]\",\n+ \"[text(1,7):block 3\\nblock 3::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(3,5):6::]\",\n+ \"[para(3,7):]\",\n+ \"[text(3,7):block 3:]\",\n+ \"[end-para:::False]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(4,3):`:3:block:::::]\",\n+ \"[text(5,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[tbreak(7,3):-::--------]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(8,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
    \n+
      \n+
    • block 3\n+block 3
    • \n+
    • block 3
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=False)\n+\n+\n+@pytest.mark.gfm\n+def test_extra_050h1():\n+ \"\"\"\n+ TBD\n+ bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop\n+ \"\"\"\n+\n+ # Arrange\n+ source_markdown = \"\"\"> > + block 3\n+> > block 3\n+> > + block 3\n+>\n+> ```block\n+> A code block\n+> ```\n+>\n+> --------\n+\"\"\"\n+ expected_tokens = [\n+ \"[block-quote(1,1)::> \\n> \\n> \\n>\\n> \\n]\",\n+ \"[block-quote(1,3)::> > \\n> > \\n> > \\n>]\",\n+ \"[ulist(1,5):+::6:: \\n]\",\n+ \"[para(1,7):\\n]\",\n+ \"[text(1,7):block 3\\nblock 3::\\n]\",\n+ \"[end-para:::True]\",\n+ \"[li(3,5):6::]\",\n+ \"[para(3,7):]\",\n+ \"[text(3,7):block 3:]\",\n+ \"[end-para:::True]\",\n+ \"[BLANK(4,2):]\",\n+ \"[end-ulist:::True]\",\n+ \"[end-block-quote:::True]\",\n+ \"[fcode-block(5,3):`:3:block:::::]\",\n+ \"[text(6,3):A code block:]\",\n+ \"[end-fcode-block:::3:False]\",\n+ \"[BLANK(8,2):]\",\n+ \"[tbreak(9,3):-::--------]\",\n+ \"[end-block-quote:::True]\",\n+ \"[BLANK(10,1):]\",\n+ ]\n+ expected_gfm = \"\"\"
    \n+
    \n+
      \n+
    • block 3\n+block 3
    • \n+
    • block 3
    • \n+
    \n+
    \n+
    A code block\n+
    \n+
    \n+
    \"\"\"\n+\n+ # Act & Assert\n+ act_and_assert(source_markdown, expected_gfm, expected_tokens, show_debug=True)\n+\n+\n @pytest.mark.gfm\n def test_extra_999():\n \"\"\"\n@@ -9545,9 +10147,12 @@ def test_extra_999():\n # Fix\n # bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics\n \n+# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n+# test_extra_050d0 test_extra_050d1\n+# - need to work with split lines\n+\n # Bad fix\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_double_drop_and_thematics\n-# bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_double_drop_with_thematics\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_triple_drop\n # bad_fenced_block_in_list_in_list_in_block_quote_with_previous_block_triple_drop_with_thematics\n", "FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop]"]}], "all_FAIL_TO_PASS": ["test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_with_previous_inner_block_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_block_quote_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_list_with_previous_inner_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_inner_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_block_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_in_list_with_previous_list_quad_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_block_quote_with_previous_list_triple_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_list_in_list_with_previous_block_triple_drop_with_thematics]", "test/test_markdown_extra.py::test_extra_050c0", "test/test_markdown_extra.py::test_extra_050c1", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_block_quote_in_block_quote_with_previous_inner_list_double_drop]", "test/rules/test_md031.py::test_md031_fix[bad_fenced_block_in_list_in_block_quote_in_list_with_previous_block_double_drop]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3182_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3182:latest", "base_commit": "4b36b9c99475057e921b50e7056428c64700567a", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3182", "base_commit": "4b36b9c99475057e921b50e7056428c64700567a", "gold_patch": "diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py\nindex 9837025a..470fd7c3 100644\n--- a/sqlglot/dialects/duckdb.py\n+++ b/sqlglot/dialects/duckdb.py\n@@ -38,10 +38,12 @@ def _ts_or_ds_add_sql(self: DuckDB.Generator, expression: exp.TsOrDsAdd) -> str:\n return f\"CAST({this} AS {self.sql(expression.return_type)}) + {interval}\"\n \n \n-def _date_delta_sql(self: DuckDB.Generator, expression: exp.DateAdd | exp.DateSub) -> str:\n+def _date_delta_sql(\n+ self: DuckDB.Generator, expression: exp.DateAdd | exp.DateSub | exp.TimeAdd\n+) -> str:\n this = self.sql(expression, \"this\")\n unit = self.sql(expression, \"unit\").strip(\"'\") or \"DAY\"\n- op = \"+\" if isinstance(expression, exp.DateAdd) else \"-\"\n+ op = \"+\" if isinstance(expression, (exp.DateAdd, exp.TimeAdd)) else \"-\"\n return f\"{this} {op} {self.sql(exp.Interval(this=expression.expression, unit=unit))}\"\n \n \n@@ -427,6 +429,7 @@ class DuckDB(Dialect):\n \"EPOCH\", self.func(\"STRPTIME\", e.this, self.format_time(e))\n ),\n exp.Struct: _struct_sql,\n+ exp.TimeAdd: _date_delta_sql,\n exp.Timestamp: no_timestamp_sql,\n exp.TimestampDiff: lambda self, e: self.func(\n \"DATE_DIFF\", exp.Literal.string(e.unit), e.expression, e.this\ndiff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 0ffe4cf0..c13c15ab 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -78,6 +78,17 @@ def _build_datediff(args: t.List) -> exp.DateDiff:\n )\n \n \n+def _build_date_time_add(expr_type: t.Type[E]) -> t.Callable[[t.List], E]:\n+ def _builder(args: t.List) -> E:\n+ return expr_type(\n+ this=seq_get(args, 2),\n+ expression=seq_get(args, 1),\n+ unit=_map_date_part(seq_get(args, 0)),\n+ )\n+\n+ return _builder\n+\n+\n # https://docs.snowflake.com/en/sql-reference/functions/div0\n def _build_if_from_div0(args: t.List) -> exp.If:\n cond = exp.EQ(this=seq_get(args, 1), expression=exp.Literal.number(0))\n@@ -345,11 +356,7 @@ class Snowflake(Dialect):\n \"CONVERT_TIMEZONE\": _build_convert_timezone,\n \"DATE\": _build_datetime(\"DATE\", exp.DataType.Type.DATE),\n \"DATE_TRUNC\": _date_trunc_to_time,\n- \"DATEADD\": lambda args: exp.DateAdd(\n- this=seq_get(args, 2),\n- expression=seq_get(args, 1),\n- unit=_map_date_part(seq_get(args, 0)),\n- ),\n+ \"DATEADD\": _build_date_time_add(exp.DateAdd),\n \"DATEDIFF\": _build_datediff,\n \"DIV0\": _build_if_from_div0,\n \"FLATTEN\": exp.Explode.from_arg_list,\n@@ -367,7 +374,9 @@ class Snowflake(Dialect):\n \"REGEXP_SUBSTR\": exp.RegexpExtract.from_arg_list,\n \"RLIKE\": exp.RegexpLike.from_arg_list,\n \"SQUARE\": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),\n+ \"TIMEADD\": _build_date_time_add(exp.TimeAdd),\n \"TIMEDIFF\": _build_datediff,\n+ \"TIMESTAMPADD\": _build_date_time_add(exp.DateAdd),\n \"TIMESTAMPDIFF\": _build_datediff,\n \"TIMESTAMPFROMPARTS\": _build_timestamp_from_parts,\n \"TIMESTAMP_FROM_PARTS\": _build_timestamp_from_parts,\n@@ -792,6 +801,7 @@ class Snowflake(Dialect):\n ),\n exp.StrToTime: lambda self, e: self.func(\"TO_TIMESTAMP\", e.this, self.format_time(e)),\n exp.Stuff: rename_func(\"INSERT\"),\n+ exp.TimeAdd: date_delta_sql(\"TIMEADD\"),\n exp.TimestampDiff: lambda self, e: self.func(\n \"TIMESTAMPDIFF\", e.unit, e.expression, e.this\n ),\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex c24fdff2..57a1044f 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -320,19 +320,39 @@ class Expression(metaclass=_Expression):\n value.index = len(values)\n values.append(value)\n \n- def set(self, arg_key: str, value: t.Any) -> None:\n+ def set(self, arg_key: str, value: t.Any, index: t.Optional[int] = None) -> None:\n \"\"\"\n Sets arg_key to value.\n \n Args:\n arg_key: name of the expression arg.\n value: value to set the arg to.\n- \"\"\"\n- if value is None:\n+ index: if the arg is a list, this specifies what position to add the value in it.\n+ \"\"\"\n+ if index is not None:\n+ expressions = self.args.get(arg_key) or []\n+\n+ if seq_get(expressions, index) is None:\n+ return\n+ if value is None:\n+ expressions.pop(index)\n+ for v in expressions[index:]:\n+ v.index = v.index - 1\n+ return\n+\n+ if isinstance(value, list):\n+ expressions.pop(index)\n+ expressions[index:index] = value\n+ else:\n+ expressions[index] = value\n+\n+ value = expressions\n+ elif value is None:\n self.args.pop(arg_key, None)\n- else:\n- self.args[arg_key] = value\n- self._set_parent(arg_key, value)\n+ return\n+\n+ self.args[arg_key] = value\n+ self._set_parent(arg_key, value, index)\n \n def _set_parent(self, arg_key: str, value: t.Any, index: t.Optional[int] = None) -> None:\n if hasattr(value, \"parent\"):\n@@ -579,13 +599,13 @@ class Expression(metaclass=_Expression):\n new_node = None\n \n for node in (self.copy() if copy else self).dfs(prune=lambda n: n is not new_node):\n+ parent, arg_key, index = node.parent, node.arg_key, node.index\n new_node = fun(node, *args, **kwargs)\n \n- if root:\n- if new_node is not node:\n- node.replace(new_node)\n- else:\n+ if not root:\n root = new_node\n+ elif new_node is not node:\n+ parent.set(arg_key, new_node, index)\n \n assert root\n return root.assert_is(Expression)\n@@ -617,37 +637,16 @@ class Expression(metaclass=_Expression):\n \"\"\"\n parent = self.parent\n \n- if not parent:\n+ if not parent or parent is expression:\n return expression\n \n key = self.arg_key\n value = parent.args.get(key)\n- exp_is_list = type(expression) is list\n \n- if type(value) is list:\n- index = self.index\n-\n- if exp_is_list:\n- value.pop(index)\n- value[index:index] = expression\n- parent._set_parent(key, value)\n- else:\n- if expression is None:\n- value.pop(index)\n-\n- for v in value[index:]:\n- v.index = v.index - 1\n- else:\n- value[index] = expression\n- parent._set_parent(key, expression, index=index)\n- elif value is not None:\n- if expression is None:\n- parent.args.pop(key)\n- else:\n- if exp_is_list and value.parent:\n- value.parent.replace(expression)\n- else:\n- parent.set(key, expression)\n+ if type(expression) is list and isinstance(value, Expression) and value.parent:\n+ value.parent.replace(expression)\n+ else:\n+ parent.set(key, expression, self.index)\n \n if expression is not self:\n self.parent = None\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 917230b2..5cfcfea2 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -15,6 +15,17 @@ class TestDuckDB(Validator):\n \"WITH _data AS (SELECT [STRUCT(1 AS a, 2 AS b), STRUCT(2 AS a, 3 AS b)] AS col) SELECT col.b FROM _data, UNNEST(_data.col) AS col WHERE col.a = 1\",\n )\n \n+ self.validate_all(\n+ \"SELECT CAST('09:05:03' AS TIME) + INTERVAL 2 HOUR\",\n+ read={\n+ \"bigquery\": \"SELECT TIME_ADD(CAST('09:05:03' AS TIME), INTERVAL 2 HOUR)\",\n+ \"snowflake\": \"SELECT TIMEADD(HOUR, 2, TO_TIME('09:05:03'))\",\n+ },\n+ write={\n+ \"duckdb\": \"SELECT CAST('09:05:03' AS TIME) + INTERVAL '2' HOUR\",\n+ \"snowflake\": \"SELECT CAST('09:05:03' AS TIME) + INTERVAL '2 HOUR'\",\n+ },\n+ )\n self.validate_all(\n 'STRUCT_PACK(\"a b\" := 1)',\n write={\ndiff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 00e6169a..4d7d97c5 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -40,6 +40,7 @@ WHERE\n )\"\"\",\n )\n \n+ self.validate_identity(\"SELECT TIMEADD(HOUR, 2, CAST('09:05:03' AS TIME))\")\n self.validate_identity(\"SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS MAP(VARCHAR, INT))\")\n self.validate_identity(\"SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS OBJECT(a CHAR NOT NULL))\")\n self.validate_identity(\"SELECT CAST([1, 2, 3] AS ARRAY(INT))\")\n@@ -956,6 +957,9 @@ WHERE\n )\n self.validate_all(\n \"DATEADD(DAY, 5, CAST('2008-12-25' AS DATE))\",\n+ read={\n+ \"snowflake\": \"TIMESTAMPADD(DAY, 5, CAST('2008-12-25' AS DATE))\",\n+ },\n write={\n \"bigquery\": \"DATE_ADD(CAST('2008-12-25' AS DATE), INTERVAL 5 DAY)\",\n \"snowflake\": \"DATEADD(DAY, 5, CAST('2008-12-25' AS DATE))\",\ndiff --git a/tests/test_expressions.py b/tests/test_expressions.py\nindex 547f6356..54bc223c 100644\n--- a/tests/test_expressions.py\n+++ b/tests/test_expressions.py\n@@ -501,6 +501,18 @@ class TestExpressions(unittest.TestCase):\n \n self.assertEqual(expression.transform(fun).sql(), \"FUN(a)\")\n \n+ def test_transform_with_parent_mutation(self):\n+ expression = parse_one(\"SELECT COUNT(1) FROM table\")\n+\n+ def fun(node):\n+ if str(node) == \"COUNT(1)\":\n+ # node gets silently mutated here - its parent points to the filter node\n+ return exp.Filter(this=node, expression=exp.Where(this=exp.true()))\n+ return node\n+\n+ transformed = expression.transform(fun)\n+ self.assertEqual(transformed.sql(), \"SELECT COUNT(1) FILTER(WHERE TRUE) FROM table\")\n+\n def test_transform_multiple_children(self):\n expression = parse_one(\"SELECT * FROM x\")\n \n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/test_expressions.py::TestExpressions::test_transform_with_parent_mutation"]}, {"instance_id": "tobymao__sqlglot-3191", "base_commit": "66e2e497626a77540b9addd35f2edb287c7b62fe", "gold_patch": "diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py\nindex 43029f02..1fe0d5c6 100644\n--- a/sqlglot/dialects/dialect.py\n+++ b/sqlglot/dialects/dialect.py\n@@ -1019,7 +1019,7 @@ def merge_without_target_sql(self: Generator, expression: exp.Merge) -> str:\n \n \n def build_json_extract_path(\n- expr_type: t.Type[F], zero_based_indexing: bool = True\n+ expr_type: t.Type[F], zero_based_indexing: bool = True, arrow_req_json_type: bool = False\n ) -> t.Callable[[t.List], F]:\n def _builder(args: t.List) -> F:\n segments: t.List[exp.JSONPathPart] = [exp.JSONPathRoot()]\n@@ -1039,7 +1039,11 @@ def build_json_extract_path(\n \n # This is done to avoid failing in the expression validator due to the arg count\n del args[2:]\n- return expr_type(this=seq_get(args, 0), expression=exp.JSONPath(expressions=segments))\n+ return expr_type(\n+ this=seq_get(args, 0),\n+ expression=exp.JSONPath(expressions=segments),\n+ only_json_types=arrow_req_json_type,\n+ )\n \n return _builder\n \ndiff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex 2836dcc5..4ea89b21 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -408,6 +408,11 @@ class MySQL(Dialect):\n \"SPATIAL\": lambda self: self._parse_index_constraint(kind=\"SPATIAL\"),\n }\n \n+ ALTER_PARSERS = {\n+ **parser.Parser.ALTER_PARSERS,\n+ \"MODIFY\": lambda self: self._parse_alter_table_alter(),\n+ }\n+\n SCHEMA_UNNAMED_CONSTRAINTS = {\n *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,\n \"FULLTEXT\",\ndiff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py\nindex 35fc01ed..11398ed2 100644\n--- a/sqlglot/dialects/postgres.py\n+++ b/sqlglot/dialects/postgres.py\n@@ -357,6 +357,16 @@ class Postgres(Dialect):\n \n JSON_ARROWS_REQUIRE_JSON_TYPE = True\n \n+ COLUMN_OPERATORS = {\n+ **parser.Parser.COLUMN_OPERATORS,\n+ TokenType.ARROW: lambda self, this, path: build_json_extract_path(\n+ exp.JSONExtract, arrow_req_json_type=self.JSON_ARROWS_REQUIRE_JSON_TYPE\n+ )([this, path]),\n+ TokenType.DARROW: lambda self, this, path: build_json_extract_path(\n+ exp.JSONExtractScalar, arrow_req_json_type=self.JSON_ARROWS_REQUIRE_JSON_TYPE\n+ )([this, path]),\n+ }\n+\n def _parse_operator(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]:\n while True:\n if not self._match(TokenType.L_PAREN):\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 57a1044f..883ab41a 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -643,7 +643,9 @@ class Expression(metaclass=_Expression):\n key = self.arg_key\n value = parent.args.get(key)\n \n- if type(expression) is list and isinstance(value, Expression) and value.parent:\n+ if type(expression) is list and isinstance(value, Expression):\n+ # We are trying to replace an Expression with a list, so it's assumed that\n+ # the intention was to really replace the parent of this expression.\n value.parent.replace(expression)\n else:\n parent.set(key, expression, self.index)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 9102f8a7..274614af 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -5695,10 +5695,11 @@ class Parser(metaclass=_Parser):\n return self.expression(exp.AlterColumn, this=column, comment=self._parse_string())\n \n self._match_text_seq(\"SET\", \"DATA\")\n+ self._match_text_seq(\"TYPE\")\n return self.expression(\n exp.AlterColumn,\n this=column,\n- dtype=self._match_text_seq(\"TYPE\") and self._parse_types(),\n+ dtype=self._parse_types(),\n collate=self._match(TokenType.COLLATE) and self._parse_term(),\n using=self._match(TokenType.USING) and self._parse_conjunction(),\n )\n", "test_patch": "diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py\nindex e1587601..23607da6 100644\n--- a/tests/dialects/test_mysql.py\n+++ b/tests/dialects/test_mysql.py\n@@ -85,6 +85,9 @@ class TestMySQL(Validator):\n \"ALTER TABLE test_table ALTER COLUMN test_column SET DATA TYPE LONGTEXT\",\n \"ALTER TABLE test_table MODIFY COLUMN test_column LONGTEXT\",\n )\n+ self.validate_identity(\n+ \"ALTER TABLE test_table MODIFY COLUMN test_column LONGTEXT\",\n+ )\n self.validate_identity(\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC\",\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()) DEFAULT CHARACTER SET=utf8 ROW_FORMAT=DYNAMIC\",\ndiff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex e2a153f5..f1c17667 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -108,6 +108,8 @@ class TestPostgres(Validator):\n self.validate_identity(\n \"SELECT * FROM foo, LATERAL (SELECT * FROM bar WHERE bar.id = foo.bar_id) AS ss\"\n )\n+ self.validate_identity(\"SELECT ('data' -> 'en-US') AS acat FROM my_table\")\n+ self.validate_identity(\"SELECT ('data' ->> 'en-US') AS acat FROM my_table\")\n self.validate_identity(\n \"SELECT c.oid, n.nspname, c.relname \"\n \"FROM pg_catalog.pg_class AS c \"\n", "FAIL_TO_PASS": ["tests/dialects/test_postgres.py::TestPostgres::test_postgres"]}, {"instance_id": "tobymao__sqlglot-3198", "base_commit": "0dd9ba5ef57d29b6406a5d2a7e381eb6e6f56221", "gold_patch": "diff --git a/sqlglot/dataframe/sql/functions.py b/sqlglot/dataframe/sql/functions.py\nindex ca117e13..b4dd2c6d 100644\n--- a/sqlglot/dataframe/sql/functions.py\n+++ b/sqlglot/dataframe/sql/functions.py\n@@ -356,15 +356,15 @@ def coalesce(*cols: ColumnOrName) -> Column:\n \n \n def corr(col1: ColumnOrName, col2: ColumnOrName) -> Column:\n- return Column.invoke_anonymous_function(col1, \"CORR\", col2)\n+ return Column.invoke_expression_over_column(col1, expression.Corr, expression=col2)\n \n \n def covar_pop(col1: ColumnOrName, col2: ColumnOrName) -> Column:\n- return Column.invoke_anonymous_function(col1, \"COVAR_POP\", col2)\n+ return Column.invoke_expression_over_column(col1, expression.CovarPop, expression=col2)\n \n \n def covar_samp(col1: ColumnOrName, col2: ColumnOrName) -> Column:\n- return Column.invoke_anonymous_function(col1, \"COVAR_SAMP\", col2)\n+ return Column.invoke_expression_over_column(col1, expression.CovarSamp, expression=col2)\n \n \n def first(col: ColumnOrName, ignorenulls: t.Optional[bool] = None) -> Column:\ndiff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex c13c15ab..a138eb00 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -368,6 +368,9 @@ class Snowflake(Dialect):\n this=seq_get(args, 0), unit=_map_date_part(seq_get(args, 1))\n ),\n \"LISTAGG\": exp.GroupConcat.from_arg_list,\n+ \"MEDIAN\": lambda args: exp.PercentileCont(\n+ this=seq_get(args, 0), expression=exp.Literal.number(0.5)\n+ ),\n \"NULLIFZERO\": _build_if_from_nullifzero,\n \"OBJECT_CONSTRUCT\": _build_object_construct,\n \"REGEXP_REPLACE\": _build_regexp_replace,\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 883ab41a..da206544 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5745,6 +5745,10 @@ class Upper(Func):\n _sql_names = [\"UPPER\", \"UCASE\"]\n \n \n+class Corr(Binary, AggFunc):\n+ pass\n+\n+\n class Variance(AggFunc):\n _sql_names = [\"VARIANCE\", \"VARIANCE_SAMP\", \"VAR_SAMP\"]\n \n@@ -5753,6 +5757,14 @@ class VariancePop(AggFunc):\n _sql_names = [\"VARIANCE_POP\", \"VAR_POP\"]\n \n \n+class CovarSamp(Binary, AggFunc):\n+ pass\n+\n+\n+class CovarPop(Binary, AggFunc):\n+ pass\n+\n+\n class Week(Func):\n arg_types = {\"this\": True, \"mode\": False}\n \n@@ -6958,6 +6970,8 @@ def convert(value: t.Any, copy: bool = False) -> Expression:\n return null()\n if isinstance(value, numbers.Number):\n return Literal.number(value)\n+ if isinstance(value, bytes):\n+ return HexString(this=value.hex())\n if isinstance(value, datetime.datetime):\n datetime_literal = Literal.string(\n (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 4d7d97c5..495159c9 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -435,6 +435,46 @@ WHERE\n \"sqlite\": \"SELECT MIN(c1), MIN(c2) FROM test\",\n },\n )\n+ for suffix in (\n+ \"\",\n+ \" OVER ()\",\n+ ):\n+ self.validate_all(\n+ f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x){suffix}\",\n+ read={\n+ \"snowflake\": f\"SELECT MEDIAN(x){suffix}\",\n+ \"postgres\": f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x){suffix}\",\n+ },\n+ write={\n+ \"\": f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x NULLS LAST){suffix}\",\n+ \"duckdb\": f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x){suffix}\",\n+ \"postgres\": f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x){suffix}\",\n+ \"snowflake\": f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x){suffix}\",\n+ },\n+ )\n+ self.validate_all(\n+ f\"SELECT MEDIAN(x){suffix}\",\n+ write={\n+ \"\": f\"SELECT PERCENTILE_CONT(x, 0.5){suffix}\",\n+ \"duckdb\": f\"SELECT QUANTILE_CONT(x, 0.5){suffix}\",\n+ \"postgres\": f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x){suffix}\",\n+ \"snowflake\": f\"SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x){suffix}\",\n+ },\n+ )\n+ for func in (\n+ \"CORR\",\n+ \"COVAR_POP\",\n+ \"COVAR_SAMP\",\n+ ):\n+ self.validate_all(\n+ f\"SELECT {func}(y, x){suffix}\",\n+ write={\n+ \"\": f\"SELECT {func}(y, x){suffix}\",\n+ \"duckdb\": f\"SELECT {func}(y, x){suffix}\",\n+ \"postgres\": f\"SELECT {func}(y, x){suffix}\",\n+ \"snowflake\": f\"SELECT {func}(y, x){suffix}\",\n+ },\n+ )\n self.validate_all(\n \"TO_CHAR(x, y)\",\n read={\ndiff --git a/tests/test_expressions.py b/tests/test_expressions.py\nindex 54bc223c..9365fc4e 100644\n--- a/tests/test_expressions.py\n+++ b/tests/test_expressions.py\n@@ -802,6 +802,7 @@ class TestExpressions(unittest.TestCase):\n ),\n (datetime.date(2022, 10, 1), \"DATE_STR_TO_DATE('2022-10-01')\"),\n (math.nan, \"NULL\"),\n+ (b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x07\\xd3\", \"2003\"),\n ]:\n with self.subTest(value):\n self.assertEqual(exp.convert(value).sql(), expected)\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/test_expressions.py::TestExpressions::test_convert"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/test_expressions.py::TestExpressions::test_transform_with_parent_mutation", "tests/dialects/test_postgres.py::TestPostgres::test_postgres", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/test_expressions.py::TestExpressions::test_convert"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "omni-us__jsonargparse-559_x3", "level": 3, "source": "swerebench", "repo": "omni-us/jsonargparse", "image": "swerebench/sweb.eval.x86_64.omni-us_1776_jsonargparse-559:latest", "base_commit": "74c169b6feb07808f41f65da069870e1e0db0203", "num_bugs": 3, "bugs": [{"instance_id": "omni-us__jsonargparse-559", "base_commit": "74c169b6feb07808f41f65da069870e1e0db0203", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex eeeff79..e531ed7 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -12,6 +12,15 @@ The semantic versioning only considers the public API as described in\n paths are considered internals and can change in minor and patch releases.\n \n \n+v4.32.1 (2024-08-??)\n+--------------------\n+\n+Fixed\n+^^^^^\n+- ``dict`` types not correctly forwarding previous nested values when parsing\n+ (`#559 `__).\n+\n+\n v4.32.0 (2024-07-19)\n --------------------\n \ndiff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py\nindex aec416d..4c90a74 100644\n--- a/jsonargparse/_typehints.py\n+++ b/jsonargparse/_typehints.py\n@@ -904,7 +904,12 @@ def adapt_typehints(\n for t in sub_add_kwargs[\"linked_targets\"]\n }\n else:\n- kwargs = adapt_kwargs\n+ kwargs = adapt_kwargs.copy()\n+ if kwargs.get(\"prev_val\"):\n+ if isinstance(kwargs[\"prev_val\"], dict):\n+ kwargs[\"prev_val\"] = kwargs[\"prev_val\"].get(k)\n+ else:\n+ kwargs[\"prev_val\"] = None\n val[k] = adapt_typehints(v, subtypehints[1], **kwargs)\n if get_import_path(typehint.__class__) == \"typing._TypedDictMeta\":\n if typehint.__total__:\n", "test_patch": "diff --git a/jsonargparse_tests/test_dataclass_like.py b/jsonargparse_tests/test_dataclass_like.py\nindex 9d884c4..963eeaf 100644\n--- a/jsonargparse_tests/test_dataclass_like.py\n+++ b/jsonargparse_tests/test_dataclass_like.py\n@@ -1,6 +1,7 @@\n from __future__ import annotations\n \n import dataclasses\n+import json\n from typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar, Union\n from unittest.mock import patch\n \n@@ -684,6 +685,13 @@ if pydantic_support:\n def __init__(self, a: Optional[PydanticModel] = None):\n self.a = a\n \n+ class NestedModel(pydantic.BaseModel):\n+ inputs: List[str]\n+ outputs: List[str]\n+\n+ class PydanticNestedDict(pydantic.BaseModel):\n+ nested: Optional[Dict[str, NestedModel]] = None\n+\n \n def none(x):\n return x\n@@ -817,6 +825,23 @@ class TestPydantic:\n assert cfg.b.class_path == f\"{__name__}.OptionalPydantic\"\n assert cfg.b.init_args == Namespace(a=Namespace(p1=\"x\", p2=3))\n \n+ def test_nested_dict(self, parser):\n+ parser.add_argument(\"--config\", action=\"config\")\n+ parser.add_argument(\"--model\", type=PydanticNestedDict)\n+ model = {\n+ \"nested\": {\n+ \"key\": {\n+ \"inputs\": [\"a\", \"b\"],\n+ \"outputs\": [\"x\", \"y\"],\n+ }\n+ }\n+ }\n+ cfg = parser.parse_args([\"--model\", json.dumps(model)])\n+ assert cfg.model.nested[\"key\"] == Namespace(inputs=[\"a\", \"b\"], outputs=[\"x\", \"y\"])\n+ init = parser.instantiate_classes(cfg)\n+ assert isinstance(init.model, PydanticNestedDict)\n+ assert isinstance(init.model.nested[\"key\"], NestedModel)\n+\n \n # attrs tests\n \n", "FAIL_TO_PASS": ["jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_nested_dict"]}, {"instance_id": "omni-us__jsonargparse-560", "base_commit": "c634a88f120b96d87f80e079417f0138aabe466f", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex e531ed7..7fc944c 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -19,6 +19,8 @@ Fixed\n ^^^^^\n - ``dict`` types not correctly forwarding previous nested values when parsing\n (`#559 `__).\n+- ``List`` type incorrectly using defaults from previous item (`#560\n+ `__).\n \n \n v4.32.0 (2024-07-19)\ndiff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py\nindex 4c90a74..98b79c3 100644\n--- a/jsonargparse/_typehints.py\n+++ b/jsonargparse/_typehints.py\n@@ -871,10 +871,11 @@ def adapt_typehints(\n elif not isinstance(val, list):\n raise_unexpected_value(f\"Expected a {typehint_origin}\", val)\n if subtypehints is not None:\n- adapt_kwargs_n = adapt_kwargs\n for n, v in enumerate(val):\n if isinstance(prev_val, list) and len(prev_val) == len(val):\n- adapt_kwargs_n = {**adapt_kwargs, \"prev_val\": prev_val[n]}\n+ adapt_kwargs_n = {**deepcopy(adapt_kwargs), \"prev_val\": prev_val[n]}\n+ else:\n+ adapt_kwargs_n = deepcopy(adapt_kwargs)\n val[n] = adapt_typehints(v, subtypehints[0], list_item=True, **adapt_kwargs_n)\n \n # Dict, Mapping\n", "test_patch": "diff --git a/jsonargparse_tests/test_dataclass_like.py b/jsonargparse_tests/test_dataclass_like.py\nindex 963eeaf..818eb3b 100644\n--- a/jsonargparse_tests/test_dataclass_like.py\n+++ b/jsonargparse_tests/test_dataclass_like.py\n@@ -203,6 +203,18 @@ def test_list_nested_optional_dataclass(parser):\n assert cfg.b == [Namespace(a=Namespace(x=1))]\n \n \n+@dataclasses.dataclass\n+class ItemData:\n+ x: int = 1\n+ y: str = \"one\"\n+\n+\n+def test_list_append_defaults(parser):\n+ parser.add_argument(\"--list\", type=List[ItemData])\n+ cfg = parser.parse_args([\"--list+={}\", '--list+={\"x\":2,\"y\":\"two\"}', '--list+={\"x\":3}'])\n+ assert cfg.list == [Namespace(x=1, y=\"one\"), Namespace(x=2, y=\"two\"), Namespace(x=3, y=\"one\")]\n+\n+\n def test_add_argument_dataclass_type(parser):\n parser.add_argument(\"--b\", type=DataClassB, default=DataClassB(b1=7.0))\n cfg = parser.get_defaults()\n", "FAIL_TO_PASS": ["jsonargparse_tests/test_dataclass_like.py::test_list_append_defaults"]}, {"instance_id": "omni-us__jsonargparse-562", "base_commit": "f7aa49f434115f721a16a373c598d5fb9aaa2d5f", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 7fc944c..28d4c38 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -21,6 +21,8 @@ Fixed\n (`#559 `__).\n - ``List`` type incorrectly using defaults from previous item (`#560\n `__).\n+- ``--print_shtab`` not adding file completer for ``_ActionConfigLoad`` (`#562\n+ `__).\n \n \n v4.32.0 (2024-07-19)\ndiff --git a/jsonargparse/_completions.py b/jsonargparse/_completions.py\nindex ee722e5..15e6b36 100644\n--- a/jsonargparse/_completions.py\n+++ b/jsonargparse/_completions.py\n@@ -12,7 +12,7 @@ from importlib.util import find_spec\n from subprocess import PIPE, Popen\n from typing import List, Union\n \n-from ._actions import ActionConfigFile, _ActionHelpClassPath, remove_actions\n+from ._actions import ActionConfigFile, _ActionConfigLoad, _ActionHelpClassPath, remove_actions\n from ._parameter_resolvers import get_signature_parameters\n from ._typehints import (\n ActionTypeHint,\n@@ -142,7 +142,7 @@ def shtab_prepare_action(action, parser) -> None:\n return\n \n complete = None\n- if isinstance(action, ActionConfigFile):\n+ if isinstance(action, (ActionConfigFile, _ActionConfigLoad)):\n complete = shtab.FILE\n elif isinstance(action, ActionTypeHint):\n typehint = action._typehint\n", "test_patch": "diff --git a/jsonargparse_tests/test_shtab.py b/jsonargparse_tests/test_shtab.py\nindex ae463a9..9802357 100644\n--- a/jsonargparse_tests/test_shtab.py\n+++ b/jsonargparse_tests/test_shtab.py\n@@ -194,6 +194,12 @@ class Base:\n pass\n \n \n+def test_bash_class_config(parser):\n+ parser.add_class_arguments(Base, \"class\")\n+ shtab_script = get_shtab_script(parser, \"bash\")\n+ assert \"_class_COMPGEN=_shtab_compgen_files\" in shtab_script\n+\n+\n class SubA(Base):\n def __init__(self, p1: int, p2: AXEnum):\n pass\n", "FAIL_TO_PASS": ["jsonargparse_tests/test_shtab.py::test_bash_class_config"]}], "all_FAIL_TO_PASS": ["jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_nested_dict", "jsonargparse_tests/test_dataclass_like.py::test_list_append_defaults", "jsonargparse_tests/test_shtab.py::test_bash_class_config"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "sdepy__sdepy-12_x3", "level": 3, "source": "swerebench", "repo": "sdepy/sdepy", "image": "swerebench/sweb.eval.x86_64.sdepy_1776_sdepy-12:latest", "base_commit": "47ffea9072ee6cb5f33a1a8e98db0063fab18634", "num_bugs": 3, "bugs": [{"instance_id": "sdepy__sdepy-12", "base_commit": "47ffea9072ee6cb5f33a1a8e98db0063fab18634", "gold_patch": "diff --git a/sdepy/infrastructure.py b/sdepy/infrastructure.py\nindex 122f02b..dc873b3 100644\n--- a/sdepy/infrastructure.py\n+++ b/sdepy/infrastructure.py\n@@ -289,7 +289,7 @@ class process(np.ndarray):\n A process is a subclass of numpy.ndarray, where its values as an array\n are the process values along the timeline and across paths. All\n numpy.ndarray methods, attributes and properties are guaranteed to act\n- upon such values, as would those of the parent class. Such no-overriding\n+ upon such values, as would those of the parent class. Such no overriding\n commitment is intended to safeguard predictablity of array operations\n on process instances; process-specific functionalities are delegated\n to process-specific methods, attributes and properties.\n@@ -464,30 +464,38 @@ class process(np.ndarray):\n 'timelines'.format(a.shape, self.shape))\n return out_array\n \n- def __array_wrap__(self, out_array, context):\n- ufunc, inputs, domain = context\n- assert hasattr(self, 't')\n- assert any(self is a for a in inputs)\n-\n- # get process inputs\n- p_inputs = [a for a in inputs\n- if isinstance(a, process)]\n-\n- # ??? overcautious - to be eliminated\n- for a in p_inputs:\n- if not self._is_compatible(a):\n- assert False, 'this should never occur - '\\\n- '__array_prepare__ should enforce compatibility'\n-\n- # set t to the common non constant timeline\n- # or to the constant timeline of the first input\n- t = p_inputs[0].t\n- for a in p_inputs[1:]:\n- if len(a.t) > 1:\n- t = a.t\n- break\n- cls = type(self)\n- return cls(t=t, x=out_array)\n+ def __array_wrap__(self, out_array, context=None):\n+ if context is None:\n+ # this may happen since numpy 1.16.0 when a process instance\n+ # invokes a numpy.ndarray method (eg. sum, mean, etc.):\n+ # in such case the resulting out_array is returned, as\n+ # needed to comply with the no overriding commitment\n+ # for numpy.ndarray methods\n+ return out_array\n+ else:\n+ ufunc, inputs, domain = context\n+ assert hasattr(self, 't')\n+ assert any(self is a for a in inputs)\n+\n+ # get process inputs\n+ p_inputs = [a for a in inputs\n+ if isinstance(a, process)]\n+\n+ # ??? overcautious - to be eliminated\n+ for a in p_inputs:\n+ if not self._is_compatible(a):\n+ assert False, 'this should never occur - '\\\n+ '__array_prepare__ should enforce compatibility'\n+\n+ # set t to the common non constant timeline\n+ # or to the constant timeline of the first input\n+ t = p_inputs[0].t\n+ for a in p_inputs[1:]:\n+ if len(a.t) > 1:\n+ t = a.t\n+ break\n+ cls = type(self)\n+ return cls(t=t, x=out_array)\n \n # -------------\n # interpolation\n@@ -1095,14 +1103,14 @@ class process(np.ndarray):\n def piecewise(t=0., *, x=None, v=None, dtype=None, mode='mid'):\n \"\"\"\n Return a process that interpolates to a piecewise constant function.\n- \n+\n Parameters\n ----------\n t : array-like\n Reference timeline (see below).\n x : array-like, optional\n Values of the process along the timeline and across paths.\n- One and only one of ``x``, ``v``, must be provided, \n+ One and only one of ``x``, ``v``, must be provided,\n as a keyword argument.\n v : array-like, optional\n Values of a deterministic (one path) process along the timeline.\n@@ -1113,22 +1121,22 @@ def piecewise(t=0., *, x=None, v=None, dtype=None, mode='mid'):\n to the reference timeline: 'mid', 'forward', 'backward'\n set ``t[i]`` to be the midpoint, start or end point respectively,\n of the constant segment with value ``x[i]`` or ``v[i]``.\n- \n+\n See Also\n --------\n process\n- \n+\n Notes\n -----\n Parameters ``t``, ``x``, ``v``, ``dtype`` conform to the ``process``\n instantiation interface and shape requirements.\n- \n+\n The returned process ``p`` behaves as advertised upon interpolation\n- with default interpolation kind, and may be used \n- as a time dependent piecewise constant parameter in SDE integration. \n- However, its timeline ``p.t`` and values ``p.x`` \n- are not guaranteed to coincide with the given ``t`` or ``x``, \n- and should not be relied upon. \n+ with default interpolation kind, and may be used\n+ as a time dependent piecewise constant parameter in SDE integration.\n+ However, its timeline ``p.t`` and values ``p.x``\n+ are not guaranteed to coincide with the given ``t`` or ``x``,\n+ and should not be relied upon.\n \"\"\"\n # delegate preprocessing of arguments to the process class\n p = process(t, x=x, v=v, dtype=dtype)\n", "test_patch": "diff --git a/sdepy/tests/test_process.py b/sdepy/tests/test_process.py\nindex 6ca77a7..26bea8d 100644\n--- a/sdepy/tests/test_process.py\n+++ b/sdepy/tests/test_process.py\n@@ -605,6 +605,16 @@ def test_summary():\n b = np.cumsum(p, axis=0)\n assert_allclose(a, b, rtol=eps(p.dtype))\n \n+ # numpy summary operations\n+ for f in funcs:\n+ a = getattr(p, f)()\n+ b = getattr(np, f)(p)\n+ c = getattr(np, f)(p.x)\n+ assert_(isinstance(a, np.ndarray) and not isinstance(a, process))\n+ assert_(isinstance(b, np.ndarray) and not isinstance(b, process))\n+ assert_allclose(a, c)\n+ assert_allclose(b, c)\n+\n \n # ----------------------------------------\n # test increments, derivative and integral\n@@ -714,7 +724,7 @@ def test_piecewise():\n p = piecewise((1, 2), v=(10, 20), mode='zzz')\n with assert_warns(DeprecationWarning):\n p = _piecewise_constant_process((1, 2), v=(10, 20))\n- \n+\n \n # case testing\n def tst_piecewise(dtype, paths, vshape, mode, shift):\n@@ -728,7 +738,7 @@ def tst_piecewise(dtype, paths, vshape, mode, shift):\n else:\n x = xx = 1 + np.random.random((3,) + vshape + (paths,)).astype(dtype)\n vv = None\n- \n+\n if mode is None:\n p = piecewise(t, x=xx, v=vv) # default mode is 'mid'\n else:\n", "FAIL_TO_PASS": ["sdepy/tests/test_process.py::test_constructor", "sdepy/tests/test_process.py::test_interp", "sdepy/tests/test_process.py::test_t_getitem", "sdepy/tests/test_process.py::test_p_getitem", "sdepy/tests/test_process.py::test_v_getitem", "sdepy/tests/test_process.py::test_properties", "sdepy/tests/test_process.py::test_summary", "sdepy/tests/test_process.py::test_increments"]}, {"instance_id": "sdepy__sdepy-13", "base_commit": "b90667045d3d2480b39151152ee7ba4b429fec19", "gold_patch": "diff --git a/sdepy/infrastructure.py b/sdepy/infrastructure.py\nindex dc873b3..d557ea4 100644\n--- a/sdepy/infrastructure.py\n+++ b/sdepy/infrastructure.py\n@@ -796,7 +796,8 @@ class process(np.ndarray):\n the minimum process value attained across paths.\n \"\"\"\n return process(t=self.t,\n- v=self.min(axis=-1, out=out))\n+ x=self.min(axis=-1, out=out,\n+ keepdims=True))\n \n def pmax(self, out=None):\n \"\"\"\n@@ -804,7 +805,8 @@ class process(np.ndarray):\n the maximum process value attained across paths.\n \"\"\"\n return process(t=self.t,\n- v=self.max(axis=-1, out=out))\n+ x=self.max(axis=-1, out=out,\n+ keepdims=True))\n \n def psum(self, dtype=None, out=None):\n \"\"\"\n@@ -855,14 +857,16 @@ class process(np.ndarray):\n process value attained along time.\n \"\"\"\n return process(t=self.t[:1],\n- x=self.min(axis=0, out=out)[np.newaxis, ...])\n+ x=self.min(axis=0, out=out,\n+ keepdims=True))\n \n def tmax(self, out=None):\n \"\"\"Constant process exposing for each path the maximum\n process value attained along time.\n \"\"\"\n return process(t=self.t[:1],\n- x=self.max(axis=0, out=out)[np.newaxis, ...])\n+ x=self.max(axis=0, out=out,\n+ keepdims=True))\n \n def tsum(self, dtype=None, out=None):\n \"\"\"\n", "test_patch": "diff --git a/sdepy/tests/test_process.py b/sdepy/tests/test_process.py\nindex 26bea8d..5a7f2ad 100644\n--- a/sdepy/tests/test_process.py\n+++ b/sdepy/tests/test_process.py\n@@ -582,28 +582,63 @@ def test_summary():\n \n # summary across paths\n for f in funcs:\n+ # test values\n a = getattr(p, 'p' + f)()\n- b = getattr(np, f)(p, axis=-1)\n- assert_allclose(a, b[..., np.newaxis], rtol=eps(p.dtype))\n- a = p.pmean(dtype=np.float32)\n+ b = getattr(np, f)(p, axis=-1)[..., np.newaxis]\n+ assert_allclose(a, b, rtol=eps(p.dtype))\n+ # test out parameter\n+ y = np.full((3, 5, 7, 1), np.nan)\n+ a = getattr(p, 'p' + f)(out=y)\n+ assert_(a.base is y)\n+ assert_allclose(y, b, rtol=eps(p.dtype))\n+ for f in ('sum', 'mean', 'var', 'std'):\n+ # test dtype parameter\n+ a = getattr(p, 'p' + f)(dtype=np.float32)\n assert_(a.dtype == np.float32)\n- b = p.pvar(ddof=1, out=a)\n- assert_allclose(b, p.var(ddof=1, axis=-1)[..., np.newaxis],\n- rtol=eps(np.float32))\n+ # test ddof parameter for pvar and pstd\n+ a = p.pvar(ddof=1)\n+ assert_allclose(a, p.var(ddof=1, axis=-1)[..., np.newaxis],\n+ rtol=eps(p.dtype))\n+ a = p.pstd(ddof=1)\n+ assert_allclose(a, p.std(ddof=1, axis=-1)[..., np.newaxis],\n+ rtol=eps(p.dtype))\n \n # summary along the timeline\n for f in funcs:\n+ # test values\n a = getattr(p, 't' + f)()\n- b = getattr(np, f)(p, axis=0)\n- assert_allclose(a, b[np.newaxis, ...], rtol=eps(p.dtype))\n- a = p.tmean(dtype=np.float32)\n- assert_(a.dtype == np.float32)\n- b = p.tvar(ddof=1, out=a)\n- assert_allclose(b, p.var(ddof=1, axis=0)[np.newaxis, ...],\n- rtol=eps(np.float32))\n- a = p.tcumsum()\n- b = np.cumsum(p, axis=0)\n+ b = getattr(np, f)(p, axis=0)[np.newaxis, ...]\n assert_allclose(a, b, rtol=eps(p.dtype))\n+ # test out parameter\n+ y = np.full((1, 5, 7, 11), np.nan)\n+ a = getattr(p, 't' + f)(out=y)\n+ assert_(a.base is y)\n+ assert_allclose(y, b, rtol=eps(p.dtype))\n+ for f in ('sum', 'mean', 'var', 'std'):\n+ # test dtype parameter\n+ a = getattr(p, 't' + f)(dtype=np.float32)\n+ assert_(a.dtype == np.float32)\n+\n+ # test ddof parameter for tvar and tstd\n+ a = p.tvar(ddof=1)\n+ assert_allclose(a, p.var(ddof=1, axis=0)[np.newaxis, ...],\n+ rtol=eps(p.dtype))\n+ a = p.tstd(ddof=1)\n+ assert_allclose(a, p.std(ddof=1, axis=0)[np.newaxis, ...],\n+ rtol=eps(p.dtype))\n+\n+ # test tcumsum values\n+ a = p.tcumsum()\n+ b = np.cumsum(p, axis=0)\n+ assert_allclose(a, b, rtol=3*eps(p.dtype))\n+ # test tcumsum out parameter\n+ y = np.full((3, 5, 7, 11), np.nan)\n+ a = p.tcumsum(out=y)\n+ assert_(a.base is y)\n+ assert_allclose(y, b, rtol=3*eps(p.dtype))\n+ # test tcumsum dtype parameter\n+ a = p.tcumsum(dtype=np.float32)\n+ assert_(a.dtype == np.float32)\n \n # numpy summary operations\n for f in funcs:\n", "FAIL_TO_PASS": ["sdepy/tests/test_process.py::test_summary"]}, {"instance_id": "sdepy__sdepy-21", "base_commit": "6396bfdb9e690afcc6c549bc4a0bd8f0263307ff", "gold_patch": "diff --git a/sdepy/integration.py b/sdepy/integration.py\nindex 60aa665..6557a3e 100644\n--- a/sdepy/integration.py\n+++ b/sdepy/integration.py\n@@ -714,7 +714,7 @@ class integrator(paths_generator):\n x = xw[0]\n # compute A, dZ and make them available as attributes\n A, dZ = self.A(s, x), self.dZ(s, ds)\n- xw[1][...] = x + sum(A[id]*dZ[id] for id in A.keys())\n+ xw[1][...] = x + sum(A.get(id, 0)*dZ[id] for id in A.keys())\n \n if self.getinfo:\n iv.update(last_t=s, last_dt=ds,\n@@ -1186,13 +1186,29 @@ class SDE:\n # algorithm of the integrator class\n # -----------------------------------\n \n+ def _check_sde_values(self, A):\n+ if not isinstance(A, dict):\n+ raise TypeError(\n+ 'invalid {} return values: a dict, not a {} object expected'\n+ .format(self.sde, type(A))\n+ )\n+ if not set(A.keys()).issubset(self.sources):\n+ raise KeyError(\n+ 'invalid {} return values: {} entries expected (one per '\n+ 'stochasticity source), not {}'\n+ .format(self.sde, set(self.sources), set(A.keys()))\n+ )\n+\n def A(self, t, x):\n \"\"\"See documentation integrator.A\"\"\"\n sde_args_eval = {\n k: (z(t) if callable(z) else z)\n for (k, z) in self._get_args(self._sde_args_keys).items()\n }\n- return self.sde(t, x, **sde_args_eval)\n+ # get and check sde values\n+ A_ = self.sde(t, x, **sde_args_eval)\n+ self._check_sde_values(A_)\n+ return A_\n \n def dZ(self, t, dt):\n \"\"\"See documentation of integrator.dZ\"\"\"\n@@ -1642,6 +1658,20 @@ class SDEs(SDE):\n # algorithm of the integrator class\n # -----------------------------------\n \n+ def _check_sde_values(self, As):\n+ if not isinstance(As, (list, tuple)):\n+ raise TypeError(\n+ 'invalid {} return values: a list or tuple of {} dict '\n+ '(one per equation) expected, not a {} object'\n+ .format(self.sde, self.q, type(As))\n+ )\n+ if len(As) != self.q:\n+ raise ValueError(\n+ 'invalid {} return values: {} equations expected, '\n+ 'not {}'.format(self.sde, self.q, len(As)))\n+ for a in As:\n+ super()._check_sde_values(a)\n+\n def A(self, t, X):\n \"\"\"See documentation of integrator.A\"\"\"\n sde_args_eval = {\n@@ -1653,12 +1683,13 @@ class SDEs(SDE):\n # of arrays (one per equation)\n xs = self.unpack(X)\n \n- # get sde values, as a list of dicts (one per equation)\n+ # get and check sde values\n As = self.sde(t, *xs, **sde_args_eval)\n+ self._check_sde_values(As)\n A_ids = set()\n for a in As:\n- A_ids.update(a)\n- A = {id: self.pack(tuple(a[id] for a in As))\n+ A_ids.update(a.keys())\n+ A = {id: self.pack(tuple(a.get(id, 0) for a in As))\n for id in A_ids}\n return A\n \n@@ -1739,7 +1770,6 @@ class SDEs(SDE):\n \n Parameters\n ----------\n-\n t : float\n Time point at which the SDE should be evaluated.\n x, y, ... : arrays\n@@ -1751,9 +1781,8 @@ class SDEs(SDE):\n \n Returns\n -------\n-\n- sde_terms : list of dict of arrays\n- A list of dictionaries, one per equation.\n+ sde_terms : list or tuple of dict of arrays\n+ A list or tuple of dictionaries, one per equation.\n See documentation of ``SDE.sde``.\n \n Notes\n", "test_patch": "diff --git a/sdepy/tests/test_integrator.py b/sdepy/tests/test_integrator.py\nindex a06788e..47bf979 100644\n--- a/sdepy/tests/test_integrator.py\n+++ b/sdepy/tests/test_integrator.py\n@@ -386,3 +386,62 @@ def test_SDE():\n xs2 = integrate(f)(x0=(1.,)*4, dw=tw, paths=11, steps=30)(t)\n for u, v in zip(xs1, xs2):\n assert_allclose(xs1, xs2, rtol=eps(u.dtype))\n+\n+ # 4 equations with terms partially omitted\n+ # (formerly a cause of error)\n+ # ----------------------------------------\n+ @integrate\n+ def f_process(t, x=0, y=0, z=0, w=0):\n+ return ({'dt': 1, 'dw': 1}, {'dt': 1}, {'dw': 1}, {})\n+ xs = f_process(x0=(1,)*4, paths=11, steps=30)(t)\n+\n+ # SDE class from integrate\n+ # ------------------------\n+ @integrate(q=1, sources={'dw', 'dt'})\n+ def f_process(t, x):\n+ return {'dt': 1, 'dw': 1}\n+ assert_(issubclass(f_process, SDE))\n+ assert_(issubclass(f_process, SDEs)) # FIXME: should be SDE subclass only\n+\n+ @integrate\n+ def f_process(t, x):\n+ return {'dt': 1, 'dw': 1}\n+ assert_ (issubclass(f_process, SDE))\n+ assert_(not issubclass(f_process, SDEs)) # this is ok\n+\n+ # test errors\n+ # -----------\n+\n+ # SDE: ok\n+ class f_process(SDE, integrator):\n+ def sde(self, t, x):\n+ return {'dt': 1, 'dw': 1}\n+ x = f_process(x0=1, paths=11, steps=30)(t)\n+\n+ # SDE: wrong type\n+ f_process.sde = lambda self, t, x: x\n+ assert_raises(TypeError, f_process(x0=1, paths=11, steps=30), t)\n+\n+ # SDE: wrong sde entry\n+ f_process.sde = lambda self, t, x: {'dt': 1, 'dzzz': 1}\n+ assert_raises(KeyError, f_process(x0=1, paths=11, steps=30), t)\n+\n+ # SDEs: ok\n+ @integrate(q=2, sources=('dt', 'dw'))\n+ def f_process(t, x, y):\n+ return {'dt': 1, 'dw': 1}, {'dt': 1}\n+ assert f_process.q == 2\n+ x, y = f_process(x0=(1,)*2, paths=11, steps=30)(t)\n+\n+ # SDEs: wrong type\n+ f_process.sde = lambda self, t, x, y: {'dt': 1, 'dw': 1}\n+ assert f_process.q == 2\n+ assert_raises(TypeError, f_process(x0=(1,)*2, paths=11, steps=30), t)\n+\n+ # SDEs: wrong number of equations\n+ f_process.sde = lambda self, t, x, y: ({'dt': 1, 'dw': 1},)\n+ assert_raises(ValueError, f_process(x0=(1,)*2, paths=11, steps=30), t)\n+\n+ # SDEs: wrong sde entry\n+ f_process.sde = lambda self, t, x, y: ({'dt': 1}, {'dzzz': 1})\n+ assert_raises(KeyError, f_process(x0=(1,)*2, paths=11, steps=30), t)\n", "FAIL_TO_PASS": ["sdepy/tests/test_integrator.py::test_SDE"]}], "all_FAIL_TO_PASS": ["sdepy/tests/test_process.py::test_constructor", "sdepy/tests/test_process.py::test_interp", "sdepy/tests/test_process.py::test_t_getitem", "sdepy/tests/test_process.py::test_p_getitem", "sdepy/tests/test_process.py::test_v_getitem", "sdepy/tests/test_process.py::test_properties", "sdepy/tests/test_process.py::test_summary", "sdepy/tests/test_process.py::test_increments", "sdepy/tests/test_process.py::test_summary", "sdepy/tests/test_integrator.py::test_SDE"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3621_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3621:latest", "base_commit": "5396a8e6ea29876c824b741c2812ad15f4768e4c", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3621", "base_commit": "5396a8e6ea29876c824b741c2812ad15f4768e4c", "gold_patch": "diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex 26c7ad2d..67a32709 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -202,6 +202,7 @@ class MySQL(Dialect):\n \"CHARSET\": TokenType.CHARACTER_SET,\n \"FORCE\": TokenType.FORCE,\n \"IGNORE\": TokenType.IGNORE,\n+ \"KEY\": TokenType.KEY,\n \"LOCK TABLES\": TokenType.COMMAND,\n \"LONGBLOB\": TokenType.LONGBLOB,\n \"LONGTEXT\": TokenType.LONGTEXT,\ndiff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 8c3c471c..c8ac0db1 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -510,15 +510,18 @@ class Snowflake(Dialect):\n self._retreat(self._index - 1)\n \n if self._match_text_seq(\"MASKING\", \"POLICY\"):\n+ policy = self._parse_column()\n return self.expression(\n exp.MaskingPolicyColumnConstraint,\n- this=self._parse_id_var(),\n+ this=policy.to_dot() if isinstance(policy, exp.Column) else policy,\n expressions=self._match(TokenType.USING)\n and self._parse_wrapped_csv(self._parse_id_var),\n )\n if self._match_text_seq(\"PROJECTION\", \"POLICY\"):\n+ policy = self._parse_column()\n return self.expression(\n- exp.ProjectionPolicyColumnConstraint, this=self._parse_id_var()\n+ exp.ProjectionPolicyColumnConstraint,\n+ this=policy.to_dot() if isinstance(policy, exp.Column) else policy,\n )\n if self._match(TokenType.TAG):\n return self.expression(\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex c6802605..b99d34c0 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1138,7 +1138,14 @@ class Parser(metaclass=_Parser):\n \n FETCH_TOKENS = ID_VAR_TOKENS - {TokenType.ROW, TokenType.ROWS, TokenType.PERCENT}\n \n- ADD_CONSTRAINT_TOKENS = {TokenType.CONSTRAINT, TokenType.PRIMARY_KEY, TokenType.FOREIGN_KEY}\n+ ADD_CONSTRAINT_TOKENS = {\n+ TokenType.CONSTRAINT,\n+ TokenType.FOREIGN_KEY,\n+ TokenType.INDEX,\n+ TokenType.KEY,\n+ TokenType.PRIMARY_KEY,\n+ TokenType.UNIQUE,\n+ }\n \n DISTINCT_TOKENS = {TokenType.DISTINCT}\n \n@@ -3242,7 +3249,7 @@ class Parser(metaclass=_Parser):\n while self._match_set(self.TABLE_INDEX_HINT_TOKENS):\n hint = exp.IndexTableHint(this=self._prev.text.upper())\n \n- self._match_texts((\"INDEX\", \"KEY\"))\n+ self._match_set((TokenType.INDEX, TokenType.KEY))\n if self._match(TokenType.FOR):\n hint.set(\"target\", self._advance_any() and self._prev.text.upper())\n \ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex 5b2f2415..cd582f46 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -287,6 +287,7 @@ class TokenType(AutoName):\n JOIN = auto()\n JOIN_MARKER = auto()\n KEEP = auto()\n+ KEY = auto()\n KILL = auto()\n LANGUAGE = auto()\n LATERAL = auto()\n", "test_patch": "diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py\nindex fdb7e919..e19a072e 100644\n--- a/tests/dialects/test_mysql.py\n+++ b/tests/dialects/test_mysql.py\n@@ -21,6 +21,9 @@ class TestMySQL(Validator):\n self.validate_identity(\"CREATE TABLE foo (a BIGINT, FULLTEXT INDEX (b))\")\n self.validate_identity(\"CREATE TABLE foo (a BIGINT, SPATIAL INDEX (b))\")\n self.validate_identity(\"ALTER TABLE t1 ADD COLUMN x INT, ALGORITHM=INPLACE, LOCK=EXCLUSIVE\")\n+ self.validate_identity(\"ALTER TABLE t ADD INDEX `i` (`c`)\")\n+ self.validate_identity(\"ALTER TABLE t ADD UNIQUE `i` (`c`)\")\n+ self.validate_identity(\"ALTER TABLE test_table MODIFY COLUMN test_column LONGTEXT\")\n self.validate_identity(\n \"CREATE TABLE `oauth_consumer` (`key` VARCHAR(32) NOT NULL, UNIQUE `OAUTH_CONSUMER_KEY` (`key`))\"\n )\n@@ -60,6 +63,10 @@ class TestMySQL(Validator):\n self.validate_identity(\n \"CREATE OR REPLACE VIEW my_view AS SELECT column1 AS `boo`, column2 AS `foo` FROM my_table WHERE column3 = 'some_value' UNION SELECT q.* FROM fruits_table, JSON_TABLE(Fruits, '$[*]' COLUMNS(id VARCHAR(255) PATH '$.$id', value VARCHAR(255) PATH '$.value')) AS q\",\n )\n+ self.validate_identity(\n+ \"ALTER TABLE t ADD KEY `i` (`c`)\",\n+ \"ALTER TABLE t ADD INDEX `i` (`c`)\",\n+ )\n self.validate_identity(\n \"CREATE TABLE `foo` (`id` char(36) NOT NULL DEFAULT (uuid()), PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`))\",\n \"CREATE TABLE `foo` (`id` CHAR(36) NOT NULL DEFAULT (UUID()), PRIMARY KEY (`id`), UNIQUE `id` (`id`))\",\n@@ -76,9 +83,6 @@ class TestMySQL(Validator):\n \"ALTER TABLE test_table ALTER COLUMN test_column SET DATA TYPE LONGTEXT\",\n \"ALTER TABLE test_table MODIFY COLUMN test_column LONGTEXT\",\n )\n- self.validate_identity(\n- \"ALTER TABLE test_table MODIFY COLUMN test_column LONGTEXT\",\n- )\n self.validate_identity(\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC\",\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()) DEFAULT CHARACTER SET=utf8 ROW_FORMAT=DYNAMIC\",\ndiff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 9d9371db..e5bf4f27 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -1196,16 +1196,16 @@ WHERE\n for constraint_prefix in (\"WITH \", \"\"):\n with self.subTest(f\"Constraint prefix: {constraint_prefix}\"):\n self.validate_identity(\n- f\"CREATE TABLE t (id INT {constraint_prefix}MASKING POLICY p)\",\n- \"CREATE TABLE t (id INT MASKING POLICY p)\",\n+ f\"CREATE TABLE t (id INT {constraint_prefix}MASKING POLICY p.q.r)\",\n+ \"CREATE TABLE t (id INT MASKING POLICY p.q.r)\",\n )\n self.validate_identity(\n f\"CREATE TABLE t (id INT {constraint_prefix}MASKING POLICY p USING (c1, c2, c3))\",\n \"CREATE TABLE t (id INT MASKING POLICY p USING (c1, c2, c3))\",\n )\n self.validate_identity(\n- f\"CREATE TABLE t (id INT {constraint_prefix}PROJECTION POLICY p)\",\n- \"CREATE TABLE t (id INT PROJECTION POLICY p)\",\n+ f\"CREATE TABLE t (id INT {constraint_prefix}PROJECTION POLICY p.q.r)\",\n+ \"CREATE TABLE t (id INT PROJECTION POLICY p.q.r)\",\n )\n self.validate_identity(\n f\"CREATE TABLE t (id INT {constraint_prefix}TAG (key1='value_1', key2='value_2'))\",\n", "FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl"]}, {"instance_id": "tobymao__sqlglot-3627", "base_commit": "ee9b01d5631f8f0942b61dfaf0632ae0ac2543bb", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex b99d34c0..854f5e7d 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4534,7 +4534,11 @@ class Parser(metaclass=_Parser):\n \n while self._match(TokenType.COLON):\n start_index = self._index\n- path = self._parse_column_ops(self._parse_field(any_token=True))\n+\n+ # Snowflake allows reserved keywords as json keys but advance_any() excludes TokenType.SELECT from any_tokens=True\n+ path = self._parse_column_ops(\n+ self._parse_field(any_token=True, tokens=(TokenType.SELECT,))\n+ )\n \n # The cast :: operator has a lower precedence than the extraction operator :, so\n # we rearrange the AST appropriately to avoid casting the JSON path\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex e5bf4f27..12864369 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -125,6 +125,10 @@ WHERE\n \"SELECT a:from::STRING, a:from || ' test' \",\n \"SELECT CAST(GET_PATH(a, 'from') AS TEXT), GET_PATH(a, 'from') || ' test'\",\n )\n+ self.validate_identity(\n+ \"SELECT a:select\",\n+ \"SELECT GET_PATH(a, 'select')\",\n+ )\n self.validate_identity(\"x:from\", \"GET_PATH(x, 'from')\")\n self.validate_identity(\n \"value:values::string::int\",\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-3630", "base_commit": "c49cefafaf5e9e51778ab85499fde29600d66ed7", "gold_patch": "diff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex 3b6fc428..1282e150 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -1273,18 +1273,6 @@ class Tokenizer(metaclass=_Tokenizer):\n elif token_type == TokenType.BIT_STRING:\n base = 2\n elif token_type == TokenType.HEREDOC_STRING:\n- if (\n- self.HEREDOC_TAG_IS_IDENTIFIER\n- and not self._peek.isidentifier()\n- and not self._peek == end\n- ):\n- if self.HEREDOC_STRING_ALTERNATIVE != token_type.VAR:\n- self._add(self.HEREDOC_STRING_ALTERNATIVE)\n- else:\n- self._scan_var()\n-\n- return True\n-\n self._advance()\n \n if self._char == end:\n@@ -1296,7 +1284,10 @@ class Tokenizer(metaclass=_Tokenizer):\n raise_unmatched=not self.HEREDOC_TAG_IS_IDENTIFIER,\n )\n \n- if self._end and tag and self.HEREDOC_TAG_IS_IDENTIFIER:\n+ if tag and self.HEREDOC_TAG_IS_IDENTIFIER and (self._end or not tag.isidentifier()):\n+ if not self._end:\n+ self._advance(-1)\n+\n self._advance(-len(tag))\n self._add(self.HEREDOC_STRING_ALTERNATIVE)\n return True\ndiff --git a/sqlglotrs/src/tokenizer.rs b/sqlglotrs/src/tokenizer.rs\nindex e79d0e90..45bbe778 100644\n--- a/sqlglotrs/src/tokenizer.rs\n+++ b/sqlglotrs/src/tokenizer.rs\n@@ -405,19 +405,6 @@ impl<'a> TokenizerState<'a> {\n } else if *token_type == self.token_types.bit_string {\n (Some(2), *token_type, end.clone())\n } else if *token_type == self.token_types.heredoc_string {\n- if self.settings.heredoc_tag_is_identifier\n- && !self.is_identifier(self.peek_char)\n- && self.peek_char.to_string() != *end\n- {\n- if self.token_types.heredoc_string_alternative != self.token_types.var {\n- self.add(self.token_types.heredoc_string_alternative, None)?\n- } else {\n- self.scan_var()?\n- };\n-\n- return Ok(true)\n- };\n-\n self.advance(1)?;\n \n let tag = if self.current_char.to_string() == *end {\n@@ -426,7 +413,14 @@ impl<'a> TokenizerState<'a> {\n self.extract_string(end, false, false, !self.settings.heredoc_tag_is_identifier)?\n };\n \n- if self.is_end && !tag.is_empty() && self.settings.heredoc_tag_is_identifier {\n+ if !tag.is_empty()\n+ && self.settings.heredoc_tag_is_identifier\n+ && (self.is_end || !self.is_identifier(&tag))\n+ {\n+ if !self.is_end {\n+ self.advance(-1)?;\n+ }\n+\n self.advance(-(tag.len() as isize))?;\n self.add(self.token_types.heredoc_string_alternative, None)?;\n return Ok(true)\n@@ -494,7 +488,7 @@ impl<'a> TokenizerState<'a> {\n } else if self.peek_char.to_ascii_uppercase() == 'E' && scientific == 0 {\n scientific += 1;\n self.advance(1)?;\n- } else if self.is_identifier(self.peek_char) {\n+ } else if self.is_alphabetic_or_underscore(self.peek_char) {\n let number_text = self.text();\n let mut literal = String::from(\"\");\n \n@@ -676,10 +670,18 @@ impl<'a> TokenizerState<'a> {\n Ok(text)\n }\n \n- fn is_identifier(&mut self, name: char) -> bool {\n+ fn is_alphabetic_or_underscore(&mut self, name: char) -> bool {\n name.is_alphabetic() || name == '_'\n }\n \n+ fn is_identifier(&mut self, s: &str) -> bool {\n+ s.chars().enumerate().all(\n+ |(i, c)|\n+ if i == 0 { self.is_alphabetic_or_underscore(c) }\n+ else { self.is_alphabetic_or_underscore(c) || c.is_digit(10) }\n+ )\n+ }\n+\n fn extract_value(&mut self) -> Result {\n loop {\n if !self.peek_char.is_whitespace()\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 7bc493ac..08a65091 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -285,6 +285,7 @@ class TestDuckDB(Validator):\n self.validate_identity(\"FROM tbl\", \"SELECT * FROM tbl\")\n self.validate_identity(\"x -> '$.family'\")\n self.validate_identity(\"CREATE TABLE color (name ENUM('RED', 'GREEN', 'BLUE'))\")\n+ self.validate_identity(\"SELECT * FROM foo WHERE bar > $baz AND bla = $bob\")\n self.validate_identity(\n \"SELECT * FROM x LEFT JOIN UNNEST(y)\", \"SELECT * FROM x LEFT JOIN UNNEST(y) ON TRUE\"\n )\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_mysql.py::TestMySQL::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3734_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3734:latest", "base_commit": "1e07c4d29a43192fb57c120f3b9c1c2fa27d0fa6", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3734", "base_commit": "1e07c4d29a43192fb57c120f3b9c1c2fa27d0fa6", "gold_patch": "diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py\nindex e4dad2cc..ed01ee8b 100644\n--- a/sqlglot/dialects/oracle.py\n+++ b/sqlglot/dialects/oracle.py\n@@ -107,6 +107,7 @@ class Oracle(Dialect):\n \"TO_TIMESTAMP\": build_formatted_time(exp.StrToTime, \"oracle\"),\n \"TO_DATE\": build_formatted_time(exp.StrToDate, \"oracle\"),\n }\n+ FUNCTIONS.pop(\"NVL\")\n \n FUNCTION_PARSERS: t.Dict[str, t.Callable] = {\n **parser.Parser.FUNCTION_PARSERS,\ndiff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 1eab756b..a3e84f47 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -504,10 +504,11 @@ class Snowflake(Dialect):\n \n return lateral\n \n- def _parse_at_before(self, table: exp.Table) -> exp.Table:\n+ def _parse_historical_data(self) -> t.Optional[exp.HistoricalData]:\n # https://docs.snowflake.com/en/sql-reference/constructs/at-before\n index = self._index\n- if self._match_texts((\"AT\", \"BEFORE\")):\n+ historical_data = None\n+ if self._match_texts(self.HISTORICAL_DATA_PREFIX):\n this = self._prev.text.upper()\n kind = (\n self._match(TokenType.L_PAREN)\n@@ -518,14 +519,27 @@ class Snowflake(Dialect):\n \n if expression:\n self._match_r_paren()\n- when = self.expression(\n+ historical_data = self.expression(\n exp.HistoricalData, this=this, kind=kind, expression=expression\n )\n- table.set(\"when\", when)\n else:\n self._retreat(index)\n \n- return table\n+ return historical_data\n+\n+ def _parse_changes(self) -> t.Optional[exp.Changes]:\n+ if not self._match_text_seq(\"CHANGES\", \"(\", \"INFORMATION\", \"=>\"):\n+ return None\n+\n+ information = self._parse_var(any_token=True)\n+ self._match_r_paren()\n+\n+ return self.expression(\n+ exp.Changes,\n+ information=information,\n+ at_before=self._parse_historical_data(),\n+ end=self._parse_historical_data(),\n+ )\n \n def _parse_table_parts(\n self, schema: bool = False, is_db_reference: bool = False, wildcard: bool = False\n@@ -559,7 +573,15 @@ class Snowflake(Dialect):\n else:\n table = super()._parse_table_parts(schema=schema, is_db_reference=is_db_reference)\n \n- return self._parse_at_before(table)\n+ changes = self._parse_changes()\n+ if changes:\n+ table.set(\"changes\", changes)\n+\n+ at_before = self._parse_historical_data()\n+ if at_before:\n+ table.set(\"when\", at_before)\n+\n+ return table\n \n def _parse_id_var(\n self,\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 764810dc..79511da4 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2002,6 +2002,10 @@ class Check(Expression):\n pass\n \n \n+class Changes(Expression):\n+ arg_types = {\"information\": True, \"at_before\": False, \"end\": False}\n+\n+\n # https://docs.snowflake.com/en/sql-reference/constructs/connect-by\n class Connect(Expression):\n arg_types = {\"start\": False, \"connect\": True, \"nocycle\": False}\n@@ -3034,6 +3038,7 @@ class Table(Expression):\n \"when\": False,\n \"only\": False,\n \"partition\": False,\n+ \"changes\": False,\n }\n \n @property\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 6a2589f3..40ad4680 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1749,7 +1749,10 @@ class Generator(metaclass=_Generator):\n if when:\n table = f\"{table} {when}\"\n \n- return f\"{only}{table}{partition}{version}{file_format}{alias}{hints}{pivots}{joins}{laterals}{ordinality}\"\n+ changes = self.sql(expression, \"changes\")\n+ changes = f\" {changes}\" if changes else \"\"\n+\n+ return f\"{only}{table}{changes}{partition}{version}{file_format}{alias}{hints}{pivots}{joins}{laterals}{ordinality}\"\n \n def tablesample_sql(\n self,\n@@ -4028,3 +4031,13 @@ class Generator(metaclass=_Generator):\n expression.args.get(\"format\"),\n expression.args.get(\"zone\"),\n )\n+\n+ def changes_sql(self, expression: exp.Changes) -> str:\n+ information = self.sql(expression, \"information\")\n+ information = f\"INFORMATION => {information}\"\n+ at_before = self.sql(expression, \"at_before\")\n+ at_before = f\"{self.seg('')}{at_before}\" if at_before else \"\"\n+ end = self.sql(expression, \"end\")\n+ end = f\"{self.seg('')}{end}\" if end else \"\"\n+\n+ return f\"CHANGES ({information}){at_before}{end}\"\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex d5fe792b..d655b849 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1132,6 +1132,7 @@ class Parser(metaclass=_Parser):\n INSERT_ALTERNATIVES = {\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"}\n \n CLONE_KEYWORDS = {\"CLONE\", \"COPY\"}\n+ HISTORICAL_DATA_PREFIX = {\"AT\", \"BEFORE\", \"END\"}\n HISTORICAL_DATA_KIND = {\"TIMESTAMP\", \"OFFSET\", \"STATEMENT\", \"STREAM\"}\n \n OPCLASS_FOLLOW_KEYWORDS = {\"ASC\", \"DESC\", \"NULLS\", \"WITH\"}\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 70b8595d..1d9fd99b 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -86,9 +86,9 @@ class TestOracle(Validator):\n \"SELECT DISTINCT col1, col2 FROM table\",\n )\n self.validate_identity(\n- \"SELECT * FROM T ORDER BY I OFFSET nvl(:variable1, 10) ROWS FETCH NEXT nvl(:variable2, 10) ROWS ONLY\",\n- \"SELECT * FROM T ORDER BY I OFFSET COALESCE(:variable1, 10) ROWS FETCH NEXT COALESCE(:variable2, 10) ROWS ONLY\",\n+ \"SELECT * FROM T ORDER BY I OFFSET NVL(:variable1, 10) ROWS FETCH NEXT NVL(:variable2, 10) ROWS ONLY\",\n )\n+ self.validate_identity(\"NVL(x, y)\").assert_is(exp.Anonymous)\n self.validate_identity(\n \"SELECT * FROM t SAMPLE (.25)\",\n \"SELECT * FROM t SAMPLE (0.25)\",\n@@ -189,13 +189,6 @@ class TestOracle(Validator):\n \"spark\": \"SELECT CAST(NULL AS VARCHAR(2328)) AS COL1\",\n },\n )\n- self.validate_all(\n- \"NVL(NULL, 1)\",\n- write={\n- \"\": \"COALESCE(NULL, 1)\",\n- \"oracle\": \"COALESCE(NULL, 1)\",\n- },\n- )\n self.validate_all(\n \"DATE '2022-01-01'\",\n write={\ndiff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 80f8faaa..88b2148d 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -190,18 +190,6 @@ WHERE\n \"\"\"SELECT PARSE_JSON('{\"food\":{\"fruit\":\"banana\"}}'):food.fruit::VARCHAR\"\"\",\n \"\"\"SELECT CAST(GET_PATH(PARSE_JSON('{\"food\":{\"fruit\":\"banana\"}}'), 'food.fruit') AS VARCHAR)\"\"\",\n )\n- self.validate_identity(\n- \"SELECT * FROM foo at\",\n- \"SELECT * FROM foo AS at\",\n- )\n- self.validate_identity(\n- \"SELECT * FROM foo before\",\n- \"SELECT * FROM foo AS before\",\n- )\n- self.validate_identity(\n- \"SELECT * FROM foo at (col)\",\n- \"SELECT * FROM foo AS at(col)\",\n- )\n self.validate_identity(\n \"SELECT * FROM unnest(x) with ordinality\",\n \"SELECT * FROM TABLE(FLATTEN(INPUT => x)) AS _u(seq, key, path, index, value, this)\",\n@@ -1204,6 +1192,17 @@ WHERE\n \"SELECT oldt.*, newt.* FROM my_table BEFORE (STATEMENT => '8e5d0ca9-005e-44e6-b858-a8f5b37c5726') AS oldt FULL OUTER JOIN my_table AT (STATEMENT => '8e5d0ca9-005e-44e6-b858-a8f5b37c5726') AS newt ON oldt.id = newt.id WHERE oldt.id IS NULL OR newt.id IS NULL\",\n )\n \n+ # Make sure that the historical data keywords can still be used as aliases\n+ for historical_data_prefix in (\"AT\", \"BEFORE\", \"END\", \"CHANGES\"):\n+ for schema_suffix in (\"\", \"(col)\"):\n+ with self.subTest(\n+ f\"Testing historical data prefix alias: {historical_data_prefix}{schema_suffix}\"\n+ ):\n+ self.validate_identity(\n+ f\"SELECT * FROM foo {historical_data_prefix}{schema_suffix}\",\n+ f\"SELECT * FROM foo AS {historical_data_prefix}{schema_suffix}\",\n+ )\n+\n def test_ddl(self):\n for constraint_prefix in (\"WITH \", \"\"):\n with self.subTest(f\"Constraint prefix: {constraint_prefix}\"):\n@@ -2033,3 +2032,15 @@ SINGLE = TRUE\"\"\",\n \n self.validate_identity(\"ALTER TABLE foo UNSET TAG a, b, c\")\n self.validate_identity(\"ALTER TABLE foo UNSET DATA_RETENTION_TIME_IN_DAYS, CHANGE_TRACKING\")\n+\n+ def test_from_changes(self):\n+ self.validate_identity(\n+ \"\"\"SELECT C1 FROM t1 CHANGES (INFORMATION => APPEND_ONLY) AT (STREAM => 's1') END (TIMESTAMP => $ts2)\"\"\"\n+ )\n+ self.validate_identity(\n+ \"\"\"SELECT C1 FROM t1 CHANGES (INFORMATION => APPEND_ONLY) BEFORE (STATEMENT => 'STMT_ID') END (TIMESTAMP => $ts2)\"\"\"\n+ )\n+ self.validate_identity(\n+ \"\"\"SELECT 1 FROM some_table CHANGES (INFORMATION => APPEND_ONLY) AT (TIMESTAMP => TO_TIMESTAMP_TZ('2024-07-01 00:00:00+00:00')) END (TIMESTAMP => TO_TIMESTAMP_TZ('2024-07-01 14:28:59.999999+00:00'))\"\"\",\n+ \"\"\"SELECT 1 FROM some_table CHANGES (INFORMATION => APPEND_ONLY) AT (TIMESTAMP => CAST('2024-07-01 00:00:00+00:00' AS TIMESTAMPTZ)) END (TIMESTAMP => CAST('2024-07-01 14:28:59.999999+00:00' AS TIMESTAMPTZ))\"\"\",\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_snowflake.py::TestSnowflake::test_from_changes"]}, {"instance_id": "tobymao__sqlglot-3745", "base_commit": "44977e97e4188322b92eb1269aa321aa689f2dcf", "gold_patch": "diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py\nindex fd03798b..e6fcf356 100644\n--- a/sqlglot/dialects/bigquery.py\n+++ b/sqlglot/dialects/bigquery.py\n@@ -735,6 +735,13 @@ class BigQuery(Dialect):\n exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,\n }\n \n+ # WINDOW comes after QUALIFY\n+ # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#window_clause\n+ AFTER_HAVING_MODIFIER_TRANSFORMS = {\n+ \"qualify\": generator.Generator.AFTER_HAVING_MODIFIER_TRANSFORMS[\"qualify\"],\n+ \"windows\": generator.Generator.AFTER_HAVING_MODIFIER_TRANSFORMS[\"windows\"],\n+ }\n+\n # from: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#reserved_keywords\n RESERVED_KEYWORDS = {\n \"all\",\ndiff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 75217499..3841ea64 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -2,7 +2,7 @@ from __future__ import annotations\n \n import typing as t\n \n-from sqlglot import exp, generator, parser, tokens, transforms\n+from sqlglot import exp, generator, parser, tokens\n from sqlglot.dialects.dialect import (\n Dialect,\n arg_max_or_min_no_count,\n@@ -789,7 +789,6 @@ class ClickHouse(Dialect):\n exp.Quantile: _quantile_sql,\n exp.RegexpLike: lambda self, e: self.func(\"match\", e.this, e.expression),\n exp.Rand: rename_func(\"randCanonical\"),\n- exp.Select: transforms.preprocess([transforms.eliminate_qualify]),\n exp.StartsWith: rename_func(\"startsWith\"),\n exp.StrPosition: lambda self, e: self.func(\n \"position\", e.this, e.args.get(\"substr\"), e.args.get(\"position\")\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex c2a6c557..482e5f34 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -406,13 +406,13 @@ class Generator(metaclass=_Generator):\n AFTER_HAVING_MODIFIER_TRANSFORMS = {\n \"cluster\": lambda self, e: self.sql(e, \"cluster\"),\n \"distribute\": lambda self, e: self.sql(e, \"distribute\"),\n- \"qualify\": lambda self, e: self.sql(e, \"qualify\"),\n \"sort\": lambda self, e: self.sql(e, \"sort\"),\n \"windows\": lambda self, e: (\n self.seg(\"WINDOW \") + self.expressions(e, key=\"windows\", flat=True)\n if e.args.get(\"windows\")\n else \"\"\n ),\n+ \"qualify\": lambda self, e: self.sql(e, \"qualify\"),\n }\n \n TOKEN_MAPPING: t.Dict[TokenType, str] = {}\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex ef84d488..a31cc24a 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -83,6 +83,9 @@ class TestClickhouse(Validator):\n self.validate_identity(\"TRUNCATE TABLE t1 ON CLUSTER test_cluster\")\n self.validate_identity(\"TRUNCATE DATABASE db\")\n self.validate_identity(\"TRUNCATE DATABASE db ON CLUSTER test_cluster\")\n+ self.validate_identity(\n+ \"SELECT number, COUNT() OVER (PARTITION BY number % 3) AS partition_count FROM numbers(10) WINDOW window_name AS (PARTITION BY number) QUALIFY partition_count = 4 ORDER BY number\"\n+ )\n self.validate_identity(\n \"SELECT id, quantileGK(100, 0.95)(reading) OVER (PARTITION BY id ORDER BY id RANGE BETWEEN 30000 PRECEDING AND CURRENT ROW) AS window FROM table\"\n )\ndiff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py\nindex c0afb2f4..44839e9e 100644\n--- a/tests/dialects/test_dialect.py\n+++ b/tests/dialects/test_dialect.py\n@@ -2267,7 +2267,7 @@ SELECT\n write={\n \"duckdb\": \"SELECT * FROM t QUALIFY COUNT(*) OVER () > 1\",\n \"snowflake\": \"SELECT * FROM t QUALIFY COUNT(*) OVER () > 1\",\n- \"clickhouse\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n+ \"clickhouse\": \"SELECT * FROM t QUALIFY COUNT(*) OVER () > 1\",\n \"mysql\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n \"oracle\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) _t WHERE _w > 1\",\n \"postgres\": \"SELECT * FROM (SELECT *, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n@@ -2279,7 +2279,7 @@ SELECT\n write={\n \"duckdb\": 'SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\" FROM t QUALIFY COUNT(*) OVER () > 1',\n \"snowflake\": 'SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\" FROM t QUALIFY COUNT(*) OVER () > 1',\n- \"clickhouse\": 'SELECT \"user id\", some_id, other_id, \"2 nd id\" FROM (SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\", COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1',\n+ \"clickhouse\": 'SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\" FROM t QUALIFY COUNT(*) OVER () > 1',\n \"mysql\": \"SELECT `user id`, some_id, other_id, `2 nd id` FROM (SELECT `user id`, some_id, 1 AS other_id, 2 AS `2 nd id`, COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1\",\n \"oracle\": 'SELECT \"user id\", some_id, other_id, \"2 nd id\" FROM (SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\", COUNT(*) OVER () AS _w FROM t) _t WHERE _w > 1',\n \"postgres\": 'SELECT \"user id\", some_id, other_id, \"2 nd id\" FROM (SELECT \"user id\", some_id, 1 AS other_id, 2 AS \"2 nd id\", COUNT(*) OVER () AS _w FROM t) AS _t WHERE _w > 1',\ndiff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex e0b0131f..395cbe65 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -361,6 +361,10 @@ class TestDuckDB(Validator):\n self.validate_identity(\n \"SELECT * FROM (PIVOT Cities ON Year USING SUM(Population) GROUP BY Country) AS pivot_alias\"\n )\n+ self.validate_identity(\n+ # QUALIFY comes after WINDOW\n+ \"SELECT schema_name, function_name, ROW_NUMBER() OVER my_window AS function_rank FROM DUCKDB_FUNCTIONS() WINDOW my_window AS (PARTITION BY schema_name ORDER BY function_name) QUALIFY ROW_NUMBER() OVER my_window < 3\"\n+ )\n self.validate_identity(\"DATE_SUB('YEAR', col, '2020-01-01')\").assert_is(exp.Anonymous)\n self.validate_identity(\"DATESUB('YEAR', col, '2020-01-01')\").assert_is(exp.Anonymous)\n \n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_dialect.py::TestDialect::test_qualify", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"]}, {"instance_id": "tobymao__sqlglot-3756", "base_commit": "15ca924ac6e8a72396a882c394856e466cae9ac3", "gold_patch": "diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py\nindex da212869..3ba72ea7 100644\n--- a/sqlglot/dialects/dialect.py\n+++ b/sqlglot/dialects/dialect.py\n@@ -356,6 +356,11 @@ class Dialect(metaclass=_Dialect):\n EXPAND_ALIAS_REFS_EARLY_ONLY_IN_GROUP_BY = False\n \"\"\"Whether alias reference expansion before qualification should only happen for the GROUP BY clause.\"\"\"\n \n+ SUPPORTS_ORDER_BY_ALL = False\n+ \"\"\"\n+ Whether ORDER BY ALL is supported (expands to all the selected columns) as in DuckDB, Spark3/Databricks\n+ \"\"\"\n+\n # --- Autofilled ---\n \n tokenizer_class = Tokenizer\ndiff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py\nindex c8313054..0f3c9ee3 100644\n--- a/sqlglot/dialects/duckdb.py\n+++ b/sqlglot/dialects/duckdb.py\n@@ -172,6 +172,7 @@ class DuckDB(Dialect):\n SAFE_DIVISION = True\n INDEX_OFFSET = 1\n CONCAT_COALESCE = True\n+ SUPPORTS_ORDER_BY_ALL = True\n \n # https://duckdb.org/docs/sql/introduction.html#creating-a-new-table\n NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE\ndiff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py\nindex 2f2ec878..623aaba7 100644\n--- a/sqlglot/dialects/spark.py\n+++ b/sqlglot/dialects/spark.py\n@@ -90,6 +90,8 @@ def _dateadd_sql(self: Spark.Generator, expression: exp.TsOrDsAdd | exp.Timestam\n \n \n class Spark(Spark2):\n+ SUPPORTS_ORDER_BY_ALL = True\n+\n class Tokenizer(Spark2.Tokenizer):\n STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = False\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 482e5f34..c2ad9ade 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -512,6 +512,7 @@ class Generator(metaclass=_Generator):\n \n # Expressions whose comments are separated from them for better formatting\n WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (\n+ exp.Command,\n exp.Create,\n exp.Delete,\n exp.Drop,\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 2718a135..f9ec3fd4 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -1478,7 +1478,10 @@ class Parser(metaclass=_Parser):\n def _parse_command(self) -> exp.Command:\n self._warn_unsupported()\n return self.expression(\n- exp.Command, this=self._prev.text.upper(), expression=self._parse_string()\n+ exp.Command,\n+ comments=self._prev_comments,\n+ this=self._prev.text.upper(),\n+ expression=self._parse_string(),\n )\n \n def _try_parse(self, parse_method: t.Callable[[], T], retreat: bool = False) -> t.Optional[T]:\n@@ -3842,6 +3845,9 @@ class Parser(metaclass=_Parser):\n if not this:\n return None\n \n+ if this.name.upper() == \"ALL\" and self.dialect.SUPPORTS_ORDER_BY_ALL:\n+ this = exp.var(\"ALL\")\n+\n asc = self._match(TokenType.ASC)\n desc = self._match(TokenType.DESC) or (asc and False)\n \n", "test_patch": "diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py\nindex 803ac11a..75be8480 100644\n--- a/tests/dialects/test_bigquery.py\n+++ b/tests/dialects/test_bigquery.py\n@@ -1427,6 +1427,12 @@ WHERE\n transpile(\"DATE_ADD(x, day)\", read=\"bigquery\")\n \n def test_warnings(self):\n+ with self.assertLogs(parser_logger) as cm:\n+ self.validate_identity(\n+ \"/* some comment */ DECLARE foo DATE DEFAULT DATE_SUB(current_date, INTERVAL 2 day)\"\n+ )\n+ self.assertIn(\"contains unsupported syntax\", cm.output[0])\n+\n with self.assertLogs(helper_logger) as cm:\n self.validate_identity(\n \"WITH cte(c) AS (SELECT * FROM t) SELECT * FROM cte\",\ndiff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py\nindex 44839e9e..a6ac69a7 100644\n--- a/tests/dialects/test_dialect.py\n+++ b/tests/dialects/test_dialect.py\n@@ -1164,6 +1164,13 @@ class TestDialect(Validator):\n },\n )\n \n+ order_by_all_sql = \"SELECT * FROM t ORDER BY ALL\"\n+ self.validate_identity(order_by_all_sql).find(exp.Ordered).this.assert_is(exp.Column)\n+\n+ for dialect in (\"duckdb\", \"spark\", \"databricks\"):\n+ with self.subTest(f\"Testing ORDER BY ALL in {dialect}\"):\n+ parse_one(order_by_all_sql, read=dialect).find(exp.Ordered).this.assert_is(exp.Var)\n+\n def test_json(self):\n self.validate_all(\n \"\"\"JSON_EXTRACT(x, '$[\"a b\"]')\"\"\",\n", "FAIL_TO_PASS": ["tests/dialects/test_bigquery.py::TestBigQuery::test_warnings", "tests/dialects/test_dialect.py::TestDialect::test_order_by"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_snowflake.py::TestSnowflake::test_from_changes", "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_dialect.py::TestDialect::test_qualify", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_bigquery.py::TestBigQuery::test_warnings", "tests/dialects/test_dialect.py::TestDialect::test_order_by"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "neovasili__tflens-35_x3", "level": 3, "source": "swerebench", "repo": "neovasili/tflens", "image": "swerebench/sweb.eval.x86_64.neovasili_1776_tflens-35:latest", "base_commit": "8fed041deb04b1abef816991fe185a7c0821c5ee", "num_bugs": 3, "bugs": [{"instance_id": "neovasili__tflens-35", "base_commit": "8fed041deb04b1abef816991fe185a7c0821c5ee", "gold_patch": "diff --git a/README.md b/README.md\nindex 3b089dd..b4b09a0 100644\n--- a/README.md\n+++ b/README.md\n@@ -78,6 +78,8 @@ optional arguments:\n Applies a regular expression to the module field in order to filter the resources list to output\n -n FILTER_NAME, --filter-name FILTER_NAME\n Applies a regular expression to the name field in order to filter the resources list to output\n+ -t FILTER_TYPE, --filter-type FILTER_TYPE\n+ Applies a regular expression to the type field in order to filter the resources list to output\n ```\n \n ### Examples\ndiff --git a/tflens/__main__.py b/tflens/__main__.py\nindex 8991726..f7f87a2 100644\n--- a/tflens/__main__.py\n+++ b/tflens/__main__.py\n@@ -51,6 +51,14 @@ parser.add_argument('-n', '--filter-name',\n filter the resources list to output\",\n default=\"\")\n \n+parser.add_argument('-t', '--filter-type',\n+ type=str,\n+ action=\"store\",\n+ dest=\"filter_type\",\n+ help=\"Applies a regular expression to the type field in order to \\\n+ filter the resources list to output\",\n+ default=\"\")\n+\n args = parser.parse_args()\n \n ARGS_REMOTE = args.remote\n@@ -58,6 +66,7 @@ ARGS_FILE_LOCATION = args.file_location\n ARGS_OUTPUT = args.output\n ARGS_FILTER_MODULE = args.filter_module\n ARGS_FILTER_NAME = args.filter_name\n+ARGS_FILTER_TYPE = args.filter_type\n \n if not ARGS_FILE_LOCATION:\n ARGS_FILE_LOCATION = \"{}/terraform.tfstate\".format(Path().absolute())\n@@ -71,6 +80,7 @@ def main():\n tfstate_controller = remote_router[ARGS_REMOTE](\n file_location=ARGS_FILE_LOCATION,\n name_filter_expression=ARGS_FILTER_NAME,\n+ type_filter_expression=ARGS_FILTER_TYPE,\n module_filter_expression=ARGS_FILTER_MODULE\n )\n \ndiff --git a/tflens/controller/tfstate.py b/tflens/controller/tfstate.py\nindex 7f0fec6..478c492 100644\n--- a/tflens/controller/tfstate.py\n+++ b/tflens/controller/tfstate.py\n@@ -15,6 +15,7 @@ class TfStateController():\n self,\n tfstate_content: dict,\n name_filter_expression: str=None,\n+ type_filter_expression: str=None,\n module_filter_expression: str=None\n ):\n self.__tfstate = TfState(\n@@ -22,6 +23,7 @@ class TfStateController():\n )\n self.__resources = TfStateFilterHelper(\n name_filter_expression=name_filter_expression,\n+ type_filter_expression=type_filter_expression,\n module_filter_expression=module_filter_expression,\n resources=self.__tfstate.get_resources()\n ).apply_filter()\n@@ -53,6 +55,7 @@ class LocalTfStateController(TfStateController):\n self,\n file_location: str,\n module_filter_expression: str=None,\n+ type_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__local_tfstate_service = LocalTfStateService(\n@@ -62,6 +65,7 @@ class LocalTfStateController(TfStateController):\n super().__init__(\n tfstate_content=self.__local_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n+ type_filter_expression=type_filter_expression,\n module_filter_expression=module_filter_expression\n )\n \n@@ -71,6 +75,7 @@ class RemoteS3TfStateController(TfStateController):\n self,\n file_location: str,\n module_filter_expression: str=None,\n+ type_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__remote_s3_tfstate_service = RemoteS3TfStateService(\n@@ -80,5 +85,6 @@ class RemoteS3TfStateController(TfStateController):\n super().__init__(\n tfstate_content=self.__remote_s3_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n+ type_filter_expression=type_filter_expression,\n module_filter_expression=module_filter_expression\n )\ndiff --git a/tflens/helper/filter.py b/tflens/helper/filter.py\nindex d5cd16c..f6ce147 100644\n--- a/tflens/helper/filter.py\n+++ b/tflens/helper/filter.py\n@@ -27,15 +27,25 @@ class NameFilterHelper(FilterHelper):\n object_attribute_value=resource.get_name()\n )\n \n+class TypeFilterHelper(FilterHelper):\n+\n+ def __init__(self, filter_expression: str, resource: TfStateResource):\n+ super().__init__(\n+ filter_expression=filter_expression,\n+ object_attribute_value=resource.get_type()\n+ )\n+\n class TfStateFilterHelper():\n \n def __init__(\n self,\n name_filter_expression: str=None,\n+ type_filter_expression: str=None,\n module_filter_expression: str=None,\n resources: list=None\n ):\n self.__name_filter_expression = name_filter_expression\n+ self.__type_filter_expression = type_filter_expression\n self.__module_filter_expression = module_filter_expression\n self.__resources = resources\n \n@@ -45,16 +55,21 @@ class TfStateFilterHelper():\n for resource in self.__resources or []:\n pass_name_filter = True\n pass_module_filter = True\n+ pass_type_filter = True\n \n if self.__name_filter_expression:\n filter_helper = NameFilterHelper(filter_expression=self.__name_filter_expression, resource=resource)\n pass_name_filter = filter_helper.check_filter()\n \n+ if self.__type_filter_expression:\n+ filter_helper = TypeFilterHelper(filter_expression=self.__type_filter_expression, resource=resource)\n+ pass_type_filter = filter_helper.check_filter()\n+\n if self.__module_filter_expression:\n filter_helper = ModuleFilterHelper(filter_expression=self.__module_filter_expression, resource=resource)\n pass_module_filter = filter_helper.check_filter()\n \n- if pass_module_filter and pass_name_filter:\n+ if pass_module_filter and pass_name_filter and pass_type_filter:\n filtered_list.append(resource)\n \n return filtered_list\ndiff --git a/tflens/model/tfstate_resource.py b/tflens/model/tfstate_resource.py\nindex be6a07a..afd3dbf 100644\n--- a/tflens/model/tfstate_resource.py\n+++ b/tflens/model/tfstate_resource.py\n@@ -30,6 +30,9 @@ class TfStateResource():\n def get_name(self):\n return self.__name\n \n+ def get_type(self):\n+ return self.__type\n+\n def get_parent_module(self):\n return self.__module.split('.')[1] if self.__module else '-'\n \n", "test_patch": "diff --git a/tests/controllers_test.py b/tests/controllers_test.py\nindex 61504b4..65f8078 100644\n--- a/tests/controllers_test.py\n+++ b/tests/controllers_test.py\n@@ -114,6 +114,28 @@ class TestLocalTfStateController(unittest.TestCase):\n \n self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n \n+ def test_local_show_resources_matching_type_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ type_filter_expression=\"aws_caller_identity\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), self.print_table_output)\n+\n+ def test_local_show_resources_not_matching_type_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ type_filter_expression=\"Aws_caller_identity\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n+\n def test_local_create_markdown_file(self):\n local_tfstate_controller = LocalTfStateController(self.existing_file)\n local_tfstate_controller.create_markdown_file()\n", "FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_type_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_type_filter"]}, {"instance_id": "neovasili__tflens-36", "base_commit": "ba81fda814f0f1401a79f52365d9ba1d3ca5799d", "gold_patch": "diff --git a/README.md b/README.md\nindex b4b09a0..5676c16 100644\n--- a/README.md\n+++ b/README.md\n@@ -80,6 +80,8 @@ optional arguments:\n Applies a regular expression to the name field in order to filter the resources list to output\n -t FILTER_TYPE, --filter-type FILTER_TYPE\n Applies a regular expression to the type field in order to filter the resources list to output\n+ -p FILTER_PROVIDER, --filter-provider FILTER_PROVIDER\n+ Applies a regular expression to the provider field in order to filter the resources list to output\n ```\n \n ### Examples\ndiff --git a/tflens/__main__.py b/tflens/__main__.py\nindex f7f87a2..fe1ca3d 100644\n--- a/tflens/__main__.py\n+++ b/tflens/__main__.py\n@@ -59,6 +59,14 @@ parser.add_argument('-t', '--filter-type',\n filter the resources list to output\",\n default=\"\")\n \n+parser.add_argument('-p', '--filter-provider',\n+ type=str,\n+ action=\"store\",\n+ dest=\"filter_provider\",\n+ help=\"Applies a regular expression to the provider field in order to \\\n+ filter the resources list to output\",\n+ default=\"\")\n+\n args = parser.parse_args()\n \n ARGS_REMOTE = args.remote\n@@ -67,6 +75,7 @@ ARGS_OUTPUT = args.output\n ARGS_FILTER_MODULE = args.filter_module\n ARGS_FILTER_NAME = args.filter_name\n ARGS_FILTER_TYPE = args.filter_type\n+ARGS_FILTER_PROVIDER = args.filter_provider\n \n if not ARGS_FILE_LOCATION:\n ARGS_FILE_LOCATION = \"{}/terraform.tfstate\".format(Path().absolute())\n@@ -81,6 +90,7 @@ def main():\n file_location=ARGS_FILE_LOCATION,\n name_filter_expression=ARGS_FILTER_NAME,\n type_filter_expression=ARGS_FILTER_TYPE,\n+ provider_filter_expression=ARGS_FILTER_PROVIDER,\n module_filter_expression=ARGS_FILTER_MODULE\n )\n \ndiff --git a/tflens/controller/tfstate.py b/tflens/controller/tfstate.py\nindex 478c492..0f4c7a5 100644\n--- a/tflens/controller/tfstate.py\n+++ b/tflens/controller/tfstate.py\n@@ -16,6 +16,7 @@ class TfStateController():\n tfstate_content: dict,\n name_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n module_filter_expression: str=None\n ):\n self.__tfstate = TfState(\n@@ -24,6 +25,7 @@ class TfStateController():\n self.__resources = TfStateFilterHelper(\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n+ provider_filter_expression=provider_filter_expression,\n module_filter_expression=module_filter_expression,\n resources=self.__tfstate.get_resources()\n ).apply_filter()\n@@ -56,6 +58,7 @@ class LocalTfStateController(TfStateController):\n file_location: str,\n module_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__local_tfstate_service = LocalTfStateService(\n@@ -66,6 +69,7 @@ class LocalTfStateController(TfStateController):\n tfstate_content=self.__local_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n+ provider_filter_expression=provider_filter_expression,\n module_filter_expression=module_filter_expression\n )\n \n@@ -76,6 +80,7 @@ class RemoteS3TfStateController(TfStateController):\n file_location: str,\n module_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n name_filter_expression: str=None\n ):\n self.__remote_s3_tfstate_service = RemoteS3TfStateService(\n@@ -86,5 +91,6 @@ class RemoteS3TfStateController(TfStateController):\n tfstate_content=self.__remote_s3_tfstate_service.read_content(),\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n+ provider_filter_expression=provider_filter_expression,\n module_filter_expression=module_filter_expression\n )\ndiff --git a/tflens/helper/filter.py b/tflens/helper/filter.py\nindex f6ce147..ee86ff3 100644\n--- a/tflens/helper/filter.py\n+++ b/tflens/helper/filter.py\n@@ -35,17 +35,27 @@ class TypeFilterHelper(FilterHelper):\n object_attribute_value=resource.get_type()\n )\n \n+class ProviderFilterHelper(FilterHelper):\n+\n+ def __init__(self, filter_expression: str, resource: TfStateResource):\n+ super().__init__(\n+ filter_expression=filter_expression,\n+ object_attribute_value=resource.get_type()\n+ )\n+\n class TfStateFilterHelper():\n \n def __init__(\n self,\n name_filter_expression: str=None,\n type_filter_expression: str=None,\n+ provider_filter_expression: str=None,\n module_filter_expression: str=None,\n resources: list=None\n ):\n self.__name_filter_expression = name_filter_expression\n self.__type_filter_expression = type_filter_expression\n+ self.__provider_filter_expression = provider_filter_expression\n self.__module_filter_expression = module_filter_expression\n self.__resources = resources\n \n@@ -56,6 +66,7 @@ class TfStateFilterHelper():\n pass_name_filter = True\n pass_module_filter = True\n pass_type_filter = True\n+ pass_provider_filter = True\n \n if self.__name_filter_expression:\n filter_helper = NameFilterHelper(filter_expression=self.__name_filter_expression, resource=resource)\n@@ -65,11 +76,15 @@ class TfStateFilterHelper():\n filter_helper = TypeFilterHelper(filter_expression=self.__type_filter_expression, resource=resource)\n pass_type_filter = filter_helper.check_filter()\n \n+ if self.__provider_filter_expression:\n+ filter_helper = ProviderFilterHelper(filter_expression=self.__provider_filter_expression, resource=resource)\n+ pass_provider_filter = filter_helper.check_filter()\n+\n if self.__module_filter_expression:\n filter_helper = ModuleFilterHelper(filter_expression=self.__module_filter_expression, resource=resource)\n pass_module_filter = filter_helper.check_filter()\n \n- if pass_module_filter and pass_name_filter and pass_type_filter:\n+ if pass_module_filter and pass_name_filter and pass_type_filter and pass_provider_filter:\n filtered_list.append(resource)\n \n return filtered_list\n", "test_patch": "diff --git a/tests/controllers_test.py b/tests/controllers_test.py\nindex 65f8078..b250a98 100644\n--- a/tests/controllers_test.py\n+++ b/tests/controllers_test.py\n@@ -136,6 +136,28 @@ class TestLocalTfStateController(unittest.TestCase):\n \n self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n \n+ def test_local_show_resources_matching_provider_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ provider_filter_expression=\"aws\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), self.print_table_output)\n+\n+ def test_local_show_resources_not_matching_provider_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ provider_filter_expression=\"Aws\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n+\n def test_local_create_markdown_file(self):\n local_tfstate_controller = LocalTfStateController(self.existing_file)\n local_tfstate_controller.create_markdown_file()\n", "FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_provider_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_provider_filter"]}, {"instance_id": "neovasili__tflens-37", "base_commit": "658445946b11c2776992bec4ae31e12e829a5136", "gold_patch": "diff --git a/README.md b/README.md\nindex 5676c16..1c92c04 100644\n--- a/README.md\n+++ b/README.md\n@@ -82,6 +82,8 @@ optional arguments:\n Applies a regular expression to the type field in order to filter the resources list to output\n -p FILTER_PROVIDER, --filter-provider FILTER_PROVIDER\n Applies a regular expression to the provider field in order to filter the resources list to output\n+ -d FILTER_MODE, --filter-mode FILTER_MODE\n+ Applies a regular expression to the mode field in order to filter the resources list to output\n ```\n \n ### Examples\ndiff --git a/tflens/__main__.py b/tflens/__main__.py\nindex fe1ca3d..2e696e3 100644\n--- a/tflens/__main__.py\n+++ b/tflens/__main__.py\n@@ -67,6 +67,14 @@ parser.add_argument('-p', '--filter-provider',\n filter the resources list to output\",\n default=\"\")\n \n+parser.add_argument('-d', '--filter-mode',\n+ type=str,\n+ action=\"store\",\n+ dest=\"filter_mode\",\n+ help=\"Applies a regular expression to the mode field in order to \\\n+ filter the resources list to output\",\n+ default=\"\")\n+\n args = parser.parse_args()\n \n ARGS_REMOTE = args.remote\n@@ -76,6 +84,7 @@ ARGS_FILTER_MODULE = args.filter_module\n ARGS_FILTER_NAME = args.filter_name\n ARGS_FILTER_TYPE = args.filter_type\n ARGS_FILTER_PROVIDER = args.filter_provider\n+ARGS_FILER_MODE = args.filter_mode\n \n if not ARGS_FILE_LOCATION:\n ARGS_FILE_LOCATION = \"{}/terraform.tfstate\".format(Path().absolute())\n@@ -91,7 +100,8 @@ def main():\n name_filter_expression=ARGS_FILTER_NAME,\n type_filter_expression=ARGS_FILTER_TYPE,\n provider_filter_expression=ARGS_FILTER_PROVIDER,\n- module_filter_expression=ARGS_FILTER_MODULE\n+ module_filter_expression=ARGS_FILTER_MODULE,\n+ mode_filter_expression=ARGS_FILER_MODE\n )\n \n output_router = {\ndiff --git a/tflens/controller/tfstate.py b/tflens/controller/tfstate.py\nindex 0f4c7a5..bafd4cb 100644\n--- a/tflens/controller/tfstate.py\n+++ b/tflens/controller/tfstate.py\n@@ -17,7 +17,8 @@ class TfStateController():\n name_filter_expression: str=None,\n type_filter_expression: str=None,\n provider_filter_expression: str=None,\n- module_filter_expression: str=None\n+ module_filter_expression: str=None,\n+ mode_filter_expression: str=None\n ):\n self.__tfstate = TfState(\n content=tfstate_content\n@@ -27,6 +28,7 @@ class TfStateController():\n type_filter_expression=type_filter_expression,\n provider_filter_expression=provider_filter_expression,\n module_filter_expression=module_filter_expression,\n+ mode_filter_expression=mode_filter_expression,\n resources=self.__tfstate.get_resources()\n ).apply_filter()\n \n@@ -59,7 +61,8 @@ class LocalTfStateController(TfStateController):\n module_filter_expression: str=None,\n type_filter_expression: str=None,\n provider_filter_expression: str=None,\n- name_filter_expression: str=None\n+ name_filter_expression: str=None,\n+ mode_filter_expression: str=None\n ):\n self.__local_tfstate_service = LocalTfStateService(\n file_location=file_location\n@@ -70,7 +73,8 @@ class LocalTfStateController(TfStateController):\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n provider_filter_expression=provider_filter_expression,\n- module_filter_expression=module_filter_expression\n+ module_filter_expression=module_filter_expression,\n+ mode_filter_expression=mode_filter_expression\n )\n \n class RemoteS3TfStateController(TfStateController):\n@@ -81,7 +85,8 @@ class RemoteS3TfStateController(TfStateController):\n module_filter_expression: str=None,\n type_filter_expression: str=None,\n provider_filter_expression: str=None,\n- name_filter_expression: str=None\n+ name_filter_expression: str=None,\n+ mode_filter_expression: str=None\n ):\n self.__remote_s3_tfstate_service = RemoteS3TfStateService(\n file_location=file_location\n@@ -92,5 +97,6 @@ class RemoteS3TfStateController(TfStateController):\n name_filter_expression=name_filter_expression,\n type_filter_expression=type_filter_expression,\n provider_filter_expression=provider_filter_expression,\n- module_filter_expression=module_filter_expression\n+ module_filter_expression=module_filter_expression,\n+ mode_filter_expression=mode_filter_expression\n )\ndiff --git a/tflens/helper/filter.py b/tflens/helper/filter.py\nindex ee86ff3..58bba51 100644\n--- a/tflens/helper/filter.py\n+++ b/tflens/helper/filter.py\n@@ -9,7 +9,9 @@ class FilterHelper():\n self.__object_attribute_value = object_attribute_value\n \n def check_filter(self):\n- return re.match(self.__filter_expression, self.__object_attribute_value)\n+ compiled_pattern = re.compile(self.__filter_expression)\n+\n+ return compiled_pattern.search(self.__object_attribute_value)\n \n class ModuleFilterHelper(FilterHelper):\n \n@@ -40,7 +42,15 @@ class ProviderFilterHelper(FilterHelper):\n def __init__(self, filter_expression: str, resource: TfStateResource):\n super().__init__(\n filter_expression=filter_expression,\n- object_attribute_value=resource.get_type()\n+ object_attribute_value=resource.get_provider()\n+ )\n+\n+class ModeFilterHelper(FilterHelper):\n+\n+ def __init__(self, filter_expression: str, resource: TfStateResource):\n+ super().__init__(\n+ filter_expression=filter_expression,\n+ object_attribute_value=resource.get_mode()\n )\n \n class TfStateFilterHelper():\n@@ -51,12 +61,14 @@ class TfStateFilterHelper():\n type_filter_expression: str=None,\n provider_filter_expression: str=None,\n module_filter_expression: str=None,\n+ mode_filter_expression: str=None,\n resources: list=None\n ):\n self.__name_filter_expression = name_filter_expression\n self.__type_filter_expression = type_filter_expression\n self.__provider_filter_expression = provider_filter_expression\n self.__module_filter_expression = module_filter_expression\n+ self.__mode_filter_expression = mode_filter_expression\n self.__resources = resources\n \n def apply_filter(self):\n@@ -67,6 +79,7 @@ class TfStateFilterHelper():\n pass_module_filter = True\n pass_type_filter = True\n pass_provider_filter = True\n+ pass_mode_filter = True\n \n if self.__name_filter_expression:\n filter_helper = NameFilterHelper(filter_expression=self.__name_filter_expression, resource=resource)\n@@ -84,7 +97,11 @@ class TfStateFilterHelper():\n filter_helper = ModuleFilterHelper(filter_expression=self.__module_filter_expression, resource=resource)\n pass_module_filter = filter_helper.check_filter()\n \n- if pass_module_filter and pass_name_filter and pass_type_filter and pass_provider_filter:\n+ if self.__mode_filter_expression:\n+ filter_helper = ModeFilterHelper(filter_expression=self.__mode_filter_expression, resource=resource)\n+ pass_mode_filter = filter_helper.check_filter()\n+\n+ if pass_module_filter and pass_name_filter and pass_type_filter and pass_provider_filter and pass_mode_filter:\n filtered_list.append(resource)\n \n return filtered_list\ndiff --git a/tflens/model/tfstate_resource.py b/tflens/model/tfstate_resource.py\nindex afd3dbf..fa14840 100644\n--- a/tflens/model/tfstate_resource.py\n+++ b/tflens/model/tfstate_resource.py\n@@ -33,6 +33,12 @@ class TfStateResource():\n def get_type(self):\n return self.__type\n \n+ def get_provider(self):\n+ return self.__provider\n+\n+ def get_mode(self):\n+ return self.__mode\n+\n def get_parent_module(self):\n return self.__module.split('.')[1] if self.__module else '-'\n \n", "test_patch": "diff --git a/tests/controllers_test.py b/tests/controllers_test.py\nindex b250a98..6560a65 100644\n--- a/tests/controllers_test.py\n+++ b/tests/controllers_test.py\n@@ -158,6 +158,58 @@ class TestLocalTfStateController(unittest.TestCase):\n \n self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n \n+ def test_local_show_resources_matching_mode_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ mode_filter_expression=\"data\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), self.print_table_output)\n+\n+ def test_local_show_resources_not_matching_mode_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ mode_filter_expression=\"Data\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n+\n+ def test_local_show_resources_matching_mixed_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ module_filter_expression=\"test\",\n+ name_filter_expression=\"current_user\",\n+ type_filter_expression=\"aws_caller_identity\",\n+ provider_filter_expression=\"aws\",\n+ mode_filter_expression=\"data\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), self.print_table_output)\n+\n+ def test_local_show_resources_not_matching_mixed_filter(self):\n+ local_tfstate_controller = LocalTfStateController(\n+ file_location=self.existing_file,\n+ module_filter_expression=\"test\",\n+ name_filter_expression=\"current_user\",\n+ type_filter_expression=\"aws_caller_identity\",\n+ provider_filter_expression=\"aws\",\n+ mode_filter_expression=\"Data\"\n+ )\n+ captured_output = io.StringIO()\n+ sys.stdout = captured_output\n+ local_tfstate_controller.show_resources()\n+\n+ self.assertEqual(captured_output.getvalue().replace('\\n', ''), '')\n+\n def test_local_create_markdown_file(self):\n local_tfstate_controller = LocalTfStateController(self.existing_file)\n local_tfstate_controller.create_markdown_file()\n", "FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_mixed_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_mode_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_mixed_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_mode_filter"]}], "all_FAIL_TO_PASS": ["tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_type_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_type_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_provider_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_provider_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_mixed_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_matching_mode_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_mixed_filter", "tests/controllers_test.py::TestLocalTfStateController::test_local_show_resources_not_matching_mode_filter"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NREL__hescore-hpxml-113_x3", "level": 3, "source": "swerebench", "repo": "NREL/hescore-hpxml", "image": "swerebench/sweb.eval.x86_64.nrel_1776_hescore-hpxml-113:latest", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "num_bugs": 3, "bugs": [{"instance_id": "NREL__hescore-hpxml-113", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "gold_patch": "diff --git a/docs/source/translation/zone_window.rst b/docs/source/translation/zone_window.rst\nindex 480fe5db..5062926c 100644\n--- a/docs/source/translation/zone_window.rst\n+++ b/docs/source/translation/zone_window.rst\n@@ -13,17 +13,21 @@ assumed to mean the sum of the areas of the windows that the ``Window`` element\n represents. Each ``Window`` is then assigned to a side of the building in one of\n two ways:\n \n- #. By association with a particular wall.\n #. By inspecting the azimuth or orientation of the window.\n+ #. By association with a particular wall.\n \n-If an HPXML window has the ``AttachedToWall`` element, the id reference in that\n-element is used to find the associated wall and the side of the building that\n-the window faces is inferred from the :ref:`wall orientation `.\n-\n-If there is not an ``AttachedToWall`` element, the side is determined via the\n-``Azimuth`` or ``Orientation`` elements with preference given to the\n-``Azimuth`` if present. If the window falls between two sides of the house, the\n-window area is divided between the sides of the house evenly. \n+If there is an ``Orientation`` or ``Azimuth`` element, the side is determined\n+via the one of those elements with preference given to the ``Azimuth`` if\n+present. If the window falls between two sides of the house, the window area is\n+divided between the sides of the house evenly. \n+\n+If ``Orientation`` or ``Azimuth`` are missing and the HPXML window has the\n+``AttachedToWall`` element, the id reference in that element is used to find the\n+associated wall and the side of the building that the window faces is inferred\n+from the :ref:`wall orientation `. If the window is attached to\n+a foundation wall, the orientation/azimuth must be provided on the ``Window``\n+element because foundation walls do not have orientation or azimuth elements\n+available.\n \n The areas on each side of the house are summed and the :ref:`window-prop` are\n determined independently for each side of the house. Since HPXML requires that\ndiff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 55a58b86..102d0f48 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -1530,29 +1530,33 @@ class HPXMLtoHEScoreTranslator(object):\n \n # Window side\n window_sides = []\n- attached_to_wall_id = xpath(hpxmlwndw, 'h:AttachedToWall/@idref')\n- if attached_to_wall_id is not None:\n- # Give preference to the Attached to Wall element to determine the side of the house.\n- for side, walls in list(hpxmlwalls.items()):\n- for wall in walls:\n- if attached_to_wall_id == wall['id']:\n- window_sides.append(side)\n- break\n+ window_id = xpath(hpxmlwndw, 'h:SystemIdentifier/@id')\n+ try:\n+ # Get the aziumuth or orientation if they exist\n+ wndw_azimuth = self.get_nearest_azimuth(xpath(hpxmlwndw, 'h:Azimuth/text()'),\n+ xpath(hpxmlwndw, 'h:Orientation/text()'))\n+ except TranslationError:\n+ # The window doesn't have orientation/azimuth information, get from wall\n+ attached_to_wall_id = xpath(hpxmlwndw, 'h:AttachedToWall/@idref')\n+ if attached_to_wall_id is not None:\n+ for side, walls in list(hpxmlwalls.items()):\n+ for wall in walls:\n+ if attached_to_wall_id == wall['id']:\n+ window_sides.append(side)\n+ break\n+ if not window_sides:\n+ raise TranslationError('The Window[SystemIdentifier/@id=\"{}\"] has no Azimuth or Orientation, and the Window/AttachedToWall/@idref of \"{}\" didn\\'t reference a Wall element.'.format(window_id, attached_to_wall_id)) # noqa: E501\n+ else:\n+ raise TranslationError(\n+ 'Window[SystemIdentifier/@id=\"{}\"] doesn\\'t have Azimuth, Orientation, or AttachedToWall. At least one is required.'.format(window_id) # noqa: E501\n+ )\n else:\n- # If there's not Attached to Wall element, figure it out from the Azimuth/Orientation\n+ # Azimuth found, associate with a side\n try:\n- wndw_azimuth = self.get_nearest_azimuth(xpath(hpxmlwndw, 'h:Azimuth/text()'),\n- xpath(hpxmlwndw, 'h:Orientation/text()'))\n- except TranslationError:\n- # there's no directional information in the window\n- raise TranslationError(\n- 'All windows need to have either an AttachedToWall, Orientation, or Azimuth sub element.')\n- else:\n- try:\n- window_sides = [sidemap[wndw_azimuth]]\n- except KeyError:\n- # the direction of the window is between sides, split area\n- window_sides = [sidemap[unspin_azimuth(wndw_azimuth + x)] for x in (-45, 45)]\n+ window_sides = [sidemap[wndw_azimuth]]\n+ except KeyError:\n+ # the direction of the window is between sides, split area\n+ window_sides = [sidemap[unspin_azimuth(wndw_azimuth + x)] for x in (-45, 45)]\n \n # Assign properties and areas to the correct side of the house\n windowd['area'] /= float(len(window_sides))\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex 1f6fd6cb..31a901bc 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -333,9 +333,23 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el.getparent().remove(el)\n self.assertRaisesRegexp(\n TranslationError,\n- r'All windows need to have either an AttachedToWall, Orientation, or Azimuth sub element\\.',\n+ r'Window\\[SystemIdentifier/@id=\"\\w+\"\\] doesn\\'t have Azimuth, Orientation, or AttachedToWall. At least one is required.', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n+ def test_window_only_attached_to_foundation_wall(self):\n+ tr = self._load_xmlfile('house4')\n+ window_orientation = self.xpath('//h:Window[1]/h:Orientation')\n+ window = window_orientation.getparent()\n+ etree.SubElement(window, tr.addns('h:AttachedToWall'), attrib={'idref': 'crawlwall'})\n+ self._do_compare('house4')\n+\n+ window.remove(window_orientation)\n+ self.assertRaisesRegexp(\n+ TranslationError,\n+ r'The Window\\[SystemIdentifier/@id=\"\\w+\"\\] has no Azimuth or Orientation, and the .* didn\\'t reference a Wall element.', # noqa E501\n+ tr.hpxml_to_hescore_dict\n+ )\n+\n def test_window_attached_to_wall(self):\n filebase = 'house6'\n tr = self._load_xmlfile(filebase)\n", "FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_window_orientation", "tests/tests.py::TestOtherHouses::test_window_only_attached_to_foundation_wall"]}, {"instance_id": "NREL__hescore-hpxml-115", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "gold_patch": "diff --git a/docs/source/translation/hvac.rst b/docs/source/translation/hvac.rst\nindex ec1bc7e9..cdc7169f 100644\n--- a/docs/source/translation/hvac.rst\n+++ b/docs/source/translation/hvac.rst\n@@ -1,26 +1,35 @@\n HVAC Systems\n ############\n \n-HEScore allows the definition of up to two HVAC systems which can each include a heating system, cooling system, and duct system.\n-To determine which HPXML elements are associated, the ``DistributionSystem`` subelement of\n-``HeatingSystem``, ``CoolingSystem``, ``HeatPump`` is used to find the link to ``HVACDistributionSystem``.\n-Systems that share the same ``HVACDistributionSystem`` are determined to be the same HVAC system for HEScore.\n-\n-Sometimes an HVAC system will not share ducts, for instance a central air conditioner and boiler.\n-In that case, if each of those systems serve a fraction of the home's load within 5% of each other\n-they will be combined into the same HVAC system for HEScore.\n-If a ``HeatingSystem`` and ``CoolingSystem`` that are associated with the same ``HVACDistributionSystem`` serve differing\n-portions of the house's heating and cooling load, that weight is averaged to find the combined system weight.\n-\n-If either a heating or cooling system meets all of the load and two systems of the opposite (cooling or heating, respectively)\n-are required to meet the same fraction of the load, the larger system is split into two for input into HEScore.\n-\n-To determine the fraction of the home's heating and cooling load each system serves,\n-each HPXML heating or cooling system is required to have ``FloorAreaServed`` or, alternatively ``FracLoadServed``.\n-The two combined HVAC systems that serve the greatest portion of the house's load are sent to HEScore.\n-\n-For details about how each kind of ``HeatingSystem``, ``CoolingSystem``, ``HeatPump``, and ``HVACDistributionSystem``\n-are translated into HEScore inputs, see the appropriate subsection:\n+HEScore allows the definition of up to two HVAC systems which can each include a\n+heating system, cooling system, and duct system. To determine which HPXML\n+elements are associated, the ``DistributionSystem`` subelement of\n+``HeatingSystem``, ``CoolingSystem``, ``HeatPump`` is used to find the link to\n+``HVACDistributionSystem``. Systems that share the same\n+``HVACDistributionSystem`` are determined to be the same HVAC system for\n+HEScore.\n+\n+Sometimes an HVAC system will not share ducts, for instance a central air\n+conditioner and boiler. In that case, if each of those systems serve a fraction\n+of the home's load within 5% of each other they will be combined into the same\n+HVAC system for HEScore. If a ``HeatingSystem`` and ``CoolingSystem`` that are\n+associated with the same ``HVACDistributionSystem`` serve differing portions of\n+the house's heating and cooling load, that weight is averaged to find the\n+combined system weight.\n+\n+If either a heating or cooling system meets all of the load and two systems of\n+the opposite (cooling or heating, respectively) are required to meet the same\n+fraction of the load, the larger system is split into two for input into\n+HEScore.\n+\n+To determine the fraction of the home's heating and cooling load each system\n+serves, each HPXML heating and cooling system is required to have\n+``FloorAreaServed`` or, alternatively ``FracLoadServed``. The two combined HVAC\n+systems that serve the greatest portion of the house's load are sent to HEScore.\n+\n+For details about how each kind of ``HeatingSystem``, ``CoolingSystem``,\n+``HeatPump``, and ``HVACDistributionSystem`` are translated into HEScore inputs,\n+see the appropriate subsection:\n \n .. toctree::\n :maxdepth: 1\ndiff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 55a58b86..dc737aa9 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -688,7 +688,7 @@ class HPXMLtoHEScoreTranslator(object):\n bldg['zone']['window_construction_same'] = False\n bldg['zone']['zone_wall'] = self._get_building_zone_wall(b, bldg['about'])\n bldg['systems'] = OrderedDict()\n- bldg['systems']['hvac'] = self._get_hvac(b)\n+ bldg['systems']['hvac'] = self._get_hvac(b, bldg['about'])\n bldg['systems']['domestic_hot_water'] = self._get_systems_dhw(b)\n generation = self._get_generation(b)\n if generation:\n@@ -1678,7 +1678,7 @@ class HPXMLtoHEScoreTranslator(object):\n zone_window['solar_screen'] = max(list(window_sunscreen_areas.items()), key=lambda x: x[1])[0]\n return zone_wall\n \n- def _get_hvac(self, b):\n+ def _get_hvac(self, b, bldg_about):\n \n def _get_dict_of_hpxml_elements_by_id(xpathexpr):\n return_dict = {}\n@@ -1786,48 +1786,41 @@ class HPXMLtoHEScoreTranslator(object):\n distribution_systems[key] = self._get_hvac_distribution(el)\n \n # Determine the weighting factors\n- def _choose_weighting_factor(systems_dict):\n- weighting_factor_priority = ['_floorarea', '_fracload']\n- found_weighting_factor = False\n- for weighting_factor in weighting_factor_priority:\n- weighting_factor_list = [item[weighting_factor] for item in list(systems_dict.values())]\n- if None not in weighting_factor_list and len(weighting_factor_list) > 0:\n- found_weighting_factor = True\n- break\n- if not found_weighting_factor:\n- if len(systems_dict) == 1:\n- list(systems_dict.values())[0]['_fracload'] = 1.0\n- weighting_factor_list = [1.0]\n- weighting_factor = '_fracload'\n- else:\n- raise TranslationError(\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed.')\n- return weighting_factor, sum(weighting_factor_list)\n- if heating_systems:\n- heating_weighting_factor, heating_weight_sum = _choose_weighting_factor(heating_systems)\n- else:\n- heating_weight_sum = 0\n- heating_weighting_factor = None\n- if cooling_systems:\n- cooling_weighting_factor, cooling_weight_sum = _choose_weighting_factor(cooling_systems)\n- else:\n- cooling_weight_sum = 0\n- cooling_weighting_factor = None\n \n- if cooling_systems and heating_systems and heating_weighting_factor != cooling_weighting_factor:\n+ # If there's only one heating or cooling system and no weighting elements, fill it in.\n+ for heating_or_cooling_systems in (heating_systems, cooling_systems):\n+ if len(heating_or_cooling_systems) == 1:\n+ for key, hvac_sys in heating_or_cooling_systems.items():\n+ if hvac_sys.get('_floorarea') is None and hvac_sys.get('_fracload') is None:\n+ hvac_sys['_fracload'] = 1.0\n+ hvac_sys['_floorarea'] = bldg_about['conditioned_floor_area']\n+\n+ # Choose a weighting factor that all the heating and cooling systems use\n+ all_systems = []\n+ all_systems.extend(heating_systems.values())\n+ all_systems.extend(cooling_systems.values())\n+ found_weighting_factor = False\n+ for weighting_factor in ['_floorarea', '_fracload']:\n+ if None not in [x.get(weighting_factor) for x in all_systems]:\n+ found_weighting_factor = True\n+ break\n+ if not found_weighting_factor:\n raise TranslationError(\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed.')\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed.' # noqa: E501\n+ )\n \n- weight_sum = max(heating_weight_sum, cooling_weight_sum)\n- del heating_weight_sum\n- del cooling_weight_sum\n+ # Calculate the sum of the weights (total fraction or floor area)\n+ weight_sum = max(\n+ sum([x[weighting_factor] for x in heating_systems.values()]),\n+ sum([x[weighting_factor] for x in cooling_systems.values()])\n+ )\n \n # Ensure that heating and cooling systems attached to the same ducts are within 5% of each other\n # in terms of fraction of the load served.\n for duct_id, (htg_id, clg_id) in list(dist_heating_cooling_map.items()):\n try:\n- htg_weight = old_div(heating_systems[htg_id][heating_weighting_factor], weight_sum)\n- clg_weight = old_div(cooling_systems[clg_id][cooling_weighting_factor], weight_sum)\n+ htg_weight = old_div(heating_systems[htg_id][weighting_factor], weight_sum)\n+ clg_weight = old_div(cooling_systems[clg_id][weighting_factor], weight_sum)\n except KeyError:\n continue\n if abs(htg_weight - clg_weight) > 0.051:\n@@ -1859,9 +1852,9 @@ class HPXMLtoHEScoreTranslator(object):\n for dist_sys_id, (htg_sys_id, clg_sys_id) in list(dist_heating_cooling_map.items()):\n weights_to_average = []\n if htg_sys_id is not None:\n- weights_to_average.append(old_div(heating_systems[htg_sys_id][heating_weighting_factor], weight_sum))\n+ weights_to_average.append(old_div(heating_systems[htg_sys_id][weighting_factor], weight_sum))\n if clg_sys_id is not None:\n- weights_to_average.append(old_div(cooling_systems[clg_sys_id][cooling_weighting_factor], weight_sum))\n+ weights_to_average.append(old_div(cooling_systems[clg_sys_id][weighting_factor], weight_sum))\n avg_sys_weight = old_div(sum(weights_to_average), len(weights_to_average))\n hvac_systems_ids.add(IDsAndWeights(htg_sys_id, clg_sys_id, dist_sys_id, avg_sys_weight))\n \n@@ -1875,7 +1868,7 @@ class HPXMLtoHEScoreTranslator(object):\n heatpump_id,\n heatpump_id,\n None,\n- old_div(heating_systems[heatpump_id][heating_weighting_factor], weight_sum)))\n+ old_div(heating_systems[heatpump_id][weighting_factor], weight_sum)))\n \n # Add the singletons to the list\n for htg_sys_id in singleton_heating_systems:\n@@ -1883,13 +1876,13 @@ class HPXMLtoHEScoreTranslator(object):\n htg_sys_id,\n None,\n None,\n- old_div(heating_systems[htg_sys_id][heating_weighting_factor], weight_sum)))\n+ old_div(heating_systems[htg_sys_id][weighting_factor], weight_sum)))\n for clg_sys_id in singleton_cooling_systems:\n hvac_systems_ids.add(IDsAndWeights(\n None,\n clg_sys_id,\n None,\n- old_div(cooling_systems[clg_sys_id][cooling_weighting_factor], weight_sum)))\n+ old_div(cooling_systems[clg_sys_id][weighting_factor], weight_sum)))\n \n # Split and combine systems by fraction as needed #45\n singleton_heating_systems = []\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex 1f6fd6cb..a6cd505f 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -410,7 +410,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = self.xpath('//h:HeatPump[1]/h:FloorAreaServed')\n el.getparent().remove(el)\n self.assertRaisesRegexp(TranslationError,\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed',\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n def test_missing_cooling_weighting_factor(self):\n@@ -420,7 +420,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = self.xpath('//h:CoolingSystem[2]/h:FloorAreaServed')\n el.getparent().remove(el)\n self.assertRaisesRegexp(TranslationError,\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed',\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n def test_bad_duct_location(self):\n@@ -1179,7 +1179,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n aircond.insert(-1, el)\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 3213})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1229,7 +1229,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n tr.xpath(ducts2, 'h:SystemIdentifier').attrib['id'] = 'ducts2'\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1275,7 +1275,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n clgsys_floor_area_el.text = str(total_floor_area)\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1325,7 +1325,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n \n # Get HEScore inputs and sort by fraction\n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1348,7 +1348,21 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n frac_cool_load_served.text = '1.0'\n clg_sys_eff.addprevious(frac_cool_load_served)\n b = self.xpath('h:Building[1]')\n- tr._get_hvac(b)\n+ tr._get_hvac(b, {\"conditioned_floor_area\": 2400})\n+\n+ def test_different_weighting_factors(self):\n+ tr = self._load_xmlfile('hescore_min')\n+ htg_sys = self.xpath('//h:HeatingSystem')\n+ frac_heat_load_served = etree.SubElement(htg_sys, tr.addns('h:FractionHeatLoadServed'))\n+ frac_heat_load_served.text = '1.0'\n+ heating_floor_area_served = etree.SubElement(htg_sys, tr.addns('h:FloorAreaServed'))\n+ heating_floor_area_served.text = '2400'\n+ clg_sys_eff = self.xpath('//h:CoolingSystem/h:AnnualCoolingEfficiency')\n+ frac_cool_load_served = etree.Element(tr.addns('h:FractionCoolLoadServed'))\n+ frac_cool_load_served.text = '1.0'\n+ clg_sys_eff.addprevious(frac_cool_load_served)\n+ b = self.xpath('h:Building[1]')\n+ tr._get_hvac(b, {\"conditioned_floor_area\": 2400})\n \n \n class TestPhotovoltaics(unittest.TestCase, ComparatorBase):\n", "FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_cooling_weighting_factor", "tests/tests.py::TestOtherHouses::test_missing_heating_weighting_factor", "tests/tests.py::TestHVACFractions::test_allow_5pct_diff", "tests/tests.py::TestHVACFractions::test_boiler_roomac", "tests/tests.py::TestHVACFractions::test_different_weighting_factors", "tests/tests.py::TestHVACFractions::test_furnace_baseboard_centralac", "tests/tests.py::TestHVACFractions::test_furnace_heat_pump", "tests/tests.py::TestHVACFractions::test_wall_furnace_baseboard_centralac"]}, {"instance_id": "NREL__hescore-hpxml-117", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "gold_patch": "diff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 55a58b86..e7bfb5c8 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -1345,7 +1345,7 @@ class HPXMLtoHEScoreTranslator(object):\n elif zone_floor['foundation_type'] == 'slab_on_grade':\n del fw_eff_rvalues[11] # remove unused values\n del fw_eff_rvalues[19]\n- slabs = foundation.xpath('h:Slab', namespaces=ns)\n+ slabs = xpath(foundation, 'h:Slab', raise_err=True, aslist=True)\n slabua = 0\n slabtotalperimeter = 0\n for slab in slabs:\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex 1f6fd6cb..60924139 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -320,6 +320,15 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n r'The house is a slab on grade foundation, but has foundation walls\\.',\n tr.hpxml_to_hescore_dict)\n \n+ def test_slab_missing(self):\n+ tr = self._load_xmlfile('house3')\n+ el = self.xpath('//h:Slab')\n+ el.getparent().remove(el)\n+ self.assertRaises(\n+ ElementNotFoundError,\n+ tr.hpxml_to_hescore_dict\n+ )\n+\n def test_missing_window_area(self):\n tr = self._load_xmlfile('hescore_min')\n el = self.xpath('//h:Window[1]/h:Area')\n", "FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_slab_missing"]}], "all_FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_window_orientation", "tests/tests.py::TestOtherHouses::test_window_only_attached_to_foundation_wall", "tests/tests.py::TestOtherHouses::test_missing_cooling_weighting_factor", "tests/tests.py::TestOtherHouses::test_missing_heating_weighting_factor", "tests/tests.py::TestHVACFractions::test_allow_5pct_diff", "tests/tests.py::TestHVACFractions::test_boiler_roomac", "tests/tests.py::TestHVACFractions::test_different_weighting_factors", "tests/tests.py::TestHVACFractions::test_furnace_baseboard_centralac", "tests/tests.py::TestHVACFractions::test_furnace_heat_pump", "tests/tests.py::TestHVACFractions::test_wall_furnace_baseboard_centralac", "tests/tests.py::TestOtherHouses::test_slab_missing"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-2083_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-2083:latest", "base_commit": "c5dc9acdfeb715de1c219eb228fe2dda1b9af497", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-2083", "base_commit": "c5dc9acdfeb715de1c219eb228fe2dda1b9af497", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex efe3c6e8..23b63fe4 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -294,8 +294,20 @@ class ClickHouse(Dialect):\n STRUCT_DELIMITER = (\"(\", \")\")\n NVL2_SUPPORTED = False\n \n+ STRING_TYPE_MAPPING = {\n+ exp.DataType.Type.CHAR: \"String\",\n+ exp.DataType.Type.LONGBLOB: \"String\",\n+ exp.DataType.Type.LONGTEXT: \"String\",\n+ exp.DataType.Type.MEDIUMBLOB: \"String\",\n+ exp.DataType.Type.MEDIUMTEXT: \"String\",\n+ exp.DataType.Type.TEXT: \"String\",\n+ exp.DataType.Type.VARBINARY: \"String\",\n+ exp.DataType.Type.VARCHAR: \"String\",\n+ }\n+\n TYPE_MAPPING = {\n **generator.Generator.TYPE_MAPPING,\n+ **STRING_TYPE_MAPPING,\n exp.DataType.Type.ARRAY: \"Array\",\n exp.DataType.Type.BIGINT: \"Int64\",\n exp.DataType.Type.DATETIME64: \"DateTime64\",\n@@ -365,6 +377,16 @@ class ClickHouse(Dialect):\n \"NAMED COLLECTION\",\n }\n \n+ def datatype_sql(self, expression: exp.DataType) -> str:\n+ # String is the standard ClickHouse type, every other variant is just an alias.\n+ # Additionally, any supplied length parameter will be ignored.\n+ #\n+ # https://clickhouse.com/docs/en/sql-reference/data-types/string\n+ if expression.this in self.STRING_TYPE_MAPPING:\n+ return \"String\"\n+\n+ return super().datatype_sql(expression)\n+\n def safeconcat_sql(self, expression: exp.SafeConcat) -> str:\n # Clickhouse errors out if we try to cast a NULL value to TEXT\n expression = expression.copy()\ndiff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py\nindex dea7f26a..eb891a16 100644\n--- a/sqlglot/dialects/duckdb.py\n+++ b/sqlglot/dialects/duckdb.py\n@@ -207,6 +207,9 @@ class DuckDB(Dialect):\n \n return this\n \n+ def _parse_struct_types(self) -> t.Optional[exp.Expression]:\n+ return self._parse_field_def()\n+\n def _pivot_column_names(self, aggregations: t.List[exp.Expression]) -> t.List[str]:\n if len(aggregations) == 1:\n return super()._pivot_column_names(aggregations)\ndiff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py\nindex eb3a1580..c43c020d 100644\n--- a/sqlglot/dialects/oracle.py\n+++ b/sqlglot/dialects/oracle.py\n@@ -22,7 +22,7 @@ def _parse_xml_table(self: parser.Parser) -> exp.XMLTable:\n by_ref = self._match_text_seq(\"RETURNING\", \"SEQUENCE\", \"BY\", \"REF\")\n \n if self._match_text_seq(\"COLUMNS\"):\n- columns = self._parse_csv(lambda: self._parse_column_def(self._parse_field(any_token=True)))\n+ columns = self._parse_csv(self._parse_field_def)\n \n return self.expression(exp.XMLTable, this=this, passing=passing, columns=columns, by_ref=by_ref)\n \ndiff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py\nindex 1f5c351b..1470455c 100644\n--- a/sqlglot/dialects/tsql.py\n+++ b/sqlglot/dialects/tsql.py\n@@ -666,6 +666,16 @@ class TSQL(Dialect):\n \n return sql\n \n+ def create_sql(self, expression: exp.Create) -> str:\n+ kind = self.sql(expression, \"kind\").upper()\n+ exists = expression.args.get(\"exists\")\n+\n+ if exists and kind == \"SCHEMA\":\n+ schema_name = self.sql(expression, \"this\")\n+ return f\"IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE SCHEMA_NAME = {schema_name}) EXEC('CREATE SCHEMA {schema_name}')\"\n+\n+ return super().create_sql(expression)\n+\n def offset_sql(self, expression: exp.Offset) -> str:\n return f\"{super().offset_sql(expression)} ROWS\"\n \ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 24f12cba..c1d86954 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3489,14 +3489,14 @@ class Parser(metaclass=_Parser):\n if not self._match(TokenType.L_PAREN):\n return this\n \n- args = self._parse_csv(\n- lambda: self._parse_constraint()\n- or self._parse_column_def(self._parse_field(any_token=True))\n- )\n+ args = self._parse_csv(lambda: self._parse_constraint() or self._parse_field_def())\n \n self._match_r_paren()\n return self.expression(exp.Schema, this=this, expressions=args)\n \n+ def _parse_field_def(self) -> t.Optional[exp.Expression]:\n+ return self._parse_column_def(self._parse_field(any_token=True))\n+\n def _parse_column_def(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]:\n # column defs are not really columns, they're identifiers\n if isinstance(this, exp.Column):\n@@ -4506,7 +4506,7 @@ class Parser(metaclass=_Parser):\n \n self._match(TokenType.COLUMN)\n exists_column = self._parse_exists(not_=True)\n- expression = self._parse_column_def(self._parse_field(any_token=True))\n+ expression = self._parse_field_def()\n \n if expression:\n expression.set(\"exists\", exists_column)\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex 583be3ef..c014aa0e 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -47,8 +47,10 @@ class TestClickhouse(Validator):\n self.validate_identity(\"position(haystack, needle)\")\n self.validate_identity(\"position(haystack, needle, position)\")\n self.validate_identity(\"CAST(x AS DATETIME)\")\n+ self.validate_identity(\"CAST(x AS VARCHAR(255))\", \"CAST(x AS String)\")\n+ self.validate_identity(\"CAST(x AS BLOB)\", \"CAST(x AS String)\")\n self.validate_identity(\n- 'SELECT CAST(tuple(1 AS \"a\", 2 AS \"b\", 3.0 AS \"c\").2 AS Nullable(TEXT))'\n+ 'SELECT CAST(tuple(1 AS \"a\", 2 AS \"b\", 3.0 AS \"c\").2 AS Nullable(String))'\n )\n self.validate_identity(\n \"CREATE TABLE test (id UInt8) ENGINE=AggregatingMergeTree() ORDER BY tuple()\"\n@@ -95,11 +97,11 @@ class TestClickhouse(Validator):\n },\n )\n self.validate_all(\n- \"CONCAT(CASE WHEN COALESCE(CAST(a AS TEXT), '') IS NULL THEN COALESCE(CAST(a AS TEXT), '') ELSE CAST(COALESCE(CAST(a AS TEXT), '') AS TEXT) END, CASE WHEN COALESCE(CAST(b AS TEXT), '') IS NULL THEN COALESCE(CAST(b AS TEXT), '') ELSE CAST(COALESCE(CAST(b AS TEXT), '') AS TEXT) END)\",\n+ \"CONCAT(CASE WHEN COALESCE(CAST(a AS String), '') IS NULL THEN COALESCE(CAST(a AS String), '') ELSE CAST(COALESCE(CAST(a AS String), '') AS String) END, CASE WHEN COALESCE(CAST(b AS String), '') IS NULL THEN COALESCE(CAST(b AS String), '') ELSE CAST(COALESCE(CAST(b AS String), '') AS String) END)\",\n read={\"postgres\": \"CONCAT(a, b)\"},\n )\n self.validate_all(\n- \"CONCAT(CASE WHEN a IS NULL THEN a ELSE CAST(a AS TEXT) END, CASE WHEN b IS NULL THEN b ELSE CAST(b AS TEXT) END)\",\n+ \"CONCAT(CASE WHEN a IS NULL THEN a ELSE CAST(a AS String) END, CASE WHEN b IS NULL THEN b ELSE CAST(b AS String) END)\",\n read={\"mysql\": \"CONCAT(a, b)\"},\n )\n self.validate_all(\n@@ -233,7 +235,7 @@ class TestClickhouse(Validator):\n self.validate_all(\n \"SELECT {abc: UInt32}, {b: String}, {c: DateTime},{d: Map(String, Array(UInt8))}, {e: Tuple(UInt8, String)}\",\n write={\n- \"clickhouse\": \"SELECT {abc: UInt32}, {b: TEXT}, {c: DATETIME}, {d: Map(TEXT, Array(UInt8))}, {e: Tuple(UInt8, String)}\",\n+ \"clickhouse\": \"SELECT {abc: UInt32}, {b: String}, {c: DATETIME}, {d: Map(String, Array(UInt8))}, {e: Tuple(UInt8, String)}\",\n \"\": \"SELECT :abc, :b, :c, :d, :e\",\n },\n )\n@@ -283,8 +285,8 @@ class TestClickhouse(Validator):\n \"clickhouse\": \"\"\"CREATE TABLE example1 (\n timestamp DATETIME,\n x UInt32 TTL now() + INTERVAL '1' MONTH,\n- y TEXT TTL timestamp + INTERVAL '1' DAY,\n- z TEXT\n+ y String TTL timestamp + INTERVAL '1' DAY,\n+ z String\n )\n ENGINE=MergeTree\n ORDER BY tuple()\"\"\",\n@@ -305,7 +307,7 @@ ORDER BY tuple()\"\"\",\n \"clickhouse\": \"\"\"CREATE TABLE test (\n id UInt64,\n timestamp DateTime64,\n- data TEXT,\n+ data String,\n max_hits UInt64,\n sum_hits UInt64\n )\n@@ -332,8 +334,8 @@ SET\n \"\"\",\n write={\n \"clickhouse\": \"\"\"CREATE TABLE test (\n- id TEXT,\n- data TEXT\n+ id String,\n+ data String\n )\n ENGINE=AggregatingMergeTree()\n ORDER BY tuple()\n@@ -416,7 +418,7 @@ WHERE\n \"clickhouse\": \"\"\"CREATE TABLE table_for_recompression (\n d DATETIME,\n key UInt64,\n- value TEXT\n+ value String\n )\n ENGINE=MergeTree()\n ORDER BY tuple()\n@@ -512,9 +514,9 @@ RANGE(MIN discount_start_date MAX discount_end_date)\"\"\",\n \"\"\",\n write={\n \"clickhouse\": \"\"\"CREATE DICTIONARY my_ip_trie_dictionary (\n- prefix TEXT,\n+ prefix String,\n asn UInt32,\n- cca2 TEXT DEFAULT '??'\n+ cca2 String DEFAULT '??'\n )\n PRIMARY KEY (prefix)\n SOURCE(CLICKHOUSE(\n@@ -540,7 +542,7 @@ LIFETIME(MIN 0 MAX 3600)\"\"\",\n write={\n \"clickhouse\": \"\"\"CREATE DICTIONARY polygons_test_dictionary (\n key Array(Array(Array(Tuple(Float64, Float64)))),\n- name TEXT\n+ name String\n )\n PRIMARY KEY (key)\n SOURCE(CLICKHOUSE(\ndiff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py\nindex 100f4a06..5f2afd75 100644\n--- a/tests/dialects/test_dialect.py\n+++ b/tests/dialects/test_dialect.py\n@@ -78,7 +78,7 @@ class TestDialect(Validator):\n \"CAST(a AS TEXT)\",\n write={\n \"bigquery\": \"CAST(a AS STRING)\",\n- \"clickhouse\": \"CAST(a AS TEXT)\",\n+ \"clickhouse\": \"CAST(a AS String)\",\n \"drill\": \"CAST(a AS VARCHAR)\",\n \"duckdb\": \"CAST(a AS TEXT)\",\n \"mysql\": \"CAST(a AS CHAR)\",\n@@ -116,7 +116,7 @@ class TestDialect(Validator):\n \"CAST(a AS VARBINARY(4))\",\n write={\n \"bigquery\": \"CAST(a AS BYTES)\",\n- \"clickhouse\": \"CAST(a AS VARBINARY(4))\",\n+ \"clickhouse\": \"CAST(a AS String)\",\n \"duckdb\": \"CAST(a AS BLOB(4))\",\n \"mysql\": \"CAST(a AS VARBINARY(4))\",\n \"hive\": \"CAST(a AS BINARY(4))\",\n@@ -133,7 +133,7 @@ class TestDialect(Validator):\n self.validate_all(\n \"CAST(MAP('a', '1') AS MAP(TEXT, TEXT))\",\n write={\n- \"clickhouse\": \"CAST(map('a', '1') AS Map(TEXT, TEXT))\",\n+ \"clickhouse\": \"CAST(map('a', '1') AS Map(String, String))\",\n },\n )\n self.validate_all(\ndiff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex c800e589..99a331ac 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -508,6 +508,10 @@ class TestDuckDB(Validator):\n self.validate_identity(\"CAST(x AS INT128)\")\n self.validate_identity(\"CAST(x AS DOUBLE)\")\n self.validate_identity(\"CAST(x AS DECIMAL(15, 4))\")\n+ self.validate_identity(\"CAST(x AS STRUCT(number BIGINT))\")\n+ self.validate_identity(\n+ \"CAST(ROW(1, ROW(1)) AS STRUCT(number BIGINT, row STRUCT(number BIGINT)))\"\n+ )\n \n self.validate_all(\"CAST(x AS NUMERIC(1, 2))\", write={\"duckdb\": \"CAST(x AS DECIMAL(1, 2))\"})\n self.validate_all(\"CAST(x AS HUGEINT)\", write={\"duckdb\": \"CAST(x AS INT128)\"})\ndiff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex 530522da..11740239 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -608,7 +608,7 @@ class TestPostgres(Validator):\n \"a || b\",\n write={\n \"\": \"a || b\",\n- \"clickhouse\": \"CONCAT(CAST(a AS TEXT), CAST(b AS TEXT))\",\n+ \"clickhouse\": \"CONCAT(CAST(a AS String), CAST(b AS String))\",\n \"duckdb\": \"a || b\",\n \"postgres\": \"a || b\",\n \"presto\": \"CONCAT(CAST(a AS VARCHAR), CAST(b AS VARCHAR))\",\ndiff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py\nindex a3fba58f..8d3c7d70 100644\n--- a/tests/dialects/test_tsql.py\n+++ b/tests/dialects/test_tsql.py\n@@ -410,6 +410,12 @@ class TestTSQL(Validator):\n )\n \n def test_ddl(self):\n+ self.validate_all(\n+ \"IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE SCHEMA_NAME = foo) EXEC('CREATE SCHEMA foo')\",\n+ read={\n+ \"\": \"CREATE SCHEMA IF NOT EXISTS foo\",\n+ },\n+ )\n self.validate_all(\n \"CREATE TABLE #mytemp (a INTEGER, b CHAR(2), c TIME(4), d FLOAT(24))\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_clickhouse.py::TestClickhouse::test_ddl", "tests/dialects/test_clickhouse.py::TestClickhouse::test_parameterization", "tests/dialects/test_dialect.py::TestDialect::test_cast", "tests/dialects/test_duckdb.py::TestDuckDB::test_cast", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_tsql.py::TestTSQL::test_ddl"]}, {"instance_id": "tobymao__sqlglot-2093", "base_commit": "1da653f64f91556e5a32b5a513f5404886da0c37", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex c1d86954..14c5e964 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -578,7 +578,7 @@ class Parser(metaclass=_Parser):\n TokenType.PLACEHOLDER: lambda self: self.expression(exp.Placeholder),\n TokenType.PARAMETER: lambda self: self._parse_parameter(),\n TokenType.COLON: lambda self: self.expression(exp.Placeholder, this=self._prev.text)\n- if self._match_set((TokenType.NUMBER, TokenType.VAR))\n+ if self._match(TokenType.NUMBER) or self._match_set(self.ID_VAR_TOKENS)\n else None,\n }\n \n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex 694cd68b..fb8f8fbb 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -6,6 +6,7 @@ class TestOracle(Validator):\n dialect = \"oracle\"\n \n def test_oracle(self):\n+ self.validate_identity(\"SELECT :OBJECT\")\n self.validate_identity(\"SELECT * FROM t FOR UPDATE\")\n self.validate_identity(\"SELECT * FROM t FOR UPDATE WAIT 5\")\n self.validate_identity(\"SELECT * FROM t FOR UPDATE NOWAIT\")\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-2095", "base_commit": "1aafe6e3e606603a5188696c0bca036ccdc1673a", "gold_patch": "diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py\nindex c43c020d..fe31a912 100644\n--- a/sqlglot/dialects/oracle.py\n+++ b/sqlglot/dialects/oracle.py\n@@ -166,7 +166,7 @@ class Oracle(Dialect):\n return f\"XMLTABLE({self.sep('')}{self.indent(this + passing + by_ref + columns)}{self.seg(')', sep='')}\"\n \n class Tokenizer(tokens.Tokenizer):\n- VAR_SINGLE_TOKENS = {\"@\"}\n+ VAR_SINGLE_TOKENS = {\"@\", \"$\", \"#\"}\n \n KEYWORDS = {\n **tokens.Tokenizer.KEYWORDS,\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex fb8f8fbb..7ccb0afd 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -6,6 +6,7 @@ class TestOracle(Validator):\n dialect = \"oracle\"\n \n def test_oracle(self):\n+ self.validate_identity(\"SELECT a$x#b\")\n self.validate_identity(\"SELECT :OBJECT\")\n self.validate_identity(\"SELECT * FROM t FOR UPDATE\")\n self.validate_identity(\"SELECT * FROM t FOR UPDATE WAIT 5\")\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_clickhouse.py::TestClickhouse::test_ddl", "tests/dialects/test_clickhouse.py::TestClickhouse::test_parameterization", "tests/dialects/test_dialect.py::TestDialect::test_cast", "tests/dialects/test_duckdb.py::TestDuckDB::test_cast", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_tsql.py::TestTSQL::test_ddl", "tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_oracle.py::TestOracle::test_oracle"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3238_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3238:latest", "base_commit": "647611e16bdb5ecfc2eec30111cc6689200836b7", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3238", "base_commit": "647611e16bdb5ecfc2eec30111cc6689200836b7", "gold_patch": "diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 5ca0d5d2..742dfcea 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -1839,7 +1839,7 @@ class Check(Expression):\n \n # https://docs.snowflake.com/en/sql-reference/constructs/connect-by\n class Connect(Expression):\n- arg_types = {\"start\": False, \"connect\": True}\n+ arg_types = {\"start\": False, \"connect\": True, \"nocycle\": False}\n \n \n class Prior(Expression):\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 99a3f120..caec78d8 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1846,8 +1846,9 @@ class Generator(metaclass=_Generator):\n def connect_sql(self, expression: exp.Connect) -> str:\n start = self.sql(expression, \"start\")\n start = self.seg(f\"START WITH {start}\") if start else \"\"\n+ nocycle = \" NOCYCLE\" if expression.args.get(\"nocycle\") else \"\"\n connect = self.sql(expression, \"connect\")\n- connect = self.seg(f\"CONNECT BY {connect}\")\n+ connect = self.seg(f\"CONNECT BY{nocycle} {connect}\")\n return start + connect\n \n def prior_sql(self, expression: exp.Prior) -> str:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 01d13346..b380875f 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -3505,6 +3505,7 @@ class Parser(metaclass=_Parser):\n return None\n \n self._match(TokenType.CONNECT_BY)\n+ nocycle = self._match_text_seq(\"NOCYCLE\")\n self.NO_PAREN_FUNCTION_PARSERS[\"PRIOR\"] = lambda self: self.expression(\n exp.Prior, this=self._parse_bitwise()\n )\n@@ -3514,7 +3515,7 @@ class Parser(metaclass=_Parser):\n if not start and self._match(TokenType.START_WITH):\n start = self._parse_conjunction()\n \n- return self.expression(exp.Connect, start=start, connect=connect)\n+ return self.expression(exp.Connect, start=start, connect=connect, nocycle=nocycle)\n \n def _parse_name_as_expression(self) -> exp.Alias:\n return self.expression(\n", "test_patch": "diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py\nindex d1033e47..526b0b5a 100644\n--- a/tests/dialects/test_oracle.py\n+++ b/tests/dialects/test_oracle.py\n@@ -94,6 +94,9 @@ class TestOracle(Validator):\n \"SELECT * FROM t SAMPLE (0.25)\",\n )\n self.validate_identity(\"SELECT TO_CHAR(-100, 'L99', 'NL_CURRENCY = '' AusDollars '' ')\")\n+ self.validate_identity(\n+ \"SELECT * FROM t START WITH col CONNECT BY NOCYCLE PRIOR col1 = col2\"\n+ )\n \n self.validate_all(\n \"CURRENT_TIMESTAMP BETWEEN TO_DATE(f.C_SDATE, 'yyyy/mm/dd') AND TO_DATE(f.C_EDATE, 'yyyy/mm/dd')\",\n", "FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle"]}, {"instance_id": "tobymao__sqlglot-3242", "base_commit": "59f1d13bc5e37ebe6636b05e0381facc9725f7b0", "gold_patch": "diff --git a/sqlglot/dialects/sqlite.py b/sqlglot/dialects/sqlite.py\nindex 63540a8e..ef7d9aa1 100644\n--- a/sqlglot/dialects/sqlite.py\n+++ b/sqlglot/dialects/sqlite.py\n@@ -33,6 +33,14 @@ def _json_extract_sql(self: SQLite.Generator, expression: exp.JSONExtract) -> st\n return arrow_json_extract_sql(self, expression)\n \n \n+def _build_strftime(args: t.List) -> exp.Anonymous | exp.TimeToStr:\n+ if len(args) == 1:\n+ args.append(exp.CurrentTimestamp())\n+ if len(args) == 2:\n+ return exp.TimeToStr(this=exp.TsOrDsToTimestamp(this=args[1]), format=args[0])\n+ return exp.Anonymous(this=\"STRFTIME\", expressions=args)\n+\n+\n def _transform_create(expression: exp.Expression) -> exp.Expression:\n \"\"\"Move primary key to a column and enforce auto_increment on primary keys.\"\"\"\n schema = expression.this\n@@ -82,6 +90,7 @@ class SQLite(Dialect):\n FUNCTIONS = {\n **parser.Parser.FUNCTIONS,\n \"EDITDIST3\": exp.Levenshtein.from_arg_list,\n+ \"STRFTIME\": _build_strftime,\n }\n STRING_ALIASES = True\n \n@@ -152,7 +161,9 @@ class SQLite(Dialect):\n ),\n exp.TableSample: no_tablesample_sql,\n exp.TimeStrToTime: lambda self, e: self.sql(e, \"this\"),\n+ exp.TimeToStr: lambda self, e: self.func(\"STRFTIME\", e.args.get(\"format\"), e.this),\n exp.TryCast: no_trycast_sql,\n+ exp.TsOrDsToTimestamp: lambda self, e: self.sql(e, \"this\"),\n }\n \n # SQLite doesn't generally support CREATE TABLE .. properties\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 742dfcea..75751444 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5687,6 +5687,10 @@ class TsOrDsToTime(Func):\n pass\n \n \n+class TsOrDsToTimestamp(Func):\n+ pass\n+\n+\n class TsOrDiToDi(Func):\n pass\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex caec78d8..a67c7003 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -3516,6 +3516,13 @@ class Generator(metaclass=_Generator):\n \n return self.sql(exp.cast(this, \"time\"))\n \n+ def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:\n+ this = expression.this\n+ if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):\n+ return self.sql(this)\n+\n+ return self.sql(exp.cast(this, \"timestamp\"))\n+\n def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:\n this = expression.this\n time_format = self.format_time(expression)\n", "test_patch": "diff --git a/tests/dialects/test_sqlite.py b/tests/dialects/test_sqlite.py\nindex e935c194..f3cde0b6 100644\n--- a/tests/dialects/test_sqlite.py\n+++ b/tests/dialects/test_sqlite.py\n@@ -6,62 +6,6 @@ from sqlglot.helper import logger as helper_logger\n class TestSQLite(Validator):\n dialect = \"sqlite\"\n \n- def test_ddl(self):\n- for conflict_action in (\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"):\n- with self.subTest(f\"ON CONFLICT {conflict_action}\"):\n- self.validate_identity(\"CREATE TABLE a (b, c, UNIQUE (b, c) ON CONFLICT IGNORE)\")\n-\n- self.validate_identity(\"INSERT OR ABORT INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR FAIL INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR IGNORE INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR REPLACE INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR ROLLBACK INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"CREATE TABLE foo (id INTEGER PRIMARY KEY ASC)\")\n- self.validate_identity(\"CREATE TEMPORARY TABLE foo (id INTEGER)\")\n-\n- self.validate_all(\n- \"\"\"\n- CREATE TABLE \"Track\"\n- (\n- CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n- FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n- \"AlbumId\"\n- ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n- FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n- FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n- )\n- \"\"\",\n- write={\n- \"sqlite\": \"\"\"CREATE TABLE \"Track\" (\n- CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n- FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n- \"AlbumId\"\n- ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n- FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n- FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n-)\"\"\",\n- },\n- pretty=True,\n- )\n- self.validate_all(\n- \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n- read={\n- \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n- },\n- write={\n- \"sqlite\": \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n- \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n- \"postgres\": \"CREATE TABLE z (a INT GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE PRIMARY KEY)\",\n- },\n- )\n- self.validate_all(\n- \"\"\"CREATE TABLE \"x\" (\"Name\" NVARCHAR(200) NOT NULL)\"\"\",\n- write={\n- \"sqlite\": \"\"\"CREATE TABLE \"x\" (\"Name\" TEXT(200) NOT NULL)\"\"\",\n- \"mysql\": \"CREATE TABLE `x` (`Name` VARCHAR(200) NOT NULL)\",\n- },\n- )\n-\n def test_sqlite(self):\n self.validate_identity(\"SELECT DATE()\")\n self.validate_identity(\"SELECT DATE('now', 'start of month', '+1 month', '-1 day')\")\n@@ -69,7 +13,6 @@ class TestSQLite(Validator):\n self.validate_identity(\"SELECT DATETIME(1092941466, 'auto')\")\n self.validate_identity(\"SELECT DATETIME(1092941466, 'unixepoch', 'localtime')\")\n self.validate_identity(\"SELECT UNIXEPOCH()\")\n- self.validate_identity(\"SELECT STRFTIME('%s')\")\n self.validate_identity(\"SELECT JULIANDAY('now') - JULIANDAY('1776-07-04')\")\n self.validate_identity(\"SELECT UNIXEPOCH() - UNIXEPOCH('2004-01-01 02:34:56')\")\n self.validate_identity(\"SELECT DATE('now', 'start of year', '+9 months', 'weekday 2')\")\n@@ -149,6 +92,29 @@ class TestSQLite(Validator):\n write={\"snowflake\": \"LEAST(x, y, z)\"},\n )\n \n+ def test_strftime(self):\n+ self.validate_identity(\"SELECT STRFTIME('%Y/%m/%d', 'now')\")\n+ self.validate_identity(\"SELECT STRFTIME('%Y-%m-%d', '2016-10-16', 'start of month')\")\n+ self.validate_identity(\n+ \"SELECT STRFTIME('%s')\",\n+ \"SELECT STRFTIME('%s', CURRENT_TIMESTAMP)\",\n+ )\n+\n+ self.validate_all(\n+ \"SELECT STRFTIME('%Y-%m-%d', '2020-01-01 12:05:03')\",\n+ write={\n+ \"duckdb\": \"SELECT STRFTIME(CAST('2020-01-01 12:05:03' AS TIMESTAMP), '%Y-%m-%d')\",\n+ \"sqlite\": \"SELECT STRFTIME('%Y-%m-%d', '2020-01-01 12:05:03')\",\n+ },\n+ )\n+ self.validate_all(\n+ \"SELECT STRFTIME('%Y-%m-%d', CURRENT_TIMESTAMP)\",\n+ write={\n+ \"duckdb\": \"SELECT STRFTIME(CAST(CURRENT_TIMESTAMP AS TIMESTAMP), '%Y-%m-%d')\",\n+ \"sqlite\": \"SELECT STRFTIME('%Y-%m-%d', CURRENT_TIMESTAMP)\",\n+ },\n+ )\n+\n def test_datediff(self):\n self.validate_all(\n \"DATEDIFF(a, b, 'day')\",\n@@ -194,3 +160,59 @@ class TestSQLite(Validator):\n )\n \n self.assertIn(\"Named columns are not supported in table alias.\", cm.output[0])\n+\n+ def test_ddl(self):\n+ for conflict_action in (\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"):\n+ with self.subTest(f\"ON CONFLICT {conflict_action}\"):\n+ self.validate_identity(\"CREATE TABLE a (b, c, UNIQUE (b, c) ON CONFLICT IGNORE)\")\n+\n+ self.validate_identity(\"INSERT OR ABORT INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR FAIL INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR IGNORE INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR REPLACE INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR ROLLBACK INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"CREATE TABLE foo (id INTEGER PRIMARY KEY ASC)\")\n+ self.validate_identity(\"CREATE TEMPORARY TABLE foo (id INTEGER)\")\n+\n+ self.validate_all(\n+ \"\"\"\n+ CREATE TABLE \"Track\"\n+ (\n+ CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n+ FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n+ \"AlbumId\"\n+ ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n+ )\n+ \"\"\",\n+ write={\n+ \"sqlite\": \"\"\"CREATE TABLE \"Track\" (\n+ CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n+ FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n+ \"AlbumId\"\n+ ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n+)\"\"\",\n+ },\n+ pretty=True,\n+ )\n+ self.validate_all(\n+ \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n+ read={\n+ \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n+ },\n+ write={\n+ \"sqlite\": \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n+ \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n+ \"postgres\": \"CREATE TABLE z (a INT GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE PRIMARY KEY)\",\n+ },\n+ )\n+ self.validate_all(\n+ \"\"\"CREATE TABLE \"x\" (\"Name\" NVARCHAR(200) NOT NULL)\"\"\",\n+ write={\n+ \"sqlite\": \"\"\"CREATE TABLE \"x\" (\"Name\" TEXT(200) NOT NULL)\"\"\",\n+ \"mysql\": \"CREATE TABLE `x` (`Name` VARCHAR(200) NOT NULL)\",\n+ },\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_sqlite.py::TestSQLite::test_strftime"]}, {"instance_id": "tobymao__sqlglot-3252", "base_commit": "150a8270c9e1c5a74aeaeeedac2773c41760cb14", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 5c953188..874ce901 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -261,6 +261,11 @@ class ClickHouse(Dialect):\n \"ArgMax\",\n ]\n \n+ FUNC_TOKENS = {\n+ *parser.Parser.FUNC_TOKENS,\n+ TokenType.SET,\n+ }\n+\n AGG_FUNC_MAPPING = (\n lambda functions, suffixes: {\n f\"{f}{sfx}\": (f, sfx) for sfx in (suffixes + [\"\"]) for f in functions\n@@ -321,6 +326,17 @@ class ClickHouse(Dialect):\n TokenType.FORMAT: lambda self: (\"format\", self._advance() or self._parse_id_var()),\n }\n \n+ CONSTRAINT_PARSERS = {\n+ **parser.Parser.CONSTRAINT_PARSERS,\n+ \"INDEX\": lambda self: self._parse_index_constraint(),\n+ \"CODEC\": lambda self: self._parse_compress(),\n+ }\n+\n+ SCHEMA_UNNAMED_CONSTRAINTS = {\n+ *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,\n+ \"INDEX\",\n+ }\n+\n def _parse_conjunction(self) -> t.Optional[exp.Expression]:\n this = super()._parse_conjunction()\n \n@@ -512,6 +528,27 @@ class ClickHouse(Dialect):\n self._retreat(index)\n return None\n \n+ def _parse_index_constraint(\n+ self, kind: t.Optional[str] = None\n+ ) -> exp.IndexColumnConstraint:\n+ # INDEX name1 expr TYPE type1(args) GRANULARITY value\n+ this = self._parse_id_var()\n+ expression = self._parse_conjunction()\n+\n+ index_type = self._match_text_seq(\"TYPE\") and (\n+ self._parse_function() or self._parse_var()\n+ )\n+\n+ granularity = self._match_text_seq(\"GRANULARITY\") and self._parse_term()\n+\n+ return self.expression(\n+ exp.IndexColumnConstraint,\n+ this=this,\n+ expression=expression,\n+ index_type=index_type,\n+ granularity=granularity,\n+ )\n+\n class Generator(generator.Generator):\n QUERY_HINTS = False\n STRUCT_DELIMITER = (\"(\", \")\")\n@@ -590,6 +627,9 @@ class ClickHouse(Dialect):\n exp.Array: inline_array_sql,\n exp.CastToStrType: rename_func(\"CAST\"),\n exp.CountIf: rename_func(\"countIf\"),\n+ exp.CompressColumnConstraint: lambda self,\n+ e: f\"CODEC({self.expressions(e, key='this', flat=True)})\",\n+ exp.ComputedColumnConstraint: lambda self, e: f\"ALIAS {self.sql(e, 'this')}\",\n exp.CurrentDate: lambda self, e: self.func(\"CURRENT_DATE\"),\n exp.DateAdd: date_delta_sql(\"DATE_ADD\"),\n exp.DateDiff: date_delta_sql(\"DATE_DIFF\"),\n@@ -742,3 +782,15 @@ class ClickHouse(Dialect):\n def prewhere_sql(self, expression: exp.PreWhere) -> str:\n this = self.indent(self.sql(expression, \"this\"))\n return f\"{self.seg('PREWHERE')}{self.sep()}{this}\"\n+\n+ def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:\n+ this = self.sql(expression, \"this\")\n+ this = f\" {this}\" if this else \"\"\n+ expr = self.sql(expression, \"expression\")\n+ expr = f\" {expr}\" if expr else \"\"\n+ index_type = self.sql(expression, \"index_type\")\n+ index_type = f\" TYPE {index_type}\" if index_type else \"\"\n+ granularity = self.sql(expression, \"granularity\")\n+ granularity = f\" GRANULARITY {granularity}\" if granularity else \"\"\n+\n+ return f\"INDEX{this}{expr}{index_type}{granularity}\"\ndiff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex aef2a759..66302fc4 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -480,9 +480,6 @@ class MySQL(Dialect):\n elif self._match_text_seq(\"ENGINE_ATTRIBUTE\"):\n self._match(TokenType.EQ)\n opt = exp.IndexConstraintOption(engine_attr=self._parse_string())\n- elif self._match_text_seq(\"ENGINE_ATTRIBUTE\"):\n- self._match(TokenType.EQ)\n- opt = exp.IndexConstraintOption(engine_attr=self._parse_string())\n elif self._match_text_seq(\"SECONDARY_ENGINE_ATTRIBUTE\"):\n self._match(TokenType.EQ)\n opt = exp.IndexConstraintOption(secondary_engine_attr=self._parse_string())\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 22f92b75..9f72c290 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -1665,13 +1665,16 @@ class GeneratedAsRowColumnConstraint(ColumnConstraintKind):\n \n \n # https://dev.mysql.com/doc/refman/8.0/en/create-table.html\n+# https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/ParserCreateQuery.h#L646\n class IndexColumnConstraint(ColumnConstraintKind):\n arg_types = {\n \"this\": False,\n- \"schema\": True,\n+ \"schema\": False,\n \"kind\": False,\n \"index_type\": False,\n \"options\": False,\n+ \"expression\": False, # Clickhouse\n+ \"granularity\": False,\n }\n \n \ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex a2fcf3d5..474ba050 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4504,7 +4504,7 @@ class Parser(metaclass=_Parser):\n \n constraints: t.List[exp.Expression] = []\n \n- if not kind and self._match(TokenType.ALIAS):\n+ if (not kind and self._match(TokenType.ALIAS)) or self._match_text_seq(\"ALIAS\"):\n constraints.append(\n self.expression(\n exp.ComputedColumnConstraint,\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex f7165846..c5f9847c 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -154,7 +154,9 @@ class TestClickhouse(Validator):\n self.validate_identity(\"TRUNCATE TABLE t1 ON CLUSTER test_cluster\")\n self.validate_identity(\"TRUNCATE DATABASE db\")\n self.validate_identity(\"TRUNCATE DATABASE db ON CLUSTER test_cluster\")\n-\n+ self.validate_identity(\n+ \"CREATE TABLE t (foo String CODEC(LZ4HC(9), ZSTD, DELTA), size String ALIAS formatReadableSize(size_bytes), INDEX idx1 a TYPE bloom_filter(0.001) GRANULARITY 1, INDEX idx2 a TYPE set(100) GRANULARITY 2, INDEX idx3 a TYPE minmax GRANULARITY 3)\"\n+ )\n self.validate_all(\n \"SELECT arrayJoin([1,2,3])\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_sqlite.py::TestSQLite::test_strftime", "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-700_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-700:latest", "base_commit": "e66f20671e6d4c9dab46aa7b79a2447224ed02b7", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-700", "base_commit": "e66f20671e6d4c9dab46aa7b79a2447224ed02b7", "gold_patch": "diff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex c1976d16..0a517dcb 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -153,6 +153,7 @@ class Parser(metaclass=_Parser):\n TokenType.COMMAND,\n TokenType.COMMIT,\n TokenType.CONSTRAINT,\n+ TokenType.CURRENT_TIME,\n TokenType.DEFAULT,\n TokenType.DELETE,\n TokenType.DESCRIBE,\n@@ -214,6 +215,7 @@ class Parser(metaclass=_Parser):\n TokenType.VOLATILE,\n *SUBQUERY_PREDICATES,\n *TYPE_TOKENS,\n+ *NO_PAREN_FUNCTIONS,\n }\n \n TABLE_ALIAS_TOKENS = ID_VAR_TOKENS - {TokenType.NATURAL, TokenType.APPLY}\n", "test_patch": "diff --git a/tests/test_transpile.py b/tests/test_transpile.py\nindex 942053eb..70412ca4 100644\n--- a/tests/test_transpile.py\n+++ b/tests/test_transpile.py\n@@ -20,6 +20,13 @@ class TestTranspile(unittest.TestCase):\n self.assertEqual(transpile(sql, **kwargs)[0], target)\n \n def test_alias(self):\n+ self.assertEqual(transpile(\"SELECT 1 current_time\")[0], \"SELECT 1 AS current_time\")\n+ self.assertEqual(\n+ transpile(\"SELECT 1 current_timestamp\")[0], \"SELECT 1 AS current_timestamp\"\n+ )\n+ self.assertEqual(transpile(\"SELECT 1 current_date\")[0], \"SELECT 1 AS current_date\")\n+ self.assertEqual(transpile(\"SELECT 1 current_datetime\")[0], \"SELECT 1 AS current_datetime\")\n+\n for key in (\"union\", \"filter\", \"over\", \"from\", \"join\"):\n with self.subTest(f\"alias {key}\"):\n self.validate(f\"SELECT x AS {key}\", f\"SELECT x AS {key}\")\n", "FAIL_TO_PASS": ["tests/test_transpile.py::TestTranspile::test_alias"]}, {"instance_id": "tobymao__sqlglot-702", "base_commit": "22091ae448af2d243cd9068c6eab2341cda50991", "gold_patch": "diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex d1aadede..a96bd80d 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -148,6 +148,7 @@ class Snowflake(Dialect):\n **parser.Parser.FUNCTION_PARSERS,\n \"DATE_PART\": _parse_date_part,\n }\n+ FUNCTION_PARSERS.pop(\"TRIM\")\n \n FUNC_TOKENS = {\n *parser.Parser.FUNC_TOKENS,\n@@ -203,6 +204,7 @@ class Snowflake(Dialect):\n exp.StrPosition: rename_func(\"POSITION\"),\n exp.Parameter: lambda self, e: f\"${self.sql(e, 'this')}\",\n exp.PartitionedByProperty: lambda self, e: f\"PARTITION BY {self.sql(e, 'value')}\",\n+ exp.Trim: lambda self, e: f\"TRIM({self.format_args(e.this, e.expression)})\",\n }\n \n TYPE_MAPPING = {\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 164849ff..17775693 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2821,8 +2821,8 @@ class TimeStrToUnix(Func):\n class Trim(Func):\n arg_types = {\n \"this\": True,\n- \"position\": False,\n \"expression\": False,\n+ \"position\": False,\n \"collation\": False,\n }\n \n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 1846b17f..0e69f4e5 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -169,6 +169,17 @@ class TestSnowflake(Validator):\n \"snowflake\": \"SELECT a FROM test AS unpivot\",\n },\n )\n+ self.validate_all(\n+ \"trim(date_column, 'UTC')\",\n+ write={\n+ \"snowflake\": \"TRIM(date_column, 'UTC')\",\n+ \"postgres\": \"TRIM('UTC' FROM date_column)\",\n+ },\n+ )\n+ self.validate_all(\n+ \"trim(date_column)\",\n+ write={\"snowflake\": \"TRIM(date_column)\"},\n+ )\n \n def test_null_treatment(self):\n self.validate_all(\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}, {"instance_id": "tobymao__sqlglot-749", "base_commit": "a936dd21a396dab3008e11f842673d18d8810f25", "gold_patch": "diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py\nindex 4353164a..c4476d98 100644\n--- a/sqlglot/dialects/postgres.py\n+++ b/sqlglot/dialects/postgres.py\n@@ -74,6 +74,12 @@ def _trim_sql(self, expression):\n return f\"TRIM({trim_type}{remove_chars}{from_part}{target}{collation})\"\n \n \n+def _datatype_sql(self, expression):\n+ if expression.this == exp.DataType.Type.ARRAY:\n+ return f\"{self.expressions(expression, flat=True)}[]\"\n+ return self.datatype_sql(expression)\n+\n+\n def _auto_increment_to_serial(expression):\n auto = expression.find(exp.AutoIncrementColumnConstraint)\n \n@@ -191,25 +197,27 @@ class Postgres(Dialect):\n KEYWORDS = {\n **tokens.Tokenizer.KEYWORDS,\n \"ALWAYS\": TokenType.ALWAYS,\n- \"BY DEFAULT\": TokenType.BY_DEFAULT,\n- \"IDENTITY\": TokenType.IDENTITY,\n- \"GENERATED\": TokenType.GENERATED,\n- \"DOUBLE PRECISION\": TokenType.DOUBLE,\n- \"BIGSERIAL\": TokenType.BIGSERIAL,\n- \"SERIAL\": TokenType.SERIAL,\n- \"SMALLSERIAL\": TokenType.SMALLSERIAL,\n- \"UUID\": TokenType.UUID,\n- \"TEMP\": TokenType.TEMPORARY,\n- \"BEGIN TRANSACTION\": TokenType.BEGIN,\n \"BEGIN\": TokenType.COMMAND,\n+ \"BEGIN TRANSACTION\": TokenType.BEGIN,\n+ \"BIGSERIAL\": TokenType.BIGSERIAL,\n+ \"BY DEFAULT\": TokenType.BY_DEFAULT,\n \"COMMENT ON\": TokenType.COMMAND,\n \"DECLARE\": TokenType.COMMAND,\n \"DO\": TokenType.COMMAND,\n+ \"DOUBLE PRECISION\": TokenType.DOUBLE,\n+ \"GENERATED\": TokenType.GENERATED,\n+ \"GRANT\": TokenType.COMMAND,\n+ \"HSTORE\": TokenType.HSTORE,\n+ \"IDENTITY\": TokenType.IDENTITY,\n+ \"JSONB\": TokenType.JSONB,\n \"REFRESH\": TokenType.COMMAND,\n \"REINDEX\": TokenType.COMMAND,\n \"RESET\": TokenType.COMMAND,\n \"REVOKE\": TokenType.COMMAND,\n- \"GRANT\": TokenType.COMMAND,\n+ \"SERIAL\": TokenType.SERIAL,\n+ \"SMALLSERIAL\": TokenType.SMALLSERIAL,\n+ \"TEMP\": TokenType.TEMPORARY,\n+ \"UUID\": TokenType.UUID,\n **{f\"CREATE {kind}\": TokenType.COMMAND for kind in CREATABLES},\n **{f\"DROP {kind}\": TokenType.COMMAND for kind in CREATABLES},\n }\n@@ -265,4 +273,5 @@ class Postgres(Dialect):\n exp.Trim: _trim_sql,\n exp.TryCast: no_trycast_sql,\n exp.UnixToTime: lambda self, e: f\"TO_TIMESTAMP({self.sql(e, 'this')})\",\n+ exp.DataType: _datatype_sql,\n }\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 357d375a..ae26db94 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2020,6 +2020,7 @@ class DataType(Expression):\n DECIMAL = auto()\n BOOLEAN = auto()\n JSON = auto()\n+ JSONB = auto()\n INTERVAL = auto()\n TIMESTAMP = auto()\n TIMESTAMPTZ = auto()\n@@ -2034,6 +2035,7 @@ class DataType(Expression):\n STRUCT = auto()\n NULLABLE = auto()\n HLLSKETCH = auto()\n+ HSTORE = auto()\n SUPER = auto()\n SERIAL = auto()\n SMALLSERIAL = auto()\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 7830f62e..a543ad18 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -104,6 +104,7 @@ class Parser(metaclass=_Parser):\n TokenType.BINARY,\n TokenType.VARBINARY,\n TokenType.JSON,\n+ TokenType.JSONB,\n TokenType.INTERVAL,\n TokenType.TIMESTAMP,\n TokenType.TIMESTAMPTZ,\n@@ -115,6 +116,7 @@ class Parser(metaclass=_Parser):\n TokenType.GEOGRAPHY,\n TokenType.GEOMETRY,\n TokenType.HLLSKETCH,\n+ TokenType.HSTORE,\n TokenType.SUPER,\n TokenType.SERIAL,\n TokenType.SMALLSERIAL,\n@@ -1727,17 +1729,6 @@ class Parser(metaclass=_Parser):\n expressions = None\n maybe_func = False\n \n- if not nested and self._match_pair(TokenType.L_BRACKET, TokenType.R_BRACKET):\n- return exp.DataType(\n- this=exp.DataType.Type.ARRAY,\n- expressions=[exp.DataType.build(type_token.value)],\n- nested=True,\n- )\n-\n- if self._match(TokenType.L_BRACKET):\n- self._retreat(index)\n- return None\n-\n if self._match(TokenType.L_PAREN):\n if is_struct:\n expressions = self._parse_csv(self._parse_struct_kwargs)\n@@ -1753,6 +1744,17 @@ class Parser(metaclass=_Parser):\n self._match_r_paren()\n maybe_func = True\n \n+ if not nested and self._match_pair(TokenType.L_BRACKET, TokenType.R_BRACKET):\n+ return exp.DataType(\n+ this=exp.DataType.Type.ARRAY,\n+ expressions=[exp.DataType.build(type_token.value, expressions=expressions)],\n+ nested=True,\n+ )\n+\n+ if self._match(TokenType.L_BRACKET):\n+ self._retreat(index)\n+ return None\n+\n if nested and self._match(TokenType.LT):\n if is_struct:\n expressions = self._parse_csv(self._parse_struct_kwargs)\ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex 6d447dd7..fa006268 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -81,6 +81,7 @@ class TokenType(AutoName):\n BINARY = auto()\n VARBINARY = auto()\n JSON = auto()\n+ JSONB = auto()\n TIMESTAMP = auto()\n TIMESTAMPTZ = auto()\n TIMESTAMPLTZ = auto()\n@@ -91,6 +92,7 @@ class TokenType(AutoName):\n NULLABLE = auto()\n GEOMETRY = auto()\n HLLSKETCH = auto()\n+ HSTORE = auto()\n SUPER = auto()\n SERIAL = auto()\n SMALLSERIAL = auto()\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 625156b5..06787022 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -89,6 +89,7 @@ class TestDuckDB(Validator):\n \"presto\": \"CAST(COL AS ARRAY(BIGINT))\",\n \"hive\": \"CAST(COL AS ARRAY)\",\n \"spark\": \"CAST(COL AS ARRAY)\",\n+ \"postgres\": \"CAST(COL AS BIGINT[])\",\n },\n )\n \ndiff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex 8294eea7..c41fe01d 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -6,6 +6,9 @@ class TestPostgres(Validator):\n dialect = \"postgres\"\n \n def test_ddl(self):\n+ self.validate_identity(\"CREATE TABLE test (foo HSTORE)\")\n+ self.validate_identity(\"CREATE TABLE test (foo JSONB)\")\n+ self.validate_identity(\"CREATE TABLE test (foo VARCHAR(64)[])\")\n self.validate_all(\n \"CREATE TABLE products (product_no INT UNIQUE, name TEXT, price DECIMAL)\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_postgres.py::TestPostgres::test_ddl"]}], "all_FAIL_TO_PASS": ["tests/test_transpile.py::TestTranspile::test_alias", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_postgres.py::TestPostgres::test_ddl"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jboss-dockerfiles__dogen-143_x3", "level": 3, "source": "swerebench", "repo": "jboss-dockerfiles/dogen", "image": "swerebench/sweb.eval.x86_64.jboss-dockerfiles_1776_dogen-143:latest", "base_commit": "a55fa36d7ae6d19688c93d42629fbd763b72419f", "num_bugs": 3, "bugs": [{"instance_id": "jboss-dockerfiles__dogen-143", "base_commit": "a55fa36d7ae6d19688c93d42629fbd763b72419f", "gold_patch": "diff --git a/dogen/cli.py b/dogen/cli.py\nindex 6540695..c70984c 100644\n--- a/dogen/cli.py\n+++ b/dogen/cli.py\n@@ -14,6 +14,7 @@ from dogen.version import version\n from dogen.errors import Error\n from dogen.plugin import Plugin\n \n+import colorlog\n \n class MyParser(argparse.ArgumentParser):\n \n@@ -25,14 +26,15 @@ class MyParser(argparse.ArgumentParser):\n class CLI(object):\n \n def __init__(self):\n- self.log = logging.getLogger(\"dogen\")\n+ formatter = colorlog.ColoredFormatter(\n+ '%(log_color)s%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n handler = logging.StreamHandler()\n- formatter = logging.Formatter(\n- '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n handler.setFormatter(formatter)\n+\n+ self.log = logging.getLogger(\"dogen\")\n self.log.addHandler(handler)\n \n- for package in [\"requests.packages.urllib3\", \"pykwalify.core\", \"pykwalify.rule\"]:\n+ for package in [\"requests.packages.urllib3\", \"pykwalify.rule\"]:\n log = logging.getLogger(package)\n log.setLevel(logging.INFO)\n \n@@ -86,7 +88,10 @@ class CLI(object):\n except KeyboardInterrupt as e:\n pass\n except Error as e:\n- self.log.exception(e)\n+ if args.verbose:\n+ self.log.exception(e)\n+ else:\n+ self.log.error(str(e))\n sys.exit(1)\n \n def get_plugins(self):\ndiff --git a/dogen/generator.py b/dogen/generator.py\nindex 335db99..0562cd8 100644\n--- a/dogen/generator.py\n+++ b/dogen/generator.py\n@@ -48,12 +48,12 @@ class Generator(object):\n self.ssl_verify to False.\n \"\"\"\n \n- self.log.info(\"Fetching '%s' file...\" % location)\n+ self.log.debug(\"Fetching '%s' file...\" % location)\n \n if not output:\n output = tempfile.mktemp(\"-dogen\")\n \n- self.log.info(\"Fetched file will be saved as '%s'...\" % os.path.basename(output))\n+ self.log.debug(\"Fetched file will be saved as '%s'...\" % os.path.basename(output))\n \n r = requests.get(location, verify=self.ssl_verify, stream=True)\n \n@@ -261,8 +261,12 @@ class Generator(object):\n if 'sources' not in self.cfg or self.without_sources:\n return []\n \n+ self.log.info(\"Handling artifacts...\")\n self.cfg['artifacts'] = {}\n \n+ sources_cache = os.environ.get(\"DOGEN_SOURCES_CACHE\")\n+ self.log.debug(\"Source cache will be used for all artifacts\")\n+\n for source in self.cfg['sources']:\n url = source.get('url')\n artifact = source.get('artifact')\n@@ -279,6 +283,8 @@ class Generator(object):\n if not artifact:\n raise Error(\"Artifact location for one or more sources was not provided, please check your image descriptor!\")\n \n+ self.log.info(\"Handling artifact '%s'\" % artifact)\n+\n basename = os.path.basename(artifact)\n target = source.get('target')\n \n@@ -312,24 +318,28 @@ class Generator(object):\n self.check_sum(filename, source[algorithm], algorithm)\n passed = True\n except Exception as e:\n- self.log.warn(str(e))\n+ self.log.debug(str(e))\n+ self.log.warn(\"Local file doesn't match provided checksum, artifact '%s' will be downloaded again\" % artifact)\n passed = False\n \n if not passed:\n- sources_cache = os.environ.get(\"DOGEN_SOURCES_CACHE\")\n \n if sources_cache:\n- artifact = sources_cache.replace('#filename#', basename)\n+ cached_artifact = sources_cache.replace('#filename#', basename)\n \n if algorithms:\n if len(algorithms) > 1:\n self.log.warn(\"You specified multiple algorithms for '%s' artifact, but only '%s' will be used to fetch it from cache\" % (artifact, algorithms[0]))\n \n- artifact = artifact.replace('#hash#', source[algorithms[0]]).replace('#algorithm#', algorithms[0])\n-\n- self.log.info(\"Using '%s' as cached location for artifact\" % artifact)\n+ cached_artifact = cached_artifact.replace('#hash#', source[algorithms[0]]).replace('#algorithm#', algorithms[0])\n \n- self._fetch_file(artifact, filename)\n+ try:\n+ self._fetch_file(cached_artifact, filename)\n+ except Exception as e:\n+ self.log.warn(\"Could not download artifact from cached location: '%s': %s. Please make sure you set the correct value for DOGEN_SOURCES_CACHE (currently: '%s').\" % (cached_artifact, str(e), sources_cache))\n+ self._download_source(artifact, filename, source.get('hint'))\n+ else:\n+ self._download_source(artifact, filename, source.get('hint'))\n \n if algorithms:\n for algorithm in algorithms:\n@@ -338,10 +348,24 @@ class Generator(object):\n if algorithms:\n self.cfg['artifacts'][target] = \"%s:%s\" % (algorithms[0], source[algorithms[0]])\n else:\n+ self.log.warn(\"No checksum was specified for artifact '%s'!\" % artifact)\n self.cfg['artifacts'][target] = None\n \n+ def _download_source(self, artifact, filename, hint=None):\n+ if Tools.is_url(artifact):\n+ self.log.warn(\"Trying to download the '%s' artifact from original location\" % artifact)\n+ try:\n+ self._fetch_file(artifact, filename)\n+ except Exception as e:\n+ raise Error(\"Could not download artifact from orignal location, reason: %s\" % str(e))\n+ else:\n+ if hint:\n+ self.log.info(hint)\n+ self.log.info(\"Please download the '%s' artifact manually and save it as '%s'\" % (artifact, filename))\n+ raise Error(\"Artifact '%s' could not be fetched!\" % artifact)\n+\n def check_sum(self, filename, checksum, algorithm):\n- self.log.info(\"Checking '%s' %s hash...\" % (os.path.basename(filename), algorithm))\n+ self.log.debug(\"Checking '%s' %s hash...\" % (os.path.basename(filename), algorithm))\n \n hash = getattr(hashlib, algorithm)()\n \ndiff --git a/dogen/schema/kwalify_schema.yaml b/dogen/schema/kwalify_schema.yaml\nindex 05069f3..82c400d 100644\n--- a/dogen/schema/kwalify_schema.yaml\n+++ b/dogen/schema/kwalify_schema.yaml\n@@ -64,6 +64,7 @@ map:\n sha1: {type: str}\n sha256: {type: str}\n target: {type: str}\n+ hint: {type: str}\n packages:\n seq:\n - {type: str}\ndiff --git a/requirements.txt b/requirements.txt\nindex f7e4f1f..43c4660 100644\n--- a/requirements.txt\n+++ b/requirements.txt\n@@ -3,3 +3,4 @@ Jinja2>=2.8\n requests>=2.8.1\n six>=1.10.0\n pykwalify>=1.5.1\n+colorlog>=2.10.0\n", "test_patch": "diff --git a/tests/test_unit_generate_handle_files.py b/tests/test_unit_generate_handle_files.py\nindex eb85ab9..daf240a 100644\n--- a/tests/test_unit_generate_handle_files.py\n+++ b/tests/test_unit_generate_handle_files.py\n@@ -1,6 +1,7 @@\n import argparse\n import unittest\n import mock\n+import os\n import six\n \n from dogen.generator import Generator\n@@ -45,8 +46,8 @@ class TestFetchFile(unittest.TestCase):\n mock_requests.assert_called_with('https://host/file.tmp', verify=None, stream=True)\n mock_file().write.assert_called_once_with(\"file-content\")\n \n- self.log.info.assert_any_call(\"Fetching 'https://host/file.tmp' file...\")\n- self.log.info.assert_any_call(\"Fetched file will be saved as 'some-file'...\")\n+ self.log.debug.assert_any_call(\"Fetching 'https://host/file.tmp' file...\")\n+ self.log.debug.assert_any_call(\"Fetched file will be saved as 'some-file'...\")\n \n \n @mock.patch('dogen.generator.tempfile.mktemp', return_value=\"tmpfile\")\n@@ -64,8 +65,8 @@ class TestFetchFile(unittest.TestCase):\n mock_requests.assert_called_with('https://host/file.tmp', verify=None, stream=True)\n mock_file().write.assert_called_once_with(\"file-content\")\n \n- self.log.info.assert_any_call(\"Fetching 'https://host/file.tmp' file...\")\n- self.log.info.assert_any_call(\"Fetched file will be saved as 'tmpfile'...\")\n+ self.log.debug.assert_any_call(\"Fetching 'https://host/file.tmp' file...\")\n+ self.log.debug.assert_any_call(\"Fetched file will be saved as 'tmpfile'...\")\n \n class TestCustomTemplateHandling(unittest.TestCase):\n def setUp(self):\n@@ -113,3 +114,76 @@ class TestCustomTemplateHandling(unittest.TestCase):\n \n fetch_file_mock.assert_called_with(\"http://host/custom-template\")\n self.assertEqual(self.generator.template, \"some-tmp-file\")\n+\n+class TestHandleSources(unittest.TestCase):\n+ def setUp(self):\n+ self.log = mock.Mock()\n+ args = argparse.Namespace(path=\"image.yaml\", output=\"target\", without_sources=None,\n+ template=\"http://host/custom-template\", scripts_path=None,\n+ additional_script=None, skip_ssl_verification=None)\n+ self.generator = Generator(self.log, args)\n+\n+ def test_fetch_artifact_without_url_should_fail(self):\n+ self.generator.cfg = {'sources': [{'artifact': 'jboss-eap.zip'}]}\n+\n+ with self.assertRaises(Error) as cm:\n+ self.generator.handle_sources()\n+\n+ self.assertEquals(str(cm.exception), \"Artifact 'jboss-eap.zip' could not be fetched!\")\n+\n+ @mock.patch('dogen.generator.Generator._fetch_file', side_effect=Error(\"Blah\"))\n+ def test_fetch_artifact_should_fail_when_fetching_fails(self, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'http://jboss-eap.zip'}]}\n+\n+ with self.assertRaises(Error) as cm:\n+ self.generator.handle_sources()\n+\n+ self.assertEquals(str(cm.exception), \"Could not download artifact from orignal location, reason: Blah\")\n+\n+ @mock.patch('dogen.generator.Generator._fetch_file', side_effect=[Error(\"cached\"), Error(\"original\")])\n+ def test_fetch_artifact_should_fail_when_cached_download_failed_and_original_failed_too(self, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n+\n+ k = mock.patch.dict(os.environ, {'DOGEN_SOURCES_CACHE':'http://cache/get?#algorithm#=#hash#'})\n+ k.start()\n+\n+ with self.assertRaises(Error) as cm:\n+ self.generator.handle_sources()\n+\n+ k.stop()\n+\n+ self.assertEquals(str(cm.exception), \"Could not download artifact from orignal location, reason: original\")\n+ mock_fetch_file.assert_has_calls([mock.call('http://cache/get?#algorithm#=#hash#', 'target/jboss-eap.zip'), mock.call('http://host.com/jboss-eap.zip', 'target/jboss-eap.zip')])\n+\n+ @mock.patch('dogen.generator.Generator._fetch_file')\n+ def test_fetch_artifact_should_fetch_file_from_cache(self, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n+\n+ k = mock.patch.dict(os.environ, {'DOGEN_SOURCES_CACHE':'http://cache/get?#filename#'})\n+ k.start()\n+ self.generator.handle_sources()\n+ k.stop()\n+\n+ # No checksum provided and computed\n+ self.assertEquals(self.generator.cfg['artifacts'], {'jboss-eap.zip': None})\n+ mock_fetch_file.assert_called_with('http://cache/get?jboss-eap.zip', 'target/jboss-eap.zip')\n+\n+ @mock.patch('dogen.generator.Generator._fetch_file')\n+ def test_fetch_artifact_should_fetch_file(self, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n+ self.generator.handle_sources()\n+ # No checksum provided and computed\n+ self.assertEquals(self.generator.cfg['artifacts'], {'jboss-eap.zip': None})\n+ mock_fetch_file.assert_called_with('http://host.com/jboss-eap.zip', 'target/jboss-eap.zip')\n+\n+ @mock.patch('dogen.generator.Generator._fetch_file', side_effect=[Error(\"cached\"), None])\n+ def test_fetch_artifact_should_download_from_original_location_if_cached_location_failed(self, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n+\n+ k = mock.patch.dict(os.environ, {'DOGEN_SOURCES_CACHE':'http://cache/get?#algorithm#=#hash#'})\n+ k.start()\n+ self.generator.handle_sources()\n+ k.stop()\n+\n+ self.assertEquals(self.generator.cfg['artifacts'], {'jboss-eap.zip': None})\n+ mock_fetch_file.assert_has_calls([mock.call('http://cache/get?#algorithm#=#hash#', 'target/jboss-eap.zip'), mock.call('http://host.com/jboss-eap.zip', 'target/jboss-eap.zip')])\n", "FAIL_TO_PASS": ["tests/test_unit_generate_handle_files.py::TestFetchFile::test_fetching_with_filename", "tests/test_unit_generate_handle_files.py::TestFetchFile::test_fetching_with_tmpfile", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_download_from_original_location_if_cached_location_failed", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_when_cached_download_failed_and_original_failed_too", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_when_fetching_fails", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fetch_file", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_without_url_should_fail"]}, {"instance_id": "jboss-dockerfiles__dogen-149", "base_commit": "a475173ce00b2d6686c601ffc46a8d2bc3ed0a7f", "gold_patch": "diff --git a/dogen/generator.py b/dogen/generator.py\nindex 0562cd8..415dcb0 100644\n--- a/dogen/generator.py\n+++ b/dogen/generator.py\n@@ -313,9 +313,10 @@ class Generator(object):\n algorithms.append(supported_algorithm)\n \n try:\n- if os.path.exists(filename) and algorithms:\n- for algorithm in algorithms:\n- self.check_sum(filename, source[algorithm], algorithm)\n+ if os.path.exists(filename):\n+ if algorithms:\n+ for algorithm in algorithms:\n+ self.check_sum(filename, source[algorithm], algorithm)\n passed = True\n except Exception as e:\n self.log.debug(str(e))\n@@ -361,7 +362,7 @@ class Generator(object):\n else:\n if hint:\n self.log.info(hint)\n- self.log.info(\"Please download the '%s' artifact manually and save it as '%s'\" % (artifact, filename))\n+ self.log.info(\"Please download the '%s' artifact manually and save it as '%s'\" % (artifact, filename))\n raise Error(\"Artifact '%s' could not be fetched!\" % artifact)\n \n def check_sum(self, filename, checksum, algorithm):\n", "test_patch": "diff --git a/tests/test_unit_generate_handle_files.py b/tests/test_unit_generate_handle_files.py\nindex daf240a..e811ebb 100644\n--- a/tests/test_unit_generate_handle_files.py\n+++ b/tests/test_unit_generate_handle_files.py\n@@ -155,6 +155,17 @@ class TestHandleSources(unittest.TestCase):\n self.assertEquals(str(cm.exception), \"Could not download artifact from orignal location, reason: original\")\n mock_fetch_file.assert_has_calls([mock.call('http://cache/get?#algorithm#=#hash#', 'target/jboss-eap.zip'), mock.call('http://host.com/jboss-eap.zip', 'target/jboss-eap.zip')])\n \n+ @mock.patch('dogen.generator.Generator._fetch_file')\n+ def test_fetch_artifact_should_fail_with_nice_message_when_artifact_without_url_is_not_found_locally(self, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'jboss-eap.zip'}]}\n+\n+ with self.assertRaises(Error) as cm:\n+ self.generator.handle_sources()\n+\n+ self.assertEquals(str(cm.exception), \"Artifact 'jboss-eap.zip' could not be fetched!\")\n+ mock_fetch_file.assert_not_called()\n+ self.log.info.assert_any_call(\"Please download the 'jboss-eap.zip' artifact manually and save it as 'target/jboss-eap.zip'\")\n+\n @mock.patch('dogen.generator.Generator._fetch_file')\n def test_fetch_artifact_should_fetch_file_from_cache(self, mock_fetch_file):\n self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n@@ -169,7 +180,8 @@ class TestHandleSources(unittest.TestCase):\n mock_fetch_file.assert_called_with('http://cache/get?jboss-eap.zip', 'target/jboss-eap.zip')\n \n @mock.patch('dogen.generator.Generator._fetch_file')\n- def test_fetch_artifact_should_fetch_file(self, mock_fetch_file):\n+ @mock.patch('dogen.generator.os.path.exists', return_value=False)\n+ def test_fetch_artifact_should_fetch_file(self, mock_path_exists, mock_fetch_file):\n self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n self.generator.handle_sources()\n # No checksum provided and computed\n@@ -187,3 +199,12 @@ class TestHandleSources(unittest.TestCase):\n \n self.assertEquals(self.generator.cfg['artifacts'], {'jboss-eap.zip': None})\n mock_fetch_file.assert_has_calls([mock.call('http://cache/get?#algorithm#=#hash#', 'target/jboss-eap.zip'), mock.call('http://host.com/jboss-eap.zip', 'target/jboss-eap.zip')])\n+\n+ @mock.patch('dogen.generator.Generator._fetch_file')\n+ @mock.patch('dogen.generator.os.path.exists', return_value=True)\n+ def test_fetch_artifact_should_not_fetch_file_if_exists(self, mock_path_exists, mock_fetch_file):\n+ self.generator.cfg = {'sources': [{'artifact': 'http://host.com/jboss-eap.zip'}]}\n+ self.generator.handle_sources()\n+ # No checksum provided and computed\n+ self.assertEquals(self.generator.cfg['artifacts'], {'jboss-eap.zip': None})\n+ mock_fetch_file.assert_not_called()\n", "FAIL_TO_PASS": ["tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_with_nice_message_when_artifact_without_url_is_not_found_locally", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_not_fetch_file_if_exists"]}, {"instance_id": "jboss-dockerfiles__dogen-196", "base_commit": "611898a32fca936d5a45368f049c1e3f74ea3c2f", "gold_patch": "diff --git a/dogen/generator.py b/dogen/generator.py\nindex 1106f49..3a13051 100644\n--- a/dogen/generator.py\n+++ b/dogen/generator.py\n@@ -232,13 +232,24 @@ class Generator(object):\n if not self.cfg.get('labels'):\n self.cfg['labels'] = []\n \n+ labels = {}\n+\n+ for label in self.cfg.get('labels'):\n+ labels[label['name']] = label['value']\n+\n # https://github.com/jboss-dockerfiles/dogen/issues/129\n # https://github.com/jboss-dockerfiles/dogen/issues/137\n for label in ['maintainer', 'description']:\n value = self.cfg.get(label)\n \n- if value:\n+ if value and not label in labels:\n self.cfg['labels'].append({'name': label, 'value': value})\n+ labels[label] = value\n+\n+ # https://github.com/jboss-dockerfiles/dogen/issues/195\n+ if 'summary' not in labels:\n+ if 'description' in labels:\n+ self.cfg['labels'].append({'name': 'summary', 'value': labels.get('description')})\n \n if self.template:\n template_file = self.template\n", "test_patch": "diff --git a/tests/test_dockerfile.py b/tests/test_dockerfile.py\nindex 3ab2885..9f34741 100644\n--- a/tests/test_dockerfile.py\n+++ b/tests/test_dockerfile.py\n@@ -170,7 +170,7 @@ class TestDockerfile(unittest.TestCase):\n generator.configure()\n generator.render_from_template()\n \n- self.assertEqual(generator.cfg['labels'], [{'name': 'description', 'value': 'This is a nice image'}])\n+ self.assertEqual(generator.cfg['labels'], [{'name': 'description', 'value': 'This is a nice image'}, {'name': 'summary', 'value': 'This is a nice image'}])\n \n with open(os.path.join(self.target, \"Dockerfile\"), \"r\") as f:\n dockerfile = f.read()\n", "FAIL_TO_PASS": ["tests/test_dockerfile.py::TestDockerfile::test_generating_description_label"]}], "all_FAIL_TO_PASS": ["tests/test_unit_generate_handle_files.py::TestFetchFile::test_fetching_with_filename", "tests/test_unit_generate_handle_files.py::TestFetchFile::test_fetching_with_tmpfile", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_download_from_original_location_if_cached_location_failed", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_when_cached_download_failed_and_original_failed_too", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_when_fetching_fails", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fetch_file", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_without_url_should_fail", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_fail_with_nice_message_when_artifact_without_url_is_not_found_locally", "tests/test_unit_generate_handle_files.py::TestHandleSources::test_fetch_artifact_should_not_fetch_file_if_exists", "tests/test_dockerfile.py::TestDockerfile::test_generating_description_label"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NREL__hescore-hpxml-137_x3", "level": 3, "source": "swerebench", "repo": "NREL/hescore-hpxml", "image": "swerebench/sweb.eval.x86_64.nrel_1776_hescore-hpxml-137:latest", "base_commit": "1bd1dd87237c00280c2150d96df6a33919659836", "num_bugs": 3, "bugs": [{"instance_id": "NREL__hescore-hpxml-137", "base_commit": "1bd1dd87237c00280c2150d96df6a33919659836", "gold_patch": "diff --git a/examples/house6.xml b/examples/house6.xml\nindex 0ab806c2..fdc7713d 100644\n--- a/examples/house6.xml\n+++ b/examples/house6.xml\n@@ -32,7 +32,7 @@\n single-family detached\n 2\n 8\n- 11\n+ 10\n 2600\n \n \ndiff --git a/examples/house6_v3.xml b/examples/house6_v3.xml\nindex 83d2f02f..c8c2c7d8 100644\n--- a/examples/house6_v3.xml\n+++ b/examples/house6_v3.xml\n@@ -32,7 +32,7 @@\n single-family detached\n 2\n 8\n- 11\n+ 10\n 2600\n \n \ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 3dc254f5..e8c9380b 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -927,8 +927,6 @@ class HPXMLtoHEScoreTranslatorBase(object):\n bldg_cons_el = xpath(b, 'h:BuildingDetails/h:BuildingSummary/h:BuildingConstruction', raise_err=True)\n bldg_about['year_built'] = int(xpath(bldg_cons_el, 'h:YearBuilt/text()', raise_err=True))\n nbedrooms = int(xpath(bldg_cons_el, 'h:NumberofBedrooms/text()', raise_err=True))\n- if nbedrooms > 10:\n- nbedrooms = 10\n bldg_about['number_bedrooms'] = nbedrooms\n bldg_about['num_floor_above_grade'] = int(\n math.ceil(float(xpath(bldg_cons_el, 'h:NumberofConditionedFloorsAboveGrade/text()', raise_err=True))))\n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 50571e69..5dd4fd65 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -1149,6 +1149,14 @@ class TestInputOutOfBounds(unittest.TestCase, ComparatorBase):\n 'num_floor_above_grade is out of bounds',\n tr.hpxml_to_hescore)\n \n+ def test_number_bedrooms(self):\n+ tr = self._load_xmlfile('hescore_min')\n+ el = self.xpath('//h:NumberofBedrooms')\n+ el.text = '25'\n+ self.assertRaisesRegex(InputOutOfBounds,\n+ 'number_bedrooms is out of bounds',\n+ tr.hpxml_to_hescore)\n+\n def test_floor_to_ceiling_height1(self):\n tr = self._load_xmlfile('hescore_min')\n el = self.xpath('//h:AverageCeilingHeight')\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestInputOutOfBounds::test_number_bedrooms"]}, {"instance_id": "NREL__hescore-hpxml-139", "base_commit": "1bd1dd87237c00280c2150d96df6a33919659836", "gold_patch": "diff --git a/docs/source/translation/zone_window.rst b/docs/source/translation/zone_window.rst\nindex 2275a2c5..22a50602 100644\n--- a/docs/source/translation/zone_window.rst\n+++ b/docs/source/translation/zone_window.rst\n@@ -36,7 +36,9 @@ window properties be assigned to each direction, the\n windows will be specified separately. \n \n Skylights in HEScore do not have an orientation that can be set, therefore\n-orientation/azimuth information about skylights is ignored.\n+orientation/azimuth information about skylights is ignored. Use `AttachedToRoof`\n+to specify which HPXML roof each skylight is attached to. If not specified, skylights\n+will be assigned to the first hescore roof.\n \n .. _window-prop:\n \ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 3dc254f5..07959248 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -758,9 +758,9 @@ class HPXMLtoHEScoreTranslatorBase(object):\n bldg['zone']['zone_floor'] = self.get_building_zone_floor(b, bldg['about'])\n footprint_area = self.get_footprint_area(bldg)\n bldg['zone']['zone_roof'] = self.get_building_zone_roof(b, footprint_area)\n- bldg['zone']['zone_roof'][0]['zone_skylight'] = self.get_skylights(b)\n- for zone_roof in bldg['zone']['zone_roof'][1:]:\n- zone_roof['zone_skylight'] = {'skylight_area': 0}\n+ skylights = self.get_skylights(b, bldg['zone']['zone_roof'])\n+ for roof_num in range(len(bldg['zone']['zone_roof'])):\n+ bldg['zone']['zone_roof'][roof_num]['zone_skylight'] = skylights[roof_num]\n bldg['zone']['wall_construction_same'] = False\n bldg['zone']['window_construction_same'] = False\n bldg['zone']['zone_wall'] = self.get_building_zone_wall(b, bldg['about'])\n@@ -1155,9 +1155,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n del atticd['roof_absorptance']\n \n # ids of hpxml roofs along for the ride\n- atticd['_roofid'] = ''\n- for attic_roofs_dict in attic_roof_ls:\n- atticd['_roofid'] += attic_roofs_dict['roof_id']\n+ atticd['_roofid'] = set([attic_roofs_dict['roof_id'] for attic_roofs_dict in attic_roof_ls])\n \n # Calculate roof area weighted center of cavity R-value for attic,\n # might be combined later by averaging again\n@@ -1194,7 +1192,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n raise TranslationError('There are no Attic elements in this building.')\n elif len(atticds) <= 2:\n for atticd in atticds:\n- atticd['_roofids'] = {atticd['_roofid']}\n+ atticd['_roofids'] = atticd['_roofid']\n del atticd['_roofid']\n elif len(atticds) > 2:\n # If there are more than two attics, combine and average by rooftype.\n@@ -1224,7 +1222,7 @@ class HPXMLtoHEScoreTranslatorBase(object):\n combined_atticd[attic_key] = max(roof_area_by_cat, key=lambda x: roof_area_by_cat[x])\n \n # ids of hpxml roofs along for the ride\n- combined_atticd['_roofids'] = set([atticd['_roofid'] for atticd in atticds])\n+ combined_atticd['_roofids'] = set().union(*[atticd['_roofid'] for atticd in atticds])\n \n # Calculate roof area weighted center of cavity R-value\n combined_atticd['roof_coc_rvalue'] = \\\n@@ -1274,70 +1272,102 @@ class HPXMLtoHEScoreTranslatorBase(object):\n \n return zone_roof\n \n- def get_skylights(self, b):\n+ def get_skylights(self, b, zone_roof):\n ns = self.ns\n xpath = self.xpath\n skylights = b.xpath('descendant::h:Skylight', namespaces=ns)\n \n- zone_skylight = OrderedDict()\n-\n- if len(skylights) == 0:\n- zone_skylight['skylight_area'] = 0\n- return zone_skylight\n-\n- # Get areas, u-factors, and shgcs if they exist\n- uvalues, shgcs, areas = map(list, zip(*[[xpath(skylight, 'h:%s/text()' % x)\n- for x in ('UFactor', 'SHGC', 'Area')]\n- for skylight in skylights]))\n- if None in areas:\n- raise TranslationError('Every skylight needs an area.')\n- areas = list(map(float, areas))\n- zone_skylight['skylight_area'] = sum(areas)\n-\n- # Remove skylights from the calculation where a uvalue or shgc isn't set.\n- idxstoremove = set()\n- for i, uvalue in enumerate(uvalues):\n- if uvalue is None:\n- idxstoremove.add(i)\n- for i, shgc in enumerate(shgcs):\n- if shgc is None:\n- idxstoremove.add(i)\n- for i in sorted(idxstoremove, reverse=True):\n- uvalues.pop(i)\n- shgcs.pop(i)\n- areas.pop(i)\n- assert len(uvalues) == len(shgcs)\n- uvalues = list(map(float, uvalues))\n- shgcs = list(map(float, shgcs))\n-\n- if len(uvalues) > 0:\n- # Use an area weighted average of the uvalues, shgcs\n- zone_skylight['skylight_method'] = 'custom'\n- zone_skylight['skylight_u_value'] = old_div(sum(\n- [uvalue * area for (uvalue, area) in zip(uvalues, areas)]), sum(areas))\n- zone_skylight['skylight_shgc'] = sum([shgc * area for (shgc, area) in zip(shgcs, areas)]) / sum(areas)\n- else:\n- # use a construction code\n- skylight_type_areas = {}\n+ skylight_by_roof_id = {}\n+ skylight_by_roof_num = {}\n+ for i in range(len(zone_roof)):\n+ skylight_by_roof_num[i] = []\n+\n+ for skylight in skylights:\n+ if xpath(skylight, 'h:AttachedToRoof/@idref') is None:\n+ # No roof attached, attach to the first roof\n+ skylight_by_roof_num[0].append(skylight)\n+ else:\n+ try:\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')].append(skylight)\n+ except KeyError:\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')] = []\n+ skylight_by_roof_id[xpath(skylight, 'h:AttachedToRoof/@idref')].append(skylight)\n+\n+ for roof_id, skylights in list(skylight_by_roof_id.items()):\n+ # roof_found = False\n+ for i in range(len(zone_roof)):\n+ if roof_id in zone_roof[i]['_roofids']:\n+ # roof_found = True\n+ for skylight in skylights:\n+ skylight_by_roof_num[i].append(skylight)\n+ break\n+ # if not roof_found:\n+ # The roof attached is not simulated, should we: 1. attach to the first roof or 2. discard the skylight?\n+ # for skylight in skylights:\n+ # skylight_by_roof_num[0].append(skylight)\n+\n+ # combine skylights by roof_num\n+ zone_skylight = []\n+ for roof_num, skylights in list(skylight_by_roof_num.items()):\n+ skylight_d = OrderedDict()\n+ zone_skylight.append(skylight_d)\n+\n+ if len(skylights) == 0:\n+ skylight_d['skylight_area'] = 0\n+ continue\n+ # Get areas, u-factors, and shgcs if they exist\n+ uvalues, shgcs, areas = map(list, zip(*[[xpath(skylight, 'h:%s/text()' % x)\n+ for x in ('UFactor', 'SHGC', 'Area')]\n+ for skylight in skylights]))\n+ if None in areas:\n+ raise TranslationError('Every skylight needs an area.')\n+ areas = list(map(float, areas))\n+ skylight_d['skylight_area'] = sum(areas)\n+\n+ # Remove skylights from the calculation where a uvalue or shgc isn't set.\n+ idxstoremove = set()\n+ for i, uvalue in enumerate(uvalues):\n+ if uvalue is None:\n+ idxstoremove.add(i)\n+ for i, shgc in enumerate(shgcs):\n+ if shgc is None:\n+ idxstoremove.add(i)\n+ for i in sorted(idxstoremove, reverse=True):\n+ uvalues.pop(i)\n+ shgcs.pop(i)\n+ areas.pop(i)\n+ assert len(uvalues) == len(shgcs)\n+ uvalues = list(map(float, uvalues))\n+ shgcs = list(map(float, shgcs))\n+\n+ if len(uvalues) > 0:\n+ # Use an area weighted average of the uvalues, shgcs\n+ skylight_d['skylight_method'] = 'custom'\n+ skylight_d['skylight_u_value'] = old_div(sum(\n+ [uvalue * area for (uvalue, area) in zip(uvalues, areas)]), sum(areas))\n+ skylight_d['skylight_shgc'] = sum([shgc * area for (shgc, area) in zip(shgcs, areas)]) / sum(areas)\n+ else:\n+ # use a construction code\n+ skylight_type_areas = {}\n+ for skylight in skylights:\n+ area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n+ skylight_code = self.get_window_code(skylight)\n+ try:\n+ skylight_type_areas[skylight_code] += area\n+ except KeyError:\n+ skylight_type_areas[skylight_code] = area\n+ skylight_d['skylight_method'] = 'code'\n+ skylight_d['skylight_code'] = max(list(skylight_type_areas.items()), key=lambda x: x[1])[0]\n+ skylight_sunscreen_areas = {}\n for skylight in skylights:\n+ solar_screen = self.get_sunscreen(skylight)\n area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n- skylight_code = self.get_window_code(skylight)\n try:\n- skylight_type_areas[skylight_code] += area\n+ skylight_sunscreen_areas[solar_screen] += area\n except KeyError:\n- skylight_type_areas[skylight_code] = area\n- zone_skylight['skylight_method'] = 'code'\n- zone_skylight['skylight_code'] = max(list(skylight_type_areas.items()), key=lambda x: x[1])[0]\n- skylight_sunscreen_areas = {}\n- for skylight in skylights:\n- solar_screen = self.get_sunscreen(skylight)\n- area = convert_to_type(float, xpath(skylight, 'h:Area/text()', raise_err=True))\n- try:\n- skylight_sunscreen_areas[solar_screen] += area\n- except KeyError:\n- skylight_sunscreen_areas[solar_screen] = area\n+ skylight_sunscreen_areas[solar_screen] = area\n \n- zone_skylight['solar_screen'] = max(list(skylight_sunscreen_areas.items()), key=lambda x: x[1])[0]\n+ skylight_d['solar_screen'] = max(list(skylight_sunscreen_areas.items()), key=lambda x: x[1])[0]\n \n return zone_skylight\n \n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 50571e69..b59531b7 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -2669,6 +2669,45 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n self.assertEqual(d_4['building']['systems']['hvac'], d_4_v3['building']['systems']['hvac'])\n \n \n+class TestHEScore2021Updates(unittest.TestCase, ComparatorBase):\n+\n+ def test_skylight_assignment(self):\n+ tr = self._load_xmlfile('house4_v3')\n+ attach_roof = etree.Element(tr.addns('h:AttachedToRoof'))\n+ attach_roof.attrib['idref'] = \"roof2\"\n+ glass_type = self.xpath('//h:Skylight/h:GlassType')\n+ glass_type.addnext(attach_roof)\n+ res = tr.hpxml_to_hescore()\n+ # Skylight attached to the second roof\n+ self.assertEqual(res['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 12.0)\n+ self.assertEqual(res['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+ skylight = self.xpath('//h:Skylight')\n+ skylight_2 = deepcopy(skylight)\n+ skylight.addnext(skylight_2)\n+ tr.xpath(skylight_2, 'h:SystemIdentifier').attrib['id'] = \"skylight2\"\n+ tr.xpath(skylight_2, 'h:AttachedToRoof').attrib['idref'] = \"roof1\"\n+ tr.xpath(skylight_2, 'h:Area').text = \"15\"\n+ res2 = tr.hpxml_to_hescore()\n+ # Skylight attached to the first and second roof\n+ self.assertEqual(res2['building']['zone']['zone_roof'][0]['zone_skylight']['skylight_area'], 15.0)\n+ self.assertEqual(res2['building']['zone']['zone_roof'][0]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res2['building']['zone']['zone_roof'][0]['zone_skylight']['solar_screen'])\n+ self.assertEqual(res2['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 12.0)\n+ self.assertEqual(res2['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res2['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+ tr.xpath(skylight_2, 'h:AttachedToRoof').attrib['idref'] = \"roof2\"\n+ tr.xpath(skylight_2, 'h:Area').text = \"10\"\n+ tr.xpath(skylight_2, 'h:GlassType').text = \"low-e\"\n+ # skylight1 dominates the properties\n+ res3 = tr.hpxml_to_hescore()\n+ self.assertEqual(res3['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_area'], 22.0)\n+ self.assertEqual(res3['building']['zone']['zone_roof'][1]['zone_skylight']['skylight_code'], 'dtab')\n+ self.assertFalse(res3['building']['zone']['zone_roof'][1]['zone_skylight']['solar_screen'])\n+\n+\n class TestHEScoreV3(unittest.TestCase, ComparatorBase):\n \n def test_attic_with_multiple_roofs(self):\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestHEScore2021Updates::test_skylight_assignment"]}, {"instance_id": "NREL__hescore-hpxml-149", "base_commit": "e5af84582b4524ad92bac0a9f153051f2d39f5eb", "gold_patch": "diff --git a/docs/source/translation/about.rst b/docs/source/translation/about.rst\nindex c083c764..6eebb65c 100644\n--- a/docs/source/translation/about.rst\n+++ b/docs/source/translation/about.rst\n@@ -10,15 +10,6 @@ HEScore requires an assessment date. If a date is stored in the element\n ``Building/ProjectStatus/Date``, that date is used. If not, the current date is\n used.\n \n-External Building ID\n-********************\n-\n-The value of ``Building/extension/HESExternalID`` or\n-``Building/BuildingID/SendingSystemIdentifierValue``, if present, is copied into the\n-``building.about.external_building_id`` field in HEScore.\n-Preference is given to the `extension` element if both are present.\n-This is optional, but may be useful for those wanting to pass an additional building identifier for their own tracking purposes.\n-\n Building Shape\n **************\n \ndiff --git a/docs/source/translation/building_address.rst b/docs/source/translation/building_address.rst\nindex 2937502f..33449491 100644\n--- a/docs/source/translation/building_address.rst\n+++ b/docs/source/translation/building_address.rst\n@@ -91,3 +91,12 @@ element in the ``extension`` of ``Building/ProjectStatus``:\n \n Upon finding this ``HEScoreMentorAssessment`` element, the HEScore assessment\n type will be set to \"mentor\" regardless of the mapping :ref:`above `.\n+\n+External Building ID\n+********************\n+\n+The value of ``Building/extension/HESExternalID`` or\n+``Building/BuildingID/SendingSystemIdentifierValue``, if present, is copied into the\n+``building_address.external_building_id`` field in HEScore.\n+Preference is given to the `extension` element if both are present.\n+This is optional, but may be useful for those wanting to pass an additional building identifier for their own tracking purposes.\ndiff --git a/hescorehpxml/base.py b/hescorehpxml/base.py\nindex 0c9b2559..4f3a4544 100644\n--- a/hescorehpxml/base.py\n+++ b/hescorehpxml/base.py\n@@ -828,6 +828,17 @@ class HPXMLtoHEScoreTranslatorBase(object):\n else:\n assert transaction_type == 'update'\n bldgaddr['assessment_type'] = 'corrected'\n+\n+ ext_id_xpath_exprs = (\n+ 'h:extension/h:HESExternalID/text()',\n+ 'h:BuildingID/h:SendingSystemIdentifierValue/text()'\n+ )\n+ for ext_id_xpath_expr in ext_id_xpath_exprs:\n+ external_id_value = xpath(b, ext_id_xpath_expr)\n+ if external_id_value is not None:\n+ bldgaddr['external_building_id'] = external_id_value\n+ break\n+\n return bldgaddr\n \n def get_hpwes(self, p, c):\n@@ -869,16 +880,6 @@ class HPXMLtoHEScoreTranslatorBase(object):\n ns = self.ns\n bldg_about = OrderedDict()\n \n- ext_id_xpath_exprs = (\n- 'h:extension/h:HESExternalID/text()',\n- 'h:BuildingID/h:SendingSystemIdentifierValue/text()'\n- )\n- for ext_id_xpath_expr in ext_id_xpath_exprs:\n- external_id_value = xpath(b, ext_id_xpath_expr)\n- if external_id_value is not None:\n- bldg_about['external_building_id'] = external_id_value\n- break\n-\n project_status_date_el = b.find('h:ProjectStatus/h:Date', namespaces=ns)\n if project_status_date_el is None:\n bldg_about['assessment_date'] = dt.date.today()\n", "test_patch": "diff --git a/tests/test_translation.py b/tests/test_translation.py\nindex 47a0e703..8287a01b 100644\n--- a/tests/test_translation.py\n+++ b/tests/test_translation.py\n@@ -1056,7 +1056,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n myid = uuid.uuid4().hex\n el.text = myid\n res = tr.hpxml_to_hescore()\n- self.assertEqual(myid, res['building']['about'].get('external_building_id'))\n+ self.assertEqual(myid, res['building_address'].get('external_building_id'))\n \n def test_external_id_extension_passthru(self):\n tr = self._load_xmlfile('hescore_min')\n@@ -1069,7 +1069,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = etree.SubElement(self.xpath('//h:Building/h:BuildingID'), tr.addns('h:SendingSystemIdentifierValue'))\n el.text = uuid.uuid4().hex\n res = tr.hpxml_to_hescore()\n- self.assertEqual(myid, res['building']['about'].get('external_building_id'))\n+ self.assertEqual(myid, res['building_address'].get('external_building_id'))\n \n def test_preconstruction_event_type(self):\n tr = self._load_xmlfile('hescore_min')\n", "FAIL_TO_PASS": ["tests/test_translation.py::TestOtherHouses::test_external_id_extension_passthru", "tests/test_translation.py::TestOtherHouses::test_external_id_passthru"]}], "all_FAIL_TO_PASS": ["tests/test_translation.py::TestInputOutOfBounds::test_number_bedrooms", "tests/test_translation.py::TestHEScore2021Updates::test_skylight_assignment", "tests/test_translation.py::TestOtherHouses::test_external_id_extension_passthru", "tests/test_translation.py::TestOtherHouses::test_external_id_passthru"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "yukinarit__pyserde-208_x3", "level": 3, "source": "swerebench", "repo": "yukinarit/pyserde", "image": "swerebench/sweb.eval.x86_64.yukinarit_1776_pyserde-208:latest", "base_commit": "508c54d86a5e1fb954eea865e32ea426ee98f1cc", "num_bugs": 3, "bugs": [{"instance_id": "yukinarit__pyserde-208", "base_commit": "508c54d86a5e1fb954eea865e32ea426ee98f1cc", "gold_patch": "diff --git a/serde/compat.py b/serde/compat.py\nindex 8c1af36..b5e2143 100644\n--- a/serde/compat.py\n+++ b/serde/compat.py\n@@ -121,6 +121,11 @@ def typename(typ) -> str:\n else:\n return 'Union'\n elif is_list(typ):\n+ # Workaround for python 3.7.\n+ # get_args for the bare List returns parameter T.\n+ if typ is List:\n+ return 'List'\n+\n args = type_args(typ)\n if args:\n et = typename(args[0])\n@@ -128,6 +133,11 @@ def typename(typ) -> str:\n else:\n return 'List'\n elif is_set(typ):\n+ # Workaround for python 3.7.\n+ # get_args for the bare Set returns parameter T.\n+ if typ is Set:\n+ return 'Set'\n+\n args = type_args(typ)\n if args:\n et = typename(args[0])\n@@ -135,6 +145,11 @@ def typename(typ) -> str:\n else:\n return 'Set'\n elif is_dict(typ):\n+ # Workaround for python 3.7.\n+ # get_args for the bare Dict returns parameter K, V.\n+ if typ is Dict:\n+ return 'Dict'\n+\n args = type_args(typ)\n if args and len(args) == 2:\n kt = typename(args[0])\ndiff --git a/serde/de.py b/serde/de.py\nindex e76660b..3416505 100644\n--- a/serde/de.py\n+++ b/serde/de.py\n@@ -562,7 +562,9 @@ class Renderer:\n res = self.default(arg, res)\n \n if self.custom and not arg.deserializer:\n- return self.custom_class_deserializer(arg, res)\n+ # Rerender the code for default deserializer.\n+ default = Renderer(self.func, self.cls, None).render(arg)\n+ return self.custom_class_deserializer(arg, default)\n else:\n return res\n \n", "test_patch": "diff --git a/tests/test_compat.py b/tests/test_compat.py\nindex f0819ff..8991865 100644\n--- a/tests/test_compat.py\n+++ b/tests/test_compat.py\n@@ -1,5 +1,6 @@\n import sys\n from dataclasses import dataclass\n+from datetime import datetime\n from typing import Dict, Generic, List, NewType, Optional, Set, Tuple, TypeVar, Union\n \n import serde\n@@ -67,9 +68,18 @@ def test_typename():\n class Foo(Generic[T]):\n nested: Bar[T]\n \n- assert typename(Optional) == \"Optional\"\n assert typename(Foo[int]) == \"Foo\"\n assert typename(Foo) == \"Foo\"\n+ assert typename(List[int]) == \"List[int]\"\n+ assert typename(Optional) == \"Optional\"\n+ assert typename(List) == \"List\"\n+ assert typename(List[int]) == \"List[int]\"\n+ assert typename(Tuple) == \"Tuple\"\n+ assert typename(Tuple[int, str]) == \"Tuple[int, str]\"\n+ assert typename(Dict) == \"Dict\"\n+ assert typename(Dict[str, Foo]) == \"Dict[str, Foo]\"\n+ assert typename(Set) == \"Set\"\n+ assert typename(Set[int]) == \"Set[int]\"\n \n \n def test_iter_types():\n@@ -79,6 +89,17 @@ def test_iter_types():\n assert [Tuple, int, str, bool, float] == list(iter_types(Tuple[int, str, bool, float]))\n assert [PriOpt, Optional, int, Optional, str, Optional, float, Optional, bool] == list(iter_types(PriOpt))\n \n+ @serde.serde\n+ class Foo:\n+ a: int\n+ b: datetime\n+ c: datetime\n+ d: Optional[str] = None\n+ e: Union[str, int] = 10\n+ f: List[int] = serde.field(default_factory=list)\n+\n+ assert [Foo, int, datetime, datetime, Optional, str, Union, str, int, List, int] == list(iter_types(Foo))\n+\n \n def test_iter_unions():\n assert [Union[str, int]] == list(iter_unions(Union[str, int]))\ndiff --git a/tests/test_custom.py b/tests/test_custom.py\nindex 060f046..dc75515 100644\n--- a/tests/test_custom.py\n+++ b/tests/test_custom.py\n@@ -2,7 +2,7 @@\n Tests for custom serializer/deserializer.\n \"\"\"\n from datetime import datetime\n-from typing import Optional, Union\n+from typing import List, Optional, Union\n \n import pytest\n \n@@ -81,14 +81,15 @@ def test_custom_class_serializer():\n c: datetime\n d: Optional[str] = None\n e: Union[str, int] = 10\n+ f: List[int] = field(default_factory=list)\n \n dt = datetime(2021, 1, 1, 0, 0, 0)\n- f = Foo(10, dt, dt)\n+ f = Foo(10, dt, dt, f=[1, 2, 3])\n \n- assert to_json(f) == '{\"a\": 10, \"b\": \"01/01/21\", \"c\": \"01/01/21\", \"d\": null, \"e\": 10}'\n+ assert to_json(f) == '{\"a\": 10, \"b\": \"01/01/21\", \"c\": \"01/01/21\", \"d\": null, \"e\": 10, \"f\": [1, 2, 3]}'\n assert f == from_json(Foo, to_json(f))\n \n- assert to_tuple(f) == (10, '01/01/21', '01/01/21', None, 10)\n+ assert to_tuple(f) == (10, '01/01/21', '01/01/21', None, 10, [1, 2, 3])\n assert f == from_tuple(Foo, to_tuple(f))\n \n def fallback(_, __):\n", "FAIL_TO_PASS": ["tests/test_custom.py::test_custom_class_serializer"]}, {"instance_id": "yukinarit__pyserde-229", "base_commit": "bd9039ef1ffac752f7566eb39fc2b3c0a18f7728", "gold_patch": "diff --git a/examples/union_operator.py b/examples/union_operator.py\nindex a6d2f68..cb78577 100644\n--- a/examples/union_operator.py\n+++ b/examples/union_operator.py\n@@ -17,6 +17,7 @@ class Foo:\n a: int | str\n b: dict[str, int] | list[int]\n c: Bar | Baz\n+ d: str | None = None # Should be treated as Optional\n \n \n def main():\ndiff --git a/serde/compat.py b/serde/compat.py\nindex b5e2143..dc8b5a5 100644\n--- a/serde/compat.py\n+++ b/serde/compat.py\n@@ -354,16 +354,16 @@ def is_union(typ) -> bool:\n True\n \"\"\"\n \n- is_union_type = False\n+ # Python 3.10 Union operator e.g. str | int\n if sys.version_info[:2] >= (3, 10):\n try:\n- is_union_type = isinstance(typ, types.UnionType) and not is_opt(typ)\n+ if isinstance(typ, types.UnionType):\n+ return True\n except Exception:\n pass\n \n- typing_union = typing_inspect.is_union_type(typ) and not is_opt(typ)\n-\n- return is_union_type or typing_union\n+ # typing.Union\n+ return typing_inspect.is_union_type(typ)\n \n \n def is_opt(typ) -> bool:\n@@ -377,9 +377,22 @@ def is_opt(typ) -> bool:\n >>> is_opt(None.__class__)\n False\n \"\"\"\n+\n+ # Python 3.10 Union operator e.g. str | None\n+ is_union_type = False\n+ if sys.version_info[:2] >= (3, 10):\n+ try:\n+ if isinstance(typ, types.UnionType):\n+ is_union_type = True\n+ except Exception:\n+ pass\n+\n+ # typing.Optional\n+ is_typing_union = typing_inspect.is_optional_type(typ)\n+\n args = type_args(typ)\n if args:\n- return typing_inspect.is_optional_type(typ) and len(args) == 2 and not is_none(args[0]) and is_none(args[1])\n+ return (is_union_type or is_typing_union) and len(args) == 2 and not is_none(args[0]) and is_none(args[1])\n else:\n return typ is Optional\n \n", "test_patch": "diff --git a/tests/test_compat.py b/tests/test_compat.py\nindex 8991865..2f6ba0b 100644\n--- a/tests/test_compat.py\n+++ b/tests/test_compat.py\n@@ -37,10 +37,10 @@ def test_types():\n assert is_dict(Dict[str, int])\n assert is_dict(Dict)\n assert is_opt(Optional[int])\n+ assert is_opt(Union[int, None])\n assert is_union(Union[int, str])\n assert is_union(Union[Optional[int], Optional[str]])\n- assert is_opt(Optional[int])\n- assert not is_union(Optional[int])\n+ assert is_union(Optional[int])\n assert not is_opt(Union[Optional[int], Optional[str]])\n assert is_union(Union[Optional[int], Optional[str]])\n \n@@ -58,6 +58,11 @@ def test_types():\n assert is_tuple(tuple[int, int, int])\n assert is_dict(dict[str, int])\n \n+ if sys.version_info[:3] >= (3, 10, 0):\n+ assert is_union(str | int)\n+ assert is_union(str | None)\n+ assert is_opt(str | None)\n+\n \n def test_typename():\n @serde.serde\n", "FAIL_TO_PASS": ["tests/test_compat.py::test_types"]}, {"instance_id": "yukinarit__pyserde-264", "base_commit": "1f48c9ccd358f6d0eb5d0afd2ff87a0b47300ade", "gold_patch": "diff --git a/serde/de.py b/serde/de.py\nindex 240df8b..a88a2e7 100644\n--- a/serde/de.py\n+++ b/serde/de.py\n@@ -648,14 +648,11 @@ class Renderer:\n if data.get(\"f\") is not None else None'\n \"\"\"\n value = arg[0]\n- if has_default(arg):\n- return self.render(value)\n+ if arg.iterbased:\n+ exists = f'{arg.data} is not None'\n else:\n- if arg.iterbased:\n- exists = f'{arg.data} is not None'\n- else:\n- exists = f'{arg.datavar}.get(\"{arg.conv_name()}\") is not None'\n- return f'({self.render(value)}) if {exists} else None'\n+ exists = f'{arg.datavar}.get(\"{arg.conv_name()}\") is not None'\n+ return f'({self.render(value)}) if {exists} else None'\n \n def list(self, arg: DeField) -> str:\n \"\"\"\n", "test_patch": "diff --git a/tests/test_union.py b/tests/test_union.py\nindex be7317a..e6fa792 100644\n--- a/tests/test_union.py\n+++ b/tests/test_union.py\n@@ -225,6 +225,29 @@ def test_optional_union_with_complex_types():\n assert a_none == from_dict(A, to_dict(a_none, reuse_instances=True), reuse_instances=True)\n \n \n+def test_optional_complex_type_with_default():\n+ for T, default in [\n+ (IPv4Address, IPv4Address(\"127.0.0.1\")),\n+ (UUID, UUID(\"9c244009-c60d-452b-a378-b8afdc0c2d90\")),\n+ ]:\n+\n+ @serde\n+ class A:\n+ id: Optional[T] = None\n+\n+ a = A(default)\n+ assert a == from_dict(A, to_dict(a, reuse_instances=False), reuse_instances=False)\n+ assert a == from_dict(A, to_dict(a, reuse_instances=True), reuse_instances=True)\n+\n+ a_none = A(None)\n+ assert a_none == from_dict(A, to_dict(a_none, reuse_instances=False), reuse_instances=False)\n+ assert a_none == from_dict(A, to_dict(a_none, reuse_instances=True), reuse_instances=True)\n+\n+ a_default = A()\n+ assert a_default == from_dict(A, to_dict(a_default, reuse_instances=False), reuse_instances=False)\n+ assert a_default == from_dict(A, to_dict(a_default, reuse_instances=True), reuse_instances=True)\n+\n+\n def test_union_with_complex_types_in_containers():\n @serde\n class A:\n", "FAIL_TO_PASS": ["tests/test_union.py::test_optional_complex_type_with_default"]}], "all_FAIL_TO_PASS": ["tests/test_custom.py::test_custom_class_serializer", "tests/test_compat.py::test_types", "tests/test_union.py::test_optional_complex_type_with_default"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "reata__sqllineage-40_x3", "level": 3, "source": "swerebench", "repo": "reata/sqllineage", "image": "swerebench/sweb.eval.x86_64.reata_1776_sqllineage-40:latest", "base_commit": "d80f93bcdcdd4d4b9120ba8c6a0159b7e0e8ba26", "num_bugs": 3, "bugs": [{"instance_id": "reata__sqllineage-40", "base_commit": "d80f93bcdcdd4d4b9120ba8c6a0159b7e0e8ba26", "gold_patch": "diff --git a/sqllineage/core.py b/sqllineage/core.py\nindex 5b010e2..0d7c505 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -1,4 +1,5 @@\n import argparse\n+import re\n import sys\n from typing import List, Set\n \n@@ -6,8 +7,9 @@ import sqlparse\n from sqlparse.sql import Comment, Function, Identifier, Parenthesis, Statement, TokenList\n from sqlparse.tokens import Keyword, Token\n \n-SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN',\n- 'FULL OUTER JOIN', 'CROSS JOIN')\n+SOURCE_TABLE_TOKENS = (r'FROM',\n+ # inspired by https://github.com/andialbrecht/sqlparse/blob/master/sqlparse/keywords.py\n+ r'((LEFT\\s+|RIGHT\\s+|FULL\\s+)?(INNER\\s+|OUTER\\s+|STRAIGHT\\s+)?|(CROSS\\s+|NATURAL\\s+)?)?JOIN')\n TARGET_TABLE_TOKENS = ('INTO', 'OVERWRITE', 'TABLE')\n TEMP_TABLE_TOKENS = ('WITH',)\n \n@@ -59,7 +61,7 @@ Target Tables:\n if isinstance(sub_token, TokenList):\n self._extract_from_token(sub_token)\n if sub_token.ttype in Keyword:\n- if sub_token.normalized in SOURCE_TABLE_TOKENS:\n+ if any(re.match(regex, sub_token.normalized) for regex in SOURCE_TABLE_TOKENS):\n source_table_token_flag = True\n elif sub_token.normalized in TARGET_TABLE_TOKENS:\n target_table_token_flag = True\n", "test_patch": "diff --git a/tests/test_select.py b/tests/test_select.py\nindex 69b6133..8f31412 100644\n--- a/tests/test_select.py\n+++ b/tests/test_select.py\n@@ -69,6 +69,10 @@ def test_select_left_join():\n helper(\"SELECT * FROM tab1 LEFT JOIN tab2\", {\"tab1\", \"tab2\"})\n \n \n+def test_select_left_join_with_extra_space_in_middle():\n+ helper(\"SELECT * FROM tab1 LEFT JOIN tab2\", {\"tab1\", \"tab2\"})\n+\n+\n def test_select_left_semi_join():\n helper(\"SELECT * FROM tab1 LEFT SEMI JOIN tab2\", {\"tab1\", \"tab2\"})\n \n", "FAIL_TO_PASS": ["tests/test_select.py::test_select_left_join_with_extra_space_in_middle"]}, {"instance_id": "reata__sqllineage-41", "base_commit": "c16243c03e8d619a40afaef7d720ed82834da015", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex eb1e3f6..59abe34 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -4,6 +4,7 @@ python:\n - \"3.5\"\n - \"3.6\"\n - \"3.7\"\n+ - \"3.8\"\n # command to install dependencies\n install:\n - pip install tox-travis codecov\ndiff --git a/sqllineage/core.py b/sqllineage/core.py\nindex 0d7c505..a46e388 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -23,7 +23,8 @@ class LineageParser(object):\n self._stmt = [s for s in sqlparse.parse(sql.strip(), self._encoding) if s.token_first(skip_cm=True)]\n for stmt in self._stmt:\n if stmt.get_type() == \"DROP\":\n- self._target_tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)}\n+ for tables in (self._source_tables, self._target_tables):\n+ tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)}\n else:\n self._extract_from_token(stmt)\n self._tmp_tables = self._source_tables.intersection(self._target_tables)\ndiff --git a/tox.ini b/tox.ini\nindex 0fa8e74..9546285 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -1,5 +1,5 @@\n [tox]\n-envlist = py35,py36,py37\n+envlist = py35,py36,py37,py38\n \n [testenv]\n deps =\n", "test_patch": "diff --git a/tests/test_others.py b/tests/test_others.py\nindex ddc0c30..eabb6d4 100644\n--- a/tests/test_others.py\n+++ b/tests/test_others.py\n@@ -31,6 +31,13 @@ def test_drop_after_create():\n helper(\"CREATE TABLE IF NOT EXISTS tab1 (col1 STRING);DROP TABLE IF EXISTS tab1\", None, None)\n \n \n+def test_drop_tmp_tab_after_create():\n+ sql = \"\"\"create table tab_a as select * from tab_b;\n+insert overwrite table tab_c select * from tab_a;\n+drop table tab_a;\"\"\"\n+ helper(sql, {\"tab_b\"}, {\"tab_c\"})\n+\n+\n def test_create_select():\n helper(\"CREATE TABLE tab1 SELECT * FROM tab2\", {\"tab2\"}, {\"tab1\"})\n \n", "FAIL_TO_PASS": ["tests/test_others.py::test_drop_tmp_tab_after_create"]}, {"instance_id": "reata__sqllineage-42", "base_commit": "b8eaecc85b279dc18f9464b9e2bf6b2164b63211", "gold_patch": "diff --git a/sqllineage/core.py b/sqllineage/core.py\nindex a46e388..1d9a021 100644\n--- a/sqllineage/core.py\n+++ b/sqllineage/core.py\n@@ -4,7 +4,7 @@ import sys\n from typing import List, Set\n \n import sqlparse\n-from sqlparse.sql import Comment, Function, Identifier, Parenthesis, Statement, TokenList\n+from sqlparse.sql import Comment, Comparison, Function, Identifier, Parenthesis, Statement, TokenList\n from sqlparse.tokens import Keyword, Token\n \n SOURCE_TABLE_TOKENS = (r'FROM',\n@@ -95,11 +95,17 @@ Target Tables:\n # referring https://github.com/andialbrecht/sqlparse/issues/483 for further information\n assert isinstance(sub_token.token_first(skip_cm=True), Identifier)\n self._target_tables.add(sub_token.token_first(skip_cm=True).get_real_name())\n- target_table_token_flag = False\n+ elif isinstance(sub_token, Comparison):\n+ # create table tab1 like tab2, tab1 like tab2 will be parsed as Comparison\n+ # referring https://github.com/andialbrecht/sqlparse/issues/543 for further information\n+ assert isinstance(sub_token.left, Identifier)\n+ assert isinstance(sub_token.right, Identifier)\n+ self._target_tables.add(sub_token.left.get_real_name())\n+ self._source_tables.add(sub_token.right.get_real_name())\n else:\n assert isinstance(sub_token, Identifier)\n self._target_tables.add(sub_token.get_real_name())\n- target_table_token_flag = False\n+ target_table_token_flag = False\n elif temp_table_token_flag:\n if self.__token_negligible_before_tablename(sub_token):\n continue\n", "test_patch": "diff --git a/tests/test_others.py b/tests/test_others.py\nindex eabb6d4..a9405c8 100644\n--- a/tests/test_others.py\n+++ b/tests/test_others.py\n@@ -14,6 +14,14 @@ def test_create_if_not_exist():\n helper(\"CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)\", None, {\"tab1\"})\n \n \n+def test_create_as():\n+ helper(\"CREATE TABLE tab1 AS SELECT * FROM tab2\", {\"tab2\"}, {\"tab1\"})\n+\n+\n+def test_create_like():\n+ helper(\"CREATE TABLE tab1 LIKE tab2\", {\"tab2\"}, {\"tab1\"})\n+\n+\n def test_create_after_drop():\n helper(\"DROP TABLE IF EXISTS tab1; CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)\", None, {\"tab1\"})\n \n", "FAIL_TO_PASS": ["tests/test_others.py::test_create_like"]}], "all_FAIL_TO_PASS": ["tests/test_select.py::test_select_left_join_with_extra_space_in_middle", "tests/test_others.py::test_drop_tmp_tab_after_create", "tests/test_others.py::test_create_like"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "NREL__hescore-hpxml-103_x3", "level": 3, "source": "swerebench", "repo": "NREL/hescore-hpxml", "image": "swerebench/sweb.eval.x86_64.nrel_1776_hescore-hpxml-103:latest", "base_commit": "8b8d22ce729c851042f074b36709407fdda5be8f", "num_bugs": 3, "bugs": [{"instance_id": "NREL__hescore-hpxml-103", "base_commit": "8b8d22ce729c851042f074b36709407fdda5be8f", "gold_patch": "diff --git a/docs/source/translation/cooling_system.rst b/docs/source/translation/cooling_system.rst\nindex 898bb821..33949281 100644\n--- a/docs/source/translation/cooling_system.rst\n+++ b/docs/source/translation/cooling_system.rst\n@@ -59,7 +59,7 @@ is done according to the following mapping.\n ========================= ====================\n central air conditioning split_dx\n room air conditioner packaged_dx\n- mini-split split_dx\n+ mini-split mini_split\n evaporative cooler dec\n other *not translated*\n ========================= ====================\n@@ -68,10 +68,6 @@ is done according to the following mapping.\n \n If an HPXML cooling system type maps to *not translated* the translation will fail.\n \n-.. note::\n-\n- A cooling-only mini-split is not available in HEScore, therefore the mini-split type is translated into a ``split_dx``.\n-\n .. note::\n \n Prior to v2016, HEScore did not have an evaporative cooler type and these were translated as high efficiency ``split_dx`` systems.\ndiff --git a/examples/house4.json b/examples/house4.json\nindex 151eaf0e..4c5760ee 100644\n--- a/examples/house4.json\n+++ b/examples/house4.json\n@@ -147,15 +147,7 @@\n \"efficiency_method\": \"user\",\n \"efficiency\": 15.0\n },\n- \"hvac_distribution\": [\n- {\n- \"name\": \"duct1\",\n- \"location\": \"cond_space\",\n- \"fraction\": 100,\n- \"insulated\": true,\n- \"sealed\": true\n- }\n- ]\n+ \"hvac_distribution\": []\n }\n ],\n \"domestic_hot_water\": {\ndiff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 8dd5a6a5..be36f602 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -13,7 +13,6 @@ import logging\n import re\n import json\n import math\n-import uuid\n from lxml import etree\n from collections import defaultdict, namedtuple\n from decimal import Decimal\n@@ -386,7 +385,7 @@ class HPXMLtoHEScoreTranslator(object):\n try:\n sys_cooling['type'] = {'central air conditioning': 'split_dx',\n 'room air conditioner': 'packaged_dx',\n- 'mini-split': 'split_dx',\n+ 'mini-split': 'mini_split',\n 'evaporative cooler': 'dec'}[hpxml_cooling_type]\n except KeyError:\n raise TranslationError('HEScore does not support the HPXML CoolingSystemType %s' % hpxml_cooling_type)\n@@ -1846,27 +1845,6 @@ class HPXMLtoHEScoreTranslator(object):\n )\n )\n \n- # Connect mini-split heat pumps to \"ducts\"\n- # Find heating and cooling ids that are in both singleton lists (heat pumps with no ducts)\n- singletons_to_combine = singleton_cooling_systems.intersection(singleton_heating_systems)\n- singleton_heating_systems -= singletons_to_combine\n- singleton_cooling_systems -= singletons_to_combine\n- for heatpump_id in singletons_to_combine:\n- if heating_systems[heatpump_id]['type'] != 'mini_split' or cooling_systems[heatpump_id]['type'] != 'mini_split': # noqa: E501\n- continue\n- dummy_duct_id = str(uuid.uuid4())\n- dist_heating_cooling_map[dummy_duct_id] = (heatpump_id, heatpump_id)\n- dist_heating_map[dummy_duct_id] = heatpump_id\n- dist_cooling_map[dummy_duct_id] = heatpump_id\n-\n- dummy_duct = OrderedDict()\n- dummy_duct['name'] = 'duct1'\n- dummy_duct['location'] = 'cond_space'\n- dummy_duct['fraction'] = 100\n- dummy_duct['insulated'] = True\n- dummy_duct['sealed'] = True\n- distribution_systems[dummy_duct_id] = [dummy_duct]\n-\n # Check to make sure heating and cooling systems that need a distribution system have them.\n heating_sys_types_requiring_ducts = ('gchp', 'heat_pump', 'central_furnace')\n for htg_sys_id, htg_sys in list(heating_systems.items()):\n@@ -1893,6 +1871,18 @@ class HPXMLtoHEScoreTranslator(object):\n avg_sys_weight = old_div(sum(weights_to_average), len(weights_to_average))\n hvac_systems_ids.add(IDsAndWeights(htg_sys_id, clg_sys_id, dist_sys_id, avg_sys_weight))\n \n+ singletons_to_combine = singleton_cooling_systems.intersection(singleton_heating_systems)\n+ singleton_heating_systems -= singletons_to_combine\n+ singleton_cooling_systems -= singletons_to_combine\n+ for heatpump_id in singletons_to_combine:\n+ if heating_systems[heatpump_id]['type'] != 'mini_split' or cooling_systems[heatpump_id]['type'] != 'mini_split': # noqa: E501\n+ continue\n+ hvac_systems_ids.add(IDsAndWeights(\n+ heatpump_id,\n+ heatpump_id,\n+ None,\n+ old_div(heating_systems[heatpump_id][heating_weighting_factor], weight_sum)))\n+\n # Add the singletons to the list\n for htg_sys_id in singleton_heating_systems:\n hvac_systems_ids.add(IDsAndWeights(\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex a110d679..378b93ab 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -1535,7 +1535,6 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n clg_sys_test_cooling_type = [\n 'central air conditioning',\n 'room air conditioner',\n- 'mini-split',\n 'evaporative cooler']\n hp_test_type = ['water-to-air', 'water-to-water', 'air-to-air', 'mini-split', 'ground-to-air']\n \n@@ -1651,7 +1650,6 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n # cooling system map between hpxml and hescore api\n clg_system_map = {'central air conditioning': 'split_dx',\n 'room air conditioner': 'packaged_dx',\n- 'mini-split': 'split_dx',\n 'evaporative cooler': 'dec'}\n \n for clg_system_type in clg_sys_test_cooling_type:\n@@ -2140,6 +2138,80 @@ class TestHEScore2019Updates(unittest.TestCase, ComparatorBase):\n 'dseab'\n )\n \n+ def test_mini_split_cooling_only(self):\n+ tr = self._load_xmlfile('hescore_min')\n+ E = self.element_maker()\n+\n+ # cooling system type: mini-split + heating system\n+ clg_type = self.xpath('//h:CoolingSystem[h:SystemIdentifier/@id=\"centralair1\"]/h:CoolingSystemType')\n+ clg_type.text = 'mini-split'\n+\n+ d = tr.hpxml_to_hescore_dict()\n+ self.assertEqual(d['building']['systems']['hvac'][0]['cooling']['type'], 'mini_split')\n+ self.assertEqual(d['building']['systems']['hvac'][0]['heating']['type'], 'central_furnace')\n+\n+ # heatpump system type: mini-split + heating system\n+ heatpump = E.HeatPump(\n+ E.SystemIdentifier(id='heatpump1'),\n+ E.YearInstalled('2005'),\n+ E.HeatPumpType('mini-split'),\n+ E.HeatingCapacity('18000'),\n+ E.CoolingCapacity('18000'),\n+ E.FractionHeatLoadServed('0'),\n+ E.FractionCoolLoadServed('1.0'),\n+ E.AnnualCoolEfficiency(E.Units('SEER'), E.Value('15')),\n+ E.AnnualHeatEfficiency(E.Units('HSPF'), E.Value('8.2'))\n+ )\n+ clg_sys = self.xpath('//h:CoolingSystem[h:SystemIdentifier/@id=\"centralair1\"]')\n+ clg_sys.addnext(heatpump)\n+ clg_sys.getparent().remove(clg_sys)\n+ # Add fraction to heating system for system weight calculation\n+ htg_sys = self.xpath('//h:HeatingSystem[h:SystemIdentifier/@id=\"furnace1\"]')\n+ htg_sys.append(E.FractionHeatLoadServed('1.0'))\n+ d = tr.hpxml_to_hescore_dict()\n+ self.assertEqual(d['building']['systems']['hvac'][0]['cooling']['type'], 'mini_split')\n+ self.assertEqual(d['building']['systems']['hvac'][0]['heating']['type'], 'central_furnace')\n+\n+ # clg system mini-split + heatpump for heating: should give error for two different heat pump systems\n+ clg_sys = E.CoolingSystem(\n+ E.SystemIdentifier(id='centralair'),\n+ E.YearInstalled('2005'),\n+ E.CoolingSystemType('mini-split'),\n+ E.FractionCoolLoadServed('1.0'),\n+ E.AnnualCoolingEfficiency(E.Units('SEER'), E.Value('13')),\n+ )\n+ heatpump.addprevious(clg_sys)\n+ htg_sys.getparent().remove(htg_sys)\n+ heatpump_fraction_htg = self.xpath('//h:HeatPump[h:SystemIdentifier/@id=\"heatpump1\"]/h:FractionHeatLoadServed')\n+ heatpump_fraction_clg = self.xpath('//h:HeatPump[h:SystemIdentifier/@id=\"heatpump1\"]/h:FractionCoolLoadServed')\n+ heatpump_fraction_htg.text = '1.0'\n+ heatpump_fraction_clg.text = '0.0'\n+ heatpump_type = self.xpath('//h:HeatPump[h:SystemIdentifier/@id=\"heatpump1\"]/h:HeatPumpType')\n+ heatpump_type.text = 'air-to-air'\n+ heatpump_type.addprevious(E.DistributionSystem(idref='hvacd1'))\n+ self.assertRaisesRegexp(\n+ TranslationError,\n+ r'Two different heat pump systems: .+ for heating, and .+ for cooling are not supported in one hvac system.', # noqa E501\n+ tr.hpxml_to_hescore_dict)\n+\n+ # heatpump system type: mini-split + other cooling system\n+ clg_sys_type = self.xpath('//h:CoolingSystem[h:SystemIdentifier/@id=\"centralair\"]/h:CoolingSystemType')\n+ clg_sys_type.text = 'central air conditioning'\n+ clg_sys_type.addprevious(E.DistributionSystem(idref='hvacd1'))\n+ heatpump_type.text = 'mini-split'\n+ heatpump.remove(self.xpath('//h:HeatPump[h:SystemIdentifier/@id=\"heatpump1\"]/h:DistributionSystem'))\n+ d = tr.hpxml_to_hescore_dict()\n+ self.assertEqual(d['building']['systems']['hvac'][0]['cooling']['type'], 'split_dx')\n+ self.assertEqual(d['building']['systems']['hvac'][0]['heating']['type'], 'mini_split')\n+\n+ # heatpump system type: mini-split\n+ clg_sys.getparent().remove(clg_sys)\n+ heatpump.remove(heatpump_fraction_clg)\n+ heatpump.remove(heatpump_fraction_htg)\n+ d = tr.hpxml_to_hescore_dict()\n+ self.assertEqual(d['building']['systems']['hvac'][0]['cooling']['type'], 'mini_split')\n+ self.assertEqual(d['building']['systems']['hvac'][0]['heating']['type'], 'mini_split')\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["tests/tests.py::TestHEScore2019Updates::test_mini_split_cooling_only"]}, {"instance_id": "NREL__hescore-hpxml-113", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "gold_patch": "diff --git a/docs/source/translation/zone_window.rst b/docs/source/translation/zone_window.rst\nindex 480fe5db..5062926c 100644\n--- a/docs/source/translation/zone_window.rst\n+++ b/docs/source/translation/zone_window.rst\n@@ -13,17 +13,21 @@ assumed to mean the sum of the areas of the windows that the ``Window`` element\n represents. Each ``Window`` is then assigned to a side of the building in one of\n two ways:\n \n- #. By association with a particular wall.\n #. By inspecting the azimuth or orientation of the window.\n+ #. By association with a particular wall.\n \n-If an HPXML window has the ``AttachedToWall`` element, the id reference in that\n-element is used to find the associated wall and the side of the building that\n-the window faces is inferred from the :ref:`wall orientation `.\n-\n-If there is not an ``AttachedToWall`` element, the side is determined via the\n-``Azimuth`` or ``Orientation`` elements with preference given to the\n-``Azimuth`` if present. If the window falls between two sides of the house, the\n-window area is divided between the sides of the house evenly. \n+If there is an ``Orientation`` or ``Azimuth`` element, the side is determined\n+via the one of those elements with preference given to the ``Azimuth`` if\n+present. If the window falls between two sides of the house, the window area is\n+divided between the sides of the house evenly. \n+\n+If ``Orientation`` or ``Azimuth`` are missing and the HPXML window has the\n+``AttachedToWall`` element, the id reference in that element is used to find the\n+associated wall and the side of the building that the window faces is inferred\n+from the :ref:`wall orientation `. If the window is attached to\n+a foundation wall, the orientation/azimuth must be provided on the ``Window``\n+element because foundation walls do not have orientation or azimuth elements\n+available.\n \n The areas on each side of the house are summed and the :ref:`window-prop` are\n determined independently for each side of the house. Since HPXML requires that\ndiff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 55a58b86..102d0f48 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -1530,29 +1530,33 @@ class HPXMLtoHEScoreTranslator(object):\n \n # Window side\n window_sides = []\n- attached_to_wall_id = xpath(hpxmlwndw, 'h:AttachedToWall/@idref')\n- if attached_to_wall_id is not None:\n- # Give preference to the Attached to Wall element to determine the side of the house.\n- for side, walls in list(hpxmlwalls.items()):\n- for wall in walls:\n- if attached_to_wall_id == wall['id']:\n- window_sides.append(side)\n- break\n+ window_id = xpath(hpxmlwndw, 'h:SystemIdentifier/@id')\n+ try:\n+ # Get the aziumuth or orientation if they exist\n+ wndw_azimuth = self.get_nearest_azimuth(xpath(hpxmlwndw, 'h:Azimuth/text()'),\n+ xpath(hpxmlwndw, 'h:Orientation/text()'))\n+ except TranslationError:\n+ # The window doesn't have orientation/azimuth information, get from wall\n+ attached_to_wall_id = xpath(hpxmlwndw, 'h:AttachedToWall/@idref')\n+ if attached_to_wall_id is not None:\n+ for side, walls in list(hpxmlwalls.items()):\n+ for wall in walls:\n+ if attached_to_wall_id == wall['id']:\n+ window_sides.append(side)\n+ break\n+ if not window_sides:\n+ raise TranslationError('The Window[SystemIdentifier/@id=\"{}\"] has no Azimuth or Orientation, and the Window/AttachedToWall/@idref of \"{}\" didn\\'t reference a Wall element.'.format(window_id, attached_to_wall_id)) # noqa: E501\n+ else:\n+ raise TranslationError(\n+ 'Window[SystemIdentifier/@id=\"{}\"] doesn\\'t have Azimuth, Orientation, or AttachedToWall. At least one is required.'.format(window_id) # noqa: E501\n+ )\n else:\n- # If there's not Attached to Wall element, figure it out from the Azimuth/Orientation\n+ # Azimuth found, associate with a side\n try:\n- wndw_azimuth = self.get_nearest_azimuth(xpath(hpxmlwndw, 'h:Azimuth/text()'),\n- xpath(hpxmlwndw, 'h:Orientation/text()'))\n- except TranslationError:\n- # there's no directional information in the window\n- raise TranslationError(\n- 'All windows need to have either an AttachedToWall, Orientation, or Azimuth sub element.')\n- else:\n- try:\n- window_sides = [sidemap[wndw_azimuth]]\n- except KeyError:\n- # the direction of the window is between sides, split area\n- window_sides = [sidemap[unspin_azimuth(wndw_azimuth + x)] for x in (-45, 45)]\n+ window_sides = [sidemap[wndw_azimuth]]\n+ except KeyError:\n+ # the direction of the window is between sides, split area\n+ window_sides = [sidemap[unspin_azimuth(wndw_azimuth + x)] for x in (-45, 45)]\n \n # Assign properties and areas to the correct side of the house\n windowd['area'] /= float(len(window_sides))\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex 1f6fd6cb..31a901bc 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -333,9 +333,23 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el.getparent().remove(el)\n self.assertRaisesRegexp(\n TranslationError,\n- r'All windows need to have either an AttachedToWall, Orientation, or Azimuth sub element\\.',\n+ r'Window\\[SystemIdentifier/@id=\"\\w+\"\\] doesn\\'t have Azimuth, Orientation, or AttachedToWall. At least one is required.', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n+ def test_window_only_attached_to_foundation_wall(self):\n+ tr = self._load_xmlfile('house4')\n+ window_orientation = self.xpath('//h:Window[1]/h:Orientation')\n+ window = window_orientation.getparent()\n+ etree.SubElement(window, tr.addns('h:AttachedToWall'), attrib={'idref': 'crawlwall'})\n+ self._do_compare('house4')\n+\n+ window.remove(window_orientation)\n+ self.assertRaisesRegexp(\n+ TranslationError,\n+ r'The Window\\[SystemIdentifier/@id=\"\\w+\"\\] has no Azimuth or Orientation, and the .* didn\\'t reference a Wall element.', # noqa E501\n+ tr.hpxml_to_hescore_dict\n+ )\n+\n def test_window_attached_to_wall(self):\n filebase = 'house6'\n tr = self._load_xmlfile(filebase)\n", "FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_window_orientation", "tests/tests.py::TestOtherHouses::test_window_only_attached_to_foundation_wall"]}, {"instance_id": "NREL__hescore-hpxml-115", "base_commit": "0b79d17c5fff0876a18ccd2efca3d058323d7810", "gold_patch": "diff --git a/docs/source/translation/hvac.rst b/docs/source/translation/hvac.rst\nindex ec1bc7e9..cdc7169f 100644\n--- a/docs/source/translation/hvac.rst\n+++ b/docs/source/translation/hvac.rst\n@@ -1,26 +1,35 @@\n HVAC Systems\n ############\n \n-HEScore allows the definition of up to two HVAC systems which can each include a heating system, cooling system, and duct system.\n-To determine which HPXML elements are associated, the ``DistributionSystem`` subelement of\n-``HeatingSystem``, ``CoolingSystem``, ``HeatPump`` is used to find the link to ``HVACDistributionSystem``.\n-Systems that share the same ``HVACDistributionSystem`` are determined to be the same HVAC system for HEScore.\n-\n-Sometimes an HVAC system will not share ducts, for instance a central air conditioner and boiler.\n-In that case, if each of those systems serve a fraction of the home's load within 5% of each other\n-they will be combined into the same HVAC system for HEScore.\n-If a ``HeatingSystem`` and ``CoolingSystem`` that are associated with the same ``HVACDistributionSystem`` serve differing\n-portions of the house's heating and cooling load, that weight is averaged to find the combined system weight.\n-\n-If either a heating or cooling system meets all of the load and two systems of the opposite (cooling or heating, respectively)\n-are required to meet the same fraction of the load, the larger system is split into two for input into HEScore.\n-\n-To determine the fraction of the home's heating and cooling load each system serves,\n-each HPXML heating or cooling system is required to have ``FloorAreaServed`` or, alternatively ``FracLoadServed``.\n-The two combined HVAC systems that serve the greatest portion of the house's load are sent to HEScore.\n-\n-For details about how each kind of ``HeatingSystem``, ``CoolingSystem``, ``HeatPump``, and ``HVACDistributionSystem``\n-are translated into HEScore inputs, see the appropriate subsection:\n+HEScore allows the definition of up to two HVAC systems which can each include a\n+heating system, cooling system, and duct system. To determine which HPXML\n+elements are associated, the ``DistributionSystem`` subelement of\n+``HeatingSystem``, ``CoolingSystem``, ``HeatPump`` is used to find the link to\n+``HVACDistributionSystem``. Systems that share the same\n+``HVACDistributionSystem`` are determined to be the same HVAC system for\n+HEScore.\n+\n+Sometimes an HVAC system will not share ducts, for instance a central air\n+conditioner and boiler. In that case, if each of those systems serve a fraction\n+of the home's load within 5% of each other they will be combined into the same\n+HVAC system for HEScore. If a ``HeatingSystem`` and ``CoolingSystem`` that are\n+associated with the same ``HVACDistributionSystem`` serve differing portions of\n+the house's heating and cooling load, that weight is averaged to find the\n+combined system weight.\n+\n+If either a heating or cooling system meets all of the load and two systems of\n+the opposite (cooling or heating, respectively) are required to meet the same\n+fraction of the load, the larger system is split into two for input into\n+HEScore.\n+\n+To determine the fraction of the home's heating and cooling load each system\n+serves, each HPXML heating and cooling system is required to have\n+``FloorAreaServed`` or, alternatively ``FracLoadServed``. The two combined HVAC\n+systems that serve the greatest portion of the house's load are sent to HEScore.\n+\n+For details about how each kind of ``HeatingSystem``, ``CoolingSystem``,\n+``HeatPump``, and ``HVACDistributionSystem`` are translated into HEScore inputs,\n+see the appropriate subsection:\n \n .. toctree::\n :maxdepth: 1\ndiff --git a/hescorehpxml/__init__.py b/hescorehpxml/__init__.py\nindex 55a58b86..dc737aa9 100644\n--- a/hescorehpxml/__init__.py\n+++ b/hescorehpxml/__init__.py\n@@ -688,7 +688,7 @@ class HPXMLtoHEScoreTranslator(object):\n bldg['zone']['window_construction_same'] = False\n bldg['zone']['zone_wall'] = self._get_building_zone_wall(b, bldg['about'])\n bldg['systems'] = OrderedDict()\n- bldg['systems']['hvac'] = self._get_hvac(b)\n+ bldg['systems']['hvac'] = self._get_hvac(b, bldg['about'])\n bldg['systems']['domestic_hot_water'] = self._get_systems_dhw(b)\n generation = self._get_generation(b)\n if generation:\n@@ -1678,7 +1678,7 @@ class HPXMLtoHEScoreTranslator(object):\n zone_window['solar_screen'] = max(list(window_sunscreen_areas.items()), key=lambda x: x[1])[0]\n return zone_wall\n \n- def _get_hvac(self, b):\n+ def _get_hvac(self, b, bldg_about):\n \n def _get_dict_of_hpxml_elements_by_id(xpathexpr):\n return_dict = {}\n@@ -1786,48 +1786,41 @@ class HPXMLtoHEScoreTranslator(object):\n distribution_systems[key] = self._get_hvac_distribution(el)\n \n # Determine the weighting factors\n- def _choose_weighting_factor(systems_dict):\n- weighting_factor_priority = ['_floorarea', '_fracload']\n- found_weighting_factor = False\n- for weighting_factor in weighting_factor_priority:\n- weighting_factor_list = [item[weighting_factor] for item in list(systems_dict.values())]\n- if None not in weighting_factor_list and len(weighting_factor_list) > 0:\n- found_weighting_factor = True\n- break\n- if not found_weighting_factor:\n- if len(systems_dict) == 1:\n- list(systems_dict.values())[0]['_fracload'] = 1.0\n- weighting_factor_list = [1.0]\n- weighting_factor = '_fracload'\n- else:\n- raise TranslationError(\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed.')\n- return weighting_factor, sum(weighting_factor_list)\n- if heating_systems:\n- heating_weighting_factor, heating_weight_sum = _choose_weighting_factor(heating_systems)\n- else:\n- heating_weight_sum = 0\n- heating_weighting_factor = None\n- if cooling_systems:\n- cooling_weighting_factor, cooling_weight_sum = _choose_weighting_factor(cooling_systems)\n- else:\n- cooling_weight_sum = 0\n- cooling_weighting_factor = None\n \n- if cooling_systems and heating_systems and heating_weighting_factor != cooling_weighting_factor:\n+ # If there's only one heating or cooling system and no weighting elements, fill it in.\n+ for heating_or_cooling_systems in (heating_systems, cooling_systems):\n+ if len(heating_or_cooling_systems) == 1:\n+ for key, hvac_sys in heating_or_cooling_systems.items():\n+ if hvac_sys.get('_floorarea') is None and hvac_sys.get('_fracload') is None:\n+ hvac_sys['_fracload'] = 1.0\n+ hvac_sys['_floorarea'] = bldg_about['conditioned_floor_area']\n+\n+ # Choose a weighting factor that all the heating and cooling systems use\n+ all_systems = []\n+ all_systems.extend(heating_systems.values())\n+ all_systems.extend(cooling_systems.values())\n+ found_weighting_factor = False\n+ for weighting_factor in ['_floorarea', '_fracload']:\n+ if None not in [x.get(weighting_factor) for x in all_systems]:\n+ found_weighting_factor = True\n+ break\n+ if not found_weighting_factor:\n raise TranslationError(\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed.')\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed.' # noqa: E501\n+ )\n \n- weight_sum = max(heating_weight_sum, cooling_weight_sum)\n- del heating_weight_sum\n- del cooling_weight_sum\n+ # Calculate the sum of the weights (total fraction or floor area)\n+ weight_sum = max(\n+ sum([x[weighting_factor] for x in heating_systems.values()]),\n+ sum([x[weighting_factor] for x in cooling_systems.values()])\n+ )\n \n # Ensure that heating and cooling systems attached to the same ducts are within 5% of each other\n # in terms of fraction of the load served.\n for duct_id, (htg_id, clg_id) in list(dist_heating_cooling_map.items()):\n try:\n- htg_weight = old_div(heating_systems[htg_id][heating_weighting_factor], weight_sum)\n- clg_weight = old_div(cooling_systems[clg_id][cooling_weighting_factor], weight_sum)\n+ htg_weight = old_div(heating_systems[htg_id][weighting_factor], weight_sum)\n+ clg_weight = old_div(cooling_systems[clg_id][weighting_factor], weight_sum)\n except KeyError:\n continue\n if abs(htg_weight - clg_weight) > 0.051:\n@@ -1859,9 +1852,9 @@ class HPXMLtoHEScoreTranslator(object):\n for dist_sys_id, (htg_sys_id, clg_sys_id) in list(dist_heating_cooling_map.items()):\n weights_to_average = []\n if htg_sys_id is not None:\n- weights_to_average.append(old_div(heating_systems[htg_sys_id][heating_weighting_factor], weight_sum))\n+ weights_to_average.append(old_div(heating_systems[htg_sys_id][weighting_factor], weight_sum))\n if clg_sys_id is not None:\n- weights_to_average.append(old_div(cooling_systems[clg_sys_id][cooling_weighting_factor], weight_sum))\n+ weights_to_average.append(old_div(cooling_systems[clg_sys_id][weighting_factor], weight_sum))\n avg_sys_weight = old_div(sum(weights_to_average), len(weights_to_average))\n hvac_systems_ids.add(IDsAndWeights(htg_sys_id, clg_sys_id, dist_sys_id, avg_sys_weight))\n \n@@ -1875,7 +1868,7 @@ class HPXMLtoHEScoreTranslator(object):\n heatpump_id,\n heatpump_id,\n None,\n- old_div(heating_systems[heatpump_id][heating_weighting_factor], weight_sum)))\n+ old_div(heating_systems[heatpump_id][weighting_factor], weight_sum)))\n \n # Add the singletons to the list\n for htg_sys_id in singleton_heating_systems:\n@@ -1883,13 +1876,13 @@ class HPXMLtoHEScoreTranslator(object):\n htg_sys_id,\n None,\n None,\n- old_div(heating_systems[htg_sys_id][heating_weighting_factor], weight_sum)))\n+ old_div(heating_systems[htg_sys_id][weighting_factor], weight_sum)))\n for clg_sys_id in singleton_cooling_systems:\n hvac_systems_ids.add(IDsAndWeights(\n None,\n clg_sys_id,\n None,\n- old_div(cooling_systems[clg_sys_id][cooling_weighting_factor], weight_sum)))\n+ old_div(cooling_systems[clg_sys_id][weighting_factor], weight_sum)))\n \n # Split and combine systems by fraction as needed #45\n singleton_heating_systems = []\n", "test_patch": "diff --git a/tests/tests.py b/tests/tests.py\nindex 1f6fd6cb..a6cd505f 100644\n--- a/tests/tests.py\n+++ b/tests/tests.py\n@@ -410,7 +410,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = self.xpath('//h:HeatPump[1]/h:FloorAreaServed')\n el.getparent().remove(el)\n self.assertRaisesRegexp(TranslationError,\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed',\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n def test_missing_cooling_weighting_factor(self):\n@@ -420,7 +420,7 @@ class TestOtherHouses(unittest.TestCase, ComparatorBase):\n el = self.xpath('//h:CoolingSystem[2]/h:FloorAreaServed')\n el.getparent().remove(el)\n self.assertRaisesRegexp(TranslationError,\n- 'Every heating/cooling system needs to have either FloorAreaServed or FracLoadServed',\n+ 'Every heating/cooling system needs to have either FloorAreaServed or FracHeatLoadServed/FracCoolLoadServed', # noqa E501\n tr.hpxml_to_hescore_dict)\n \n def test_bad_duct_location(self):\n@@ -1179,7 +1179,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n aircond.insert(-1, el)\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 3213})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1229,7 +1229,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n tr.xpath(ducts2, 'h:SystemIdentifier').attrib['id'] = 'ducts2'\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1275,7 +1275,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n clgsys_floor_area_el.text = str(total_floor_area)\n \n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1325,7 +1325,7 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n \n # Get HEScore inputs and sort by fraction\n b = self.xpath('h:Building[1]')\n- hvac_systems = tr._get_hvac(b)\n+ hvac_systems = tr._get_hvac(b, {\"conditioned_floor_area\": 2600})\n hvac_systems.sort(key=lambda x: x['hvac_fraction'])\n \n hvac1 = hvac_systems[0]\n@@ -1348,7 +1348,21 @@ class TestHVACFractions(unittest.TestCase, ComparatorBase):\n frac_cool_load_served.text = '1.0'\n clg_sys_eff.addprevious(frac_cool_load_served)\n b = self.xpath('h:Building[1]')\n- tr._get_hvac(b)\n+ tr._get_hvac(b, {\"conditioned_floor_area\": 2400})\n+\n+ def test_different_weighting_factors(self):\n+ tr = self._load_xmlfile('hescore_min')\n+ htg_sys = self.xpath('//h:HeatingSystem')\n+ frac_heat_load_served = etree.SubElement(htg_sys, tr.addns('h:FractionHeatLoadServed'))\n+ frac_heat_load_served.text = '1.0'\n+ heating_floor_area_served = etree.SubElement(htg_sys, tr.addns('h:FloorAreaServed'))\n+ heating_floor_area_served.text = '2400'\n+ clg_sys_eff = self.xpath('//h:CoolingSystem/h:AnnualCoolingEfficiency')\n+ frac_cool_load_served = etree.Element(tr.addns('h:FractionCoolLoadServed'))\n+ frac_cool_load_served.text = '1.0'\n+ clg_sys_eff.addprevious(frac_cool_load_served)\n+ b = self.xpath('h:Building[1]')\n+ tr._get_hvac(b, {\"conditioned_floor_area\": 2400})\n \n \n class TestPhotovoltaics(unittest.TestCase, ComparatorBase):\n", "FAIL_TO_PASS": ["tests/tests.py::TestOtherHouses::test_missing_cooling_weighting_factor", "tests/tests.py::TestOtherHouses::test_missing_heating_weighting_factor", "tests/tests.py::TestHVACFractions::test_allow_5pct_diff", "tests/tests.py::TestHVACFractions::test_boiler_roomac", "tests/tests.py::TestHVACFractions::test_different_weighting_factors", "tests/tests.py::TestHVACFractions::test_furnace_baseboard_centralac", "tests/tests.py::TestHVACFractions::test_furnace_heat_pump", "tests/tests.py::TestHVACFractions::test_wall_furnace_baseboard_centralac"]}], "all_FAIL_TO_PASS": ["tests/tests.py::TestHEScore2019Updates::test_mini_split_cooling_only", "tests/tests.py::TestOtherHouses::test_missing_window_orientation", "tests/tests.py::TestOtherHouses::test_window_only_attached_to_foundation_wall", "tests/tests.py::TestOtherHouses::test_missing_cooling_weighting_factor", "tests/tests.py::TestOtherHouses::test_missing_heating_weighting_factor", "tests/tests.py::TestHVACFractions::test_allow_5pct_diff", "tests/tests.py::TestHVACFractions::test_boiler_roomac", "tests/tests.py::TestHVACFractions::test_different_weighting_factors", "tests/tests.py::TestHVACFractions::test_furnace_baseboard_centralac", "tests/tests.py::TestHVACFractions::test_furnace_heat_pump", "tests/tests.py::TestHVACFractions::test_wall_furnace_baseboard_centralac"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3242_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3242:latest", "base_commit": "59f1d13bc5e37ebe6636b05e0381facc9725f7b0", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3242", "base_commit": "59f1d13bc5e37ebe6636b05e0381facc9725f7b0", "gold_patch": "diff --git a/sqlglot/dialects/sqlite.py b/sqlglot/dialects/sqlite.py\nindex 63540a8e..ef7d9aa1 100644\n--- a/sqlglot/dialects/sqlite.py\n+++ b/sqlglot/dialects/sqlite.py\n@@ -33,6 +33,14 @@ def _json_extract_sql(self: SQLite.Generator, expression: exp.JSONExtract) -> st\n return arrow_json_extract_sql(self, expression)\n \n \n+def _build_strftime(args: t.List) -> exp.Anonymous | exp.TimeToStr:\n+ if len(args) == 1:\n+ args.append(exp.CurrentTimestamp())\n+ if len(args) == 2:\n+ return exp.TimeToStr(this=exp.TsOrDsToTimestamp(this=args[1]), format=args[0])\n+ return exp.Anonymous(this=\"STRFTIME\", expressions=args)\n+\n+\n def _transform_create(expression: exp.Expression) -> exp.Expression:\n \"\"\"Move primary key to a column and enforce auto_increment on primary keys.\"\"\"\n schema = expression.this\n@@ -82,6 +90,7 @@ class SQLite(Dialect):\n FUNCTIONS = {\n **parser.Parser.FUNCTIONS,\n \"EDITDIST3\": exp.Levenshtein.from_arg_list,\n+ \"STRFTIME\": _build_strftime,\n }\n STRING_ALIASES = True\n \n@@ -152,7 +161,9 @@ class SQLite(Dialect):\n ),\n exp.TableSample: no_tablesample_sql,\n exp.TimeStrToTime: lambda self, e: self.sql(e, \"this\"),\n+ exp.TimeToStr: lambda self, e: self.func(\"STRFTIME\", e.args.get(\"format\"), e.this),\n exp.TryCast: no_trycast_sql,\n+ exp.TsOrDsToTimestamp: lambda self, e: self.sql(e, \"this\"),\n }\n \n # SQLite doesn't generally support CREATE TABLE .. properties\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 742dfcea..75751444 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -5687,6 +5687,10 @@ class TsOrDsToTime(Func):\n pass\n \n \n+class TsOrDsToTimestamp(Func):\n+ pass\n+\n+\n class TsOrDiToDi(Func):\n pass\n \ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex caec78d8..a67c7003 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -3516,6 +3516,13 @@ class Generator(metaclass=_Generator):\n \n return self.sql(exp.cast(this, \"time\"))\n \n+ def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:\n+ this = expression.this\n+ if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):\n+ return self.sql(this)\n+\n+ return self.sql(exp.cast(this, \"timestamp\"))\n+\n def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:\n this = expression.this\n time_format = self.format_time(expression)\n", "test_patch": "diff --git a/tests/dialects/test_sqlite.py b/tests/dialects/test_sqlite.py\nindex e935c194..f3cde0b6 100644\n--- a/tests/dialects/test_sqlite.py\n+++ b/tests/dialects/test_sqlite.py\n@@ -6,62 +6,6 @@ from sqlglot.helper import logger as helper_logger\n class TestSQLite(Validator):\n dialect = \"sqlite\"\n \n- def test_ddl(self):\n- for conflict_action in (\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"):\n- with self.subTest(f\"ON CONFLICT {conflict_action}\"):\n- self.validate_identity(\"CREATE TABLE a (b, c, UNIQUE (b, c) ON CONFLICT IGNORE)\")\n-\n- self.validate_identity(\"INSERT OR ABORT INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR FAIL INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR IGNORE INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR REPLACE INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"INSERT OR ROLLBACK INTO foo (x, y) VALUES (1, 2)\")\n- self.validate_identity(\"CREATE TABLE foo (id INTEGER PRIMARY KEY ASC)\")\n- self.validate_identity(\"CREATE TEMPORARY TABLE foo (id INTEGER)\")\n-\n- self.validate_all(\n- \"\"\"\n- CREATE TABLE \"Track\"\n- (\n- CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n- FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n- \"AlbumId\"\n- ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n- FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n- FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n- )\n- \"\"\",\n- write={\n- \"sqlite\": \"\"\"CREATE TABLE \"Track\" (\n- CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n- FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n- \"AlbumId\"\n- ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n- FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n- FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n-)\"\"\",\n- },\n- pretty=True,\n- )\n- self.validate_all(\n- \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n- read={\n- \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n- },\n- write={\n- \"sqlite\": \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n- \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n- \"postgres\": \"CREATE TABLE z (a INT GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE PRIMARY KEY)\",\n- },\n- )\n- self.validate_all(\n- \"\"\"CREATE TABLE \"x\" (\"Name\" NVARCHAR(200) NOT NULL)\"\"\",\n- write={\n- \"sqlite\": \"\"\"CREATE TABLE \"x\" (\"Name\" TEXT(200) NOT NULL)\"\"\",\n- \"mysql\": \"CREATE TABLE `x` (`Name` VARCHAR(200) NOT NULL)\",\n- },\n- )\n-\n def test_sqlite(self):\n self.validate_identity(\"SELECT DATE()\")\n self.validate_identity(\"SELECT DATE('now', 'start of month', '+1 month', '-1 day')\")\n@@ -69,7 +13,6 @@ class TestSQLite(Validator):\n self.validate_identity(\"SELECT DATETIME(1092941466, 'auto')\")\n self.validate_identity(\"SELECT DATETIME(1092941466, 'unixepoch', 'localtime')\")\n self.validate_identity(\"SELECT UNIXEPOCH()\")\n- self.validate_identity(\"SELECT STRFTIME('%s')\")\n self.validate_identity(\"SELECT JULIANDAY('now') - JULIANDAY('1776-07-04')\")\n self.validate_identity(\"SELECT UNIXEPOCH() - UNIXEPOCH('2004-01-01 02:34:56')\")\n self.validate_identity(\"SELECT DATE('now', 'start of year', '+9 months', 'weekday 2')\")\n@@ -149,6 +92,29 @@ class TestSQLite(Validator):\n write={\"snowflake\": \"LEAST(x, y, z)\"},\n )\n \n+ def test_strftime(self):\n+ self.validate_identity(\"SELECT STRFTIME('%Y/%m/%d', 'now')\")\n+ self.validate_identity(\"SELECT STRFTIME('%Y-%m-%d', '2016-10-16', 'start of month')\")\n+ self.validate_identity(\n+ \"SELECT STRFTIME('%s')\",\n+ \"SELECT STRFTIME('%s', CURRENT_TIMESTAMP)\",\n+ )\n+\n+ self.validate_all(\n+ \"SELECT STRFTIME('%Y-%m-%d', '2020-01-01 12:05:03')\",\n+ write={\n+ \"duckdb\": \"SELECT STRFTIME(CAST('2020-01-01 12:05:03' AS TIMESTAMP), '%Y-%m-%d')\",\n+ \"sqlite\": \"SELECT STRFTIME('%Y-%m-%d', '2020-01-01 12:05:03')\",\n+ },\n+ )\n+ self.validate_all(\n+ \"SELECT STRFTIME('%Y-%m-%d', CURRENT_TIMESTAMP)\",\n+ write={\n+ \"duckdb\": \"SELECT STRFTIME(CAST(CURRENT_TIMESTAMP AS TIMESTAMP), '%Y-%m-%d')\",\n+ \"sqlite\": \"SELECT STRFTIME('%Y-%m-%d', CURRENT_TIMESTAMP)\",\n+ },\n+ )\n+\n def test_datediff(self):\n self.validate_all(\n \"DATEDIFF(a, b, 'day')\",\n@@ -194,3 +160,59 @@ class TestSQLite(Validator):\n )\n \n self.assertIn(\"Named columns are not supported in table alias.\", cm.output[0])\n+\n+ def test_ddl(self):\n+ for conflict_action in (\"ABORT\", \"FAIL\", \"IGNORE\", \"REPLACE\", \"ROLLBACK\"):\n+ with self.subTest(f\"ON CONFLICT {conflict_action}\"):\n+ self.validate_identity(\"CREATE TABLE a (b, c, UNIQUE (b, c) ON CONFLICT IGNORE)\")\n+\n+ self.validate_identity(\"INSERT OR ABORT INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR FAIL INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR IGNORE INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR REPLACE INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"INSERT OR ROLLBACK INTO foo (x, y) VALUES (1, 2)\")\n+ self.validate_identity(\"CREATE TABLE foo (id INTEGER PRIMARY KEY ASC)\")\n+ self.validate_identity(\"CREATE TEMPORARY TABLE foo (id INTEGER)\")\n+\n+ self.validate_all(\n+ \"\"\"\n+ CREATE TABLE \"Track\"\n+ (\n+ CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n+ FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n+ \"AlbumId\"\n+ ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n+ )\n+ \"\"\",\n+ write={\n+ \"sqlite\": \"\"\"CREATE TABLE \"Track\" (\n+ CONSTRAINT \"PK_Track\" FOREIGN KEY (\"TrackId\"),\n+ FOREIGN KEY (\"AlbumId\") REFERENCES \"Album\" (\n+ \"AlbumId\"\n+ ) ON DELETE NO ACTION ON UPDATE NO ACTION,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE CASCADE ON UPDATE RESTRICT,\n+ FOREIGN KEY (\"AlbumId\") ON DELETE SET NULL ON UPDATE SET DEFAULT\n+)\"\"\",\n+ },\n+ pretty=True,\n+ )\n+ self.validate_all(\n+ \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n+ read={\n+ \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n+ },\n+ write={\n+ \"sqlite\": \"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)\",\n+ \"mysql\": \"CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)\",\n+ \"postgres\": \"CREATE TABLE z (a INT GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE PRIMARY KEY)\",\n+ },\n+ )\n+ self.validate_all(\n+ \"\"\"CREATE TABLE \"x\" (\"Name\" NVARCHAR(200) NOT NULL)\"\"\",\n+ write={\n+ \"sqlite\": \"\"\"CREATE TABLE \"x\" (\"Name\" TEXT(200) NOT NULL)\"\"\",\n+ \"mysql\": \"CREATE TABLE `x` (`Name` VARCHAR(200) NOT NULL)\",\n+ },\n+ )\n", "FAIL_TO_PASS": ["tests/dialects/test_sqlite.py::TestSQLite::test_strftime"]}, {"instance_id": "tobymao__sqlglot-3252", "base_commit": "150a8270c9e1c5a74aeaeeedac2773c41760cb14", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 5c953188..874ce901 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -261,6 +261,11 @@ class ClickHouse(Dialect):\n \"ArgMax\",\n ]\n \n+ FUNC_TOKENS = {\n+ *parser.Parser.FUNC_TOKENS,\n+ TokenType.SET,\n+ }\n+\n AGG_FUNC_MAPPING = (\n lambda functions, suffixes: {\n f\"{f}{sfx}\": (f, sfx) for sfx in (suffixes + [\"\"]) for f in functions\n@@ -321,6 +326,17 @@ class ClickHouse(Dialect):\n TokenType.FORMAT: lambda self: (\"format\", self._advance() or self._parse_id_var()),\n }\n \n+ CONSTRAINT_PARSERS = {\n+ **parser.Parser.CONSTRAINT_PARSERS,\n+ \"INDEX\": lambda self: self._parse_index_constraint(),\n+ \"CODEC\": lambda self: self._parse_compress(),\n+ }\n+\n+ SCHEMA_UNNAMED_CONSTRAINTS = {\n+ *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,\n+ \"INDEX\",\n+ }\n+\n def _parse_conjunction(self) -> t.Optional[exp.Expression]:\n this = super()._parse_conjunction()\n \n@@ -512,6 +528,27 @@ class ClickHouse(Dialect):\n self._retreat(index)\n return None\n \n+ def _parse_index_constraint(\n+ self, kind: t.Optional[str] = None\n+ ) -> exp.IndexColumnConstraint:\n+ # INDEX name1 expr TYPE type1(args) GRANULARITY value\n+ this = self._parse_id_var()\n+ expression = self._parse_conjunction()\n+\n+ index_type = self._match_text_seq(\"TYPE\") and (\n+ self._parse_function() or self._parse_var()\n+ )\n+\n+ granularity = self._match_text_seq(\"GRANULARITY\") and self._parse_term()\n+\n+ return self.expression(\n+ exp.IndexColumnConstraint,\n+ this=this,\n+ expression=expression,\n+ index_type=index_type,\n+ granularity=granularity,\n+ )\n+\n class Generator(generator.Generator):\n QUERY_HINTS = False\n STRUCT_DELIMITER = (\"(\", \")\")\n@@ -590,6 +627,9 @@ class ClickHouse(Dialect):\n exp.Array: inline_array_sql,\n exp.CastToStrType: rename_func(\"CAST\"),\n exp.CountIf: rename_func(\"countIf\"),\n+ exp.CompressColumnConstraint: lambda self,\n+ e: f\"CODEC({self.expressions(e, key='this', flat=True)})\",\n+ exp.ComputedColumnConstraint: lambda self, e: f\"ALIAS {self.sql(e, 'this')}\",\n exp.CurrentDate: lambda self, e: self.func(\"CURRENT_DATE\"),\n exp.DateAdd: date_delta_sql(\"DATE_ADD\"),\n exp.DateDiff: date_delta_sql(\"DATE_DIFF\"),\n@@ -742,3 +782,15 @@ class ClickHouse(Dialect):\n def prewhere_sql(self, expression: exp.PreWhere) -> str:\n this = self.indent(self.sql(expression, \"this\"))\n return f\"{self.seg('PREWHERE')}{self.sep()}{this}\"\n+\n+ def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:\n+ this = self.sql(expression, \"this\")\n+ this = f\" {this}\" if this else \"\"\n+ expr = self.sql(expression, \"expression\")\n+ expr = f\" {expr}\" if expr else \"\"\n+ index_type = self.sql(expression, \"index_type\")\n+ index_type = f\" TYPE {index_type}\" if index_type else \"\"\n+ granularity = self.sql(expression, \"granularity\")\n+ granularity = f\" GRANULARITY {granularity}\" if granularity else \"\"\n+\n+ return f\"INDEX{this}{expr}{index_type}{granularity}\"\ndiff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex aef2a759..66302fc4 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -480,9 +480,6 @@ class MySQL(Dialect):\n elif self._match_text_seq(\"ENGINE_ATTRIBUTE\"):\n self._match(TokenType.EQ)\n opt = exp.IndexConstraintOption(engine_attr=self._parse_string())\n- elif self._match_text_seq(\"ENGINE_ATTRIBUTE\"):\n- self._match(TokenType.EQ)\n- opt = exp.IndexConstraintOption(engine_attr=self._parse_string())\n elif self._match_text_seq(\"SECONDARY_ENGINE_ATTRIBUTE\"):\n self._match(TokenType.EQ)\n opt = exp.IndexConstraintOption(secondary_engine_attr=self._parse_string())\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 22f92b75..9f72c290 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -1665,13 +1665,16 @@ class GeneratedAsRowColumnConstraint(ColumnConstraintKind):\n \n \n # https://dev.mysql.com/doc/refman/8.0/en/create-table.html\n+# https://github.com/ClickHouse/ClickHouse/blob/master/src/Parsers/ParserCreateQuery.h#L646\n class IndexColumnConstraint(ColumnConstraintKind):\n arg_types = {\n \"this\": False,\n- \"schema\": True,\n+ \"schema\": False,\n \"kind\": False,\n \"index_type\": False,\n \"options\": False,\n+ \"expression\": False, # Clickhouse\n+ \"granularity\": False,\n }\n \n \ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex a2fcf3d5..474ba050 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -4504,7 +4504,7 @@ class Parser(metaclass=_Parser):\n \n constraints: t.List[exp.Expression] = []\n \n- if not kind and self._match(TokenType.ALIAS):\n+ if (not kind and self._match(TokenType.ALIAS)) or self._match_text_seq(\"ALIAS\"):\n constraints.append(\n self.expression(\n exp.ComputedColumnConstraint,\n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex f7165846..c5f9847c 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -154,7 +154,9 @@ class TestClickhouse(Validator):\n self.validate_identity(\"TRUNCATE TABLE t1 ON CLUSTER test_cluster\")\n self.validate_identity(\"TRUNCATE DATABASE db\")\n self.validate_identity(\"TRUNCATE DATABASE db ON CLUSTER test_cluster\")\n-\n+ self.validate_identity(\n+ \"CREATE TABLE t (foo String CODEC(LZ4HC(9), ZSTD, DELTA), size String ALIAS formatReadableSize(size_bytes), INDEX idx1 a TYPE bloom_filter(0.001) GRANULARITY 1, INDEX idx2 a TYPE set(100) GRANULARITY 2, INDEX idx3 a TYPE minmax GRANULARITY 3)\"\n+ )\n self.validate_all(\n \"SELECT arrayJoin([1,2,3])\",\n write={\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse"]}, {"instance_id": "tobymao__sqlglot-3255", "base_commit": "f88640b8df22e29ad2fa845b580cf78ad4fb2262", "gold_patch": "diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 1e94c05a..73a9166e 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -335,7 +335,13 @@ class Snowflake(Dialect):\n class Parser(parser.Parser):\n IDENTIFY_PIVOT_STRINGS = True\n \n+ ID_VAR_TOKENS = {\n+ *parser.Parser.ID_VAR_TOKENS,\n+ TokenType.MATCH_CONDITION,\n+ }\n+\n TABLE_ALIAS_TOKENS = parser.Parser.TABLE_ALIAS_TOKENS | {TokenType.WINDOW}\n+ TABLE_ALIAS_TOKENS.discard(TokenType.MATCH_CONDITION)\n \n FUNCTIONS = {\n **parser.Parser.FUNCTIONS,\n@@ -698,6 +704,7 @@ class Snowflake(Dialect):\n \"EXCLUDE\": TokenType.EXCEPT,\n \"ILIKE ANY\": TokenType.ILIKE_ANY,\n \"LIKE ANY\": TokenType.LIKE_ANY,\n+ \"MATCH_CONDITION\": TokenType.MATCH_CONDITION,\n \"MATCH_RECOGNIZE\": TokenType.MATCH_RECOGNIZE,\n \"MINUS\": TokenType.EXCEPT,\n \"NCHAR VARYING\": TokenType.VARCHAR,\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 9f72c290..78cc9d50 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -2100,6 +2100,7 @@ class Join(Expression):\n \"method\": False,\n \"global\": False,\n \"hint\": False,\n+ \"match_condition\": False, # Snowflake\n }\n \n @property\ndiff --git a/sqlglot/generator.py b/sqlglot/generator.py\nindex 470fa422..ae4b1ccd 100644\n--- a/sqlglot/generator.py\n+++ b/sqlglot/generator.py\n@@ -1873,6 +1873,8 @@ class Generator(metaclass=_Generator):\n )\n if op\n )\n+ match_cond = self.sql(expression, \"match_condition\")\n+ match_cond = f\" MATCH_CONDITION ({match_cond})\" if match_cond else \"\"\n on_sql = self.sql(expression, \"on\")\n using = expression.args.get(\"using\")\n \n@@ -1896,7 +1898,7 @@ class Generator(metaclass=_Generator):\n return f\", {this_sql}\"\n \n op_sql = f\"{op_sql} JOIN\" if op_sql else \"JOIN\"\n- return f\"{self.seg(op_sql)} {this_sql}{on_sql}\"\n+ return f\"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}\"\n \n def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = \"->\") -> str:\n args = self.expressions(expression, flat=True)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 474ba050..c8077ad3 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -2907,6 +2907,9 @@ class Parser(metaclass=_Parser):\n if hint:\n kwargs[\"hint\"] = hint\n \n+ if self._match(TokenType.MATCH_CONDITION):\n+ kwargs[\"match_condition\"] = self._parse_wrapped(self._parse_comparison)\n+\n if self._match(TokenType.ON):\n kwargs[\"on\"] = self._parse_conjunction()\n elif self._match(TokenType.USING):\ndiff --git a/sqlglot/tokens.py b/sqlglot/tokens.py\nindex f26511c2..1c5f8bc9 100644\n--- a/sqlglot/tokens.py\n+++ b/sqlglot/tokens.py\n@@ -291,6 +291,7 @@ class TokenType(AutoName):\n LOAD = auto()\n LOCK = auto()\n MAP = auto()\n+ MATCH_CONDITION = auto()\n MATCH_RECOGNIZE = auto()\n MEMBER_OF = auto()\n MERGE = auto()\n", "test_patch": "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex ad169e98..69c03bac 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -97,6 +97,10 @@ WHERE\n self.validate_identity(\n \"SELECT a FROM test PIVOT(SUM(x) FOR y IN ('z', 'q')) AS x TABLESAMPLE (0.1)\"\n )\n+ self.validate_identity(\n+ \"SELECT * FROM DATA AS DATA_L ASOF JOIN DATA AS DATA_R MATCH_CONDITION (DATA_L.VAL > DATA_R.VAL) ON DATA_L.ID = DATA_R.ID\"\n+ )\n+ self.validate_identity(\"SELECT MATCH_CONDITION\")\n self.validate_identity(\n \"SELECT a:from::STRING, a:from || ' test' \",\n \"SELECT CAST(GET_PATH(a, 'from') AS TEXT), GET_PATH(a, 'from') || ' test'\",\n", "FAIL_TO_PASS": ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_sqlite.py::TestSQLite::test_strftime", "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tobymao__sqlglot-3179_x3", "level": 3, "source": "swerebench", "repo": "tobymao/sqlglot", "image": "swerebench/sweb.eval.x86_64.tobymao_1776_sqlglot-3179:latest", "base_commit": "49f1e4e3ff1b9ddc9d238d2b409683cfe50e6819", "num_bugs": 3, "bugs": [{"instance_id": "tobymao__sqlglot-3179", "base_commit": "49f1e4e3ff1b9ddc9d238d2b409683cfe50e6819", "gold_patch": "diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py\nindex 8cc16be3..22715982 100644\n--- a/sqlglot/dialects/clickhouse.py\n+++ b/sqlglot/dialects/clickhouse.py\n@@ -306,6 +306,10 @@ class ClickHouse(Dialect):\n TokenType.SETTINGS,\n }\n \n+ ALIAS_TOKENS = parser.Parser.ALIAS_TOKENS - {\n+ TokenType.FORMAT,\n+ }\n+\n LOG_DEFAULTS_TO_LN = True\n \n QUERY_MODIFIER_PARSERS = {\ndiff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py\nindex f76ba546..a41b6ea8 100644\n--- a/sqlglot/dialects/redshift.py\n+++ b/sqlglot/dialects/redshift.py\n@@ -92,14 +92,6 @@ class Redshift(Postgres):\n \n return self.expression(exp.Pivot, this=table, unpivot=True) if unpivot else table\n \n- def _parse_type_size(self) -> t.Optional[exp.DataTypeParam]:\n- size = super()._parse_type_size()\n-\n- if size and isinstance(size.this, exp.Column):\n- size.set(\"this\", exp.var(size.this.name.upper()))\n-\n- return size\n-\n def _parse_convert(\n self, strict: bool, safe: t.Optional[bool] = None\n ) -> t.Optional[exp.Expression]:\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 208f3364..9102f8a7 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -405,6 +405,8 @@ class Parser(metaclass=_Parser):\n TokenType.WINDOW,\n }\n \n+ ALIAS_TOKENS = ID_VAR_TOKENS\n+\n COMMENT_TABLE_ALIAS_TOKENS = TABLE_ALIAS_TOKENS - {TokenType.IS}\n \n UPDATE_ALIAS_TOKENS = TABLE_ALIAS_TOKENS - {TokenType.SET}\n@@ -3928,6 +3930,9 @@ class Parser(metaclass=_Parser):\n if not this:\n return None\n \n+ if isinstance(this, exp.Column) and not this.table:\n+ this = exp.var(this.name.upper())\n+\n return self.expression(\n exp.DataTypeParam, this=this, expression=self._parse_var(any_token=True)\n )\n@@ -5254,6 +5259,9 @@ class Parser(metaclass=_Parser):\n def _parse_window(\n self, this: t.Optional[exp.Expression], alias: bool = False\n ) -> t.Optional[exp.Expression]:\n+ func = this\n+ comments = func.comments if isinstance(func, exp.Expression) else None\n+\n if self._match_pair(TokenType.FILTER, TokenType.L_PAREN):\n self._match(TokenType.WHERE)\n this = self.expression(\n@@ -5299,9 +5307,16 @@ class Parser(metaclass=_Parser):\n else:\n over = self._prev.text.upper()\n \n+ if comments:\n+ func.comments = None # type: ignore\n+\n if not self._match(TokenType.L_PAREN):\n return self.expression(\n- exp.Window, this=this, alias=self._parse_id_var(False), over=over\n+ exp.Window,\n+ comments=comments,\n+ this=this,\n+ alias=self._parse_id_var(False),\n+ over=over,\n )\n \n window_alias = self._parse_id_var(any_token=False, tokens=self.WINDOW_ALIAS_TOKENS)\n@@ -5334,6 +5349,7 @@ class Parser(metaclass=_Parser):\n \n window = self.expression(\n exp.Window,\n+ comments=comments,\n this=this,\n partition_by=partition,\n order=order,\n@@ -5385,7 +5401,7 @@ class Parser(metaclass=_Parser):\n self._match_r_paren(aliases)\n return aliases\n \n- alias = self._parse_id_var(any_token) or (\n+ alias = self._parse_id_var(any_token, tokens=self.ALIAS_TOKENS) or (\n self.STRING_ALIASES and self._parse_string_as_identifier()\n )\n \n", "test_patch": "diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py\nindex 8a40899a..b50c9b1c 100644\n--- a/tests/dialects/test_clickhouse.py\n+++ b/tests/dialects/test_clickhouse.py\n@@ -401,6 +401,11 @@ class TestClickhouse(Validator):\n \"\"\"INSERT INTO FUNCTION hdfs('hdfs://hdfs1:9000/test', 'TSV', 'name String, column2 UInt32, column3 UInt32') VALUES ('test', 1, 2)\"\"\",\n )\n \n+ self.validate_identity(\"SELECT 1 FORMAT TabSeparated\")\n+ self.validate_identity(\"SELECT * FROM t FORMAT TabSeparated\")\n+ self.validate_identity(\"SELECT FORMAT\")\n+ self.validate_identity(\"1 AS FORMAT\").assert_is(exp.Alias)\n+\n def test_cte(self):\n self.validate_identity(\"WITH 'x' AS foo SELECT foo\")\n self.validate_identity(\"WITH ['c'] AS field_names SELECT field_names\")\ndiff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py\nindex 411c29eb..896ee451 100644\n--- a/tests/dialects/test_redshift.py\n+++ b/tests/dialects/test_redshift.py\n@@ -504,7 +504,11 @@ FROM (\n \n def test_varchar_max(self):\n self.validate_all(\n- \"CREATE TABLE TEST (cola VARCHAR(max))\",\n+ 'CREATE TABLE \"TEST\" (\"cola\" VARCHAR(MAX))',\n+ read={\n+ \"redshift\": \"CREATE TABLE TEST (cola VARCHAR(max))\",\n+ \"tsql\": \"CREATE TABLE TEST (cola VARCHAR(max))\",\n+ },\n write={\n \"redshift\": 'CREATE TABLE \"TEST\" (\"cola\" VARCHAR(MAX))',\n },\ndiff --git a/tests/test_transpile.py b/tests/test_transpile.py\nindex d633f75e..0170e230 100644\n--- a/tests/test_transpile.py\n+++ b/tests/test_transpile.py\n@@ -480,6 +480,13 @@ SELECT\n FROM base\"\"\",\n pretty=True,\n )\n+ self.validate(\n+ \"\"\"-- comment\n+SOME_FUNC(arg IGNORE NULLS)\n+ OVER (PARTITION BY foo ORDER BY bla) AS col\"\"\",\n+ \"SOME_FUNC(arg IGNORE NULLS) OVER (PARTITION BY foo ORDER BY bla) AS col /* comment */\",\n+ pretty=True,\n+ )\n \n def test_types(self):\n self.validate(\"INT 1\", \"CAST(1 AS INT)\")\n", "FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_redshift.py::TestRedshift::test_varchar_max", "tests/test_transpile.py::TestTranspile::test_comments"]}, {"instance_id": "tobymao__sqlglot-3182", "base_commit": "4b36b9c99475057e921b50e7056428c64700567a", "gold_patch": "diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py\nindex 9837025a..470fd7c3 100644\n--- a/sqlglot/dialects/duckdb.py\n+++ b/sqlglot/dialects/duckdb.py\n@@ -38,10 +38,12 @@ def _ts_or_ds_add_sql(self: DuckDB.Generator, expression: exp.TsOrDsAdd) -> str:\n return f\"CAST({this} AS {self.sql(expression.return_type)}) + {interval}\"\n \n \n-def _date_delta_sql(self: DuckDB.Generator, expression: exp.DateAdd | exp.DateSub) -> str:\n+def _date_delta_sql(\n+ self: DuckDB.Generator, expression: exp.DateAdd | exp.DateSub | exp.TimeAdd\n+) -> str:\n this = self.sql(expression, \"this\")\n unit = self.sql(expression, \"unit\").strip(\"'\") or \"DAY\"\n- op = \"+\" if isinstance(expression, exp.DateAdd) else \"-\"\n+ op = \"+\" if isinstance(expression, (exp.DateAdd, exp.TimeAdd)) else \"-\"\n return f\"{this} {op} {self.sql(exp.Interval(this=expression.expression, unit=unit))}\"\n \n \n@@ -427,6 +429,7 @@ class DuckDB(Dialect):\n \"EPOCH\", self.func(\"STRPTIME\", e.this, self.format_time(e))\n ),\n exp.Struct: _struct_sql,\n+ exp.TimeAdd: _date_delta_sql,\n exp.Timestamp: no_timestamp_sql,\n exp.TimestampDiff: lambda self, e: self.func(\n \"DATE_DIFF\", exp.Literal.string(e.unit), e.expression, e.this\ndiff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py\nindex 0ffe4cf0..c13c15ab 100644\n--- a/sqlglot/dialects/snowflake.py\n+++ b/sqlglot/dialects/snowflake.py\n@@ -78,6 +78,17 @@ def _build_datediff(args: t.List) -> exp.DateDiff:\n )\n \n \n+def _build_date_time_add(expr_type: t.Type[E]) -> t.Callable[[t.List], E]:\n+ def _builder(args: t.List) -> E:\n+ return expr_type(\n+ this=seq_get(args, 2),\n+ expression=seq_get(args, 1),\n+ unit=_map_date_part(seq_get(args, 0)),\n+ )\n+\n+ return _builder\n+\n+\n # https://docs.snowflake.com/en/sql-reference/functions/div0\n def _build_if_from_div0(args: t.List) -> exp.If:\n cond = exp.EQ(this=seq_get(args, 1), expression=exp.Literal.number(0))\n@@ -345,11 +356,7 @@ class Snowflake(Dialect):\n \"CONVERT_TIMEZONE\": _build_convert_timezone,\n \"DATE\": _build_datetime(\"DATE\", exp.DataType.Type.DATE),\n \"DATE_TRUNC\": _date_trunc_to_time,\n- \"DATEADD\": lambda args: exp.DateAdd(\n- this=seq_get(args, 2),\n- expression=seq_get(args, 1),\n- unit=_map_date_part(seq_get(args, 0)),\n- ),\n+ \"DATEADD\": _build_date_time_add(exp.DateAdd),\n \"DATEDIFF\": _build_datediff,\n \"DIV0\": _build_if_from_div0,\n \"FLATTEN\": exp.Explode.from_arg_list,\n@@ -367,7 +374,9 @@ class Snowflake(Dialect):\n \"REGEXP_SUBSTR\": exp.RegexpExtract.from_arg_list,\n \"RLIKE\": exp.RegexpLike.from_arg_list,\n \"SQUARE\": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),\n+ \"TIMEADD\": _build_date_time_add(exp.TimeAdd),\n \"TIMEDIFF\": _build_datediff,\n+ \"TIMESTAMPADD\": _build_date_time_add(exp.DateAdd),\n \"TIMESTAMPDIFF\": _build_datediff,\n \"TIMESTAMPFROMPARTS\": _build_timestamp_from_parts,\n \"TIMESTAMP_FROM_PARTS\": _build_timestamp_from_parts,\n@@ -792,6 +801,7 @@ class Snowflake(Dialect):\n ),\n exp.StrToTime: lambda self, e: self.func(\"TO_TIMESTAMP\", e.this, self.format_time(e)),\n exp.Stuff: rename_func(\"INSERT\"),\n+ exp.TimeAdd: date_delta_sql(\"TIMEADD\"),\n exp.TimestampDiff: lambda self, e: self.func(\n \"TIMESTAMPDIFF\", e.unit, e.expression, e.this\n ),\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex c24fdff2..57a1044f 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -320,19 +320,39 @@ class Expression(metaclass=_Expression):\n value.index = len(values)\n values.append(value)\n \n- def set(self, arg_key: str, value: t.Any) -> None:\n+ def set(self, arg_key: str, value: t.Any, index: t.Optional[int] = None) -> None:\n \"\"\"\n Sets arg_key to value.\n \n Args:\n arg_key: name of the expression arg.\n value: value to set the arg to.\n- \"\"\"\n- if value is None:\n+ index: if the arg is a list, this specifies what position to add the value in it.\n+ \"\"\"\n+ if index is not None:\n+ expressions = self.args.get(arg_key) or []\n+\n+ if seq_get(expressions, index) is None:\n+ return\n+ if value is None:\n+ expressions.pop(index)\n+ for v in expressions[index:]:\n+ v.index = v.index - 1\n+ return\n+\n+ if isinstance(value, list):\n+ expressions.pop(index)\n+ expressions[index:index] = value\n+ else:\n+ expressions[index] = value\n+\n+ value = expressions\n+ elif value is None:\n self.args.pop(arg_key, None)\n- else:\n- self.args[arg_key] = value\n- self._set_parent(arg_key, value)\n+ return\n+\n+ self.args[arg_key] = value\n+ self._set_parent(arg_key, value, index)\n \n def _set_parent(self, arg_key: str, value: t.Any, index: t.Optional[int] = None) -> None:\n if hasattr(value, \"parent\"):\n@@ -579,13 +599,13 @@ class Expression(metaclass=_Expression):\n new_node = None\n \n for node in (self.copy() if copy else self).dfs(prune=lambda n: n is not new_node):\n+ parent, arg_key, index = node.parent, node.arg_key, node.index\n new_node = fun(node, *args, **kwargs)\n \n- if root:\n- if new_node is not node:\n- node.replace(new_node)\n- else:\n+ if not root:\n root = new_node\n+ elif new_node is not node:\n+ parent.set(arg_key, new_node, index)\n \n assert root\n return root.assert_is(Expression)\n@@ -617,37 +637,16 @@ class Expression(metaclass=_Expression):\n \"\"\"\n parent = self.parent\n \n- if not parent:\n+ if not parent or parent is expression:\n return expression\n \n key = self.arg_key\n value = parent.args.get(key)\n- exp_is_list = type(expression) is list\n \n- if type(value) is list:\n- index = self.index\n-\n- if exp_is_list:\n- value.pop(index)\n- value[index:index] = expression\n- parent._set_parent(key, value)\n- else:\n- if expression is None:\n- value.pop(index)\n-\n- for v in value[index:]:\n- v.index = v.index - 1\n- else:\n- value[index] = expression\n- parent._set_parent(key, expression, index=index)\n- elif value is not None:\n- if expression is None:\n- parent.args.pop(key)\n- else:\n- if exp_is_list and value.parent:\n- value.parent.replace(expression)\n- else:\n- parent.set(key, expression)\n+ if type(expression) is list and isinstance(value, Expression) and value.parent:\n+ value.parent.replace(expression)\n+ else:\n+ parent.set(key, expression, self.index)\n \n if expression is not self:\n self.parent = None\n", "test_patch": "diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py\nindex 917230b2..5cfcfea2 100644\n--- a/tests/dialects/test_duckdb.py\n+++ b/tests/dialects/test_duckdb.py\n@@ -15,6 +15,17 @@ class TestDuckDB(Validator):\n \"WITH _data AS (SELECT [STRUCT(1 AS a, 2 AS b), STRUCT(2 AS a, 3 AS b)] AS col) SELECT col.b FROM _data, UNNEST(_data.col) AS col WHERE col.a = 1\",\n )\n \n+ self.validate_all(\n+ \"SELECT CAST('09:05:03' AS TIME) + INTERVAL 2 HOUR\",\n+ read={\n+ \"bigquery\": \"SELECT TIME_ADD(CAST('09:05:03' AS TIME), INTERVAL 2 HOUR)\",\n+ \"snowflake\": \"SELECT TIMEADD(HOUR, 2, TO_TIME('09:05:03'))\",\n+ },\n+ write={\n+ \"duckdb\": \"SELECT CAST('09:05:03' AS TIME) + INTERVAL '2' HOUR\",\n+ \"snowflake\": \"SELECT CAST('09:05:03' AS TIME) + INTERVAL '2 HOUR'\",\n+ },\n+ )\n self.validate_all(\n 'STRUCT_PACK(\"a b\" := 1)',\n write={\ndiff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 00e6169a..4d7d97c5 100644\n--- a/tests/dialects/test_snowflake.py\n+++ b/tests/dialects/test_snowflake.py\n@@ -40,6 +40,7 @@ WHERE\n )\"\"\",\n )\n \n+ self.validate_identity(\"SELECT TIMEADD(HOUR, 2, CAST('09:05:03' AS TIME))\")\n self.validate_identity(\"SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS MAP(VARCHAR, INT))\")\n self.validate_identity(\"SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS OBJECT(a CHAR NOT NULL))\")\n self.validate_identity(\"SELECT CAST([1, 2, 3] AS ARRAY(INT))\")\n@@ -956,6 +957,9 @@ WHERE\n )\n self.validate_all(\n \"DATEADD(DAY, 5, CAST('2008-12-25' AS DATE))\",\n+ read={\n+ \"snowflake\": \"TIMESTAMPADD(DAY, 5, CAST('2008-12-25' AS DATE))\",\n+ },\n write={\n \"bigquery\": \"DATE_ADD(CAST('2008-12-25' AS DATE), INTERVAL 5 DAY)\",\n \"snowflake\": \"DATEADD(DAY, 5, CAST('2008-12-25' AS DATE))\",\ndiff --git a/tests/test_expressions.py b/tests/test_expressions.py\nindex 547f6356..54bc223c 100644\n--- a/tests/test_expressions.py\n+++ b/tests/test_expressions.py\n@@ -501,6 +501,18 @@ class TestExpressions(unittest.TestCase):\n \n self.assertEqual(expression.transform(fun).sql(), \"FUN(a)\")\n \n+ def test_transform_with_parent_mutation(self):\n+ expression = parse_one(\"SELECT COUNT(1) FROM table\")\n+\n+ def fun(node):\n+ if str(node) == \"COUNT(1)\":\n+ # node gets silently mutated here - its parent points to the filter node\n+ return exp.Filter(this=node, expression=exp.Where(this=exp.true()))\n+ return node\n+\n+ transformed = expression.transform(fun)\n+ self.assertEqual(transformed.sql(), \"SELECT COUNT(1) FILTER(WHERE TRUE) FROM table\")\n+\n def test_transform_multiple_children(self):\n expression = parse_one(\"SELECT * FROM x\")\n \n", "FAIL_TO_PASS": ["tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/test_expressions.py::TestExpressions::test_transform_with_parent_mutation"]}, {"instance_id": "tobymao__sqlglot-3191", "base_commit": "66e2e497626a77540b9addd35f2edb287c7b62fe", "gold_patch": "diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py\nindex 43029f02..1fe0d5c6 100644\n--- a/sqlglot/dialects/dialect.py\n+++ b/sqlglot/dialects/dialect.py\n@@ -1019,7 +1019,7 @@ def merge_without_target_sql(self: Generator, expression: exp.Merge) -> str:\n \n \n def build_json_extract_path(\n- expr_type: t.Type[F], zero_based_indexing: bool = True\n+ expr_type: t.Type[F], zero_based_indexing: bool = True, arrow_req_json_type: bool = False\n ) -> t.Callable[[t.List], F]:\n def _builder(args: t.List) -> F:\n segments: t.List[exp.JSONPathPart] = [exp.JSONPathRoot()]\n@@ -1039,7 +1039,11 @@ def build_json_extract_path(\n \n # This is done to avoid failing in the expression validator due to the arg count\n del args[2:]\n- return expr_type(this=seq_get(args, 0), expression=exp.JSONPath(expressions=segments))\n+ return expr_type(\n+ this=seq_get(args, 0),\n+ expression=exp.JSONPath(expressions=segments),\n+ only_json_types=arrow_req_json_type,\n+ )\n \n return _builder\n \ndiff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py\nindex 2836dcc5..4ea89b21 100644\n--- a/sqlglot/dialects/mysql.py\n+++ b/sqlglot/dialects/mysql.py\n@@ -408,6 +408,11 @@ class MySQL(Dialect):\n \"SPATIAL\": lambda self: self._parse_index_constraint(kind=\"SPATIAL\"),\n }\n \n+ ALTER_PARSERS = {\n+ **parser.Parser.ALTER_PARSERS,\n+ \"MODIFY\": lambda self: self._parse_alter_table_alter(),\n+ }\n+\n SCHEMA_UNNAMED_CONSTRAINTS = {\n *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,\n \"FULLTEXT\",\ndiff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py\nindex 35fc01ed..11398ed2 100644\n--- a/sqlglot/dialects/postgres.py\n+++ b/sqlglot/dialects/postgres.py\n@@ -357,6 +357,16 @@ class Postgres(Dialect):\n \n JSON_ARROWS_REQUIRE_JSON_TYPE = True\n \n+ COLUMN_OPERATORS = {\n+ **parser.Parser.COLUMN_OPERATORS,\n+ TokenType.ARROW: lambda self, this, path: build_json_extract_path(\n+ exp.JSONExtract, arrow_req_json_type=self.JSON_ARROWS_REQUIRE_JSON_TYPE\n+ )([this, path]),\n+ TokenType.DARROW: lambda self, this, path: build_json_extract_path(\n+ exp.JSONExtractScalar, arrow_req_json_type=self.JSON_ARROWS_REQUIRE_JSON_TYPE\n+ )([this, path]),\n+ }\n+\n def _parse_operator(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]:\n while True:\n if not self._match(TokenType.L_PAREN):\ndiff --git a/sqlglot/expressions.py b/sqlglot/expressions.py\nindex 57a1044f..883ab41a 100644\n--- a/sqlglot/expressions.py\n+++ b/sqlglot/expressions.py\n@@ -643,7 +643,9 @@ class Expression(metaclass=_Expression):\n key = self.arg_key\n value = parent.args.get(key)\n \n- if type(expression) is list and isinstance(value, Expression) and value.parent:\n+ if type(expression) is list and isinstance(value, Expression):\n+ # We are trying to replace an Expression with a list, so it's assumed that\n+ # the intention was to really replace the parent of this expression.\n value.parent.replace(expression)\n else:\n parent.set(key, expression, self.index)\ndiff --git a/sqlglot/parser.py b/sqlglot/parser.py\nindex 9102f8a7..274614af 100644\n--- a/sqlglot/parser.py\n+++ b/sqlglot/parser.py\n@@ -5695,10 +5695,11 @@ class Parser(metaclass=_Parser):\n return self.expression(exp.AlterColumn, this=column, comment=self._parse_string())\n \n self._match_text_seq(\"SET\", \"DATA\")\n+ self._match_text_seq(\"TYPE\")\n return self.expression(\n exp.AlterColumn,\n this=column,\n- dtype=self._match_text_seq(\"TYPE\") and self._parse_types(),\n+ dtype=self._parse_types(),\n collate=self._match(TokenType.COLLATE) and self._parse_term(),\n using=self._match(TokenType.USING) and self._parse_conjunction(),\n )\n", "test_patch": "diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py\nindex e1587601..23607da6 100644\n--- a/tests/dialects/test_mysql.py\n+++ b/tests/dialects/test_mysql.py\n@@ -85,6 +85,9 @@ class TestMySQL(Validator):\n \"ALTER TABLE test_table ALTER COLUMN test_column SET DATA TYPE LONGTEXT\",\n \"ALTER TABLE test_table MODIFY COLUMN test_column LONGTEXT\",\n )\n+ self.validate_identity(\n+ \"ALTER TABLE test_table MODIFY COLUMN test_column LONGTEXT\",\n+ )\n self.validate_identity(\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC\",\n \"CREATE TABLE t (c DATETIME DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()) DEFAULT CHARACTER SET=utf8 ROW_FORMAT=DYNAMIC\",\ndiff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py\nindex e2a153f5..f1c17667 100644\n--- a/tests/dialects/test_postgres.py\n+++ b/tests/dialects/test_postgres.py\n@@ -108,6 +108,8 @@ class TestPostgres(Validator):\n self.validate_identity(\n \"SELECT * FROM foo, LATERAL (SELECT * FROM bar WHERE bar.id = foo.bar_id) AS ss\"\n )\n+ self.validate_identity(\"SELECT ('data' -> 'en-US') AS acat FROM my_table\")\n+ self.validate_identity(\"SELECT ('data' ->> 'en-US') AS acat FROM my_table\")\n self.validate_identity(\n \"SELECT c.oid, n.nspname, c.relname \"\n \"FROM pg_catalog.pg_class AS c \"\n", "FAIL_TO_PASS": ["tests/dialects/test_postgres.py::TestPostgres::test_postgres"]}], "all_FAIL_TO_PASS": ["tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_redshift.py::TestRedshift::test_varchar_max", "tests/test_transpile.py::TestTranspile::test_comments", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/test_expressions.py::TestExpressions::test_transform_with_parent_mutation", "tests/dialects/test_postgres.py::TestPostgres::test_postgres"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "d0c-s4vage__pfp-116_x1", "level": 1, "source": "swerebenchv2", "repo": "d0c-s4vage/pfp", "image": "swerebenchv2/d0c-s4vage-pfp:116-36a03d8", "base_commit": "36a03d880ae74f888ccc97f31f6f851bcd102a62", "num_bugs": 1, "bugs": [{"instance_id": "d0c-s4vage__pfp-116", "base_commit": "36a03d880ae74f888ccc97f31f6f851bcd102a62", "gold_patch": "diff --git a/pfp/interp.py b/pfp/interp.py\nindex ffe3705..75e5369 100644\n--- a/pfp/interp.py\n+++ b/pfp/interp.py\n@@ -2070,6 +2070,7 @@ class PfpInterp(object):\n if node.op not in switch:\n raise errors.UnsupportedAssignmentOperator(node.coord, node.op)\n switch[node.op](field, value)\n+ return field\n \n def _handle_func_def(self, node, scope, ctxt, stream):\n \"\"\"Handle FuncDef nodes\n", "test_patch": "diff --git a/tests/test_control_flow.py b/tests/test_control_flow.py\nindex 99249eb..b71d785 100644\n--- a/tests/test_control_flow.py\n+++ b/tests/test_control_flow.py\n@@ -322,6 +322,21 @@ class TestControlFlow(utils.PfpTestCase):\n \"\"\",\n )\n \n+ def test_chained_assignment(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int b = 10;\n+ local int c;\n+ local int d;\n+\n+ c = d = b;\n+ \"\"\",\n+ )\n+ self.assertEqual(dom.b is dom.c, False)\n+ self.assertEqual(dom.b is dom.d, False)\n+ self.assertEqual(dom.c is dom.d, False)\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_control_flow.py::TestControlFlow::test_chained_assignment", "tests/test_control_flow.py::TestControlFlow::test_chained_assignment_with_string_data"]}], "all_FAIL_TO_PASS": ["tests/test_control_flow.py::TestControlFlow::test_chained_assignment", "tests/test_control_flow.py::TestControlFlow::test_chained_assignment_with_string_data"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "d0c-s4vage__pfp-121_x1", "level": 1, "source": "swerebenchv2", "repo": "d0c-s4vage/pfp", "image": "swerebenchv2/d0c-s4vage-pfp:121-7aa2577", "base_commit": "7aa2577fcc30de18ab8fc5a3707bd35f73decc53", "num_bugs": 1, "bugs": [{"instance_id": "d0c-s4vage__pfp-121", "base_commit": "7aa2577fcc30de18ab8fc5a3707bd35f73decc53", "gold_patch": "diff --git a/pfp/fields.py b/pfp/fields.py\nindex 58810ca..78dd419 100644\n--- a/pfp/fields.py\n+++ b/pfp/fields.py\n@@ -262,6 +262,12 @@ class Field(object):\n if stream is not None:\n self._pfp__parse(stream, save_offset=True)\n \n+ def _pfp__get_class(self):\n+ \"\"\"Return the class for this field. This would be used for things like\n+ integer promotion and type casting.\n+ \"\"\"\n+ return self.__class__\n+\n # see #51 - fields should have a method of returning the full path of its name\n def _pfp__path(self):\n \"\"\"Return the full pathname of this field. E.g. given\n@@ -678,6 +684,12 @@ class ImplicitArrayWrapper(Field):\n super(Field, self).__setattr__(\"last_field\", last_field)\n super(Field, self).__setattr__(\"implicit_array\", implicit_array)\n \n+ def _pfp__get_class(self):\n+ \"\"\"Return the last field class type and not the array type. Overrides\n+ :any:`Field._pfp__get_class`.\n+ \"\"\"\n+ return self.last_field._pfp__get_class()\n+\n def __setattr__(self, name, value):\n \"\"\"Custom setattr that forwards all sets to the last_field\n \"\"\"\ndiff --git a/pfp/interp.py b/pfp/interp.py\nindex 75e5369..73aafa6 100644\n--- a/pfp/interp.py\n+++ b/pfp/interp.py\n@@ -398,7 +398,7 @@ class Scope(object):\n \n \"\"\"\n if new_scope is None:\n- new_scope = {\"types\": {}, \"vars\": {}}\n+ new_scope = {\"types\": {}, \"vars\": {}, \"meta\": {}}\n self._curr_scope = new_scope\n self._dlog(\"pushing new scope, scope level = {}\".format(self.level()))\n self._scope_stack.append(self._curr_scope)\n@@ -428,6 +428,34 @@ class Scope(object):\n self._dlog(\"popping scope, scope level = {}\".format(self.level()))\n self._curr_scope = self._scope_stack[-1]\n return res\n+ \n+ def clear_meta(self):\n+ \"\"\"Clear metadata about the current statement\n+ \"\"\"\n+ self._curr_scope[\"meta\"] = {}\n+ \n+ def push_meta(self, meta_name, meta_value):\n+ \"\"\"Push metadata about the current statement onto the metadata stack\n+ for the current statement. Mostly used for tracking integer promotion\n+ and casting types\n+ \"\"\"\n+ self._dlog(\"adding metadata '{}'\".format(meta_name))\n+ self._curr_scope[\"meta\"].setdefault(meta_name, []).append(meta_value)\n+\n+ def get_meta(self, meta_name):\n+ \"\"\"Get the current meta value named ``meta_name``\n+ \"\"\"\n+ self._dlog(\"getting metadata '{}'\".format(meta_name))\n+ return self._curr_scope[\"meta\"].get(meta_name, [None])[-1]\n+\n+ def pop_meta(self, name):\n+ \"\"\"Pop metadata about the current statement from the metadata stack\n+ for the current statement.\n+\n+ :name: The name of the metadata\n+ \"\"\"\n+ self._dlog(\"getting meta '{}'\".format(name))\n+ return self._curr_scope[\"meta\"][name].pop()\n \n def add_var(self, field_name, field, root=False):\n \"\"\"Add a var to the current scope (vars are fields that\n@@ -455,7 +483,6 @@ class Scope(object):\n :name: The name of the id\n :recurse: Whether parent scopes should also be searched (defaults to True)\n :returns: TODO\n-\n \"\"\"\n self._dlog(\"getting var '{}'\".format(name))\n return self._search(\"vars\", name, recurse)\n@@ -853,7 +880,7 @@ class PfpInterp(object):\n res = None\n for child in ast.children():\n res = self._handle_node(\n- child, self._scope, self._ctxt, self._stream\n+ child, self._scope, self._ctxt, self._stream,\n )\n return res\n except errors.InterpReturn as e:\n@@ -1139,6 +1166,7 @@ class PfpInterp(object):\n and not is_forward_declared_struct(child):\n continue\n self._handle_node(child, scope, ctxt, stream)\n+ scope.clear_meta()\n \n for child in children:\n if type(child) is tuple:\n@@ -1176,9 +1204,13 @@ class PfpInterp(object):\n \"\"\"\n self._dlog(\"handling cast\")\n to_type = self._handle_node(node.to_type, scope, ctxt, stream)\n+\n+ scope.push_meta(\"dest_type\", to_type)\n val_to_cast = self._handle_node(node.expr, scope, ctxt, stream)\n+ scope.pop_meta(\"dest_type\")\n \n res = to_type()\n+\n res._pfp__set_value(val_to_cast)\n return res\n \n@@ -1584,6 +1616,7 @@ class PfpInterp(object):\n max_pos = 0\n for decl in node.decls:\n self._handle_node(decl, scope, ctxt, stream)\n+ scope.clear_meta()\n \n finally:\n # the union will have reset the stream\n@@ -1666,6 +1699,7 @@ class PfpInterp(object):\n for decl in node.decls:\n # new context! (struct)\n self._handle_node(decl, scope, ctxt, stream)\n+ scope.clear_meta()\n \n ctxt._pfp__process_fields_metadata()\n \n@@ -1821,18 +1855,29 @@ class PfpInterp(object):\n \"%\": lambda x, y: x % y,\n \">\": lambda x, y: x > y,\n \"<\": lambda x, y: x < y,\n- \"||\": lambda x, y: x or y,\n+ \"||\": lambda x, y: 1 if x or y else 0,\n \">=\": lambda x, y: x >= y,\n \"<=\": lambda x, y: x <= y,\n \"==\": lambda x, y: x == y,\n \"!=\": lambda x, y: x != y,\n- \"&&\": lambda x, y: x and y,\n+ \"&&\": lambda x, y: 1 if x and y else 0,\n \">>\": lambda x, y: x >> y,\n \"<<\": lambda x, y: x << y,\n }\n \n+ dest_type = scope.get_meta(\"dest_type\")\n+\n left_val = self._handle_node(node.left, scope, ctxt, stream)\n+ if dest_type is not None and not isinstance(left_val, dest_type):\n+ new_left_val = dest_type()\n+ new_left_val._pfp__set_value(left_val)\n+ left_val = new_left_val\n+\n right_val = self._handle_node(node.right, scope, ctxt, stream)\n+ if dest_type is not None and not isinstance(right_val, dest_type):\n+ new_right_val = dest_type()\n+ new_right_val._pfp__set_value(right_val)\n+ right_val = new_right_val\n \n if node.op not in switch:\n raise errors.UnsupportedBinaryOperator(node.coord, node.op)\n@@ -2057,10 +2102,20 @@ class PfpInterp(object):\n \"=\": assign_op,\n }\n \n+ scope.clear_meta()\n+\n self._dlog(\"handling assignment\")\n field = self._handle_node(node.lvalue, scope, ctxt, stream)\n self._dlog(\"field = {}\".format(field))\n- value = self._handle_node(node.rvalue, scope, ctxt, stream)\n+\n+ scope.push_meta(\"dest_type\", field._pfp__get_class())\n+\n+ value = self._handle_node(\n+ node.rvalue,\n+ scope,\n+ ctxt,\n+ stream,\n+ )\n \n if node.op is None:\n self._dlog(\"value = {}\".format(value))\n@@ -2185,6 +2240,7 @@ class PfpInterp(object):\n \n try:\n for child in node.children():\n+ scope.clear_meta()\n self._handle_node(child, scope, ctxt, stream)\n \n # in case a return occurs, be sure to pop the scope\n@@ -2398,7 +2454,7 @@ class PfpInterp(object):\n except errors.InterpContinue as e:\n pass\n if node.cond is not None and not self._handle_node(\n- node.cond, scope, ctxt, stream\n+ node.cond, scope, ctxt, stream,\n ):\n break\n \n@@ -2594,7 +2650,6 @@ class PfpInterp(object):\n :returns: TODO\n \n \"\"\"\n-\n res = self._handle_node(node, scope, ctxt, stream)\n \n if isinstance(res, fields.Field):\n", "test_patch": "diff --git a/tests/test_arrays.py b/tests/test_arrays.py\nindex 450995d..f98a224 100644\n--- a/tests/test_arrays.py\n+++ b/tests/test_arrays.py\n@@ -287,7 +287,6 @@ class TestArrays(utils.PfpTestCase):\n uint array[1];\n } TestStruct;\n \"\"\",\n- verify=False,\n )\n struct = dom.TestStruct()\n struct.array = [0xFFFF]\ndiff --git a/tests/test_basic.py b/tests/test_basic.py\nindex d735e91..1739846 100644\n--- a/tests/test_basic.py\n+++ b/tests/test_basic.py\n@@ -212,6 +212,180 @@ class TestBasic(utils.PfpTestCase):\n \"\"\",\n )\n \n+ def test_add_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 2;\n+ local int j = 3;\n+ local int k = i + j;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"5\",\n+ )\n+\n+ def test_minus_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 2;\n+ local int j = 3;\n+ local int k = i - j;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"-1\",\n+ )\n+\n+ def test_mul_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 2;\n+ local int j = 3;\n+ local int k = i * j;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"6\",\n+ )\n+\n+ def test_div_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 2;\n+ local int j = 6;\n+ local int k = j / i;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"3\",\n+ )\n+\n+ def test_mod_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 5;\n+ local int j = 7;\n+ local int k = j % i;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"2\",\n+ )\n+\n+ def test_xor_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 6;\n+ local int j = 3;\n+ local int k = j ^ i;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"5\",\n+ )\n+\n+ def test_and_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 56; // 0b111000\n+ local int j = 25; // 0b011001\n+ local int k = j & i;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=str(int(\"011000\", 2)),\n+ )\n+\n+ def test_or_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 56; // 0b111000\n+ local int j = 25; // 0b011001\n+ local int k = j | i;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=str(int(\"111001\", 2)),\n+ )\n+\n+ def test_logical_or_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 0;\n+ local int j = 25;\n+ local int k = j || i;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"1\",\n+ )\n+\n+ def test_logical_or_operator2(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ Printf(\n+ \"%d,%d,%d,%d\",\n+ 0 || 0,\n+ 0 || 1,\n+ 1 || 0,\n+ 1 || 1\n+ );\n+ \"\"\",\n+ stdout=\"0,1,1,1\",\n+ )\n+\n+ def test_logical_and_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 0;\n+ local int j = 25;\n+ local int k = j && i;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"0\",\n+ )\n+\n+ def test_logical_and_operator2(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ Printf(\n+ \"%d,%d,%d,%d\",\n+ 0 && 0,\n+ 0 && 1,\n+ 1 && 0,\n+ 1 && 1\n+ );\n+ \"\"\",\n+ stdout=\"0,0,0,1\",\n+ )\n+\n+ def test_logical_shl_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 3;\n+ local int j = 4;\n+ local int k = i << j;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"48\",\n+ )\n+\n+ def test_logical_shr_operator(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local int i = 0x17000;\n+ local int j = 4;\n+ local int k = i >> j;\n+ Printf(\"%d\", k);\n+ \"\"\",\n+ stdout=\"5888\",\n+ )\n+\n def test_local_accessible_via_this(self):\n dom = self._test_parse_build(\n \"\\x01\\x02\\x03\\x04\",\n@@ -222,7 +396,6 @@ class TestBasic(utils.PfpTestCase):\n Printf(\"%d\", test);\n } blah;\n \"\"\",\n- verify=False,\n stdout=\"{a},{a}\".format(a=str(0x04030201)),\n )\n \n@@ -240,7 +413,6 @@ class TestBasic(utils.PfpTestCase):\n Printf(\"%d\", test);\n } blah;\n \"\"\",\n- verify=False,\n stdout=\"{a},{a}\".format(a=str(0x04030201)),\n )\n \ndiff --git a/tests/test_cast.py b/tests/test_cast.py\nindex f9ba96e..7d4ee7d 100644\n--- a/tests/test_cast.py\n+++ b/tests/test_cast.py\n@@ -34,6 +34,18 @@ class TestArrays(utils.PfpTestCase):\n stdout=\"a\",\n )\n \n+ def test_cast_from_dex(self):\n+ dom = self._test_parse_build(\n+ \"\",\n+ \"\"\"\n+ local ubyte cur = 7;\n+ local uint test1 = (uint)(10);\n+ local uint test2 = (uint)((cur & 0x7f) << 7);\n+ Printf(\"%u,%u\", test1, test2);\n+ \"\"\",\n+ stdout=\"10,896\",\n+ )\n+\n \n if __name__ == \"__main__\":\n unittest.main()\ndiff --git a/tests/test_compat.py b/tests/test_compat.py\nindex d6b6245..c3c5f26 100644\n--- a/tests/test_compat.py\n+++ b/tests/test_compat.py\n@@ -137,7 +137,6 @@ class TestCompatIO(utils.PfpTestCase):\n Printf(\"%d|\", blah);\n Printf(\"%d\", FTell());\n \"\"\",\n- verify=False,\n stdout=\"32769|0\",\n )\n \n@@ -153,7 +152,6 @@ class TestCompatIO(utils.PfpTestCase):\n uchar b;\n Printf(\"%d%d\", a, b);\n \"\"\",\n- verify=False,\n stdout=\"ab9798\",\n )\n \n@@ -204,7 +202,6 @@ class TestCompatIO(utils.PfpTestCase):\n Printf(\"%d\", FSeek(FTell() + 4));\n Printf(\"%d\", FSeek(FTell() + 2));\n \"\"\",\n- verify=False,\n stdout=\"0-1\",\n )\n \n@@ -226,7 +223,6 @@ class TestCompatIO(utils.PfpTestCase):\n local int rv6 = FSeek(0);\n local int pos7 = FTell();\n \"\"\",\n- verify=False,\n )\n self.assertEqual(dom.pos1, 0)\n self.assertEqual(dom.rv1, 0)\n@@ -293,7 +289,6 @@ class TestCompatIO(utils.PfpTestCase):\n local int fskip_rv2 = FSkip(3);\n local int pos2 = FTell();\n \"\"\",\n- verify=False,\n )\n self.assertEqual(dom.fskip_rv1, 0)\n self.assertEqual(dom.pos1, 1)\n@@ -542,7 +537,6 @@ class TestCompatTools(utils.PfpTestCase):\n }\n \"\"\",\n stdout=\"count:3start-size:5-5start-size:17-5start-size:28-5\",\n- verify=False,\n predefines=True,\n )\n \n@@ -562,7 +556,6 @@ class TestCompatTools(utils.PfpTestCase):\n }\n \"\"\",\n stdout=\"count:3start-size:5-5start-size:17-5start-size:28-5\",\n- verify=False,\n predefines=True,\n )\n \n@@ -582,7 +575,6 @@ class TestCompatTools(utils.PfpTestCase):\n }\n \"\"\",\n stdout=\"count:3start-size:5-5start-size:17-5start-size:28-5\",\n- verify=False,\n predefines=True,\n )\n \n@@ -602,7 +594,6 @@ class TestCompatTools(utils.PfpTestCase):\n }\n \"\"\",\n stdout=\"count:3start-size:5-5start-size:22-5start-size:33-5\",\n- verify=False,\n predefines=True,\n )\n \n@@ -627,7 +618,6 @@ class TestCompatTools(utils.PfpTestCase):\n }\n \"\"\",\n stdout=\"count:3start-size:5-5start-size:22-5start-size:33-5\",\n- verify=False,\n predefines=True,\n )\n \n@@ -652,7 +642,6 @@ class TestCompatTools(utils.PfpTestCase):\n }\n \"\"\",\n stdout=\"count:3start-size:5-5start-size:16-5start-size:27-5\",\n- verify=False,\n predefines=True,\n )\n \n@@ -681,7 +670,6 @@ class TestCompatTools(utils.PfpTestCase):\n }\n \"\"\",\n stdout=\"count:2start-size:5-5start-size:16-5\",\n- verify=False,\n predefines=True,\n )\n \n@@ -696,7 +684,6 @@ class TestCompatTools(utils.PfpTestCase):\n index = FindNext();\n Printf(\"%d\", index);\n \"\"\",\n- verify=False,\n stdout=\"5,16,27\",\n )\n \ndiff --git a/tests/test_functions.py b/tests/test_functions.py\nindex fb4b302..ad88ca9 100644\n--- a/tests/test_functions.py\n+++ b/tests/test_functions.py\n@@ -155,7 +155,6 @@ class TestFunctions(utils.PfpTestCase):\n Printf(\"false\");\n }\n \"\"\",\n- verify=False,\n stdout=\"true\",\n )\n \ndiff --git a/tests/test_strings.py b/tests/test_strings.py\nindex 6bf4a0d..7ced832 100644\n--- a/tests/test_strings.py\n+++ b/tests/test_strings.py\n@@ -121,7 +121,6 @@ class TestStrings(utils.PfpTestCase):\n Printf(\"%s\", temp_expected);\n \"\"\",\n stdout=\"0102030405\",\n- verify=False,\n )\n \n def test_add_strings_simple(self):\n@@ -136,7 +135,6 @@ class TestStrings(utils.PfpTestCase):\n Printf(\"%s\", test);\n \"\"\",\n stdout=\"testtesttesttesttest\",\n- verify=False,\n )\n \n \ndiff --git a/tests/utils.py b/tests/utils.py\nindex 4e8255e..13ef1ab 100644\n--- a/tests/utils.py\n+++ b/tests/utils.py\n@@ -59,7 +59,6 @@ class PfpTestCase(unittest.TestCase):\n stdout=None,\n debug=False,\n predefines=False,\n- verify=True,\n _stream=True,\n printf=True,\n ):\n", "FAIL_TO_PASS": ["tests/test_basic.py::TestBasic::test_logical_or_operator", "tests/test_basic.py::TestBasic::test_logical_or_operator_with_string_data", "tests/test_cast.py::TestArrays::test_cast_from_dex", "tests/test_cast.py::TestArrays::test_cast_from_dex_with_string_data"]}], "all_FAIL_TO_PASS": ["tests/test_basic.py::TestBasic::test_logical_or_operator", "tests/test_basic.py::TestBasic::test_logical_or_operator_with_string_data", "tests/test_cast.py::TestArrays::test_cast_from_dex", "tests/test_cast.py::TestArrays::test_cast_from_dex_with_string_data"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "takluyver__flit-168_x1", "level": 1, "source": "swerebenchv2", "repo": "takluyver/flit", "image": "swerebenchv2/takluyver-flit:168-29dbe93", "base_commit": "29dbe93af9005487e14a85da4e0e7c408f536231", "num_bugs": 1, "bugs": [{"instance_id": "takluyver__flit-168", "base_commit": "29dbe93af9005487e14a85da4e0e7c408f536231", "gold_patch": "diff --git a/doc/history.rst b/doc/history.rst\nindex 650ad1e..4effcd6 100644\n--- a/doc/history.rst\n+++ b/doc/history.rst\n@@ -1,6 +1,13 @@\n Release history\n ===============\n \n+Version 0.14\n+------------\n+\n+- Multiple links (e.g. documentation, bug tracker) can now be specified in a\n+ new :ref:`[tool.flit.metadata.urls] section ` of\n+ ``pyproject.toml``.\n+\n Version 0.13\n ------------\n \ndiff --git a/doc/pyproject_toml.rst b/doc/pyproject_toml.rst\nindex 422cda7..09dfcf4 100644\n--- a/doc/pyproject_toml.rst\n+++ b/doc/pyproject_toml.rst\n@@ -115,6 +115,25 @@ Here's the full metadata section from flit itself:\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ]\n \n+.. _pyproject_toml_urls:\n+\n+URLs subsection\n+~~~~~~~~~~~~~~~\n+\n+Your project's page on `pypi.org `_ can show a number of\n+links, in addition to the required ``home-page`` URL described above. You can\n+point people to documentation or a bug tracker, for example.\n+\n+This section is called ``[tool.flit.metadata.urls]`` in the file. You can use\n+any names inside it. Here it is for flit:\n+\n+.. code-block:: toml\n+\n+ [tool.flit.metadata.urls]\n+ Documentation = \"https://flit.readthedocs.io/en/latest/\"\n+\n+.. versionadded:: 0.14\n+\n .. _pyproject_toml_scripts:\n \n Scripts section\ndiff --git a/flit/common.py b/flit/common.py\nindex 833f31a..5def1f9 100644\n--- a/flit/common.py\n+++ b/flit/common.py\n@@ -277,6 +277,9 @@ class Metadata:\n for req in self.requires_dist:\n fp.write('Requires-Dist: {}\\n'.format(req))\n \n+ for url in self.project_urls:\n+ fp.write('Project-URL: {}\\n'.format(url))\n+\n if self.description is not None:\n fp.write('\\n' + self.description + '\\n')\n \ndiff --git a/flit/inifile.py b/flit/inifile.py\nindex 3c1b9e0..234683f 100644\n--- a/flit/inifile.py\n+++ b/flit/inifile.py\n@@ -198,6 +198,11 @@ def _prep_metadata(md_sect, path):\n log.warning(stream.getvalue())\n md_dict['description'] = raw_desc\n \n+ if 'urls' in md_sect:\n+ project_urls = md_dict['project_urls'] = []\n+ for label, url in md_sect.pop('urls').items():\n+ project_urls.append(\"{}, {}\".format(label, url))\n+\n for key, value in md_sect.items():\n if key in {'description-file', 'module'}:\n continue\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 0299700..276ef75 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -25,5 +25,8 @@ classifiers=[\"Intended Audience :: Developers\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ]\n \n+[tool.flit.metadata.urls]\n+Documentation = \"https://flit.readthedocs.io/en/latest/\"\n+\n [tool.flit.scripts]\n flit = \"flit:main\"\n", "test_patch": "diff --git a/tests/samples/module1-pkg.toml b/tests/samples/module1-pkg.toml\nindex f7dc8f1..740ec87 100644\n--- a/tests/samples/module1-pkg.toml\n+++ b/tests/samples/module1-pkg.toml\n@@ -7,3 +7,6 @@ author = \"Sir Robin\"\n author-email = \"robin@camelot.uk\"\n home-page = \"http://github.com/sirrobin/module1\"\n description-file = \"EG_README.rst\"\n+\n+[tool.flit.metadata.urls]\n+Documentation = \"https://example.com/module1\"\n", "FAIL_TO_PASS": ["tests/test_build.py::test_build_main", "tests/test_inifile.py::test_load_toml"]}], "all_FAIL_TO_PASS": ["tests/test_build.py::test_build_main", "tests/test_inifile.py::test_load_toml"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "kayak__pypika-31_x1", "level": 1, "source": "swerebenchv2", "repo": "kayak/pypika", "image": "swerebenchv2/kayak-pypika:31-f9a70e3", "base_commit": "f9a70e361512de5f0bcdb50723e1445760fc698e", "num_bugs": 1, "bugs": [{"instance_id": "kayak__pypika-31", "base_commit": "f9a70e361512de5f0bcdb50723e1445760fc698e", "gold_patch": "diff --git a/pypika/queries.py b/pypika/queries.py\nindex 6afa498..f070a6a 100644\n--- a/pypika/queries.py\n+++ b/pypika/queries.py\n@@ -152,7 +152,7 @@ class QueryBuilder(Selectable, Term):\n def __init__(self):\n super(QueryBuilder, self).__init__(None)\n \n- self._from = None\n+ self._from = []\n self._insert_table = None\n \n self._selects = []\n@@ -192,13 +192,11 @@ class QueryBuilder(Selectable, Term):\n :returns\n A copy of the query with the table added.\n \"\"\"\n- if self._from is not None:\n- raise AttributeError(\"'Query' object has no attribute '%s'\" % 'from_')\n \n- self._from = Table(selectable) if isinstance(selectable, str) else selectable\n+ self._from.append(Table(selectable) if isinstance(selectable, str) else selectable)\n \n if isinstance(selectable, QueryBuilder):\n- selectable.table_name = 'sq0'\n+ selectable.table_name = 'sq%d' % self._subquery_count\n self._subquery_count += 1\n \n @builder\n@@ -280,7 +278,7 @@ class QueryBuilder(Selectable, Term):\n def groupby(self, *terms):\n for term in terms:\n if isinstance(term, str):\n- term = Field(term, table=self._from)\n+ term = Field(term, table=self._from[0])\n \n self._validate_term(term)\n self._groupbys.append(term)\n@@ -306,7 +304,7 @@ class QueryBuilder(Selectable, Term):\n @builder\n def orderby(self, *fields, **kwargs):\n for field in fields:\n- field = (Field(field, table=self._from)\n+ field = (Field(field, table=self._from[0])\n if isinstance(field, str)\n else self._wrap(field))\n \n@@ -362,7 +360,7 @@ class QueryBuilder(Selectable, Term):\n self._selects = [Star()]\n return\n \n- self._select_field(Field(term, table=self._from))\n+ self._select_field(Field(term, table=self._from[0]))\n \n def _select_field(self, term):\n if self._select_star:\n@@ -417,25 +415,28 @@ class QueryBuilder(Selectable, Term):\n if isinstance(item, QueryBuilder):\n self._tag_subquery(item)\n \n- if (isinstance(item, Table) and isinstance(self._from, Table) and\n- item.alias is None and item.table_name == self._from.table_name):\n+ table_in_from = any(isinstance(clause, Table)\n+ and item.table_name == self._from[0].table_name\n+ for clause in self._from)\n+ if (isinstance(item, Table) and item.alias is None and table_in_from):\n # On the odd chance that we join the same table as the FROM table and don't set an alias\n+ # FIXME only works once\n item.alias = item.table_name + '2'\n \n self._joins.append(Join(item, criterion, how))\n \n def _validate_term(self, term):\n for field in term.fields():\n- if (field.table is not None\n- and field.table != self._from\n- and field.table not in [join.item for join in self._joins]):\n+ table_in_froms = field.table in self._from\n+ table_in_joins = field.table in [join.item for join in self._joins]\n+ if field.table is not None and not table_in_froms and not table_in_joins:\n raise JoinException('Table [%s] missing from query. '\n 'Table must be first joined before any of '\n 'its fields can be used' % field.table)\n \n def _validate_join(self, criterion, item):\n criterion_tables = set([f.table for f in criterion.fields()])\n- available_tables = ({self._from} | {join.item for join in self._joins} | {item})\n+ available_tables = (set(self._from) | {join.item for join in self._joins} | {item})\n missing_tables = criterion_tables - available_tables\n if missing_tables:\n raise JoinException('Invalid join criterion. One field is required from the joined item and '\n@@ -457,16 +458,13 @@ class QueryBuilder(Selectable, Term):\n if not self.alias == other.alias:\n return False\n \n- if not self._from == other._from:\n- return False\n-\n return True\n \n def __ne__(self, other):\n return not self.__eq__(other)\n \n def __hash__(self):\n- return hash(self.alias) + hash(self._from)\n+ return hash(self.alias) + sum(hash(clause) for clause in self._from)\n \n def get_sql(self, with_alias=False, subquery=False, with_unions=False, **kwargs):\n if not (self._selects or self._insert_table):\n@@ -474,7 +472,7 @@ class QueryBuilder(Selectable, Term):\n if self._insert_table and not (self._selects or self._values):\n return ''\n \n- kwargs = {'with_namespace': bool(self._joins)}\n+ kwargs = {'with_namespace': bool(self._joins) or 1 < len(self._from)}\n \n if not self._select_into and self._insert_table:\n querystring = self._insert_sql()\n@@ -494,7 +492,7 @@ class QueryBuilder(Selectable, Term):\n querystring += self._into_sql()\n \n if self._from:\n- querystring += self._from_sql()\n+ querystring += self._from_sql(**kwargs)\n \n if self._joins:\n for join_item in self._joins:\n@@ -567,10 +565,11 @@ class QueryBuilder(Selectable, Term):\n table=self._insert_table.get_sql(with_quotes=True, with_alias=False),\n )\n \n- def _from_sql(self):\n- return ' FROM {selectable}'.format(\n- selectable=self._from.get_sql(with_quotes=True, subquery=True, with_alias=bool(self._joins)),\n- )\n+ def _from_sql(self, with_namespace=False, **kwargs):\n+ return ' FROM {selectable}'.format(selectable=','.join(\n+ clause.get_sql(with_quotes=True, subquery=True, with_alias=with_namespace)\n+ for clause in self._from\n+ ))\n \n def _jointype_sql(self, join_item):\n return ' {type}'.format(type=join_item.how.value)\n", "test_patch": "diff --git a/pypika/tests/test_selects.py b/pypika/tests/test_selects.py\nindex 457e365..e705b29 100644\n--- a/pypika/tests/test_selects.py\n+++ b/pypika/tests/test_selects.py\n@@ -8,7 +8,7 @@ __email__ = \"theys@kayak.com\"\n \n \n class SelectTests(unittest.TestCase):\n- t = Table('abc')\n+ table_abc, table_efg = Tables('abc', 'efg')\n \n def test_empty_query(self):\n q = Query.from_('abc')\n@@ -59,16 +59,31 @@ class SelectTests(unittest.TestCase):\n self.assertEqual('SELECT \"foo\",\"bar\" FROM \"abc\"', str(q2))\n \n def test_select__columns__multi__field(self):\n- q1 = Query.from_(self.t).select(self.t.foo, self.t.bar)\n- q2 = Query.from_(self.t).select(self.t.foo).select(self.t.bar)\n+ q1 = Query.from_(self.table_abc).select(self.table_abc.foo, self.table_abc.bar)\n+ q2 = Query.from_(self.table_abc).select(self.table_abc.foo).select(self.table_abc.bar)\n \n self.assertEqual('SELECT \"foo\",\"bar\" FROM \"abc\"', str(q1))\n self.assertEqual('SELECT \"foo\",\"bar\" FROM \"abc\"', str(q2))\n \n- def test_select__fields_after_star(self):\n- q = Query.from_('abc').select('*').select('foo')\n+ def test_select__multiple_tables(self):\n+ q = Query.from_(self.table_abc) \\\n+ .select(self.table_abc.foo) \\\n+ .from_(self.table_efg) \\\n+ .select(self.table_efg.bar)\n \n- self.assertEqual('SELECT * FROM \"abc\"', str(q))\n+ self.assertEqual('SELECT \"abc\".\"foo\",\"efg\".\"bar\" FROM \"abc\",\"efg\"', str(q))\n+\n+ def test_select__multiple_subqueries(self):\n+ subquery0 = Query.from_(self.table_abc).select(\"foo\")\n+ subquery1 = Query.from_(self.table_efg).select(\"bar\")\n+ q = Query \\\n+ .from_(subquery0) \\\n+ .from_(subquery1) \\\n+ .select(subquery0.foo, subquery1.bar)\n+\n+ self.assertEqual('SELECT \"sq0\".\"foo\",\"sq1\".\"bar\" '\n+ 'FROM (SELECT \"foo\" FROM \"abc\") \"sq0\",'\n+ '(SELECT \"bar\" FROM \"efg\") \"sq1\"', str(q))\n \n def test_select__no_table(self):\n q = Query.select(1, 2, 3)\n@@ -80,14 +95,6 @@ class SelectTests(unittest.TestCase):\n \n self.assertEqual('SELECT 1,2,3,\"foo\" FROM \"abc\"', str(q))\n \n- def test_static_from_function_removed_after_called(self):\n- with self.assertRaises(AttributeError):\n- Query.from_('abc').from_('efg')\n-\n- def test_instance_from_function_removed_after_called(self):\n- with self.assertRaises(AttributeError):\n- Query.select(1).from_('abc').from_('efg')\n-\n def test_select_with_limit(self):\n q1 = Query.from_('abc').select('foo')[:10]\n \n@@ -393,6 +400,16 @@ class AliasTests(unittest.TestCase):\n \n self.assertListEqual(['foo', 'buz2'], test_query.groupby_aliases())\n \n+ def test_select__multiple_tables(self):\n+ table_abc, table_efg = Table('abc', alias='q0'), Table('efg', alias='q1')\n+\n+ q = Query.from_(table_abc) \\\n+ .select(table_abc.foo) \\\n+ .from_(table_efg) \\\n+ .select(table_efg.bar)\n+\n+ self.assertEqual('SELECT \"q0\".\"foo\",\"q1\".\"bar\" FROM \"abc\" \"q0\",\"efg\" \"q1\"', str(q))\n+\n \n class SubqueryTests(unittest.TestCase):\n maxDiff = None\n", "FAIL_TO_PASS": ["pypika/tests/test_selects.py::SelectTests::test_select__multiple_subqueries", "pypika/tests/test_selects.py::SelectTests::test_select__multiple_tables", "pypika/tests/test_selects.py::AliasTests::test_select__multiple_tables"]}], "all_FAIL_TO_PASS": ["pypika/tests/test_selects.py::SelectTests::test_select__multiple_subqueries", "pypika/tests/test_selects.py::SelectTests::test_select__multiple_tables", "pypika/tests/test_selects.py::AliasTests::test_select__multiple_tables"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "kayak__pypika-33_x1", "level": 1, "source": "swerebenchv2", "repo": "kayak/pypika", "image": "swerebenchv2/kayak-pypika:33-675812e", "base_commit": "675812eca20b252fa572404be81aecf0c54b114d", "num_bugs": 1, "bugs": [{"instance_id": "kayak__pypika-33", "base_commit": "675812eca20b252fa572404be81aecf0c54b114d", "gold_patch": "diff --git a/pypika/queries.py b/pypika/queries.py\nindex f070a6a..91faa46 100644\n--- a/pypika/queries.py\n+++ b/pypika/queries.py\n@@ -529,7 +529,7 @@ class QueryBuilder(Selectable, Term):\n return self._queryalias_sql(querystring)\n \n if with_unions:\n- querystring += self._union_sql(querystring)\n+ querystring = self._union_sql(querystring)\n \n return querystring\n \n@@ -614,8 +614,10 @@ class QueryBuilder(Selectable, Term):\n )\n \n def _union_sql(self, querystring):\n- unionstring = ''\n if self._unions:\n+ # Some queries require brackets for unions so easier to just always use them\n+ querystring = \"({})\".format(querystring)\n+\n for (union_type, other) in self._unions:\n if len(self._selects) != len(other._selects):\n raise UnionException(\"Queries must have an equal number of select statements in a union.\"\n@@ -623,11 +625,10 @@ class QueryBuilder(Selectable, Term):\n \"\\n\\nUnion Query:\\n{query2}\".format(query1=querystring,\n query2=other.get_sql()))\n \n- unionstring += ' UNION{type} {query}'.format(\n- type=union_type.value,\n- query=other.get_sql()\n- )\n- return unionstring\n+ querystring += ' UNION{type} ({query})' \\\n+ .format(type=union_type.value, query=other.get_sql())\n+\n+ return querystring\n \n def _offset_sql(self):\n return \" OFFSET {offset}\".format(offset=self._offset)\n", "test_patch": "diff --git a/pypika/tests/test_joins.py b/pypika/tests/test_joins.py\nindex 7d45293..ad423f9 100644\n--- a/pypika/tests/test_joins.py\n+++ b/pypika/tests/test_joins.py\n@@ -260,15 +260,15 @@ class UnionTests(unittest.TestCase):\n query1 = Query.from_(self.table1).select(self.table1.foo)\n query2 = Query.from_(self.table2).select(self.table2.bar)\n \n- self.assertEqual('SELECT \"foo\" FROM \"abc\" UNION SELECT \"bar\" FROM \"efg\"', str(query1 + query2))\n- self.assertEqual('SELECT \"foo\" FROM \"abc\" UNION SELECT \"bar\" FROM \"efg\"', str(query1.union(query2)))\n+ self.assertEqual('(SELECT \"foo\" FROM \"abc\") UNION (SELECT \"bar\" FROM \"efg\")', str(query1 + query2))\n+ self.assertEqual('(SELECT \"foo\" FROM \"abc\") UNION (SELECT \"bar\" FROM \"efg\")', str(query1.union(query2)))\n \n def test_union_all(self):\n query1 = Query.from_(self.table1).select(self.table1.foo)\n query2 = Query.from_(self.table2).select(self.table2.bar)\n \n- self.assertEqual('SELECT \"foo\" FROM \"abc\" UNION ALL SELECT \"bar\" FROM \"efg\"', str(query1 * query2))\n- self.assertEqual('SELECT \"foo\" FROM \"abc\" UNION ALL SELECT \"bar\" FROM \"efg\"', str(query1.union_all(query2)))\n+ self.assertEqual('(SELECT \"foo\" FROM \"abc\") UNION ALL (SELECT \"bar\" FROM \"efg\")', str(query1 * query2))\n+ self.assertEqual('(SELECT \"foo\" FROM \"abc\") UNION ALL (SELECT \"bar\" FROM \"efg\")', str(query1.union_all(query2)))\n \n def test_require_equal_number_of_fields(self):\n query1 = Query.from_(self.table1).select(self.table1.foo)\n", "FAIL_TO_PASS": ["pypika/tests/test_joins.py::UnionTests::test_union", "pypika/tests/test_joins.py::UnionTests::test_union_all"]}], "all_FAIL_TO_PASS": ["pypika/tests/test_joins.py::UnionTests::test_union", "pypika/tests/test_joins.py::UnionTests::test_union_all"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "kayak__pypika-38_x1", "level": 1, "source": "swerebenchv2", "repo": "kayak/pypika", "image": "swerebenchv2/kayak-pypika:38-fe6bf77", "base_commit": "fe6bf777316d7044a484d39206c30afa0ea8ec53", "num_bugs": 1, "bugs": [{"instance_id": "kayak__pypika-38", "base_commit": "fe6bf777316d7044a484d39206c30afa0ea8ec53", "gold_patch": "diff --git a/README.rst b/README.rst\nindex 2154b78..3bba5bd 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -289,11 +289,13 @@ After adding a ``GROUP BY`` clause to a query, the ``HAVING`` clause becomes ava\n Joining Tables and Subqueries\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n \n-Tables and subqueries can be joined to any query using the ``Query.join()`` method. When joining tables and\n-subqueries, a criterion must provided containing an equality between a field from the primary table or joined tables and\n-a field from the joining table. When calling ``Query.join()`` with a table, a ``TablerJoiner`` will be\n-returned with only the ``Joiner.on()`` function available which takes a ``Criterion`` parameter. After\n-calling ``Joiner.on()`` the original query builder is returned and additional methods may be chained.\n+Tables and subqueries can be joined to any query using the ``Query.join()`` method. Joins can be performed with either\n+a ``USING`` or ``ON`` clauses. The ``USING`` clause can be used when both tables/subqueries contain the same field and\n+the ``ON`` clause can be used with a criterion. To perform a join, ``...join()`` can be chained but then must be\n+followed immediately by ``...on()`` or ``...using(*field)``.\n+\n+Example of a join using `ON`\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n .. code-block:: python\n \n@@ -308,9 +310,33 @@ calling ``Joiner.on()`` the original query builder is returned and additional me\n customers.id == 5\n )\n \n+\n .. code-block:: sql\n \n- SELECT history.* FROM history JOIN customers ON history.customer_id=customers.id WHERE customers.id=5\n+ SELECT \"history\".* FROM \"history\" JOIN \"customers\" ON \"history\".\"customer_id\"=\"customers\".\"id\" WHERE \"customers\".\"id\"=5\n+\n+\n+Example of a join using `USING`\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+.. code-block:: python\n+\n+ history, customers = Tables('history', 'customers')\n+ q = Query.from_(history).join(\n+ customers\n+ ).on(\n+ 'customer_id'\n+ ).select(\n+ history.star\n+ ).where(\n+ customers.id == 5\n+ )\n+\n+\n+.. code-block:: sql\n+\n+ SELECT \"history\".* FROM \"history\" JOIN \"customers\" USING \"customer_id\" WHERE \"customers\".\"id\"=5\n+\n \n Unions\n \"\"\"\"\"\"\n@@ -333,7 +359,7 @@ union all, use ``Query.union_all()`` or the `*` operator.\n \n .. code-block:: sql\n \n- SELECT created_time,foo,bar FROM provider_a UNION SELECT created_time,fiz,buz FROM provider_b\n+ SELECT \"created_time\",\"foo\",\"bar\" FROM \"provider_a\" UNION SELECT \"created_time\",\"fiz\",\"buz\" FROM \"provider_b\"\n \n \n Date, Time, and Intervals\ndiff --git a/pypika/queries.py b/pypika/queries.py\nindex 91faa46..3feffe2 100644\n--- a/pypika/queries.py\n+++ b/pypika/queries.py\n@@ -409,21 +409,21 @@ class QueryBuilder(Selectable, Term):\n \"\"\"\n return self._list_aliases(self._groupbys)\n \n- def do_join(self, item, criterion, how):\n- self._validate_join(criterion, item)\n+ def do_join(self, join):\n+ join.validate(self._from, self._joins)\n \n- if isinstance(item, QueryBuilder):\n- self._tag_subquery(item)\n+ if isinstance(join.item, QueryBuilder):\n+ self._tag_subquery(join.item)\n \n table_in_from = any(isinstance(clause, Table)\n- and item.table_name == self._from[0].table_name\n+ and join.item.table_name == self._from[0].table_name\n for clause in self._from)\n- if (isinstance(item, Table) and item.alias is None and table_in_from):\n+ if isinstance(join.item, Table) and join.item.alias is None and table_in_from:\n # On the odd chance that we join the same table as the FROM table and don't set an alias\n # FIXME only works once\n- item.alias = item.table_name + '2'\n+ join.item.alias = join.item.table_name + '2'\n \n- self._joins.append(Join(item, criterion, how))\n+ self._joins.append(join)\n \n def _validate_term(self, term):\n for field in term.fields():\n@@ -434,16 +434,6 @@ class QueryBuilder(Selectable, Term):\n 'Table must be first joined before any of '\n 'its fields can be used' % field.table)\n \n- def _validate_join(self, criterion, item):\n- criterion_tables = set([f.table for f in criterion.fields()])\n- available_tables = (set(self._from) | {join.item for join in self._joins} | {item})\n- missing_tables = criterion_tables - available_tables\n- if missing_tables:\n- raise JoinException('Invalid join criterion. One field is required from the joined item and '\n- 'another from the selected table or an existing join. Found [{tables}]'.format(\n- tables=', '.join(map(str, missing_tables))\n- ))\n-\n def _tag_subquery(self, subquery):\n subquery.alias = 'sq%d' % self._subquery_count\n self._subquery_count += 1\n@@ -495,10 +485,8 @@ class QueryBuilder(Selectable, Term):\n querystring += self._from_sql(**kwargs)\n \n if self._joins:\n- for join_item in self._joins:\n- if join_item.how.value:\n- querystring += self._jointype_sql(join_item)\n- querystring += self._join_sql(join_item, **kwargs)\n+ querystring += \" \" + \" \".join(join.get_sql(**kwargs)\n+ for join in self._joins)\n \n if self._wheres:\n querystring += self._where_sql(**kwargs)\n@@ -571,15 +559,6 @@ class QueryBuilder(Selectable, Term):\n for clause in self._from\n ))\n \n- def _jointype_sql(self, join_item):\n- return ' {type}'.format(type=join_item.how.value)\n-\n- def _join_sql(self, join, **kwargs):\n- return ' JOIN {table} ON {criterion}'.format(\n- table=join.item.get_sql(with_quotes=True, subquery=True, with_alias=True),\n- criterion=join.criteria.get_sql(with_quotes=True, **kwargs),\n- )\n-\n def _where_sql(self, **kwargs):\n return ' WHERE {where}'.format(where=self._wheres.get_sql(with_quotes=True, subquery=True, **kwargs))\n \n@@ -649,12 +628,67 @@ class Joiner(object):\n raise JoinException(\"Parameter 'on' is required when joining a \"\n \"{type} but was not supplied.\".format(type=self.type_label))\n \n- self.query.do_join(self.item, criterion, self.how)\n+ self.query.do_join(JoinOn(self.item, self.how, criterion))\n+ return self.query\n+\n+ def using(self, *fields):\n+ if not fields:\n+ raise JoinException(\"Parameter 'fields' is required when joining with \"\n+ \"a using clause but was not supplied.\".format(type=self.type_label))\n+\n+ self.query.do_join(JoinUsing(self.item, self.how, [Field(field) for field in fields]))\n return self.query\n \n \n class Join(object):\n- def __init__(self, item, criteria, how):\n+ def __init__(self, item, how):\n self.item = item\n- self.criteria = criteria\n self.how = how\n+\n+ def get_sql(self, **kwargs):\n+ sql = 'JOIN {table}'.format(\n+ table=self.item.get_sql(with_quotes=True, subquery=True, with_alias=True),\n+ )\n+\n+ if self.how.value:\n+ return '{type} {join}'.format(join=sql, type=self.how.value)\n+ return sql\n+\n+\n+class JoinOn(Join):\n+ def __init__(self, item, how, criteria):\n+ super(JoinOn, self).__init__(item, how)\n+ self.criterion = criteria\n+\n+ def get_sql(self, **kwargs):\n+ join_sql = super(JoinOn, self).get_sql(**kwargs)\n+ return '{join} ON {criterion}'.format(\n+ join=join_sql,\n+ criterion=self.criterion.get_sql(with_quotes=True, **kwargs),\n+ )\n+\n+ def validate(self, _from, _joins):\n+ criterion_tables = set([f.table for f in self.criterion.fields()])\n+ available_tables = (set(_from) | {join.item for join in _joins} | {self.item})\n+ missing_tables = criterion_tables - available_tables\n+ if missing_tables:\n+ raise JoinException('Invalid join criterion. One field is required from the joined item and '\n+ 'another from the selected table or an existing join. Found [{tables}]'.format(\n+ tables=', '.join(map(str, missing_tables))\n+ ))\n+\n+\n+class JoinUsing(Join):\n+ def __init__(self, item, how, fields):\n+ super(JoinUsing, self).__init__(item, how)\n+ self.fields = fields\n+\n+ def get_sql(self, **kwargs):\n+ join_sql = super(JoinUsing, self).get_sql(**kwargs)\n+ return '{join} USING ({fields})'.format(\n+ join=join_sql,\n+ fields=','.join(str(field) for field in self.fields)\n+ )\n+\n+ def validate(self, _from, _joins):\n+ pass\n", "test_patch": "diff --git a/pypika/tests/test_joins.py b/pypika/tests/test_joins.py\nindex ad423f9..7667ced 100644\n--- a/pypika/tests/test_joins.py\n+++ b/pypika/tests/test_joins.py\n@@ -31,6 +31,16 @@ class JoinTypeTests(unittest.TestCase):\n self.assertEqual('SELECT * FROM \"abc\" JOIN \"efg\" ON \"abc\".\"foo\"=\"efg\".\"bar\"', str(query))\n self.assertEqual('SELECT * FROM \"abc\" JOIN \"efg\" ON \"abc\".\"foo\"=\"efg\".\"bar\"', str(query_explicit))\n \n+ def test_join_using_string_field_name(self):\n+ query = Query.from_(self.table0).join(self.table1).using('id').select('*')\n+\n+ self.assertEqual('SELECT * FROM \"abc\" JOIN \"efg\" USING (\"id\")', str(query))\n+\n+ def test_join_using_multiple_fields(self):\n+ query = Query.from_(self.table0).join(self.table1).using('foo', 'bar').select('*')\n+\n+ self.assertEqual('SELECT * FROM \"abc\" JOIN \"efg\" USING (\"foo\",\"bar\")', str(query))\n+\n def test_outer_join(self):\n query = Query.from_(self.table0).join(self.table1, how=JoinType.outer).on(\n self.table0.foo == self.table1.bar).select('*')\n", "FAIL_TO_PASS": ["pypika/tests/test_joins.py::JoinTypeTests::test_join_using_multiple_fields", "pypika/tests/test_joins.py::JoinTypeTests::test_join_using_string_field_name"]}], "all_FAIL_TO_PASS": ["pypika/tests/test_joins.py::JoinTypeTests::test_join_using_multiple_fields", "pypika/tests/test_joins.py::JoinTypeTests::test_join_using_string_field_name"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "neurodatawithoutborders__pynwb-791_x1", "level": 1, "source": "swerebenchv2", "repo": "NeurodataWithoutBorders/pynwb", "image": "swerebenchv2/neurodatawithoutborders-pynwb:791-16e7259", "base_commit": "16e7259f2ed111f5ae1ca4c2463b7c42f1fde0e0", "num_bugs": 1, "bugs": [{"instance_id": "neurodatawithoutborders__pynwb-791", "base_commit": "16e7259f2ed111f5ae1ca4c2463b7c42f1fde0e0", "gold_patch": "diff --git a/src/pynwb/core.py b/src/pynwb/core.py\nindex 58f85657..23f6bcfd 100644\n--- a/src/pynwb/core.py\n+++ b/src/pynwb/core.py\n@@ -80,6 +80,21 @@ class NWBBaseType(with_metaclass(ExtenderMeta, Container)):\n call_docval_func(super(NWBBaseType, self).__init__, kwargs)\n self.__fields = dict()\n \n+ @docval({'name': 'neurodata_type', 'type': str, 'doc': 'the neurodata_type to search for', 'default': None})\n+ def get_ancestor(self, **kwargs):\n+ \"\"\"\n+ Traverse parent hierarchy and return first instance of the specified neurodata_type\n+ \"\"\"\n+ neurodata_type = getargs('neurodata_type', kwargs)\n+ if neurodata_type is None:\n+ return self.parent\n+ p = self.parent\n+ while p is not None:\n+ if p.neurodata_type == neurodata_type:\n+ return p\n+ p = p.parent\n+ return None\n+\n @property\n def fields(self):\n return self.__fields\n@@ -984,6 +999,7 @@ class DynamicTable(NWBDataInterface):\n \n # to make generating DataFrames and Series easier\n col_dict = dict()\n+ self.__indices = dict()\n for col in self.columns:\n if isinstance(col, VectorData):\n existing = col_dict.get(col.name)\n@@ -1000,6 +1016,7 @@ class DynamicTable(NWBDataInterface):\n col_dict[col.name] = col\n elif isinstance(col, VectorIndex):\n col_dict[col.target.name] = col # use target name for reference and VectorIndex for retrieval\n+ self.__indices[col.name] = col\n \n self.__df_cols = [self.id] + [col_dict[name] for name in self.colnames]\n self.__colids = {name: i+1 for i, name in enumerate(self.colnames)}\n@@ -1140,6 +1157,7 @@ class DynamicTable(NWBDataInterface):\n columns.insert(0, col_index)\n self.add_child(col_index)\n col = col_index\n+ self.__indices[col_index.name] = col_index\n \n if len(col) != len(self.id):\n raise ValueError(\"column must have the same number of rows as 'id'\")\n@@ -1181,7 +1199,12 @@ class DynamicTable(NWBDataInterface):\n arg = key\n if isinstance(arg, str):\n # index by one string, return column\n- ret = self.__df_cols[self.__colids[arg]]\n+ if arg in self.__colids:\n+ ret = self.__df_cols[self.__colids[arg]]\n+ elif arg in self.__indices:\n+ return self.__indices[arg]\n+ else:\n+ raise KeyError(arg)\n elif isinstance(arg, (int, np.int8, np.int16, np.int32, np.int64)):\n # index by int, return row\n ret = tuple(col[arg] for col in self.__df_cols)\n@@ -1194,7 +1217,7 @@ class DynamicTable(NWBDataInterface):\n return ret\n \n def __contains__(self, val):\n- return val in self.__colids\n+ return val in self.__colids or val in self.__indices\n \n def get(self, key, default=None):\n if key in self:\ndiff --git a/src/pynwb/form/build/map.py b/src/pynwb/form/build/map.py\nindex 8b15d819..eedade2a 100644\n--- a/src/pynwb/form/build/map.py\n+++ b/src/pynwb/form/build/map.py\n@@ -102,6 +102,10 @@ class BuildManager(object):\n def namespace_catalog(self):\n return self.__type_map.namespace_catalog\n \n+ @property\n+ def type_map(self):\n+ return self.__type_map\n+\n @docval({\"name\": \"object\", \"type\": (BaseBuilder, Container), \"doc\": \"the container or builder to get a proxy for\"},\n {\"name\": \"source\", \"type\": str,\n \"doc\": \"the source of container being built i.e. file path\", 'default': None})\n@@ -854,7 +858,11 @@ class ObjectMapper(with_metaclass(ExtenderMeta, object)):\n \n if isinstance(spec.dtype, RefSpec):\n if not self.__is_reftype(attr_value):\n- msg = \"invalid type for reference '%s' (%s) - must be Container\" % (spec.name, type(attr_value))\n+ if attr_value is None:\n+ msg = \"object of data_type %s not found on %s '%s'\" % \\\n+ (spec.dtype.target_type, type(container).__name__, container.name)\n+ else:\n+ msg = \"invalid type for reference '%s' (%s) - must be Container\" % (spec.name, type(attr_value))\n raise ValueError(msg)\n target_builder = build_manager.build(attr_value, source=source)\n attr_value = ReferenceBuilder(target_builder)\ndiff --git a/src/pynwb/io/core.py b/src/pynwb/io/core.py\nindex 9f712046..30293b4f 100644\n--- a/src/pynwb/io/core.py\n+++ b/src/pynwb/io/core.py\n@@ -8,8 +8,7 @@ from pynwb.file import NWBFile\n from pynwb.core import NWBData, DynamicTable, NWBContainer, VectorIndex\n \n \n-@register_map(NWBContainer)\n-class NWBContainerMapper(ObjectMapper):\n+class NWBBaseTypeMapper(ObjectMapper):\n \n @staticmethod\n def get_nwb_file(container):\n@@ -20,6 +19,12 @@ class NWBContainerMapper(ObjectMapper):\n curr = container.parent\n \n \n+@register_map(NWBContainer)\n+class NWBContainerMapper(NWBBaseTypeMapper):\n+\n+ pass\n+\n+\n @register_map(DynamicTable)\n class DynamicTableMap(NWBContainerMapper):\n \n@@ -55,11 +60,13 @@ class DynamicTableMap(NWBContainerMapper):\n msg = \"empty or missing table for DynamicTableRegion '%s' in DynamicTable '%s'\" %\\\n (attr_value.name, container.name)\n raise ValueError(msg)\n+ elif spec.neurodata_type_inc == 'VectorIndex':\n+ attr_value = container[spec.name]\n return attr_value\n \n \n @register_map(NWBData)\n-class NWBDataMap(ObjectMapper):\n+class NWBDataMap(NWBBaseTypeMapper):\n \n @ObjectMapper.constructor_arg('name')\n def carg_name(self, builder, manager):\ndiff --git a/src/pynwb/misc.py b/src/pynwb/misc.py\nindex 8b2d6059..3ecde661 100644\n--- a/src/pynwb/misc.py\n+++ b/src/pynwb/misc.py\n@@ -193,13 +193,16 @@ class Units(DynamicTable):\n {'name': 'columns', 'type': (tuple, list), 'doc': 'the columns in this table', 'default': None},\n {'name': 'colnames', 'type': 'array_data', 'doc': 'the names of the columns in this table',\n 'default': None},\n- {'name': 'description', 'type': str, 'doc': 'a description of what is in this table', 'default': None})\n+ {'name': 'description', 'type': str, 'doc': 'a description of what is in this table', 'default': None},\n+ {'name': 'electrode_table', 'type': DynamicTable,\n+ 'doc': 'the table that the *electrodes* column indexes', 'default': None})\n def __init__(self, **kwargs):\n if kwargs.get('description', None) is None:\n- kwargs['description'] = \"\"\n+ kwargs['description'] = \"data on spiking units\"\n call_docval_func(super(Units, self).__init__, kwargs)\n if 'spike_times' not in self.colnames:\n self.__has_spike_times = False\n+ self.__electrode_table = getargs('electrode_table', kwargs)\n \n @docval({'name': 'spike_times', 'type': 'array_data', 'doc': 'the spike times for each unit',\n 'default': None, 'shape': (None,)},\n@@ -223,6 +226,14 @@ class Units(DynamicTable):\n Add a unit to this table\n \"\"\"\n super(Units, self).add_row(**kwargs)\n+ if 'electrodes' in self:\n+ elec_col = self['electrodes'].target\n+ if elec_col.table is None:\n+ if self.__electrode_table is None:\n+ nwbfile = self.get_ancestor(neurodata_type='NWBFile')\n+ elec_col.table = nwbfile.electrodes\n+ else:\n+ elec_col.table = self.__electrode_table\n \n @docval({'name': 'index', 'type': int,\n 'doc': 'the index of the unit in unit_ids to retrieve spike times for'})\n", "test_patch": "diff --git a/tests/unit/pynwb_tests/test_file.py b/tests/unit/pynwb_tests/test_file.py\nindex b1363b0a..b44638e3 100644\n--- a/tests/unit/pynwb_tests/test_file.py\n+++ b/tests/unit/pynwb_tests/test_file.py\n@@ -262,6 +262,18 @@ class NWBFileTest(unittest.TestCase):\n source_script=None,\n source_script_file_name='nofilename')\n \n+ def test_get_neurodata_type(self):\n+ ts1 = TimeSeries('test_ts1', [0, 1, 2, 3, 4, 5],\n+ 'grams', timestamps=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5])\n+ ts2 = TimeSeries('test_ts2', [0, 1, 2, 3, 4, 5],\n+ 'grams', timestamps=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5])\n+ self.nwbfile.add_acquisition(ts1)\n+ self.nwbfile.add_acquisition(ts2)\n+ p1 = ts1.get_ancestor(neurodata_type='NWBFile')\n+ self.assertIs(p1, self.nwbfile)\n+ p2 = ts2.get_ancestor(neurodata_type='NWBFile')\n+ self.assertIs(p2, self.nwbfile)\n+\n \n class SubjectTest(unittest.TestCase):\n def setUp(self):\n", "FAIL_TO_PASS": ["tests/unit/pynwb_tests/test_file.py::NWBFileTest::test_get_neurodata_type"]}], "all_FAIL_TO_PASS": ["tests/unit/pynwb_tests/test_file.py::NWBFileTest::test_get_neurodata_type"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "neurodatawithoutborders__pynwb-811_x1", "level": 1, "source": "swerebenchv2", "repo": "NeurodataWithoutBorders/pynwb", "image": "swerebenchv2/neurodatawithoutborders-pynwb:811-605d78d", "base_commit": "605d78d93f84328be54c6a09b301f86de3631658", "num_bugs": 1, "bugs": [{"instance_id": "neurodatawithoutborders__pynwb-811", "base_commit": "605d78d93f84328be54c6a09b301f86de3631658", "gold_patch": "diff --git a/docs/gallery/domain/brain_observatory.py b/docs/gallery/domain/brain_observatory.py\nindex 81049264..f931c3f0 100644\n--- a/docs/gallery/domain/brain_observatory.py\n+++ b/docs/gallery/domain/brain_observatory.py\n@@ -40,7 +40,7 @@ metadata = dataset.get_metadata()\n cell_specimen_ids = dataset.get_cell_specimen_ids()\n timestamps, dFF = dataset.get_dff_traces()\n stimulus_list = [s for s in si.SESSION_STIMULUS_MAP[metadata['session_type']]\n- if s is not 'spontaneous']\n+ if s != 'spontaneous']\n running_data, _ = dataset.get_running_speed()\n trial_table = dataset.get_stimulus_table('master')\n trial_table['start'] = timestamps[trial_table['start'].values]\ndiff --git a/src/pynwb/core.py b/src/pynwb/core.py\nindex 42b26207..b128fc46 100644\n--- a/src/pynwb/core.py\n+++ b/src/pynwb/core.py\n@@ -144,10 +144,10 @@ class NWBBaseType(with_metaclass(ExtenderMeta, Container)):\n raise TypeError(\"'__nwbfields__' must be of type tuple\")\n \n if len(bases) and 'NWBContainer' in globals() and issubclass(bases[-1], NWBContainer) \\\n- and bases[-1].__nwbfields__ is not cls.__nwbfields__:\n- new_nwbfields = list(cls.__nwbfields__)\n- new_nwbfields[0:0] = bases[-1].__nwbfields__\n- cls.__nwbfields__ = tuple(new_nwbfields)\n+ and bases[-1].__nwbfields__ is not cls.__nwbfields__:\n+ new_nwbfields = list(cls.__nwbfields__)\n+ new_nwbfields[0:0] = bases[-1].__nwbfields__\n+ cls.__nwbfields__ = tuple(new_nwbfields)\n new_nwbfields = list()\n docs = {dv['name']: dv['doc'] for dv in get_docval(cls.__init__)}\n for f in cls.__nwbfields__:\n@@ -912,10 +912,10 @@ class DynamicTable(NWBDataInterface):\n raise TypeError(msg)\n \n if len(bases) and 'DynamicTable' in globals() and issubclass(bases[-1], NWBContainer) \\\n- and bases[-1].__columns__ is not cls.__columns__:\n- new_columns = list(cls.__columns__)\n- new_columns[0:0] = bases[-1].__columns__\n- cls.__columns__ = tuple(new_columns)\n+ and bases[-1].__columns__ is not cls.__columns__:\n+ new_columns = list(cls.__columns__)\n+ new_columns[0:0] = bases[-1].__columns__\n+ cls.__columns__ = tuple(new_columns)\n \n @docval({'name': 'name', 'type': str, 'doc': 'the name of this table'}, # noqa: C901\n {'name': 'description', 'type': str, 'doc': 'a description of what is in this table'},\n@@ -1353,6 +1353,9 @@ class DynamicTableRegion(VectorData):\n arg1 = key[0]\n arg2 = key[1]\n return self.table[self.data[arg1], arg2]\n+ elif isinstance(key, slice):\n+ data = np.arange(*key.indices(len(self.table)))\n+ return DynamicTableRegion(name=self.name, data=data, description=self.description, table=self.table)\n else:\n if isinstance(key, int):\n return self.table[self.data[key]]\ndiff --git a/src/pynwb/form/query.py b/src/pynwb/form/query.py\nindex db6ffa7b..a309aece 100644\n--- a/src/pynwb/form/query.py\n+++ b/src/pynwb/form/query.py\n@@ -27,10 +27,10 @@ class Query(with_metaclass(ExtenderMeta, object)):\n raise TypeError(\"'__operations__' must be of type tuple\")\n # add any new operations\n if len(bases) and 'Query' in globals() and issubclass(bases[-1], Query) \\\n- and bases[-1].__operations__ is not cls.__operations__:\n- new_operations = list(cls.__operations__)\n- new_operations[0:0] = bases[-1].__operations__\n- cls.__operations__ = tuple(new_operations)\n+ and bases[-1].__operations__ is not cls.__operations__:\n+ new_operations = list(cls.__operations__)\n+ new_operations[0:0] = bases[-1].__operations__\n+ cls.__operations__ = tuple(new_operations)\n for op in cls.__operations__:\n if not hasattr(cls, op):\n setattr(cls, op, cls.__build_operation(op))\n@@ -117,10 +117,10 @@ class FORMDataset(with_metaclass(ExtenderMeta, object)):\n raise TypeError(\"'__operations__' must be of type tuple\")\n # add any new operations\n if len(bases) and 'Query' in globals() and issubclass(bases[-1], Query) \\\n- and bases[-1].__operations__ is not cls.__operations__:\n- new_operations = list(cls.__operations__)\n- new_operations[0:0] = bases[-1].__operations__\n- cls.__operations__ = tuple(new_operations)\n+ and bases[-1].__operations__ is not cls.__operations__:\n+ new_operations = list(cls.__operations__)\n+ new_operations[0:0] = bases[-1].__operations__\n+ cls.__operations__ = tuple(new_operations)\n for op in cls.__operations__:\n setattr(cls, op, cls.__build_operation(op))\n \ndiff --git a/src/pynwb/form/utils.py b/src/pynwb/form/utils.py\nindex f19b38e6..d1f9855f 100644\n--- a/src/pynwb/form/utils.py\n+++ b/src/pynwb/form/utils.py\n@@ -44,9 +44,9 @@ def __type_okay(value, argtype, allow_none=False):\n if isinstance(argtype, str):\n if argtype in __macros:\n return __type_okay(value, __macros[argtype], allow_none=allow_none)\n- elif argtype is 'int':\n+ elif argtype == 'int':\n return __is_int(value)\n- elif argtype is 'float':\n+ elif argtype == 'float':\n return __is_float(value)\n return argtype in [cls.__name__ for cls in value.__class__.__mro__]\n elif isinstance(argtype, type):\n", "test_patch": "diff --git a/tests/integration/ui_write/base.py b/tests/integration/ui_write/base.py\nindex 5d41145b..c0f88858 100644\n--- a/tests/integration/ui_write/base.py\n+++ b/tests/integration/ui_write/base.py\n@@ -102,8 +102,8 @@ class TestMapNWBContainer(unittest.TestCase):\n if len(f1) == 0:\n continue\n if isinstance(f1[0], float):\n- for v1, v2 in zip(f1, f2):\n- self.assertAlmostEqual(v1, v2, places=6)\n+ for v1, v2 in zip(f1, f2):\n+ self.assertAlmostEqual(v1, v2, places=6)\n else:\n self.assertTrue(np.array_equal(f1, f2))\n elif isinstance(f1, dict) and len(f1) and isinstance(next(iter(f1.values())), NWBContainer):\ndiff --git a/tests/integration/ui_write/test_core.py b/tests/integration/ui_write/test_core.py\nindex f1db241f..1cfe0d1a 100644\n--- a/tests/integration/ui_write/test_core.py\n+++ b/tests/integration/ui_write/test_core.py\n@@ -43,7 +43,7 @@ class TestUnits(base.TestMapRoundTrip):\n return nwbfile.units\n \n \n-class TestUnitsDf(base.TestMapRoundTrip):\n+class TestFromDataframe(base.TestMapRoundTrip):\n \n def setUpContainer(self):\n # this will get ignored\ndiff --git a/tests/integration/ui_write/test_misc.py b/tests/integration/ui_write/test_misc.py\nindex 50e24cb4..7f8cd5e0 100644\n--- a/tests/integration/ui_write/test_misc.py\n+++ b/tests/integration/ui_write/test_misc.py\n@@ -75,6 +75,37 @@ class TestUnitsIO(base.TestDataInterfaceIO):\n self.assertTrue(np.array_equal(ut['obs_intervals'][:], [[[0, 1], [2, 3]], [[2, 5], [6, 7]]]))\n \n \n+class TestUnitElectrodes(base.TestMapRoundTrip):\n+\n+ def setUpContainer(self):\n+ # this will get ignored\n+ return Units('placeholder_units')\n+\n+ def addContainer(self, nwbfile):\n+ device = nwbfile.create_device(name='trodes_rig123')\n+ electrode_name = 'tetrode1'\n+ description = \"an example tetrode\"\n+ location = \"somewhere in the hippocampus\"\n+ electrode_group = nwbfile.create_electrode_group(electrode_name,\n+ description=description,\n+ location=location,\n+ device=device)\n+ for idx in [1, 2, 3, 4]:\n+ nwbfile.add_electrode(idx,\n+ x=1.0, y=2.0, z=3.0,\n+ imp=float(-idx),\n+ location='CA1', filtering='none',\n+ group=electrode_group)\n+\n+ nwbfile.add_unit(id=1, electrodes=[1])\n+ nwbfile.add_unit(id=2, electrodes=[1])\n+ nwbfile.units.to_dataframe()\n+ self.container = nwbfile.units\n+\n+ def getContainer(self, nwbfile):\n+ return nwbfile.units\n+\n+\n class TestSpectralAnalysis(base.TestDataInterfaceIO):\n def setUpContainer(self):\n self.timeseries = TimeSeries(name='dummy timeseries', description='desc',\ndiff --git a/tests/integration/ui_write/test_nwbfile.py b/tests/integration/ui_write/test_nwbfile.py\nindex 2d2291bf..c669df66 100644\n--- a/tests/integration/ui_write/test_nwbfile.py\n+++ b/tests/integration/ui_write/test_nwbfile.py\n@@ -12,7 +12,6 @@ from pynwb import NWBFile, TimeSeries\n from pynwb.file import Subject\n from pynwb.ecephys import Clustering\n from pynwb.epoch import TimeIntervals\n-from pynwb.misc import Units\n \n from . import base\n \n@@ -270,33 +269,3 @@ class TestEpochsRoundtripDf(base.TestMapRoundTrip):\n \n def getContainer(self, nwbfile):\n return nwbfile.epochs\n-\n-\n-class TestUnitElectrodes(base.TestMapRoundTrip):\n-\n- def setUpContainer(self):\n- # this will get ignored\n- return Units('placeholder_units')\n-\n- def addContainer(self, nwbfile):\n- device = nwbfile.create_device(name='trodes_rig123')\n- electrode_name = 'tetrode1'\n- description = \"an example tetrode\"\n- location = \"somewhere in the hippocampus\"\n- electrode_group = nwbfile.create_electrode_group(electrode_name,\n- description=description,\n- location=location,\n- device=device)\n- for idx in [1, 2, 3, 4]:\n- nwbfile.add_electrode(idx,\n- x=1.0, y=2.0, z=3.0,\n- imp=float(-idx),\n- location='CA1', filtering='none',\n- group=electrode_group)\n-\n- nwbfile.add_unit(id=1, electrodes=[1])\n- nwbfile.add_unit(id=2, electrodes=[1])\n- self.container = nwbfile.units\n-\n- def getContainer(self, nwbfile):\n- return nwbfile.units\ndiff --git a/tests/unit/pynwb_tests/test_core.py b/tests/unit/pynwb_tests/test_core.py\nindex 700c074c..c8a6df7f 100644\n--- a/tests/unit/pynwb_tests/test_core.py\n+++ b/tests/unit/pynwb_tests/test_core.py\n@@ -1,11 +1,10 @@\n-import unittest2 as unittest\n-\n-from pynwb.core import DynamicTable, VectorData, ElementIdentifiers, NWBTable\n-from pynwb import NWBFile, TimeSeries, available_namespaces\n+from datetime import datetime\n \n import pandas as pd\n-from datetime import datetime\n+import unittest2 as unittest\n from dateutil.tz import tzlocal\n+from pynwb import NWBFile, TimeSeries, available_namespaces\n+from pynwb.core import DynamicTable, VectorData, ElementIdentifiers, NWBTable, DynamicTableRegion\n \n \n class TestDynamicTable(unittest.TestCase):\n@@ -14,7 +13,7 @@ class TestDynamicTable(unittest.TestCase):\n self.spec = [\n {'name': 'foo', 'description': 'foo column'},\n {'name': 'bar', 'description': 'bar column'},\n- {'name': 'baz', 'description': 'baz column'}\n+ {'name': 'baz', 'description': 'baz column'},\n ]\n self.data = [\n [1, 2, 3, 4, 5],\n@@ -202,6 +201,12 @@ class TestDynamicTable(unittest.TestCase):\n with self.assertRaises(ValueError):\n table.add_row({'bar': 60.0, 'foo': 6, 'baz': 'oryx', 'qax': -1}, None)\n \n+ def test_indexed_dynamic_table_region(self):\n+ table = self.with_columns_and_data()\n+\n+ dynamic_table_region = DynamicTableRegion('dtr', [0, 1], 'desc', table=table)\n+ assert dynamic_table_region[slice(0, 1)]\n+\n \n class TestNWBTable(unittest.TestCase):\n \n@@ -213,7 +218,8 @@ class TestNWBTable(unittest.TestCase):\n ]\n self.cls = MyTable\n \n- def basic_data(self):\n+ @staticmethod\n+ def basic_data():\n return [\n [1, 'a'],\n [2, 'b'],\ndiff --git a/tests/unit/pynwb_tests/test_file.py b/tests/unit/pynwb_tests/test_file.py\nindex b44638e3..16ce6314 100644\n--- a/tests/unit/pynwb_tests/test_file.py\n+++ b/tests/unit/pynwb_tests/test_file.py\n@@ -180,6 +180,8 @@ class NWBFileTest(unittest.TestCase):\n table.add_row(x=1.0, y=2.0, z=3.0, imp=-4.0, location='CA1', filtering='none', group=group,\n group_name='tetrode1')\n self.nwbfile.set_electrode_table(table)\n+\n+ self.assertIs(self.nwbfile.ec_electrodes, self.nwbfile.electrodes)\n self.assertIs(self.nwbfile.electrodes, table)\n self.assertIs(table.parent, self.nwbfile)\n \n@@ -228,14 +230,14 @@ class NWBFileTest(unittest.TestCase):\n 'tetrode description', 'tetrode location', dev1)\n self.nwbfile.add_electrode(1.0, 2.0, 3.0, -1.0, 'CA1',\n 'none', group=group, id=1)\n- self.assertEqual(self.nwbfile.ec_electrodes[0][0], 1)\n- self.assertEqual(self.nwbfile.ec_electrodes[0][1], 1.0)\n- self.assertEqual(self.nwbfile.ec_electrodes[0][2], 2.0)\n- self.assertEqual(self.nwbfile.ec_electrodes[0][3], 3.0)\n- self.assertEqual(self.nwbfile.ec_electrodes[0][4], -1.0)\n- self.assertEqual(self.nwbfile.ec_electrodes[0][5], 'CA1')\n- self.assertEqual(self.nwbfile.ec_electrodes[0][6], 'none')\n- self.assertEqual(self.nwbfile.ec_electrodes[0][7], group)\n+ self.assertEqual(self.nwbfile.electrodes[0][0], 1)\n+ self.assertEqual(self.nwbfile.electrodes[0][1], 1.0)\n+ self.assertEqual(self.nwbfile.electrodes[0][2], 2.0)\n+ self.assertEqual(self.nwbfile.electrodes[0][3], 3.0)\n+ self.assertEqual(self.nwbfile.electrodes[0][4], -1.0)\n+ self.assertEqual(self.nwbfile.electrodes[0][5], 'CA1')\n+ self.assertEqual(self.nwbfile.electrodes[0][6], 'none')\n+ self.assertEqual(self.nwbfile.electrodes[0][7], group)\n \n def test_all_children(self):\n ts1 = TimeSeries('test_ts1', [0, 1, 2, 3, 4, 5],\ndiff --git a/tests/unit/pynwb_tests/test_icephys.py b/tests/unit/pynwb_tests/test_icephys.py\nindex 6e7d71c5..b2e305a7 100644\n--- a/tests/unit/pynwb_tests/test_icephys.py\n+++ b/tests/unit/pynwb_tests/test_icephys.py\n@@ -8,17 +8,17 @@ from pynwb.device import Device\n \n \n def GetElectrode():\n- device = Device(name='device_name')\n- elec = IntracellularElectrode('test_iS',\n- device,\n- 'slice',\n- 'seal',\n- 'description',\n- 'location',\n- 'resistance',\n- 'filtering',\n- 'initial_access_resistance')\n- return elec\n+ device = Device(name='device_name')\n+ elec = IntracellularElectrode('test_iS',\n+ device,\n+ 'slice',\n+ 'seal',\n+ 'description',\n+ 'location',\n+ 'resistance',\n+ 'filtering',\n+ 'initial_access_resistance')\n+ return elec\n \n \n class IntracellularElectrodeConstructor(unittest.TestCase):\n", "FAIL_TO_PASS": ["tests/integration/ui_write/test_misc.py::TestUnitElectrodes::test_roundtrip", "tests/unit/pynwb_tests/test_core.py::TestDynamicTable::test_indexed_dynamic_table_region"]}], "all_FAIL_TO_PASS": ["tests/integration/ui_write/test_misc.py::TestUnitElectrodes::test_roundtrip", "tests/unit/pynwb_tests/test_core.py::TestDynamicTable::test_indexed_dynamic_table_region"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "d0c-s4vage__pfp-123_x1", "level": 1, "source": "swerebenchv2", "repo": "d0c-s4vage/pfp", "image": "swerebenchv2/d0c-s4vage-pfp:123-5b90492", "base_commit": "5b90492789accefd24e82cd0798673feece1e33c", "num_bugs": 1, "bugs": [{"instance_id": "d0c-s4vage__pfp-123", "base_commit": "5b90492789accefd24e82cd0798673feece1e33c", "gold_patch": "diff --git a/pfp/fields.py b/pfp/fields.py\nindex 78dd419..537439d 100644\n--- a/pfp/fields.py\n+++ b/pfp/fields.py\n@@ -1029,6 +1029,11 @@ class Struct(Field):\n )\n res.append(\"{}}}\".format(\" \" * level))\n return \"\\n\".join(res)\n+ \n+ def __iter__(self):\n+ \"\"\"Iterate over this struct's children\n+ \"\"\"\n+ return self._pfp__children.__iter__()\n \n \n @inherit_hash\n@@ -2324,6 +2329,11 @@ class Array(Field):\n else:\n return len(self.items)\n \n+ def __iter__(self):\n+ \"\"\"Iterate over all items in this array\n+ \"\"\"\n+ return self.items.__iter__()\n+\n \n # http://www.sweetscape.com/010editor/manual/ArraysStrings.htm\n @inherit_hash\n", "test_patch": "diff --git a/tests/test_arrays.py b/tests/test_arrays.py\nindex f98a224..3da3263 100644\n--- a/tests/test_arrays.py\n+++ b/tests/test_arrays.py\n@@ -292,6 +292,32 @@ class TestArrays(utils.PfpTestCase):\n struct.array = [0xFFFF]\n self.assertEqual(struct.array[0], 0xFFFF)\n \n+ def test_array_iter(self):\n+ \"\"\"Test array item iteration.\n+ \"\"\"\n+ dom = self._test_parse_build(\n+ \"ABCDEFGHI\",\n+ \"\"\"\n+ typedef struct {\n+ char first;\n+ char second;\n+ char third;\n+ } three_bytes;\n+\n+ three_bytes three_three_bytes[3];\n+ \"\"\",\n+ )\n+ items = [x for x in dom.three_three_bytes]\n+ self.assertEqual(items[0].first, 0x41)\n+ self.assertEqual(items[0].second, 0x42)\n+ self.assertEqual(items[0].third, 0x43)\n+ self.assertEqual(items[1].first, 0x44)\n+ self.assertEqual(items[1].second, 0x45)\n+ self.assertEqual(items[1].third, 0x46)\n+ self.assertEqual(items[2].first, 0x47)\n+ self.assertEqual(items[2].second, 0x48)\n+ self.assertEqual(items[2].third, 0x49)\n+\n \n if __name__ == \"__main__\":\n unittest.main()\ndiff --git a/tests/test_struct_union.py b/tests/test_struct_union.py\nindex d0197e6..b65265b 100644\n--- a/tests/test_struct_union.py\n+++ b/tests/test_struct_union.py\n@@ -443,6 +443,26 @@ class TestStructUnion(utils.PfpTestCase):\n stdout=\"3\",\n )\n \n+ def test_struct_iter(self):\n+ \"\"\"Test struct children iteration.\n+ \"\"\"\n+ dom = self._test_parse_build(\n+ \"ABC\",\n+ \"\"\"\n+ typedef struct {\n+ char first;\n+ char second;\n+ char third;\n+ } three_bytes;\n+\n+ three_bytes bytes;\n+ \"\"\",\n+ )\n+ chars = [x for x in dom.bytes]\n+ self.assertEquals(chars[0], 0x41)\n+ self.assertEquals(chars[1], 0x42)\n+ self.assertEquals(chars[2], 0x43)\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_struct_union.py::TestStructUnion::test_struct_iter", "tests/test_struct_union.py::TestStructUnion::test_struct_iter_with_string_data"]}], "all_FAIL_TO_PASS": ["tests/test_struct_union.py::TestStructUnion::test_struct_iter", "tests/test_struct_union.py::TestStructUnion::test_struct_iter_with_string_data"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pypa__pipx-1267_x1", "level": 1, "source": "swerebenchv2", "repo": "pypa/pipx", "image": "swerebenchv2/pypa-pipx:1267-6eb7773", "base_commit": "6eb777318996e3ec1b3a9ac5da427feae37cdf76", "num_bugs": 1, "bugs": [{"instance_id": "pypa__pipx-1267", "base_commit": "6eb777318996e3ec1b3a9ac5da427feae37cdf76", "gold_patch": "diff --git a/changelog.d/1262.feature.md b/changelog.d/1262.feature.md\nnew file mode 100644\nindex 0000000..1452b72\n--- /dev/null\n+++ b/changelog.d/1262.feature.md\n@@ -0,0 +1,3 @@\n+Add `--install` option to `pipx upgrade` command.\n+\n+This will install the package given as argument if it is not already installed.\ndiff --git a/src/pipx/commands/upgrade.py b/src/pipx/commands/upgrade.py\nindex 1530a30..5cc23f1 100644\n--- a/src/pipx/commands/upgrade.py\n+++ b/src/pipx/commands/upgrade.py\n@@ -1,8 +1,9 @@\n import logging\n+import os\n from pathlib import Path\n-from typing import List, Sequence\n+from typing import List, Optional, Sequence\n \n-from pipx import constants\n+from pipx import commands, constants\n from pipx.colors import bold, red\n from pipx.commands.common import expose_resources_globally\n from pipx.constants import EXIT_CODE_OK, ExitCode\n@@ -101,15 +102,38 @@ def _upgrade_venv(\n include_injected: bool,\n upgrading_all: bool,\n force: bool,\n+ install: bool = False,\n+ python: Optional[str] = None,\n ) -> int:\n- \"\"\"Returns number of packages with changed versions.\"\"\"\n+ \"\"\"Return number of packages with changed versions.\"\"\"\n if not venv_dir.is_dir():\n- raise PipxError(\n- f\"\"\"\n- Package is not installed. Expected to find {str(venv_dir)}, but it\n- does not exist.\n- \"\"\"\n- )\n+ if install:\n+ commands.install(\n+ venv_dir=None,\n+ venv_args=[],\n+ package_names=None,\n+ package_specs=[str(venv_dir).split(os.path.sep)[-1]],\n+ local_bin_dir=constants.LOCAL_BIN_DIR,\n+ local_man_dir=constants.LOCAL_MAN_DIR,\n+ python=python,\n+ pip_args=pip_args,\n+ verbose=verbose,\n+ force=force,\n+ reinstall=False,\n+ include_dependencies=False,\n+ preinstall_packages=None,\n+ )\n+ return 0\n+ else:\n+ raise PipxError(\n+ f\"\"\"\n+ Package is not installed. Expected to find {str(venv_dir)}, but it\n+ does not exist.\n+ \"\"\"\n+ )\n+\n+ if python and not install:\n+ logger.info(\"Ignoring --python as not combined with --install\")\n \n venv = Venv(venv_dir, verbose=verbose)\n \n@@ -154,13 +178,15 @@ def _upgrade_venv(\n \n def upgrade(\n venv_dir: Path,\n+ python: Optional[str],\n pip_args: List[str],\n verbose: bool,\n *,\n include_injected: bool,\n force: bool,\n+ install: bool,\n ) -> ExitCode:\n- \"\"\"Returns pipx exit code.\"\"\"\n+ \"\"\"Return pipx exit code.\"\"\"\n \n _ = _upgrade_venv(\n venv_dir,\n@@ -169,6 +195,8 @@ def upgrade(\n include_injected=include_injected,\n upgrading_all=False,\n force=force,\n+ install=install,\n+ python=python,\n )\n \n # Any error in upgrade will raise PipxError (e.g. from venv.upgrade_package())\n@@ -194,7 +222,7 @@ def upgrade_all(\n venvs_upgraded += _upgrade_venv(\n venv_dir,\n venv.pipx_metadata.main_package.pip_args,\n- verbose,\n+ verbose=verbose,\n include_injected=include_injected,\n upgrading_all=True,\n force=force,\ndiff --git a/src/pipx/main.py b/src/pipx/main.py\nindex b8a13f9..f3f4859 100644\n--- a/src/pipx/main.py\n+++ b/src/pipx/main.py\n@@ -268,10 +268,12 @@ def run_pipx_command(args: argparse.Namespace, subparsers: Dict[str, argparse.Ar\n elif args.command == \"upgrade\":\n return commands.upgrade(\n venv_dir,\n+ args.python,\n pip_args,\n verbose,\n include_injected=args.include_injected,\n force=args.force,\n+ install=args.install,\n )\n elif args.command == \"upgrade-all\":\n return commands.upgrade_all(\n@@ -497,6 +499,12 @@ def _add_upgrade(subparsers, venv_completer: VenvCompleter, shared_parser: argpa\n help=\"Modify existing virtual environment and files in PIPX_BIN_DIR and PIPX_MAN_DIR\",\n )\n add_pip_venv_args(p)\n+ p.add_argument(\n+ \"--install\",\n+ action=\"store_true\",\n+ help=\"Install package spec if missing\",\n+ )\n+ add_python_options(p)\n \n \n def _add_upgrade_all(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:\n", "test_patch": "diff --git a/tests/test_upgrade.py b/tests/test_upgrade.py\nindex 816b7c4..c89629d 100644\n--- a/tests/test_upgrade.py\n+++ b/tests/test_upgrade.py\n@@ -73,3 +73,9 @@ def test_upgrade_no_include_injected(pipx_temp_env, capsys):\n captured = capsys.readouterr()\n assert \"upgraded package pylint\" in captured.out\n assert \"upgraded package black\" not in captured.out\n+\n+\n+def test_upgrade_install_missing(pipx_temp_env, capsys):\n+ assert not run_pipx_cli([\"upgrade\", \"pycowsay\", \"--install\"])\n+ captured = capsys.readouterr()\n+ assert \"installed package pycowsay\" in captured.out\n", "FAIL_TO_PASS": ["tests/test_upgrade.py::test_upgrade_install_missing"]}], "all_FAIL_TO_PASS": ["tests/test_upgrade.py::test_upgrade_install_missing"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pypa__pipx-1284_x1", "level": 1, "source": "swerebenchv2", "repo": "pypa/pipx", "image": "swerebenchv2/pypa-pipx:1284-f3b4abc", "base_commit": "f3b4abc1087b63724369fbcf5baa5220fdb60900", "num_bugs": 1, "bugs": [{"instance_id": "pypa__pipx-1284", "base_commit": "f3b4abc1087b63724369fbcf5baa5220fdb60900", "gold_patch": "diff --git a/changelog.d/1283.bugfix.md b/changelog.d/1283.bugfix.md\nnew file mode 100644\nindex 0000000..482f8af\n--- /dev/null\n+++ b/changelog.d/1283.bugfix.md\n@@ -0,0 +1,1 @@\n+Fix crashes due to superfluous `-q ` flags by discarding exceeding values\ndiff --git a/src/pipx/main.py b/src/pipx/main.py\nindex f3f4859..9e43784 100644\n--- a/src/pipx/main.py\n+++ b/src/pipx/main.py\n@@ -758,11 +758,20 @@ def get_command_parser() -> Tuple[argparse.ArgumentParser, Dict[str, argparse.Ar\n default=0,\n help=(\n \"Give less output. May be used multiple times corresponding to the\"\n- \" WARNING, ERROR, and CRITICAL logging levels.\"\n+ \" ERROR and CRITICAL logging levels. The count maxes out at 2.\"\n ),\n )\n \n- shared_parser.add_argument(\"--verbose\", \"-v\", action=\"count\", default=0, help=(\"Give more output.\"))\n+ shared_parser.add_argument(\n+ \"--verbose\",\n+ \"-v\",\n+ action=\"count\",\n+ default=0,\n+ help=(\n+ \"Give more output. May be used multiple times corresponding to the\"\n+ \" INFO, DEBUG and NOTSET logging levels. The count maxes out at 3.\"\n+ ),\n+ )\n \n parser = argparse.ArgumentParser(\n prog=prog_name(),\n@@ -843,8 +852,8 @@ def setup_logging(verbose: int) -> None:\n pipx_str = bold(green(\"pipx >\")) if sys.stdout.isatty() else \"pipx >\"\n pipx.constants.pipx_log_file = setup_log_file()\n \n- # Determine logging level\n- level_number = max(0, logging.WARNING - 10 * verbose)\n+ # Determine logging level, a value between 0 and 50\n+ level_number = min(max(0, logging.WARNING - 10 * verbose), 50)\n \n level = logging.getLevelName(level_number)\n \n", "test_patch": "diff --git a/tests/test_main.py b/tests/test_main.py\nindex 3a8bd53..a8e2a43 100644\n--- a/tests/test_main.py\n+++ b/tests/test_main.py\n@@ -35,3 +35,8 @@ def test_prog_name(monkeypatch, argv, executable, expected):\n monkeypatch.setattr(\"pipx.main.sys.argv\", [argv])\n monkeypatch.setattr(\"pipx.main.sys.executable\", executable)\n assert main.prog_name() == expected\n+\n+\n+def test_limit_verbosity():\n+ assert not run_pipx_cli([\"list\", \"-qqq\"])\n+ assert not run_pipx_cli([\"list\", \"-vvvv\"])\n", "FAIL_TO_PASS": ["tests/test_main.py::test_limit_verbosity"]}], "all_FAIL_TO_PASS": ["tests/test_main.py::test_limit_verbosity"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "takluyver__flit-169_x1", "level": 1, "source": "swerebenchv2", "repo": "takluyver/flit", "image": "swerebenchv2/takluyver-flit:169-08dcf99", "base_commit": "08dcf993229894901e33b88ab9b8c0cf19c88415", "num_bugs": 1, "bugs": [{"instance_id": "takluyver__flit-169", "base_commit": "08dcf993229894901e33b88ab9b8c0cf19c88415", "gold_patch": "diff --git a/.gitignore b/.gitignore\nindex c2acbe3..d64b220 100644\n--- a/.gitignore\n+++ b/.gitignore\n@@ -6,3 +6,4 @@ __pycache__/\n /tests/samples/dist/\n /htmlcov/\n /.coverage\n+/.pytest_cache\ndiff --git a/.travis.yml b/.travis.yml\nindex 8afc588..b43c127 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -4,6 +4,7 @@ python:\n - \"3.5\"\n - \"3.4\"\n install:\n+ - pip install --upgrade pytest\n - pip install -r requirements-test.txt\n - pip install codecov\n script: py.test --cov=flit\ndiff --git a/doc/history.rst b/doc/history.rst\nindex 4effcd6..a9375e7 100644\n--- a/doc/history.rst\n+++ b/doc/history.rst\n@@ -4,6 +4,10 @@ Release history\n Version 0.14\n ------------\n \n+- The description file may now be written in reStructuredText, Markdown or\n+ plain text. The file extension should indicate which of these formats it is\n+ (``.rst``, ``.md`` or ``.txt``). Previously, only reStructuredText was\n+ officially supported.\n - Multiple links (e.g. documentation, bug tracker) can now be specified in a\n new :ref:`[tool.flit.metadata.urls] section ` of\n ``pyproject.toml``.\ndiff --git a/doc/pyproject_toml.rst b/doc/pyproject_toml.rst\nindex 09dfcf4..8e7a826 100644\n--- a/doc/pyproject_toml.rst\n+++ b/doc/pyproject_toml.rst\n@@ -71,11 +71,11 @@ dev-requires\n These are not (yet) encoded in the wheel, but are used when doing\n ``flit install``.\n description-file\n- A path (relative to the .ini file) to a file containing a longer description\n+ A path (relative to the .toml file) to a file containing a longer description\n of your package to show on PyPI. This should be written in `reStructuredText\n- `_, if your long\n- description is not valid reStructuredText, a warning will be printed,\n- and it will be interpreted as plain text on PyPI.\n+ `_, Markdown or\n+ plain text, and the filename should have the appropriate extension\n+ (``.rst``, ``.md`` or ``.txt``).\n classifiers\n A list of `Trove classifiers `_.\n requires-python\ndiff --git a/flit/common.py b/flit/common.py\nindex ad79813..b73ebc9 100644\n--- a/flit/common.py\n+++ b/flit/common.py\n@@ -212,6 +212,7 @@ class Metadata:\n keywords = None\n download_url = None\n requires_python = None\n+ description_content_type = None\n \n platform = ()\n supported_platform = ()\n@@ -224,8 +225,9 @@ class Metadata:\n requires_dist = ()\n obsoletes_dist = ()\n requires_external = ()\n+ provides_extra = ()\n \n- metadata_version=\"1.2\"\n+ metadata_version=\"2.1\"\n \n # this is part of metadata spec 2, we are using it for installation but it\n # doesn't actually get written to the metadata file\n@@ -244,7 +246,7 @@ class Metadata:\n return n.lower().replace('-', '_')\n \n def write_metadata_file(self, fp):\n- \"\"\"Write out metadata in the 1.x format (email like)\"\"\"\n+ \"\"\"Write out metadata in the email headers format\"\"\"\n fields = [\n 'Metadata-Version',\n 'Name',\n@@ -260,6 +262,7 @@ class Metadata:\n 'Maintainer',\n 'Maintainer-email',\n 'Requires-Python',\n+ 'Description-Content-Type',\n ]\n \n for field in fields:\n@@ -280,6 +283,9 @@ class Metadata:\n for url in self.project_urls:\n fp.write('Project-URL: {}\\n'.format(url))\n \n+ for extra in self.provides_extra:\n+ fp.write('Provides-Extra: {}\\n'.format(extra))\n+\n if self.description is not None:\n fp.write('\\n' + self.description + '\\n')\n \ndiff --git a/flit/inifile.py b/flit/inifile.py\nindex 234683f..2af1ae2 100644\n--- a/flit/inifile.py\n+++ b/flit/inifile.py\n@@ -157,6 +157,12 @@ def _read_pkg_ini(path):\n \n return cp\n \n+readme_ext_to_content_type = {\n+ '.rst': 'text/x-rst',\n+ '.md': 'text/markdown',\n+ '.txt': 'text/plain',\n+}\n+\n def _prep_metadata(md_sect, path):\n \"\"\"Process & verify the metadata from a config file\n \n@@ -180,23 +186,26 @@ def _prep_metadata(md_sect, path):\n description_file = path.parent / md_sect.get('description-file')\n with description_file.open(encoding='utf-8') as f:\n raw_desc = f.read()\n- if description_file.suffix == '.md':\n- try:\n- import pypandoc\n- log.debug('will convert %s to rst', description_file)\n- raw_desc = pypandoc.convert(raw_desc, 'rst', format='markdown')\n- except Exception:\n- log.warning('Unable to convert markdown to rst. Please install '\n- '`pypandoc` and `pandoc` to use markdown long description.')\n-\n- # rst check\n- stream = io.StringIO()\n- res = render(raw_desc, stream)\n- if not res:\n- log.warning(\"The file description seems not to be valid rst for PyPI;\"\n- \" it will be interpreted as plain text\")\n- log.warning(stream.getvalue())\n+ ext = description_file.suffix\n+ try:\n+ mimetype = readme_ext_to_content_type[ext]\n+ except KeyError:\n+ log.warning(\"Unknown extension %r for description file.\", ext)\n+ log.warning(\" Recognised extensions: %s\",\n+ \" \".join(readme_ext_to_content_type))\n+ mimetype = None\n+\n+ if mimetype == 'text/x-rst':\n+ # rst check\n+ stream = io.StringIO()\n+ res = render(raw_desc, stream)\n+ if not res:\n+ log.warning(\"The file description seems not to be valid rst for PyPI;\"\n+ \" it will be interpreted as plain text\")\n+ log.warning(stream.getvalue())\n+\n md_dict['description'] = raw_desc\n+ md_dict['description_content_type'] = mimetype\n \n if 'urls' in md_sect:\n project_urls = md_dict['project_urls'] = []\n", "test_patch": "diff --git a/tests/samples/bad-description-ext.toml b/tests/samples/bad-description-ext.toml\nnew file mode 100644\nindex 0000000..1062829\n--- /dev/null\n+++ b/tests/samples/bad-description-ext.toml\n@@ -0,0 +1,9 @@\n+[build-system]\n+requires = [\"flit\"]\n+\n+[tool.flit.metadata]\n+module = \"module1\"\n+author = \"Sir Robin\"\n+author-email = \"robin@camelot.uk\"\n+home-page = \"http://github.com/sirrobin/module1\"\n+description-file = \"module1.py\" # WRONG\ndiff --git a/tests/test_inifile.py b/tests/test_inifile.py\nindex d506651..c7d3e5f 100644\n--- a/tests/test_inifile.py\n+++ b/tests/test_inifile.py\n@@ -1,3 +1,4 @@\n+import logging\n import pathlib\n \n import pytest\n@@ -48,4 +49,10 @@ def test_description_file():\n info = read_pkg_ini(samples_dir / 'package1-pkg.ini')\n assert info['metadata']['description'] == \\\n \"Sample description for test.\\n\"\n+ assert info['metadata']['description_content_type'] == 'text/x-rst'\n \n+def test_bad_description_extension(caplog):\n+ info = read_pkg_ini(samples_dir / 'bad-description-ext.toml')\n+ assert info['metadata']['description_content_type'] is None\n+ assert any((r.levelno == logging.WARN and \"Unknown extension\" in r.msg)\n+ for r in caplog.records)\n", "FAIL_TO_PASS": ["tests/test_inifile.py::test_description_file", "tests/test_inifile.py::test_bad_description_extension"]}], "all_FAIL_TO_PASS": ["tests/test_inifile.py::test_description_file", "tests/test_inifile.py::test_bad_description_extension"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pybamm-team__pybamm-1020_x1", "level": 1, "source": "swerebenchv2", "repo": "pybamm-team/PyBaMM", "image": "swerebenchv2/pybamm-team-pybamm:1020-1007c87", "base_commit": "1007c87379a6364384d30db315d4a99bc30a7173", "num_bugs": 1, "bugs": [{"instance_id": "pybamm-team__pybamm-1020", "base_commit": "1007c87379a6364384d30db315d4a99bc30a7173", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 7a68ee6a5..59560dc9d 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -2,6 +2,7 @@\n \n ## Features\n \n+- Allowed `ProcessedVariable` to handle cases where `len(solution.t)=1` ([#1020](https://github.com/pybamm-team/PyBaMM/pull/1020))\n - Added `BackwardIndefiniteIntegral` symbol ([#1014](https://github.com/pybamm-team/PyBaMM/pull/1014))\n - Added `plot` and `plot2D` to enable easy plotting of `pybamm.Array` objects ([#1008](https://github.com/pybamm-team/PyBaMM/pull/1008))\n - Updated effective current collector models and added example notebook ([#1007](https://github.com/pybamm-team/PyBaMM/pull/1007))\n@@ -41,6 +42,7 @@\n \n ## Breaking changes\n \n+- For variables discretised using finite elements the result returned by calling `ProcessedVariable` is now transposed ([#1020](https://github.com/pybamm-team/PyBaMM/pull/1020))\n - Renamed \"surface area density\" to \"surface area to volume ratio\" ([#975](https://github.com/pybamm-team/PyBaMM/pull/975))\n - Replaced \"reaction rate\" with \"exchange-current density\" ([#975](https://github.com/pybamm-team/PyBaMM/pull/975))\n - Changed the implementation of reactions in submodels ([#948](https://github.com/pybamm-team/PyBaMM/pull/948))\ndiff --git a/pybamm/solvers/base_solver.py b/pybamm/solvers/base_solver.py\nindex ad34a98ff..4b4286b4b 100644\n--- a/pybamm/solvers/base_solver.py\n+++ b/pybamm/solvers/base_solver.py\n@@ -616,6 +616,15 @@ class BaseSolver(object):\n timer.format(solution.total_time),\n )\n )\n+\n+ # Raise error if solution only contains one timestep (except for algebraic\n+ # solvers, where we may only expect one time in the solution)\n+ if self.algebraic_solver is False and len(solution.t) == 1:\n+ raise pybamm.SolverError(\n+ \"Solution time vector has length 1. \"\n+ \"Check whether simulation terminated too early.\"\n+ )\n+\n return solution\n \n def step(\ndiff --git a/pybamm/solvers/processed_variable.py b/pybamm/solvers/processed_variable.py\nindex 9133a6e3d..f324b0068 100644\n--- a/pybamm/solvers/processed_variable.py\n+++ b/pybamm/solvers/processed_variable.py\n@@ -7,6 +7,26 @@ import pybamm\n import scipy.interpolate as interp\n \n \n+def make_interp2D_fun(input, interpolant):\n+ \"\"\"\n+ Calls and returns a 2D interpolant of the correct shape depending on the\n+ shape of the input\n+ \"\"\"\n+ first_dim, second_dim, _ = input\n+ if isinstance(first_dim, np.ndarray) and isinstance(second_dim, np.ndarray):\n+ first_dim = first_dim[:, 0, 0]\n+ second_dim = second_dim[:, 0]\n+ return interpolant(second_dim, first_dim)\n+ elif isinstance(first_dim, np.ndarray):\n+ first_dim = first_dim[:, 0]\n+ return interpolant(second_dim, first_dim)[:, 0]\n+ elif isinstance(second_dim, np.ndarray):\n+ second_dim = second_dim[:, 0]\n+ return interpolant(second_dim, first_dim)\n+ else:\n+ return interpolant(second_dim, first_dim)[0]\n+\n+\n class ProcessedVariable(object):\n \"\"\"\n An object that can be evaluated at arbitrary (scalars or vectors) t and x, and\n@@ -55,48 +75,11 @@ class ProcessedVariable(object):\n and \"current collector\" in self.domain\n and isinstance(self.mesh[0], pybamm.ScikitSubMesh2D)\n ):\n- if len(solution.t) == 1:\n- # space only (steady solution)\n- self.initialise_2D_fixed_t_scikit_fem()\n- else:\n- self.initialise_2D_scikit_fem()\n+ self.initialise_2D_scikit_fem()\n \n # check variable shape\n else:\n- if len(solution.t) == 1:\n- # Implementing a workaround for 0D and 1D variables. Processing\n- # variables that are functions of space only needs to be implemented\n- # properly, see #1006\n- if (\n- isinstance(self.base_eval, numbers.Number)\n- or len(self.base_eval.shape) == 0\n- or self.base_eval.shape[0] == 1\n- ):\n- # Scalar value\n- t = self.t_sol\n- u = self.u_sol\n- inputs = {name: inp[0] for name, inp in self.inputs.items()}\n-\n- entries = self.base_variable.evaluate(t, u, inputs=inputs)\n-\n- def fun(t):\n- return entries\n-\n- self._interpolation_function = fun\n- self.entries = entries\n- self.dimensions = 0\n- else:\n- # 1D function of space only\n- n = self.mesh[0].npts\n- base_shape = self.base_eval.shape[0]\n- if base_shape in [n, n + 1]:\n- self.initialise_1D(fixed_t=True)\n- else:\n- raise pybamm.SolverError(\n- \"Solution time vector must have length > 1. Check whether \"\n- \"simulation terminated too early.\"\n- )\n- elif (\n+ if (\n isinstance(self.base_eval, numbers.Number)\n or len(self.base_eval.shape) == 0\n or self.base_eval.shape[0] == 1\n@@ -141,9 +124,21 @@ class ProcessedVariable(object):\n entries[idx] = self.base_variable.evaluate(t, u, inputs=inputs)\n \n # No discretisation provided, or variable has no domain (function of t only)\n- self._interpolation_function = interp.interp1d(\n- self.t_sol, entries, kind=\"linear\", fill_value=np.nan, bounds_error=False\n- )\n+ if len(self.t_sol) == 1:\n+ # Variable is just a scalar value, but we need to create a callable\n+ # function to be consitent with other processed variables\n+ def fun(t):\n+ return entries\n+\n+ self._interpolation_function = fun\n+ else:\n+ self._interpolation_function = interp.interp1d(\n+ self.t_sol,\n+ entries,\n+ kind=\"linear\",\n+ fill_value=np.nan,\n+ bounds_error=False,\n+ )\n \n self.entries = entries\n self.dimensions = 0\n@@ -208,19 +203,22 @@ class ProcessedVariable(object):\n self.internal_boundaries = self.mesh[0].internal_boundaries\n \n # set up interpolation\n- # note that the order of 't' and 'space' is the reverse of what you'd expect\n- # TODO: fix processing when variable is a function of space only\n- if fixed_t:\n- # Hack for 1D space only\n+ if len(self.t_sol) == 1:\n+ # function of space only\n interpolant = interp.interp1d(\n space, entries_for_interp[:, 0], kind=\"linear\", fill_value=np.nan\n )\n \n def interp_fun(t, z):\n- return interpolant(z)[:, np.newaxis]\n+ if isinstance(z, np.ndarray):\n+ return interpolant(z)[:, np.newaxis]\n+ else:\n+ return interpolant(z)\n \n self._interpolation_function = interp_fun\n else:\n+ # function of space and time. Note that the order of 't' and 'space'\n+ # is the reverse of what you'd expect\n self._interpolation_function = interp.interp2d(\n self.t_sol, space, entries_for_interp, kind=\"linear\", fill_value=np.nan\n )\n@@ -297,40 +295,29 @@ class ProcessedVariable(object):\n self.second_dim_pts = second_dim_pts\n \n # set up interpolation\n- self._interpolation_function = interp.RegularGridInterpolator(\n- (first_dim_pts, second_dim_pts, self.t_sol),\n- entries,\n- method=\"linear\",\n- fill_value=np.nan,\n- )\n-\n- def initialise_2D_fixed_t_scikit_fem(self):\n- y_sol = self.mesh[0].edges[\"y\"]\n- len_y = len(y_sol)\n- z_sol = self.mesh[0].edges[\"z\"]\n- len_z = len(z_sol)\n-\n- # Evaluate the base_variable\n- inputs = {name: inp[0] for name, inp in self.inputs.items()}\n+ if len(self.t_sol) == 1:\n+ # function of space only. Note the order of the points is the reverse\n+ # of what you'd expect\n+ interpolant = interp.interp2d(\n+ second_dim_pts,\n+ first_dim_pts,\n+ entries[:, :, 0],\n+ kind=\"linear\",\n+ fill_value=np.nan,\n+ )\n \n- entries = np.reshape(\n- self.base_variable.evaluate(0, self.u_sol, inputs=inputs), [len_y, len_z]\n- )\n+ def interp_fun(input):\n+ return make_interp2D_fun(input, interpolant)\n \n- # assign attributes for reference\n- self.entries = entries\n- self.dimensions = 2\n- self.y_sol = y_sol\n- self.z_sol = z_sol\n- self.first_dimension = \"y\"\n- self.second_dimension = \"z\"\n- self.first_dim_pts = y_sol\n- self.second_dim_pts = z_sol\n-\n- # set up interpolation\n- self._interpolation_function = interp.interp2d(\n- y_sol, z_sol, entries, kind=\"linear\", fill_value=np.nan\n- )\n+ self._interpolation_function = interp_fun\n+ else:\n+ # function of space and time.\n+ self._interpolation_function = interp.RegularGridInterpolator(\n+ (first_dim_pts, second_dim_pts, self.t_sol),\n+ entries,\n+ method=\"linear\",\n+ fill_value=np.nan,\n+ )\n \n def initialise_2D_scikit_fem(self):\n y_sol = self.mesh[0].edges[\"y\"]\n@@ -349,11 +336,15 @@ class ProcessedVariable(object):\n eval_and_known_evals = self.base_variable.evaluate(\n t, u, inputs=inputs, known_evals=self.known_evals[t]\n )\n- entries[:, :, idx] = np.reshape(eval_and_known_evals[0], [len_y, len_z])\n+ entries[:, :, idx] = np.reshape(\n+ eval_and_known_evals[0], [len_y, len_z], order=\"F\"\n+ )\n self.known_evals[t] = eval_and_known_evals[1]\n else:\n entries[:, :, idx] = np.reshape(\n- self.base_variable.evaluate(t, u, inputs=inputs), [len_y, len_z]\n+ self.base_variable.evaluate(t, u, inputs=inputs),\n+ [len_y, len_z],\n+ order=\"F\",\n )\n \n # assign attributes for reference\n@@ -367,23 +358,49 @@ class ProcessedVariable(object):\n self.second_dim_pts = z_sol\n \n # set up interpolation\n- self._interpolation_function = interp.RegularGridInterpolator(\n- (y_sol, z_sol, self.t_sol), entries, method=\"linear\", fill_value=np.nan\n- )\n+ if len(self.t_sol) == 1:\n+ # function of space only. Note the order of the points is the reverse\n+ # of what you'd expect\n+ interpolant = interp.interp2d(\n+ z_sol, y_sol, entries, kind=\"linear\", fill_value=np.nan\n+ )\n+\n+ def interp_fun(input):\n+ return make_interp2D_fun(input, interpolant)\n+\n+ self._interpolation_function = interp_fun\n+ else:\n+ # function of space and time.\n+ self._interpolation_function = interp.RegularGridInterpolator(\n+ (y_sol, z_sol, self.t_sol), entries, method=\"linear\", fill_value=np.nan\n+ )\n \n def __call__(self, t=None, x=None, r=None, y=None, z=None, warn=True):\n \"\"\"\n Evaluate the variable at arbitrary t (and x, r, y and/or z), using interpolation\n \"\"\"\n+ # If t is None and there is only one value of time in the soluton (i.e.\n+ # the solution is independent of time) then we set t equal to the value\n+ # stored in the solution. If the variable is constant (doesn't depend on\n+ # time) evaluate arbitrarily at the first value of t. Otherwise, raise\n+ # an error\n+ if t is None:\n+ if len(self.t_sol) == 1:\n+ t = self.t_sol\n+ elif self.base_variable.is_constant():\n+ t = self.t_sol[0]\n+ else:\n+ raise ValueError(\n+ \"t cannot be None for variable {}\".format(self.base_variable)\n+ )\n+\n+ # Call interpolant of correct spatial dimension\n if self.dimensions == 0:\n out = self._interpolation_function(t)\n elif self.dimensions == 1:\n out = self.call_1D(t, x, r, z)\n elif self.dimensions == 2:\n- if t is None:\n- out = self._interpolation_function(y, z)\n- else:\n- out = self.call_2D(t, x, r, y, z)\n+ out = self.call_2D(t, x, r, y, z)\n if warn is True and np.isnan(out).any():\n pybamm.logger.warning(\n \"Calling variable outside interpolation range (returns 'nan')\"\n", "test_patch": "diff --git a/tests/unit/test_solvers/test_base_solver.py b/tests/unit/test_solvers/test_base_solver.py\nindex 885032e5c..99e9ed3aa 100644\n--- a/tests/unit/test_solvers/test_base_solver.py\n+++ b/tests/unit/test_solvers/test_base_solver.py\n@@ -71,6 +71,17 @@ class TestBaseSolver(unittest.TestCase):\n ):\n solver.solve(model, np.array([1, 2, 3, 2]))\n \n+ def test_solution_time_length_fail(self):\n+ model = pybamm.BaseModel()\n+ v = pybamm.Scalar(1)\n+ model.variables = {\"v\": v}\n+ solver = pybamm.DummySolver()\n+ t_eval = np.array([0])\n+ with self.assertRaisesRegex(\n+ pybamm.SolverError, \"Solution time vector has length 1\"\n+ ):\n+ solver.solve(model, t_eval)\n+\n def test_block_symbolic_inputs(self):\n solver = pybamm.BaseSolver(rtol=1e-2, atol=1e-4)\n model = pybamm.BaseModel()\n@@ -203,13 +214,13 @@ class TestBaseSolver(unittest.TestCase):\n solver.calculate_consistent_state(Model())\n solver = pybamm.BaseSolver(root_method=\"lm\")\n with self.assertRaisesRegex(\n- pybamm.SolverError, \"Could not find acceptable solution: solver terminated\",\n+ pybamm.SolverError, \"Could not find acceptable solution: solver terminated\"\n ):\n solver.calculate_consistent_state(Model())\n # with casadi\n solver = pybamm.BaseSolver(root_method=\"casadi\")\n with self.assertRaisesRegex(\n- pybamm.SolverError, \"Could not find acceptable solution: .../casadi\",\n+ pybamm.SolverError, \"Could not find acceptable solution: .../casadi\"\n ):\n solver.calculate_consistent_state(Model())\n \ndiff --git a/tests/unit/test_solvers/test_processed_variable.py b/tests/unit/test_solvers/test_processed_variable.py\nindex d9e6a1a50..d7c583a26 100644\n--- a/tests/unit/test_solvers/test_processed_variable.py\n+++ b/tests/unit/test_solvers/test_processed_variable.py\n@@ -20,6 +20,14 @@ class TestProcessedVariable(unittest.TestCase):\n processed_var = pybamm.ProcessedVariable(var, pybamm.Solution(t_sol, y_sol))\n np.testing.assert_array_equal(processed_var.entries, t_sol * y_sol[0])\n \n+ # scalar value\n+ var = y\n+ var.mesh = None\n+ t_sol = np.array([0])\n+ y_sol = np.array([1])[:, np.newaxis]\n+ processed_var = pybamm.ProcessedVariable(var, pybamm.Solution(t_sol, y_sol))\n+ np.testing.assert_array_equal(processed_var.entries, y_sol[0])\n+\n def test_processed_variable_1D(self):\n t = pybamm.t\n var = pybamm.Variable(\"var\", domain=[\"negative electrode\", \"separator\"])\n@@ -59,6 +67,18 @@ class TestProcessedVariable(unittest.TestCase):\n x_s_edge.entries[:, 0], processed_x_s_edge.entries[:, 0]\n )\n \n+ # space only\n+ eqn = var + x\n+ eqn_sol = disc.process_symbol(eqn)\n+ t_sol = np.array([0])\n+ y_sol = np.ones_like(x_sol)[:, np.newaxis]\n+ processed_eqn2 = pybamm.ProcessedVariable(\n+ eqn_sol, pybamm.Solution(t_sol, y_sol)\n+ )\n+ np.testing.assert_array_equal(\n+ processed_eqn2.entries, y_sol + x_sol[:, np.newaxis]\n+ )\n+\n def test_processed_variable_1D_unknown_domain(self):\n x = pybamm.SpatialVariable(\"x\", domain=\"SEI layer\", coord_sys=\"cartesian\")\n geometry = pybamm.Geometry()\n@@ -150,6 +170,31 @@ class TestProcessedVariable(unittest.TestCase):\n x_s_edge.entries.flatten(), processed_x_s_edge.entries[:, :, 0].T.flatten()\n )\n \n+ def test_processed_variable_2D_space_only(self):\n+ var = pybamm.Variable(\n+ \"var\",\n+ domain=[\"negative particle\"],\n+ auxiliary_domains={\"secondary\": [\"negative electrode\"]},\n+ )\n+ x = pybamm.SpatialVariable(\"x\", domain=[\"negative electrode\"])\n+ r = pybamm.SpatialVariable(\"r\", domain=[\"negative particle\"])\n+\n+ disc = tests.get_p2d_discretisation_for_testing()\n+ disc.set_variable_slices([var])\n+ x_sol = disc.process_symbol(x).entries[:, 0]\n+ r_sol = disc.process_symbol(r).entries[:, 0]\n+ # Keep only the first iteration of entries\n+ r_sol = r_sol[: len(r_sol) // len(x_sol)]\n+ var_sol = disc.process_symbol(var)\n+ t_sol = np.array([0])\n+ y_sol = np.ones(len(x_sol) * len(r_sol))[:, np.newaxis]\n+\n+ processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, y_sol))\n+ np.testing.assert_array_equal(\n+ processed_var.entries,\n+ np.reshape(y_sol, [len(r_sol), len(x_sol), len(t_sol)]),\n+ )\n+\n def test_processed_variable_2D_scikit(self):\n var = pybamm.Variable(\"var\", domain=[\"current collector\"])\n \n@@ -181,7 +226,7 @@ class TestProcessedVariable(unittest.TestCase):\n \n processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, u_sol))\n np.testing.assert_array_equal(\n- processed_var.entries, np.reshape(u_sol, [len(y), len(z)])\n+ processed_var.entries, np.reshape(u_sol, [len(y), len(z), len(t_sol)])\n )\n \n def test_processed_var_0D_interpolation(self):\n@@ -211,6 +256,19 @@ class TestProcessedVariable(unittest.TestCase):\n np.testing.assert_array_equal(processed_eqn(2), np.nan)\n pybamm.set_logging_level(\"WARNING\")\n \n+ def test_processed_var_0D_fixed_t_interpolation(self):\n+ y = pybamm.StateVector(slice(0, 1))\n+ var = y\n+ eqn = 2 * y\n+ var.mesh = None\n+ eqn.mesh = None\n+\n+ t_sol = np.array([10])\n+ y_sol = np.array([[100]])\n+ processed_var = pybamm.ProcessedVariable(eqn, pybamm.Solution(t_sol, y_sol))\n+\n+ np.testing.assert_array_equal(processed_var(), 200)\n+\n def test_processed_var_1D_interpolation(self):\n t = pybamm.t\n var = pybamm.Variable(\"var\", domain=[\"negative electrode\", \"separator\"])\n@@ -250,6 +308,12 @@ class TestProcessedVariable(unittest.TestCase):\n # 2 scalars\n self.assertEqual(processed_eqn(0.5, x_sol[-1]).shape, (1,))\n \n+ # test x\n+ processed_x = pybamm.ProcessedVariable(\n+ disc.process_symbol(x), pybamm.Solution(t_sol, y_sol)\n+ )\n+ np.testing.assert_array_almost_equal(processed_x(x=x_sol), x_sol[:, np.newaxis])\n+\n # On microscale\n r_n = pybamm.Matrix(\n disc.mesh[\"negative particle\"][0].nodes, domain=\"negative particle\"\n@@ -261,6 +325,27 @@ class TestProcessedVariable(unittest.TestCase):\n processed_r_n(0, r=np.linspace(0, 1))[:, 0], np.linspace(0, 1)\n )\n \n+ def test_processed_var_1D_fixed_t_interpolation(self):\n+ var = pybamm.Variable(\"var\", domain=[\"negative electrode\", \"separator\"])\n+ x = pybamm.SpatialVariable(\"x\", domain=[\"negative electrode\", \"separator\"])\n+ eqn = var + x\n+\n+ disc = tests.get_discretisation_for_testing()\n+ disc.set_variable_slices([var])\n+ x_sol = disc.process_symbol(x).entries[:, 0]\n+ eqn_sol = disc.process_symbol(eqn)\n+ t_sol = np.array([1])\n+ y_sol = x_sol[:, np.newaxis]\n+\n+ processed_var = pybamm.ProcessedVariable(eqn_sol, pybamm.Solution(t_sol, y_sol))\n+\n+ # vector\n+ np.testing.assert_array_almost_equal(\n+ processed_var(x=x_sol), 2 * x_sol[:, np.newaxis]\n+ )\n+ # scalar\n+ np.testing.assert_array_almost_equal(processed_var(x=0.5), 1)\n+\n def test_processed_var_2D_interpolation(self):\n var = pybamm.Variable(\n \"var\",\n@@ -324,6 +409,34 @@ class TestProcessedVariable(unittest.TestCase):\n processed_var(t_sol, x_sol, r_sol).shape, (10, 35, 50)\n )\n \n+ def test_processed_var_2D_fixed_t_interpolation(self):\n+ var = pybamm.Variable(\n+ \"var\",\n+ domain=[\"negative particle\"],\n+ auxiliary_domains={\"secondary\": [\"negative electrode\"]},\n+ )\n+ x = pybamm.SpatialVariable(\"x\", domain=[\"negative electrode\"])\n+ r = pybamm.SpatialVariable(\"r\", domain=[\"negative particle\"])\n+\n+ disc = tests.get_p2d_discretisation_for_testing()\n+ disc.set_variable_slices([var])\n+ x_sol = disc.process_symbol(x).entries[:, 0]\n+ r_sol = disc.process_symbol(r).entries[:, 0]\n+ # Keep only the first iteration of entries\n+ r_sol = r_sol[: len(r_sol) // len(x_sol)]\n+ var_sol = disc.process_symbol(var)\n+ t_sol = np.array([0])\n+ y_sol = np.ones(len(x_sol) * len(r_sol))[:, np.newaxis]\n+\n+ processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, y_sol))\n+ # 2 vectors\n+ np.testing.assert_array_equal(processed_var(x=x_sol, r=r_sol).shape, (10, 40))\n+ # 1 vector, 1 scalar\n+ np.testing.assert_array_equal(processed_var(x=0.2, r=r_sol).shape, (10,))\n+ np.testing.assert_array_equal(processed_var(x=x_sol, r=0.5).shape, (40,))\n+ # 2 scalars\n+ np.testing.assert_array_equal(processed_var(x=0.2, r=0.2).shape, ())\n+\n def test_processed_var_2D_secondary_broadcast(self):\n var = pybamm.Variable(\"var\", domain=[\"negative particle\"])\n broad_var = pybamm.SecondaryBroadcast(var, \"negative electrode\")\n@@ -429,18 +542,12 @@ class TestProcessedVariable(unittest.TestCase):\n \n processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, u_sol))\n # 2 vectors\n- np.testing.assert_array_equal(\n- processed_var(t=None, y=y_sol, z=z_sol).shape, (15, 15)\n- )\n+ np.testing.assert_array_equal(processed_var(y=y_sol, z=z_sol).shape, (15, 15))\n # 1 vector, 1 scalar\n- np.testing.assert_array_equal(\n- processed_var(t=None, y=0.2, z=z_sol).shape, (15, 1)\n- )\n- np.testing.assert_array_equal(\n- processed_var(t=None, y=y_sol, z=0.5).shape, (15,)\n- )\n+ np.testing.assert_array_equal(processed_var(y=0.2, z=z_sol).shape, (15,))\n+ np.testing.assert_array_equal(processed_var(y=y_sol, z=0.5).shape, (15,))\n # 2 scalars\n- np.testing.assert_array_equal(processed_var(t=None, y=0.2, z=0.2).shape, (1,))\n+ np.testing.assert_array_equal(processed_var(t=None, y=0.2, z=0.2).shape, ())\n \n def test_processed_variable_ode_pde_solution(self):\n # without space\n@@ -518,18 +625,9 @@ class TestProcessedVariable(unittest.TestCase):\n with self.assertRaisesRegex(ValueError, \"r cannot be None\"):\n processed_var(0, 1)\n \n- def test_solution_too_short(self):\n- t = pybamm.t\n- y = pybamm.StateVector(slice(0, 3))\n- var = t * y\n- disc = tests.get_2p1d_discretisation_for_testing()\n- var.mesh = disc.mesh[\"current collector\"]\n- t_sol = np.array([1])\n- y_sol = np.linspace(0, 5)[:, np.newaxis]\n- with self.assertRaisesRegex(\n- pybamm.SolverError, \"Solution time vector must have length > 1\"\n- ):\n- pybamm.ProcessedVariable(var, pybamm.Solution(t_sol, y_sol))\n+ # t is None but len(solution.t) > 1\n+ with self.assertRaisesRegex(ValueError, \"t cannot be None\"):\n+ processed_var()\n \n def test_3D_raises_error(self):\n var = pybamm.Variable(\n", "FAIL_TO_PASS": ["tests/unit/test_solvers/test_base_solver.py::TestBaseSolver::test_solution_time_length_fail", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_var_1D_fixed_t_interpolation", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_variable_0D"]}], "all_FAIL_TO_PASS": ["tests/unit/test_solvers/test_base_solver.py::TestBaseSolver::test_solution_time_length_fail", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_var_1D_fixed_t_interpolation", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_variable_0D"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pybamm-team__pybamm-1025_x1", "level": 1, "source": "swerebenchv2", "repo": "pybamm-team/PyBaMM", "image": "swerebenchv2/pybamm-team-pybamm:1025-1007c87", "base_commit": "1007c87379a6364384d30db315d4a99bc30a7173", "num_bugs": 1, "bugs": [{"instance_id": "pybamm-team__pybamm-1025", "base_commit": "1007c87379a6364384d30db315d4a99bc30a7173", "gold_patch": "diff --git a/pybamm/simulation.py b/pybamm/simulation.py\nindex e32421b18..003b03895 100644\n--- a/pybamm/simulation.py\n+++ b/pybamm/simulation.py\n@@ -298,13 +298,16 @@ class Simulation:\n \n if self.built_model:\n return None\n-\n- self.set_parameters()\n- self._mesh = pybamm.Mesh(self._geometry, self._submesh_types, self._var_pts)\n- self._disc = pybamm.Discretisation(self._mesh, self._spatial_methods)\n- self._built_model = self._disc.process_model(\n- self._model_with_set_params, inplace=False, check_model=check_model\n- )\n+ elif self.model.is_discretised:\n+ self._model_with_set_params = self.model\n+ self._built_model = self.model\n+ else:\n+ self.set_parameters()\n+ self._mesh = pybamm.Mesh(self._geometry, self._submesh_types, self._var_pts)\n+ self._disc = pybamm.Discretisation(self._mesh, self._spatial_methods)\n+ self._built_model = self._disc.process_model(\n+ self._model_with_set_params, inplace=False, check_model=check_model\n+ )\n \n def solve(\n self,\n", "test_patch": "diff --git a/tests/unit/test_simulation.py b/tests/unit/test_simulation.py\nindex 8a59951fd..7cb8fc40a 100644\n--- a/tests/unit/test_simulation.py\n+++ b/tests/unit/test_simulation.py\n@@ -103,6 +103,27 @@ class TestSimulation(unittest.TestCase):\n sim.solution[\"v\"].entries, np.exp(-np.linspace(0, 1, 100))\n )\n \n+ def test_solve_already_partially_processed_model(self):\n+\n+ model = pybamm.lithium_ion.SPM()\n+\n+ # Process model manually\n+ geometry = model.default_geometry\n+ param = model.default_parameter_values\n+ param.process_model(model)\n+ param.process_geometry(geometry)\n+ # Let simulation take over\n+ sim = pybamm.Simulation(model)\n+ sim.solve()\n+\n+ # Discretised manually\n+ mesh = pybamm.Mesh(geometry, model.default_submesh_types, model.default_var_pts)\n+ disc = pybamm.Discretisation(mesh, model.default_spatial_methods)\n+ disc.process_model(model)\n+ # Let simulation take over\n+ sim = pybamm.Simulation(model)\n+ sim.solve()\n+\n def test_reuse_commands(self):\n \n sim = pybamm.Simulation(pybamm.lithium_ion.SPM())\n", "FAIL_TO_PASS": ["tests/unit/test_simulation.py::TestSimulation::test_solve_already_partially_processed_model"]}], "all_FAIL_TO_PASS": ["tests/unit/test_simulation.py::TestSimulation::test_solve_already_partially_processed_model"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "oceanparcels__parcels-476_x1", "level": 1, "source": "swerebenchv2", "repo": "OceanParcels/parcels", "image": "swerebenchv2/oceanparcels-parcels:476-fea6b8e", "base_commit": "fea6b8e3b2f61317ee5d8bde00c9112ac7e9ea20", "num_bugs": 1, "bugs": [{"instance_id": "oceanparcels__parcels-476", "base_commit": "fea6b8e3b2f61317ee5d8bde00c9112ac7e9ea20", "gold_patch": "diff --git a/environment_py2_linux.yml b/environment_py2_linux.yml\nindex c51502b1..a0882889 100644\n--- a/environment_py2_linux.yml\n+++ b/environment_py2_linux.yml\n@@ -23,6 +23,7 @@ dependencies:\n - scipy>=0.16.0\n - six >=1.10.0\n - xarray>=0.10.8\n+ - dask\n - cftime\n - pip:\n - pytest>=2.7.0\ndiff --git a/environment_py2_osx.yml b/environment_py2_osx.yml\nindex 8a0a25b3..84a57995 100644\n--- a/environment_py2_osx.yml\n+++ b/environment_py2_osx.yml\n@@ -23,6 +23,7 @@ dependencies:\n - scipy>=0.16.0\n - six>=1.10.0\n - xarray>=0.10.8\n+ - dask\n - cftime\n - pip:\n - pytest>=2.7.0\ndiff --git a/environment_py3_linux.yml b/environment_py3_linux.yml\nindex ac9a13c5..eecb2c43 100644\n--- a/environment_py3_linux.yml\n+++ b/environment_py3_linux.yml\n@@ -23,6 +23,7 @@ dependencies:\n - six >=1.10.0\n - xarray>=0.10.8\n - cftime\n+ - dask\n - pip:\n - pytest>=2.7.0\n - nbval\ndiff --git a/environment_py3_osx.yml b/environment_py3_osx.yml\nindex 41760b19..393488f1 100644\n--- a/environment_py3_osx.yml\n+++ b/environment_py3_osx.yml\n@@ -22,6 +22,7 @@ dependencies:\n - scipy>=0.16.0\n - six>=1.10.0\n - xarray>=0.10.8\n+ - dask\n - cftime\n - pip:\n - pytest>=2.7.0\ndiff --git a/parcels/examples/example_globcurrent.py b/parcels/examples/example_globcurrent.py\nindex 2d15e0a0..d511ceda 100644\n--- a/parcels/examples/example_globcurrent.py\n+++ b/parcels/examples/example_globcurrent.py\n@@ -4,29 +4,35 @@ from os import path\n from glob import glob\n import numpy as np\n import pytest\n+import xarray as xr\n \n \n ptype = {'scipy': ScipyParticle, 'jit': JITParticle}\n \n \n-def set_globcurrent_fieldset(filename=None, indices=None, full_load=False):\n+def set_globcurrent_fieldset(filename=None, indices=None, full_load=False, use_xarray=False):\n if filename is None:\n filename = path.join(path.dirname(__file__), 'GlobCurrent_example_data',\n '20*-GLOBCURRENT-L4-CUReul_hs-ALT_SUM-v02.0-fv01.0.nc')\n variables = {'U': 'eastward_eulerian_current_velocity', 'V': 'northward_eulerian_current_velocity'}\n dimensions = {'lat': 'lat', 'lon': 'lon', 'time': 'time'}\n- return FieldSet.from_netcdf(filename, variables, dimensions, indices, full_load=full_load)\n+ if use_xarray:\n+ ds = xr.open_mfdataset(filename)\n+ return FieldSet.from_xarray_dataset(ds, variables, dimensions, indices, full_load=full_load)\n+ else:\n+ return FieldSet.from_netcdf(filename, variables, dimensions, indices, full_load=full_load)\n \n \n-def test_globcurrent_fieldset():\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_fieldset(use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n assert(fieldset.U.lon.size == 81)\n assert(fieldset.U.lat.size == 41)\n assert(fieldset.V.lon.size == 81)\n assert(fieldset.V.lat.size == 41)\n \n indices = {'lon': [5], 'lat': range(20, 30)}\n- fieldsetsub = set_globcurrent_fieldset(indices=indices)\n+ fieldsetsub = set_globcurrent_fieldset(indices=indices, use_xarray=use_xarray)\n assert np.allclose(fieldsetsub.U.lon, fieldset.U.lon[indices['lon']])\n assert np.allclose(fieldsetsub.U.lat, fieldset.U.lat[indices['lat']])\n assert np.allclose(fieldsetsub.V.lon, fieldset.V.lon[indices['lon']])\n@@ -34,34 +40,32 @@ def test_globcurrent_fieldset():\n \n \n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-@pytest.mark.parametrize('dt, substart, subend, lonstart, latstart, irange', [\n- (3600., 0, 3, 25, -35, range(3, 9, 1)),\n- (-3600., 8, 10, 20, -39, range(7, 2, -1))\n-])\n-def test_globcurrent_fieldset_advancetime(mode, dt, substart, subend, lonstart, latstart, irange):\n+@pytest.mark.parametrize('dt, lonstart, latstart', [(3600., 25, -35), (-3600., 20, -39)])\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_fieldset_advancetime(mode, dt, lonstart, latstart, use_xarray):\n basepath = path.join(path.dirname(__file__), 'GlobCurrent_example_data',\n '20*-GLOBCURRENT-L4-CUReul_hs-ALT_SUM-v02.0-fv01.0.nc')\n files = sorted(glob(str(basepath)))\n \n- fieldsetsub = set_globcurrent_fieldset(files[0:10])\n+ fieldsetsub = set_globcurrent_fieldset(files[0:10], use_xarray=use_xarray)\n psetsub = ParticleSet.from_list(fieldset=fieldsetsub, pclass=ptype[mode], lon=[lonstart], lat=[latstart])\n \n- fieldsetall = set_globcurrent_fieldset(files[0:10], full_load=True)\n+ fieldsetall = set_globcurrent_fieldset(files[0:10], full_load=True, use_xarray=use_xarray)\n psetall = ParticleSet.from_list(fieldset=fieldsetall, pclass=ptype[mode], lon=[lonstart], lat=[latstart])\n if dt < 0:\n psetsub[0].time = fieldsetsub.U.grid.time[-1]\n psetall[0].time = fieldsetall.U.grid.time[-1]\n \n- for i in irange:\n- psetsub.execute(AdvectionRK4, runtime=delta(days=1), dt=dt)\n- psetall.execute(AdvectionRK4, runtime=delta(days=1), dt=dt)\n+ psetsub.execute(AdvectionRK4, runtime=delta(days=7), dt=dt)\n+ psetall.execute(AdvectionRK4, runtime=delta(days=7), dt=dt)\n \n assert abs(psetsub[0].lon - psetall[0].lon) < 1e-4\n \n \n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-def test_globcurrent_particles(mode):\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_particles(mode, use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n \n lonstart = [25]\n latstart = [-35]\n@@ -74,6 +78,22 @@ def test_globcurrent_particles(mode):\n assert(abs(pset[0].lat - -35.3) < 1)\n \n \n+@pytest.mark.parametrize('dt', [-300, 300])\n+def test_globcurrent_xarray_vs_netcdf(dt):\n+ fieldsetNetcdf = set_globcurrent_fieldset(use_xarray=False)\n+ fieldsetxarray = set_globcurrent_fieldset(use_xarray=True)\n+ lonstart, latstart, runtime = (25, -35, delta(days=7))\n+\n+ psetN = ParticleSet(fieldsetNetcdf, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetN.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ psetX = ParticleSet(fieldsetxarray, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetX.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ assert np.allclose(psetN[0].lon, psetX[0].lon)\n+ assert np.allclose(psetN[0].lat, psetX[0].lat)\n+\n+\n def test__particles_init_time():\n fieldset = set_globcurrent_fieldset()\n \n@@ -92,8 +112,9 @@ def test__particles_init_time():\n \n @pytest.mark.xfail(reason=\"Time extrapolation error expected to be thrown\", strict=True)\n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-def test_globcurrent_time_extrapolation_error(mode):\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_time_extrapolation_error(mode, use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n \n pset = ParticleSet(fieldset, pclass=ptype[mode], lon=[25], lat=[-35],\n time=fieldset.U.time[0]-delta(days=1).total_seconds())\n@@ -103,8 +124,9 @@ def test_globcurrent_time_extrapolation_error(mode):\n \n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n @pytest.mark.parametrize('dt', [-300, 300])\n-def test_globcurrent_variable_fromfield(mode, dt):\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_variable_fromfield(mode, dt, use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n \n class MyParticle(ptype[mode]):\n sample_var = Variable('sample_var', initial=fieldset.U)\n@@ -115,8 +137,9 @@ def test_globcurrent_variable_fromfield(mode, dt):\n \n \n @pytest.mark.parametrize('full_load', [True, False])\n-def test_globcurrent_deferred_fieldset_gradient(full_load):\n- fieldset = set_globcurrent_fieldset(full_load=full_load)\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_deferred_fieldset_gradient(full_load, use_xarray):\n+ fieldset = set_globcurrent_fieldset(full_load=full_load, use_xarray=use_xarray)\n (dU_dx, dU_dy) = fieldset.U.gradient()\n fieldset.add_field(dU_dy)\n \ndiff --git a/parcels/examples/example_ofam.py b/parcels/examples/example_ofam.py\nindex f7c318cd..5fdf63b9 100644\n--- a/parcels/examples/example_ofam.py\n+++ b/parcels/examples/example_ofam.py\n@@ -1,30 +1,54 @@\n from parcels import FieldSet, ParticleSet, ScipyParticle, JITParticle, AdvectionRK4\n from datetime import timedelta as delta\n import pytest\n+import xarray as xr\n+import numpy as np\n from os import path\n \n \n ptype = {'scipy': ScipyParticle, 'jit': JITParticle}\n \n \n-def set_ofam_fieldset(full_load=False):\n+def set_ofam_fieldset(full_load=False, use_xarray=False):\n filenames = {'U': path.join(path.dirname(__file__), 'OFAM_example_data', 'OFAM_simple_U.nc'),\n 'V': path.join(path.dirname(__file__), 'OFAM_example_data', 'OFAM_simple_V.nc')}\n variables = {'U': 'u', 'V': 'v'}\n dimensions = {'lat': 'yu_ocean', 'lon': 'xu_ocean', 'depth': 'st_ocean',\n 'time': 'Time'}\n- return FieldSet.from_netcdf(filenames, variables, dimensions, allow_time_extrapolation=True, full_load=full_load)\n+ if use_xarray:\n+ ds = xr.open_mfdataset([filenames['U'], filenames['V']])\n+ return FieldSet.from_xarray_dataset(ds, variables, dimensions, allow_time_extrapolation=True, full_load=full_load)\n+ else:\n+ return FieldSet.from_netcdf(filenames, variables, dimensions, allow_time_extrapolation=True, full_load=full_load)\n \n \n-def test_ofam_fieldset_fillvalues():\n- fieldset = set_ofam_fieldset(full_load=True)\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_ofam_fieldset_fillvalues(use_xarray):\n+ fieldset = set_ofam_fieldset(full_load=True, use_xarray=use_xarray)\n # V.data[0, 0, 150] is a landpoint, that makes NetCDF4 generate a masked array, instead of an ndarray\n assert(fieldset.V.data[0, 0, 150] == 0)\n \n \n+@pytest.mark.parametrize('dt', [delta(minutes=-5), delta(minutes=5)])\n+def test_ofam_xarray_vs_netcdf(dt):\n+ fieldsetNetcdf = set_ofam_fieldset(use_xarray=False)\n+ fieldsetxarray = set_ofam_fieldset(use_xarray=True)\n+ lonstart, latstart, runtime = (180, 10, delta(days=7))\n+\n+ psetN = ParticleSet(fieldsetNetcdf, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetN.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ psetX = ParticleSet(fieldsetxarray, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetX.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ assert np.allclose(psetN[0].lon, psetX[0].lon)\n+ assert np.allclose(psetN[0].lat, psetX[0].lat)\n+\n+\n+@pytest.mark.parametrize('use_xarray', [True, False])\n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-def test_ofam_particles(mode):\n- fieldset = set_ofam_fieldset()\n+def test_ofam_particles(mode, use_xarray):\n+ fieldset = set_ofam_fieldset(use_xarray=use_xarray)\n \n lonstart = [180]\n latstart = [10]\ndiff --git a/parcels/field.py b/parcels/field.py\nindex 22003f49..73dfd838 100644\n--- a/parcels/field.py\n+++ b/parcels/field.py\n@@ -155,30 +155,35 @@ class Field(object):\n :param netcdf_engine: engine to use for netcdf reading in xarray. Default is 'netcdf',\n but in cases where this doesn't work, setting netcdf_engine='scipy' could help\n \"\"\"\n-\n- if not isinstance(filenames, Iterable) or isinstance(filenames, str):\n- filenames = [filenames]\n-\n- data_filenames = filenames['data'] if type(filenames) is dict else filenames\n- if type(filenames) == dict:\n- for k in filenames.keys():\n- assert k in ['lon', 'lat', 'depth', 'data'], \\\n- 'filename dimension keys must be lon, lat, depth or data'\n- assert len(filenames['lon']) == 1\n- if filenames['lon'] != filenames['lat']:\n- raise NotImplementedError('longitude and latitude dimensions are currently processed together from one single file')\n- lonlat_filename = filenames['lon'][0]\n- if 'depth' in dimensions:\n- if len(filenames['depth']) != 1:\n- raise NotImplementedError('Vertically adaptive meshes not implemented for from_netcdf()')\n- depth_filename = filenames['depth'][0]\n-\n+ if isinstance(variable, xr.core.dataarray.DataArray):\n+ lonlat_filename = variable\n+ depth_filename = variable\n+ data_filenames = variable\n+ netcdf_engine = 'xarray'\n else:\n- lonlat_filename = filenames[0]\n- depth_filename = filenames[0]\n+ if not isinstance(filenames, Iterable) or isinstance(filenames, str):\n+ filenames = [filenames]\n+\n+ data_filenames = filenames['data'] if type(filenames) is dict else filenames\n+ if type(filenames) == dict:\n+ for k in filenames.keys():\n+ assert k in ['lon', 'lat', 'depth', 'data'], \\\n+ 'filename dimension keys must be lon, lat, depth or data'\n+ assert len(filenames['lon']) == 1\n+ if filenames['lon'] != filenames['lat']:\n+ raise NotImplementedError('longitude and latitude dimensions are currently processed together from one single file')\n+ lonlat_filename = filenames['lon'][0]\n+ if 'depth' in dimensions:\n+ if len(filenames['depth']) != 1:\n+ raise NotImplementedError('Vertically adaptive meshes not implemented for from_netcdf()')\n+ depth_filename = filenames['depth'][0]\n+ else:\n+ lonlat_filename = filenames[0]\n+ depth_filename = filenames[0]\n+ netcdf_engine = kwargs.pop('netcdf_engine', 'netcdf4')\n \n indices = {} if indices is None else indices.copy()\n- netcdf_engine = kwargs.pop('netcdf_engine', 'netcdf4')\n+\n with NetcdfFileBuffer(lonlat_filename, dimensions, indices, netcdf_engine) as filebuffer:\n lon, lat = filebuffer.read_lonlat\n indices = filebuffer.indices\n@@ -199,16 +204,22 @@ class Field(object):\n if grid is None:\n # Concatenate time variable to determine overall dimension\n # across multiple files\n- timeslices = []\n- dataFiles = []\n- for fname in data_filenames:\n- with NetcdfFileBuffer(fname, dimensions, indices, netcdf_engine) as filebuffer:\n- ftime = filebuffer.time\n- timeslices.append(ftime)\n- dataFiles.append([fname] * len(ftime))\n- timeslices = np.array(timeslices)\n- time = np.concatenate(timeslices)\n- dataFiles = np.concatenate(np.array(dataFiles))\n+ if netcdf_engine == 'xarray':\n+ with NetcdfFileBuffer(data_filenames, dimensions, indices, netcdf_engine) as filebuffer:\n+ time = filebuffer.time\n+ timeslices = time if isinstance(time, (list, np.ndarray)) else [time]\n+ dataFiles = data_filenames if isinstance(data_filenames, (list, np.ndarray)) else [data_filenames] * len(time)\n+ else:\n+ timeslices = []\n+ dataFiles = []\n+ for fname in data_filenames:\n+ with NetcdfFileBuffer(fname, dimensions, indices, netcdf_engine) as filebuffer:\n+ ftime = filebuffer.time\n+ timeslices.append(ftime)\n+ dataFiles.append([fname] * len(ftime))\n+ timeslices = np.array(timeslices)\n+ time = np.concatenate(timeslices)\n+ dataFiles = np.concatenate(np.array(dataFiles))\n if time.size == 1 and time[0] is None:\n time[0] = 0\n time_origin = TimeConverter(time[0])\n@@ -239,17 +250,20 @@ class Field(object):\n with NetcdfFileBuffer(fname, dimensions, indices, netcdf_engine) as filebuffer:\n # If Field.from_netcdf is called directly, it may not have a 'data' dimension\n # In that case, assume that 'name' is the data dimension\n- filebuffer.name = filebuffer.parse_name(dimensions, variable)\n+ if netcdf_engine == 'xarray':\n+ tslice = [tslice]\n+ else:\n+ filebuffer.name = filebuffer.parse_name(dimensions, variable)\n \n- if len(filebuffer.dataset[filebuffer.name].shape) == 2:\n- data[ti:ti+len(tslice), 0, :, :] = filebuffer.data[:, :]\n- elif len(filebuffer.dataset[filebuffer.name].shape) == 3:\n+ if len(filebuffer.data.shape) == 2:\n+ data[ti:ti+len(tslice), 0, :, :] = filebuffer.data\n+ elif len(filebuffer.data.shape) == 3:\n if len(filebuffer.indices['depth']) > 1:\n- data[ti:ti+len(tslice), :, :, :] = filebuffer.data[:, :, :]\n+ data[ti:ti+len(tslice), :, :, :] = filebuffer.data\n else:\n- data[ti:ti+len(tslice), 0, :, :] = filebuffer.data[:, :, :]\n+ data[ti:ti+len(tslice), 0, :, :] = filebuffer.data\n else:\n- data[ti:ti+len(tslice), :, :, :] = filebuffer.data[:, :, :, :]\n+ data[ti:ti+len(tslice), :, :, :] = filebuffer.data\n ti += len(tslice)\n else:\n grid.defer_load = True\n@@ -264,6 +278,7 @@ class Field(object):\n kwargs['time_periodic'] = time_periodic\n kwargs['netcdf_engine'] = netcdf_engine\n \n+ variable = kwargs['var_name'] if netcdf_engine == 'xarray' else variable\n return cls(variable, data, grid=grid,\n allow_time_extrapolation=allow_time_extrapolation, **kwargs)\n \n@@ -866,21 +881,20 @@ class Field(object):\n def computeTimeChunk(self, data, tindex):\n g = self.grid\n with NetcdfFileBuffer(self.dataFiles[g.ti+tindex], self.dimensions, self.indices, self.netcdf_engine) as filebuffer:\n- filebuffer.name = filebuffer.parse_name(self.dimensions, self.name)\n time_data = filebuffer.time\n time_data = g.time_origin.reltime(time_data)\n- ti = (time_data <= g.time[tindex]).argmin() - 1\n- if len(filebuffer.dataset[filebuffer.name].shape) == 2:\n- data[tindex, 0, :, :] = filebuffer.data[:, :]\n- elif len(filebuffer.dataset[filebuffer.name].shape) == 3:\n+ filebuffer.ti = (time_data <= g.time[tindex]).argmin() - 1\n+ if self.netcdf_engine != 'xarray':\n+ filebuffer.name = filebuffer.parse_name(self.dimensions, self.name)\n+ if len(filebuffer.data.shape) == 2:\n+ data[tindex, 0, :, :] = filebuffer.data\n+ elif len(filebuffer.data.shape) == 3:\n if g.zdim > 1:\n- data[tindex, :, :, :] = filebuffer.data[:, :, :]\n+ data[tindex, :, :, :] = filebuffer.data\n else:\n- data[tindex, 0, :, :] = filebuffer.data[ti, :, :]\n+ data[tindex, 0, :, :] = filebuffer.data\n else:\n- data[tindex, :, :, :] = filebuffer.data[ti, :, :, :]\n-\n- return data\n+ data[tindex, :, :, :] = filebuffer.data\n \n def __add__(self, field):\n if isinstance(self, Field) and isinstance(field, Field):\n@@ -1139,12 +1153,16 @@ class NetcdfFileBuffer(object):\n \n def __init__(self, filename, dimensions, indices, netcdf_engine):\n self.filename = filename\n- self.dimensions = dimensions # Dict with dimension keyes for file data\n+ self.dimensions = dimensions # Dict with dimension keys for file data\n self.indices = indices\n self.dataset = None\n self.netcdf_engine = netcdf_engine\n+ self.ti = None\n \n def __enter__(self):\n+ if self.netcdf_engine == 'xarray':\n+ self.dataset = self.filename\n+ return self\n try:\n self.dataset = xr.open_dataset(str(self.filename), decode_cf=True, engine=self.netcdf_engine)\n self.dataset['decoded'] = True\n@@ -1159,7 +1177,10 @@ class NetcdfFileBuffer(object):\n return self\n \n def __exit__(self, type, value, traceback):\n- self.dataset.close()\n+ if self.netcdf_engine == 'xarray':\n+ pass\n+ else:\n+ self.dataset.close()\n \n def parse_name(self, dimensions, variable):\n name = dimensions['data'] if 'data' in dimensions else variable\n@@ -1228,16 +1249,20 @@ class NetcdfFileBuffer(object):\n \n @property\n def data(self):\n- data = self.dataset[self.name]\n+ if self.netcdf_engine == 'xarray':\n+ data = self.dataset\n+ else:\n+ data = self.dataset[self.name]\n+ ti = range(data.shape[0]) if self.ti is None else self.ti\n if len(data.shape) == 2:\n data = data[self.indices['lat'], self.indices['lon']]\n elif len(data.shape) == 3:\n if len(self.indices['depth']) > 1:\n data = data[self.indices['depth'], self.indices['lat'], self.indices['lon']]\n else:\n- data = data[:, self.indices['lat'], self.indices['lon']]\n+ data = data[ti, self.indices['lat'], self.indices['lon']]\n else:\n- data = data[:, self.indices['depth'], self.indices['lat'], self.indices['lon']]\n+ data = data[ti, self.indices['depth'], self.indices['lat'], self.indices['lon']]\n \n if np.ma.is_masked(data): # convert masked array to ndarray\n data = np.ma.filled(data, np.nan)\n@@ -1247,7 +1272,7 @@ class NetcdfFileBuffer(object):\n def time(self):\n try:\n time_da = self.dataset[self.dimensions['time']]\n- if self.dataset['decoded'] and 'Unit' not in time_da.attrs:\n+ if self.netcdf_engine != 'xarray' and (self.dataset['decoded'] and 'Unit' not in time_da.attrs):\n time = np.array([time_da]) if len(time_da.shape) == 0 else np.array(time_da)\n else:\n if 'units' not in time_da.attrs and 'Unit' in time_da.attrs:\ndiff --git a/parcels/fieldset.py b/parcels/fieldset.py\nindex 6232ce73..012cd2df 100644\n--- a/parcels/fieldset.py\n+++ b/parcels/fieldset.py\n@@ -331,6 +331,51 @@ class FieldSet(object):\n dimensions=dimensions, allow_time_extrapolation=allow_time_extrapolation,\n time_periodic=time_periodic, full_load=full_load, **kwargs)\n \n+ @classmethod\n+ def from_xarray_dataset(cls, ds, variables, dimensions, indices=None, mesh='spherical', allow_time_extrapolation=None,\n+ time_periodic=False, full_load=False, **kwargs):\n+ \"\"\"Initialises FieldSet data from xarray Datasets.\n+\n+ :param ds: xarray Dataset\n+ :param dimensions: Dictionary mapping data dimensions (lon,\n+ lat, depth, time, data) to dimensions in the xarray Dataset.\n+ Note that dimensions can also be a dictionary of dictionaries if\n+ dimension names are different for each variable\n+ (e.g. dimensions['U'], dimensions['V'], etc).\n+ :param indices: Optional dictionary of indices for each dimension\n+ to read from file(s), to allow for reading of subset of data.\n+ Default is to read the full extent of each dimension.\n+ :param mesh: String indicating the type of mesh coordinates and\n+ units used during velocity interpolation:\n+\n+ 1. spherical (default): Lat and lon in degree, with a\n+ correction for zonal velocity U near the poles.\n+ 2. flat: No conversion, lat/lon are assumed to be in m.\n+ :param allow_time_extrapolation: boolean whether to allow for extrapolation\n+ (i.e. beyond the last available time snapshot)\n+ Default is False if dimensions includes time, else True\n+ :param time_periodic: boolean whether to loop periodically over the time component of the FieldSet\n+ This flag overrides the allow_time_interpolation and sets it to False\n+ :param full_load: boolean whether to fully load the data or only pre-load them. (default: False)\n+ It is advised not to fully load the data, since in that case Parcels deals with\n+ a better memory management during particle set execution.\n+ full_load is however sometimes necessary for plotting the fields.\n+ \"\"\"\n+\n+ fields = {}\n+ for var, name in variables.items():\n+\n+ # Use dimensions[var] and indices[var] if either of them is a dict of dicts\n+ dims = dimensions[var] if var in dimensions else dimensions\n+ inds = indices[var] if (indices and var in indices) else indices\n+\n+ fields[var] = Field.from_netcdf(None, ds[name], dimensions=dims, indices=inds, grid=None, mesh=mesh,\n+ allow_time_extrapolation=allow_time_extrapolation, var_name=var,\n+ time_periodic=time_periodic, full_load=full_load, **kwargs)\n+ u = fields.pop('U', None)\n+ v = fields.pop('V', None)\n+ return cls(u, v, fields=fields)\n+\n @property\n def fields(self):\n \"\"\"Returns a list of all the :class:`parcels.field.Field` objects\n@@ -446,7 +491,7 @@ class FieldSet(object):\n data = np.empty((g.tdim, g.zdim, g.ydim-2*g.meridional_halo, g.xdim-2*g.zonal_halo), dtype=np.float32)\n f.loaded_time_indices = range(3)\n for tind in f.loaded_time_indices:\n- data = f.computeTimeChunk(data, tind)\n+ f.computeTimeChunk(data, tind)\n f.data = f.reshape(data)\n elif g.update_status == 'updated':\n data = np.empty((g.tdim, g.zdim, g.ydim-2*g.meridional_halo, g.xdim-2*g.zonal_halo), dtype=np.float32)\n@@ -456,7 +501,7 @@ class FieldSet(object):\n else:\n f.data[1:, :] = f.data[:2, :]\n f.loaded_time_indices = [0]\n- data = f.computeTimeChunk(data, f.loaded_time_indices[0])\n+ f.computeTimeChunk(data, f.loaded_time_indices[0])\n f.data[f.loaded_time_indices[0], :] = f.reshape(data)[f.loaded_time_indices[0], :]\n else:\n f.loaded_time_indices = []\n", "test_patch": "diff --git a/tests/test_fieldset.py b/tests/test_fieldset.py\nindex d4f897f2..bebcda16 100644\n--- a/tests/test_fieldset.py\n+++ b/tests/test_fieldset.py\n@@ -4,6 +4,7 @@ from parcels.tools.converters import TimeConverter\n from datetime import timedelta as delta\n import datetime\n import numpy as np\n+import xarray as xr\n import math\n import pytest\n from os import path\n@@ -365,3 +366,31 @@ def test_fieldset_defer_loading_function(zdim, scale_fac, tmpdir, filename='test\n pset.execute(DoNothing, dt=3600)\n assert np.allclose(fieldset.U.data, scale_fac*(zdim-1.)/zdim)\n assert np.allclose(dFdx.data, 0)\n+\n+\n+@pytest.mark.parametrize('maxlatind', [3, pytest.param(2, marks=pytest.mark.xfail(strict=True))])\n+def test_fieldset_from_xarray(maxlatind):\n+ def generate_dataset(xdim, ydim, zdim=1, tdim=1):\n+ lon = np.linspace(0., 12, xdim, dtype=np.float32)\n+ lat = np.linspace(0., 12, ydim, dtype=np.float32)\n+ depth = np.linspace(0., 20., zdim, dtype=np.float32)\n+ time = np.linspace(0., 10, tdim, dtype=np.float64)\n+ Uxr = np.ones((tdim, zdim, ydim, xdim), dtype=np.float32)\n+ Vxr = np.ones((tdim, zdim, ydim, xdim), dtype=np.float32)\n+ for t in range(Uxr.shape[0]):\n+ Uxr[t, :, :, :] = t/10.\n+ coords = {'lat': lat, 'lon': lon, 'depth': depth, 'time': time}\n+ dims = ('time', 'depth', 'lat', 'lon')\n+ return xr.Dataset({'Uxr': xr.DataArray(Uxr, coords=coords, dims=dims),\n+ 'Vxr': xr.DataArray(Vxr, coords=coords, dims=dims)})\n+\n+ ds = generate_dataset(3, 3, 2, 10)\n+ variables = {'U': 'Uxr', 'V': 'Vxr'}\n+ dimensions = {'lat': 'lat', 'lon': 'lon', 'depth': 'depth', 'time': 'time'}\n+ indices = {'lat': range(0, maxlatind)}\n+ fieldset = FieldSet.from_xarray_dataset(ds, variables, dimensions, indices, mesh='flat')\n+\n+ pset = ParticleSet(fieldset, JITParticle, 0, 0)\n+\n+ pset.execute(AdvectionRK4, dt=1)\n+ assert pset[0].lon == 4.5 and pset[0].lat == 10\n", "FAIL_TO_PASS": ["tests/test_fieldset.py::test_fieldset_from_xarray[3]"]}], "all_FAIL_TO_PASS": ["tests/test_fieldset.py::test_fieldset_from_xarray[3]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "oceanparcels__parcels-541_x1", "level": 1, "source": "swerebenchv2", "repo": "OceanParcels/parcels", "image": "swerebenchv2/oceanparcels-parcels:541-1ba7770", "base_commit": "1ba77703fb2ff32311f5a948af64130e960cb84c", "num_bugs": 1, "bugs": [{"instance_id": "oceanparcels__parcels-541", "base_commit": "1ba77703fb2ff32311f5a948af64130e960cb84c", "gold_patch": "diff --git a/parcels/codegenerator.py b/parcels/codegenerator.py\nindex 47695ea7..08001043 100644\n--- a/parcels/codegenerator.py\n+++ b/parcels/codegenerator.py\n@@ -209,7 +209,7 @@ class IntrinsicTransformer(ast.NodeTransformer):\n \n def get_tmp(self):\n \"\"\"Create a new temporary veriable name\"\"\"\n- tmp = \"tmp%d\" % self._tmp_counter\n+ tmp = \"parcels_tmpvar%d\" % self._tmp_counter\n self._tmp_counter += 1\n self.tmp_vars += [tmp]\n return tmp\n@@ -228,6 +228,8 @@ class IntrinsicTransformer(ast.NodeTransformer):\n node = RandomNode(math, ccode='')\n elif node.id == 'print':\n node = PrintNode()\n+ elif 'parcels_tmpvar' in node.id:\n+ raise NotImplementedError(\"Custom Kernels cannot contain string 'parcels_tmpvar'; please change your kernel\")\n return node\n \n def visit_Attribute(self, node):\n@@ -542,7 +544,7 @@ class KernelGenerator(ast.NodeVisitor):\n self.visit(b)\n # field evals are replaced by a tmp variable is added to the stack.\n # Here it means field evals passes from node.test to node.body. We take it out manually\n- fieldInTestCount = node.test.ccode.count('tmp')\n+ fieldInTestCount = node.test.ccode.count('parcels_tmpvar')\n body0 = c.Block([b.ccode for b in node.body[:fieldInTestCount]])\n body = c.Block([b.ccode for b in node.body[fieldInTestCount:]])\n orelse = c.Block([b.ccode for b in node.orelse]) if len(node.orelse) > 0 else None\n", "test_patch": "diff --git a/tests/test_kernel_language.py b/tests/test_kernel_language.py\nindex a87f4d56..874bc981 100644\n--- a/tests/test_kernel_language.py\n+++ b/tests/test_kernel_language.py\n@@ -110,6 +110,39 @@ def test_while_if_break(fieldset, mode):\n assert np.allclose(np.array([p.p for p in pset]), 20., rtol=1e-12)\n \n \n+@pytest.mark.parametrize('mode', ['scipy', 'jit'])\n+def test_nested_if(fieldset, mode):\n+ \"\"\"Test nested if commands\"\"\"\n+ class TestParticle(ptype[mode]):\n+ p0 = Variable('p0', dtype=np.int32, initial=0)\n+ p1 = Variable('p1', dtype=np.int32, initial=1)\n+ pset = ParticleSet(fieldset, pclass=TestParticle, lon=0, lat=0)\n+\n+ def kernel(particle, fieldset, time):\n+ if particle.p1 >= particle.p0:\n+ var = particle.p0\n+ if var + 1 < particle.p1:\n+ particle.p1 = -1\n+\n+ pset.execute(kernel, endtime=10, dt=1.)\n+ assert np.allclose([pset[0].p0, pset[0].p1], [0, 1])\n+\n+\n+def test_parcels_tmpvar_in_kernel(fieldset):\n+ \"\"\"Tests for error thrown if vartiable with 'tmp' defined in custom kernel\"\"\"\n+ error_thrown = False\n+ pset = ParticleSet(fieldset, pclass=JITParticle, lon=0, lat=0)\n+\n+ def kernel_tmpvar(particle, fieldset, time):\n+ parcels_tmpvar0 = 0 # noqa\n+\n+ try:\n+ pset.execute(kernel_tmpvar, endtime=1, dt=1.)\n+ except NotImplementedError:\n+ error_thrown = True\n+ assert error_thrown\n+\n+\n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n def test_if_withfield(fieldset, mode):\n \"\"\"Test combination of if and Field sampling commands\"\"\"\n", "FAIL_TO_PASS": ["tests/test_kernel_language.py::test_parcels_tmpvar_in_kernel"]}], "all_FAIL_TO_PASS": ["tests/test_kernel_language.py::test_parcels_tmpvar_in_kernel"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aws-cloudformation__cfn-lint-3898_x1", "level": 1, "source": "swerebenchv2", "repo": "aws-cloudformation/cfn-lint", "image": "swerebenchv2/aws-cloudformation-cfn-lint:3898-e087f10", "base_commit": "e087f1037b067288e377d197d6b855cd481d6a47", "num_bugs": 1, "bugs": [{"instance_id": "aws-cloudformation__cfn-lint-3898", "base_commit": "e087f1037b067288e377d197d6b855cd481d6a47", "gold_patch": "diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py\nindex 03846af54..a9f4aa5e4 100644\n--- a/src/cfnlint/config.py\n+++ b/src/cfnlint/config.py\n@@ -313,7 +313,7 @@ class RuleConfigurationAction(argparse.Action):\n setattr(namespace, self.dest, items)\n except Exception: # pylint: disable=W0703\n parser.print_help()\n- parser.exit()\n+ parser.exit(1)\n \n \n class CliArgs:\n@@ -331,7 +331,7 @@ class CliArgs:\n \n def error(self, message):\n self.print_help(sys.stderr)\n- self.exit(32, f\"{self.prog}: error: {message}\\n\")\n+ self.exit(1, f\"{self.prog}: error: {message}\\n\")\n \n class ExtendAction(argparse.Action):\n \"\"\"Support argument types that are lists and can\n@@ -620,7 +620,6 @@ class ManualArgs(TypedDict, total=False):\n \n # pylint: disable=too-many-public-methods\n class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n- \"\"\"Mixin for the Configs\"\"\"\n \n def __init__(self, cli_args: list[str] | None = None, **kwargs: Unpack[ManualArgs]):\n self._manual_args = kwargs or ManualArgs()\n@@ -721,7 +720,7 @@ class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n \n @property\n def debug(self):\n- return self._get_argument_value(\"debug\", False, False)\n+ return self._get_argument_value(\"debug\", False, True)\n \n @property\n def info(self):\ndiff --git a/src/cfnlint/core.py b/src/cfnlint/core.py\nindex e1e231d76..899e06cbe 100644\n--- a/src/cfnlint/core.py\n+++ b/src/cfnlint/core.py\n@@ -9,9 +9,10 @@ import os\n from typing import Sequence\n \n from cfnlint.config import _DEFAULT_RULESDIR, ConfigMixIn, ManualArgs\n+from cfnlint.exceptions import UnexpectedRuleException\n from cfnlint.match import Match\n from cfnlint.rules import RulesCollection\n-from cfnlint.runner import TemplateRunner, UnexpectedRuleException\n+from cfnlint.runner import TemplateRunner\n \n \n def get_rules(\ndiff --git a/src/cfnlint/data/CfnLintCli/config/schema.json b/src/cfnlint/data/CfnLintCli/config/schema.json\nindex f72fc6189..e87f1234b 100644\n--- a/src/cfnlint/data/CfnLintCli/config/schema.json\n+++ b/src/cfnlint/data/CfnLintCli/config/schema.json\n@@ -58,6 +58,10 @@\n \"description\": \"custom rule file to use\",\n \"type\": \"string\"\n },\n+ \"debug\": {\n+ \"description\": \"Debug mode\",\n+ \"type\": \"boolean\"\n+ },\n \"ignore_bad_template\": {\n \"description\": \"Ignore bad templates\",\n \"type\": \"boolean\"\ndiff --git a/src/cfnlint/exceptions.py b/src/cfnlint/exceptions.py\nindex cedb10369..993106ab0 100644\n--- a/src/cfnlint/exceptions.py\n+++ b/src/cfnlint/exceptions.py\n@@ -1,21 +1,57 @@\n-class CfnLintError(Exception):\n+class CfnLintExitException(Exception):\n \"\"\"\n- The base exception class for cfn-lint exceptions.\n- :ivar msg: The descriptive message associated with the error.\n+ An exception that is raised to indicate that the CloudFormation linter should exit.\n+\n+ This exception is used to signal that the linter should exit\n+ with a specific exit code, typically indicating the severity\n+ of the issues found in the CloudFormation template.\n+\n+ Attributes:\n+ exit_code (int): The exit code to be used when the linter exits.\n+\n+ Methods:\n+ __init__(self, exit_code: int) -> None:\n+ Initialize a new CfnLintExitException instance with the specified exit code.\n \"\"\"\n \n- fmt = \"An unspecified error occurred\"\n+ def __init__(self, msg=None, exit_code=1):\n+ \"\"\"\n+ Initialize a new CfnLintExitException instance with the specified exit code.\n+\n+ Args:\n+ exit_code (int): The exit code to be used when the linter exits.\n+ \"\"\"\n+ if msg is None:\n+ msg = f\"process failed with exit code {exit_code}\"\n+ super().__init__(msg)\n+ self.exit_code = exit_code\n+\n+\n+class InvalidRegionException(CfnLintExitException):\n+ \"\"\"\n+ An exception that is raised when an invalid AWS region is encountered.\n \n- def __init__(self, **kwargs):\n- msg = self.fmt.format(**kwargs)\n- Exception.__init__(self, msg)\n- self.kwargs = kwargs\n+ This exception is raised when the CloudFormation linter encounters a resource\n+ or parameter that references an AWS region that is not valid or supported.\n+ \"\"\"\n+\n+\n+class UnexpectedRuleException(CfnLintExitException):\n+ \"\"\"\n+ An exception that is raised when an unexpected error occurs while loading rules.\n+\n+ This exception is raised when the CloudFormation linter encounters an error\n+ while attempting to load custom rules or rules from a specified directory or\n+ module. This could be due to a variety of reasons, such as a missing file,\n+ a syntax error in the rule code, or an issue with the rule implementation.\n+ \"\"\"\n \n \n-class DuplicateRuleError(CfnLintError):\n+class DuplicateRuleError(CfnLintExitException):\n \"\"\"\n The data associated with a particular path could not be loaded.\n :ivar data_path: The data path that the user attempted to load.\n \"\"\"\n \n- fmt = \"Rule already included: {rule_id}\"\n+ def __init__(self, rule_id: str):\n+ super().__init__(f\"Rule already included: {rule_id}\")\ndiff --git a/src/cfnlint/runner.py b/src/cfnlint/runner.py\nindex 6b8acabd5..a334fba12 100644\n--- a/src/cfnlint/runner.py\n+++ b/src/cfnlint/runner.py\n@@ -15,6 +15,11 @@ import cfnlint.formatters\n import cfnlint.maintenance\n from cfnlint.config import ConfigMixIn, configure_logging\n from cfnlint.decode.decode import decode\n+from cfnlint.exceptions import (\n+ CfnLintExitException,\n+ InvalidRegionException,\n+ UnexpectedRuleException,\n+)\n from cfnlint.helpers import REGIONS\n from cfnlint.rules import Match, Rules\n from cfnlint.rules.errors import ConfigError, ParseError, TransformError\n@@ -452,55 +457,10 @@ class Runner:\n \n \n def main() -> None:\n- config = ConfigMixIn(sys.argv[1:])\n+ try:\n+ config = ConfigMixIn(sys.argv[1:])\n+ except Exception as e:\n+ print(e)\n+ sys.exit(1)\n runner = Runner(config)\n runner.cli()\n-\n-\n-class CfnLintExitException(Exception):\n- \"\"\"\n- An exception that is raised to indicate that the CloudFormation linter should exit.\n-\n- This exception is used to signal that the linter should exit\n- with a specific exit code, typically indicating the severity\n- of the issues found in the CloudFormation template.\n-\n- Attributes:\n- exit_code (int): The exit code to be used when the linter exits.\n-\n- Methods:\n- __init__(self, exit_code: int) -> None:\n- Initialize a new CfnLintExitException instance with the specified exit code.\n- \"\"\"\n-\n- def __init__(self, msg=None, exit_code=1):\n- \"\"\"\n- Initialize a new CfnLintExitException instance with the specified exit code.\n-\n- Args:\n- exit_code (int): The exit code to be used when the linter exits.\n- \"\"\"\n- if msg is None:\n- msg = f\"process failed with exit code {exit_code}\"\n- super().__init__(msg)\n- self.exit_code = exit_code\n-\n-\n-class InvalidRegionException(CfnLintExitException):\n- \"\"\"\n- An exception that is raised when an invalid AWS region is encountered.\n-\n- This exception is raised when the CloudFormation linter encounters a resource\n- or parameter that references an AWS region that is not valid or supported.\n- \"\"\"\n-\n-\n-class UnexpectedRuleException(CfnLintExitException):\n- \"\"\"\n- An exception that is raised when an unexpected error occurs while loading rules.\n-\n- This exception is raised when the CloudFormation linter encounters an error\n- while attempting to load custom rules or rules from a specified directory or\n- module. This could be due to a variety of reasons, such as a missing file,\n- a syntax error in the rule code, or an issue with the rule implementation.\n- \"\"\"\n", "test_patch": "diff --git a/test/unit/module/config/test_config_file_args.py b/test/unit/module/config/test_config_file_args.py\nindex 86144086c..2541f599d 100644\n--- a/test/unit/module/config/test_config_file_args.py\n+++ b/test/unit/module/config/test_config_file_args.py\n@@ -8,7 +8,7 @@ from pathlib import Path\n from test.testlib.testcase import BaseTestCase\n from unittest.mock import patch\n \n-import cfnlint.config # pylint: disable=E0401\n+import cfnlint.config\n from cfnlint.jsonschema import ValidationError\n \n LOGGER = logging.getLogger(\"cfnlint\")\ndiff --git a/test/unit/module/runner/test_rule_configuration.py b/test/unit/module/runner/test_rule_configuration.py\nindex 444ad341e..7a58e8b99 100644\n--- a/test/unit/module/runner/test_rule_configuration.py\n+++ b/test/unit/module/runner/test_rule_configuration.py\n@@ -7,7 +7,8 @@ import os\n from test.testlib.testcase import BaseTestCase\n \n from cfnlint.config import ConfigMixIn\n-from cfnlint.runner import Runner, UnexpectedRuleException\n+from cfnlint.exceptions import UnexpectedRuleException\n+from cfnlint.runner import Runner\n \n \n class TestGetRules(BaseTestCase):\n", "FAIL_TO_PASS": ["test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_bad_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_config_rules", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yaml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config_only_one_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_merge", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_directory", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_module", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_invalid_rule"]}], "all_FAIL_TO_PASS": ["test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_bad_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_config_rules", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yaml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config_only_one_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_merge", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_directory", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_module", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_invalid_rule"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "neurodatawithoutborders__pynwb-814_x1", "level": 1, "source": "swerebenchv2", "repo": "NeurodataWithoutBorders/pynwb", "image": "swerebenchv2/neurodatawithoutborders-pynwb:814-c0a0724", "base_commit": "c0a072421d121cf0e4b6db4d02d64d2d6725df5a", "num_bugs": 1, "bugs": [{"instance_id": "neurodatawithoutborders__pynwb-814", "base_commit": "c0a072421d121cf0e4b6db4d02d64d2d6725df5a", "gold_patch": "diff --git a/src/pynwb/core.py b/src/pynwb/core.py\nindex b128fc46..5f7c713a 100644\n--- a/src/pynwb/core.py\n+++ b/src/pynwb/core.py\n@@ -1240,7 +1240,10 @@ class DynamicTable(NWBDataInterface):\n data = {}\n for name in self.colnames:\n col = self.__df_cols[self.__colids[name]]\n- data[name] = col[:]\n+ if isinstance(col.data, np.ndarray) and col.data.ndim > 1:\n+ data[name] = [x for x in col[:]]\n+ else:\n+ data[name] = col[:]\n \n return pd.DataFrame(data, index=pd.Index(name=self.id.name, data=self.id.data))\n \n", "test_patch": "diff --git a/tests/unit/pynwb_tests/test_core.py b/tests/unit/pynwb_tests/test_core.py\nindex c8a6df7f..5c0dc791 100644\n--- a/tests/unit/pynwb_tests/test_core.py\n+++ b/tests/unit/pynwb_tests/test_core.py\n@@ -1,6 +1,8 @@\n from datetime import datetime\n \n+import numpy as np\n import pandas as pd\n+from pandas.util.testing import assert_frame_equal\n import unittest2 as unittest\n from dateutil.tz import tzlocal\n from pynwb import NWBFile, TimeSeries, available_namespaces\n@@ -207,6 +209,14 @@ class TestDynamicTable(unittest.TestCase):\n dynamic_table_region = DynamicTableRegion('dtr', [0, 1], 'desc', table=table)\n assert dynamic_table_region[slice(0, 1)]\n \n+ def test_nd_array_to_df(self):\n+ data = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])\n+ col = VectorData(name='name', description='desc', data=data)\n+ df = DynamicTable('test', 'desc', np.arange(3, dtype='int'), (col, )).to_dataframe()\n+ df2 = pd.DataFrame({'name': [x for x in data]},\n+ index=pd.Index(name='id', data=[0, 1, 2]))\n+ assert_frame_equal(df, df2)\n+\n \n class TestNWBTable(unittest.TestCase):\n \n", "FAIL_TO_PASS": ["tests/unit/pynwb_tests/test_core.py::TestDynamicTable::test_nd_array_to_df"]}], "all_FAIL_TO_PASS": ["tests/unit/pynwb_tests/test_core.py::TestDynamicTable::test_nd_array_to_df"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "modin-project__modin-6751_x1", "level": 1, "source": "swerebenchv2", "repo": "modin-project/modin", "image": "swerebenchv2/modin-project-modin:6751-adfd2bb", "base_commit": "adfd2bb3b1347a618039e28ae3504a7d808b792f", "num_bugs": 1, "bugs": [{"instance_id": "modin-project__modin-6751", "base_commit": "adfd2bb3b1347a618039e28ae3504a7d808b792f", "gold_patch": "diff --git a/modin/core/dataframe/pandas/dataframe/dataframe.py b/modin/core/dataframe/pandas/dataframe/dataframe.py\nindex 7031b269..b9a57271 100644\n--- a/modin/core/dataframe/pandas/dataframe/dataframe.py\n+++ b/modin/core/dataframe/pandas/dataframe/dataframe.py\n@@ -1323,11 +1323,13 @@ class PandasDataframe(ClassLogger):\n if \"index\" not in self.columns\n else \"level_{}\".format(0)\n ]\n- new_dtypes = None\n- if self.has_materialized_dtypes:\n- names = tuple(level_names) if len(level_names) > 1 else level_names[0]\n- new_dtypes = self.index.to_frame(name=names).dtypes\n- new_dtypes = pandas.concat([new_dtypes, self.dtypes])\n+ names = tuple(level_names) if len(level_names) > 1 else level_names[0]\n+ new_dtypes = self.index.to_frame(name=names).dtypes\n+ try:\n+ new_dtypes = ModinDtypes.concat([new_dtypes, self._dtypes])\n+ except NotImplementedError:\n+ # can raise on duplicated labels\n+ new_dtypes = None\n \n # We will also use the `new_column_names` in the calculation of the internal metadata, so this is a\n # lightweight way of ensuring the metadata matches.\n@@ -2587,7 +2589,7 @@ class PandasDataframe(ClassLogger):\n return df\n \n # If this df is empty, we don't want to try and shuffle or sort.\n- if len(self.get_axis(0)) == 0 or len(self.get_axis(1)) == 0:\n+ if len(self.get_axis(1)) == 0 or len(self) == 0:\n return self.copy()\n \n axis = Axis(axis)\ndiff --git a/modin/core/dataframe/pandas/metadata/dtypes.py b/modin/core/dataframe/pandas/metadata/dtypes.py\nindex fc6cc211..ffd81eb7 100644\n--- a/modin/core/dataframe/pandas/metadata/dtypes.py\n+++ b/modin/core/dataframe/pandas/metadata/dtypes.py\n@@ -260,13 +260,15 @@ class DtypesDescriptor:\n DtypesDescriptor\n \"\"\"\n return type(self)(\n- self._known_dtypes.copy(),\n- self._cols_with_unknown_dtypes.copy(),\n- self._remaining_dtype,\n- self._parent_df,\n- columns_order=None\n- if self.columns_order is None\n- else self.columns_order.copy(),\n+ # should access '.columns_order' first, as it may compute columns order\n+ # and complete the metadata for 'self'\n+ columns_order=(\n+ None if self.columns_order is None else self.columns_order.copy()\n+ ),\n+ known_dtypes=self._known_dtypes.copy(),\n+ cols_with_unknown_dtypes=self._cols_with_unknown_dtypes.copy(),\n+ remaining_dtype=self._remaining_dtype,\n+ parent_df=self._parent_df,\n know_all_names=self._know_all_names,\n _schema_is_known=self._schema_is_known,\n )\n@@ -646,7 +648,16 @@ class ModinDtypes:\n else:\n raise NotImplementedError(type(val))\n \n- desc = DtypesDescriptor.concat(preprocessed_vals)\n+ try:\n+ desc = DtypesDescriptor.concat(preprocessed_vals)\n+ except NotImplementedError as e:\n+ # 'DtypesDescriptor' doesn't support duplicated labels, however, if all values are pandas Serieses,\n+ # we still can perform concatenation using pure pandas\n+ if \"duplicated\" not in e.args[0].lower() or not all(\n+ isinstance(val, pandas.Series) for val in values\n+ ):\n+ raise e\n+ desc = pandas.concat(values)\n return ModinDtypes(desc)\n \n def set_index(self, new_index: Union[pandas.Index, \"ModinIndex\"]) -> \"ModinDtypes\":\ndiff --git a/modin/core/storage_formats/pandas/query_compiler.py b/modin/core/storage_formats/pandas/query_compiler.py\nindex ba907a8b..0565a7d1 100644\n--- a/modin/core/storage_formats/pandas/query_compiler.py\n+++ b/modin/core/storage_formats/pandas/query_compiler.py\n@@ -58,6 +58,7 @@ from modin.core.dataframe.algebra.default2pandas.groupby import (\n SeriesGroupByDefault,\n )\n from modin.core.dataframe.base.dataframe.utils import join_columns\n+from modin.core.dataframe.pandas.metadata import ModinDtypes\n from modin.core.storage_formats.base.query_compiler import BaseQueryCompiler\n from modin.error_message import ErrorMessage\n from modin.utils import (\n@@ -719,10 +720,20 @@ class PandasQueryCompiler(BaseQueryCompiler):\n df.index = pandas.RangeIndex(start, stop)\n return df\n \n- if self._modin_frame.has_columns_cache and kwargs[\"drop\"]:\n- new_columns = self._modin_frame.copy_columns_cache(copy_lengths=True)\n+ new_columns = None\n+ if kwargs[\"drop\"]:\n+ dtypes = self._modin_frame.copy_dtypes_cache()\n+ if self._modin_frame.has_columns_cache:\n+ new_columns = self._modin_frame.copy_columns_cache(\n+ copy_lengths=True\n+ )\n else:\n- new_columns = None\n+ # concat index dtypes (None, since they're unknown) with column dtypes\n+ try:\n+ dtypes = ModinDtypes.concat([None, self._modin_frame._dtypes])\n+ except NotImplementedError:\n+ # may raise on duplicated names in materialized 'self.dtypes'\n+ dtypes = None\n \n return self.__constructor__(\n self._modin_frame.apply_full_axis(\n@@ -730,9 +741,7 @@ class PandasQueryCompiler(BaseQueryCompiler):\n func=_reset,\n enumerate_partitions=True,\n new_columns=new_columns,\n- dtypes=(\n- self._modin_frame._dtypes if kwargs.get(\"drop\", False) else None\n- ),\n+ dtypes=dtypes,\n sync_labels=False,\n pass_axis_lengths_to_partitions=True,\n )\n", "test_patch": "diff --git a/modin/test/storage_formats/pandas/test_internals.py b/modin/test/storage_formats/pandas/test_internals.py\nindex b459f050..5279614b 100644\n--- a/modin/test/storage_formats/pandas/test_internals.py\n+++ b/modin/test/storage_formats/pandas/test_internals.py\n@@ -21,6 +21,7 @@ import pytest\n \n import modin.pandas as pd\n from modin.config import Engine, ExperimentalGroupbyImpl, MinPartitionSize, NPartitions\n+from modin.core.dataframe.pandas.dataframe.dataframe import PandasDataframe\n from modin.core.dataframe.pandas.dataframe.utils import ColumnInfo, ShuffleSortFunctions\n from modin.core.dataframe.pandas.metadata import (\n DtypesDescriptor,\n@@ -1814,6 +1815,24 @@ class TestModinDtypes:\n )\n assert res.equals(exp)\n \n+ def test_ModinDtypes_duplicated_concat(self):\n+ # test that 'ModinDtypes' is able to perform dtypes concatenation on duplicated labels\n+ # if all of them are Serieses\n+ res = ModinDtypes.concat([pandas.Series([np.dtype(int)], index=[\"a\"])] * 2)\n+ assert isinstance(res._value, pandas.Series)\n+ assert res._value.equals(\n+ pandas.Series([np.dtype(int), np.dtype(int)], index=[\"a\", \"a\"])\n+ )\n+\n+ # test that 'ModinDtypes.concat' with duplicated labels raises when not all dtypes are materialized\n+ with pytest.raises(NotImplementedError):\n+ res = ModinDtypes.concat(\n+ [\n+ pandas.Series([np.dtype(int)], index=[\"a\"]),\n+ DtypesDescriptor(cols_with_unknown_dtypes=[\"a\"]),\n+ ]\n+ )\n+\n def test_update_parent(self):\n \"\"\"\n Test that updating parents in ``DtypesDescriptor`` also propagates to stored lazy categoricals.\n@@ -1947,8 +1966,6 @@ class TestZeroComputationDtypes:\n \"\"\"\n \n def test_get_dummies_case(self):\n- from modin.core.dataframe.pandas.dataframe.dataframe import PandasDataframe\n-\n with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n df = pd.DataFrame(\n {\"items\": [1, 2, 3, 4], \"b\": [3, 3, 4, 4], \"c\": [1, 0, 0, 1]}\n@@ -1960,3 +1977,91 @@ class TestZeroComputationDtypes:\n assert res._query_compiler._modin_frame.has_materialized_dtypes\n \n patch.assert_not_called()\n+\n+ @pytest.mark.parametrize(\"has_materialized_index\", [True, False])\n+ @pytest.mark.parametrize(\"drop\", [True, False])\n+ def test_preserve_dtypes_reset_index(self, drop, has_materialized_index):\n+ with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n+ # case 1: 'df' has complete dtype by default\n+ df = pd.DataFrame({\"a\": [1, 2, 3]})\n+ if has_materialized_index:\n+ assert df._query_compiler._modin_frame.has_materialized_index\n+ else:\n+ df._query_compiler._modin_frame.set_index_cache(None)\n+ assert not df._query_compiler._modin_frame.has_materialized_index\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+\n+ res = df.reset_index(drop=drop)\n+ if drop:\n+ # we droped the index, so columns and dtypes shouldn't change\n+ assert res._query_compiler._modin_frame.has_materialized_dtypes\n+ assert res.dtypes.equals(df.dtypes)\n+ else:\n+ if has_materialized_index:\n+ # we should have inserted index dtype into the descriptor,\n+ # and since both of them are materialized, the result should be\n+ # materialized too\n+ assert res._query_compiler._modin_frame.has_materialized_dtypes\n+ assert res.dtypes.equals(\n+ pandas.Series(\n+ [np.dtype(int), np.dtype(int)], index=[\"index\", \"a\"]\n+ )\n+ )\n+ else:\n+ # we now know that there are cols with unknown name and dtype in our dataframe,\n+ # so the resulting dtypes should contain information only about original column\n+ expected_dtypes = DtypesDescriptor(\n+ {\"a\": np.dtype(int)},\n+ know_all_names=False,\n+ )\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ expected_dtypes\n+ )\n+\n+ # case 2: 'df' has partial dtype by default\n+ df = pd.DataFrame({\"a\": [1, 2, 3], \"b\": [3, 4, 5]})\n+ df._query_compiler._modin_frame.set_dtypes_cache(\n+ ModinDtypes(\n+ DtypesDescriptor(\n+ {\"a\": np.dtype(int)}, cols_with_unknown_dtypes=[\"b\"]\n+ )\n+ )\n+ )\n+ if has_materialized_index:\n+ assert df._query_compiler._modin_frame.has_materialized_index\n+ else:\n+ df._query_compiler._modin_frame.set_index_cache(None)\n+ assert not df._query_compiler._modin_frame.has_materialized_index\n+\n+ res = df.reset_index(drop=drop)\n+ if drop:\n+ # we droped the index, so columns and dtypes shouldn't change\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ df._query_compiler._modin_frame._dtypes._value\n+ )\n+ else:\n+ if has_materialized_index:\n+ # we should have inserted index dtype into the descriptor,\n+ # the resulted dtype should have information about 'index' and 'a' columns,\n+ # and miss dtype info for 'b' column\n+ expected_dtypes = DtypesDescriptor(\n+ {\"index\": np.dtype(int), \"a\": np.dtype(int)},\n+ cols_with_unknown_dtypes=[\"b\"],\n+ columns_order={0: \"index\", 1: \"a\", 2: \"b\"},\n+ )\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ expected_dtypes\n+ )\n+ else:\n+ # we miss info about the 'index' column since it wasn't materialized at\n+ # the time of 'reset_index()' and we're still missing dtype info for 'b' column\n+ expected_dtypes = DtypesDescriptor(\n+ {\"a\": np.dtype(int)},\n+ cols_with_unknown_dtypes=[\"b\"],\n+ know_all_names=False,\n+ )\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ expected_dtypes\n+ )\n+\n+ patch.assert_not_called()\n", "FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestModinDtypes::test_ModinDtypes_duplicated_concat", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-True]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-False]"]}], "all_FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestModinDtypes::test_ModinDtypes_duplicated_concat", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-True]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-False]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "modin-project__modin-6757_x1", "level": 1, "source": "swerebenchv2", "repo": "modin-project/modin", "image": "swerebenchv2/modin-project-modin:6757-0ba2a46", "base_commit": "0ba2a46218ecbc6f4b7d0d9e54c25e437e5e0b23", "num_bugs": 1, "bugs": [{"instance_id": "modin-project__modin-6757", "base_commit": "0ba2a46218ecbc6f4b7d0d9e54c25e437e5e0b23", "gold_patch": "diff --git a/modin/core/dataframe/pandas/dataframe/dataframe.py b/modin/core/dataframe/pandas/dataframe/dataframe.py\nindex b9a57271..88c97843 100644\n--- a/modin/core/dataframe/pandas/dataframe/dataframe.py\n+++ b/modin/core/dataframe/pandas/dataframe/dataframe.py\n@@ -2804,6 +2804,7 @@ class PandasDataframe(ClassLogger):\n new_index=None,\n new_columns=None,\n keep_remaining=False,\n+ new_dtypes=None,\n ):\n \"\"\"\n Apply a function across an entire axis for a subset of the data.\n@@ -2826,6 +2827,10 @@ class PandasDataframe(ClassLogger):\n advance, and if not provided it must be computed.\n keep_remaining : boolean, default: False\n Whether or not to drop the data that is not computed over.\n+ new_dtypes : ModinDtypes or pandas.Series, optional\n+ The data types of the result. This is an optimization\n+ because there are functions that always result in a particular data\n+ type, and allows us to avoid (re)computing it.\n \n Returns\n -------\n@@ -2854,7 +2859,9 @@ class PandasDataframe(ClassLogger):\n new_index = self.index if axis == 1 else None\n if new_columns is None:\n new_columns = self.columns if axis == 0 else None\n- return self.__constructor__(new_partitions, new_index, new_columns, None, None)\n+ return self.__constructor__(\n+ new_partitions, new_index, new_columns, None, None, dtypes=new_dtypes\n+ )\n \n @lazy_metadata_decorator(apply_axis=\"both\")\n def apply_select_indices(\ndiff --git a/modin/core/storage_formats/pandas/query_compiler.py b/modin/core/storage_formats/pandas/query_compiler.py\nindex 0565a7d1..a6b9fd1a 100644\n--- a/modin/core/storage_formats/pandas/query_compiler.py\n+++ b/modin/core/storage_formats/pandas/query_compiler.py\n@@ -58,7 +58,7 @@ from modin.core.dataframe.algebra.default2pandas.groupby import (\n SeriesGroupByDefault,\n )\n from modin.core.dataframe.base.dataframe.utils import join_columns\n-from modin.core.dataframe.pandas.metadata import ModinDtypes\n+from modin.core.dataframe.pandas.metadata import DtypesDescriptor, ModinDtypes\n from modin.core.storage_formats.base.query_compiler import BaseQueryCompiler\n from modin.error_message import ErrorMessage\n from modin.utils import (\n@@ -3112,6 +3112,23 @@ class PandasQueryCompiler(BaseQueryCompiler):\n df.insert(internal_idx, column, value)\n return df\n \n+ if hasattr(value, \"dtype\"):\n+ value_dtype = value.dtype\n+ elif is_scalar(value):\n+ value_dtype = np.dtype(type(value))\n+ else:\n+ value_dtype = np.array(value).dtype\n+\n+ new_columns = self.columns.insert(loc, column)\n+ new_dtypes = ModinDtypes.concat(\n+ [\n+ self._modin_frame._dtypes,\n+ DtypesDescriptor({column: value_dtype}, cols_with_unknown_dtypes=[]),\n+ ]\n+ ).lazy_get(\n+ new_columns\n+ ) # get dtypes in a proper order\n+\n # TODO: rework by passing list-like values to `apply_select_indices`\n # as an item to distribute\n new_modin_frame = self._modin_frame.apply_full_axis_select_indices(\n@@ -3120,7 +3137,8 @@ class PandasQueryCompiler(BaseQueryCompiler):\n numeric_indices=[loc],\n keep_remaining=True,\n new_index=self.index,\n- new_columns=self.columns.insert(loc, column),\n+ new_columns=new_columns,\n+ new_dtypes=new_dtypes,\n )\n return self.__constructor__(new_modin_frame)\n \n", "test_patch": "diff --git a/modin/test/storage_formats/pandas/test_internals.py b/modin/test/storage_formats/pandas/test_internals.py\nindex 5279614b..243a496c 100644\n--- a/modin/test/storage_formats/pandas/test_internals.py\n+++ b/modin/test/storage_formats/pandas/test_internals.py\n@@ -1965,6 +1965,61 @@ class TestZeroComputationDtypes:\n Test cases that shouldn't trigger dtypes computation during their execution.\n \"\"\"\n \n+ @pytest.mark.parametrize(\"self_dtype\", [\"materialized\", \"partial\", \"unknown\"])\n+ @pytest.mark.parametrize(\n+ \"value, value_dtype\",\n+ [\n+ [3.5, np.dtype(float)],\n+ [[3.5, 2.4], np.dtype(float)],\n+ [np.array([3.5, 2.4]), np.dtype(float)],\n+ [pd.Series([3.5, 2.4]), np.dtype(float)],\n+ ],\n+ )\n+ def test_preserve_dtypes_insert(self, self_dtype, value, value_dtype):\n+ with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n+ df = pd.DataFrame({\"a\": [1, 2], \"b\": [3, 4]})\n+ if self_dtype == \"materialized\":\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+ elif self_dtype == \"partial\":\n+ df._query_compiler._modin_frame.set_dtypes_cache(\n+ ModinDtypes(\n+ DtypesDescriptor(\n+ {\"a\": np.dtype(int)}, cols_with_unknown_dtypes=[\"b\"]\n+ )\n+ )\n+ )\n+ elif self_dtype == \"unknown\":\n+ df._query_compiler._modin_frame.set_dtypes_cache(None)\n+ else:\n+ raise NotImplementedError(self_dtype)\n+\n+ df.insert(loc=0, column=\"c\", value=value)\n+\n+ if self_dtype == \"materialized\":\n+ result_dtype = pandas.Series(\n+ [value_dtype, np.dtype(int), np.dtype(int)], index=[\"c\", \"a\", \"b\"]\n+ )\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+ assert df.dtypes.equals(result_dtype)\n+ elif self_dtype == \"partial\":\n+ result_dtype = DtypesDescriptor(\n+ {\"a\": np.dtype(int), \"c\": value_dtype},\n+ cols_with_unknown_dtypes=[\"b\"],\n+ columns_order={0: \"c\", 1: \"a\", 2: \"b\"},\n+ )\n+ df._query_compiler._modin_frame._dtypes._value.equals(result_dtype)\n+ elif self_dtype == \"unknown\":\n+ result_dtype = DtypesDescriptor(\n+ {\"c\": value_dtype},\n+ cols_with_unknown_dtypes=[\"a\", \"b\"],\n+ columns_order={0: \"c\", 1: \"a\", 2: \"b\"},\n+ )\n+ df._query_compiler._modin_frame._dtypes._value.equals(result_dtype)\n+ else:\n+ raise NotImplementedError(self_dtype)\n+\n+ patch.assert_not_called()\n+\n def test_get_dummies_case(self):\n with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n df = pd.DataFrame(\n", "FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_insert[3.5-value_dtype0-materialized]"]}], "all_FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_insert[3.5-value_dtype0-materialized]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tornadoweb__tornado-3488_x1", "level": 1, "source": "swerebenchv2", "repo": "tornadoweb/tornado", "image": "swerebenchv2/tornadoweb-tornado:3488-1a8c152", "base_commit": "1a8c15283af6bfc5b5944a3f2c6df4ff067e56a7", "num_bugs": 1, "bugs": [{"instance_id": "tornadoweb__tornado-3488", "base_commit": "1a8c15283af6bfc5b5944a3f2c6df4ff067e56a7", "gold_patch": "diff --git a/tornado/httputil.py b/tornado/httputil.py\nindex 0f443cdd..5d05cacb 100644\n--- a/tornado/httputil.py\n+++ b/tornado/httputil.py\n@@ -248,7 +248,7 @@ class HTTPHeaders(StrMutableMapping):\n if not line:\n # Empty line, or the final CRLF of a header block.\n return\n- if line[0].isspace():\n+ if line[0] in HTTP_WHITESPACE:\n # continuation of a multi-line header\n # TODO(7.0): Remove support for line folding.\n if self._last_key is None:\n", "test_patch": "diff --git a/tornado/test/httputil_test.py b/tornado/test/httputil_test.py\nindex 53ae4607..221c1dcb 100644\n--- a/tornado/test/httputil_test.py\n+++ b/tornado/test/httputil_test.py\n@@ -287,13 +287,22 @@ Foo: even\n [(\"Asdf\", \"qwer zxcv\"), (\"Foo\", \"bar baz\"), (\"Foo\", \"even more lines\")],\n )\n \n- def test_malformed_continuation(self):\n+ def test_continuation(self):\n+ data = \"Foo: bar\\r\\n\\tasdf\"\n+ headers = HTTPHeaders.parse(data)\n+ self.assertEqual(headers[\"Foo\"], \"bar asdf\")\n+\n # If the first line starts with whitespace, it's a\n # continuation line with nothing to continue, so reject it\n # (with a proper error).\n data = \" Foo: bar\"\n self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n \n+ # \\f (formfeed) is whitespace according to str.isspace, but\n+ # not according to the HTTP spec.\n+ data = \"Foo: bar\\r\\n\\fasdf\"\n+ self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n+\n def test_unicode_newlines(self):\n # Ensure that only \\r\\n is recognized as a header separator, and not\n # the other newline-like unicode characters.\n", "FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_continuation"]}], "all_FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_continuation"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "enthought__traits-1550_x1", "level": 1, "source": "swerebenchv2", "repo": "enthought/traits", "image": "swerebenchv2/enthought-traits:1550-eb62eb6", "base_commit": "eb62eb6aa0eb30ff4540c1d07cfb36bdeccfe946", "num_bugs": 1, "bugs": [{"instance_id": "enthought__traits-1550", "base_commit": "eb62eb6aa0eb30ff4540c1d07cfb36bdeccfe946", "gold_patch": "diff --git a/traits/has_traits.py b/traits/has_traits.py\nindex 883619b3..12d3cee6 100644\n--- a/traits/has_traits.py\n+++ b/traits/has_traits.py\n@@ -36,7 +36,7 @@ from .traits import (\n Trait,\n generic_trait,\n )\n-from .trait_types import Any, Bool, Disallow, Event, Python\n+from .trait_types import Any, Bool, Disallow, Event, Python, Str\n from .trait_notifiers import (\n ExtendedTraitChangeNotifyWrapper,\n FastUITraitChangeNotifyWrapper,\n@@ -417,13 +417,25 @@ class MetaHasTraits(type):\n \n If the class name is the empty string then the listener will be called\n when *any* class is created.\n+\n+ .. deprecated:: 6.3.0\n \"\"\"\n+ warnings.warn(\n+ \"add_listener is deprecated\", DeprecationWarning, stacklevel=2\n+ )\n+\n MetaHasTraits._listeners.setdefault(class_name, []).append(listener)\n \n @classmethod\n def remove_listener(cls, listener, class_name=\"\"):\n \"\"\" Removes a class creation listener.\n+\n+ .. deprecated:: 6.3.0\n \"\"\"\n+ warnings.warn(\n+ \"remove_listener is deprecated\", DeprecationWarning, stacklevel=2\n+ )\n+\n MetaHasTraits._listeners[class_name].remove(listener)\n \n \n@@ -1111,12 +1123,13 @@ class HasTraits(CHasTraits, metaclass=MetaHasTraits):\n \n # -- Trait Definitions ----------------------------------------------------\n \n- #: An event fired when a new trait is dynamically added to the object\n- trait_added = Event(str)\n+ #: An event fired when a new trait is dynamically added to the object. The\n+ #: value is the name of the trait that was added.\n+ trait_added = Event(Str())\n \n #: An event that can be fired to indicate that the state of the object has\n- #: been modified\n- trait_modified = Event\n+ #: been modified.\n+ trait_modified = Event()\n \n def _trait_added_changed(self, name):\n \"\"\" Handles a 'trait_added' event being fired.\n", "test_patch": "diff --git a/traits/tests/test_has_traits.py b/traits/tests/test_has_traits.py\nindex e94432f7..5e39f9e2 100644\n--- a/traits/tests/test_has_traits.py\n+++ b/traits/tests/test_has_traits.py\n@@ -26,6 +26,7 @@ from traits.has_traits import (\n SingletonHasTraits,\n SingletonHasStrictTraits,\n SingletonHasPrivateTraits,\n+ MetaHasTraits,\n )\n from traits.ctrait import CTrait\n from traits.observation.api import (\n@@ -55,6 +56,21 @@ def _dummy_validator(self, value):\n pass\n \n \n+class TestMetaHasTraits(unittest.TestCase):\n+ def test_add_listener_and_remove_listener_deprecated(self):\n+ def listener(cls):\n+ pass\n+\n+ with self.assertWarnsRegex(\n+ DeprecationWarning, \"add_listener is deprecated\"\n+ ):\n+ MetaHasTraits.add_listener(listener)\n+ with self.assertWarnsRegex(\n+ DeprecationWarning, \"remove_listener is deprecated\"\n+ ):\n+ MetaHasTraits.remove_listener(listener)\n+\n+\n class TestCreateTraitsMetaDict(unittest.TestCase):\n def test_class_attributes(self):\n # Given\n", "FAIL_TO_PASS": ["traits/tests/test_has_traits.py::TestMetaHasTraits::test_add_listener_and_remove_listener_deprecated"]}], "all_FAIL_TO_PASS": ["traits/tests/test_has_traits.py::TestMetaHasTraits::test_add_listener_and_remove_listener_deprecated"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tornadoweb__tornado-3489_x1", "level": 1, "source": "swerebenchv2", "repo": "tornadoweb/tornado", "image": "swerebenchv2/tornadoweb-tornado:3489-5976db7", "base_commit": "5976db7db6796ea75bfaec9d620b4ba3ff6f2023", "num_bugs": 1, "bugs": [{"instance_id": "tornadoweb__tornado-3489", "base_commit": "5976db7db6796ea75bfaec9d620b4ba3ff6f2023", "gold_patch": "diff --git a/tornado/httputil.py b/tornado/httputil.py\nindex 5d05cacb..7044aca0 100644\n--- a/tornado/httputil.py\n+++ b/tornado/httputil.py\n@@ -33,7 +33,7 @@ import time\n import unicodedata\n from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl\n \n-from tornado.escape import native_str, parse_qs_bytes, utf8\n+from tornado.escape import native_str, parse_qs_bytes, utf8, to_unicode\n from tornado.log import gen_log\n from tornado.util import ObjectDict, unicode_type\n \n@@ -100,6 +100,12 @@ class _ABNF:\n # RFC 9110 (HTTP Semantics)\n obs_text = re.compile(r\"[\\x80-\\xFF]\")\n field_vchar = re.compile(rf\"(?:{VCHAR.pattern}|{obs_text.pattern})\")\n+ # Not exactly from the RFC to simplify and combine field-content and field-value.\n+ field_value = re.compile(\n+ rf\"|\"\n+ rf\"{field_vchar.pattern}|\"\n+ rf\"{field_vchar.pattern}(?:{field_vchar.pattern}| |\\t)*{field_vchar.pattern}\"\n+ )\n tchar = re.compile(r\"[!#$%&'*+\\-.^_`|~0-9A-Za-z]\")\n token = re.compile(rf\"{tchar.pattern}+\")\n field_name = token\n@@ -195,6 +201,10 @@ class HTTPHeaders(StrMutableMapping):\n \"\"\"Adds a new value for the given key.\"\"\"\n if not _ABNF.field_name.fullmatch(name):\n raise HTTPInputError(\"Invalid header name %r\" % name)\n+ if not _ABNF.field_value.fullmatch(to_unicode(value)):\n+ # TODO: the fact we still support bytes here (contrary to type annotations)\n+ # and still test for it should probably be changed.\n+ raise HTTPInputError(\"Invalid header value %r\" % value)\n norm_name = _normalize_header(name)\n self._last_key = norm_name\n if norm_name in self:\n@@ -254,6 +264,8 @@ class HTTPHeaders(StrMutableMapping):\n if self._last_key is None:\n raise HTTPInputError(\"first header line cannot start with whitespace\")\n new_part = \" \" + line.strip(HTTP_WHITESPACE)\n+ if not _ABNF.field_value.fullmatch(new_part[1:]):\n+ raise HTTPInputError(\"Invalid header continuation %r\" % new_part)\n self._as_list[self._last_key][-1] += new_part\n self._dict[self._last_key] += new_part\n else:\n", "test_patch": "diff --git a/tornado/test/httputil_test.py b/tornado/test/httputil_test.py\nindex 221c1dcb..30fbec4d 100644\n--- a/tornado/test/httputil_test.py\n+++ b/tornado/test/httputil_test.py\n@@ -303,6 +303,17 @@ Foo: even\n data = \"Foo: bar\\r\\n\\fasdf\"\n self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n \n+ def test_forbidden_ascii_characters(self):\n+ # Control characters and ASCII whitespace other than space, tab, and CRLF are not allowed in\n+ # headers.\n+ for c in range(0xFF):\n+ data = f\"Foo: bar{chr(c)}baz\\r\\n\"\n+ if c == 0x09 or (c >= 0x20 and c != 0x7F):\n+ headers = HTTPHeaders.parse(data)\n+ self.assertEqual(headers[\"Foo\"], f\"bar{chr(c)}baz\")\n+ else:\n+ self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n+\n def test_unicode_newlines(self):\n # Ensure that only \\r\\n is recognized as a header separator, and not\n # the other newline-like unicode characters.\n@@ -311,10 +322,13 @@ Foo: even\n # and cpython's unicodeobject.c (which defines the implementation\n # of unicode_type.splitlines(), and uses a different list than TR13).\n newlines = [\n- \"\\u001b\", # VERTICAL TAB\n- \"\\u001c\", # FILE SEPARATOR\n- \"\\u001d\", # GROUP SEPARATOR\n- \"\\u001e\", # RECORD SEPARATOR\n+ # The following ascii characters are sometimes treated as newline-like,\n+ # but they're disallowed in HTTP headers. This test covers unicode\n+ # characters that are permitted in headers (under the obs-text rule).\n+ # \"\\u001b\", # VERTICAL TAB\n+ # \"\\u001c\", # FILE SEPARATOR\n+ # \"\\u001d\", # GROUP SEPARATOR\n+ # \"\\u001e\", # RECORD SEPARATOR\n \"\\u0085\", # NEXT LINE\n \"\\u2028\", # LINE SEPARATOR\n \"\\u2029\", # PARAGRAPH SEPARATOR\n@@ -363,13 +377,16 @@ Foo: even\n self.assertEqual(expected, list(headers.get_all()))\n \n def test_optional_cr(self):\n+ # Bare CR is not a valid line separator\n+ with self.assertRaises(HTTPInputError):\n+ HTTPHeaders.parse(\"CRLF: crlf\\r\\nLF: lf\\nCR: cr\\rMore: more\\r\\n\")\n+\n # Both CRLF and LF should be accepted as separators. CR should not be\n- # part of the data when followed by LF, but it is a normal char\n- # otherwise (or should bare CR be an error?)\n- headers = HTTPHeaders.parse(\"CRLF: crlf\\r\\nLF: lf\\nCR: cr\\rMore: more\\r\\n\")\n+ # part of the data when followed by LF.\n+ headers = HTTPHeaders.parse(\"CRLF: crlf\\r\\nLF: lf\\nMore: more\\r\\n\")\n self.assertEqual(\n sorted(headers.get_all()),\n- [(\"Cr\", \"cr\\rMore: more\"), (\"Crlf\", \"crlf\"), (\"Lf\", \"lf\")],\n+ [(\"Crlf\", \"crlf\"), (\"Lf\", \"lf\"), (\"More\", \"more\")],\n )\n \n def test_copy(self):\n", "FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_forbidden_ascii_characters", "tornado/test/httputil_test.py::HTTPHeadersTest::test_optional_cr"]}], "all_FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_forbidden_ascii_characters", "tornado/test/httputil_test.py::HTTPHeadersTest::test_optional_cr"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "rochacbruno__dynaconf-292_x1", "level": 1, "source": "swerebenchv2", "repo": "rochacbruno/dynaconf", "image": "swerebenchv2/rochacbruno-dynaconf:292-b0bc78d", "base_commit": "b0bc78de719fc8c3a0180be9aaea1d233a3dab86", "num_bugs": 1, "bugs": [{"instance_id": "rochacbruno__dynaconf-292", "base_commit": "b0bc78de719fc8c3a0180be9aaea1d233a3dab86", "gold_patch": "diff --git a/Makefile b/Makefile\nindex 62c0e41..2880947 100644\n--- a/Makefile\n+++ b/Makefile\n@@ -14,6 +14,7 @@ test_examples:\n \tcd example/;pwd;python compat.py\n \tcd example/app;pwd;python app.py\n \tcd example/dunder;pwd;python app.py\n+\tcd example/format;pwd;python app.py\n \tcd example/app_with_dotenv;pwd;python app.py\n \tcd example/merge_enabled;pwd;python app.py\n \tcd example/new_merge;pwd;python app.py\ndiff --git a/docs/guides/environment_variables.md b/docs/guides/environment_variables.md\nindex 5c92425..46675b7 100644\n--- a/docs/guides/environment_variables.md\n+++ b/docs/guides/environment_variables.md\n@@ -54,6 +54,14 @@ DYNACONF_NONE='@none None'\n \n # toml syntax does not allow mixed type arrays so use @json\n DYNACONF_ARRAY='@json [42, 3.14, \"hello\", true, [\"otherarray\"], {\"foo\": \"bar\"}]'\n+\n+# Lazily formatted string can access env vars and settings variables.\n+\n+# using str.format\n+DYNACONF_DATABASE_PATH=\"@format {env[HOME]}/.config/databases/{this.DB_NAME}\"\n+\n+# using jinja2\n+DYNACONF_DATABASE_PATH=\"@jinja {{env.HOME}}/.config/databases/{{this.DB_NAME}}\"\n ```\n \n > **NOTE**: Older versions of Dynaconf used the `@casting` prefixes for env vars like `export DYNACONF_INTEGER='@int 123'` still works but this casting is deprecated in favor of using TOML syntax described above. To disable the `@casting` do `export AUTO_CAST_FOR_DYNACONF=false`\ndiff --git a/docs/guides/usage.md b/docs/guides/usage.md\nindex 6cb3890..8cc02dd 100644\n--- a/docs/guides/usage.md\n+++ b/docs/guides/usage.md\n@@ -501,7 +501,85 @@ settings.load_file(path=\"/path/to/file.toml\") # list or `;/,` separated allowed\n \n > **NOTE**: programmatically loaded file is not persisted, once `env` is changed via `setenv|ugin_env`, or a `reload` or `configure` is invoked it will be cleaned, to persist it needs to go to `INCLUDES_FOR_DYNACONF` variable or you need to load it programmatically again.\n \n-## Merging existing values\n+## Template substitutions\n+\n+Dynaconf has 2 tokens to enable string substitutions `@format` and `@jinja`.\n+\n+### @format token\n+\n+Dynaconf allows template substitutions for strings values, by using the `@format` token prefix and including placeholders accepted by Python's `str.format` method Dynaconf will call\n+it lazily upon access time.\n+\n+The call will be like:\n+\n+```py\n+\"\".format(env=os.environ, this=dynaconf.settings)\n+```\n+\n+So in your string you can refer to environment variables via `env` object, and also to variables defined int the settings object itself via `this` reference. It is lazily evaluated on access it will use the final value for a settings regardless the order of load.\n+\n+Example:\n+\n+```bash\n+export PROGRAM_NAME=calculator\n+```\n+\n+settings.toml\n+\n+```toml\n+[default]\n+DB_NAME = \"mydb.db\"\n+\n+[development]\n+DB_PATH = \"@format {env[HOME]}/{this.current_env}/{env[PROGRAM_NAME]}/{this.DB_NAME}\"\n+```\n+\n+- `{env[HOME]}` is the same as `os.environ[\"HOME\"]` or `$HOME` in the shell.\n+- `{this.current_env}` is the same as `settings.current_env`\n+- `{env[PROGRAM_NAME]}` is the same as `os.environ[\"PROGRAM_NAME\"]` or `$PROGRAM_NAME` in the shell.\n+- `{this.DB_NAME}` is the same as `settins.DB_NAME` or `settings[\"DB_NAME\"]`\n+\n+so in your `program`\n+\n+```py\n+from dynaconf import settings\n+\n+settings.DB_PATH == '~/DEVELOPMENT/calculator/mydb.db'\n+```\n+\n+### @jinja token\n+\n+If `jinja2` package is installed then dynaconf will also allow the use jinja to render string values.\n+\n+Example:\n+\n+```bash\n+export PROGRAM_NAME=calculator\n+```\n+\n+settings.toml\n+\n+```toml\n+[default]\n+DB_NAME = \"mydb.db\"\n+\n+[development]\n+DB_PATH = \"@jinja {{env.HOME}}/{{this.current_env | lower}}/{{env['PROGRAM_NAME']}}/{{this.DB_NAME}}\"\n+```\n+\n+so in your `program`\n+\n+```py\n+from dynaconf import settings\n+\n+settings.DB_PATH == '~/development/calculator/mydb.db'\n+```\n+\n+The main difference is that Jinja allows some Python expressions to be avaluated such as `{% for, if, while %}` and also supports calling methods and has lots of filters like `| lower`.\n+\n+Jinja supports its built-in filters listed in [Builtin Filters Page](http://jinja.palletsprojects.com/en/master/templates/#builtin-filters) and Dynaconf includes aditional filters for `os.path` module: `abspath`. `realpath`, `relpath`, `basename` and `dirname` and usage is like: `VALUE = \"@jinja {{this.FOO | abspath}}\"`\n+\n+## Merging existing data structures\n \n If your settings has existing variables of types `list` ot `dict` and you want to `merge` instead of `override` then \n the `dynaconf_merge` and `dynaconf_merge_unique` stanzas can mark that variable as a candidate for merging.\ndiff --git a/dynaconf/base.py b/dynaconf/base.py\nindex db7fef5..b6a96d1 100644\n--- a/dynaconf/base.py\n+++ b/dynaconf/base.py\n@@ -25,6 +25,7 @@ from dynaconf.utils.files import find_file\n from dynaconf.utils.functional import empty\n from dynaconf.utils.functional import LazyObject\n from dynaconf.utils.parse_conf import converters\n+from dynaconf.utils.parse_conf import evaluate_lazy_format\n from dynaconf.utils.parse_conf import parse_conf_data\n from dynaconf.utils.parse_conf import true_values\n from dynaconf.validator import ValidatorList\n@@ -90,6 +91,7 @@ class LazySettings(LazyObject):\n self._kwargs = kwargs\n super(LazySettings, self).__init__()\n \n+ @evaluate_lazy_format\n def __getattr__(self, name):\n \"\"\"Allow getting keys from self.store using dot notation\"\"\"\n if self._wrapped is empty:\n@@ -276,6 +278,7 @@ class Settings(object):\n \".\".join(keys), default=default, parent=result, **kwargs\n )\n \n+ @evaluate_lazy_format\n def get(\n self,\n key,\ndiff --git a/dynaconf/utils/parse_conf.py b/dynaconf/utils/parse_conf.py\nindex d9fc4c5..d33673f 100644\n--- a/dynaconf/utils/parse_conf.py\n+++ b/dynaconf/utils/parse_conf.py\n@@ -1,11 +1,21 @@\n import json\n import os\n+from functools import wraps\n \n import toml\n from box import BoxKeyError\n \n from dynaconf.utils.boxing import DynaBox\n \n+try:\n+ from jinja2 import Environment\n+\n+ jinja_env = Environment()\n+ for p_method in (\"abspath\", \"realpath\", \"relpath\", \"dirname\", \"basename\"):\n+ jinja_env.filters[p_method] = getattr(os.path, p_method)\n+except ImportError: # pragma: no cover\n+ jinja_env = None\n+\n true_values = (\"t\", \"true\", \"enabled\", \"1\", \"on\", \"yes\", \"True\")\n false_values = (\"f\", \"false\", \"disabled\", \"0\", \"off\", \"no\", \"False\", \"\")\n \n@@ -42,13 +52,55 @@ class Merge(MetaValue):\n dynaconf_merge = True\n \n \n+class LazyFormat:\n+ \"\"\"Holds data to format lazily.\"\"\"\n+\n+ dynaconf_lazy_format = True\n+\n+ def __init__(self, value, formatter=str.format):\n+ self.value = value\n+ self.formatter = formatter\n+\n+ @property\n+ def context(self):\n+ \"\"\"Builds a context for formatting.\"\"\"\n+ return {\"env\": os.environ, \"this\": self.settings}\n+\n+ def __call__(self, settings):\n+ \"\"\"LazyValue triggers format lazily.\"\"\"\n+ self.settings = settings\n+ return self.formatter(self.value, **self.context)\n+\n+\n+def evaluate_lazy_format(f):\n+ \"\"\"Marks a method on Settings instance to\n+ lazily evaluate LazyFormat objects upon access.\"\"\"\n+\n+ @wraps(f)\n+ def evaluate(settings, *args, **kwargs):\n+ value = f(settings, *args, **kwargs)\n+ if getattr(value, \"dynaconf_lazy_format\", None):\n+ return value(settings)\n+ return value\n+\n+ return evaluate\n+\n+\n+def jinja_formatter(value, **context):\n+ if jinja_env is None: # pragma: no cover\n+ raise ImportError(\n+ \"jinja2 must be installed to enable '@jinja' settings in dynaconf\"\n+ )\n+ return jinja_env.from_string(value).render(**context)\n+\n+\n converters = {\n \"@int\": int,\n \"@float\": float,\n- \"@bool\": (\n- lambda value: True if str(value).lower() in true_values else False\n- ),\n+ \"@bool\": lambda value: str(value).lower() in true_values,\n \"@json\": json.loads,\n+ \"@format\": lambda value: LazyFormat(value),\n+ \"@jinja\": lambda value: LazyFormat(value, formatter=jinja_formatter),\n # Meta Values to trigger pre assignment actions\n \"@reset\": lambda value: Reset(value),\n \"@del\": lambda value: Del(value),\ndiff --git a/example/format/.env b/example/format/.env\nnew file mode 100644\nindex 0000000..bf7bb51\n--- /dev/null\n+++ b/example/format/.env\n@@ -0,0 +1,1 @@\n+USERNAME='robert_plant'\ndiff --git a/example/format/app.py b/example/format/app.py\nnew file mode 100644\nindex 0000000..234dd3d\n--- /dev/null\n+++ b/example/format/app.py\n@@ -0,0 +1,18 @@\n+import os\n+\n+from dynaconf import settings\n+\n+assert settings.get(\"USERNAME\") is None\n+assert settings.DATABASE_NAME == \"my_database.db\"\n+assert os.environ[\"USERNAME\"] == \"robert_plant\"\n+\n+DB_PATH = \"/home/robert_plant/databases/my_database.db\"\n+assert settings.DATABASE_PATH == DB_PATH, settings.DATABASE_PATH\n+print(settings.DATABASE_PATH)\n+\n+\n+DB_PATH_JINJA = \"/home/robert_plant/development/my_database.db\"\n+assert (\n+ settings.DATABASE_PATH_JINJA == DB_PATH_JINJA\n+), settings.DATABASE_PATH_JINJA\n+print(settings.DATABASE_PATH_JINJA)\ndiff --git a/example/format/settings.toml b/example/format/settings.toml\nnew file mode 100644\nindex 0000000..4b90106\n--- /dev/null\n+++ b/example/format/settings.toml\n@@ -0,0 +1,6 @@\n+[default]\n+database_name = 'my_database.db'\n+\n+[development]\n+database_path = '@format /home/{env[USERNAME]}/databases/{this[database_name]}'\n+database_path_jinja = '@jinja /home/{{env.USERNAME}}/{{this.current_env | lower}}/{{this[\"database_name\"] }}'\n", "test_patch": "diff --git a/tests/test_utils.py b/tests/test_utils.py\nindex 1abc3cd..a5e28a5 100644\n--- a/tests/test_utils.py\n+++ b/tests/test_utils.py\n@@ -12,6 +12,9 @@ from dynaconf.utils import trimmed_split\n from dynaconf.utils import upperfy\n from dynaconf.utils.files import find_file\n from dynaconf.utils.files import get_local_filename\n+from dynaconf.utils.parse_conf import evaluate_lazy_format\n+from dynaconf.utils.parse_conf import jinja_formatter\n+from dynaconf.utils.parse_conf import LazyFormat\n from dynaconf.utils.parse_conf import parse_conf_data\n from dynaconf.utils.parse_conf import unparse_conf_data\n \n@@ -242,3 +245,59 @@ def test_upperfy():\n )\n assert upperfy(\"foo_bar\") == \"FOO_BAR\"\n assert upperfy(\"foo_BAR\") == \"FOO_BAR\"\n+\n+\n+def test_lazy_format_class():\n+ value = LazyFormat(\"{this[FOO]}/bar\")\n+ settings = {\"FOO\": \"foo\"}\n+ assert value(settings) == \"foo/bar\"\n+\n+\n+def test_evaluate_lazy_format_decorator():\n+ class Settings:\n+ FOO = \"foo\"\n+\n+ @evaluate_lazy_format\n+ def get(self):\n+ return parse_conf_data(\"@format {this.FOO}/bar\")\n+\n+ settings = Settings()\n+ assert settings.get() == \"foo/bar\"\n+\n+\n+def test_lazy_format_on_settings(settings):\n+ os.environ[\"ENV_THING\"] = \"LazyFormat\"\n+ settings.set(\"set_1\", \"really\")\n+ settings.set(\"lazy\", \"@format {env[ENV_THING]}/{this[set_1]}/{this.SET_2}\")\n+ settings.set(\"set_2\", \"works\")\n+\n+ assert settings.LAZY == settings.get(\"lazy\") == \"LazyFormat/really/works\"\n+\n+\n+def test_lazy_format_class_jinja():\n+ value = LazyFormat(\"{{this['FOO']}}/bar\", formatter=jinja_formatter)\n+ settings = {\"FOO\": \"foo\"}\n+ assert value(settings) == \"foo/bar\"\n+\n+\n+def test_evaluate_lazy_format_decorator_jinja():\n+ class Settings:\n+ FOO = \"foo\"\n+\n+ @evaluate_lazy_format\n+ def get(self):\n+ return parse_conf_data(\"@jinja {{this.FOO}}/bar\")\n+\n+ settings = Settings()\n+ assert settings.get() == \"foo/bar\"\n+\n+\n+def test_lazy_format_on_settings_jinja(settings):\n+ os.environ[\"ENV_THING\"] = \"LazyFormat\"\n+ settings.set(\"set_1\", \"really\")\n+ settings.set(\n+ \"lazy\", \"@jinja {{env.ENV_THING}}/{{this['set_1']}}/{{this.SET_2}}\"\n+ )\n+ settings.set(\"set_2\", \"works\")\n+\n+ assert settings.LAZY == settings.get(\"lazy\") == \"LazyFormat/really/works\"\n", "FAIL_TO_PASS": ["tests/test_utils.py::test_unparse", "tests/test_utils.py::test_cast_bool", "tests/test_utils.py::test_find_file", "tests/test_utils.py::test_disable_cast", "tests/test_utils.py::test_tomlfy", "tests/test_utils.py::test_tomlfy_unparseable[something=42]", "tests/test_utils.py::test_missing_sentinel", "tests/test_utils.py::test_meta_values", "tests/test_utils.py::test_merge_existing_list", "tests/test_utils.py::test_merge_existing_list_unique", "tests/test_utils.py::test_merge_existing_dict", "tests/test_utils.py::test_merge_dict_with_meta_values", "tests/test_utils.py::test_trimmed_split", "tests/test_utils.py::test_ensure_a_list", "tests/test_utils.py::test_get_local_filename", "tests/test_utils.py::test_upperfy", "tests/test_utils.py::test_lazy_format_class", "tests/test_utils.py::test_evaluate_lazy_format_decorator", "tests/test_utils.py::test_lazy_format_on_settings"]}], "all_FAIL_TO_PASS": ["tests/test_utils.py::test_unparse", "tests/test_utils.py::test_cast_bool", "tests/test_utils.py::test_find_file", "tests/test_utils.py::test_disable_cast", "tests/test_utils.py::test_tomlfy", "tests/test_utils.py::test_tomlfy_unparseable[something=42]", "tests/test_utils.py::test_missing_sentinel", "tests/test_utils.py::test_meta_values", "tests/test_utils.py::test_merge_existing_list", "tests/test_utils.py::test_merge_existing_list_unique", "tests/test_utils.py::test_merge_existing_dict", "tests/test_utils.py::test_merge_dict_with_meta_values", "tests/test_utils.py::test_trimmed_split", "tests/test_utils.py::test_ensure_a_list", "tests/test_utils.py::test_get_local_filename", "tests/test_utils.py::test_upperfy", "tests/test_utils.py::test_lazy_format_class", "tests/test_utils.py::test_evaluate_lazy_format_decorator", "tests/test_utils.py::test_lazy_format_on_settings"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aws-cloudformation__cfn-lint-3900_x1", "level": 1, "source": "swerebenchv2", "repo": "aws-cloudformation/cfn-lint", "image": "swerebenchv2/aws-cloudformation-cfn-lint:3900-3ae3941", "base_commit": "3ae39419c050c54df37dfb79107cd93c3598e116", "num_bugs": 1, "bugs": [{"instance_id": "aws-cloudformation__cfn-lint-3900", "base_commit": "3ae39419c050c54df37dfb79107cd93c3598e116", "gold_patch": "diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py\nindex a9f4aa5e4..244d8df77 100644\n--- a/src/cfnlint/config.py\n+++ b/src/cfnlint/config.py\n@@ -785,9 +785,11 @@ class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n if isinstance(filenames, str):\n filenames = [filenames]\n \n- return self._glob_filenames(filenames)\n+ return self._glob_filenames(filenames, False)\n \n- def _glob_filenames(self, filenames: Sequence[str]) -> list[str]:\n+ def _glob_filenames(\n+ self, filenames: Sequence[str], raise_exception: bool = True\n+ ) -> list[str]:\n # handle different shells and Config files\n # some shells don't expand * and configparser won't expand wildcards\n all_filenames = []\n@@ -796,7 +798,8 @@ class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n add_filenames = glob.glob(filename, recursive=True)\n \n if not add_filenames and not self.ignore_bad_template:\n- raise ValueError(f\"{filename} could not be processed by glob.glob\")\n+ if raise_exception:\n+ raise ValueError(f\"{filename} could not be processed by glob.glob\")\n \n all_filenames.extend(add_filenames)\n \n", "test_patch": "diff --git a/test/unit/module/config/test_config_mixin.py b/test/unit/module/config/test_config_mixin.py\nindex 9e584ead0..cbed4b458 100644\n--- a/test/unit/module/config/test_config_mixin.py\n+++ b/test/unit/module/config/test_config_mixin.py\n@@ -247,6 +247,28 @@ class TestConfigMixIn(BaseTestCase):\n )\n self.assertEqual(len(config.templates), 3)\n \n+ @patch(\"cfnlint.config.ConfigFileArgs._read_config\", create=True)\n+ def test_config_expand_and_ignore_templates_with_bad_path(self, yaml_mock):\n+ \"\"\"Test ignore templates\"\"\"\n+\n+ yaml_mock.side_effect = [\n+ {\n+ \"templates\": [\"test/fixtures/templates/bad/resources/iam/*.yaml\"],\n+ \"ignore_templates\": [\n+ \"dne/fixtures/templates/bad/resources/iam/resource_*.yaml\"\n+ ],\n+ },\n+ {},\n+ ]\n+ config = cfnlint.config.ConfigMixIn([])\n+\n+ # test defaults\n+ self.assertIn(\n+ str(Path(\"test/fixtures/templates/bad/resources/iam/resource_policy.yaml\")),\n+ config.templates,\n+ )\n+ self.assertEqual(len(config.templates), 4)\n+\n @patch(\"cfnlint.config.ConfigFileArgs._read_config\", create=True)\n def test_config_merge(self, yaml_mock):\n \"\"\"Test merging lists\"\"\"\n", "FAIL_TO_PASS": ["test/unit/module/config/test_config_mixin.py::TestConfigMixIn::test_config_expand_and_ignore_templates_with_bad_path"]}], "all_FAIL_TO_PASS": ["test/unit/module/config/test_config_mixin.py::TestConfigMixIn::test_config_expand_and_ignore_templates_with_bad_path"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "robotpy__cxxheaderparser-98_x1", "level": 1, "source": "swerebenchv2", "repo": "robotpy/cxxheaderparser", "image": "swerebenchv2/robotpy-cxxheaderparser:98-7aac68c", "base_commit": "7aac68c1025473bda98141e3ca5fdfde34c45429", "num_bugs": 1, "bugs": [{"instance_id": "robotpy__cxxheaderparser-98", "base_commit": "7aac68c1025473bda98141e3ca5fdfde34c45429", "gold_patch": "diff --git a/.github/workflows/dist.yml b/.github/workflows/dist.yml\nindex 33c3749..175b6e2 100644\n--- a/.github/workflows/dist.yml\n+++ b/.github/workflows/dist.yml\n@@ -83,11 +83,11 @@ jobs:\n runs-on: ${{ matrix.os }}\n strategy:\n matrix:\n- os: [windows-latest, macos-latest, ubuntu-20.04]\n+ os: [windows-latest, macos-13, ubuntu-20.04]\n python_version: [3.6, 3.7, 3.8, 3.9, \"3.10\", \"3.11\", \"3.12\"]\n architecture: [x86, x64]\n exclude:\n- - os: macos-latest\n+ - os: macos-13\n architecture: x86\n - os: ubuntu-20.04\n architecture: x86\ndiff --git a/cxxheaderparser/parser.py b/cxxheaderparser/parser.py\nindex 5bef044..90a7d75 100644\n--- a/cxxheaderparser/parser.py\n+++ b/cxxheaderparser/parser.py\n@@ -1041,7 +1041,9 @@ class CxxParser:\n ) -> None:\n self.state.location = tok.location\n \n- tok = self._next_token_must_be(\"NAME\", \"DBL_COLON\", \"namespace\", \"typename\")\n+ tok = self._next_token_must_be(\n+ \"NAME\", \"DBL_COLON\", \"namespace\", \"typename\", \"enum\"\n+ )\n \n if tok.type == \"namespace\":\n if template:\n", "test_patch": "diff --git a/tests/test_using.py b/tests/test_using.py\nindex 06a355f..de25763 100644\n--- a/tests/test_using.py\n+++ b/tests/test_using.py\n@@ -716,3 +716,64 @@ def test_using_typename_in_class() -> None:\n ]\n )\n )\n+\n+\n+def test_using_enum_global() -> None:\n+ content = \"\"\"\n+ namespace A {\n+ using enum B::C;\n+ }\n+ \"\"\"\n+ data = parse_string(content, cleandoc=True)\n+\n+ assert data == ParsedData(\n+ namespace=NamespaceScope(\n+ namespaces={\n+ \"A\": NamespaceScope(\n+ name=\"A\",\n+ using=[\n+ UsingDecl(\n+ typename=PQName(\n+ segments=[\n+ NameSpecifier(name=\"B\"),\n+ NameSpecifier(name=\"C\"),\n+ ],\n+ classkey=\"enum\",\n+ )\n+ )\n+ ],\n+ )\n+ }\n+ )\n+ )\n+\n+\n+def test_using_enum_in_struct() -> None:\n+ content = \"\"\"\n+ struct S {\n+ using enum fruit;\n+ };\n+ \"\"\"\n+ data = parse_string(content, cleandoc=True)\n+\n+ assert data == ParsedData(\n+ namespace=NamespaceScope(\n+ classes=[\n+ ClassScope(\n+ class_decl=ClassDecl(\n+ typename=PQName(\n+ segments=[NameSpecifier(name=\"S\")], classkey=\"struct\"\n+ )\n+ ),\n+ using=[\n+ UsingDecl(\n+ typename=PQName(\n+ segments=[NameSpecifier(name=\"fruit\")], classkey=\"enum\"\n+ ),\n+ access=\"public\",\n+ )\n+ ],\n+ )\n+ ]\n+ )\n+ )\n", "FAIL_TO_PASS": ["tests/test_using.py::test_using_enum_global", "tests/test_using.py::test_using_enum_in_struct"]}], "all_FAIL_TO_PASS": ["tests/test_using.py::test_using_enum_global", "tests/test_using.py::test_using_enum_in_struct"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "robotpy__cxxheaderparser-100_x1", "level": 1, "source": "swerebenchv2", "repo": "robotpy/cxxheaderparser", "image": "swerebenchv2/robotpy-cxxheaderparser:100-914838c", "base_commit": "914838c970cb138994d08b3f630dcf8150ca5a32", "num_bugs": 1, "bugs": [{"instance_id": "robotpy__cxxheaderparser-100", "base_commit": "914838c970cb138994d08b3f630dcf8150ca5a32", "gold_patch": "diff --git a/cxxheaderparser/lexer.py b/cxxheaderparser/lexer.py\nindex ab3899d..17caf92 100644\n--- a/cxxheaderparser/lexer.py\n+++ b/cxxheaderparser/lexer.py\n@@ -104,9 +104,11 @@ class PlyLexer:\n \"final\",\n \"float\",\n \"for\",\n+ \"__forceinline\",\n \"friend\",\n \"goto\",\n \"if\",\n+ \"__inline\",\n \"inline\",\n \"int\",\n \"long\",\ndiff --git a/cxxheaderparser/parser.py b/cxxheaderparser/parser.py\nindex 90a7d75..41b7a54 100644\n--- a/cxxheaderparser/parser.py\n+++ b/cxxheaderparser/parser.py\n@@ -2371,6 +2371,8 @@ class CxxParser:\n volatile = True\n elif tok_type in _attribute_start:\n self._consume_attribute(tok)\n+ elif tok_type in (\"__inline\", \"__forceinline\"):\n+ both[\"inline\"] = tok\n else:\n break\n \n", "test_patch": "diff --git a/tests/test_fn.py b/tests/test_fn.py\nindex 1a4fb4e..4f67a41 100644\n--- a/tests/test_fn.py\n+++ b/tests/test_fn.py\n@@ -1258,3 +1258,58 @@ def test_method_trailing_return_with_body() -> None:\n ]\n )\n )\n+\n+\n+def test_msvc_inline() -> None:\n+ content = \"\"\"\n+ __inline double fn1() {}\n+ __forceinline double fn2() {}\n+ static __inline double fn3() {}\n+ static __forceinline double fn4() {}\n+ \"\"\"\n+ data = parse_string(content, cleandoc=True)\n+\n+ assert data == ParsedData(\n+ namespace=NamespaceScope(\n+ functions=[\n+ Function(\n+ return_type=Type(\n+ typename=PQName(segments=[FundamentalSpecifier(name=\"double\")])\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"fn1\")]),\n+ parameters=[],\n+ inline=True,\n+ has_body=True,\n+ ),\n+ Function(\n+ return_type=Type(\n+ typename=PQName(segments=[FundamentalSpecifier(name=\"double\")])\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"fn2\")]),\n+ parameters=[],\n+ inline=True,\n+ has_body=True,\n+ ),\n+ Function(\n+ return_type=Type(\n+ typename=PQName(segments=[FundamentalSpecifier(name=\"double\")])\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"fn3\")]),\n+ parameters=[],\n+ static=True,\n+ inline=True,\n+ has_body=True,\n+ ),\n+ Function(\n+ return_type=Type(\n+ typename=PQName(segments=[FundamentalSpecifier(name=\"double\")])\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"fn4\")]),\n+ parameters=[],\n+ static=True,\n+ inline=True,\n+ has_body=True,\n+ ),\n+ ]\n+ )\n+ )\n", "FAIL_TO_PASS": ["tests/test_fn.py::test_msvc_inline"]}], "all_FAIL_TO_PASS": ["tests/test_fn.py::test_msvc_inline"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "enthought__traits-1560_x1", "level": 1, "source": "swerebenchv2", "repo": "enthought/traits", "image": "swerebenchv2/enthought-traits:1560-5c775b4", "base_commit": "5c775b49c4fb7ed10478b9b58e08856406fba7c1", "num_bugs": 1, "bugs": [{"instance_id": "enthought__traits-1560", "base_commit": "5c775b49c4fb7ed10478b9b58e08856406fba7c1", "gold_patch": "diff --git a/docs/source/traits_user_manual/index.rst b/docs/source/traits_user_manual/index.rst\nindex 9ef76d03..81e2042b 100644\n--- a/docs/source/traits_user_manual/index.rst\n+++ b/docs/source/traits_user_manual/index.rst\n@@ -13,6 +13,7 @@ Contents\n :maxdepth: 3\n \n intro.rst\n+ installation.rst\n defining.rst\n notification.rst\n deferring.rst\ndiff --git a/docs/source/traits_user_manual/installation.rst b/docs/source/traits_user_manual/installation.rst\nnew file mode 100644\nindex 00000000..65842ef3\n--- /dev/null\n+++ b/docs/source/traits_user_manual/installation.rst\n@@ -0,0 +1,30 @@\n+.. index:: installation\n+\n+.. _installation:\n+\n+============\n+Installation\n+============\n+\n+The latest release of Traits is available from the Python Package Index (PyPI),\n+and the normal way to install Traits into your Python environment is using\n+pip::\n+\n+ python -m pip install traits\n+\n+Traits includes a C extension module. Binary wheels are provided on PyPI for\n+common platforms, but some platforms may need to compile Traits from source. On\n+those platforms, a suitable C compiler will be needed.\n+\n+\n+Installation from source on macOS\n+---------------------------------\n+\n+The system Python 3.8 on macOS Catalina has trouble installing Traits from\n+source, due to an apparent mismatch in architecture settings. This issue can\n+be worked around by specifying the \"ARCHFLAGS\" environment variable for\n+the install::\n+\n+ ARCHFLAGS=\"-arch x86_64\" python -m pip install traits\n+\n+See https://github.com/enthought/traits/issues/1337 for more details.\ndiff --git a/docs/source/traits_user_manual/listening.rst b/docs/source/traits_user_manual/listening.rst\nindex 274e468f..6ae7fc6f 100644\n--- a/docs/source/traits_user_manual/listening.rst\n+++ b/docs/source/traits_user_manual/listening.rst\n@@ -539,6 +539,17 @@ The arguments that are passed to the trait attribute change notification\n method depend on the method signature and on which type of static notification\n handler it is.\n \n+.. note::\n+ The :func:`~.on_trait_change` and :func:`~.observe` decorators nullify\n+ the effect of special naming. A method that looks like::\n+\n+ @observe(\"foo\")\n+ def _foo_changed(self, event):\n+ do_something_with(event)\n+\n+ will only be called once when ``foo`` changes, as a result of the\n+ ``observe`` decorator.\n+\n .. _attribute-specific-handler-signatures:\n \n Attribute-specific Handler Signatures\ndiff --git a/traits/has_traits.py b/traits/has_traits.py\nindex 12d3cee6..0962098d 100644\n--- a/traits/has_traits.py\n+++ b/traits/has_traits.py\n@@ -162,6 +162,7 @@ def _get_def(class_name, class_dict, bases, method):\n (result is not None)\n and is_unbound_method_type(result)\n and (getattr(result, \"on_trait_change\", None) is None)\n+ and (getattr(result, \"_observe_inputs\", None) is None)\n ):\n return result\n \n@@ -171,6 +172,7 @@ def _get_def(class_name, class_dict, bases, method):\n (result is not None)\n and is_unbound_method_type(result)\n and (getattr(result, \"on_trait_change\", None) is None)\n+ and (getattr(result, \"_observe_inputs\", None) is None)\n ):\n return result\n \n", "test_patch": "diff --git a/traits/tests/test_has_traits.py b/traits/tests/test_has_traits.py\nindex 5e39f9e2..3c98ff45 100644\n--- a/traits/tests/test_has_traits.py\n+++ b/traits/tests/test_has_traits.py\n@@ -604,6 +604,68 @@ class TestHasTraits(unittest.TestCase):\n {\"foo\": A.class_traits()[\"foo\"]},\n )\n \n+ def test_decorated_changed_method(self):\n+ # xref: enthought/traits#527\n+ # Traits should ignore the _changed magic naming.\n+\n+ events = []\n+\n+ class A(HasTraits):\n+ foo = Int()\n+\n+ @on_trait_change(\"foo\")\n+ def _foo_changed(self, obj, name, old, new):\n+ events.append((obj, name, old, new))\n+\n+ a = A()\n+ a.foo = 23\n+ self.assertEqual(\n+ events,\n+ [(a, \"foo\", 0, 23)],\n+ )\n+\n+ def test_observed_changed_method(self):\n+ events = []\n+\n+ class A(HasTraits):\n+ foo = Int()\n+\n+ @observe(\"foo\")\n+ def _foo_changed(self, event):\n+ events.append(event)\n+\n+ a = A()\n+ a.foo = 23\n+ self.assertEqual(len(events), 1)\n+ event = events[0]\n+ self.assertEqual(event.object, a)\n+ self.assertEqual(event.name, \"foo\")\n+ self.assertEqual(event.old, 0)\n+ self.assertEqual(event.new, 23)\n+\n+ def test_decorated_changed_method_subclass(self):\n+ # xref: enthought/traits#527\n+ # Traits should ignore the _changed magic naming.\n+\n+ events = []\n+\n+ class A(HasTraits):\n+ foo = Int()\n+\n+ @on_trait_change(\"foo\")\n+ def _foo_changed(self, obj, name, old, new):\n+ events.append((obj, name, old, new))\n+\n+ class B(A):\n+ pass\n+\n+ a = B()\n+ a.foo = 23\n+ self.assertEqual(\n+ events,\n+ [(a, \"foo\", 0, 23)],\n+ )\n+\n \n class TestObjectNotifiers(unittest.TestCase):\n \"\"\" Test calling object notifiers. \"\"\"\n", "FAIL_TO_PASS": ["traits/tests/test_has_traits.py::TestHasTraits::test_observed_changed_method"]}], "all_FAIL_TO_PASS": ["traits/tests/test_has_traits.py::TestHasTraits::test_observed_changed_method"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "robotpy__cxxheaderparser-106_x1", "level": 1, "source": "swerebenchv2", "repo": "robotpy/cxxheaderparser", "image": "swerebenchv2/robotpy-cxxheaderparser:106-d8f8bd0", "base_commit": "d8f8bd05c7b7d1bb3408207564f7734564edd19f", "num_bugs": 1, "bugs": [{"instance_id": "robotpy__cxxheaderparser-106", "base_commit": "d8f8bd05c7b7d1bb3408207564f7734564edd19f", "gold_patch": "diff --git a/cxxheaderparser/parser.py b/cxxheaderparser/parser.py\nindex d633e2a..8a51e81 100644\n--- a/cxxheaderparser/parser.py\n+++ b/cxxheaderparser/parser.py\n@@ -1937,6 +1937,11 @@ class CxxParser:\n if self.lex.token_if(\"{\"):\n self._discard_contents(\"{\", \"}\")\n fn.has_body = True\n+ elif self.lex.token_if(\"=\"):\n+ if self.lex.token_if_val(\"delete\"):\n+ fn.deleted = True\n+ else:\n+ raise self._parse_error(None, \"expected 'delete\")\n \n def _parse_method_end(self, method: Method) -> None:\n \"\"\"\ndiff --git a/cxxheaderparser/types.py b/cxxheaderparser/types.py\nindex 59169fc..ea768b6 100644\n--- a/cxxheaderparser/types.py\n+++ b/cxxheaderparser/types.py\n@@ -696,6 +696,7 @@ class Function:\n extern: typing.Union[bool, str] = False\n static: bool = False\n inline: bool = False\n+ deleted: bool = False\n \n #: If true, the body of the function is present\n has_body: bool = False\n@@ -764,7 +765,6 @@ class Method(Function):\n constructor: bool = False\n explicit: bool = False\n default: bool = False\n- deleted: bool = False\n \n destructor: bool = False\n \n", "test_patch": "diff --git a/tests/test_fn.py b/tests/test_fn.py\nindex 4f67a41..34734d6 100644\n--- a/tests/test_fn.py\n+++ b/tests/test_fn.py\n@@ -1313,3 +1313,25 @@ def test_msvc_inline() -> None:\n ]\n )\n )\n+\n+\n+def test_deleted_function() -> None:\n+ content = \"\"\"\n+ void trim() = delete;\n+ \"\"\"\n+ data = parse_string(content, cleandoc=True)\n+\n+ assert data == ParsedData(\n+ namespace=NamespaceScope(\n+ functions=[\n+ Function(\n+ return_type=Type(\n+ typename=PQName(segments=[FundamentalSpecifier(name=\"void\")])\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"trim\")]),\n+ parameters=[],\n+ deleted=True,\n+ )\n+ ]\n+ )\n+ )\n", "FAIL_TO_PASS": ["tests/test_fn.py::test_deleted_function"]}], "all_FAIL_TO_PASS": ["tests/test_fn.py::test_deleted_function"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pytask-dev__pytask-285_x1", "level": 1, "source": "swerebenchv2", "repo": "pytask-dev/pytask", "image": "swerebenchv2/pytask-dev-pytask:285-3575ede", "base_commit": "3575ede210b182494dc918cd7097245e7721e4ba", "num_bugs": 1, "bugs": [{"instance_id": "pytask-dev__pytask-285", "base_commit": "3575ede210b182494dc918cd7097245e7721e4ba", "gold_patch": "diff --git a/docs/source/changes.md b/docs/source/changes.md\nindex 5f30e3a..c05fd9e 100644\n--- a/docs/source/changes.md\n+++ b/docs/source/changes.md\n@@ -5,7 +5,15 @@ chronological order. Releases follow [semantic versioning](https://semver.org/)\n releases are available on [PyPI](https://pypi.org/project/pytask) and\n [Anaconda.org](https://anaconda.org/conda-forge/pytask).\n \n-## 0.2.3 - 2022-xx-xx\n+## 0.2.4 - 2022-xx-xx\n+\n+- {pull}`279` enhances some tutorials with spell and grammar checking.\n+- {pull}`282` updates the tox configuration.\n+- {pull}`283` fixes an issue with coverage and tests using pexpect + `pdb.set_trace()`.\n+- {pull}`285` implements that pytask does not show the traceback of tasks which are\n+ skipped because its previous task failed. Fixes {issue}`284`.\n+\n+## 0.2.3 - 2022-05-30\n \n - {pull}`276` fixes `pytask clean` when git is not installed. Fixes {issue}`275`.\n - {pull}`277` ignores `DeprecationWarning` and `PendingDeprecationWarning` by default.\ndiff --git a/src/_pytask/execute.py b/src/_pytask/execute.py\nindex 8c1609e..320bda7 100644\n--- a/src/_pytask/execute.py\n+++ b/src/_pytask/execute.py\n@@ -250,7 +250,10 @@ def pytask_execute_log_end(session: Session, reports: list[ExecutionReport]) ->\n console.print()\n \n for report in reports:\n- if report.outcome in (TaskOutcome.FAIL, TaskOutcome.SKIP_PREVIOUS_FAILED):\n+ if report.outcome == TaskOutcome.FAIL or (\n+ report.outcome == TaskOutcome.SKIP_PREVIOUS_FAILED\n+ and session.config[\"verbose\"] >= 2\n+ ):\n _print_errored_task_report(session, report)\n \n console.rule(style=\"dim\")\n", "test_patch": "diff --git a/tests/test_execute.py b/tests/test_execute.py\nindex 672efbc..aa1e80a 100644\n--- a/tests/test_execute.py\n+++ b/tests/test_execute.py\n@@ -308,3 +308,25 @@ def test_show_errors_immediately(runner, tmp_path, show_errors_immediately):\n assert len(matches_traceback) == 2\n else:\n assert len(matches_traceback) == 1\n+\n+\n+@pytest.mark.end_to_end\n+@pytest.mark.parametrize(\"verbose\", [1, 2])\n+def test_traceback_of_previous_task_failed_is_not_shown(runner, tmp_path, verbose):\n+ source = \"\"\"\n+ import pytask\n+\n+ @pytask.mark.produces(\"in.txt\")\n+ def task_first(): raise ValueError\n+\n+ @pytask.mark.depends_on(\"in.txt\")\n+ def task_second(): pass\n+ \"\"\"\n+ tmp_path.joinpath(\"task_example.py\").write_text(textwrap.dedent(source))\n+\n+ result = runner.invoke(cli, [tmp_path.as_posix(), \"--verbose\", str(verbose)])\n+\n+ assert result.exit_code == ExitCode.FAILED\n+ assert (\"Task task_example.py::task_second failed\" in result.output) is (\n+ verbose == 2\n+ )\n", "FAIL_TO_PASS": ["tests/test_execute.py::test_traceback_of_previous_task_failed_is_not_shown[1]"]}], "all_FAIL_TO_PASS": ["tests/test_execute.py::test_traceback_of_previous_task_failed_is_not_shown[1]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "toblerity__shapely-1166_x1", "level": 1, "source": "swerebenchv2", "repo": "Toblerity/Shapely", "image": "swerebenchv2/toblerity-shapely:1166-1991a72", "base_commit": "1991a72e94d7c7e5583407e4bb576c2e81292fe7", "num_bugs": 1, "bugs": [{"instance_id": "toblerity__shapely-1166", "base_commit": "1991a72e94d7c7e5583407e4bb576c2e81292fe7", "gold_patch": "diff --git a/CHANGES.txt b/CHANGES.txt\nindex a22880a..8b12c78 100644\n--- a/CHANGES.txt\n+++ b/CHANGES.txt\n@@ -10,6 +10,8 @@ Shapely 1.8 will support only Python versions >= 3.6.\n \n New features:\n \n+- The STRtree nearest*() methods now take an optional argument that\n+ specifies exclusion of the input geometry from results (#1115).\n - A GeometryTypeError has been added to shapely.errors and is consistently\n raised instead of TypeError or ValueError as in version 1.7. For backwards\n compatibility, the new exception will derive from TypeError and Value error\n@@ -23,6 +25,8 @@ New features:\n \n Bug fixes:\n \n+- We no longer attempt to load libc to get the free function on Linux, but get\n+ it from the global symbol table.\n - GEOS error messages printed when GEOS_getCoordSeq() is passed an empty\n geometry are avoided by never passing an empty geometry (#1134).\n - Python's builtin super() is now used only as described in PEP 3135 (#1109).\ndiff --git a/_vendor/packaging/specifiers.py b/_vendor/packaging/specifiers.py\nindex 902f6de..a538a62 100644\n--- a/_vendor/packaging/specifiers.py\n+++ b/_vendor/packaging/specifiers.py\n@@ -503,7 +503,7 @@ class Specifier(_IndividualSpecifier):\n return False\n \n # Ensure that we do not allow a local version of the version mentioned\n- # in the specifier, which is techincally greater than, to match.\n+ # in the specifier, which is technically greater than, to match.\n if prospective.local is not None:\n if Version(prospective.base_version) == Version(spec.base_version):\n return False\n@@ -589,7 +589,7 @@ def _pad_version(left, right):\n class SpecifierSet(BaseSpecifier):\n \n def __init__(self, specifiers=\"\", prereleases=None):\n- # Split on , to break each indidivual specifier into it's own item, and\n+ # Split on , to break each individual specifier into it's own item, and\n # strip each item to remove leading/trailing whitespace.\n specifiers = [s.strip() for s in specifiers.split(\",\") if s.strip()]\n \ndiff --git a/docs/design.rst b/docs/design.rst\nindex 0c768f0..9a6ccf4 100644\n--- a/docs/design.rst\n+++ b/docs/design.rst\n@@ -3,7 +3,7 @@ Design Notes\n ============\n \n Shapely provides classes that implement, more or less, the interfaces in the\n-OGC's simple feature acess specification [1]_. The classes are defined in\n+OGC's simple feature access specification [1]_. The classes are defined in\n similarly named modules under ``shapely.geometry``: ``Point`` is in\n ``shapely.geometry.point``, ``MultiPolygon`` is in\n ``shapely.geometry.multipolygon``. These classes derive from\ndiff --git a/shapely/geometry/base.py b/shapely/geometry/base.py\nindex 1b128ca..1ad0d07 100644\n--- a/shapely/geometry/base.py\n+++ b/shapely/geometry/base.py\n@@ -101,7 +101,7 @@ def deserialize_wkb(data):\n def geos_geom_from_py(ob, create_func=None):\n \"\"\"Helper function for geos_*_from_py functions in each geom type.\n \n- If a create_func is specified the coodinate sequence is cloned and a new\n+ If a create_func is specified the coordinate sequence is cloned and a new\n geometry is created with it, otherwise the geometry is cloned directly.\n This behaviour is useful for converting between LineString and LinearRing\n objects.\ndiff --git a/shapely/geos.py b/shapely/geos.py\nindex dea6147..fe73419 100644\n--- a/shapely/geos.py\n+++ b/shapely/geos.py\n@@ -97,11 +97,12 @@ if sys.platform.startswith('linux'):\n 'libgeos_c.so',\n ]\n _lgeos = load_dll('libgeos_c', fallbacks=alt_paths)\n- # Necessary for environments with only libc.musl\n- c_alt_paths = [\n- 'libc.musl-x86_64.so.1'\n- ]\n- free = load_dll('c', fallbacks=c_alt_paths).free\n+\n+ # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n+ # manpage says, \"If filename is NULL, then the returned handle is for the\n+ # main program\". This way we can let the linker do the work to figure out\n+ # which libc Python is actually using.\n+ free = CDLL(None).free\n free.argtypes = [c_void_p]\n free.restype = None\n \n@@ -147,10 +148,6 @@ elif sys.platform == 'darwin':\n ]\n _lgeos = load_dll('geos_c', fallbacks=alt_paths)\n \n- # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n- # manpage says, \"If filename is NULL, then the returned handle is for the\n- # main program\". This way we can let the linker do the work to figure out\n- # which libc Python is actually using.\n free = CDLL(None).free\n free.argtypes = [c_void_p]\n free.restype = None\n@@ -187,12 +184,13 @@ elif sys.platform == 'win32':\n \n elif sys.platform == 'sunos5':\n _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])\n- free = CDLL('libc.so.1').free\n+ free.restype = None\n free.argtypes = [c_void_p]\n free.restype = None\n+\n else: # other *nix systems\n _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])\n- free = load_dll('c', fallbacks=['libc.so.6']).free\n+ free = CDLL(None).free\n free.argtypes = [c_void_p]\n free.restype = None\n \ndiff --git a/shapely/ops.py b/shapely/ops.py\nindex 720d7c3..ba21ab7 100644\n--- a/shapely/ops.py\n+++ b/shapely/ops.py\n@@ -145,7 +145,7 @@ class CollectionOperator:\n \"\"\"Returns the union of a sequence of geometries\n \n This method replaces :meth:`cascaded_union` as the\n- prefered method for dissolving many polygons.\n+ preferred method for dissolving many polygons.\n \"\"\"\n try:\n if isinstance(geoms, BaseMultipartGeometry):\ndiff --git a/shapely/speedups/__init__.py b/shapely/speedups/__init__.py\nindex 1bbb04c..88ec30e 100644\n--- a/shapely/speedups/__init__.py\n+++ b/shapely/speedups/__init__.py\n@@ -33,7 +33,7 @@ def enable():\n \"\"\"Enable Cython speedups\n \n The shapely.speedups module contains performance enhancements written in C.\n- They are automaticaly installed when Python has access to a compiler and\n+ They are automatically installed when Python has access to a compiler and\n GEOS development headers during installation, and are enabled by default.\n \n You can check if speedups are installed with the `available` attribute, and\ndiff --git a/shapely/strtree.py b/shapely/strtree.py\nindex 75b0f2c..ac1008f 100644\n--- a/shapely/strtree.py\n+++ b/shapely/strtree.py\n@@ -21,6 +21,7 @@ References\n import ctypes\n import logging\n from typing import Any, ItemsView, Iterable, Iterator, Sequence, Tuple, Union\n+import sys\n from warnings import warn\n \n from shapely.errors import ShapelyDeprecationWarning\n@@ -249,7 +250,9 @@ class STRtree:\n \"\"\"\n return self.query_geoms(geom)\n \n- def nearest_item(self, geom: BaseGeometry) -> Union[Any, None]:\n+ def nearest_item(\n+ self, geom: BaseGeometry, exclusive: bool = False\n+ ) -> Union[Any, None]:\n \"\"\"Query the tree for the node nearest to geom and get the item\n stored in the node.\n \n@@ -259,6 +262,9 @@ class STRtree:\n ----------\n geom : geometry object\n The query geometry.\n+ exclusive : bool, optional\n+ Whether to exclude the item corresponding to the given geom\n+ from results or not. Default: False.\n \n Returns\n -------\n@@ -289,10 +295,14 @@ class STRtree:\n \n def callback(item1, item2, distance, userdata):\n try:\n+ callback_userdata = ctypes.cast(userdata, ctypes.py_object).value\n idx = ctypes.cast(item1, ctypes.py_object).value\n geom2 = ctypes.cast(item2, ctypes.py_object).value\n dist = ctypes.cast(distance, ctypes.POINTER(ctypes.c_double))\n- lgeos.GEOSDistance(self._rev[idx]._geom, geom2._geom, dist)\n+ if callback_userdata[\"exclusive\"] and self._rev[idx].equals(geom2):\n+ dist[0] = sys.float_info.max\n+ else:\n+ lgeos.GEOSDistance(self._rev[idx]._geom, geom2._geom, dist)\n return 1\n except Exception:\n log.exception(\"Caught exception\")\n@@ -303,12 +313,14 @@ class STRtree:\n ctypes.py_object(geom),\n envelope._geom,\n lgeos.GEOSDistanceCallback(callback),\n- None,\n+ ctypes.py_object({\"exclusive\": exclusive}),\n )\n result = ctypes.cast(item, ctypes.py_object).value\n return result\n \n- def nearest_geom(self, geom: BaseGeometry) -> Union[BaseGeometry, None]:\n+ def nearest_geom(\n+ self, geom: BaseGeometry, exclusive: bool = False\n+ ) -> Union[BaseGeometry, None]:\n \"\"\"Query the tree for the node nearest to geom and get the\n geometry corresponding to the item stored in the node.\n \n@@ -316,6 +328,9 @@ class STRtree:\n ----------\n geom : geometry object\n The query geometry.\n+ exclusive : bool, optional\n+ Whether to exclude the given geom from results or not.\n+ Default: False.\n \n Returns\n -------\n@@ -325,13 +340,15 @@ class STRtree:\n version 2.0.\n \n \"\"\"\n- item = self.nearest_item(geom)\n+ item = self.nearest_item(geom, exclusive=exclusive)\n if item is None:\n return None\n else:\n return self._rev[item]\n \n- def nearest(self, geom: BaseGeometry) -> Union[BaseGeometry, None]:\n+ def nearest(\n+ self, geom: BaseGeometry, exclusive: bool = False\n+ ) -> Union[BaseGeometry, None]:\n \"\"\"Query the tree for the node nearest to geom and get the\n geometry corresponding to the item stored in the node.\n \n@@ -342,6 +359,9 @@ class STRtree:\n ----------\n geom : geometry object\n The query geometry.\n+ exclusive : bool, optional\n+ Whether to exclude the given geom from results or not.\n+ Default: False.\n \n Returns\n -------\n@@ -351,4 +371,4 @@ class STRtree:\n version 2.0.\n \n \"\"\"\n- return self.nearest_geom(geom)\n+ return self.nearest_geom(geom, exclusive=exclusive)\n", "test_patch": "diff --git a/tests/test_strtree.py b/tests/test_strtree.py\nindex 04d5742..55b61c4 100644\n--- a/tests/test_strtree.py\n+++ b/tests/test_strtree.py\n@@ -177,3 +177,22 @@ def test_nearest_items(geoms, items):\n with pytest.warns(ShapelyDeprecationWarning):\n tree = STRtree(geoms, items)\n assert tree.nearest_item(None) is None\n+\n+\n+@pytest.mark.skipif(geos_version < (3, 6, 0), reason=\"GEOS 3.6.0 required\")\n+@pytest.mark.parametrize(\n+ \"geoms\",\n+ [\n+ [\n+ Point(0, 0.5),\n+ Polygon([(1, 0), (2, 0), (2, 1), (1, 1)]),\n+ Polygon([(0, 2), (1, 2), (1, 3), (0, 3)]),\n+ ]\n+ ],\n+)\n+@pytest.mark.parametrize(\"items\", [list(range(1, 4)), list(\"abc\")])\n+@pytest.mark.parametrize(\"query_geom\", [Point(0, 0.5)])\n+def test_nearest_item_exclusive(geoms, items, query_geom):\n+ with pytest.warns(ShapelyDeprecationWarning):\n+ tree = STRtree(geoms, items)\n+ assert tree.nearest_item(query_geom, exclusive=True) != items[0]\n", "FAIL_TO_PASS": ["tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items0-geoms0]", "tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items1-geoms0]"]}], "all_FAIL_TO_PASS": ["tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items0-geoms0]", "tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items1-geoms0]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "modin-project__modin-6758_x1", "level": 1, "source": "swerebenchv2", "repo": "modin-project/modin", "image": "swerebenchv2/modin-project-modin:6758-93275d9", "base_commit": "93275d9d3bb74158e80489fc9beb2761dd9b2a85", "num_bugs": 1, "bugs": [{"instance_id": "modin-project__modin-6758", "base_commit": "93275d9d3bb74158e80489fc9beb2761dd9b2a85", "gold_patch": "diff --git a/modin/core/dataframe/pandas/dataframe/dataframe.py b/modin/core/dataframe/pandas/dataframe/dataframe.py\nindex 88c97843..e32c1693 100644\n--- a/modin/core/dataframe/pandas/dataframe/dataframe.py\n+++ b/modin/core/dataframe/pandas/dataframe/dataframe.py\n@@ -2915,7 +2915,7 @@ class PandasDataframe(ClassLogger):\n new_index = self.index if axis == 1 else None\n if new_columns is None:\n new_columns = self.columns if axis == 0 else None\n- if new_columns is not None and new_dtypes is not None:\n+ if new_columns is not None and isinstance(new_dtypes, pandas.Series):\n assert new_dtypes.index.equals(\n new_columns\n ), f\"{new_dtypes=} doesn't have the same columns as in {new_columns=}\"\ndiff --git a/modin/core/dataframe/pandas/metadata/__init__.py b/modin/core/dataframe/pandas/metadata/__init__.py\nindex 4caf2383..2ace6d8e 100644\n--- a/modin/core/dataframe/pandas/metadata/__init__.py\n+++ b/modin/core/dataframe/pandas/metadata/__init__.py\n@@ -13,7 +13,18 @@\n \n \"\"\"Utilities and classes to handle work with metadata.\"\"\"\n \n-from .dtypes import DtypesDescriptor, LazyProxyCategoricalDtype, ModinDtypes\n+from .dtypes import (\n+ DtypesDescriptor,\n+ LazyProxyCategoricalDtype,\n+ ModinDtypes,\n+ extract_dtype,\n+)\n from .index import ModinIndex\n \n-__all__ = [\"ModinDtypes\", \"ModinIndex\", \"LazyProxyCategoricalDtype\", \"DtypesDescriptor\"]\n+__all__ = [\n+ \"ModinDtypes\",\n+ \"ModinIndex\",\n+ \"LazyProxyCategoricalDtype\",\n+ \"DtypesDescriptor\",\n+ \"extract_dtype\",\n+]\ndiff --git a/modin/core/dataframe/pandas/metadata/dtypes.py b/modin/core/dataframe/pandas/metadata/dtypes.py\nindex ffd81eb7..680825fa 100644\n--- a/modin/core/dataframe/pandas/metadata/dtypes.py\n+++ b/modin/core/dataframe/pandas/metadata/dtypes.py\n@@ -529,14 +529,23 @@ class ModinDtypes:\n \n Parameters\n ----------\n- value : pandas.Series or callable\n+ value : pandas.Series, callable, DtypesDescriptor or ModinDtypes, optional\n \"\"\"\n \n- def __init__(self, value: Union[Callable, pandas.Series, DtypesDescriptor]):\n+ def __init__(\n+ self,\n+ value: Optional[\n+ Union[Callable, pandas.Series, DtypesDescriptor, \"ModinDtypes\"]\n+ ],\n+ ):\n if callable(value) or isinstance(value, pandas.Series):\n self._value = value\n elif isinstance(value, DtypesDescriptor):\n self._value = value.to_series() if value.is_materialized else value\n+ elif isinstance(value, type(self)):\n+ self._value = value.copy()._value\n+ elif isinstance(value, None):\n+ self._value = DtypesDescriptor()\n else:\n raise ValueError(f\"ModinDtypes doesn't work with '{value}'\")\n \n@@ -985,3 +994,27 @@ def get_categories_dtype(\n if isinstance(cdt, LazyProxyCategoricalDtype)\n else cdt.categories.dtype\n )\n+\n+\n+def extract_dtype(value):\n+ \"\"\"\n+ Extract dtype(s) from the passed `value`.\n+\n+ Parameters\n+ ----------\n+ value : object\n+\n+ Returns\n+ -------\n+ numpy.dtype or pandas.Series of numpy.dtypes\n+ \"\"\"\n+ from modin.pandas.utils import is_scalar\n+\n+ if hasattr(value, \"dtype\"):\n+ return value.dtype\n+ elif hasattr(value, \"dtypes\"):\n+ return value.dtypes\n+ elif is_scalar(value):\n+ return np.dtype(type(value))\n+ else:\n+ return np.array(value).dtype\ndiff --git a/modin/core/storage_formats/pandas/query_compiler.py b/modin/core/storage_formats/pandas/query_compiler.py\nindex a34c8d4b..14020e03 100644\n--- a/modin/core/storage_formats/pandas/query_compiler.py\n+++ b/modin/core/storage_formats/pandas/query_compiler.py\n@@ -58,7 +58,11 @@ from modin.core.dataframe.algebra.default2pandas.groupby import (\n SeriesGroupByDefault,\n )\n from modin.core.dataframe.base.dataframe.utils import join_columns\n-from modin.core.dataframe.pandas.metadata import DtypesDescriptor, ModinDtypes\n+from modin.core.dataframe.pandas.metadata import (\n+ DtypesDescriptor,\n+ ModinDtypes,\n+ extract_dtype,\n+)\n from modin.core.storage_formats.base.query_compiler import BaseQueryCompiler\n from modin.error_message import ErrorMessage\n from modin.utils import (\n@@ -2943,6 +2947,22 @@ class PandasQueryCompiler(BaseQueryCompiler):\n idx = self.get_axis(axis ^ 1).get_indexer_for([key])[0]\n return self.insert_item(axis ^ 1, idx, value, how, replace=True)\n \n+ if axis == 0:\n+ value_dtype = extract_dtype(value)\n+\n+ old_columns = self.columns.difference(pandas.Index([key]))\n+ old_dtypes = ModinDtypes(self._modin_frame._dtypes).lazy_get(old_columns)\n+ new_dtypes = ModinDtypes.concat(\n+ [\n+ old_dtypes,\n+ DtypesDescriptor({key: value_dtype}, cols_with_unknown_dtypes=[]),\n+ ]\n+ # get dtypes in a proper order\n+ ).lazy_get(self.columns)\n+ else:\n+ # TODO: apply 'find_common_dtype' to the value's dtype and old column dtypes\n+ new_dtypes = None\n+\n # TODO: rework by passing list-like values to `apply_select_indices`\n # as an item to distribute\n if is_list_like(value):\n@@ -2953,6 +2973,7 @@ class PandasQueryCompiler(BaseQueryCompiler):\n new_index=self.index,\n new_columns=self.columns,\n keep_remaining=True,\n+ new_dtypes=new_dtypes,\n )\n else:\n new_modin_frame = self._modin_frame.apply_select_indices(\n@@ -2961,6 +2982,7 @@ class PandasQueryCompiler(BaseQueryCompiler):\n [key],\n new_index=self.index,\n new_columns=self.columns,\n+ new_dtypes=new_dtypes,\n keep_remaining=True,\n )\n return self.__constructor__(new_modin_frame)\n@@ -3135,13 +3157,7 @@ class PandasQueryCompiler(BaseQueryCompiler):\n df.insert(internal_idx, column, value)\n return df\n \n- if hasattr(value, \"dtype\"):\n- value_dtype = value.dtype\n- elif is_scalar(value):\n- value_dtype = np.dtype(type(value))\n- else:\n- value_dtype = np.array(value).dtype\n-\n+ value_dtype = extract_dtype(value)\n new_columns = self.columns.insert(loc, column)\n new_dtypes = ModinDtypes.concat(\n [\n", "test_patch": "diff --git a/modin/test/storage_formats/pandas/test_internals.py b/modin/test/storage_formats/pandas/test_internals.py\nindex 243a496c..f315aa0b 100644\n--- a/modin/test/storage_formats/pandas/test_internals.py\n+++ b/modin/test/storage_formats/pandas/test_internals.py\n@@ -1965,6 +1965,64 @@ class TestZeroComputationDtypes:\n Test cases that shouldn't trigger dtypes computation during their execution.\n \"\"\"\n \n+ @pytest.mark.parametrize(\"self_dtype\", [\"materialized\", \"partial\", \"unknown\"])\n+ @pytest.mark.parametrize(\n+ \"value, value_dtype\",\n+ [\n+ [3.5, np.dtype(float)],\n+ [[3.5, 2.4], np.dtype(float)],\n+ [np.array([3.5, 2.4]), np.dtype(float)],\n+ [pd.Series([3.5, 2.4]), np.dtype(float)],\n+ ],\n+ )\n+ def test_preserve_dtypes_setitem(self, self_dtype, value, value_dtype):\n+ \"\"\"\n+ Test that ``df[single_existing_column] = value`` preserves dtypes cache.\n+ \"\"\"\n+ with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n+ df = pd.DataFrame({\"a\": [1, 2], \"b\": [3, 4], \"c\": [3, 4]})\n+ if self_dtype == \"materialized\":\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+ elif self_dtype == \"partial\":\n+ df._query_compiler._modin_frame.set_dtypes_cache(\n+ ModinDtypes(\n+ DtypesDescriptor(\n+ {\"a\": np.dtype(int)}, cols_with_unknown_dtypes=[\"b\", \"c\"]\n+ )\n+ )\n+ )\n+ elif self_dtype == \"unknown\":\n+ df._query_compiler._modin_frame.set_dtypes_cache(None)\n+ else:\n+ raise NotImplementedError(self_dtype)\n+\n+ df[\"b\"] = value\n+\n+ if self_dtype == \"materialized\":\n+ result_dtype = pandas.Series(\n+ [np.dtype(int), value_dtype, np.dtype(int)], index=[\"a\", \"b\", \"c\"]\n+ )\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+ assert df.dtypes.equals(result_dtype)\n+ elif self_dtype == \"partial\":\n+ result_dtype = DtypesDescriptor(\n+ {\"a\": np.dtype(int), \"b\": value_dtype},\n+ cols_with_unknown_dtypes=[\"c\"],\n+ columns_order={0: \"a\", 1: \"b\", 2: \"c\"},\n+ )\n+ df._query_compiler._modin_frame._dtypes._value.equals(result_dtype)\n+ elif self_dtype == \"unknown\":\n+ result_dtype = DtypesDescriptor(\n+ {\"b\": value_dtype},\n+ cols_with_unknown_dtypes=[\"a\", \"b\"],\n+ columns_order={0: \"a\", 1: \"b\", 2: \"c\"},\n+ )\n+ df._query_compiler._modin_frame._dtypes._value.equals(result_dtype)\n+ else:\n+ raise NotImplementedError(self_dtype)\n+\n+ patch.assert_not_called()\n+\n @pytest.mark.parametrize(\"self_dtype\", [\"materialized\", \"partial\", \"unknown\"])\n @pytest.mark.parametrize(\n \"value, value_dtype\",\n", "FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_setitem[3.5-value_dtype0-materialized]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_setitem[value1-value_dtype1-materialized]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_setitem[value2-value_dtype2-materialized]"]}], "all_FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_setitem[3.5-value_dtype0-materialized]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_setitem[value1-value_dtype1-materialized]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_setitem[value2-value_dtype2-materialized]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pytask-dev__pytask-287_x1", "level": 1, "source": "swerebenchv2", "repo": "pytask-dev/pytask", "image": "swerebenchv2/pytask-dev-pytask:287-74ad361", "base_commit": "74ad361c5aeb85909afd0f4fd37c92f1c09af184", "num_bugs": 1, "bugs": [{"instance_id": "pytask-dev__pytask-287", "base_commit": "74ad361c5aeb85909afd0f4fd37c92f1c09af184", "gold_patch": "diff --git a/docs/source/changes.md b/docs/source/changes.md\nindex c05fd9e..be3ae4f 100644\n--- a/docs/source/changes.md\n+++ b/docs/source/changes.md\n@@ -12,6 +12,8 @@ releases are available on [PyPI](https://pypi.org/project/pytask) and\n - {pull}`283` fixes an issue with coverage and tests using pexpect + `pdb.set_trace()`.\n - {pull}`285` implements that pytask does not show the traceback of tasks which are\n skipped because its previous task failed. Fixes {issue}`284`.\n+- {pull}`287` changes that all files that are not produced by a task are displayed in\n+ the error message. Fixes {issue}`262`.\n \n ## 0.2.3 - 2022-05-30\n \ndiff --git a/src/_pytask/execute.py b/src/_pytask/execute.py\nindex 320bda7..f7380fb 100644\n--- a/src/_pytask/execute.py\n+++ b/src/_pytask/execute.py\n@@ -11,6 +11,7 @@ from _pytask.config_utils import ShowCapture\n from _pytask.console import console\n from _pytask.console import create_summary_panel\n from _pytask.console import create_url_style_for_task\n+from _pytask.console import format_strings_as_flat_tree\n from _pytask.console import format_task_id\n from _pytask.console import unify_styles\n from _pytask.dag import descending_tasks\n@@ -27,6 +28,7 @@ from _pytask.outcomes import TaskOutcome\n from _pytask.report import ExecutionReport\n from _pytask.session import Session\n from _pytask.shared import get_first_non_none_value\n+from _pytask.shared import reduce_node_name\n from _pytask.traceback import format_exception_without_traceback\n from _pytask.traceback import remove_traceback_from_exc_info\n from _pytask.traceback import render_exc_info\n@@ -167,15 +169,23 @@ def pytask_execute_task(task: Task) -> bool:\n \n @hookimpl\n def pytask_execute_task_teardown(session: Session, task: Task) -> None:\n- \"\"\"Check if each produced node was indeed produced.\"\"\"\n+ \"\"\"Check if :class:`_pytask.nodes.FilePathNode` are produced by a task.\"\"\"\n+ missing_nodes = []\n for product in session.dag.successors(task.name):\n node = session.dag.nodes[product][\"node\"]\n- try:\n- node.state()\n- except NodeNotFoundError as e:\n- raise NodeNotFoundError(\n- f\"{node.name} was not produced by {task.name}.\"\n- ) from e\n+ if isinstance(node, FilePathNode):\n+\n+ try:\n+ node.state()\n+ except NodeNotFoundError:\n+ missing_nodes.append(node)\n+\n+ if missing_nodes:\n+ paths = [reduce_node_name(i, session.config[\"paths\"]) for i in missing_nodes]\n+ formatted = format_strings_as_flat_tree(\n+ paths, \"The task did not produce the following files:\\n\", \"\"\n+ )\n+ raise NodeNotFoundError(formatted)\n \n \n @hookimpl(trylast=True)\n", "test_patch": "diff --git a/tests/test_execute.py b/tests/test_execute.py\nindex aa1e80a..333ba9f 100644\n--- a/tests/test_execute.py\n+++ b/tests/test_execute.py\n@@ -36,6 +36,25 @@ def test_task_did_not_produce_node(tmp_path):\n assert isinstance(session.execution_reports[0].exc_info[1], NodeNotFoundError)\n \n \n+@pytest.mark.end_to_end\n+def test_task_did_not_produce_multiple_nodes_and_all_are_shown(runner, tmp_path):\n+ source = \"\"\"\n+ import pytask\n+\n+ @pytask.mark.produces([\"1.txt\", \"2.txt\"])\n+ def task_example():\n+ pass\n+ \"\"\"\n+ tmp_path.joinpath(\"task_module.py\").write_text(textwrap.dedent(source))\n+\n+ result = runner.invoke(cli, [tmp_path.as_posix()])\n+\n+ assert result.exit_code == ExitCode.FAILED\n+ assert \"NodeNotFoundError\" in result.output\n+ assert \"1.txt\" in result.output\n+ assert \"2.txt\" in result.output\n+\n+\n @pytest.mark.end_to_end\n def test_node_not_found_in_task_setup(tmp_path):\n \"\"\"Test for :class:`_pytask.exceptions.NodeNotFoundError` in task setup.\n", "FAIL_TO_PASS": ["tests/test_execute.py::test_task_did_not_produce_multiple_nodes_and_all_are_shown"]}], "all_FAIL_TO_PASS": ["tests/test_execute.py::test_task_did_not_produce_multiple_nodes_and_all_are_shown"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "rochacbruno__dynaconf-300_x1", "level": 1, "source": "swerebenchv2", "repo": "rochacbruno/dynaconf", "image": "swerebenchv2/rochacbruno-dynaconf:300-c4d93e2", "base_commit": "c4d93e2e481808309d75a0288e6053699859f32a", "num_bugs": 1, "bugs": [{"instance_id": "rochacbruno__dynaconf-300", "base_commit": "c4d93e2e481808309d75a0288e6053699859f32a", "gold_patch": "diff --git a/Makefile b/Makefile\nindex 65139e5..3a9136d 100644\n--- a/Makefile\n+++ b/Makefile\n@@ -91,6 +91,7 @@ test_examples:\n \tcd example/issues/228_nested_toml_bool/django_app;pwd;python manage.py test\n \tcd example/issues/251_dotted_unexistent;pwd;python app.py\n \tcd example/issues/266_envvar_from_env_override;pwd;python app.py\n+\tcd example/issues/288_null_values;pwd;python app.py\n test_vault:\n \t# @cd example/vault;pwd;python write.py\n \tdocker run --rm --name dynaconf_with_vault -d -e 'VAULT_DEV_ROOT_TOKEN_ID=myroot' -p 8200:8200 vault\ndiff --git a/azure-pipelines.yml b/azure-pipelines.yml\nindex 0cd90b4..9e7ef19 100644\n--- a/azure-pipelines.yml\n+++ b/azure-pipelines.yml\n@@ -3,6 +3,10 @@\n # Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more:\n # https://docs.microsoft.com/azure/devops/pipelines/languages/python\n \n+pr:\n+- master\n+- releases/*\n+\n trigger:\n - master\n \ndiff --git a/dynaconf/base.py b/dynaconf/base.py\nindex 57f9aa7..99b44ba 100644\n--- a/dynaconf/base.py\n+++ b/dynaconf/base.py\n@@ -219,9 +219,9 @@ class Settings(object):\n \n def __getitem__(self, item):\n \"\"\"Allow getting variables as dict keys `settings['KEY']`\"\"\"\n- value = self.get(item)\n- if value is None:\n- raise KeyError(\"{0} does not exists\".format(item))\n+ value = self.get(item, default=empty)\n+ if value is empty:\n+ raise KeyError(\"{0} does not exist\".format(item))\n return value\n \n def __setitem__(self, key, value):\ndiff --git a/dynaconf/loaders/__init__.py b/dynaconf/loaders/__init__.py\nindex d0a9939..ae7fb03 100644\n--- a/dynaconf/loaders/__init__.py\n+++ b/dynaconf/loaders/__init__.py\n@@ -196,7 +196,7 @@ def write(filename, data, env=None):\n raise IOError(\"{0} cannot be found.\".format(loader_name))\n \n data = DynaBox(data).to_dict()\n- if env and env not in data:\n+ if loader is not py_loader and env and env not in data:\n data = {env: data}\n \n loader.write(filename, data, merge=False)\ndiff --git a/dynaconf/loaders/toml_loader.py b/dynaconf/loaders/toml_loader.py\nindex 86892b1..17cfc0d 100644\n--- a/dynaconf/loaders/toml_loader.py\n+++ b/dynaconf/loaders/toml_loader.py\n@@ -57,4 +57,15 @@ def write(settings_path, settings_data, merge=True):\n \"w\",\n encoding=default_settings.ENCODING_FOR_DYNACONF,\n ) as open_file:\n- toml.dump(settings_data, open_file)\n+ toml.dump(encode_nulls(settings_data), open_file)\n+\n+\n+def encode_nulls(data):\n+ \"\"\"TOML does not support `None` so this function transforms to '@none '.\"\"\"\n+ if data is None:\n+ return \"@none \"\n+ if isinstance(data, dict):\n+ return {key: encode_nulls(value) for key, value in data.items()}\n+ elif isinstance(data, (list, tuple)):\n+ return [encode_nulls(item) for item in data]\n+ return data\ndiff --git a/dynaconf/utils/boxing.py b/dynaconf/utils/boxing.py\nindex f163b56..1613bd9 100644\n--- a/dynaconf/utils/boxing.py\n+++ b/dynaconf/utils/boxing.py\n@@ -28,8 +28,6 @@ class DynaBox(Box):\n return self.__class__(super(Box, self).copy())\n \n def get(self, item, default=None, *args, **kwargs):\n- value = super(DynaBox, self).get(item, default, *args, **kwargs)\n- if value is None or value == default:\n- n_item = item.lower() if item.isupper() else upperfy(item)\n- value = super(DynaBox, self).get(n_item, default, *args, **kwargs)\n- return value\n+ if item not in self: # toggle case\n+ item = item.lower() if item.isupper() else upperfy(item)\n+ return super(DynaBox, self).get(item, default, *args, **kwargs)\ndiff --git a/example/issues/288_null_values/.env b/example/issues/288_null_values/.env\nnew file mode 100644\nindex 0000000..e69de29\ndiff --git a/example/issues/288_null_values/app.py b/example/issues/288_null_values/app.py\nnew file mode 100644\nindex 0000000..016ef07\n--- /dev/null\n+++ b/example/issues/288_null_values/app.py\n@@ -0,0 +1,8 @@\n+from dynaconf import settings\n+\n+assert settings[\"NULLED_VALUE_PYTHON\"] is None\n+assert settings[\"nulled_value_json\"] is None\n+assert settings[\"nulled_value_yaml\"] is None\n+assert settings[\"nulled_value_toml\"] is None\n+\n+print(\"#288 PASSED\")\ndiff --git a/example/issues/288_null_values/settings.json b/example/issues/288_null_values/settings.json\nnew file mode 100644\nindex 0000000..eef4cf1\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.json\n@@ -0,0 +1,5 @@\n+{\n+ \"default\": {\n+ \"nulled_value_json\": null\n+ }\n+}\ndiff --git a/example/issues/288_null_values/settings.py b/example/issues/288_null_values/settings.py\nnew file mode 100644\nindex 0000000..c82da42\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.py\n@@ -0,0 +1,1 @@\n+NULLED_VALUE_PYTHON = None\ndiff --git a/example/issues/288_null_values/settings.toml b/example/issues/288_null_values/settings.toml\nnew file mode 100644\nindex 0000000..9a04eee\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.toml\n@@ -0,0 +1,2 @@\n+[default]\n+nulled_value_toml = \"@none \"\ndiff --git a/example/issues/288_null_values/settings.yaml b/example/issues/288_null_values/settings.yaml\nnew file mode 100644\nindex 0000000..25a1cb4\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.yaml\n@@ -0,0 +1,2 @@\n+default:\n+ nulled_value_yaml: null\n", "test_patch": "diff --git a/tests/test_toml_loader.py b/tests/test_toml_loader.py\nindex 6694798..6dd2609 100644\n--- a/tests/test_toml_loader.py\n+++ b/tests/test_toml_loader.py\n@@ -1,6 +1,7 @@\n import pytest\n \n from dynaconf import LazySettings\n+from dynaconf.loaders.toml_loader import encode_nulls\n from dynaconf.loaders.toml_loader import load\n \n settings = LazySettings(ENV_FOR_DYNACONF=\"PRODUCTION\")\n@@ -179,3 +180,16 @@ def test_load_dunder():\n load(settings, filename=toml, env=\"FOO\")\n assert settings.COLORS.gray.code == \"#CCCCCC\"\n assert settings.COLORS.gray.name == \"Gray\"\n+\n+\n+def test_encode_nulls():\n+ assert encode_nulls(None) == \"@none \"\n+ assert encode_nulls([None, None]) == [\"@none \", \"@none \"]\n+ assert encode_nulls((None, None)) == [\"@none \", \"@none \"]\n+ assert encode_nulls({\"nullable\": None}) == {\"nullable\": \"@none \"}\n+ assert encode_nulls(1) == 1\n+ assert encode_nulls(1.1) == 1.1\n+ assert encode_nulls(True) is True\n+ assert encode_nulls(False) is False\n+ assert encode_nulls(\"\") == \"\"\n+ assert encode_nulls(\"text\") == \"text\"\n", "FAIL_TO_PASS": ["tests/test_toml_loader.py::test_load_from_toml", "tests/test_toml_loader.py::test_load_from_multiple_toml", "tests/test_toml_loader.py::test_no_filename_is_none", "tests/test_toml_loader.py::test_key_error_on_invalid_env", "tests/test_toml_loader.py::test_no_key_error_on_invalid_env", "tests/test_toml_loader.py::test_load_single_key", "tests/test_toml_loader.py::test_empty_value", "tests/test_toml_loader.py::test_multiple_filenames", "tests/test_toml_loader.py::test_cleaner", "tests/test_toml_loader.py::test_using_env", "tests/test_toml_loader.py::test_load_dunder", "tests/test_toml_loader.py::test_encode_nulls"]}], "all_FAIL_TO_PASS": ["tests/test_toml_loader.py::test_load_from_toml", "tests/test_toml_loader.py::test_load_from_multiple_toml", "tests/test_toml_loader.py::test_no_filename_is_none", "tests/test_toml_loader.py::test_key_error_on_invalid_env", "tests/test_toml_loader.py::test_no_key_error_on_invalid_env", "tests/test_toml_loader.py::test_load_single_key", "tests/test_toml_loader.py::test_empty_value", "tests/test_toml_loader.py::test_multiple_filenames", "tests/test_toml_loader.py::test_cleaner", "tests/test_toml_loader.py::test_using_env", "tests/test_toml_loader.py::test_load_dunder", "tests/test_toml_loader.py::test_encode_nulls"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "materials-consortia__optimade-python-tools-547_x1", "level": 1, "source": "swerebenchv2", "repo": "Materials-Consortia/optimade-python-tools", "image": "swerebenchv2/materials-consortia-optimade-python-tools:547-6f34399", "base_commit": "6f3439900630d71f6e23400e4a2aea11d8c5eefd", "num_bugs": 1, "bugs": [{"instance_id": "materials-consortia__optimade-python-tools-547", "base_commit": "6f3439900630d71f6e23400e4a2aea11d8c5eefd", "gold_patch": "diff --git a/openapi/openapi.json b/openapi/openapi.json\nindex ad33b329..98f07741 100644\n--- a/openapi/openapi.json\n+++ b/openapi/openapi.json\n@@ -3050,16 +3050,19 @@\n },\n \"chemical_formula_reduced\": {\n \"title\": \"Chemical Formula Reduced\",\n+ \"pattern\": \"^([A-Z][a-z]?\\\\d*)*$\",\n \"type\": \"string\",\n \"description\": \"The reduced chemical formula for a structure as a string with element symbols and integer chemical proportion numbers.\\nThe proportion number MUST be omitted if it is 1.\\n\\n- **Type**: string\\n\\n- **Requirements/Conventions**:\\n - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.\\n - **Query**: MUST be a queryable property.\\n However, support for filters using partial string matching with this property is OPTIONAL (i.e., BEGINS WITH, ENDS WITH, and CONTAINS).\\n Intricate queries on formula components are instead suggested to be formulated using set-type filter operators on the multi valued `elements` and `elements_ratios` properties.\\n - Element names MUST have proper capitalization (e.g., `\\\"Si\\\"`, not `\\\"SI\\\"` for \\\"silicon\\\").\\n - Elements MUST be placed in alphabetical order, followed by their integer chemical proportion number.\\n - For structures with no partial occupation, the chemical proportion numbers are the smallest integers for which the chemical proportion is exactly correct.\\n - For structures with partial occupation, the chemical proportion numbers are integers that within reasonable approximation indicate the correct chemical proportions. The precise details of how to perform the rounding is chosen by the API implementation.\\n - No spaces or separators are allowed.\\n\\n- **Examples**:\\n - `\\\"H2NaO\\\"`\\n - `\\\"ClNa\\\"`\\n - `\\\"CCaO3\\\"`\\n\\n- **Query examples**:\\n - A filter that matches an exactly given formula is `chemical_formula_reduced=\\\"H2NaO\\\"`.\"\n },\n \"chemical_formula_hill\": {\n \"title\": \"Chemical Formula Hill\",\n+ \"pattern\": \"^([A-Z][a-z]?\\\\d*)*$\",\n \"type\": \"string\",\n \"description\": \"The chemical formula for a structure in [Hill form](https://dx.doi.org/10.1021/ja02046a005) with element symbols followed by integer chemical proportion numbers. The proportion number MUST be omitted if it is 1.\\n\\n- **Type**: string\\n\\n- **Requirements/Conventions**:\\n - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`.\\n - **Query**: Support for queries on this property is OPTIONAL.\\n If supported, only a subset of the filter features MAY be supported.\\n - The overall scale factor of the chemical proportions is chosen such that the resulting values are integers that indicate the most chemically relevant unit of which the system is composed.\\n For example, if the structure is a repeating unit cell with four hydrogens and four oxygens that represents two hydroperoxide molecules, `chemical_formula_hill` is `\\\"H2O2\\\"` (i.e., not `\\\"HO\\\"`, nor `\\\"H4O4\\\"`).\\n - If the chemical insight needed to ascribe a Hill formula to the system is not present, the property MUST be handled as unset.\\n - Element names MUST have proper capitalization (e.g., `\\\"Si\\\"`, not `\\\"SI\\\"` for \\\"silicon\\\").\\n - Elements MUST be placed in [Hill order](https://dx.doi.org/10.1021/ja02046a005), followed by their integer chemical proportion number.\\n Hill order means: if carbon is present, it is placed first, and if also present, hydrogen is placed second.\\n After that, all other elements are ordered alphabetically.\\n If carbon is not present, all elements are ordered alphabetically.\\n - If the system has sites with partial occupation and the total occupations of each element do not all sum up to integers, then the Hill formula SHOULD be handled as unset.\\n - No spaces or separators are allowed.\\n\\n- **Examples**:\\n - `\\\"H2O2\\\"`\\n\\n- **Query examples**:\\n - A filter that matches an exactly given formula is `chemical_formula_hill=\\\"H2O2\\\"`.\"\n },\n \"chemical_formula_anonymous\": {\n \"title\": \"Chemical Formula Anonymous\",\n+ \"pattern\": \"^([A-Z][a-z]?\\\\d*)*$\",\n \"type\": \"string\",\n \"description\": \"The anonymous formula is the `chemical_formula_reduced`, but where the elements are instead first ordered by their chemical proportion number, and then, in order left to right, replaced by anonymous symbols A, B, C, ..., Z, Aa, Ba, ..., Za, Ab, Bb, ... and so on.\\n\\n- **Type**: string\\n\\n- **Requirements/Conventions**:\\n - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.\\n - **Query**: MUST be a queryable property.\\n However, support for filters using partial string matching with this property is OPTIONAL (i.e., BEGINS WITH, ENDS WITH, and CONTAINS).\\n\\n- **Examples**:\\n - `\\\"A2B\\\"`\\n - `\\\"A42B42C16D12E10F9G5\\\"`\\n\\n- **Querying**:\\n - A filter that matches an exactly given formula is `chemical_formula_anonymous=\\\"A2B\\\"`.\"\n },\ndiff --git a/optimade/models/structures.py b/optimade/models/structures.py\nindex bb5483f7..4203824a 100644\n--- a/optimade/models/structures.py\n+++ b/optimade/models/structures.py\n@@ -1,4 +1,5 @@\n # pylint: disable=no-self-argument,line-too-long,no-name-in-module\n+import re\n from enum import IntEnum, Enum\n from sys import float_info\n from typing import List, Optional, Union\n@@ -12,6 +13,8 @@ from optimade.models.utils import (\n OptimadeField,\n StrictField,\n SupportLevel,\n+ ANONYMOUS_ELEMENTS,\n+ CHEMICAL_FORMULA_REGEXP,\n )\n \n EXTENDED_CHEMICAL_SYMBOLS = CHEMICAL_SYMBOLS + EXTRA_SYMBOLS\n@@ -366,6 +369,7 @@ The proportion number MUST be omitted if it is 1.\n - A filter that matches an exactly given formula is `chemical_formula_reduced=\"H2NaO\"`.\"\"\",\n support=SupportLevel.SHOULD,\n queryable=SupportLevel.MUST,\n+ regex=CHEMICAL_FORMULA_REGEXP,\n )\n \n chemical_formula_hill: Optional[str] = OptimadeField(\n@@ -396,6 +400,7 @@ The proportion number MUST be omitted if it is 1.\n - A filter that matches an exactly given formula is `chemical_formula_hill=\"H2O2\"`.\"\"\",\n support=SupportLevel.OPTIONAL,\n queryable=SupportLevel.OPTIONAL,\n+ regex=CHEMICAL_FORMULA_REGEXP,\n )\n \n chemical_formula_anonymous: str = OptimadeField(\n@@ -417,6 +422,7 @@ The proportion number MUST be omitted if it is 1.\n - A filter that matches an exactly given formula is `chemical_formula_anonymous=\"A2B\"`.\"\"\",\n support=SupportLevel.SHOULD,\n queryable=SupportLevel.MUST,\n+ regex=CHEMICAL_FORMULA_REGEXP,\n )\n \n dimension_types: conlist(Periodicity, min_items=3, max_items=3) = OptimadeField(\n@@ -758,6 +764,62 @@ The properties of the species are found in the property `species`.\n queryable=SupportLevel.MUST,\n )\n \n+ @validator(\"chemical_formula_reduced\", \"chemical_formula_hill\")\n+ def check_ordered_formula(cls, v, field):\n+ if v is None:\n+ return v\n+\n+ numbers = re.findall(r\"(\\d+\\.?)+\", v)\n+ elements = re.findall(r\"[A-Z][a-z]?\", v)\n+ expected_elements = sorted(elements)\n+\n+ if field.name == \"chemical_formula_hill\":\n+ for elem in (\"C\", \"H\"):\n+ if elem in expected_elements:\n+ expected_elements.pop(expected_elements.index(elem))\n+ expected_elements.insert(0, elem)\n+\n+ if any(elem not in CHEMICAL_SYMBOLS for elem in elements):\n+ raise ValueError(\n+ f\"Cannot use unknown chemical symbols {[elem for elem in elements if elem not in CHEMICAL_SYMBOLS]} in {field.name!r}\"\n+ )\n+\n+ if \"1\" in numbers:\n+ raise ValueError(\n+ \"Must omit proportion '1' from formula {v} in {field.name!r}\"\n+ )\n+ if expected_elements != elements:\n+ order = \"Hill\" if field == \"chemical_formula_hill\" else \"alphabetical\"\n+ raise ValueError(\n+ f\"Elements in {field.name!r} must appear in {order} order: {expected_elements} not {elements}.\"\n+ )\n+\n+ return v\n+\n+ @validator(\"chemical_formula_anonymous\")\n+ def check_anonymous_formula(cls, v):\n+ elements = tuple(re.findall(r\"[A-Z][a-z]*\", v))\n+ numbers = [int(n.strip()) for n in re.split(r\"[A-Z][a-z]*\", v) if n.strip()]\n+\n+ if any(n == 1 for n in numbers):\n+ raise ValueError(\n+ \"'chemical_formula_anonymous' {v} must omit proportion '1'\"\n+ )\n+\n+ expected_labels = ANONYMOUS_ELEMENTS[: len(elements)]\n+ expected_numbers = sorted(numbers, reverse=True)\n+\n+ if expected_numbers != numbers:\n+ raise ValueError(\n+ f\"'chemical_formula_anonymous' {v} has wrong order: elements with highest proportion should appear first: {numbers} vs expected {expected_numbers}\"\n+ )\n+ if elements != expected_labels:\n+ raise ValueError(\n+ f\"'chemical_formula_anonymous' {v} has wrong labels: {elements} vs expected {expected_labels}.\"\n+ )\n+\n+ return v\n+\n @validator(\"elements\", each_item=True)\n def element_must_be_chemical_symbol(cls, v):\n if v not in CHEMICAL_SYMBOLS:\n@@ -778,12 +840,6 @@ The properties of the species are found in the property `species`.\n )\n return v\n \n- @validator(\"chemical_formula_reduced\", \"chemical_formula_hill\")\n- def no_spaces_in_reduced(cls, v):\n- if v and \" \" in v:\n- raise ValueError(f\"Spaces are not allowed, you passed: {v}\")\n- return v\n-\n @validator(\"nperiodic_dimensions\")\n def check_periodic_dimensions(cls, v, values):\n if values.get(\"dimension_types\", []) and v is None:\ndiff --git a/optimade/models/utils.py b/optimade/models/utils.py\nindex 5f02f3c1..f3765e41 100644\n--- a/optimade/models/utils.py\n+++ b/optimade/models/utils.py\n@@ -1,6 +1,7 @@\n import inspect\n import warnings\n import re\n+import itertools\n from enum import Enum\n from typing import Optional\n \n@@ -182,6 +183,22 @@ class SemanticVersion(str):\n return f\"{self.major}.{self.minor}.{self.patch}\"\n \n \n+def anonymous_element_generator():\n+ \"\"\" Generator that yields the next symbol in the A, B, Aa, ... Az naming scheme. \"\"\"\n+ from string import ascii_lowercase\n+\n+ for size in itertools.count(1):\n+ for s in itertools.product(ascii_lowercase, repeat=size):\n+ s = list(s)\n+ s[0] = s[0].upper()\n+ yield \"\".join(s)\n+\n+\n+ANONYMOUS_ELEMENTS = tuple(itertools.islice(anonymous_element_generator(), 150))\n+\"\"\" Returns the first 150 values of the anonymous element generator. \"\"\"\n+\n+CHEMICAL_FORMULA_REGEXP = r\"^([A-Z][a-z]?\\d*)*$\"\n+\n EXTRA_SYMBOLS = [\"X\", \"vacancy\"]\n \n CHEMICAL_SYMBOLS = [\ndiff --git a/setup.py b/setup.py\nindex 9db85cfd..a222f209 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -89,7 +89,7 @@ setup(\n install_requires=[\n \"lark-parser~=0.10.1\",\n \"fastapi~=0.61.1\",\n- \"pydantic~=1.6\",\n+ \"pydantic~=1.6.1\",\n \"email_validator~=1.1\",\n \"requests~=2.24\",\n 'typing-extensions~=3.7;python_version<\"3.8\"',\n", "test_patch": "diff --git a/optimade/server/data/test_structures.json b/optimade/server/data/test_structures.json\nindex 65bf537a..6bd7d291 100644\n--- a/optimade/server/data/test_structures.json\n+++ b/optimade/server/data/test_structures.json\n@@ -64,11 +64,14 @@\n \"structure_features\": [],\n \"task_id\": \"mpf_1\",\n \"relationships\": {\n- \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"dijkstra1968\"}\n- ]\n- }\n+ \"references\": {\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"dijkstra1968\"\n+ }\n+ ]\n+ }\n }\n },\n {\n@@ -176,11 +179,14 @@\n \"structure_features\": [],\n \"task_id\": \"mpf_2\",\n \"relationships\": {\n- \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"dijkstra1968\"}\n- ]\n- }\n+ \"references\": {\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"dijkstra1968\"\n+ }\n+ ]\n+ }\n }\n },\n {\n@@ -288,11 +294,14 @@\n \"structure_features\": [],\n \"task_id\": \"mpf_3\",\n \"relationships\": {\n- \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"maddox1988\"}\n- ]\n- }\n+ \"references\": {\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"maddox1988\"\n+ }\n+ ]\n+ }\n }\n },\n {\n@@ -556,7 +565,7 @@\n ],\n \"nelements\": 4,\n \"nsites\": 5,\n- \"pretty_formula\": \"AcCuO2F\",\n+ \"pretty_formula\": \"AcCuFO2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -798,7 +807,7 @@\n ],\n \"nelements\": 4,\n \"nsites\": 16,\n- \"pretty_formula\": \"Ag10Te4BrCl\",\n+ \"pretty_formula\": \"Ag10BrClTe4\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -960,7 +969,7 @@\n ],\n \"nelements\": 6,\n \"nsites\": 10,\n- \"pretty_formula\": \"Ag2CSNClO4\",\n+ \"pretty_formula\": \"Ag2CClNO4S\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1202,7 +1211,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 24,\n- \"pretty_formula\": \"Ag2H12C6N3Cl\",\n+ \"pretty_formula\": \"Ag2C6ClH12N3\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1454,7 +1463,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 25,\n- \"pretty_formula\": \"Ag2H2C2N6O13\",\n+ \"pretty_formula\": \"Ag2C2H2N6O13\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1701,7 +1710,7 @@\n ],\n \"nelements\": 7,\n \"nsites\": 23,\n- \"pretty_formula\": \"Ag2H8C2S2N5ClO3\",\n+ \"pretty_formula\": \"Ag2C2ClH8N5O3S2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1937,7 +1946,7 @@\n ],\n \"nelements\": 6,\n \"nsites\": 18,\n- \"pretty_formula\": \"Ag4Hg5S5IBrCl2\",\n+ \"pretty_formula\": \"Ag4BrCl2Hg5IS5\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -2443,7 +2452,7 @@\n ],\n \"nelements\": 8,\n \"nsites\": 74,\n- \"pretty_formula\": \"AgB10P2H40C15NCl2O3\",\n+ \"pretty_formula\": \"AgB10C15Cl2H40NO3P2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -2796,7 +2805,7 @@\n ],\n \"nelements\": 7,\n \"nsites\": 29,\n- \"pretty_formula\": \"AgH14C3S3N6ClO\",\n+ \"pretty_formula\": \"AgC3ClH14N6OS3\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -3172,7 +3181,7 @@\n ],\n \"nelements\": 8,\n \"nsites\": 44,\n- \"pretty_formula\": \"Ba2NaCe2Ti2FeSi8HO27\",\n+ \"pretty_formula\": \"Ba2Ce2FeHNaO27Si8Ti2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -3574,7 +3583,7 @@\n ],\n \"nelements\": 9,\n \"nsites\": 44,\n- \"pretty_formula\": \"Ba2NaTi2MnRe2Si8HO26F\",\n+ \"pretty_formula\": \"Ba2FHMnNaO26Re2Si8Ti2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -3708,9 +3717,12 @@\n \"task_id\": \"mpf_3819\",\n \"relationships\": {\n \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"dummy/2019\"}\n- ]\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"dummy/2019\"\n+ }\n+ ]\n }\n }\n }\ndiff --git a/tests/adapters/structures/raw_test_structures.json b/tests/adapters/structures/raw_test_structures.json\nindex 082d55e0..be13ed70 100644\n--- a/tests/adapters/structures/raw_test_structures.json\n+++ b/tests/adapters/structures/raw_test_structures.json\n@@ -506,7 +506,7 @@\n 0.4\n ],\n \"chemical_formula_descriptive\": \"AcCuO2F\",\n- \"chemical_formula_reduced\": \"AcCuO2F\",\n+ \"chemical_formula_reduced\": \"AcCuFO2\",\n \"chemical_formula_anonymous\": \"A2BCD\",\n \"dimension_types\": [\n 1,\n@@ -691,7 +691,7 @@\n 0.25\n ],\n \"chemical_formula_descriptive\": \"Ag10Te4BrCl\",\n- \"chemical_formula_reduced\": \"Ag10Te4BrCl\",\n+ \"chemical_formula_reduced\": \"Ag10BrClTe4\",\n \"chemical_formula_anonymous\": \"A10B4CD\",\n \"dimension_types\": [\n 1,\n@@ -882,7 +882,7 @@\n 0.1\n ],\n \"chemical_formula_descriptive\": \"Ag2CSNClO4\",\n- \"chemical_formula_reduced\": \"Ag2CSNClO4\",\n+ \"chemical_formula_reduced\": \"Ag2CClNO4S\",\n \"chemical_formula_anonymous\": \"A4B2CDEF\",\n \"dimension_types\": [\n 1,\n@@ -1053,7 +1053,7 @@\n 0.125\n ],\n \"chemical_formula_descriptive\": \"Ag2H12C6N3Cl\",\n- \"chemical_formula_reduced\": \"Ag2H12C6N3Cl\",\n+ \"chemical_formula_reduced\": \"Ag2C6ClH12N3\",\n \"chemical_formula_anonymous\": \"A12B6C3D2E\",\n \"dimension_types\": [\n 1,\n@@ -1299,7 +1299,7 @@\n 0.52\n ],\n \"chemical_formula_descriptive\": \"Ag2H2C2N6O13\",\n- \"chemical_formula_reduced\": \"Ag2H2C2N6O13\",\n+ \"chemical_formula_reduced\": \"Ag2C2H2N6O13\",\n \"chemical_formula_anonymous\": \"A13B6C2D2E2\",\n \"dimension_types\": [\n 1,\n@@ -1555,7 +1555,7 @@\n 0.08695652173913043\n ],\n \"chemical_formula_descriptive\": \"Ag2H8C2S2N5ClO3\",\n- \"chemical_formula_reduced\": \"Ag2H8C2S2N5ClO3\",\n+ \"chemical_formula_reduced\": \"Ag2C2ClH8N5O3S2\",\n \"chemical_formula_anonymous\": \"A8B5C3D2E2F2G\",\n \"dimension_types\": [\n 1,\n@@ -1815,7 +1815,7 @@\n 0.2777777777777778\n ],\n \"chemical_formula_descriptive\": \"Ag4Hg5S5IBrCl2\",\n- \"chemical_formula_reduced\": \"Ag4Hg5S5IBrCl2\",\n+ \"chemical_formula_reduced\": \"Ag4BrCl2Hg5IS5\",\n \"chemical_formula_anonymous\": \"A5B5C4D2EF\",\n \"dimension_types\": [\n 1,\n@@ -2040,7 +2040,7 @@\n 0.02702702702702703\n ],\n \"chemical_formula_descriptive\": \"AgB10P2H40C15NCl2O3\",\n- \"chemical_formula_reduced\": \"AgB10P2H40C15NCl2O3\",\n+ \"chemical_formula_reduced\": \"AgB10C15Cl2H40NO3P2\",\n \"chemical_formula_anonymous\": \"A40B15C10D3E2F2GH\",\n \"dimension_types\": [\n 1,\n@@ -2617,7 +2617,7 @@\n 0.10344827586206896\n ],\n \"chemical_formula_descriptive\": \"AgH14C3S3N6ClO\",\n- \"chemical_formula_reduced\": \"AgH14C3S3N6ClO\",\n+ \"chemical_formula_reduced\": \"AgC3ClH14N6OS3\",\n \"chemical_formula_anonymous\": \"A14B6C3D3EFG\",\n \"dimension_types\": [\n 1,\n@@ -2917,7 +2917,7 @@\n 0.045454545454545456\n ],\n \"chemical_formula_descriptive\": \"Ba2NaCe2Ti2FeSi8HO27\",\n- \"chemical_formula_reduced\": \"Ba2NaCe2Ti2FeSi8HO27\",\n+ \"chemical_formula_reduced\": \"Ba2Ce2FeHNaO27Si8Ti2\",\n \"chemical_formula_anonymous\": \"A27B8C2D2E2FGH\",\n \"dimension_types\": [\n 1,\n@@ -3318,7 +3318,7 @@\n 0.045454545454545456\n ],\n \"chemical_formula_descriptive\": \"Ba2NaTi2MnRe2Si8HO26F\",\n- \"chemical_formula_reduced\": \"Ba2NaTi2MnRe2Si8HO26F\",\n+ \"chemical_formula_reduced\": \"Ba2FHMnNaO26Re2Si8Ti2\",\n \"chemical_formula_anonymous\": \"A26B8C2D2E2FGHI\",\n \"dimension_types\": [\n 1,\ndiff --git a/tests/models/conftest.py b/tests/models/conftest.py\nindex cb964f4b..ff0daebe 100644\n--- a/tests/models/conftest.py\n+++ b/tests/models/conftest.py\n@@ -63,3 +63,49 @@ def starting_links() -> dict:\n \"aggregate\": \"test\",\n \"no_aggregate_reason\": \"This is a test database\",\n }\n+\n+\n+@pytest.fixture(scope=\"function\")\n+def good_structure() -> dict:\n+ \"\"\"Returns a 'good' structure that does not need to be mapped, which can be\n+ deformed to test different validators.\n+\n+ \"\"\"\n+ import datetime\n+\n+ return {\n+ \"id\": \"db/1234567\",\n+ \"type\": \"structures\",\n+ \"attributes\": {\n+ \"last_modified\": datetime.datetime.now(),\n+ \"elements\": [\"Ge\", \"Si\"],\n+ \"nsites\": 3,\n+ \"nelements\": 2,\n+ \"elements_ratios\": [0.5, 0.5],\n+ \"chemical_formula_reduced\": \"GeSi\",\n+ \"chemical_formula_hill\": \"GeSi\",\n+ \"chemical_formula_descriptive\": \"GeSi\",\n+ \"chemical_formula_anonymous\": \"AB\",\n+ \"dimension_types\": [1, 1, 1],\n+ \"nperiodic_dimensions\": 3,\n+ \"lattice_vectors\": [[4.0, 0.0, 0.0], [0.0, 4.0, 0.0], [0.0, 1.0, 4.0]],\n+ \"cartesian_site_positions\": [[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n+ \"species\": [\n+ {\"name\": \"Si\", \"chemical_symbols\": [\"Si\"], \"concentration\": [1.0]},\n+ {\"name\": \"Ge\", \"chemical_symbols\": [\"Ge\"], \"concentration\": [1.0]},\n+ {\n+ \"name\": \"vac\",\n+ \"chemical_symbols\": [\"vacancy\"],\n+ \"concentration\": [1.0],\n+ },\n+ ],\n+ \"species_at_sites\": [\"Si\", \"Ge\", \"vac\"],\n+ \"assemblies\": [\n+ {\n+ \"sites_in_groups\": [[0], [1], [2]],\n+ \"group_probabilities\": [0.3, 0.5, 0.2],\n+ }\n+ ],\n+ \"structure_features\": [\"assemblies\"],\n+ },\n+ }\ndiff --git a/tests/models/test_data/test_bad_structures.json b/tests/models/test_data/test_bad_structures.json\nindex 12697659..100feb90 100644\n--- a/tests/models/test_data/test_bad_structures.json\n+++ b/tests/models/test_data/test_bad_structures.json\n@@ -772,7 +772,7 @@\n ],\n \"nelements\": 4,\n \"nsites\": 16,\n- \"pretty_formula\": \"Ag10Te4BrCl\",\n+ \"pretty_formula\": \"Ag10BrClTe4\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -934,7 +934,7 @@\n ],\n \"nelements\": 6,\n \"nsites\": 10,\n- \"pretty_formula\": \"Ag2CSNClO4\",\n+ \"pretty_formula\": \"Ag2CClNO4S\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1176,7 +1176,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 24,\n- \"pretty_formula\": \"Ag2H12C6N3Cl\",\n+ \"pretty_formula\": \"Ag2C6ClH12N3\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1428,7 +1428,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 25,\n- \"pretty_formula\": \"Ag2H2C2N6O13\",\n+ \"pretty_formula\": \"Ag2C2H2N6O13\",\n \"species\": [\n {\n \"chemical_symbols\": [\ndiff --git a/tests/models/test_structures.py b/tests/models/test_structures.py\nindex 31ad9d2f..24d63877 100644\n--- a/tests/models/test_structures.py\n+++ b/tests/models/test_structures.py\n@@ -39,3 +39,44 @@ def test_bad_structures(bad_structures, mapper):\n print(f\"Trying structure number {index} from 'test_bad_structures.json'\")\n with pytest.raises(ValidationError):\n StructureResource(**mapper(MAPPER).map_back(structure))\n+\n+\n+deformities = (\n+ None,\n+ {\"chemical_formula_anonymous\": \"AaBC\"},\n+ {\"chemical_formula_anonymous\": \"BC\"},\n+ {\"chemical_formula_anonymous\": \"A1B1\"},\n+ {\"chemical_formula_anonymous\": \"BC1\"},\n+ {\"chemical_formula_anonymous\": \"A9C\"},\n+ {\"chemical_formula_anonymous\": \"A9.2B\"},\n+ {\"chemical_formula_anonymous\": \"A2B90\"},\n+ {\"chemical_formula_anonymous\": \"A2B10\"},\n+ {\"chemical_formula_hill\": \"SiGe\"},\n+ {\"chemical_formula_hill\": \"GeHSi\"},\n+ {\"chemical_formula_hill\": \"CGeHSi\"},\n+ {\"chemical_formula_reduced\": \"Ge1.0Si1.0\"},\n+ {\"chemical_formula_reduced\": \"GeSi2.0\"},\n+ {\"chemical_formula_reduced\": \"GeSi.2\"},\n+ {\"chemical_formula_reduced\": \"Ge1Si\"},\n+ {\"chemical_formula_reduced\": \"GeSi1\"},\n+ {\"chemical_formula_reduced\": \"SiGe2\"},\n+ {\"chemical_formula_reduced\": \"FaKeElEmENtS\"},\n+ {\"chemical_formula_reduced\": \"abcd\"},\n+ {\"chemical_formula_reduced\": \"a2BeH\"},\n+ {\"chemical_formula_reduced\": \"............\"},\n+ {\"chemical_formula_reduced\": \"Ag6 Cl2\"},\n+)\n+\n+\n+@pytest.mark.parametrize(\"deformity\", deformities)\n+def test_structure_deformities(good_structure, deformity):\n+ \"\"\"Make specific checks upon performing single invalidating deformations\n+ of the data of a good structure.\n+\n+ \"\"\"\n+ if deformity is None:\n+ StructureResource(**good_structure)\n+ else:\n+ good_structure[\"attributes\"].update(deformity)\n+ with pytest.raises(ValidationError, match=fr\".*{list(deformity.keys())[0]}.*\"):\n+ StructureResource(**good_structure)\ndiff --git a/tests/models/test_utils.py b/tests/models/test_utils.py\nindex 279d4d68..61d10d47 100644\n--- a/tests/models/test_utils.py\n+++ b/tests/models/test_utils.py\n@@ -1,5 +1,5 @@\n import pytest\n-from pydantic import BaseModel\n+from pydantic import BaseModel, ValidationError, Field\n from optimade.models.utils import OptimadeField, StrictField, SupportLevel\n from typing import List, Callable\n \n@@ -74,3 +74,40 @@ def test_compatible_strict_optimade_field():\n strict_schema = CorrectModelWithStrictField.schema()\n strict_schema[\"title\"] = optimade_schema[\"title\"]\n assert strict_schema == optimade_schema\n+\n+\n+def test_formula_regexp():\n+ \"\"\"This test checks some simple chemical formulae with the\n+ `CHEMICAL_FORMULA_REGEXP`.\n+\n+ \"\"\"\n+ import re\n+ from optimade.models.utils import CHEMICAL_FORMULA_REGEXP\n+\n+ class DummyModel(BaseModel):\n+ formula: str = Field(regex=CHEMICAL_FORMULA_REGEXP)\n+\n+ good_formulae = (\n+ \"AgCl\",\n+ \"H5F\",\n+ \"LiP5\",\n+ \"Jn7Qb4\", # Regexp does not care about the actual existence of elements\n+ \"A5B213CeD3E65F12G\",\n+ \"A1Be2\",\n+ )\n+\n+ bad_formulae = (\n+ \"Ag...Cl\",\n+ \"123123\",\n+ \"Ag Cl\",\n+ \"abcd\",\n+ \"6F7G\",\n+ )\n+\n+ for formula in good_formulae:\n+ assert re.match(CHEMICAL_FORMULA_REGEXP, formula)\n+ assert DummyModel(formula=formula)\n+\n+ for formula in bad_formulae:\n+ with pytest.raises(ValidationError):\n+ assert DummyModel(formula=formula)\ndiff --git a/tests/server/query_params/test_filter.py b/tests/server/query_params/test_filter.py\nindex 213ca68b..2633d162 100644\n--- a/tests/server/query_params/test_filter.py\n+++ b/tests/server/query_params/test_filter.py\n@@ -208,13 +208,13 @@ def test_string_contains(check_response):\n \n \n def test_string_start(check_response):\n- request = '/structures?filter=chemical_formula_descriptive STARTS WITH \"Ag2CSNCl\"'\n+ request = '/structures?filter=chemical_formula_descriptive STARTS WITH \"Ag2CClN\"'\n expected_ids = [\"mpf_259\"]\n check_response(request, expected_ids)\n \n \n def test_string_end(check_response):\n- request = '/structures?filter=chemical_formula_descriptive ENDS WITH \"NClO4\"'\n+ request = '/structures?filter=chemical_formula_descriptive ENDS WITH \"ClNO4S\"'\n expected_ids = [\"mpf_259\"]\n check_response(request, expected_ids)\n \n@@ -237,7 +237,7 @@ def test_awkward_not_queries(check_response, client):\n \"\"\"\n expected_ids = [\"mpf_3819\"]\n request = (\n- '/structures?filter=chemical_formula_descriptive=\"Ba2NaTi2MnRe2Si8HO26F\" AND '\n+ '/structures?filter=chemical_formula_descriptive=\"Ba2FHMnNaO26Re2Si8Ti2\" AND '\n 'chemical_formula_anonymous = \"A26B8C2D2E2FGHI\" '\n )\n check_response(request, expected_ids)\n@@ -260,7 +260,7 @@ def test_awkward_not_queries(check_response, client):\n request = (\n \"/structures?filter=\"\n \"NOT ( \"\n- 'chemical_formula_descriptive = \"Ba2NaTi2MnRe2Si8HO26F\" AND '\n+ 'chemical_formula_descriptive = \"Ba2FHMnNaO26Re2Si8Ti2\" AND '\n 'chemical_formula_anonymous = \"A26B8C2D2E2FGHI\" OR '\n 'chemical_formula_anonymous = \"A2BC\" AND '\n 'NOT chemical_formula_descriptive = \"Ac2AgPb\" '\n", "FAIL_TO_PASS": ["tests/models/test_structures.py::test_structure_deformities[deformity1]", "tests/models/test_structures.py::test_structure_deformities[deformity2]", "tests/models/test_structures.py::test_structure_deformities[deformity3]", "tests/models/test_structures.py::test_structure_deformities[deformity4]", "tests/models/test_structures.py::test_structure_deformities[deformity5]", "tests/models/test_structures.py::test_structure_deformities[deformity6]", "tests/models/test_structures.py::test_structure_deformities[deformity7]", "tests/models/test_structures.py::test_structure_deformities[deformity8]", "tests/models/test_structures.py::test_structure_deformities[deformity9]", "tests/models/test_structures.py::test_structure_deformities[deformity10]", "tests/models/test_structures.py::test_structure_deformities[deformity11]", "tests/models/test_structures.py::test_structure_deformities[deformity12]", "tests/models/test_structures.py::test_structure_deformities[deformity13]", "tests/models/test_structures.py::test_structure_deformities[deformity14]", "tests/models/test_structures.py::test_structure_deformities[deformity15]", "tests/models/test_structures.py::test_structure_deformities[deformity16]", "tests/models/test_structures.py::test_structure_deformities[deformity17]", "tests/models/test_structures.py::test_structure_deformities[deformity18]", "tests/models/test_structures.py::test_structure_deformities[deformity19]", "tests/models/test_structures.py::test_structure_deformities[deformity20]", "tests/models/test_structures.py::test_structure_deformities[deformity21]", "tests/models/test_utils.py::test_formula_regexp"]}], "all_FAIL_TO_PASS": ["tests/models/test_structures.py::test_structure_deformities[deformity1]", "tests/models/test_structures.py::test_structure_deformities[deformity2]", "tests/models/test_structures.py::test_structure_deformities[deformity3]", "tests/models/test_structures.py::test_structure_deformities[deformity4]", "tests/models/test_structures.py::test_structure_deformities[deformity5]", "tests/models/test_structures.py::test_structure_deformities[deformity6]", "tests/models/test_structures.py::test_structure_deformities[deformity7]", "tests/models/test_structures.py::test_structure_deformities[deformity8]", "tests/models/test_structures.py::test_structure_deformities[deformity9]", "tests/models/test_structures.py::test_structure_deformities[deformity10]", "tests/models/test_structures.py::test_structure_deformities[deformity11]", "tests/models/test_structures.py::test_structure_deformities[deformity12]", "tests/models/test_structures.py::test_structure_deformities[deformity13]", "tests/models/test_structures.py::test_structure_deformities[deformity14]", "tests/models/test_structures.py::test_structure_deformities[deformity15]", "tests/models/test_structures.py::test_structure_deformities[deformity16]", "tests/models/test_structures.py::test_structure_deformities[deformity17]", "tests/models/test_structures.py::test_structure_deformities[deformity18]", "tests/models/test_structures.py::test_structure_deformities[deformity19]", "tests/models/test_structures.py::test_structure_deformities[deformity20]", "tests/models/test_structures.py::test_structure_deformities[deformity21]", "tests/models/test_utils.py::test_formula_regexp"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "toblerity__shapely-1174_x1", "level": 1, "source": "swerebenchv2", "repo": "Toblerity/Shapely", "image": "swerebenchv2/toblerity-shapely:1174-a228836", "base_commit": "a2288360b5b4664f645199a7a605c3a062e426eb", "num_bugs": 1, "bugs": [{"instance_id": "toblerity__shapely-1174", "base_commit": "a2288360b5b4664f645199a7a605c3a062e426eb", "gold_patch": "diff --git a/shapely/coords.py b/shapely/coords.py\nindex df673b0..ce526ef 100644\n--- a/shapely/coords.py\n+++ b/shapely/coords.py\n@@ -116,7 +116,10 @@ class CoordinateSequence:\n def _ctypes(self):\n self._update()\n has_z = self._ndim == 3\n- n = self._ndim\n+ n = self._ndim or 0\n+ if n == 0:\n+ # ignore with NumPy 1.21 __array_interface__\n+ raise AttributeError(\"empty geometry sequence\")\n m = self.__len__()\n array_type = c_double * (m * n)\n data = array_type()\ndiff --git a/shapely/geometry/base.py b/shapely/geometry/base.py\nindex 1ad0d07..2a5eacb 100644\n--- a/shapely/geometry/base.py\n+++ b/shapely/geometry/base.py\n@@ -849,8 +849,8 @@ class BaseMultipartGeometry(BaseGeometry):\n @property\n def __array_interface__(self):\n \"\"\"Provide the Numpy array protocol.\"\"\"\n- raise NotImplementedError(\"Multi-part geometries do not themselves \"\n- \"provide the array interface\")\n+ raise AttributeError(\"Multi-part geometries do not themselves \"\n+ \"provide the array interface\")\n \n def _get_coords(self):\n raise NotImplementedError(\"Sub-geometries may have coordinate \"\ndiff --git a/shapely/geometry/polygon.py b/shapely/geometry/polygon.py\nindex 4386eb4..fabb6f2 100644\n--- a/shapely/geometry/polygon.py\n+++ b/shapely/geometry/polygon.py\n@@ -317,7 +317,7 @@ class Polygon(BaseGeometry):\n \n @property\n def __array_interface__(self):\n- raise NotImplementedError(\n+ raise AttributeError(\n \"A polygon does not itself provide the array interface. Its rings do.\")\n \n def _get_coords(self):\ndiff --git a/shapely/speedups/_speedups.pyx b/shapely/speedups/_speedups.pyx\nindex f5b6dc2..0b49959 100644\n--- a/shapely/speedups/_speedups.pyx\n+++ b/shapely/speedups/_speedups.pyx\n@@ -421,7 +421,10 @@ def coordseq_ctypes(self):\n cdef GEOSCoordSequence *cs\n cdef double *data_p\n self._update()\n- n = self._ndim\n+ n = self._ndim or 0\n+ if n == 0:\n+ # ignore with NumPy 1.21 __array_interface__\n+ raise AttributeError(\"empty geometry sequence\")\n m = self.__len__()\n array_type = ctypes.c_double * (m * n)\n data = array_type()\ndiff --git a/shapely/strtree.py b/shapely/strtree.py\nindex ac1008f..30c79a5 100644\n--- a/shapely/strtree.py\n+++ b/shapely/strtree.py\n@@ -20,7 +20,7 @@ References\n \n import ctypes\n import logging\n-from typing import Any, ItemsView, Iterable, Iterator, Sequence, Tuple, Union\n+from typing import Any, ItemsView, Iterable, Iterator, Optional, Sequence, Tuple, Union\n import sys\n from warnings import warn\n \n@@ -108,27 +108,24 @@ class STRtree:\n self.node_capacity = node_capacity\n self._rev = {\n item: geom\n- for geom, item in self._iterinitdata(\n- zip(geoms, items) if items is not None else geoms\n- )\n+ for geom, item in self._iterinitdata(geoms, items)\n if not geom.is_empty\n }\n-\n if self._rev:\n self._init_tree(self._rev.items())\n \n def _iterinitdata(\n self,\n- initdata: Union[Iterable[Tuple[BaseGeometry, Any]], Iterable[BaseGeometry]],\n+ geoms: Iterable[BaseGeometry], items: Optional[Iterable[BaseGeometry]],\n ) -> Iterator[Tuple[BaseGeometry, Any]]:\n- if not initdata:\n- return\n-\n- for enum_idx, item in enumerate(initdata):\n- if isinstance(item, tuple):\n- yield item[0], item[1]\n- elif isinstance(item, BaseGeometry):\n- yield (item, enum_idx)\n+ if items is not None:\n+ for geom, item in zip(geoms, items):\n+ if isinstance(geom, BaseGeometry):\n+ yield (geom, item)\n+ else:\n+ for enum_idx, geom in enumerate(geoms):\n+ if isinstance(geom, BaseGeometry):\n+ yield (geom, enum_idx)\n \n def _init_tree(self, rev_initdata: ItemsView[Any, BaseGeometry]):\n if rev_initdata:\n", "test_patch": "diff --git a/tests/test_collection.py b/tests/test_collection.py\nindex 09b5c11..5ba176b 100644\n--- a/tests/test_collection.py\n+++ b/tests/test_collection.py\n@@ -114,3 +114,14 @@ def test_len_deprecated(geometrycollection_geojson):\n geom = shape(geometrycollection_geojson)\n with pytest.warns(ShapelyDeprecationWarning, match=\"__len__\"):\n assert len(geom) == 2\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = GeometryCollection([LineString([(0, 0), (1, 1)])])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_linestring.py b/tests/test_linestring.py\nindex 2b6e7f9..a452ff7 100644\n--- a/tests/test_linestring.py\n+++ b/tests/test_linestring.py\n@@ -87,6 +87,7 @@ def test_from_numpy():\n assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)]\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n def test_numpy_empty_linestring_coords():\n np = pytest.importorskip(\"numpy\")\n \n@@ -97,6 +98,17 @@ def test_numpy_empty_linestring_coords():\n assert la.shape == (0,)\n \n \n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = LineString([(0.0, 0.0), (0.0, 1.0)])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\n+\n+\n def test_from_invalid_dim():\n with pytest.raises(ValueError, match=\"at least 2 coordinate tuples\"):\n LineString([(1, 2)])\ndiff --git a/tests/test_multilinestring.py b/tests/test_multilinestring.py\nindex bf79ddf..c6475dc 100644\n--- a/tests/test_multilinestring.py\n+++ b/tests/test_multilinestring.py\n@@ -117,3 +117,14 @@ def test_getitem_deprecated():\n geom = MultiLineString([[[5.0, 6.0], [7.0, 8.0]]])\n with pytest.warns(ShapelyDeprecationWarning, match=\"__getitem__\"):\n part = geom[0]\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = MultiLineString([[[5.0, 6.0], [7.0, 8.0]]])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_multipoint.py b/tests/test_multipoint.py\nindex afbffaf..a3e2914 100644\n--- a/tests/test_multipoint.py\n+++ b/tests/test_multipoint.py\n@@ -129,6 +129,17 @@ def test_multipoint_array_interface_numpy_deprecated():\n np.array(geom)\n \n \n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = MultiPoint(((1.0, 2.0), (3.0, 4.0)))\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\n+\n+\n def test_iteration_deprecated():\n geom = MultiPoint([[5.0, 6.0], [7.0, 8.0]])\n with pytest.warns(ShapelyDeprecationWarning, match=\"Iteration\"):\ndiff --git a/tests/test_multipolygon.py b/tests/test_multipolygon.py\nindex c3982a8..878211a 100644\n--- a/tests/test_multipolygon.py\n+++ b/tests/test_multipolygon.py\n@@ -110,3 +110,16 @@ def test_getitem_deprecated():\n [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))])])\n with pytest.warns(ShapelyDeprecationWarning, match=\"__getitem__\"):\n part = geom[0]\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = MultiPolygon(\n+ [(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)),\n+ [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))])])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_point.py b/tests/test_point.py\nindex 264118c..4a80564 100644\n--- a/tests/test_point.py\n+++ b/tests/test_point.py\n@@ -262,6 +262,7 @@ def test_point_array_interface_numpy_deprecated():\n np.array(p)\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n def test_numpy_empty_point_coords():\n np = pytest.importorskip(\"numpy\")\n \n@@ -270,3 +271,14 @@ def test_numpy_empty_point_coords():\n # Access the coords\n a = np.asarray(pe.coords)\n assert a.shape == (0,)\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = Point(3.0, 4.0)\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_polygon.py b/tests/test_polygon.py\nindex 863b623..62b2f96 100644\n--- a/tests/test_polygon.py\n+++ b/tests/test_polygon.py\n@@ -109,6 +109,7 @@ def test_numpy_linearring_coords():\n assert_array_equal(ra, expected)\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n def test_numpy_empty_linearring_coords():\n np = pytest.importorskip(\"numpy\")\n \n@@ -116,6 +117,16 @@ def test_numpy_empty_linearring_coords():\n assert np.asarray(ring.coords).shape == (0,)\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\n+\n+\n def test_polygon_from_coordinate_sequence():\n coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]\n \ndiff --git a/tests/test_strtree.py b/tests/test_strtree.py\nindex 55b61c4..e1402cc 100644\n--- a/tests/test_strtree.py\n+++ b/tests/test_strtree.py\n@@ -7,14 +7,19 @@ import sys\n import pytest\n \n from shapely.errors import ShapelyDeprecationWarning\n-from shapely.geometry import Point, Polygon\n+from shapely.geometry import Point, Polygon, box\n from shapely.geos import geos_version\n from shapely import strtree\n from shapely.strtree import STRtree\n+from shapely import wkt\n \n from .conftest import requires_geos_342\n \n \n+point = Point(2, 3)\n+empty = wkt.loads(\"GEOMETRYCOLLECTION EMPTY\")\n+\n+\n @requires_geos_342\n @pytest.mark.parametrize(\"geoms\", [[Point(i, i) for i in range(10)]])\n @pytest.mark.parametrize(\n@@ -37,11 +42,43 @@ def test_query(geoms, query_geom, num_results):\n def test_query_enumeration_idx(geoms, query_geom, expected):\n \"\"\"Store enumeration idx\"\"\"\n with pytest.warns(ShapelyDeprecationWarning):\n- tree = STRtree((g, i) for i, g in enumerate(geoms))\n+ tree = STRtree(geoms, range(len(geoms)))\n results = tree.query_items(query_geom)\n assert sorted(results) == sorted(expected)\n \n \n+@requires_geos_342\n+@pytest.mark.parametrize(\"geoms\", [[Point(i, i) for i in range(5)]])\n+@pytest.mark.parametrize(\"items\", [None, list(range(1, 6)), list(\"abcde\")])\n+@pytest.mark.parametrize(\n+ \"query_geom,expected\",\n+ [(Point(2, 2).buffer(0.99), [2]), (Point(2, 2).buffer(1.0), [1, 2, 3])],\n+)\n+def test_query_items(geoms, items, query_geom, expected):\n+ \"\"\"Store enumeration idx\"\"\"\n+ with pytest.warns(ShapelyDeprecationWarning):\n+ tree = STRtree(geoms, items)\n+ results = tree.query_items(query_geom)\n+ expected = [items[idx] for idx in expected] if items is not None else expected\n+ assert sorted(results) == sorted(expected)\n+\n+\n+@pytest.mark.parametrize(\n+ \"tree_geometry, geometry,expected\",\n+ [\n+ ([point], box(0, 0, 10, 10), [0]),\n+ # None/empty is ignored in the tree, but the index of the valid geometry\n+ # should be retained.\n+ ([None, point], box(0, 0, 10, 10), [1]),\n+ ([None, empty, point], box(0, 0, 10, 10), [2]),\n+ ],\n+)\n+def test_query_items_with_empty(tree_geometry, geometry, expected):\n+ with pytest.warns(ShapelyDeprecationWarning):\n+ tree = STRtree(tree_geometry)\n+ assert tree.query_items(geometry) == expected\n+\n+\n @requires_geos_342\n def test_insert_empty_geometry():\n \"\"\"\n@@ -112,7 +149,7 @@ def test_pickle_persistence():\n Don't crash trying to use unpickled GEOS handle.\n \"\"\"\n with pytest.warns(ShapelyDeprecationWarning):\n- tree = STRtree([(Point(i, i).buffer(0.1), i) for i in range(3)])\n+ tree = STRtree([Point(i, i).buffer(0.1) for i in range(3)], range(3))\n \n pickled_strtree = pickle.dumps(tree)\n unpickle_script_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"unpickle-strtree.py\")\n@@ -165,14 +202,14 @@ def test_nearest_item(geoms, items, query_geom):\n assert tree.nearest_item(query_geom) == items[0]\n \n \n-@pytest.mark.parametrize([\"geoms\", \"items\"], [(None, None), ([], None)])\n+@pytest.mark.parametrize([\"geoms\", \"items\"], [([], None), ([], [])])\n def test_nearest_empty(geoms, items):\n with pytest.warns(ShapelyDeprecationWarning):\n tree = STRtree(geoms, items)\n assert tree.nearest_item(None) is None\n \n \n-@pytest.mark.parametrize([\"geoms\", \"items\"], [(None, None), ([], None)])\n+@pytest.mark.parametrize([\"geoms\", \"items\"], [([], None), ([], [])])\n def test_nearest_items(geoms, items):\n with pytest.warns(ShapelyDeprecationWarning):\n tree = STRtree(geoms, items)\n", "FAIL_TO_PASS": ["tests/test_collection.py::test_numpy_object_array", "tests/test_linestring.py::test_numpy_empty_linestring_coords", "tests/test_multilinestring.py::test_numpy_object_array", "tests/test_multipolygon.py::test_numpy_object_array", "tests/test_point.py::test_numpy_empty_point_coords", "tests/test_polygon.py::test_numpy_empty_linearring_coords", "tests/test_polygon.py::test_numpy_object_array"]}], "all_FAIL_TO_PASS": ["tests/test_collection.py::test_numpy_object_array", "tests/test_linestring.py::test_numpy_empty_linestring_coords", "tests/test_multilinestring.py::test_numpy_object_array", "tests/test_multipolygon.py::test_numpy_object_array", "tests/test_point.py::test_numpy_empty_point_coords", "tests/test_polygon.py::test_numpy_empty_linearring_coords", "tests/test_polygon.py::test_numpy_object_array"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "yt-project__unyt-102_x1", "level": 1, "source": "swerebenchv2", "repo": "yt-project/unyt", "image": "swerebenchv2/yt-project-unyt:102-b779d0a", "base_commit": "b779d0a31ed3e5f8d1c035c90e4878a5078b39fc", "num_bugs": 1, "bugs": [{"instance_id": "yt-project__unyt-102", "base_commit": "b779d0a31ed3e5f8d1c035c90e4878a5078b39fc", "gold_patch": "diff --git a/tox.ini b/tox.ini\nindex 6350941..56ee095 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -12,7 +12,7 @@ setenv =\n PYTHONPATH = {toxinidir}\n depends = begin\n deps =\n- pytest\n+ pytest<5.1\n sympy\n numpy\n h5py\n@@ -30,7 +30,7 @@ commands =\n \n [testenv:py35-versions]\n deps =\n- pytest\n+ pytest<5.1\n sympy==1.2\n numpy==1.13.3\n h5py==2.6.0\n@@ -46,7 +46,7 @@ commands =\n \n [testenv:py35-dependencies]\n deps =\n- pytest\n+ pytest<5.1\n sympy\n numpy\n coverage\ndiff --git a/unyt/array.py b/unyt/array.py\nindex d601e85..ac7e643 100644\n--- a/unyt/array.py\n+++ b/unyt/array.py\n@@ -106,6 +106,11 @@ from numpy import (\n matmul,\n )\n from numpy.core.umath import _ones_like\n+\n+try:\n+ from numpy.core.umath import clip\n+except ImportError:\n+ clip = None\n from sympy import Rational\n import warnings\n \n@@ -457,6 +462,7 @@ class unyt_array(np.ndarray):\n heaviside: _preserve_units,\n _ones_like: _preserve_units,\n matmul: _multiply_units,\n+ clip: _passthrough_unit,\n }\n \n __array_priority__ = 2.0\n@@ -1705,10 +1711,21 @@ class unyt_array(np.ndarray):\n \"cannot by multiplied, divide, subtracted or added.\"\n )\n else:\n- raise RuntimeError(\n- \"Support for the %s ufunc with %i inputs has not been\"\n- \"added to unyt_array.\" % (str(ufunc), len(inputs))\n- )\n+ if ufunc is clip:\n+ inp = (inputs[0].view(np.ndarray), inputs[1], inputs[2])\n+ if out is not None:\n+ _out = out.view(np.ndarray)\n+ else:\n+ _out = None\n+ out_arr = ufunc(*inp, out=_out)\n+ unit = inputs[0].units\n+ ret_class = type(inputs[0])\n+ mul = 1\n+ else:\n+ raise RuntimeError(\n+ \"Support for the %s ufunc with %i inputs has not been \"\n+ \"added to unyt_array.\" % (str(ufunc), len(inputs))\n+ )\n if unit is None:\n out_arr = np.array(out_arr, copy=False)\n elif ufunc in (modf, divmod_):\n", "test_patch": "diff --git a/unyt/tests/test_unyt_array.py b/unyt/tests/test_unyt_array.py\nindex e588c5a..18b0f09 100644\n--- a/unyt/tests/test_unyt_array.py\n+++ b/unyt/tests/test_unyt_array.py\n@@ -2264,3 +2264,19 @@ def test_input_units_deprecation():\n unyt_array([1, 2, 3], \"mile\"), unyt_array([1, 2, 3], input_units=\"mile\")\n )\n assert unyt_quantity(3, \"mile\") == unyt_quantity(3, input_units=\"mile\")\n+\n+\n+def test_clip():\n+ from unyt import km\n+\n+ data = [1, 2, 3, 4, 5, 6] * km\n+ answer = [2, 2, 3, 4, 4, 4] * km\n+\n+ ret = np.clip(data, 2, 4)\n+ assert_array_equal(ret, answer)\n+ assert ret.units == answer.units\n+\n+ np.clip(data, 2, 4, out=data)\n+\n+ assert_array_equal(data, answer)\n+ assert data.units == answer.units\n", "FAIL_TO_PASS": ["unyt/tests/test_unyt_array.py::test_clip"]}], "all_FAIL_TO_PASS": ["unyt/tests/test_unyt_array.py::test_clip"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "drivendataorg__cloudpathlib-432_x1", "level": 1, "source": "swerebenchv2", "repo": "drivendataorg/cloudpathlib", "image": "swerebenchv2/drivendataorg-cloudpathlib:432-fabb0e4", "base_commit": "fabb0e43d677e518b5918db9db8d41c56d477071", "num_bugs": 1, "bugs": [{"instance_id": "drivendataorg__cloudpathlib-432", "base_commit": "fabb0e43d677e518b5918db9db8d41c56d477071", "gold_patch": "diff --git a/HISTORY.md b/HISTORY.md\nindex c56f815..a21d821 100644\n--- a/HISTORY.md\n+++ b/HISTORY.md\n@@ -6,6 +6,7 @@\n - Fix `CloudPath` cleanup via `CloudPath.__del__` when `Client` encounters an exception during initialization and does not create a `file_cache_mode` attribute. (Issue [#372](https://github.com/drivendataorg/cloudpathlib/issues/372), thanks to [@bryanwweber](https://github.com/bryanwweber)) \n - Drop support for Python 3.7; pin minimal `boto3` version to Python 3.8+ versions. (PR [#407](https://github.com/drivendataorg/cloudpathlib/pull/407))\n - fix: use native `exists()` method in `GSClient`. (PR [#420](https://github.com/drivendataorg/cloudpathlib/pull/420))\n+- Enhancement: lazy instantiation of default client (PR [#432](https://github.com/drivendataorg/cloudpathlib/issues/432), Issue [#428](https://github.com/drivendataorg/cloudpathlib/issues/428))\n \n ## v0.18.1 (2024-02-26)\n \ndiff --git a/cloudpathlib/cloudpath.py b/cloudpathlib/cloudpath.py\nindex 0c17a4e..afca5cb 100644\n--- a/cloudpathlib/cloudpath.py\n+++ b/cloudpathlib/cloudpath.py\n@@ -214,8 +214,10 @@ class CloudPath(metaclass=CloudPathMeta):\n # handle if local file gets opened. must be set at the top of the method in case any code\n # below raises an exception, this prevents __del__ from raising an AttributeError\n self._handle: Optional[IO] = None\n+ self._client: Optional[\"Client\"] = None\n \n self.is_valid_cloudpath(cloud_path, raise_on_error=True)\n+ self._cloud_meta.validate_completeness()\n \n # versions of the raw string that provide useful methods\n self._str = str(cloud_path)\n@@ -225,27 +227,34 @@ class CloudPath(metaclass=CloudPathMeta):\n # setup client\n if client is None:\n if isinstance(cloud_path, CloudPath):\n- client = cloud_path.client\n- else:\n- client = self._cloud_meta.client_class.get_default_client()\n- if not isinstance(client, self._cloud_meta.client_class):\n+ self._client = cloud_path.client\n+ else:\n+ self._client = client\n+\n+ if client is not None and not isinstance(client, self._cloud_meta.client_class):\n raise ClientMismatchError(\n f\"Client of type [{client.__class__}] is not valid for cloud path of type \"\n f\"[{self.__class__}]; must be instance of [{self._cloud_meta.client_class}], or \"\n f\"None to use default client for this cloud path class.\"\n )\n- self.client: Client = client\n \n # track if local has been written to, if so it may need to be uploaded\n self._dirty = False\n \n+ @property\n+ def client(self):\n+ if getattr(self, \"_client\", None) is None:\n+ self._client = self._cloud_meta.client_class.get_default_client()\n+\n+ return self._client\n+\n def __del__(self) -> None:\n # make sure that file handle to local path is closed\n if self._handle is not None:\n self._handle.close()\n \n # ensure file removed from cache when cloudpath object deleted\n- client = getattr(self, \"client\", None)\n+ client = getattr(self, \"_client\", None)\n if getattr(client, \"file_cache_mode\", None) == FileCacheMode.cloudpath_object:\n self.clear_cache()\n \n@@ -253,13 +262,11 @@ class CloudPath(metaclass=CloudPathMeta):\n state = self.__dict__.copy()\n \n # don't pickle client\n- del state[\"client\"]\n+ del state[\"_client\"]\n \n return state\n \n def __setstate__(self, state: Dict[str, Any]) -> None:\n- client = self._cloud_meta.client_class.get_default_client()\n- state[\"client\"] = client\n self.__dict__.update(state)\n \n @property\n", "test_patch": "diff --git a/tests/test_cloudpath_instantiation.py b/tests/test_cloudpath_instantiation.py\nindex fe0ca3f..b625a47 100644\n--- a/tests/test_cloudpath_instantiation.py\n+++ b/tests/test_cloudpath_instantiation.py\n@@ -59,6 +59,13 @@ def test_instantiation(rig, path):\n assert str(p._path) == expected.split(\":/\", 1)[-1]\n \n \n+def test_default_client_lazy(rig):\n+ cp = rig.path_class(rig.cloud_prefix + \"testing/file.txt\")\n+ assert cp._client is None\n+ assert cp.client is not None\n+ assert cp._client is not None\n+\n+\n def test_instantiation_errors(rig):\n with pytest.raises(TypeError):\n rig.path_class()\n", "FAIL_TO_PASS": ["tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_gs_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/custom_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/gs_rig]"]}], "all_FAIL_TO_PASS": ["tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_gs_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/custom_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/gs_rig]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "yt-project__unyt-109_x1", "level": 1, "source": "swerebenchv2", "repo": "yt-project/unyt", "image": "swerebenchv2/yt-project-unyt:109-0e465e4", "base_commit": "0e465e494ddff446324547c2756ee51313dae7ff", "num_bugs": 1, "bugs": [{"instance_id": "yt-project__unyt-109", "base_commit": "0e465e494ddff446324547c2756ee51313dae7ff", "gold_patch": "diff --git a/unyt/array.py b/unyt/array.py\nindex 6a655e3..c389812 100644\n--- a/unyt/array.py\n+++ b/unyt/array.py\n@@ -1673,7 +1673,26 @@ class unyt_array(np.ndarray):\n elif u1.is_dimensionless:\n u1 = u0\n else:\n- raise UnitOperationError(ufunc, u0, u1)\n+ # comparison with different units, so need to check if\n+ # this is == and != which we allow and handle in a\n+ # special way using an early return from __array_ufunc__\n+ if ufunc in (equal, not_equal):\n+ if ufunc is equal:\n+ func = np.zeros_like\n+ else:\n+ func = np.ones_like\n+ ret = func(np.asarray(inp1), dtype=bool)\n+ if out is not None:\n+ out[:] = ret[:]\n+ if isinstance(out, unyt_array):\n+ out.units = Unit(\n+ \"\", registry=self.units.registry\n+ )\n+ if ret.shape == ():\n+ ret = bool(ret)\n+ return ret\n+ else:\n+ raise UnitOperationError(ufunc, u0, u1)\n else:\n raise UnitOperationError(ufunc, u0, u1)\n conv, offset = u1.get_conversion_factor(u0, inp1.dtype)\n", "test_patch": "diff --git a/unyt/tests/test_unyt_array.py b/unyt/tests/test_unyt_array.py\nindex 78b6caf..5c031cc 100644\n--- a/unyt/tests/test_unyt_array.py\n+++ b/unyt/tests/test_unyt_array.py\n@@ -509,6 +509,7 @@ def test_comparisons():\n a1 = unyt_array([1, 2, 3], \"cm\")\n a2 = unyt_array([2, 1, 3], \"cm\")\n a3 = unyt_array([0.02, 0.01, 0.03], \"m\")\n+ a4 = unyt_array([1, 2, 3], \"g\")\n dimless = np.array([2, 1, 3])\n \n ops = (np.less, np.less_equal, np.greater, np.greater_equal, np.equal, np.not_equal)\n@@ -542,6 +543,26 @@ def test_comparisons():\n assert_equal(2 < a1, [False, False, True])\n assert_equal(2 < a1, np.less(2, a1))\n \n+ # Check that comparisons with arrays that have different units with\n+ # different dimensions work properly\n+ operate_and_compare(a1, a4, np.equal, [False, False, False])\n+ operate_and_compare(a1, a4, np.not_equal, [True, True, True])\n+\n+ # check that comparing quantities returns bools and not 0-D arrays\n+ el1, el4 = a1[0], a4[0]\n+ assert (el1 == el4) is False\n+ assert (el1 != el4) is True\n+\n+ # comparisons that aren't == and !=\n+ with pytest.raises(UnitOperationError):\n+ np.greater(a1, a4)\n+ with pytest.raises(UnitOperationError):\n+ a1 > a4\n+ with pytest.raises(UnitOperationError):\n+ np.greater(el1, el4)\n+ with pytest.raises(UnitOperationError):\n+ el1 > el4\n+\n \n def test_unit_conversions():\n \"\"\"\n@@ -1003,8 +1024,6 @@ def binary_ufunc_comparison(ufunc, a, b):\n \"greater_equal\",\n \"less\",\n \"less_equal\",\n- \"equal\",\n- \"not_equal\",\n \"logical_and\",\n \"logical_or\",\n \"logical_xor\",\n", "FAIL_TO_PASS": ["unyt/tests/test_unyt_array.py::test_comparisons"]}], "all_FAIL_TO_PASS": ["unyt/tests/test_unyt_array.py::test_comparisons"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aio-libs__aiohttp-8874_x1", "level": 1, "source": "swerebenchv2", "repo": "aio-libs/aiohttp", "image": "swerebenchv2/aio-libs-aiohttp:8874-48a5e07", "base_commit": "48a5e07ad833bd1a8fcb2ce6f85a41ad0cef9dc6", "num_bugs": 1, "bugs": [{"instance_id": "aio-libs__aiohttp-8874", "base_commit": "48a5e07ad833bd1a8fcb2ce6f85a41ad0cef9dc6", "gold_patch": "diff --git a/CHANGES/5343.bugfix b/CHANGES/5343.bugfix\nnew file mode 100644\nindex 000000000..4e33071ea\n--- /dev/null\n+++ b/CHANGES/5343.bugfix\n@@ -0,0 +1,1 @@\n+Fixed StreamResponse.prepared to return True after EOF is sent -- by :user:`arthurdarcet`.\ndiff --git a/aiohttp/web_response.py b/aiohttp/web_response.py\nindex a0ee89d67..238c31277 100644\n--- a/aiohttp/web_response.py\n+++ b/aiohttp/web_response.py\n@@ -121,7 +121,7 @@ class StreamResponse(BaseClass, HeadersMixin, CookieMixin):\n \n @property\n def prepared(self) -> bool:\n- return self._payload_writer is not None\n+ return self._eof_sent or self._payload_writer is not None\n \n @property\n def task(self) -> \"Optional[asyncio.Task[None]]\":\ndiff --git a/requirements/constraints.txt b/requirements/constraints.txt\nindex 661595d82..11f6d4af1 100644\n--- a/requirements/constraints.txt\n+++ b/requirements/constraints.txt\n@@ -38,13 +38,13 @@ cffi==1.17.0\n # via\n # cryptography\n # pycares\n-cfgv==3.3.1\n+cfgv==3.4.0\n # via pre-commit\n charset-normalizer==3.3.2\n # via requests\n cherry-picker==2.2.0\n # via -r requirements/dev.in\n-click==8.1.6\n+click==8.1.7\n # via\n # cherry-picker\n # pip-tools\n@@ -107,8 +107,12 @@ jinja2==3.1.4\n # via\n # sphinx\n # towncrier\n+markdown-it-py==3.0.0\n+ # via rich\n markupsafe==2.1.5\n # via jinja2\n+mdurl==0.1.2\n+ # via markdown-it-py\n multidict==6.0.5\n # via\n # -r requirements/multidict.in\n@@ -155,7 +159,9 @@ pydantic-core==2.20.1\n pyenchant==3.2.2\n # via sphinxcontrib-spelling\n pygments==2.18.0\n- # via sphinx\n+ # via\n+ # rich\n+ # sphinx\n pyjwt==2.8.0\n # via\n # gidgethub\n@@ -195,8 +201,12 @@ requests==2.32.3\n # cherry-picker\n # python-on-whales\n # sphinx\n+rich==13.7.1\n+ # via typer\n setuptools-git==1.2\n # via -r requirements/test.in\n+shellingham==1.5.4\n+ # via typer\n six==1.16.0\n # via python-dateutil\n slotscheck==0.19.0\n@@ -248,9 +258,9 @@ trustme==1.1.0 ; platform_machine != \"i686\"\n # via\n # -r requirements/lint.in\n # -r requirements/test.in\n-typer==0.9.0\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # aioredis\n # annotated-types\n@@ -258,6 +268,7 @@ typing-extensions==4.10.0\n # pydantic\n # pydantic-core\n # python-on-whales\n+ # rich\n # typer\n uritemplate==4.1.1\n # via gidgethub\ndiff --git a/requirements/dev.txt b/requirements/dev.txt\nindex 898d52f9f..181f939fb 100644\n--- a/requirements/dev.txt\n+++ b/requirements/dev.txt\n@@ -38,13 +38,13 @@ cffi==1.17.0\n # via\n # cryptography\n # pycares\n-cfgv==3.3.1\n+cfgv==3.4.0\n # via pre-commit\n charset-normalizer==3.3.2\n # via requests\n cherry-picker==2.2.0\n # via -r requirements/dev.in\n-click==8.1.6\n+click==8.1.7\n # via\n # cherry-picker\n # pip-tools\n@@ -105,8 +105,12 @@ jinja2==3.1.4\n # via\n # sphinx\n # towncrier\n+markdown-it-py==3.0.0\n+ # via rich\n markupsafe==2.1.5\n # via jinja2\n+mdurl==0.1.2\n+ # via markdown-it-py\n multidict==6.0.5\n # via\n # -r requirements/runtime-deps.in\n@@ -150,7 +154,9 @@ pydantic==2.8.2\n pydantic-core==2.20.1\n # via pydantic\n pygments==2.18.0\n- # via sphinx\n+ # via\n+ # rich\n+ # sphinx\n pyjwt==2.8.0\n # via\n # gidgethub\n@@ -190,8 +196,12 @@ requests==2.32.3\n # cherry-picker\n # python-on-whales\n # sphinx\n+rich==13.7.1\n+ # via typer\n setuptools-git==1.2\n # via -r requirements/test.in\n+shellingham==1.5.4\n+ # via typer\n six==1.16.0\n # via python-dateutil\n slotscheck==0.19.0\n@@ -240,9 +250,9 @@ trustme==1.1.0 ; platform_machine != \"i686\"\n # via\n # -r requirements/lint.in\n # -r requirements/test.in\n-typer==0.9.0\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # aioredis\n # annotated-types\n@@ -250,6 +260,7 @@ typing-extensions==4.10.0\n # pydantic\n # pydantic-core\n # python-on-whales\n+ # rich\n # typer\n uritemplate==4.1.1\n # via gidgethub\ndiff --git a/requirements/doc-spelling.txt b/requirements/doc-spelling.txt\nindex 4d55d216a..5108b7743 100644\n--- a/requirements/doc-spelling.txt\n+++ b/requirements/doc-spelling.txt\n@@ -16,7 +16,7 @@ certifi==2024.7.4\n # via requests\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via towncrier\n docutils==0.20.1\n # via sphinx\ndiff --git a/requirements/doc.txt b/requirements/doc.txt\nindex fbfc99f68..1382a7bb8 100644\n--- a/requirements/doc.txt\n+++ b/requirements/doc.txt\n@@ -16,7 +16,7 @@ certifi==2024.7.4\n # via requests\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via towncrier\n docutils==0.20.1\n # via sphinx\ndiff --git a/requirements/lint.txt b/requirements/lint.txt\nindex f9633be1b..aafe0260d 100644\n--- a/requirements/lint.txt\n+++ b/requirements/lint.txt\n@@ -18,11 +18,11 @@ cffi==1.17.0\n # via\n # cryptography\n # pycares\n-cfgv==3.3.1\n+cfgv==3.4.0\n # via pre-commit\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via\n # slotscheck\n # typer\n@@ -105,9 +105,9 @@ tqdm==4.66.5\n # via python-on-whales\n trustme==1.1.0\n # via -r requirements/lint.in\n-typer==0.12.3\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # aioredis\n # annotated-types\n", "test_patch": "diff --git a/docs/testing.rst b/docs/testing.rst\nindex 966bc4cad..1d29f3354 100644\n--- a/docs/testing.rst\n+++ b/docs/testing.rst\n@@ -496,14 +496,12 @@ Framework Agnostic Utilities\n \n High level test creation::\n \n- from aiohttp.test_utils import TestClient, TestServer, loop_context\n+ from aiohttp.test_utils import TestClient, TestServer\n from aiohttp import request\n \n- # loop_context is provided as a utility. You can use any\n- # asyncio.BaseEventLoop class in its place.\n- with loop_context() as loop:\n+ async def test():\n app = _create_example_app()\n- with TestClient(TestServer(app), loop=loop) as client:\n+ async with TestClient(TestServer(app)) as client:\n \n async def test_get_route():\n nonlocal client\n@@ -512,7 +510,7 @@ High level test creation::\n text = await resp.text()\n assert \"Hello, world\" in text\n \n- loop.run_until_complete(test_get_route())\n+ await test_get_route()\n \n \n If it's preferred to handle the creation / teardown on a more granular\n@@ -520,10 +518,10 @@ basis, the TestClient object can be used directly::\n \n from aiohttp.test_utils import TestClient, TestServer\n \n- with loop_context() as loop:\n+ async def test():\n app = _create_example_app()\n- client = TestClient(TestServer(app), loop=loop)\n- loop.run_until_complete(client.start_server())\n+ client = TestClient(TestServer(app))\n+ await client.start_server()\n root = \"http://127.0.0.1:{}\".format(port)\n \n async def test_get_route():\n@@ -532,8 +530,8 @@ basis, the TestClient object can be used directly::\n text = await resp.text()\n assert \"Hello, world\" in text\n \n- loop.run_until_complete(test_get_route())\n- loop.run_until_complete(client.close())\n+ await test_get_route()\n+ await client.close()\n \n \n A full list of the utilities provided can be found at the\ndiff --git a/requirements/test.txt b/requirements/test.txt\nindex a6d8ebab7..15aebd3d1 100644\n--- a/requirements/test.txt\n+++ b/requirements/test.txt\n@@ -24,7 +24,7 @@ cffi==1.17.0\n # pycares\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via\n # typer\n # wait-for-it\n@@ -51,6 +51,10 @@ idna==3.4\n # yarl\n iniconfig==2.0.0\n # via pytest\n+markdown-it-py==3.0.0\n+ # via rich\n+mdurl==0.1.2\n+ # via markdown-it-py\n multidict==6.0.5\n # via\n # -r requirements/runtime-deps.in\n@@ -75,6 +79,8 @@ pydantic==2.8.2\n # via python-on-whales\n pydantic-core==2.20.1\n # via pydantic\n+pygments==2.18.0\n+ # via rich\n pytest==8.1.1\n # via\n # -r requirements/test.in\n@@ -94,8 +100,12 @@ regex==2024.7.24\n # via re-assert\n requests==2.32.3\n # via python-on-whales\n+rich==13.7.1\n+ # via typer\n setuptools-git==1.2\n # via -r requirements/test.in\n+shellingham==1.5.4\n+ # via typer\n six==1.16.0\n # via python-dateutil\n tomli==2.0.1\n@@ -107,15 +117,16 @@ tqdm==4.66.5\n # via python-on-whales\n trustme==1.1.0 ; platform_machine != \"i686\"\n # via -r requirements/test.in\n-typer==0.9.0\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # annotated-types\n # mypy\n # pydantic\n # pydantic-core\n # python-on-whales\n+ # rich\n # typer\n urllib3==2.2.2\n # via requests\ndiff --git a/tests/test_web_response.py b/tests/test_web_response.py\nindex f90eb4b11..d1226f277 100644\n--- a/tests/test_web_response.py\n+++ b/tests/test_web_response.py\n@@ -734,11 +734,8 @@ async def test___repr___after_eof() -> None:\n resp = StreamResponse()\n await resp.prepare(make_request(\"GET\", \"/\"))\n \n- assert resp.prepared\n-\n await resp.write(b\"data\")\n await resp.write_eof()\n- assert not resp.prepared\n resp_repr = repr(resp)\n assert resp_repr == \"\"\n \n@@ -1110,14 +1107,22 @@ def test_content_type_with_set_body() -> None:\n assert resp.content_type == \"application/octet-stream\"\n \n \n-def test_started_when_not_started() -> None:\n+def test_prepared_when_not_started() -> None:\n resp = StreamResponse()\n assert not resp.prepared\n \n \n-async def test_started_when_started() -> None:\n+async def test_prepared_when_started() -> None:\n+ resp = StreamResponse()\n+ await resp.prepare(make_request(\"GET\", \"/\"))\n+ assert resp.prepared\n+\n+\n+async def test_prepared_after_eof() -> None:\n resp = StreamResponse()\n await resp.prepare(make_request(\"GET\", \"/\"))\n+ await resp.write(b\"data\")\n+ await resp.write_eof()\n assert resp.prepared\n \n \n", "FAIL_TO_PASS": ["tests/test_web_response.py::test_prepared_after_eof", "tests/test_web_response.py::test_drain_before_start"]}], "all_FAIL_TO_PASS": ["tests/test_web_response.py::test_prepared_after_eof", "tests/test_web_response.py::test_drain_before_start"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "drivendataorg__cloudpathlib-433_x1", "level": 1, "source": "swerebenchv2", "repo": "drivendataorg/cloudpathlib", "image": "swerebenchv2/drivendataorg-cloudpathlib:433-71331d3", "base_commit": "71331d31aec68c1a4e49fc59d30b613de2d1e657", "num_bugs": 1, "bugs": [{"instance_id": "drivendataorg__cloudpathlib-433", "base_commit": "71331d31aec68c1a4e49fc59d30b613de2d1e657", "gold_patch": "diff --git a/HISTORY.md b/HISTORY.md\nindex a21d821..046ab12 100644\n--- a/HISTORY.md\n+++ b/HISTORY.md\n@@ -7,6 +7,7 @@\n - Drop support for Python 3.7; pin minimal `boto3` version to Python 3.8+ versions. (PR [#407](https://github.com/drivendataorg/cloudpathlib/pull/407))\n - fix: use native `exists()` method in `GSClient`. (PR [#420](https://github.com/drivendataorg/cloudpathlib/pull/420))\n - Enhancement: lazy instantiation of default client (PR [#432](https://github.com/drivendataorg/cloudpathlib/issues/432), Issue [#428](https://github.com/drivendataorg/cloudpathlib/issues/428))\n+- Adds existence check before downloading in `download_to` (Issue [#430](https://github.com/drivendataorg/cloudpathlib/issues/430), PR [#432](https://github.com/drivendataorg/cloudpathlib/pull/432))\n \n ## v0.18.1 (2024-02-26)\n \ndiff --git a/cloudpathlib/cloudpath.py b/cloudpathlib/cloudpath.py\nindex afca5cb..8bad810 100644\n--- a/cloudpathlib/cloudpath.py\n+++ b/cloudpathlib/cloudpath.py\n@@ -63,6 +63,7 @@ from .exceptions import (\n CloudPathFileExistsError,\n CloudPathIsADirectoryError,\n CloudPathNotADirectoryError,\n+ CloudPathNotExistsError,\n CloudPathNotImplementedError,\n DirectoryNotEmptyError,\n IncompleteImplementationError,\n@@ -899,6 +900,10 @@ class CloudPath(metaclass=CloudPathMeta):\n # =========== public cloud methods, not in pathlib ===============\n def download_to(self, destination: Union[str, os.PathLike]) -> Path:\n destination = Path(destination)\n+\n+ if not self.exists():\n+ raise CloudPathNotExistsError(f\"Cannot download because path does not exist: {self}\")\n+\n if self.is_file():\n if destination.is_dir():\n destination = destination / self.name\ndiff --git a/cloudpathlib/exceptions.py b/cloudpathlib/exceptions.py\nindex 802f71e..1b4499f 100644\n--- a/cloudpathlib/exceptions.py\n+++ b/cloudpathlib/exceptions.py\n@@ -20,6 +20,10 @@ class CloudPathFileExistsError(CloudPathException, FileExistsError):\n pass\n \n \n+class CloudPathNotExistsError(CloudPathException):\n+ pass\n+\n+\n class CloudPathIsADirectoryError(CloudPathException, IsADirectoryError):\n pass\n \n", "test_patch": "diff --git a/tests/test_cloudpath_file_io.py b/tests/test_cloudpath_file_io.py\nindex af8f9e6..e5546f0 100644\n--- a/tests/test_cloudpath_file_io.py\n+++ b/tests/test_cloudpath_file_io.py\n@@ -10,6 +10,7 @@ import pytest\n from cloudpathlib import CloudPath\n \n from cloudpathlib.exceptions import (\n+ CloudPathNotExistsError,\n CloudPathIsADirectoryError,\n CloudPathNotImplementedError,\n DirectoryNotEmptyError,\n@@ -396,6 +397,9 @@ def test_file_read_writes(rig, tmp_path):\n )\n assert cloud_rel_paths == dled_rel_paths\n \n+ with pytest.raises(CloudPathNotExistsError):\n+ (p / \"not_exists_file\").download_to(dl_file)\n+\n \n def test_dispatch_to_local_cache(rig):\n p = rig.create_cloud_path(\"dir_0/file0_1.txt\")\n", "FAIL_TO_PASS": ["tests/test_cloudpath_file_io.py::test_glob_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/azure_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/azure_rig]", "tests/test_cloudpath_file_io.py::test_walk[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/azure_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/custom_s3_rig]"]}], "all_FAIL_TO_PASS": ["tests/test_cloudpath_file_io.py::test_glob_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/azure_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/azure_rig]", "tests/test_cloudpath_file_io.py::test_walk[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/azure_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/custom_s3_rig]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aio-libs__aiohttp-8858_x1", "level": 1, "source": "swerebenchv2", "repo": "aio-libs/aiohttp", "image": "swerebenchv2/aio-libs-aiohttp:8858-9fffd8b", "base_commit": "9fffd8b3dfd8a899de2996228d6ca8d0e38b0747", "num_bugs": 1, "bugs": [{"instance_id": "aio-libs__aiohttp-8858", "base_commit": "9fffd8b3dfd8a899de2996228d6ca8d0e38b0747", "gold_patch": "diff --git a/CHANGES/8858.bugfix.rst b/CHANGES/8858.bugfix.rst\nnew file mode 100644\nindex 000000000..e4efa91a2\n--- /dev/null\n+++ b/CHANGES/8858.bugfix.rst\n@@ -0,0 +1,1 @@\n+Stopped adding a default Content-Type header when response has no content -- by :user:`Dreamsorcerer`.\ndiff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py\nindex 785b8d15d..678fe453a 100644\n--- a/aiohttp/client_reqrep.py\n+++ b/aiohttp/client_reqrep.py\n@@ -662,9 +662,8 @@ class ClientRequest:\n self.headers[hdrs.CONNECTION] = connection\n \n # status + headers\n- status_line = \"{0} {1} HTTP/{v.major}.{v.minor}\".format(\n- self.method, path, v=self.version\n- )\n+ v = self.version\n+ status_line = f\"{self.method} {path} HTTP/{v.major}.{v.minor}\"\n await writer.write_headers(status_line, self.headers)\n coro = self.write_bytes(writer, conn)\n \ndiff --git a/aiohttp/helpers.py b/aiohttp/helpers.py\nindex 26b953ea7..2be5977c4 100644\n--- a/aiohttp/helpers.py\n+++ b/aiohttp/helpers.py\n@@ -49,7 +49,7 @@ from typing import (\n from urllib.parse import quote\n from urllib.request import getproxies, proxy_bypass\n \n-from multidict import CIMultiDict, MultiDict, MultiDictProxy\n+from multidict import CIMultiDict, MultiDict, MultiDictProxy, MultiMapping\n from yarl import URL\n \n from . import hdrs\n@@ -753,13 +753,15 @@ def ceil_timeout(\n class HeadersMixin:\n __slots__ = (\"_content_type\", \"_content_dict\", \"_stored_content_type\")\n \n+ _headers: MultiMapping[str]\n+\n def __init__(self) -> None:\n super().__init__()\n self._content_type: Optional[str] = None\n self._content_dict: Optional[Dict[str, str]] = None\n- self._stored_content_type: Union[str, _SENTINEL] = sentinel\n+ self._stored_content_type: Union[str, None, _SENTINEL] = sentinel\n \n- def _parse_content_type(self, raw: str) -> None:\n+ def _parse_content_type(self, raw: Optional[str]) -> None:\n self._stored_content_type = raw\n if raw is None:\n # default value according to RFC 2616\n@@ -774,25 +776,25 @@ class HeadersMixin:\n @property\n def content_type(self) -> str:\n \"\"\"The value of content part for Content-Type HTTP header.\"\"\"\n- raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined]\n+ raw = self._headers.get(hdrs.CONTENT_TYPE)\n if self._stored_content_type != raw:\n self._parse_content_type(raw)\n- return self._content_type # type: ignore[return-value]\n+ assert self._content_type is not None\n+ return self._content_type\n \n @property\n def charset(self) -> Optional[str]:\n \"\"\"The value of charset part for Content-Type HTTP header.\"\"\"\n- raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined]\n+ raw = self._headers.get(hdrs.CONTENT_TYPE)\n if self._stored_content_type != raw:\n self._parse_content_type(raw)\n- return self._content_dict.get(\"charset\") # type: ignore[union-attr]\n+ assert self._content_dict is not None\n+ return self._content_dict.get(\"charset\")\n \n @property\n def content_length(self) -> Optional[int]:\n \"\"\"The value of Content-Length HTTP header.\"\"\"\n- content_length = self._headers.get( # type: ignore[attr-defined]\n- hdrs.CONTENT_LENGTH\n- )\n+ content_length = self._headers.get(hdrs.CONTENT_LENGTH)\n \n if content_length is not None:\n return int(content_length)\ndiff --git a/aiohttp/web_request.py b/aiohttp/web_request.py\nindex 828776d82..4dbc19a48 100644\n--- a/aiohttp/web_request.py\n+++ b/aiohttp/web_request.py\n@@ -82,7 +82,7 @@ class FileField:\n filename: str\n file: io.BufferedReader\n content_type: str\n- headers: \"CIMultiDictProxy[str]\"\n+ headers: CIMultiDictProxy[str]\n \n \n _TCHAR: Final[str] = string.digits + string.ascii_letters + r\"!#$%&'*+.^_`|~-\"\n@@ -171,7 +171,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):\n self._payload_writer = payload_writer\n \n self._payload = payload\n- self._headers = message.headers\n+ self._headers: CIMultiDictProxy[str] = message.headers\n self._method = message.method\n self._version = message.version\n self._cache: Dict[str, Any] = {}\n@@ -483,7 +483,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):\n return self._rel_url.query_string\n \n @reify\n- def headers(self) -> \"CIMultiDictProxy[str]\":\n+ def headers(self) -> CIMultiDictProxy[str]:\n \"\"\"A case-insensitive multidict proxy with all headers.\"\"\"\n return self._headers\n \ndiff --git a/aiohttp/web_response.py b/aiohttp/web_response.py\nindex 47d75675d..a0ee89d67 100644\n--- a/aiohttp/web_response.py\n+++ b/aiohttp/web_response.py\n@@ -402,7 +402,8 @@ class StreamResponse(BaseClass, HeadersMixin, CookieMixin):\n # https://datatracker.ietf.org/doc/html/rfc9112#section-6.1-13\n if hdrs.TRANSFER_ENCODING in headers:\n del headers[hdrs.TRANSFER_ENCODING]\n- else:\n+ elif self.content_length != 0:\n+ # https://www.rfc-editor.org/rfc/rfc9110#section-8.3-5\n headers.setdefault(hdrs.CONTENT_TYPE, \"application/octet-stream\")\n headers.setdefault(hdrs.DATE, rfc822_formatted_time())\n headers.setdefault(hdrs.SERVER, SERVER_SOFTWARE)\n@@ -423,9 +424,7 @@ class StreamResponse(BaseClass, HeadersMixin, CookieMixin):\n assert writer is not None\n # status line\n version = request.version\n- status_line = \"HTTP/{}.{} {} {}\".format(\n- version[0], version[1], self._status, self._reason\n- )\n+ status_line = f\"HTTP/{version[0]}.{version[1]} {self._status} {self._reason}\"\n await writer.write_headers(status_line, self._headers)\n \n async def write(self, data: bytes) -> None:\n", "test_patch": "diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py\nindex 3ab798771..ce530eb61 100644\n--- a/tests/test_client_functional.py\n+++ b/tests/test_client_functional.py\n@@ -759,7 +759,6 @@ async def test_raw_headers(aiohttp_client: AiohttpClient) -> None:\n raw_headers = tuple((bytes(h), bytes(v)) for h, v in resp.raw_headers)\n assert raw_headers == (\n (b\"Content-Length\", b\"0\"),\n- (b\"Content-Type\", b\"application/octet-stream\"),\n (b\"Date\", mock.ANY),\n (b\"Server\", mock.ANY),\n )\n@@ -792,7 +791,6 @@ async def test_empty_header_values(aiohttp_client: AiohttpClient) -> None:\n assert raw_headers == (\n (b\"X-Empty\", b\"\"),\n (b\"Content-Length\", b\"0\"),\n- (b\"Content-Type\", b\"application/octet-stream\"),\n (b\"Date\", mock.ANY),\n (b\"Server\", mock.ANY),\n )\ndiff --git a/tests/test_web_functional.py b/tests/test_web_functional.py\nindex d82fee436..565efc7b4 100644\n--- a/tests/test_web_functional.py\n+++ b/tests/test_web_functional.py\n@@ -150,6 +150,21 @@ async def test_head_returns_empty_body(aiohttp_client: Any) -> None:\n assert resp.headers[\"Content-Length\"] == \"4\"\n \n \n+@pytest.mark.parametrize(\"status\", (201, 204, 404))\n+async def test_default_content_type_no_body(aiohttp_client: Any, status: int) -> None:\n+ async def handler(request):\n+ return web.Response(status=status)\n+\n+ app = web.Application()\n+ app.router.add_get(\"/\", handler)\n+ client = await aiohttp_client(app)\n+\n+ async with client.get(\"/\") as resp:\n+ assert resp.status == status\n+ assert await resp.read() == b\"\"\n+ assert \"Content-Type\" not in resp.headers\n+\n+\n async def test_response_before_complete(aiohttp_client: Any) -> None:\n async def handler(request):\n return web.Response(body=b\"OK\")\ndiff --git a/tests/test_web_response.py b/tests/test_web_response.py\nindex 74c2990cc..f90eb4b11 100644\n--- a/tests/test_web_response.py\n+++ b/tests/test_web_response.py\n@@ -1006,7 +1006,6 @@ async def test_send_headers_for_empty_body(buf: Any, writer: Any) -> None:\n Matches(\n \"HTTP/1.1 200 OK\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n- \"Content-Type: application/octet-stream\\r\\n\"\n \"Date: .+\\r\\n\"\n \"Server: .+\\r\\n\\r\\n\"\n )\n@@ -1049,7 +1048,6 @@ async def test_send_set_cookie_header(buf: Any, writer: Any) -> None:\n \"HTTP/1.1 200 OK\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"Set-Cookie: name=value\\r\\n\"\n- \"Content-Type: application/octet-stream\\r\\n\"\n \"Date: .+\\r\\n\"\n \"Server: .+\\r\\n\\r\\n\"\n )\n", "FAIL_TO_PASS": ["tests/test_client_functional.py::test_raw_headers[pyloop]", "tests/test_client_functional.py::test_empty_header_values[pyloop]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-201]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-404]", "tests/test_web_response.py::test_send_headers_for_empty_body", "tests/test_web_response.py::test_render_with_body", "tests/test_web_response.py::test_send_set_cookie_header", "tests/test_web_response.py::test_consecutive_write_eof"]}], "all_FAIL_TO_PASS": ["tests/test_client_functional.py::test_raw_headers[pyloop]", "tests/test_client_functional.py::test_empty_header_values[pyloop]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-201]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-404]", "tests/test_web_response.py::test_send_headers_for_empty_body", "tests/test_web_response.py::test_render_with_body", "tests/test_web_response.py::test_send_set_cookie_header", "tests/test_web_response.py::test_consecutive_write_eof"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "codezonediitj__pydatastructs-165_x1", "level": 1, "source": "swerebenchv2", "repo": "codezonediitj/pydatastructs", "image": "swerebenchv2/codezonediitj-pydatastructs:165-835aeef", "base_commit": "835aeef937c270062b713ad47b39b1788d69b374", "num_bugs": 1, "bugs": [{"instance_id": "codezonediitj__pydatastructs-165", "base_commit": "835aeef937c270062b713ad47b39b1788d69b374", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex 70dc769..3cdaff7 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -3,7 +3,7 @@ sudo: false\n language: python\n \n python:\n- - \"3.5\"\n+ - \"3.6\"\n install:\n - pip install -r requirements.txt\n \ndiff --git a/pydatastructs/graphs/__init__.py b/pydatastructs/graphs/__init__.py\nindex 6c2f3ba..fb8a518 100644\n--- a/pydatastructs/graphs/__init__.py\n+++ b/pydatastructs/graphs/__init__.py\n@@ -9,7 +9,8 @@ __all__.extend(graph.__all__)\n from . import algorithms\n from .algorithms import (\n breadth_first_search,\n- breadth_first_search_parallel\n+ breadth_first_search_parallel,\n+ minimum_spanning_tree\n )\n \n __all__.extend(algorithms.__all__)\ndiff --git a/pydatastructs/graphs/adjacency_list.py b/pydatastructs/graphs/adjacency_list.py\nindex 9adc6a3..d596633 100644\n--- a/pydatastructs/graphs/adjacency_list.py\n+++ b/pydatastructs/graphs/adjacency_list.py\n@@ -1,5 +1,6 @@\n from pydatastructs.graphs.graph import Graph\n from pydatastructs.linear_data_structures import DynamicOneDimensionalArray\n+from pydatastructs.utils.misc_util import GraphEdge\n \n __all__ = [\n 'AdjacencyList'\n@@ -19,6 +20,7 @@ class AdjacencyList(Graph):\n for vertex in vertices:\n obj.__setattr__(vertex.name, vertex)\n obj.vertices = set([vertex.name for vertex in vertices])\n+ obj.edge_weights = dict()\n return obj\n \n def is_adjacent(self, node1, node2):\n@@ -42,14 +44,24 @@ class AdjacencyList(Graph):\n delattr(node_obj, name)\n node_obj.adjacent.remove(name)\n \n- def add_edge(self, source, target):\n+ def add_edge(self, source, target, cost=None):\n source, target = self.__getattribute__(source), \\\n self.__getattribute__(target)\n source.__setattr__(target.name, target)\n source.adjacent.add(target.name)\n+ if cost is not None:\n+ self.edge_weights[source.name + \"_\" + target.name] = \\\n+ GraphEdge(source, target, cost)\n+\n+ def get_edge(self, source, target):\n+ return self.edge_weights.get(\n+ source + \"_\" + target,\n+ None)\n \n def remove_edge(self, source, target):\n source, target = self.__getattribute__(source), \\\n self.__getattribute__(target)\n source.adjacent.remove(target.name)\n delattr(source, target.name)\n+ self.edge_weights.pop(source.name + \"_\" + target.name,\n+ None)\ndiff --git a/pydatastructs/graphs/adjacency_matrix.py b/pydatastructs/graphs/adjacency_matrix.py\nindex d8135a9..5c25e7f 100644\n--- a/pydatastructs/graphs/adjacency_matrix.py\n+++ b/pydatastructs/graphs/adjacency_matrix.py\n@@ -1,6 +1,6 @@\n from pydatastructs.graphs.graph import Graph\n from pydatastructs.linear_data_structures import OneDimensionalArray\n-from pydatastructs.utils.misc_util import AdjacencyMatrixGraphNode\n+from pydatastructs.utils.misc_util import AdjacencyMatrixGraphNode, GraphEdge\n \n __all__ = [\n 'AdjacencyMatrix'\n@@ -18,11 +18,9 @@ class AdjacencyMatrix(Graph):\n def __new__(cls, *vertices):\n obj = object.__new__(cls)\n num_vertices = len(vertices)\n- obj.vertices = OneDimensionalArray(\n- AdjacencyMatrixGraphNode,\n- num_vertices)\n+ obj.vertices = [vertex.name for vertex in vertices]\n for vertex in vertices:\n- obj.vertices[vertex.name] = vertex\n+ obj.__setattr__(str(vertex.name), vertex)\n obj.matrix = OneDimensionalArray(\n OneDimensionalArray,\n num_vertices)\n@@ -31,6 +29,7 @@ class AdjacencyMatrix(Graph):\n bool,\n num_vertices)\n obj.matrix[i].fill(False)\n+ obj.edge_weights = dict()\n return obj\n \n def is_adjacent(self, node1, node2):\n@@ -40,7 +39,8 @@ class AdjacencyMatrix(Graph):\n neighbors = []\n for i in range(self.matrix[node]._size):\n if self.matrix[node][i]:\n- neighbors.append(self.vertices[i])\n+ neighbors.append(self.__getattribute__(\n+ str(self.vertices[i])))\n return neighbors\n \n def add_vertex(self, node):\n@@ -51,8 +51,20 @@ class AdjacencyMatrix(Graph):\n raise NotImplementedError(\"Currently we allow \"\n \"adjacency matrix for static graphs only.\")\n \n- def add_edge(self, source, target):\n+ def add_edge(self, source, target, cost=None):\n self.matrix[source][target] = True\n+ source, target = str(source), str(target)\n+ if cost is not None:\n+ self.edge_weights[source + \"_\" + target] = \\\n+ GraphEdge(self.__getattribute__(source),\n+ self.__getattribute__(target),\n+ cost)\n+\n+ def get_edge(self, source, target):\n+ return self.edge_weights.get(\n+ str(source) + \"_\" + str(target),\n+ None)\n \n def remove_edge(self, source, target):\n self.matrix[source][target] = False\n+ self.edge_weights.pop(str(source) + \"_\" + str(target), None)\ndiff --git a/pydatastructs/graphs/algorithms.py b/pydatastructs/graphs/algorithms.py\nindex e8c813b..f385403 100644\n--- a/pydatastructs/graphs/algorithms.py\n+++ b/pydatastructs/graphs/algorithms.py\n@@ -3,12 +3,15 @@ Contains all the algorithms associated with graph\n data structure.\n \"\"\"\n from collections import deque as Queue\n-from pydatastructs.utils.misc_util import AdjacencyListGraphNode\n from concurrent.futures import ThreadPoolExecutor\n+from pydatastructs.utils import GraphEdge\n+from pydatastructs.miscellaneous_data_structures import DisjointSetForest\n+from pydatastructs.graphs.graph import Graph\n \n __all__ = [\n 'breadth_first_search',\n- 'breadth_first_search_parallel'\n+ 'breadth_first_search_parallel',\n+ 'minimum_spanning_tree'\n ]\n \n def breadth_first_search(\n@@ -186,3 +189,83 @@ def _breadth_first_search_parallel_adjacency_list(\n return None\n \n _breadth_first_search_parallel_adjacency_matrix = _breadth_first_search_parallel_adjacency_list\n+\n+def _minimum_spanning_tree_kruskal_adjacency_list(graph):\n+ mst = Graph(*[getattr(graph, v) for v in graph.vertices])\n+ sort_key = lambda item: item[1].value\n+ dsf = DisjointSetForest()\n+ for v in graph.vertices:\n+ dsf.make_set(v)\n+ for _, edge in sorted(graph.edge_weights.items(), key=sort_key):\n+ u, v = edge.source.name, edge.target.name\n+ if dsf.find_root(u) is not dsf.find_root(v):\n+ mst.add_edge(u, v, edge.value)\n+ dsf.union(u, v)\n+ return mst\n+\n+def _minimum_spanning_tree_kruskal_adjacency_matrix(graph):\n+ mst = Graph(*[getattr(graph, str(v)) for v in graph.vertices])\n+ sort_key = lambda item: item[1].value\n+ dsf = DisjointSetForest()\n+ for v in graph.vertices:\n+ dsf.make_set(v)\n+ for _, edge in sorted(graph.edge_weights.items(), key=sort_key):\n+ u, v = edge.source.name, edge.target.name\n+ if dsf.find_root(u) is not dsf.find_root(v):\n+ mst.add_edge(u, v, edge.value)\n+ dsf.union(u, v)\n+ return mst\n+\n+def minimum_spanning_tree(graph, algorithm):\n+ \"\"\"\n+ Computes a minimum spanning tree for the given\n+ graph and algorithm.\n+\n+ Parameters\n+ ==========\n+\n+ graph: Graph\n+ The graph whose minimum spanning tree\n+ has to be computed.\n+ algorithm: str\n+ The algorithm which should be used for\n+ computing a minimum spanning tree.\n+ Currently the following algorithms are\n+ supported,\n+ 'kruskal' -> Kruskal's algorithm as given in\n+ [1].\n+\n+ Returns\n+ =======\n+\n+ mst: Graph\n+ A minimum spanning tree using the implementation\n+ same as the graph provided in the input.\n+\n+ Examples\n+ ========\n+\n+ >>> from pydatastructs import Graph, AdjacencyListGraphNode\n+ >>> from pydatastructs import minimum_spanning_tree\n+ >>> u = AdjacencyListGraphNode('u')\n+ >>> v = AdjacencyListGraphNode('v')\n+ >>> G = Graph(u, v)\n+ >>> G.add_edge(u.name, v.name, 3)\n+ >>> mst = minimum_spanning_tree(G, 'kruskal')\n+ >>> u_n = mst.neighbors(u.name)\n+ >>> mst.get_edge(u.name, u_n[0].name).value\n+ 3\n+\n+ References\n+ ==========\n+\n+ .. [1] https://en.wikipedia.org/wiki/Kruskal%27s_algorithm\n+ \"\"\"\n+ import pydatastructs.graphs.algorithms as algorithms\n+ func = \"_minimum_spanning_tree_\" + algorithm + \"_\" + graph._impl\n+ if not hasattr(algorithms, func):\n+ raise NotImplementedError(\n+ \"Currently %s algoithm for %s implementation of graphs \"\n+ \"isn't implemented for finding minimum spanning trees.\"\n+ %(algorithm, graph._impl))\n+ return getattr(algorithms, func)(graph)\ndiff --git a/pydatastructs/graphs/graph.py b/pydatastructs/graphs/graph.py\nindex f274aeb..16bad56 100644\n--- a/pydatastructs/graphs/graph.py\n+++ b/pydatastructs/graphs/graph.py\n@@ -96,7 +96,7 @@ class Graph(object):\n raise NotImplementedError(\n \"This is an abstract method.\")\n \n- def add_edge(self, source, target):\n+ def add_edge(self, source, target, cost=None):\n \"\"\"\n Adds the edge starting at first parameter\n i.e., source and ending at the second\n@@ -105,6 +105,15 @@ class Graph(object):\n raise NotImplementedError(\n \"This is an abstract method.\")\n \n+ def get_edge(self, source, target):\n+ \"\"\"\n+ Returns GraphEdge object if there\n+ is an edge between source and target\n+ otherwise None.\n+ \"\"\"\n+ raise NotImplementedError(\n+ \"This is an abstract method.\")\n+\n def remove_edge(self, source, target):\n \"\"\"\n Removes the edge starting at first parameter\ndiff --git a/pydatastructs/linear_data_structures/arrays.py b/pydatastructs/linear_data_structures/arrays.py\nindex 980aab9..454d3b9 100644\n--- a/pydatastructs/linear_data_structures/arrays.py\n+++ b/pydatastructs/linear_data_structures/arrays.py\n@@ -48,8 +48,8 @@ class OneDimensionalArray(Array):\n Examples\n ========\n \n- >>> from pydatastructs import OneDimensionalArray as ODA\n- >>> arr = ODA(int, 5)\n+ >>> from pydatastructs import OneDimensionalArray\n+ >>> arr = OneDimensionalArray(int, 5)\n >>> arr.fill(6)\n >>> arr[0]\n 6\n@@ -127,7 +127,6 @@ class OneDimensionalArray(Array):\n for i in range(self._size):\n self._data[i] = elem\n \n-ODA = OneDimensionalArray\n \n class DynamicArray(Array):\n \"\"\"\n@@ -216,7 +215,7 @@ class DynamicOneDimensionalArray(DynamicArray, OneDimensionalArray):\n below load factor.\n \"\"\"\n if self._num/self._size < self._load_factor:\n- arr_new = ODA(self._dtype, 2*self._num + 1)\n+ arr_new = OneDimensionalArray(self._dtype, 2*self._num + 1)\n j = 0\n for i in range(self._last_pos_filled + 1):\n if self[i] is not None:\n@@ -228,7 +227,7 @@ class DynamicOneDimensionalArray(DynamicArray, OneDimensionalArray):\n \n def append(self, el):\n if self._last_pos_filled + 1 == self._size:\n- arr_new = ODA(self._dtype, 2*self._size + 1)\n+ arr_new = OneDimensionalArray(self._dtype, 2*self._size + 1)\n for i in range(self._last_pos_filled + 1):\n arr_new[i] = self[i]\n arr_new[self._last_pos_filled + 1] = el\n", "test_patch": "diff --git a/pydatastructs/graphs/tests/test_adjacency_list.py b/pydatastructs/graphs/tests/test_adjacency_list.py\nindex 5581e14..d1635fc 100644\n--- a/pydatastructs/graphs/tests/test_adjacency_list.py\n+++ b/pydatastructs/graphs/tests/test_adjacency_list.py\n@@ -21,12 +21,18 @@ def test_adjacency_list():\n assert neighbors == [v_2]\n v = AdjacencyListGraphNode('v', 4)\n g.add_vertex(v)\n- g.add_edge('v_1', 'v')\n- g.add_edge('v_2', 'v')\n- g.add_edge('v_3', 'v')\n+ g.add_edge('v_1', 'v', 0)\n+ g.add_edge('v_2', 'v', 0)\n+ g.add_edge('v_3', 'v', 0)\n assert g.is_adjacent('v_1', 'v') is True\n assert g.is_adjacent('v_2', 'v') is True\n assert g.is_adjacent('v_3', 'v') is True\n+ e1 = g.get_edge('v_1', 'v')\n+ e2 = g.get_edge('v_2', 'v')\n+ e3 = g.get_edge('v_3', 'v')\n+ assert (e1.source.name, e1.target.name) == ('v_1', 'v')\n+ assert (e2.source.name, e2.target.name) == ('v_2', 'v')\n+ assert (e3.source.name, e3.target.name) == ('v_3', 'v')\n g.remove_edge('v_1', 'v')\n assert g.is_adjacent('v_1', 'v') is False\n g.remove_vertex('v')\ndiff --git a/pydatastructs/graphs/tests/test_adjacency_matrix.py b/pydatastructs/graphs/tests/test_adjacency_matrix.py\nindex b6f9c3f..5fe8c72 100644\n--- a/pydatastructs/graphs/tests/test_adjacency_matrix.py\n+++ b/pydatastructs/graphs/tests/test_adjacency_matrix.py\n@@ -5,10 +5,16 @@ def test_AdjacencyMatrix():\n v_0 = AdjacencyMatrixGraphNode(0, 0)\n v_1 = AdjacencyMatrixGraphNode(1, 1)\n v_2 = AdjacencyMatrixGraphNode(2, 2)\n- g = Graph(v_0, v_1, v_2, implementation='adjacency_matrix')\n- g.add_edge(0, 1)\n- g.add_edge(1, 2)\n- g.add_edge(2, 0)\n+ g = Graph(v_0, v_1, v_2)\n+ g.add_edge(0, 1, 0)\n+ g.add_edge(1, 2, 0)\n+ g.add_edge(2, 0, 0)\n+ e1 = g.get_edge(0, 1)\n+ e2 = g.get_edge(1, 2)\n+ e3 = g.get_edge(2, 0)\n+ assert (e1.source.name, e1.target.name) == (0, 1)\n+ assert (e2.source.name, e2.target.name) == (1, 2)\n+ assert (e3.source.name, e3.target.name) == (2, 0)\n assert g.is_adjacent(0, 1) is True\n assert g.is_adjacent(1, 2) is True\n assert g.is_adjacent(2, 0) is True\ndiff --git a/pydatastructs/graphs/tests/test_algorithms.py b/pydatastructs/graphs/tests/test_algorithms.py\nindex 065fa2e..a5c28ea 100644\n--- a/pydatastructs/graphs/tests/test_algorithms.py\n+++ b/pydatastructs/graphs/tests/test_algorithms.py\n@@ -1,10 +1,10 @@\n from pydatastructs import (breadth_first_search, Graph,\n-breadth_first_search_parallel)\n+breadth_first_search_parallel, minimum_spanning_tree)\n \n \n def test_breadth_first_search():\n \n- def _test_breadth_first_search(ds, impl):\n+ def _test_breadth_first_search(ds):\n import pydatastructs.utils.misc_util as utils\n GraphNode = getattr(utils, \"Adjacency\" + ds + \"GraphNode\")\n \n@@ -12,7 +12,7 @@ def test_breadth_first_search():\n V2 = GraphNode(1)\n V3 = GraphNode(2)\n \n- G1 = Graph(V1, V2, V3, implementation=impl)\n+ G1 = Graph(V1, V2, V3)\n \n edges = [\n (V1.name, V2.name),\n@@ -47,7 +47,7 @@ def test_breadth_first_search():\n (V7.name, V8.name)\n ]\n \n- G2 = Graph(V4, V5, V6, V7, V8, implementation=impl)\n+ G2 = Graph(V4, V5, V6, V7, V8)\n \n for edge in edges:\n G2.add_edge(*edge)\n@@ -71,12 +71,12 @@ def test_breadth_first_search():\n breadth_first_search(G2, V4.name, path_finder, V7.name, parent, path)\n assert path == [V4.name, V5.name, V6.name, V7.name]\n \n- _test_breadth_first_search(\"List\", \"adjacency_list\")\n- _test_breadth_first_search(\"Matrix\", \"adjacency_matrix\")\n+ _test_breadth_first_search(\"List\")\n+ _test_breadth_first_search(\"Matrix\")\n \n def test_breadth_first_search_parallel():\n \n- def _test_breadth_first_search_parallel(ds, impl):\n+ def _test_breadth_first_search_parallel(ds):\n import pydatastructs.utils.misc_util as utils\n GraphNode = getattr(utils, \"Adjacency\" + ds + \"GraphNode\")\n \n@@ -90,7 +90,7 @@ def test_breadth_first_search_parallel():\n V8 = GraphNode(7)\n \n \n- G1 = Graph(V1, V2, V3, V4, V5, V6, V7, V8, implementation=impl)\n+ G1 = Graph(V1, V2, V3, V4, V5, V6, V7, V8)\n \n edges = [\n (V1.name, V2.name),\n@@ -119,5 +119,32 @@ def test_breadth_first_search_parallel():\n (parent[V6.name] in (V2.name, V3.name)) and\n (parent[V7.name] in (V3.name, V4.name)) and (parent[V8.name] == V4.name))\n \n- _test_breadth_first_search_parallel(\"List\", \"adjacency_list\")\n- _test_breadth_first_search_parallel(\"Matrix\", \"adjacency_matrix\")\n+ _test_breadth_first_search_parallel(\"List\")\n+ _test_breadth_first_search_parallel(\"Matrix\")\n+\n+def test_minimum_spanning_tree():\n+\n+ def _test_minimum_spanning_tree(ds, algorithm):\n+ import pydatastructs.utils.misc_util as utils\n+ GraphNode = getattr(utils, \"Adjacency\" + ds + \"GraphNode\")\n+ a, b, c, d, e = [GraphNode(x) for x in [0, 1, 2, 3, 4]]\n+ graph = Graph(a, b, c, d, e)\n+ graph.add_edge(a.name, c.name, 10)\n+ graph.add_edge(c.name, a.name, 10)\n+ graph.add_edge(a.name, d.name, 7)\n+ graph.add_edge(d.name, a.name, 7)\n+ graph.add_edge(c.name, d.name, 9)\n+ graph.add_edge(d.name, c.name, 9)\n+ graph.add_edge(d.name, b.name, 32)\n+ graph.add_edge(b.name, d.name, 32)\n+ graph.add_edge(d.name, e.name, 23)\n+ graph.add_edge(e.name, d.name, 23)\n+ mst = minimum_spanning_tree(graph, algorithm=algorithm)\n+ expected_mst = [('0_3', 7), ('2_3', 9), ('3_4', 23), ('3_1', 32),\n+ ('3_0', 7), ('3_2', 9), ('4_3', 23), ('1_3', 32)]\n+ assert len(expected_mst) == 2*len(mst.edge_weights.items())\n+ for k, v in mst.edge_weights.items():\n+ assert (k, v.value) in expected_mst\n+\n+ _test_minimum_spanning_tree(\"List\", \"kruskal\")\n+ _test_minimum_spanning_tree(\"Matrix\", \"kruskal\")\n", "FAIL_TO_PASS": ["pydatastructs/graphs/tests/test_adjacency_list.py::test_adjacency_list", "pydatastructs/graphs/tests/test_adjacency_matrix.py::test_AdjacencyMatrix", "pydatastructs/graphs/tests/test_algorithms.py::test_breadth_first_search", "pydatastructs/graphs/tests/test_algorithms.py::test_breadth_first_search_parallel", "pydatastructs/graphs/tests/test_algorithms.py::test_minimum_spanning_tree"]}], "all_FAIL_TO_PASS": ["pydatastructs/graphs/tests/test_adjacency_list.py::test_adjacency_list", "pydatastructs/graphs/tests/test_adjacency_matrix.py::test_AdjacencyMatrix", "pydatastructs/graphs/tests/test_algorithms.py::test_breadth_first_search", "pydatastructs/graphs/tests/test_algorithms.py::test_breadth_first_search_parallel", "pydatastructs/graphs/tests/test_algorithms.py::test_minimum_spanning_tree"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "codezonediitj__pydatastructs-177_x1", "level": 1, "source": "swerebenchv2", "repo": "codezonediitj/pydatastructs", "image": "swerebenchv2/codezonediitj-pydatastructs:177-2ef83ae", "base_commit": "2ef83aeb1bc08d842d315c9c403be5b1bbfe5881", "num_bugs": 1, "bugs": [{"instance_id": "codezonediitj__pydatastructs-177", "base_commit": "2ef83aeb1bc08d842d315c9c403be5b1bbfe5881", "gold_patch": "diff --git a/pydatastructs/linear_data_structures/__init__.py b/pydatastructs/linear_data_structures/__init__.py\nindex a6e0d74..f5dcce9 100644\n--- a/pydatastructs/linear_data_structures/__init__.py\n+++ b/pydatastructs/linear_data_structures/__init__.py\n@@ -2,7 +2,8 @@ __all__ = []\n \n from . import (\n arrays,\n- linked_lists\n+ linked_lists,\n+ algorithms\n )\n \n from .arrays import (\n@@ -18,3 +19,8 @@ from .linked_lists import (\n DoublyCircularLinkedList\n )\n __all__.extend(linked_lists.__all__)\n+\n+from .algorithms import (\n+ merge_sort_parallel\n+)\n+__all__.extend(algorithms.__all__)\ndiff --git a/pydatastructs/linear_data_structures/algorithms.py b/pydatastructs/linear_data_structures/algorithms.py\nnew file mode 100644\nindex 0000000..fa830df\n--- /dev/null\n+++ b/pydatastructs/linear_data_structures/algorithms.py\n@@ -0,0 +1,95 @@\n+from pydatastructs.linear_data_structures.arrays import (\n+ OneDimensionalArray, DynamicArray)\n+from pydatastructs.utils.misc_util import _check_type\n+from concurrent.futures import ThreadPoolExecutor\n+from math import log, floor\n+\n+__all__ = [\n+ 'merge_sort_parallel'\n+]\n+\n+def _merge(array, sl, el, sr, er, end):\n+ l, r = [], []\n+ for i in range(sl, el + 1):\n+ if (i <= end and\n+ array[i] is not None):\n+ l.append(array[i])\n+ array[i] = None\n+ for i in range(sr, er + 1):\n+ if (i <= end and\n+ array[i] is not None):\n+ r.append(array[i])\n+ array[i] = None\n+ i, j, k = 0, 0, sl\n+ while i < len(l) and j < len(r):\n+ if l[i] <= r[j]:\n+ array[k] = l[i]\n+ i += 1\n+ else:\n+ array[k] = r[j]\n+ j += 1\n+ k += 1\n+\n+ while i < len(l):\n+ array[k] = l[i]\n+ i += 1\n+ k += 1\n+\n+ while j < len(r):\n+ array[k] = r[j]\n+ j += 1\n+ k += 1\n+\n+def merge_sort_parallel(array, num_threads, **kwargs):\n+ \"\"\"\n+ Implements parallel merge sort.\n+\n+ Parameters\n+ ==========\n+\n+ array: Array\n+ The array which is to be sorted.\n+ num_threads: int\n+ The maximum number of threads\n+ to be used for sorting.\n+ start: int\n+ The starting index of the portion\n+ which is to be sorted.\n+ Optional, by default 0\n+ end: int\n+ The ending index of the portion which\n+ is to be sorted.\n+ Optional, by default the index\n+ of the last position filled.\n+\n+ Examples\n+ ========\n+\n+ >>> from pydatastructs import OneDimensionalArray, merge_sort_parallel\n+ >>> arr = OneDimensionalArray(int,[3, 2, 1])\n+ >>> merge_sort_parallel(arr, 3)\n+ >>> [arr[0], arr[1], arr[2]]\n+ [1, 2, 3]\n+\n+ References\n+ ==========\n+\n+ .. [1] https://en.wikipedia.org/wiki/Merge_sort\n+ \"\"\"\n+ start = kwargs.get('start', 0)\n+ end = kwargs.get('end', array._size - 1)\n+ for size in range(floor(log(end - start + 1, 2)) + 1):\n+ pow_2 = 2**size\n+ with ThreadPoolExecutor(max_workers=num_threads) as Executor:\n+ i = start\n+ while i <= end:\n+ Executor.submit(\n+ _merge,\n+ array,\n+ i, i + pow_2 - 1,\n+ i + pow_2, i + 2*pow_2 - 1,\n+ end).result()\n+ i = i + 2*pow_2\n+\n+ if _check_type(array, DynamicArray):\n+ array._modify(force=True)\ndiff --git a/pydatastructs/linear_data_structures/arrays.py b/pydatastructs/linear_data_structures/arrays.py\nindex 454d3b9..130098b 100644\n--- a/pydatastructs/linear_data_structures/arrays.py\n+++ b/pydatastructs/linear_data_structures/arrays.py\n@@ -209,12 +209,12 @@ class DynamicOneDimensionalArray(DynamicArray, OneDimensionalArray):\n obj._last_pos_filled = obj._num - 1\n return obj\n \n- def _modify(self):\n+ def _modify(self, force=False):\n \"\"\"\n Contracts the array if Num(T)/Size(T) falls\n below load factor.\n \"\"\"\n- if self._num/self._size < self._load_factor:\n+ if (self._num/self._size < self._load_factor) or force:\n arr_new = OneDimensionalArray(self._dtype, 2*self._num + 1)\n j = 0\n for i in range(self._last_pos_filled + 1):\n@@ -231,14 +231,12 @@ class DynamicOneDimensionalArray(DynamicArray, OneDimensionalArray):\n for i in range(self._last_pos_filled + 1):\n arr_new[i] = self[i]\n arr_new[self._last_pos_filled + 1] = el\n- self._last_pos_filled += 1\n self._size = arr_new._size\n- self._num += 1\n self._data = arr_new._data\n else:\n self[self._last_pos_filled + 1] = el\n- self._last_pos_filled += 1\n- self._num += 1\n+ self._last_pos_filled += 1\n+ self._num += 1\n self._modify()\n \n def delete(self, idx):\n", "test_patch": "diff --git a/pydatastructs/linear_data_structures/tests/test_algorithm.py b/pydatastructs/linear_data_structures/tests/test_algorithm.py\nnew file mode 100644\nindex 0000000..d33f802\n--- /dev/null\n+++ b/pydatastructs/linear_data_structures/tests/test_algorithm.py\n@@ -0,0 +1,33 @@\n+from pydatastructs import (\n+ merge_sort_parallel, DynamicOneDimensionalArray,\n+ OneDimensionalArray)\n+import random\n+\n+def test_merge_sort_parallel():\n+\n+ random.seed(1000)\n+\n+ n = random.randint(10, 20)\n+ arr = DynamicOneDimensionalArray(int, 0)\n+ for _ in range(n):\n+ arr.append(random.randint(1, 1000))\n+ for _ in range(n//3):\n+ arr.delete(random.randint(0, n//2))\n+ expected_arr = [686, 779, 102, 134, 362,\n+ 448, 480, 548, 228, 688,\n+ 247, 373, 696, None, None,\n+ None, None, None, None,\n+ None, None, None, None,\n+ None, None, None, None]\n+ merge_sort_parallel(arr, 5, start=2, end=10)\n+ assert arr._data == expected_arr\n+\n+ n = random.randint(10, 20)\n+ arr = OneDimensionalArray(int, n)\n+ for i in range(n):\n+ arr[i] = random.randint(1, 1000)\n+ expected_arr = [42, 695, 147, 500, 768,\n+ 998, 473, 732, 728, 426,\n+ 709, 910]\n+ merge_sort_parallel(arr, 5, start=2, end=5)\n+ assert arr._data == expected_arr\n", "FAIL_TO_PASS": ["pydatastructs/linear_data_structures/tests/test_algorithm.py::test_merge_sort_parallel"]}], "all_FAIL_TO_PASS": ["pydatastructs/linear_data_structures/tests/test_algorithm.py::test_merge_sort_parallel"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "sdv-dev__rdt-754_x1", "level": 1, "source": "swerebenchv2", "repo": "sdv-dev/RDT", "image": "swerebenchv2/sdv-dev-rdt:754-de011e2", "base_commit": "de011e2efe5478b8c9020275893a601063364a33", "num_bugs": 1, "bugs": [{"instance_id": "sdv-dev__rdt-754", "base_commit": "de011e2efe5478b8c9020275893a601063364a33", "gold_patch": "diff --git a/rdt/transformers/text.py b/rdt/transformers/text.py\nindex 7cae7a2..ca1887a 100644\n--- a/rdt/transformers/text.py\n+++ b/rdt/transformers/text.py\n@@ -1,5 +1,5 @@\n \"\"\"Transformers for text data.\"\"\"\n-import warnings\n+import logging\n \n import numpy as np\n import pandas as pd\n@@ -8,6 +8,8 @@ from rdt.errors import TransformerProcessingError\n from rdt.transformers.base import BaseTransformer\n from rdt.transformers.utils import strings_from_regex\n \n+LOGGER = logging.getLogger(__name__)\n+\n \n class IDGenerator(BaseTransformer):\n \"\"\"Generate an ID column.\n@@ -161,10 +163,10 @@ class RegexGenerator(BaseTransformer):\n f\"Please use a different regex for column ('{self.get_input_column()}').\"\n )\n \n- warnings.warn(\n- f\"The data has {sample_size} rows but the regex for '{self.get_input_column()}' \"\n- f'can only create {self.generator_size} unique values. Some values in '\n- f\"'{self.get_input_column()}' may be repeated.\"\n+ LOGGER.info(\n+ \"The data has %s rows but the regex for '%s' can only create %s unique values.\"\n+ \" Some values in '%s' may be repeated.\",\n+ sample_size, self.get_input_column(), self.generator_size, self.get_input_column()\n )\n \n remaining = self.generator_size - self.generated\ndiff --git a/rdt/transformers/utils.py b/rdt/transformers/utils.py\nindex fe26476..240b829 100644\n--- a/rdt/transformers/utils.py\n+++ b/rdt/transformers/utils.py\n@@ -149,7 +149,7 @@ def strings_from_regex(regex, max_repeat=16):\n generators.append((generator, option, args))\n sizes.append(size)\n \n- return _from_generators(generators, max_repeat), np.prod(sizes, dtype=np.complex128)\n+ return _from_generators(generators, max_repeat), np.prod(sizes, dtype=np.complex128).real\n \n \n def fill_nan_with_none(data):\n", "test_patch": "diff --git a/tests/unit/transformers/test_text.py b/tests/unit/transformers/test_text.py\nindex 511c351..ff208b2 100644\n--- a/tests/unit/transformers/test_text.py\n+++ b/tests/unit/transformers/test_text.py\n@@ -485,3 +485,31 @@ class TestRegexGenerator:\n )\n with pytest.raises(TransformerProcessingError, match=error_msg):\n instance._reverse_transform(columns_data)\n+\n+ @patch('rdt.transformers.text.LOGGER')\n+ def test__reverse_transform_info_message(self, mock_logger):\n+ \"\"\"Test the ``_reverse_transform`` method.\n+\n+ Validate that the ``_reverse_transform`` method logs an info message when\n+ ``enforce_uniqueness`` is ``False`` and the ``instance.data_length`` is bigger than\n+ ``instance.generator_size``.\n+ \"\"\"\n+ # Setup\n+ instance = RegexGenerator('[A-Z]', enforce_uniqueness=False)\n+ instance.data_length = 6\n+ instance.generator_size = 5\n+ instance.generated = 0\n+ instance.columns = ['a']\n+ columns_data = pd.Series()\n+\n+ # Run\n+ instance._reverse_transform(columns_data)\n+\n+ # Assert\n+ expected_format = (\n+ \"The data has %s rows but the regex for '%s' can only create %s unique values. Some \"\n+ \"values in '%s' may be repeated.\"\n+ )\n+ expected_args = (6, 'a', 5, 'a')\n+\n+ mock_logger.info.assert_called_once_with(expected_format, *expected_args)\n", "FAIL_TO_PASS": ["tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message"]}], "all_FAIL_TO_PASS": ["tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "materials-consortia__optimade-python-tools-582_x1", "level": 1, "source": "swerebenchv2", "repo": "Materials-Consortia/optimade-python-tools", "image": "swerebenchv2/materials-consortia-optimade-python-tools:582-e7a8de9", "base_commit": "e7a8de9822da1edd8a2432e8d562982e27f00255", "num_bugs": 1, "bugs": [{"instance_id": "materials-consortia__optimade-python-tools-582", "base_commit": "e7a8de9822da1edd8a2432e8d562982e27f00255", "gold_patch": "diff --git a/optimade/models/structures.py b/optimade/models/structures.py\nindex 4203824a..e1aebb19 100644\n--- a/optimade/models/structures.py\n+++ b/optimade/models/structures.py\n@@ -774,7 +774,8 @@ The properties of the species are found in the property `species`.\n expected_elements = sorted(elements)\n \n if field.name == \"chemical_formula_hill\":\n- for elem in (\"C\", \"H\"):\n+ # Make sure C is first and H is second.\n+ for elem in (\"H\", \"C\"):\n if elem in expected_elements:\n expected_elements.pop(expected_elements.index(elem))\n expected_elements.insert(0, elem)\n@@ -786,10 +787,10 @@ The properties of the species are found in the property `species`.\n \n if \"1\" in numbers:\n raise ValueError(\n- \"Must omit proportion '1' from formula {v} in {field.name!r}\"\n+ f\"Must omit proportion '1' from formula {v} in {field.name!r}\"\n )\n if expected_elements != elements:\n- order = \"Hill\" if field == \"chemical_formula_hill\" else \"alphabetical\"\n+ order = \"Hill\" if field.name == \"chemical_formula_hill\" else \"alphabetical\"\n raise ValueError(\n f\"Elements in {field.name!r} must appear in {order} order: {expected_elements} not {elements}.\"\n )\n@@ -803,7 +804,7 @@ The properties of the species are found in the property `species`.\n \n if any(n == 1 for n in numbers):\n raise ValueError(\n- \"'chemical_formula_anonymous' {v} must omit proportion '1'\"\n+ f\"'chemical_formula_anonymous' {v} must omit proportion '1'\"\n )\n \n expected_labels = ANONYMOUS_ELEMENTS[: len(elements)]\n", "test_patch": "diff --git a/tests/models/test_data/test_bad_structures.json b/tests/models/test_data/test_bad_structures.json\nindex 100feb90..1204198b 100644\n--- a/tests/models/test_data/test_bad_structures.json\n+++ b/tests/models/test_data/test_bad_structures.json\n@@ -2403,5 +2403,37 @@\n }\n ],\n \"structure_features\": [\"assemblies\"]\n+ },\n+ {\n+ \"task_id\": \"db/1234567\",\n+ \"type\": \"structure\",\n+ \"last_modified\": {\n+ \"$date\": \"2019-06-08T05:13:37.331Z\"\n+ },\n+ \"band_gap\": 1.23456,\n+ \"chemsys\": \"C-H-Cl-N-Na-O-Os-P\",\n+ \"elements\": [\"C\", \"Cl\", \"H\", \"N\", \"Na\", \"O\", \"Os\", \"P\"],\n+ \"nelements\": 8,\n+ \"nsites\": 7,\n+ \"elements_ratios\": [0.09090909091, 0.36363636363, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091],\n+ \"chemical_formula_reduced\": \"CClH4NNaOOsP\",\n+ \"chemical_formula_hill\": \"H4CClNNaOOsP\",\n+ \"chemical_formula_descriptive\": \"Methyl-ClNNaOOsP\",\n+ \"formula_anonymous\": \"A4BCDEFGH\",\n+ \"dimension_types\": [1, 1, 1],\n+ \"nperiodic_dimensions\": 3,\n+ \"lattice_vectors\": [[4.0,0.0,0.0],[0.0, 4.0, 0.0],[0.0,1.0,4.0]],\n+ \"cartesian_site_positions\": [ [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0] ],\n+ \"species_at_sites\": [\"Cl\", \"O\", \"N\", \"met\", \"Os\", \"Na\", \"P\"],\n+ \"species\": [\n+ {\"name\": \"Cl\", \"chemical_symbols\": [\"Cl\"], \"concentration\": [1.0] },\n+ {\"name\": \"O\", \"chemical_symbols\": [\"O\"], \"concentration\": [1.0] },\n+ {\"name\": \"N\", \"chemical_symbols\": [\"N\"], \"concentration\": [1.0] },\n+ {\"name\": \"met\", \"chemical_symbols\": [\"C\"], \"concentration\": [1.0], \"attached\": [\"H\"], \"nattached\": [4] },\n+ {\"name\": \"Os\", \"chemical_symbols\": [\"Os\"], \"concentration\": [1.0] },\n+ {\"name\": \"Na\", \"chemical_symbols\": [\"Na\"], \"concentration\": [1.0] },\n+ {\"name\": \"P\", \"chemical_symbols\": [\"P\"], \"concentration\": [1.0] }\n+ ],\n+ \"structure_features\": [\"site_attachments\"]\n }\n ]\ndiff --git a/tests/models/test_data/test_good_structures.json b/tests/models/test_data/test_good_structures.json\nindex a44bb018..09478ba6 100644\n--- a/tests/models/test_data/test_good_structures.json\n+++ b/tests/models/test_data/test_good_structures.json\n@@ -158,5 +158,37 @@\n }\n ],\n \"structure_features\": [\"assemblies\", \"site_attachments\"]\n+ },\n+ {\n+ \"task_id\": \"db/1234567\",\n+ \"type\": \"structure\",\n+ \"last_modified\": {\n+ \"$date\": \"2019-06-08T05:13:37.331Z\"\n+ },\n+ \"band_gap\": 1.23456,\n+ \"chemsys\": \"C-H-Cl-N-Na-O-Os-P\",\n+ \"elements\": [\"C\", \"Cl\", \"H\", \"N\", \"Na\", \"O\", \"Os\", \"P\"],\n+ \"nelements\": 8,\n+ \"nsites\": 7,\n+ \"elements_ratios\": [0.09090909091, 0.36363636363, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091],\n+ \"chemical_formula_reduced\": \"CClH4NNaOOsP\",\n+ \"chemical_formula_hill\": \"CH4ClNNaOOsP\",\n+ \"chemical_formula_descriptive\": \"Methyl-ClNNaOOsP\",\n+ \"formula_anonymous\": \"A4BCDEFGH\",\n+ \"dimension_types\": [1, 1, 1],\n+ \"nperiodic_dimensions\": 3,\n+ \"lattice_vectors\": [[4.0,0.0,0.0],[0.0, 4.0, 0.0],[0.0,1.0,4.0]],\n+ \"cartesian_site_positions\": [ [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0] ],\n+ \"species_at_sites\": [\"Cl\", \"O\", \"N\", \"met\", \"Os\", \"Na\", \"P\"],\n+ \"species\": [\n+ {\"name\": \"Cl\", \"chemical_symbols\": [\"Cl\"], \"concentration\": [1.0] },\n+ {\"name\": \"O\", \"chemical_symbols\": [\"O\"], \"concentration\": [1.0] },\n+ {\"name\": \"N\", \"chemical_symbols\": [\"N\"], \"concentration\": [1.0] },\n+ {\"name\": \"met\", \"chemical_symbols\": [\"C\"], \"concentration\": [1.0], \"attached\": [\"H\"], \"nattached\": [4] },\n+ {\"name\": \"Os\", \"chemical_symbols\": [\"Os\"], \"concentration\": [1.0] },\n+ {\"name\": \"Na\", \"chemical_symbols\": [\"Na\"], \"concentration\": [1.0] },\n+ {\"name\": \"P\", \"chemical_symbols\": [\"P\"], \"concentration\": [1.0] }\n+ ],\n+ \"structure_features\": [\"site_attachments\"]\n }\n ]\ndiff --git a/tests/models/test_structures.py b/tests/models/test_structures.py\nindex 24d63877..ca72018d 100644\n--- a/tests/models/test_structures.py\n+++ b/tests/models/test_structures.py\n@@ -54,6 +54,7 @@ deformities = (\n {\"chemical_formula_hill\": \"SiGe\"},\n {\"chemical_formula_hill\": \"GeHSi\"},\n {\"chemical_formula_hill\": \"CGeHSi\"},\n+ {\"chemical_formula_hill\": \"HCGeSi\"},\n {\"chemical_formula_reduced\": \"Ge1.0Si1.0\"},\n {\"chemical_formula_reduced\": \"GeSi2.0\"},\n {\"chemical_formula_reduced\": \"GeSi.2\"},\n", "FAIL_TO_PASS": ["tests/models/test_structures.py::test_more_good_structures", "tests/models/test_structures.py::test_bad_structures", "tests/models/test_structures.py::test_structure_deformities[deformity12]"]}], "all_FAIL_TO_PASS": ["tests/models/test_structures.py::test_more_good_structures", "tests/models/test_structures.py::test_bad_structures", "tests/models/test_structures.py::test_structure_deformities[deformity12]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "scitools__cartopy-2378_x1", "level": 1, "source": "swerebenchv2", "repo": "SciTools/cartopy", "image": "swerebenchv2/scitools-cartopy:2378-631a8db", "base_commit": "631a8db383276efa447404066d817462793024f7", "num_bugs": 1, "bugs": [{"instance_id": "scitools__cartopy-2378", "base_commit": "631a8db383276efa447404066d817462793024f7", "gold_patch": "diff --git a/lib/cartopy/crs.py b/lib/cartopy/crs.py\nindex e43a266a..a39703e8 100644\n--- a/lib/cartopy/crs.py\n+++ b/lib/cartopy/crs.py\n@@ -1790,7 +1790,7 @@ class LambertConformal(Projection):\n lons[1:-1] = np.linspace(central_longitude - 180 + 0.001,\n central_longitude + 180 - 0.001, n)\n \n- points = self.transform_points(PlateCarree(globe=globe), lons, lats)\n+ points = self.transform_points(self.as_geodetic(), lons, lats)\n \n self._boundary = sgeom.LinearRing(points)\n mins = np.min(points, axis=0)\n@@ -1866,7 +1866,7 @@ class LambertAzimuthalEqualArea(Projection):\n lon = central_longitude + 180\n sign = np.sign(central_latitude) or 1\n lat = -central_latitude + sign * 0.01\n- x, max_y = self.transform_point(lon, lat, PlateCarree(globe=globe))\n+ x, max_y = self.transform_point(lon, lat, self.as_geodetic())\n \n coords = _ellipse_boundary(a * 1.9999, max_y - false_northing,\n false_easting, false_northing, 61)\n", "test_patch": "diff --git a/lib/cartopy/tests/crs/test_lambert_conformal.py b/lib/cartopy/tests/crs/test_lambert_conformal.py\nindex 23bfea68..da754c4d 100644\n--- a/lib/cartopy/tests/crs/test_lambert_conformal.py\n+++ b/lib/cartopy/tests/crs/test_lambert_conformal.py\n@@ -3,6 +3,7 @@\n # This file is part of Cartopy and is released under the BSD 3-clause license.\n # See LICENSE in the root of the repository for full licensing details.\n \n+import numpy as np\n from numpy.testing import assert_array_almost_equal\n import pyproj\n import pytest\n@@ -38,6 +39,17 @@ def test_default_with_cutoff():\n (-49788019.81831982, 30793476.08487709))\n \n \n+def test_sphere():\n+ \"\"\"Test LambertConformal with spherical globe. (#2377)\"\"\"\n+ globe = ccrs.Globe(ellipse='sphere')\n+\n+ # This would error creating a boundary\n+ crs = ccrs.LambertConformal(globe=globe)\n+\n+ assert np.all(np.isfinite(crs.x_limits))\n+ assert np.all(np.isfinite(crs.y_limits))\n+\n+\n def test_specific_lambert():\n # This projection comes from EPSG Projection 3034 - ETRS89 / ETRS-LCC.\n crs = ccrs.LambertConformal(central_longitude=10,\n", "FAIL_TO_PASS": ["lib/cartopy/tests/crs/test_lambert_conformal.py::test_sphere"]}], "all_FAIL_TO_PASS": ["lib/cartopy/tests/crs/test_lambert_conformal.py::test_sphere"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "alteryx__woodwork-640_x1", "level": 1, "source": "swerebenchv2", "repo": "alteryx/woodwork", "image": "swerebenchv2/alteryx-woodwork:640-7bde24e", "base_commit": "7bde24e9c9b5c5a0e228b4c62c094fced9901c3b", "num_bugs": 1, "bugs": [{"instance_id": "alteryx__woodwork-640", "base_commit": "7bde24e9c9b5c5a0e228b4c62c094fced9901c3b", "gold_patch": "diff --git a/docs/source/api_reference.rst b/docs/source/api_reference.rst\nindex d5b9119..dea1466 100644\n--- a/docs/source/api_reference.rst\n+++ b/docs/source/api_reference.rst\n@@ -12,6 +12,7 @@ WoodworkTableAccessor\n WoodworkTableAccessor\n WoodworkTableAccessor.describe\n WoodworkTableAccessor.describe_dict\n+ WoodworkTableAccessor.drop\n WoodworkTableAccessor.iloc\n WoodworkTableAccessor.init\n WoodworkTableAccessor.loc\ndiff --git a/docs/source/release_notes.rst b/docs/source/release_notes.rst\nindex eb2be94..ac2c7f9 100644\n--- a/docs/source/release_notes.rst\n+++ b/docs/source/release_notes.rst\n@@ -34,6 +34,7 @@ Release Notes\n * Add ``value_counts`` to WoodworkTableAccessor (:pr:`632`)\n * Add KoalasColumnAccessor (:pr:`634`)\n * Add ``pop`` to WoodworkTableAccessor (:pr:`636`)\n+ * Add ``drop`` to WoodworkTableAccessor (:pr:`640`)\n * Fixes\n * Create new Schema object when performing pandas operation on Accessors (:pr:`595`)\n * Changes\ndiff --git a/woodwork/table_accessor.py b/woodwork/table_accessor.py\nindex a5f9fe5..e34994b 100644\n--- a/woodwork/table_accessor.py\n+++ b/woodwork/table_accessor.py\n@@ -457,6 +457,33 @@ class WoodworkTableAccessor:\n \n return series\n \n+ def drop(self, columns):\n+ \"\"\"Drop specified columns from a DataFrame.\n+\n+ Args:\n+ columns (str or list[str]): Column name or names to drop. Must be present in the DataTable.\n+\n+ Returns:\n+ (pd.DataFrame): DataFrame with the specified columns removed, maintaining Woodwork typing information.\n+\n+ Note:\n+ This method is used for removing columns only. To remove rows with ``drop``, go through the\n+ DataFrame directly and then reinitialize Woodwork with ``DataFrame.ww.init``\n+ instead of calling ``DataFrame.ww.drop``.\n+ \"\"\"\n+ if not isinstance(columns, (list, set)):\n+ columns = [columns]\n+\n+ not_present = [col for col in columns if col not in self._dataframe.columns]\n+ if not_present:\n+ raise ValueError(f'{not_present} not found in DataFrame')\n+\n+ new_schema = self._schema._get_subset_schema([col for col in self._dataframe.columns if col not in columns])\n+ new_df = self._dataframe.drop(columns, axis=1)\n+ new_df.ww.init(schema=new_schema)\n+\n+ return new_df\n+\n def mutual_information_dict(self, num_bins=10, nrows=None):\n \"\"\"\n Calculates mutual information between all pairs of columns in the DataFrame that\n", "test_patch": "diff --git a/woodwork/tests/accessor/test_table_accessor.py b/woodwork/tests/accessor/test_table_accessor.py\nindex 7948061..f3b1df0 100644\n--- a/woodwork/tests/accessor/test_table_accessor.py\n+++ b/woodwork/tests/accessor/test_table_accessor.py\n@@ -721,13 +721,6 @@ def test_underlying_index(sample_df):\n assert schema_df.index.name is None\n assert type(schema_df.index) == specified_index\n \n- # --> add back when df.ww.drop is implemented\n- # schema_dropped = schema.drop('made_index')\n- # assert 'made_index' not in schema_dropped.columns\n- # assert 'made_index' not in schema_dropped._dataframe.columns\n- # assert type(schema_dropped._dataframe.index) == unspecified_index\n- # assert type(schema_dropped.to_dataframe().index) == unspecified_index\n-\n \n def test_accessor_already_sorted(sample_unsorted_df):\n if dd and isinstance(sample_unsorted_df, dd.DataFrame):\n@@ -813,7 +806,7 @@ def test_ordinal_with_nan_values():\n \n def test_accessor_with_falsy_column_names(falsy_names_df):\n if dd and isinstance(falsy_names_df, dd.DataFrame):\n- pytest.xfail('Dask DataTables cannot handle integer column names')\n+ pytest.xfail('Dask DataFrames cannot handle integer column names')\n xfail_dask_and_koalas(falsy_names_df)\n \n schema_df = falsy_names_df.copy()\n@@ -1448,3 +1441,71 @@ def test_pop_error(sample_df):\n \n with pytest.raises(LookupError, match=\"Column with name missing not found in DataFrame\"):\n sample_df.ww.pop(\"missing\")\n+\n+\n+def test_accessor_drop(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ schema_df = sample_df.copy()\n+ schema_df.ww.init()\n+\n+ single_input_df = schema_df.ww.drop('is_registered')\n+ assert len(single_input_df.ww.columns) == (len(schema_df.columns) - 1)\n+ assert 'is_registered' not in single_input_df.ww.columns\n+ assert to_pandas(schema_df).drop('is_registered', axis='columns').equals(to_pandas(single_input_df))\n+\n+ list_input_df = schema_df.ww.drop(['is_registered'])\n+ assert len(list_input_df.ww.columns) == (len(schema_df.columns) - 1)\n+ assert 'is_registered' not in list_input_df.ww.columns\n+ assert to_pandas(schema_df).drop('is_registered', axis='columns').equals(to_pandas(list_input_df))\n+ # should be equal to the single input example above\n+ assert single_input_df.ww.schema == list_input_df.ww.schema\n+ assert to_pandas(single_input_df).equals(to_pandas(list_input_df))\n+\n+ multiple_list_df = schema_df.ww.drop(['age', 'full_name', 'is_registered'])\n+ assert len(multiple_list_df.ww.columns) == (len(schema_df.columns) - 3)\n+ assert 'is_registered' not in multiple_list_df.ww.columns\n+ assert 'full_name' not in multiple_list_df.ww.columns\n+ assert 'age' not in multiple_list_df.ww.columns\n+\n+ assert to_pandas(schema_df).drop(['is_registered', 'age', 'full_name'], axis='columns').equals(to_pandas(multiple_list_df))\n+\n+ # Drop the same columns in a different order and confirm resulting DataFrame column order doesn't change\n+ different_order_df = schema_df.ww.drop(['is_registered', 'age', 'full_name'])\n+ assert different_order_df.ww.schema == multiple_list_df.ww.schema\n+ assert to_pandas(multiple_list_df).equals(to_pandas(different_order_df))\n+\n+\n+def test_accessor_drop_indices(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ sample_df.ww.init(index='id', time_index='signup_date')\n+ assert sample_df.ww.index == 'id'\n+ assert sample_df.ww.time_index == 'signup_date'\n+\n+ dropped_index_df = sample_df.ww.drop('id')\n+ assert 'id' not in dropped_index_df.ww.columns\n+ assert dropped_index_df.ww.index is None\n+ assert dropped_index_df.ww.time_index == 'signup_date'\n+\n+ dropped_time_index_df = sample_df.ww.drop(['signup_date'])\n+ assert 'signup_date' not in dropped_time_index_df.ww.columns\n+ assert dropped_time_index_df.ww.time_index is None\n+ assert dropped_time_index_df.ww.index == 'id'\n+\n+\n+def test_accessor_drop_errors(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ sample_df.ww.init()\n+\n+ error = re.escape(\"['not_present'] not found in DataFrame\")\n+ with pytest.raises(ValueError, match=error):\n+ sample_df.ww.drop('not_present')\n+\n+ with pytest.raises(ValueError, match=error):\n+ sample_df.ww.drop(['age', 'not_present'])\n+\n+ error = re.escape(\"['not_present1', 4] not found in DataFrame\")\n+ with pytest.raises(ValueError, match=error):\n+ sample_df.ww.drop(['not_present1', 4])\n", "FAIL_TO_PASS": ["woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]"]}], "all_FAIL_TO_PASS": ["woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "alteryx__woodwork-646_x1", "level": 1, "source": "swerebenchv2", "repo": "alteryx/woodwork", "image": "swerebenchv2/alteryx-woodwork:646-a55c98f", "base_commit": "a55c98ff7f71022690862d3bbaa2c9ab8d32952d", "num_bugs": 1, "bugs": [{"instance_id": "alteryx__woodwork-646", "base_commit": "a55c98ff7f71022690862d3bbaa2c9ab8d32952d", "gold_patch": "diff --git a/docs/source/release_notes.rst b/docs/source/release_notes.rst\nindex ac2c7f9..8e1ee70 100644\n--- a/docs/source/release_notes.rst\n+++ b/docs/source/release_notes.rst\n@@ -35,6 +35,7 @@ Release Notes\n * Add KoalasColumnAccessor (:pr:`634`)\n * Add ``pop`` to WoodworkTableAccessor (:pr:`636`)\n * Add ``drop`` to WoodworkTableAccessor (:pr:`640`)\n+ * Add ``rename`` to WoodworkTableAccessor (:pr:`646`)\n * Fixes\n * Create new Schema object when performing pandas operation on Accessors (:pr:`595`)\n * Changes\ndiff --git a/woodwork/exceptions.py b/woodwork/exceptions.py\nindex 2e6f887..3c6a5b3 100644\n--- a/woodwork/exceptions.py\n+++ b/woodwork/exceptions.py\n@@ -42,3 +42,7 @@ class TypeConversionError(Exception):\n \n class ParametersIgnoredWarning(UserWarning):\n pass\n+\n+\n+class ColumnNotPresentError(KeyError):\n+ pass\ndiff --git a/woodwork/schema.py b/woodwork/schema.py\nindex e9cc8a0..0eaa3b5 100644\n--- a/woodwork/schema.py\n+++ b/woodwork/schema.py\n@@ -4,6 +4,7 @@ import copy\n import pandas as pd\n \n import woodwork as ww\n+from woodwork.exceptions import ColumnNotPresentError\n from woodwork.schema_column import (\n _add_semantic_tags,\n _get_column_dict,\n@@ -327,6 +328,37 @@ class Schema(object):\n _check_time_index(self.columns.keys(), new_time_index, self.logical_types.get(new_time_index))\n self._set_time_index_tags(new_time_index)\n \n+ def rename(self, columns):\n+ \"\"\"Renames columns in a Schema\n+\n+ Args:\n+ columns (dict[str -> str]): A dictionary mapping current column names to new column names.\n+\n+ Returns:\n+ woodwork.Schema: Schema with the specified columns renamed.\n+ \"\"\"\n+ if not isinstance(columns, dict):\n+ raise TypeError('columns must be a dictionary')\n+\n+ for old_name, new_name in columns.items():\n+ if old_name not in self.columns:\n+ raise ColumnNotPresentError(f\"Column to rename must be present. {old_name} cannot be found.\")\n+ if new_name in self.columns and new_name not in columns.keys():\n+ raise ValueError(f\"The column {new_name} is already present. Please choose another name to rename {old_name} to or also rename {old_name}.\")\n+\n+ if len(columns) != len(set(columns.values())):\n+ raise ValueError('New columns names must be unique from one another.')\n+\n+ new_schema = self._get_subset_schema(list(self.columns.keys()))\n+\n+ cols_to_update = {}\n+ for old_name, new_name in columns.items():\n+ col = new_schema.columns.pop(old_name)\n+ cols_to_update[new_name] = col\n+\n+ new_schema.columns.update(cols_to_update)\n+ return new_schema\n+\n def _set_index_tags(self, index):\n '''\n Updates the semantic tags of the index by removing any standard tags\ndiff --git a/woodwork/table_accessor.py b/woodwork/table_accessor.py\nindex e34994b..349dfea 100644\n--- a/woodwork/table_accessor.py\n+++ b/woodwork/table_accessor.py\n@@ -461,7 +461,7 @@ class WoodworkTableAccessor:\n \"\"\"Drop specified columns from a DataFrame.\n \n Args:\n- columns (str or list[str]): Column name or names to drop. Must be present in the DataTable.\n+ columns (str or list[str]): Column name or names to drop. Must be present in the DataFrame.\n \n Returns:\n (pd.DataFrame): DataFrame with the specified columns removed, maintaining Woodwork typing information.\n@@ -484,6 +484,21 @@ class WoodworkTableAccessor:\n \n return new_df\n \n+ def rename(self, columns):\n+ \"\"\"Renames columns in a DataFrame, maintaining Woodwork typing information.\n+\n+ Args:\n+ columns (dict[str -> str]): A dictionary mapping current column names to new column names.\n+\n+ Returns:\n+ DataFrame: DataFrame with the specified columns renamed, maintaining Woodwork typing information.\n+ \"\"\"\n+ new_schema = self._schema.rename(columns)\n+ new_df = self._dataframe.rename(columns=columns)\n+\n+ new_df.ww.init(schema=new_schema)\n+ return new_df\n+\n def mutual_information_dict(self, num_bins=10, nrows=None):\n \"\"\"\n Calculates mutual information between all pairs of columns in the DataFrame that\n", "test_patch": "diff --git a/woodwork/tests/accessor/test_table_accessor.py b/woodwork/tests/accessor/test_table_accessor.py\nindex f3b1df0..933054a 100644\n--- a/woodwork/tests/accessor/test_table_accessor.py\n+++ b/woodwork/tests/accessor/test_table_accessor.py\n@@ -825,15 +825,17 @@ def test_accessor_with_falsy_column_names(falsy_names_df):\n assert '' not in schema_df.ww.columns\n assert schema_df.ww.time_index is None\n \n+ schema_df.ww.set_index(None)\n+ assert schema_df.ww.index is None\n+\n # --> add back in if setitem is implemented\n # dt[''] = popped_col\n # assert dt[''].name == ''\n # assert dt['']._series.name == ''\n \n- # --> add back in once rename is implemented on the accessor\n- # dt = dt.rename({'': 'col_with_name'})\n- # assert '' not in dt.columns\n- # assert 'col_with_name' in dt.columns\n+ renamed_df = schema_df.ww.rename({0: 'col_with_name'})\n+ assert 0 not in renamed_df.columns\n+ assert 'col_with_name' in renamed_df.columns\n \n \n def test_accessor_repr(sample_df, sample_column_names, sample_inferred_logical_types):\n@@ -947,11 +949,11 @@ def test_dataframe_methods_on_accessor_inplace(sample_df):\n \n pd.testing.assert_frame_equal(to_pandas(schema_df), to_pandas(df_pre_sort.sort_values(['full_name'])))\n \n- warning = \"Operation performed by rename has invalidated the Woodwork typing information:\\n \"\n+ warning = \"Operation performed by insert has invalidated the Woodwork typing information:\\n \"\n \"The following columns in the DataFrame were missing from the typing information: {'new_name'}.\\n \"\n \"Please initialize Woodwork with DataFrame.ww.init\"\n with pytest.warns(TypingInfoMismatchWarning, match=warning):\n- schema_df.ww.rename({'id': 'new_name'}, inplace=True, axis=1)\n+ schema_df.ww.insert(loc=0, column=\"new_name\", value=[1, 2, 3, 4])\n assert 'new_name' in schema_df.columns\n assert schema_df.ww.schema is None\n \n@@ -1509,3 +1511,64 @@ def test_accessor_drop_errors(sample_df):\n error = re.escape(\"['not_present1', 4] not found in DataFrame\")\n with pytest.raises(ValueError, match=error):\n sample_df.ww.drop(['not_present1', 4])\n+\n+\n+def test_accessor_rename(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ table_metadata = {'table_info': 'this is text'}\n+ id_description = 'the id of the row'\n+ sample_df.ww.init(index='id',\n+ time_index='signup_date',\n+ table_metadata=table_metadata,\n+ column_descriptions={'id': id_description},\n+ semantic_tags={'age': 'test_tag'},\n+ logical_types={'age': Double})\n+ original_df = sample_df.ww.copy()\n+\n+ new_df = sample_df.ww.rename({'age': 'birthday'})\n+\n+ assert to_pandas(sample_df.rename({'age': 'birthday'}, axis=1)).equals(to_pandas(new_df))\n+ # Confirm original dataframe hasn't changed\n+ assert to_pandas(sample_df).equals(original_df)\n+ assert sample_df.ww.schema == original_df.ww.schema\n+\n+ assert original_df.columns.get_loc('age') == new_df.columns.get_loc('birthday')\n+ pd.testing.assert_series_equal(original_df['age'], new_df['birthday'], check_names=False)\n+\n+ # confirm that metadata and descriptions are there\n+ assert new_df.ww.metadata == table_metadata\n+ assert new_df.ww.columns['id']['description'] == id_description\n+\n+ old_col = sample_df.ww.columns['age']\n+ new_col = new_df.ww.columns['birthday']\n+ assert old_col['logical_type'] == new_col['logical_type']\n+ assert old_col['semantic_tags'] == new_col['semantic_tags']\n+ assert old_col['dtype'] == new_col['dtype']\n+\n+ new_df = sample_df.ww.rename({'age': 'full_name', 'full_name': 'age'})\n+\n+ pd.testing.assert_series_equal(original_df['age'], new_df['full_name'], check_names=False)\n+ pd.testing.assert_series_equal(original_df['full_name'], new_df['age'], check_names=False)\n+\n+ assert original_df.columns.get_loc('age') == new_df.columns.get_loc('full_name')\n+ assert original_df.columns.get_loc('full_name') == new_df.columns.get_loc('age')\n+\n+\n+def test_accessor_rename_indices(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ sample_df.ww.init(\n+ index='id',\n+ time_index='signup_date')\n+\n+ renamed_df = sample_df.ww.rename({'id': 'renamed_index', 'signup_date': 'renamed_time_index'})\n+ assert 'id' not in renamed_df.columns\n+ assert 'signup_date' not in renamed_df.columns\n+ assert 'renamed_index' in renamed_df.columns\n+ assert 'renamed_time_index' in renamed_df.columns\n+\n+ assert all(renamed_df.index == renamed_df['renamed_index'])\n+\n+ assert renamed_df.ww.index == 'renamed_index'\n+ assert renamed_df.ww.time_index == 'renamed_time_index'\ndiff --git a/woodwork/tests/schema/test_schema.py b/woodwork/tests/schema/test_schema.py\nindex 3d1e408..cb60d23 100644\n--- a/woodwork/tests/schema/test_schema.py\n+++ b/woodwork/tests/schema/test_schema.py\n@@ -5,6 +5,7 @@ import pandas as pd\n import pytest\n \n from woodwork import type_system\n+from woodwork.exceptions import ColumnNotPresentError\n from woodwork.logical_types import (\n Boolean,\n Categorical,\n@@ -786,3 +787,72 @@ def test_set_index_twice(sample_column_names, sample_inferred_logical_types):\n assert schema.time_index == 'signup_date'\n assert schema.semantic_tags['signup_date'] == {'time_index'}\n assert schema == original_schema\n+\n+\n+def test_schema_rename_errors(sample_column_names, sample_inferred_logical_types):\n+ schema = Schema(sample_column_names, sample_inferred_logical_types, index='id', time_index='signup_date')\n+\n+ error = \"columns must be a dictionary\"\n+ with pytest.raises(TypeError, match=error):\n+ schema.rename(1)\n+\n+ error = 'New columns names must be unique from one another.'\n+ with pytest.raises(ValueError, match=error):\n+ schema.rename({'age': 'test', 'full_name': 'test'})\n+\n+ error = 'Column to rename must be present. not_present cannot be found.'\n+ with pytest.raises(ColumnNotPresentError, match=error):\n+ schema.rename({'not_present': 'test'})\n+\n+ error = 'The column email is already present. Please choose another name to rename age to or also rename age.'\n+ with pytest.raises(ValueError, match=error):\n+ schema.rename({'age': 'email'})\n+\n+\n+def test_schema_rename(sample_column_names, sample_inferred_logical_types):\n+\n+ table_metadata = {'table_info': 'this is text'}\n+ id_description = 'the id of the row'\n+ schema = Schema(sample_column_names, sample_inferred_logical_types,\n+ index='id',\n+ time_index='signup_date',\n+ table_metadata=table_metadata,\n+ column_descriptions={'id': id_description})\n+ original_schema = schema._get_subset_schema(list(schema.columns.keys()))\n+\n+ renamed_schema = schema.rename({'age': 'birthday'})\n+\n+ # Confirm original schema hasn't changed\n+ assert schema == original_schema\n+\n+ assert 'age' not in renamed_schema.columns\n+ assert 'birthday' in renamed_schema.columns\n+\n+ # confirm that metadata and descriptions are there\n+ assert renamed_schema.metadata == table_metadata\n+ assert schema.columns['id']['description'] == id_description\n+\n+ old_col = schema.columns['age']\n+ new_col = renamed_schema.columns['birthday']\n+ assert old_col['logical_type'] == new_col['logical_type']\n+ assert old_col['semantic_tags'] == new_col['semantic_tags']\n+ assert old_col['dtype'] == new_col['dtype']\n+\n+ swapped_schema = schema.rename({'age': 'full_name', 'full_name': 'age'})\n+ swapped_back_schema = swapped_schema.rename({'age': 'full_name', 'full_name': 'age'})\n+ assert swapped_back_schema == schema\n+\n+\n+def test_schema_rename_indices(sample_column_names, sample_inferred_logical_types):\n+ schema = Schema(sample_column_names, sample_inferred_logical_types,\n+ index='id',\n+ time_index='signup_date')\n+\n+ renamed_schema = schema.rename({'id': 'renamed_index', 'signup_date': 'renamed_time_index'})\n+ assert 'id' not in renamed_schema.columns\n+ assert 'signup_date' not in renamed_schema.columns\n+ assert 'renamed_index' in renamed_schema.columns\n+ assert 'renamed_time_index' in renamed_schema.columns\n+\n+ assert renamed_schema.index == 'renamed_index'\n+ assert renamed_schema.time_index == 'renamed_time_index'\n", "FAIL_TO_PASS": ["woodwork/tests/accessor/test_table_accessor.py::test_check_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_logical_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_time_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_unique_column_names_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_schema_property[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_separation_of_params[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_schema_parameter_warning[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_getattr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_equality_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_valid_string_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_numeric_datetime_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_numeric_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_invalid_string_time_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_string_logical_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_int_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_bool_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_str_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_float_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_datetime_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_timedelta_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_category_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_object_dtype_on_init[latlong_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_sets_string_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_boolean_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_int64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_float64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_datetime64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_invalid_dtype_casting", "woodwork/tests/accessor/test_table_accessor.py::test_underlying_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_already_sorted[sample_unsorted_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_order[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_incomplete_ranking[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_nan_values", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_falsy_column_names[falsy_names_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_repr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_invalid_schema_message[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_new_schema_object[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_inplace[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_returning_series[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_other_returns[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_subset_df_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_error[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename_indices[sample_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_physical_types", "woodwork/tests/schema/test_schema.py::test_schema_logical_types", "woodwork/tests/schema/test_schema.py::test_schema_semantic_tags", "woodwork/tests/schema/test_schema.py::test_schema_types", "woodwork/tests/schema/test_schema.py::test_schema_repr[small_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_repr_empty", "woodwork/tests/schema/test_schema.py::test_schema_equality", "woodwork/tests/schema/test_schema.py::test_schema_table_metadata", "woodwork/tests/schema/test_schema.py::test_schema_column_metadata", "woodwork/tests/schema/test_schema.py::test_get_subset_schema", "woodwork/tests/schema/test_schema.py::test_get_subset_schema_all_params", "woodwork/tests/schema/test_schema.py::test_set_logical_types", "woodwork/tests/schema/test_schema.py::test_set_logical_types_empty", "woodwork/tests/schema/test_schema.py::test_set_logical_types_invalid_data", "woodwork/tests/schema/test_schema.py::test_set_types_combined", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_add_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_all_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_invalid_column", "woodwork/tests/schema/test_schema.py::test_remove_semantic_tags", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_time_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_removes_index_via_tags", "woodwork/tests/schema/test_schema.py::test_removes_time_index_via_tags", "woodwork/tests/schema/test_schema.py::test_set_index", "woodwork/tests/schema/test_schema.py::test_set_index_errors", "woodwork/tests/schema/test_schema.py::test_set_time_index", "woodwork/tests/schema/test_schema.py::test_set_numeric_datetime_time_index", "woodwork/tests/schema/test_schema.py::test_set_time_index_errors", "woodwork/tests/schema/test_schema.py::test_set_index_twice", "woodwork/tests/schema/test_schema.py::test_schema_rename_errors", "woodwork/tests/schema/test_schema.py::test_schema_rename", "woodwork/tests/schema/test_schema.py::test_schema_rename_indices"]}], "all_FAIL_TO_PASS": ["woodwork/tests/accessor/test_table_accessor.py::test_check_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_logical_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_time_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_unique_column_names_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_schema_property[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_separation_of_params[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_schema_parameter_warning[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_getattr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_equality_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_valid_string_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_numeric_datetime_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_numeric_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_invalid_string_time_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_string_logical_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_int_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_bool_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_str_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_float_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_datetime_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_timedelta_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_category_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_object_dtype_on_init[latlong_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_sets_string_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_boolean_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_int64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_float64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_datetime64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_invalid_dtype_casting", "woodwork/tests/accessor/test_table_accessor.py::test_underlying_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_already_sorted[sample_unsorted_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_order[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_incomplete_ranking[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_nan_values", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_falsy_column_names[falsy_names_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_repr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_invalid_schema_message[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_new_schema_object[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_inplace[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_returning_series[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_other_returns[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_subset_df_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_error[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename_indices[sample_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_physical_types", "woodwork/tests/schema/test_schema.py::test_schema_logical_types", "woodwork/tests/schema/test_schema.py::test_schema_semantic_tags", "woodwork/tests/schema/test_schema.py::test_schema_types", "woodwork/tests/schema/test_schema.py::test_schema_repr[small_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_repr_empty", "woodwork/tests/schema/test_schema.py::test_schema_equality", "woodwork/tests/schema/test_schema.py::test_schema_table_metadata", "woodwork/tests/schema/test_schema.py::test_schema_column_metadata", "woodwork/tests/schema/test_schema.py::test_get_subset_schema", "woodwork/tests/schema/test_schema.py::test_get_subset_schema_all_params", "woodwork/tests/schema/test_schema.py::test_set_logical_types", "woodwork/tests/schema/test_schema.py::test_set_logical_types_empty", "woodwork/tests/schema/test_schema.py::test_set_logical_types_invalid_data", "woodwork/tests/schema/test_schema.py::test_set_types_combined", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_add_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_all_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_invalid_column", "woodwork/tests/schema/test_schema.py::test_remove_semantic_tags", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_time_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_removes_index_via_tags", "woodwork/tests/schema/test_schema.py::test_removes_time_index_via_tags", "woodwork/tests/schema/test_schema.py::test_set_index", "woodwork/tests/schema/test_schema.py::test_set_index_errors", "woodwork/tests/schema/test_schema.py::test_set_time_index", "woodwork/tests/schema/test_schema.py::test_set_numeric_datetime_time_index", "woodwork/tests/schema/test_schema.py::test_set_time_index_errors", "woodwork/tests/schema/test_schema.py::test_set_index_twice", "woodwork/tests/schema/test_schema.py::test_schema_rename_errors", "woodwork/tests/schema/test_schema.py::test_schema_rename", "woodwork/tests/schema/test_schema.py::test_schema_rename_indices"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "theacodes__nox-472_x1", "level": 1, "source": "swerebenchv2", "repo": "theacodes/nox", "image": "swerebenchv2/theacodes-nox:472-9c696e2", "base_commit": "9c696e2bc2e47ec0f2acd322c7e4be941dab0518", "num_bugs": 1, "bugs": [{"instance_id": "theacodes__nox-472", "base_commit": "9c696e2bc2e47ec0f2acd322c7e4be941dab0518", "gold_patch": "diff --git a/nox/_option_set.py b/nox/_option_set.py\nindex 1e81443..91dcc15 100644\n--- a/nox/_option_set.py\n+++ b/nox/_option_set.py\n@@ -77,7 +77,7 @@ class Option:\n self,\n name: str,\n *flags: str,\n- group: OptionGroup,\n+ group: Optional[OptionGroup],\n help: Optional[str] = None,\n noxfile: bool = False,\n merge_func: Optional[Callable[[Namespace, Namespace], Any]] = None,\n@@ -230,9 +230,15 @@ class OptionSet:\n }\n \n for option in self.options.values():\n- if option.hidden:\n+ if option.hidden is True:\n continue\n \n+ # Every option must have a group (except for hidden options)\n+ if option.group is None:\n+ raise ValueError(\n+ f\"Option {option.name} must either have a group or be hidden.\"\n+ )\n+\n argument = groups[option.group.name].add_argument(\n *option.flags, help=option.help, default=option.default, **option.kwargs\n )\ndiff --git a/nox/_options.py b/nox/_options.py\nindex 6251523..353ed64 100644\n--- a/nox/_options.py\n+++ b/nox/_options.py\n@@ -474,6 +474,14 @@ options.add_options(\n hidden=True,\n finalizer_func=_color_finalizer,\n ),\n+ # Stores the original working directory that Nox was invoked from,\n+ # since it could be different from the Noxfile's directory.\n+ _option_set.Option(\n+ \"invoked_from\",\n+ group=None,\n+ hidden=True,\n+ default=lambda: os.getcwd(),\n+ ),\n )\n \n \ndiff --git a/nox/sessions.py b/nox/sessions.py\nindex 93a33dd..c97c7eb 100644\n--- a/nox/sessions.py\n+++ b/nox/sessions.py\n@@ -189,6 +189,18 @@ class Session:\n \"\"\"Returns True if Nox is being run in an interactive session or False otherwise.\"\"\"\n return not self._runner.global_config.non_interactive and sys.stdin.isatty()\n \n+ @property\n+ def invoked_from(self) -> str:\n+ \"\"\"The directory that Nox was originally invoked from.\n+\n+ Since you can use the ``--noxfile / -f`` command-line\n+ argument to run a Noxfile in a location different from your shell's\n+ current working directory, Nox automatically changes the working directory\n+ to the Noxfile's directory before running any sessions. This gives\n+ you the original working directory that Nox was invoked form.\n+ \"\"\"\n+ return self._runner.global_config.invoked_from\n+\n def chdir(self, dir: Union[str, os.PathLike]) -> None:\n \"\"\"Change the current working directory.\"\"\"\n self.log(f\"cd {dir}\")\ndiff --git a/nox/tasks.py b/nox/tasks.py\nindex 7e55100..5226332 100644\n--- a/nox/tasks.py\n+++ b/nox/tasks.py\n@@ -60,7 +60,8 @@ def load_nox_module(global_config: Namespace) -> Union[types.ModuleType, int]:\n # Move to the path where the Noxfile is.\n # This will ensure that the Noxfile's path is on sys.path, and that\n # import-time path resolutions work the way the Noxfile author would\n- # guess.\n+ # guess. The original working directory (the directory that Nox was\n+ # invoked from) gets stored by the .invoke_from \"option\" in _options.\n os.chdir(noxfile_parent_dir)\n return importlib.machinery.SourceFileLoader(\n \"user_nox_module\", global_config.noxfile\n", "test_patch": "diff --git a/tests/test__option_set.py b/tests/test__option_set.py\nindex 202473e..3107a54 100644\n--- a/tests/test__option_set.py\n+++ b/tests/test__option_set.py\n@@ -55,6 +55,29 @@ class TestOptionSet:\n with pytest.raises(KeyError):\n optionset.namespace(non_existant_option=\"meep\")\n \n+ def test_parser_hidden_option(self):\n+ optionset = _option_set.OptionSet()\n+ optionset.add_options(\n+ _option_set.Option(\n+ \"oh_boy_i_am_hidden\", hidden=True, group=None, default=\"meep\"\n+ )\n+ )\n+\n+ parser = optionset.parser()\n+ namespace = parser.parse_args([])\n+ optionset._finalize_args(namespace)\n+\n+ assert namespace.oh_boy_i_am_hidden == \"meep\"\n+\n+ def test_parser_groupless_option(self):\n+ optionset = _option_set.OptionSet()\n+ optionset.add_options(\n+ _option_set.Option(\"oh_no_i_have_no_group\", group=None, default=\"meep\")\n+ )\n+\n+ with pytest.raises(ValueError):\n+ optionset.parser()\n+\n def test_session_completer(self):\n parsed_args = _options.options.namespace(sessions=(), keywords=(), posargs=[])\n all_nox_sessions = _options._session_completer(\ndiff --git a/tests/test_sessions.py b/tests/test_sessions.py\nindex 4408bec..f12f02c 100644\n--- a/tests/test_sessions.py\n+++ b/tests/test_sessions.py\n@@ -67,7 +67,10 @@ class TestSession:\n signatures=[\"test\"],\n func=func,\n global_config=_options.options.namespace(\n- posargs=[], error_on_external_run=False, install_only=False\n+ posargs=[],\n+ error_on_external_run=False,\n+ install_only=False,\n+ invoked_from=os.getcwd(),\n ),\n manifest=mock.create_autospec(nox.manifest.Manifest),\n )\n@@ -104,6 +107,7 @@ class TestSession:\n assert session.bin_paths is runner.venv.bin_paths\n assert session.bin is runner.venv.bin_paths[0]\n assert session.python is runner.func.python\n+ assert session.invoked_from is runner.global_config.invoked_from\n \n def test_no_bin_paths(self):\n session, runner = self.make_session_and_runner()\n@@ -155,6 +159,17 @@ class TestSession:\n assert os.getcwd() == cdto\n os.chdir(current_cwd)\n \n+ def test_invoked_from(self, tmpdir):\n+ cdto = str(tmpdir.join(\"cdbby\").ensure(dir=True))\n+ current_cwd = os.getcwd()\n+\n+ session, _ = self.make_session_and_runner()\n+\n+ session.chdir(cdto)\n+\n+ assert session.invoked_from == current_cwd\n+ os.chdir(current_cwd)\n+\n def test_chdir_pathlib(self, tmpdir):\n cdto = str(tmpdir.join(\"cdbby\").ensure(dir=True))\n current_cwd = os.getcwd()\n", "FAIL_TO_PASS": ["tests/test__option_set.py::TestOptionSet::test_parser_groupless_option", "tests/test_sessions.py::TestSession::test_create_tmp", "tests/test_sessions.py::TestSession::test_create_tmp_twice", "tests/test_sessions.py::TestSession::test_properties", "tests/test_sessions.py::TestSession::test_no_bin_paths", "tests/test_sessions.py::TestSession::test_virtualenv_as_none", "tests/test_sessions.py::TestSession::test_interactive", "tests/test_sessions.py::TestSession::test_explicit_non_interactive", "tests/test_sessions.py::TestSession::test_chdir", "tests/test_sessions.py::TestSession::test_invoked_from", "tests/test_sessions.py::TestSession::test_chdir_pathlib", "tests/test_sessions.py::TestSession::test_run_bad_args", "tests/test_sessions.py::TestSession::test_run_with_func", "tests/test_sessions.py::TestSession::test_run_with_func_error", "tests/test_sessions.py::TestSession::test_run_install_only", "tests/test_sessions.py::TestSession::test_run_install_only_should_install", "tests/test_sessions.py::TestSession::test_run_success", "tests/test_sessions.py::TestSession::test_run_error", "tests/test_sessions.py::TestSession::test_run_overly_env", "tests/test_sessions.py::TestSession::test_run_external_not_a_virtualenv", "tests/test_sessions.py::TestSession::test_run_external_condaenv", "tests/test_sessions.py::TestSession::test_run_external_with_error_on_external_run", "tests/test_sessions.py::TestSession::test_run_external_with_error_on_external_run_condaenv", "tests/test_sessions.py::TestSession::test_run_always_bad_args", "tests/test_sessions.py::TestSession::test_run_always_success", "tests/test_sessions.py::TestSession::test_run_always_install_only", "tests/test_sessions.py::TestSession::test_run_always_no_install[True-True-False]", "tests/test_sessions.py::TestSession::test_run_always_no_install[True-False-True]", "tests/test_sessions.py::TestSession::test_run_always_no_install[False-True-True]", "tests/test_sessions.py::TestSession::test_run_always_no_install[False-False-True]", "tests/test_sessions.py::TestSession::test_conda_install_bad_args", "tests/test_sessions.py::TestSession::test_conda_install_bad_args_odd_nb_double_quotes", "tests/test_sessions.py::TestSession::test_conda_install_bad_args_cannot_escape", "tests/test_sessions.py::TestSession::test_conda_install_not_a_condaenv", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[True-True-False]", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[True-False-True]", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[False-True-True]", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[False-False-True]", "tests/test_sessions.py::TestSession::test_install_bad_args_no_arg", "tests/test_sessions.py::TestSession::test_install_not_a_virtualenv", "tests/test_sessions.py::TestSession::test_notify", "tests/test_sessions.py::TestSession::test_log", "tests/test_sessions.py::TestSession::test_error", "tests/test_sessions.py::TestSession::test_error_no_log", "tests/test_sessions.py::TestSession::test_skip_no_log", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[True-True-False]", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[True-False-True]", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[False-True-True]", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[False-False-True]", "tests/test_sessions.py::TestSession::test___slots__", "tests/test_sessions.py::TestSession::test___dict__"]}], "all_FAIL_TO_PASS": ["tests/test__option_set.py::TestOptionSet::test_parser_groupless_option", "tests/test_sessions.py::TestSession::test_create_tmp", "tests/test_sessions.py::TestSession::test_create_tmp_twice", "tests/test_sessions.py::TestSession::test_properties", "tests/test_sessions.py::TestSession::test_no_bin_paths", "tests/test_sessions.py::TestSession::test_virtualenv_as_none", "tests/test_sessions.py::TestSession::test_interactive", "tests/test_sessions.py::TestSession::test_explicit_non_interactive", "tests/test_sessions.py::TestSession::test_chdir", "tests/test_sessions.py::TestSession::test_invoked_from", "tests/test_sessions.py::TestSession::test_chdir_pathlib", "tests/test_sessions.py::TestSession::test_run_bad_args", "tests/test_sessions.py::TestSession::test_run_with_func", "tests/test_sessions.py::TestSession::test_run_with_func_error", "tests/test_sessions.py::TestSession::test_run_install_only", "tests/test_sessions.py::TestSession::test_run_install_only_should_install", "tests/test_sessions.py::TestSession::test_run_success", "tests/test_sessions.py::TestSession::test_run_error", "tests/test_sessions.py::TestSession::test_run_overly_env", "tests/test_sessions.py::TestSession::test_run_external_not_a_virtualenv", "tests/test_sessions.py::TestSession::test_run_external_condaenv", "tests/test_sessions.py::TestSession::test_run_external_with_error_on_external_run", "tests/test_sessions.py::TestSession::test_run_external_with_error_on_external_run_condaenv", "tests/test_sessions.py::TestSession::test_run_always_bad_args", "tests/test_sessions.py::TestSession::test_run_always_success", "tests/test_sessions.py::TestSession::test_run_always_install_only", "tests/test_sessions.py::TestSession::test_run_always_no_install[True-True-False]", "tests/test_sessions.py::TestSession::test_run_always_no_install[True-False-True]", "tests/test_sessions.py::TestSession::test_run_always_no_install[False-True-True]", "tests/test_sessions.py::TestSession::test_run_always_no_install[False-False-True]", "tests/test_sessions.py::TestSession::test_conda_install_bad_args", "tests/test_sessions.py::TestSession::test_conda_install_bad_args_odd_nb_double_quotes", "tests/test_sessions.py::TestSession::test_conda_install_bad_args_cannot_escape", "tests/test_sessions.py::TestSession::test_conda_install_not_a_condaenv", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[True-True-False]", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[True-False-True]", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[False-True-True]", "tests/test_sessions.py::TestSession::test_conda_venv_reused_with_no_install[False-False-True]", "tests/test_sessions.py::TestSession::test_install_bad_args_no_arg", "tests/test_sessions.py::TestSession::test_install_not_a_virtualenv", "tests/test_sessions.py::TestSession::test_notify", "tests/test_sessions.py::TestSession::test_log", "tests/test_sessions.py::TestSession::test_error", "tests/test_sessions.py::TestSession::test_error_no_log", "tests/test_sessions.py::TestSession::test_skip_no_log", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[True-True-False]", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[True-False-True]", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[False-True-True]", "tests/test_sessions.py::TestSession::test_session_venv_reused_with_no_install[False-False-True]", "tests/test_sessions.py::TestSession::test___slots__", "tests/test_sessions.py::TestSession::test___dict__"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "theacodes__nox-482_x1", "level": 1, "source": "swerebenchv2", "repo": "theacodes/nox", "image": "swerebenchv2/theacodes-nox:482-e7d4f5a", "base_commit": "e7d4f5a299a356ccf8988029796fe296db57536d", "num_bugs": 1, "bugs": [{"instance_id": "theacodes__nox-482", "base_commit": "e7d4f5a299a356ccf8988029796fe296db57536d", "gold_patch": "diff --git a/nox/sessions.py b/nox/sessions.py\nindex 5d1b35c..78a0286 100644\n--- a/nox/sessions.py\n+++ b/nox/sessions.py\n@@ -516,6 +516,10 @@ class Session:\n \"\"\"Outputs a log during the session.\"\"\"\n logger.info(*args, **kwargs)\n \n+ def warn(self, *args: Any, **kwargs: Any) -> None:\n+ \"\"\"Outputs a warning during the session.\"\"\"\n+ logger.warning(*args, **kwargs)\n+\n def error(self, *args: Any) -> \"_typing.NoReturn\":\n \"\"\"Immediately aborts the session and optionally logs an error.\"\"\"\n raise _SessionQuit(*args)\n", "test_patch": "diff --git a/tests/test_sessions.py b/tests/test_sessions.py\nindex 3c949e6..2d66ba9 100644\n--- a/tests/test_sessions.py\n+++ b/tests/test_sessions.py\n@@ -601,6 +601,14 @@ class TestSession:\n \n assert \"meep\" in caplog.text\n \n+ def test_warn(self, caplog):\n+ caplog.set_level(logging.WARNING)\n+ session, _ = self.make_session_and_runner()\n+\n+ session.warn(\"meep\")\n+\n+ assert \"meep\" in caplog.text\n+\n def test_error(self, caplog):\n caplog.set_level(logging.ERROR)\n session, _ = self.make_session_and_runner()\n", "FAIL_TO_PASS": ["tests/test_sessions.py::TestSession::test_warn"]}], "all_FAIL_TO_PASS": ["tests/test_sessions.py::TestSession::test_warn"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "codezonediitj__pydatastructs-211_x1", "level": 1, "source": "swerebenchv2", "repo": "codezonediitj/pydatastructs", "image": "swerebenchv2/codezonediitj-pydatastructs:211-26c0848", "base_commit": "26c08483ec976ff95148ef0b4bf8ecbad135e822", "num_bugs": 1, "bugs": [{"instance_id": "codezonediitj__pydatastructs-211", "base_commit": "26c08483ec976ff95148ef0b4bf8ecbad135e822", "gold_patch": "diff --git a/pydatastructs/linear_data_structures/arrays.py b/pydatastructs/linear_data_structures/arrays.py\nindex d2800a5..6419898 100644\n--- a/pydatastructs/linear_data_structures/arrays.py\n+++ b/pydatastructs/linear_data_structures/arrays.py\n@@ -255,6 +255,10 @@ class DynamicOneDimensionalArray(DynamicArray, OneDimensionalArray):\n def size(self):\n return self._size\n \n+ def __reversed__(self):\n+ for i in range(self._last_pos_filled, -1, -1):\n+ yield self._data[i]\n+\n class ArrayForTrees(DynamicOneDimensionalArray):\n \"\"\"\n Utility dynamic array for storing nodes of a tree.\n", "test_patch": "diff --git a/pydatastructs/linear_data_structures/tests/test_arrays.py b/pydatastructs/linear_data_structures/tests/test_arrays.py\nindex 1a65d69..b534d82 100644\n--- a/pydatastructs/linear_data_structures/tests/test_arrays.py\n+++ b/pydatastructs/linear_data_structures/tests/test_arrays.py\n@@ -37,3 +37,11 @@ def test_DynamicOneDimensionalArray():\n assert A.size == 3\n A.fill(4)\n assert A._data == [4, 4, 4]\n+ b = DynamicOneDimensionalArray(int, 0)\n+ b.append(1)\n+ b.append(2)\n+ b.append(3)\n+ b.append(4)\n+ b.append(5)\n+ assert b._data == [1, 2, 3, 4, 5, None, None]\n+ assert list(reversed(b)) == [5, 4, 3, 2, 1]\n", "FAIL_TO_PASS": ["pydatastructs/linear_data_structures/tests/test_arrays.py::test_DynamicOneDimensionalArray"]}], "all_FAIL_TO_PASS": ["pydatastructs/linear_data_structures/tests/test_arrays.py::test_DynamicOneDimensionalArray"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "theacodes__nox-489_x1", "level": 1, "source": "swerebenchv2", "repo": "theacodes/nox", "image": "swerebenchv2/theacodes-nox:489-d95c57c", "base_commit": "d95c57cc7891b794b02c6fcb6317e8a71323c223", "num_bugs": 1, "bugs": [{"instance_id": "theacodes__nox-489", "base_commit": "d95c57cc7891b794b02c6fcb6317e8a71323c223", "gold_patch": "diff --git a/nox/sessions.py b/nox/sessions.py\nindex 78a0286..08c9cb4 100644\n--- a/nox/sessions.py\n+++ b/nox/sessions.py\n@@ -520,6 +520,10 @@ class Session:\n \"\"\"Outputs a warning during the session.\"\"\"\n logger.warning(*args, **kwargs)\n \n+ def debug(self, *args: Any, **kwargs: Any) -> None:\n+ \"\"\"Outputs a debug-level message during the session.\"\"\"\n+ logger.debug(*args, **kwargs)\n+\n def error(self, *args: Any) -> \"_typing.NoReturn\":\n \"\"\"Immediately aborts the session and optionally logs an error.\"\"\"\n raise _SessionQuit(*args)\n", "test_patch": "diff --git a/tests/test_sessions.py b/tests/test_sessions.py\nindex 2d66ba9..6bcd916 100644\n--- a/tests/test_sessions.py\n+++ b/tests/test_sessions.py\n@@ -609,6 +609,14 @@ class TestSession:\n \n assert \"meep\" in caplog.text\n \n+ def test_debug(self, caplog):\n+ caplog.set_level(logging.DEBUG)\n+ session, _ = self.make_session_and_runner()\n+\n+ session.debug(\"meep\")\n+\n+ assert \"meep\" in caplog.text\n+\n def test_error(self, caplog):\n caplog.set_level(logging.ERROR)\n session, _ = self.make_session_and_runner()\n", "FAIL_TO_PASS": ["tests/test_sessions.py::TestSession::test_debug"]}], "all_FAIL_TO_PASS": ["tests/test_sessions.py::TestSession::test_debug"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "amaranth-lang__amaranth-1319_x1", "level": 1, "source": "swerebenchv2", "repo": "amaranth-lang/amaranth", "image": "swerebenchv2/amaranth-lang-amaranth:1319-49a8a94", "base_commit": "49a8a942e82bb214d10c1bb670b61a5264b82be0", "num_bugs": 1, "bugs": [{"instance_id": "amaranth-lang__amaranth-1319", "base_commit": "49a8a942e82bb214d10c1bb670b61a5264b82be0", "gold_patch": "diff --git a/amaranth/sim/_pyrtl.py b/amaranth/sim/_pyrtl.py\nindex f6c4943..5505cfb 100644\n--- a/amaranth/sim/_pyrtl.py\n+++ b/amaranth/sim/_pyrtl.py\n@@ -153,12 +153,16 @@ class _ValueCompiler(ValueVisitor, _Compiler):\n \n \n class _RHSValueCompiler(_ValueCompiler):\n- def __init__(self, state, emitter, *, mode, inputs=None):\n+ def __init__(self, state, emitter, *, mode, inputs=None, rrhs=None):\n super().__init__(state, emitter)\n assert mode in (\"curr\", \"next\")\n self.mode = mode\n # If not None, `inputs` gets populated with RHS signals.\n self.inputs = inputs\n+ # When this compiler is used to grab the \"next\" value from within _LHSValueCompiler,\n+ # we still need to use \"curr\" mode for reading part offsets etc. Allow setting a separate\n+ # _RhsValueCompiler for these contexts.\n+ self.rrhs = rrhs or self\n \n def sign(self, value):\n value_mask = (1 << len(value)) - 1\n@@ -251,7 +255,7 @@ class _RHSValueCompiler(_ValueCompiler):\n \n def on_Part(self, value):\n offset_mask = (1 << len(value.offset)) - 1\n- offset = f\"({value.stride} * ({offset_mask:#x} & {self(value.offset)}))\"\n+ offset = f\"({value.stride} * ({offset_mask:#x} & {self.rrhs(value.offset)}))\"\n return f\"({(1 << value.width) - 1} & \" \\\n f\"{self(value.value)} >> {offset})\"\n \n@@ -267,7 +271,7 @@ class _RHSValueCompiler(_ValueCompiler):\n return f\"0\"\n \n def on_SwitchValue(self, value):\n- gen_test = self.emitter.def_var(\"test\", f\"{(1 << len(value.test)) - 1:#x} & {self(value.test)}\")\n+ gen_test = self.emitter.def_var(\"test\", f\"{(1 << len(value.test)) - 1:#x} & {self.rrhs(value.test)}\")\n gen_value = self.emitter.def_var(\"rhs_switch\", \"0\")\n def case_handler(patterns, elem):\n self.emitter.append(f\"{gen_value} = {self.sign(elem)}\")\n@@ -290,7 +294,7 @@ class _LHSValueCompiler(_ValueCompiler):\n self.rrhs = rhs\n # `lrhs` is used to translate the read part of a read-modify-write cycle during partial\n # update of an lvalue.\n- self.lrhs = _RHSValueCompiler(state, emitter, mode=\"next\", inputs=None)\n+ self.lrhs = _RHSValueCompiler(state, emitter, mode=\"next\", inputs=None, rrhs=rhs)\n # If not None, `outputs` gets populated with signals on LHS.\n self.outputs = outputs\n \n", "test_patch": "diff --git a/tests/test_sim.py b/tests/test_sim.py\nindex fa4f881..6b9affd 100644\n--- a/tests/test_sim.py\n+++ b/tests/test_sim.py\n@@ -366,6 +366,16 @@ class SimulatorUnitTestCase(FHDLTestCase):\n self.assertStatement(stmt, [C(1), C(0b010)], C(0b001110101, 9))\n self.assertStatement(stmt, [C(2), C(0b100)], C(0b001001001, 9))\n \n+ def test_array_lhs_heterogenous_slice(self):\n+ l = Signal(1, init=1)\n+ m = Signal(3, init=4)\n+ n = Signal(5, init=7)\n+ array = Array([l, m, n])\n+ stmt = lambda y, a, b: [array[a].as_value()[2:].eq(b), y.eq(Cat(*array))]\n+ self.assertStatement(stmt, [C(0), C(0b000)], C(0b001111001, 9))\n+ self.assertStatement(stmt, [C(1), C(0b010)], C(0b001110001, 9))\n+ self.assertStatement(stmt, [C(2), C(0b100)], C(0b100111001, 9))\n+\n def test_array_lhs_oob(self):\n l = Signal(3)\n m = Signal(3)\n", "FAIL_TO_PASS": ["tests/test_sim.py::SimulatorUnitTestCase::test_array_lhs_heterogenous_slice"]}], "all_FAIL_TO_PASS": ["tests/test_sim.py::SimulatorUnitTestCase::test_array_lhs_heterogenous_slice"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "scitools__cartopy-2407_x1", "level": 1, "source": "swerebenchv2", "repo": "SciTools/cartopy", "image": "swerebenchv2/scitools-cartopy:2407-738bba5", "base_commit": "738bba5921a3ca72a3f6d6ec9fa804514706bad4", "num_bugs": 1, "bugs": [{"instance_id": "scitools__cartopy-2407", "base_commit": "738bba5921a3ca72a3f6d6ec9fa804514706bad4", "gold_patch": "diff --git a/lib/cartopy/crs.py b/lib/cartopy/crs.py\nindex c2441516..bc354198 100644\n--- a/lib/cartopy/crs.py\n+++ b/lib/cartopy/crs.py\n@@ -918,10 +918,7 @@ class Projection(CRS, metaclass=ABCMeta):\n geoms = []\n for geom in geometry.geoms:\n geoms.append(self._project_point(geom, src_crs))\n- if geoms:\n- return sgeom.MultiPoint(geoms)\n- else:\n- return sgeom.MultiPoint()\n+ return sgeom.MultiPoint(geoms)\n \n def _project_multiline(self, geometry, src_crs):\n geoms = []\n@@ -929,10 +926,7 @@ class Projection(CRS, metaclass=ABCMeta):\n r = self._project_line_string(geom, src_crs)\n if r:\n geoms.extend(r.geoms)\n- if geoms:\n- return sgeom.MultiLineString(geoms)\n- else:\n- return []\n+ return sgeom.MultiLineString(geoms)\n \n def _project_multipolygon(self, geometry, src_crs):\n geoms = []\n@@ -940,11 +934,7 @@ class Projection(CRS, metaclass=ABCMeta):\n r = self._project_polygon(geom, src_crs)\n if r:\n geoms.extend(r.geoms)\n- if geoms:\n- result = sgeom.MultiPolygon(geoms)\n- else:\n- result = sgeom.MultiPolygon()\n- return result\n+ return sgeom.MultiPolygon(geoms)\n \n def _project_polygon(self, polygon, src_crs):\n \"\"\"\n", "test_patch": "diff --git a/lib/cartopy/tests/test_line_string.py b/lib/cartopy/tests/test_line_string.py\nindex a0b42ff0..926dd5b5 100644\n--- a/lib/cartopy/tests/test_line_string.py\n+++ b/lib/cartopy/tests/test_line_string.py\n@@ -8,6 +8,7 @@ import time\n \n import numpy as np\n import pytest\n+import shapely\n import shapely.geometry as sgeom\n \n import cartopy.crs as ccrs\n@@ -73,6 +74,15 @@ class TestLineString:\n tgt_proj.project_geometry(line_string, src_proj)\n assert time.time() < cutoff_time, 'Projection took too long'\n \n+ @pytest.mark.skipif(shapely.__version__ < \"2\",\n+ reason=\"Shapely <2 has an incorrect geom_type \")\n+ def test_multi_linestring_return_type(self):\n+ # Check that the return type of project_geometry is a MultiLineString\n+ # and not an empty list\n+ multi_line_string = ccrs.Mercator().project_geometry(\n+ sgeom.MultiLineString(), ccrs.PlateCarree())\n+ assert isinstance(multi_line_string, sgeom.MultiLineString)\n+\n \n class FakeProjection(ccrs.PlateCarree):\n def __init__(self, left_offset=0, right_offset=0):\n", "FAIL_TO_PASS": ["lib/cartopy/tests/test_line_string.py::TestLineString::test_multi_linestring_return_type"]}], "all_FAIL_TO_PASS": ["lib/cartopy/tests/test_line_string.py::TestLineString::test_multi_linestring_return_type"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jnothman__upsetplot-261_x1", "level": 1, "source": "swerebenchv2", "repo": "jnothman/UpSetPlot", "image": "swerebenchv2/jnothman-upsetplot:261-19e891e", "base_commit": "19e891e869a0f8dc6fbb4ba01b1949a17bc898a3", "num_bugs": 1, "bugs": [{"instance_id": "jnothman__upsetplot-261", "base_commit": "19e891e869a0f8dc6fbb4ba01b1949a17bc898a3", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 197292b..a00b4d9 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -4,6 +4,9 @@ What's new in version 0.9\n - Fixes a bug where ``show_percentages`` used the incorrect denominator if\n filtering (e.g. ``min_subset_size``) was applied. This bug was a regression\n introduced in version 0.7. (:issue:`248`)\n+- Add a ``style_categories`` method to customize category plot styles, including\n+ shading of rows in the intersection matrix, and bars in the totals plot.\n+ (:issue:`261` with thanks to :user:`Marcel Albus `).\n - Ability to disable totals plot with `totals_plot_elements=0`. (:issue:`246`)\n - Added ``max_subset_rank`` to get only n most populous subsets. (:issue:`253`)\n \ndiff --git a/examples/plot_highlight.py b/examples/plot_highlight.py\nindex 1cffbc6..bccc332 100644\n--- a/examples/plot_highlight.py\n+++ b/examples/plot_highlight.py\n@@ -62,7 +62,9 @@ plt.show()\n \n upset = UpSet(example, facecolor=\"gray\")\n upset.style_subsets(present=\"cat0\", label=\"Contains cat0\", facecolor=\"blue\")\n-upset.style_subsets(present=\"cat1\", label=\"Contains cat1\", hatch=\"xx\")\n+upset.style_subsets(\n+ present=\"cat1\", label=\"Contains cat1\", hatch=\"xx\", edgecolor=\"black\"\n+)\n upset.style_subsets(present=\"cat2\", label=\"Contains cat2\", edgecolor=\"red\")\n \n # reduce legend size:\ndiff --git a/examples/plot_highlight_categories.py b/examples/plot_highlight_categories.py\nnew file mode 100644\nindex 0000000..eae84d9\n--- /dev/null\n+++ b/examples/plot_highlight_categories.py\n@@ -0,0 +1,41 @@\n+\"\"\"\n+================================\n+Highlighting selected categories\n+================================\n+\n+Demonstrates use of the `style_categories` method to mark some\n+categories differently.\n+\"\"\"\n+\n+from matplotlib import pyplot as plt\n+\n+from upsetplot import UpSet, generate_counts\n+\n+example = generate_counts()\n+\n+\n+##########################################################################\n+# Categories can be shaded by name with the ``shading_`` parameters.\n+\n+upset = UpSet(example)\n+upset.style_categories(\"cat2\", shading_edgecolor=\"darkgreen\", shading_linewidth=1)\n+upset.style_categories(\n+ \"cat1\",\n+ shading_facecolor=\"lavender\",\n+)\n+upset.plot()\n+plt.suptitle(\"Shade or edge a category with color\")\n+plt.show()\n+\n+\n+##########################################################################\n+# Category total bars can be styled with the ``bar_`` parameters.\n+# You can also specify categories using a list of names.\n+\n+upset = UpSet(example)\n+upset.style_categories(\n+ [\"cat2\", \"cat1\"], bar_facecolor=\"aqua\", bar_hatch=\"xx\", bar_edgecolor=\"black\"\n+)\n+upset.plot()\n+plt.suptitle(\"\")\n+plt.show()\ndiff --git a/upsetplot/plotting.py b/upsetplot/plotting.py\nindex 627d846..e2f50bd 100644\n--- a/upsetplot/plotting.py\n+++ b/upsetplot/plotting.py\n@@ -266,6 +266,7 @@ class UpSet:\n \"\"\"\n \n _default_figsize = (10, 6)\n+ DPI = 100 # standard matplotlib value\n \n def __init__(\n self,\n@@ -338,6 +339,7 @@ class UpSet:\n reverse=not self._horizontal,\n include_empty_subsets=include_empty_subsets,\n )\n+ self.category_styles = {}\n self.subset_styles = [\n {\"facecolor\": facecolor} for i in range(len(self.intersections))\n ]\n@@ -924,6 +926,16 @@ class UpSet:\n )\n self._label_sizes(ax, rects, \"left\" if self._horizontal else \"top\")\n \n+ for category, rect in zip(self.totals.index.values, rects):\n+ style = {\n+ k[len(\"bar_\") :]: v\n+ for k, v in self.category_styles.get(category, {}).items()\n+ if k.startswith(\"bar_\")\n+ }\n+ style.setdefault(\"edgecolor\", style.get(\"facecolor\", self._facecolor))\n+ for attr, val in style.items():\n+ getattr(rect, \"set_\" + attr)(val)\n+\n max_total = self.totals.max()\n if self._horizontal:\n orig_ax.set_xlim(max_total, 0)\n@@ -935,15 +947,34 @@ class UpSet:\n ax.patch.set_visible(False)\n \n def plot_shading(self, ax):\n- # alternating row shading (XXX: use add_patch(Rectangle)?)\n- for i in range(0, len(self.totals), 2):\n+ # shade all rows, set every second row to zero visibility\n+ for i, category in enumerate(self.totals.index):\n+ default_shading = (\n+ self._shading_color if i % 2 == 0 else (0.0, 0.0, 0.0, 0.0)\n+ )\n+ shading_style = {\n+ k[len(\"shading_\") :]: v\n+ for k, v in self.category_styles.get(category, {}).items()\n+ if k.startswith(\"shading_\")\n+ }\n+\n+ lw = shading_style.get(\n+ \"linewidth\", 1 if shading_style.get(\"edgecolor\") else 0\n+ )\n+ lw_padding = lw / (self._default_figsize[0] * self.DPI)\n+ start_x = lw_padding\n+ end_x = 1 - lw_padding * 3\n+\n rect = plt.Rectangle(\n- self._swapaxes(0, i - 0.4),\n- *self._swapaxes(*(1, 0.8)),\n- facecolor=self._shading_color,\n- lw=0,\n+ self._swapaxes(start_x, i - 0.4),\n+ *self._swapaxes(end_x, 0.8),\n+ facecolor=shading_style.get(\"facecolor\", default_shading),\n+ edgecolor=shading_style.get(\"edgecolor\", None),\n+ ls=shading_style.get(\"linestyle\", \"-\"),\n+ lw=lw,\n zorder=0,\n )\n+\n ax.add_patch(rect)\n ax.set_frame_on(False)\n ax.tick_params(\n@@ -962,6 +993,66 @@ class UpSet:\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n \n+ def style_categories(\n+ self,\n+ categories,\n+ *,\n+ bar_facecolor=None,\n+ bar_hatch=None,\n+ bar_edgecolor=None,\n+ bar_linewidth=None,\n+ bar_linestyle=None,\n+ shading_facecolor=None,\n+ shading_edgecolor=None,\n+ shading_linewidth=None,\n+ shading_linestyle=None,\n+ ):\n+ \"\"\"Updates the style of the categories.\n+\n+ Select a category by name, and style either its total bar or its shading.\n+\n+ .. versionadded:: 0.9\n+\n+ Parameters\n+ ----------\n+ categories : str or list[str]\n+ Category names where the changed style applies.\n+ bar_facecolor : str or RGBA matplotlib color tuple, optional.\n+ Override the default facecolor in the totals plot.\n+ bar_hatch : str, optional\n+ Set a hatch for the totals plot.\n+ bar_edgecolor : str or matplotlib color, optional\n+ Set the edgecolor for total bars.\n+ bar_linewidth : int, optional\n+ Line width in points for total bar edges.\n+ bar_linestyle : str, optional\n+ Line style for edges.\n+ shading_facecolor : str or RGBA matplotlib color tuple, optional.\n+ Override the default alternating shading for specified categories.\n+ shading_edgecolor : str or matplotlib color, optional\n+ Set the edgecolor for bars, dots, and the line between dots.\n+ shading_linewidth : int, optional\n+ Line width in points for edges.\n+ shading_linestyle : str, optional\n+ Line style for edges.\n+ \"\"\"\n+ if isinstance(categories, str):\n+ categories = [categories]\n+ style = {\n+ \"bar_facecolor\": bar_facecolor,\n+ \"bar_hatch\": bar_hatch,\n+ \"bar_edgecolor\": bar_edgecolor,\n+ \"bar_linewidth\": bar_linewidth,\n+ \"bar_linestyle\": bar_linestyle,\n+ \"shading_facecolor\": shading_facecolor,\n+ \"shading_edgecolor\": shading_edgecolor,\n+ \"shading_linewidth\": shading_linewidth,\n+ \"shading_linestyle\": shading_linestyle,\n+ }\n+ style = {k: v for k, v in style.items() if v is not None}\n+ for category_name in categories:\n+ self.category_styles.setdefault(category_name, {}).update(style)\n+\n def plot(self, fig=None):\n \"\"\"Draw all parts of the plot onto fig or a new figure\n \n", "test_patch": "diff --git a/upsetplot/tests/test_upsetplot.py b/upsetplot/tests/test_upsetplot.py\nindex 80dfa76..d96b42d 100644\n--- a/upsetplot/tests/test_upsetplot.py\n+++ b/upsetplot/tests/test_upsetplot.py\n@@ -1154,6 +1154,51 @@ def test_style_subsets_artists(orientation):\n # matrix_line_collection = upset_axes[\"matrix\"].collections[1]\n \n \n+@pytest.mark.parametrize(\n+ (\n+ \"kwarg_list\",\n+ \"expected_category_styles\",\n+ ),\n+ [\n+ # Different forms of including two categories\n+ (\n+ [{\"categories\": [\"cat1\", \"cat2\"], \"shading_facecolor\": \"red\"}],\n+ {\n+ \"cat1\": {\"shading_facecolor\": \"red\"},\n+ \"cat2\": {\"shading_facecolor\": \"red\"},\n+ },\n+ ),\n+ (\n+ [\n+ {\"categories\": [\"cat1\", \"cat2\"], \"shading_facecolor\": \"red\"},\n+ {\"categories\": \"cat1\", \"shading_facecolor\": \"green\"},\n+ ],\n+ {\n+ \"cat1\": {\"shading_facecolor\": \"green\"},\n+ \"cat2\": {\"shading_facecolor\": \"red\"},\n+ },\n+ ),\n+ (\n+ [\n+ {\"categories\": [\"cat1\", \"cat2\"], \"shading_facecolor\": \"red\"},\n+ {\"categories\": \"cat1\", \"shading_edgecolor\": \"green\"},\n+ ],\n+ {\n+ \"cat1\": {\"shading_facecolor\": \"red\", \"shading_edgecolor\": \"green\"},\n+ \"cat2\": {\"shading_facecolor\": \"red\"},\n+ },\n+ ),\n+ ],\n+)\n+def test_categories(kwarg_list, expected_category_styles):\n+ data = generate_counts()\n+ upset = UpSet(data, facecolor=\"blue\")\n+ for kw in kwarg_list:\n+ upset.style_categories(**kw)\n+ actual_category_styles = upset.category_styles\n+ assert actual_category_styles == expected_category_styles\n+\n+\n def test_many_categories():\n # Tests regressions against GH#193\n n_cats = 250\n", "FAIL_TO_PASS": ["upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list0-expected_category_styles0]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list1-expected_category_styles1]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list2-expected_category_styles2]"]}], "all_FAIL_TO_PASS": ["upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list0-expected_category_styles0]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list1-expected_category_styles1]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list2-expected_category_styles2]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "sdv-dev__rdt-755_x1", "level": 1, "source": "swerebenchv2", "repo": "sdv-dev/RDT", "image": "swerebenchv2/sdv-dev-rdt:755-9f37fb4", "base_commit": "9f37fb4db6d16e5d72e42cc7fa1ba100f3878e0a", "num_bugs": 1, "bugs": [{"instance_id": "sdv-dev__rdt-755", "base_commit": "9f37fb4db6d16e5d72e42cc7fa1ba100f3878e0a", "gold_patch": "diff --git a/rdt/transformers/categorical.py b/rdt/transformers/categorical.py\nindex fef1242..13d4e03 100644\n--- a/rdt/transformers/categorical.py\n+++ b/rdt/transformers/categorical.py\n@@ -9,7 +9,7 @@ from scipy.stats import norm\n \n from rdt.errors import TransformerInputError\n from rdt.transformers.base import BaseTransformer\n-from rdt.transformers.utils import fill_nan_with_none\n+from rdt.transformers.utils import check_nan_in_transform, fill_nan_with_none, try_convert_to_dtype\n \n LOGGER = logging.getLogger(__name__)\n \n@@ -177,6 +177,7 @@ class UniformEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n data = data.clip(0, 1)\n bins = [0]\n labels = []\n@@ -192,7 +193,10 @@ class UniformEncoder(BaseTransformer):\n labels.append(key)\n \n result = pd.cut(data, bins=bins, labels=labels, include_lowest=True)\n- return result.replace(nan_name, np.nan).astype(self.dtype)\n+ result = result.replace(nan_name, np.nan)\n+ result = try_convert_to_dtype(result, self.dtype)\n+\n+ return result\n \n \n class OrderedUniformEncoder(UniformEncoder):\n@@ -333,6 +337,7 @@ class FrequencyEncoder(BaseTransformer):\n )\n super().__init__()\n self.add_noise = add_noise\n+ self._is_integer = None\n \n @staticmethod\n def _get_intervals(data):\n@@ -516,6 +521,7 @@ class FrequencyEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n data = data.clip(0, 1)\n num_rows = len(data)\n num_categories = len(self.means)\n@@ -545,6 +551,7 @@ class OneHotEncoder(BaseTransformer):\n _dummy_encoded = False\n _indexer = None\n _uniques = None\n+ dtype = None\n \n @staticmethod\n def _prepare_data(data):\n@@ -582,6 +589,7 @@ class OneHotEncoder(BaseTransformer):\n data (pandas.Series or pandas.DataFrame):\n Data to fit the transformer to.\n \"\"\"\n+ self.dtype = data.dtype\n data = self._prepare_data(data)\n \n null = pd.isna(data).to_numpy()\n@@ -657,6 +665,7 @@ class OneHotEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n if not isinstance(data, np.ndarray):\n data = data.to_numpy()\n \n@@ -664,8 +673,10 @@ class OneHotEncoder(BaseTransformer):\n data = data.reshape(-1, 1)\n \n indices = np.argmax(data, axis=1)\n+ result = pd.Series(indices).map(self.dummies.__getitem__)\n+ result = try_convert_to_dtype(result, self.dtype)\n \n- return pd.Series(indices).map(self.dummies.__getitem__)\n+ return result\n \n \n class LabelEncoder(BaseTransformer):\n@@ -801,13 +812,15 @@ class LabelEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n if self.add_noise:\n data = np.floor(data)\n \n data = data.clip(min(self.values_to_categories), max(self.values_to_categories))\n data = data.round().map(self.values_to_categories)\n+ data = try_convert_to_dtype(data, self.dtype)\n \n- return data.astype(self.dtype)\n+ return data\n \n \n class OrderedLabelEncoder(LabelEncoder):\n@@ -865,6 +878,7 @@ class OrderedLabelEncoder(LabelEncoder):\n data (pandas.Series):\n Data to fit the transformer to.\n \"\"\"\n+ self.dtype = data.dtype\n data = data.fillna(np.nan)\n missing = list(data[~data.isin(self.order)].unique())\n if len(missing) > 0:\ndiff --git a/rdt/transformers/text.py b/rdt/transformers/text.py\nindex ca1887a..bb7fd9e 100644\n--- a/rdt/transformers/text.py\n+++ b/rdt/transformers/text.py\n@@ -1,10 +1,10 @@\n \"\"\"Transformers for text data.\"\"\"\n import logging\n+import warnings\n \n import numpy as np\n import pandas as pd\n \n-from rdt.errors import TransformerProcessingError\n from rdt.transformers.base import BaseTransformer\n from rdt.transformers.utils import strings_from_regex\n \n@@ -141,6 +141,37 @@ class RegexGenerator(BaseTransformer):\n \"\"\"Drop the input column by returning ``None``.\"\"\"\n return None\n \n+ def _warn_not_enough_unique_values(self, sample_size):\n+ \"\"\"Warn the user that the regex cannot generate enough unique values.\n+\n+ Args:\n+ sample_size (int):\n+ Number of samples to be generated.\n+ \"\"\"\n+ warned = False\n+ if sample_size > self.generator_size:\n+ if self.enforce_uniqueness:\n+ warnings.warn(\n+ f\"The regex for '{self.get_input_column()}' can only generate \"\n+ f'{self.generator_size} unique values. Additional values may not exactly '\n+ 'follow the provided regex.'\n+ )\n+ warned = True\n+ else:\n+ LOGGER.info(\n+ \"The data has %s rows but the regex for '%s' can only create %s unique values.\"\n+ \" Some values in '%s' may be repeated.\",\n+ sample_size, self.get_input_column(), self.generator_size,\n+ self.get_input_column()\n+ )\n+\n+ remaining = self.generator_size - self.generated\n+ if sample_size > remaining and self.enforce_uniqueness and not warned:\n+ warnings.warn(\n+ f'The regex generator is not able to generate {sample_size} new unique '\n+ f'values (only {max(remaining, 0)} unique values left).'\n+ )\n+\n def _reverse_transform(self, data):\n \"\"\"Generate new data using the provided ``regex_format``.\n \n@@ -156,47 +187,39 @@ class RegexGenerator(BaseTransformer):\n else:\n sample_size = self.data_length\n \n- if sample_size > self.generator_size:\n- if self.enforce_uniqueness:\n- raise TransformerProcessingError(\n- f'The regex is not able to generate {sample_size} unique values. '\n- f\"Please use a different regex for column ('{self.get_input_column()}').\"\n- )\n-\n- LOGGER.info(\n- \"The data has %s rows but the regex for '%s' can only create %s unique values.\"\n- \" Some values in '%s' may be repeated.\",\n- sample_size, self.get_input_column(), self.generator_size, self.get_input_column()\n- )\n+ self._warn_not_enough_unique_values(sample_size)\n \n remaining = self.generator_size - self.generated\n- if sample_size > self.generator_size - self.generated:\n- if self.enforce_uniqueness:\n- raise TransformerProcessingError(\n- f'The regex generator is not able to generate {sample_size} new unique '\n- f'values (only {remaining} unique value left). Please use '\n- \"'reset_randomization' in order to restart the generator.\"\n- )\n-\n+ if sample_size > remaining:\n self.reset_randomization()\n remaining = self.generator_size\n \n if remaining >= sample_size:\n- reverse_transformed = np.array([\n- next(self.generator)\n- for _ in range(sample_size)\n- ], dtype=object)\n-\n+ reverse_transformed = [next(self.generator) for _ in range(sample_size)]\n self.generated += sample_size\n \n else:\n- self.generated = self.generator_size\n generated_values = list(self.generator)\n- reverse_transformed = []\n- while len(reverse_transformed) < sample_size:\n- remaining_samples = sample_size - len(reverse_transformed)\n- reverse_transformed.extend(generated_values[:remaining_samples])\n-\n- reverse_transformed = np.array(reverse_transformed, dtype=object)\n-\n- return reverse_transformed\n+ reverse_transformed = generated_values[:]\n+ self.generated = self.generator_size\n+ if self.enforce_uniqueness:\n+ try:\n+ remaining_samples = sample_size - len(reverse_transformed)\n+ start = int(generated_values[-1]) + 1\n+ reverse_transformed.extend(\n+ [str(i) for i in range(start, start + remaining_samples)])\n+\n+ except ValueError:\n+ counter = 0\n+ while len(reverse_transformed) < sample_size:\n+ remaining_samples = sample_size - len(reverse_transformed)\n+ reverse_transformed.extend(\n+ [f'{i}({counter})' for i in generated_values[:remaining_samples]])\n+ counter += 1\n+\n+ else:\n+ while len(reverse_transformed) < sample_size:\n+ remaining_samples = sample_size - len(reverse_transformed)\n+ reverse_transformed.extend(generated_values[:remaining_samples])\n+\n+ return np.array(reverse_transformed, dtype=object)\ndiff --git a/rdt/transformers/utils.py b/rdt/transformers/utils.py\nindex 240b829..4e78685 100644\n--- a/rdt/transformers/utils.py\n+++ b/rdt/transformers/utils.py\n@@ -2,8 +2,10 @@\n \n import re\n import string\n+import warnings\n \n import numpy as np\n+import pandas as pd\n \n import sre_parse # isort:skip\n \n@@ -184,3 +186,51 @@ def flatten_column_list(column_list):\n flattened.append(column)\n \n return flattened\n+\n+\n+def check_nan_in_transform(data, dtype):\n+ \"\"\"Check if there are null values in the transformed data.\n+\n+ Args:\n+ data (pd.Series or numpy.ndarray):\n+ Data that has been transformed.\n+ dtype (str):\n+ Data type of the transformed data.\n+ \"\"\"\n+ if pd.isna(data).any().any():\n+ message = (\n+ 'There are null values in the transformed data. The reversed '\n+ 'transformed data will contain null values'\n+ )\n+ is_integer = pd.api.types.is_integer_dtype(dtype)\n+ if is_integer:\n+ message += \" of type 'float'.\"\n+ else:\n+ message += '.'\n+\n+ warnings.warn(message)\n+\n+\n+def try_convert_to_dtype(data, dtype):\n+ \"\"\"Try to convert data to a given dtype.\n+\n+ Args:\n+ data (pd.Series or numpy.ndarray):\n+ Data to convert.\n+ dtype (str):\n+ Data type to convert to.\n+\n+ Returns:\n+ data:\n+ Data converted to the given dtype.\n+ \"\"\"\n+ try:\n+ data = data.astype(dtype)\n+ except ValueError as error:\n+ is_integer = pd.api.types.is_integer_dtype(dtype)\n+ if is_integer:\n+ data = data.astype(float)\n+ else:\n+ raise error\n+\n+ return data\n", "test_patch": "diff --git a/tests/integration/transformers/test_base.py b/tests/integration/transformers/test_base.py\nindex cff4869..02a4ef7 100644\n--- a/tests/integration/transformers/test_base.py\n+++ b/tests/integration/transformers/test_base.py\n@@ -136,6 +136,7 @@ def test_multi_column_transformer_same_number_of_columns_input_output():\n # Setup\n class AdditionTransformer(BaseMultiColumnTransformer):\n \"\"\"This transformer takes 3 columns and return the cumulative sum of each row.\"\"\"\n+\n def _fit(self, columns_data):\n self.output_properties = {\n f'{self.columns[0]}': {'sdtype': 'numerical'},\n@@ -188,6 +189,7 @@ def test_multi_column_transformer_less_output_than_input_columns():\n \"\"\"This transformer takes 4 columns and concatenate them into 2 columns.\n The two first and last columns are concatenated together.\n \"\"\"\n+\n def _fit(self, columns_data):\n self.name_1 = self.columns[0] + '#' + self.columns[1]\n self.name_2 = self.columns[2] + '#' + self.columns[3]\ndiff --git a/tests/integration/transformers/test_text.py b/tests/integration/transformers/test_text.py\nindex ff143d8..2111186 100644\n--- a/tests/integration/transformers/test_text.py\n+++ b/tests/integration/transformers/test_text.py\n@@ -303,3 +303,37 @@ def test_regexgenerator_with_many_possibilities():\n \n pd.testing.assert_frame_equal(transformed, expected_transformed)\n pd.testing.assert_frame_equal(reverse_transform, expected_reverse_transformed)\n+\n+\n+def test_regexgenerator_enforce_uniqueness_not_enough_values_categorical():\n+ \"\"\"Test the ``RegexGenerator`` with enforce_uniqueness=True but insufficient regex values.\"\"\"\n+ # Setup\n+ data = pd.DataFrame({\n+ 'id': [1, 2, 3, 4, 5],\n+ })\n+ instance = RegexGenerator('id_[a-b]{1}', enforce_uniqueness=True)\n+\n+ # Run\n+ transformed = instance.fit_transform(data, 'id')\n+ reverse_transform = instance.reverse_transform(transformed)\n+\n+ # Assert\n+ expected = pd.DataFrame({'id': ['id_a', 'id_b', 'id_a(0)', 'id_b(0)', 'id_a(1)']})\n+ pd.testing.assert_frame_equal(reverse_transform, expected)\n+\n+\n+def test_regexgenerator_enforce_uniqueness_not_enough_values_numerical():\n+ \"\"\"Test the ``RegexGenerator`` with enforce_uniqueness=True but insufficient regex values.\"\"\"\n+ # Setup\n+ data = pd.DataFrame({\n+ 'id': [1, 2, 3, 4, 5],\n+ })\n+ instance = RegexGenerator('[2-3]{1}', enforce_uniqueness=True)\n+\n+ # Run\n+ transformed = instance.fit_transform(data, 'id')\n+ reverse_transform = instance.reverse_transform(transformed)\n+\n+ # Assert\n+ expected = pd.DataFrame({'id': ['2', '3', '4', '5', '6']}, dtype=object)\n+ pd.testing.assert_frame_equal(reverse_transform, expected)\ndiff --git a/tests/unit/transformers/test_categorical.py b/tests/unit/transformers/test_categorical.py\nindex afd9d16..dbad53a 100644\n--- a/tests/unit/transformers/test_categorical.py\n+++ b/tests/unit/transformers/test_categorical.py\n@@ -271,7 +271,9 @@ class TestUniformEncoder:\n assert transformed.iloc[4] >= 0\n assert transformed.iloc[4] < 1\n \n- def test__reverse_transform(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ @patch('rdt.transformers.categorical.try_convert_to_dtype')\n+ def test__reverse_transform(self, mock_convert_dtype, mock_check_nan):\n \"\"\"Test the ``_reverse_transform``.\"\"\"\n # Setup\n data = pd.Series([1, 2, 3, 2, 2, 1, 3, 3, 2])\n@@ -289,12 +291,18 @@ class TestUniformEncoder:\n }\n \n transformed = pd.Series([0.12, 0.254, 0.789, 0.43, 0.56, 0.08, 0.67, 0.98, 0.36])\n+ mock_convert_dtype.return_value = pd.Series([1, 2, 3, 2, 2, 1, 3, 3, 2])\n \n # Run\n output = transformer._reverse_transform(transformed)\n \n # Asserts\n pd.testing.assert_series_equal(output, data)\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, transformed)\n+ assert mock_input_dtype == transformer.dtype\n+ mock_convert_dtype.assert_called_once()\n \n def test__reverse_transform_nans(self):\n \"\"\"Test ``_reverse_transform`` for data with NaNs.\"\"\"\n@@ -323,6 +331,25 @@ class TestUniformEncoder:\n # Asserts\n pd.testing.assert_series_equal(output, data)\n \n+ def test__reverse_transform_integer_and_nans(self):\n+ \"\"\"Test the ``reverse_transform`` method with integers and nans.\n+\n+ Test that the method correctly reverse transforms the data\n+ when the initial data is integers and the transformed data has nans.\n+ \"\"\"\n+ # Setup\n+ transformer = UniformEncoder()\n+ transformer.frequencies = {11: 0.2, 12: 0.3, 13: 0.5}\n+ transformer.intervals = {11: [0, 0.2], 12: [0.2, 0.5], 13: [0.5, 1]}\n+ transformer.dtype = np.int64\n+ data = pd.Series([0.1, 0.25, np.nan, 0.65])\n+\n+ # Run\n+ out = transformer._reverse_transform(data)\n+\n+ # Assert\n+ pd.testing.assert_series_equal(out, pd.Series([11, 12, np.nan, 13]))\n+\n \n @pytest.fixture(autouse=True)\n def _setup_caplog(caplog):\n@@ -718,7 +745,8 @@ class TestFrequencyEncoder:\n # Asserts\n assert result == 0.2745\n \n- def test__reverse_transform_series(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ def test__reverse_transform_series(self, mock_check_nan):\n \"\"\"Test reverse_transform a pandas Series\"\"\"\n # Setup\n data = pd.Series(['foo', 'bar', 'bar', 'foo', 'foo', 'tar'])\n@@ -730,6 +758,10 @@ class TestFrequencyEncoder:\n result = transformer._reverse_transform(rt_data)\n \n # Asserts\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, rt_data)\n+ assert mock_input_dtype == transformer.dtype\n expected_intervals = {\n 'foo': (\n 0,\n@@ -1123,7 +1155,8 @@ class TestFrequencyEncoder:\n np.testing.assert_array_equal(reverse_arg, data.clip(0, 1))\n assert reverse == categorical_transformer_mock._reverse_transform_by_row.return_value\n \n- def test__reverse_transform_by_row(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ def test__reverse_transform_by_row(self, mock_check_nan):\n \"\"\"Test the _reverse_transform_by_row method with numerical data.\n \n Expect that the transformed data is correctly reverse transformed.\n@@ -1156,6 +1189,10 @@ class TestFrequencyEncoder:\n reverse = transformer._reverse_transform(transformed)\n \n # Assert\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, transformed)\n+ assert mock_input_dtype == data.dtype\n pd.testing.assert_series_equal(data, reverse)\n \n \n@@ -1222,6 +1259,7 @@ class TestOneHotEncoder:\n \n # Assert\n np.testing.assert_array_equal(ohe.dummies, ['a', 2, 'c'])\n+ assert ohe.dtype == 'object'\n \n def test__fit_dummies_nans(self):\n \"\"\"Test the ``_fit`` method without nans.\n@@ -1776,11 +1814,14 @@ class TestOneHotEncoder:\n assert not ohe._dummy_encoded\n np.testing.assert_array_equal(out, expected)\n \n- def test__reverse_transform_no_nans(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ @patch('rdt.transformers.categorical.try_convert_to_dtype')\n+ def test__reverse_transform_no_nans(self, mock_convert_dtype, mock_check_nan):\n # Setup\n ohe = OneHotEncoder()\n data = pd.Series(['a', 'b', 'c'])\n ohe._fit(data)\n+ mock_convert_dtype.return_value = data\n \n # Run\n transformed = np.array([\n@@ -1793,6 +1834,11 @@ class TestOneHotEncoder:\n # Assert\n expected = pd.Series(['a', 'b', 'c'])\n pd.testing.assert_series_equal(out, expected)\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ np.testing.assert_array_equal(mock_input_data, transformed)\n+ assert mock_input_dtype == 'O'\n+ mock_convert_dtype.assert_called_once()\n \n def test__reverse_transform_nans(self):\n # Setup\n@@ -2168,7 +2214,9 @@ class TestLabelEncoder:\n # Assert\n pd.testing.assert_series_equal(out, pd.Series(['a', 'b', 'c']))\n \n- def test__reverse_transform_add_noise(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ @patch('rdt.transformers.categorical.try_convert_to_dtype')\n+ def test__reverse_transform_add_noise(self, mock_convert_dtype, mock_check_nan):\n \"\"\"Test the ``_reverse_transform`` method with ``add_noise``.\n \n Test that the method correctly reverse transforms the data\n@@ -2183,12 +2231,36 @@ class TestLabelEncoder:\n transformer = LabelEncoder(add_noise=True)\n transformer.values_to_categories = {0: 'a', 1: 'b', 2: 'c'}\n data = pd.Series([0.5, 1.0, 10.9])\n+ mock_convert_dtype.return_value = pd.Series(['a', 'b', 'c'])\n \n # Run\n out = transformer._reverse_transform(data)\n \n # Assert\n pd.testing.assert_series_equal(out, pd.Series(['a', 'b', 'c']))\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, data)\n+ assert mock_input_dtype == 'O'\n+ mock_convert_dtype.assert_called_once()\n+\n+ def test__reverse_transform_integer_and_nans(self):\n+ \"\"\"Test the ``reverse_transform`` method with integers and nans.\n+\n+ Test that the method correctly reverse transforms the data\n+ when the initial data is integers and the transformed data has nans.\n+ \"\"\"\n+ # Setup\n+ transformer = LabelEncoder()\n+ transformer.values_to_categories = {0: 11, 1: 12, 2: 13}\n+ transformer.dtype = 'int'\n+ data = pd.Series([0, 1, np.nan])\n+\n+ # Run\n+ out = transformer._reverse_transform(data)\n+\n+ # Assert\n+ pd.testing.assert_series_equal(out, pd.Series([11, 12, np.nan]))\n \n \n class TestOrderedLabelEncoder:\n@@ -2272,6 +2344,7 @@ class TestOrderedLabelEncoder:\n transformer._fit(data)\n \n # Assert\n+ assert transformer.dtype == 'float'\n expected_values_to_categories = {0: 2, 1: 3, 2: np.nan, 3: 1}\n expected_categories_to_values = {2: 0, 3: 1, 1: 3, np.nan: 2}\n for key, value in transformer.values_to_categories.items():\ndiff --git a/tests/unit/transformers/test_text.py b/tests/unit/transformers/test_text.py\nindex ff208b2..9d1bf3b 100644\n--- a/tests/unit/transformers/test_text.py\n+++ b/tests/unit/transformers/test_text.py\n@@ -1,14 +1,11 @@\n \"\"\"Test Text Transformers.\"\"\"\n \n-import re\n from string import ascii_uppercase\n from unittest.mock import Mock, patch\n \n import numpy as np\n import pandas as pd\n-import pytest\n \n-from rdt.errors import TransformerProcessingError\n from rdt.transformers.text import IDGenerator, RegexGenerator\n \n \n@@ -428,23 +425,33 @@ class TestRegexGenerator:\n np.testing.assert_array_equal(result, expected_result)\n assert instance.generated == 4\n \n- def test__reverse_transform_not_enough_unique_values(self):\n- \"\"\"Test the ``_reverse_transform`` method.\n+ @patch('rdt.transformers.text.warnings')\n+ def test__reverse_transform_not_enough_unique_values_enforce_uniqueness(self, mock_warnings):\n+ \"\"\"Test it when there are not enough unique values to generate.\"\"\"\n+ # Setup\n+ instance = RegexGenerator('[A-E]', enforce_uniqueness=True)\n+ instance.data_length = 6\n+ generator = AsciiGenerator(5)\n+ instance.generator = generator\n+ instance.generator_size = 5\n+ instance.generated = 0\n+ instance.columns = ['a']\n+ columns_data = pd.Series()\n \n- Validate that the ``_reverse_transform`` method calls the ``strings_from_regex``\n- function using the ``instance.regex_format`` and then generates the\n- ``instance.data_length`` number of data.\n+ # Run\n+ out = instance._reverse_transform(columns_data)\n \n- Setup:\n- - Initialize a ``RegexGenerator`` instance with ``enforce_uniqueness`` to ``True``.\n- - Set ``data_length`` to 6.\n- - Initialize a generator.\n+ # Assert\n+ mock_warnings.warn.assert_called_once_with(\n+ \"The regex for 'a' can only generate 5 \"\n+ 'unique values. Additional values may not exactly follow the provided regex.'\n+ )\n+ np.testing.assert_array_equal(out, np.array(['A', 'B', 'C', 'D', 'E', 'A(0)']))\n \n- Side Effects:\n- - An error is being raised as not enough unique values can be generated.\n- \"\"\"\n+ def test__reverse_transform_not_enough_unique_values(self):\n+ \"\"\"Test it when there are not enough unique values to generate.\"\"\"\n # Setup\n- instance = RegexGenerator('[A-Z]', enforce_uniqueness=True)\n+ instance = RegexGenerator('[A-E]', enforce_uniqueness=False)\n instance.data_length = 6\n generator = AsciiGenerator(5)\n instance.generator = generator\n@@ -453,21 +460,38 @@ class TestRegexGenerator:\n instance.columns = ['a']\n columns_data = pd.Series()\n \n+ # Run\n+ out = instance._reverse_transform(columns_data)\n+\n # Assert\n- error_msg = re.escape(\n- 'The regex is not able to generate 6 unique values. Please use a different regex '\n- \"for column ('a').\"\n- )\n- with pytest.raises(TransformerProcessingError, match=error_msg):\n- instance._reverse_transform(columns_data)\n+ np.testing.assert_array_equal(out, np.array(['A', 'B', 'C', 'D', 'E', 'A']))\n+\n+ @patch('rdt.transformers.text.warnings')\n+ def test__reverse_transform_not_enough_unique_values_numerical(self, mock_warnings):\n+ \"\"\"Test it when there are not enough unique values to generate.\"\"\"\n+ # Setup\n+ instance = RegexGenerator('[1-3]', enforce_uniqueness=True)\n+ instance.data_length = 6\n+ generator = AsciiGenerator(5)\n+ instance.generator = generator\n+ instance.generator_size = 3\n+ instance.generated = 0\n+ instance.columns = ['a']\n+ columns_data = pd.Series()\n \n- def test__reverse_transform_enforce_uniqueness_not_enough_remaining(self):\n- \"\"\"Test the case when ``_reverse_transform`` can't generate enough new values.\n+ # Run\n+ out = instance._reverse_transform(columns_data)\n \n- Validate that an error is being raised stating that not enough new values can be\n- generated and that the user can use ``reset_randomization`` in order to restart the\n- generator.\n- \"\"\"\n+ # Assert\n+ mock_warnings.warn.assert_called_once_with(\n+ \"The regex for 'a' can only generate 3 \"\n+ 'unique values. Additional values may not exactly follow the provided regex.'\n+ )\n+ np.testing.assert_array_equal(out, np.array(['1', '2', '3', '4', '5', '6']))\n+\n+ @patch('rdt.transformers.text.warnings')\n+ def test__reverse_transform_enforce_uniqueness_not_enough_remaining(self, mock_warnings):\n+ \"\"\"Test the case when there are not enough unique values remaining.\"\"\"\n # Setup\n instance = RegexGenerator('[A-Z]', enforce_uniqueness=True)\n instance.data_length = 6\n@@ -478,13 +502,15 @@ class TestRegexGenerator:\n instance.columns = ['a']\n columns_data = pd.Series()\n \n+ # Run\n+ out = instance._reverse_transform(columns_data)\n+\n # Assert\n- error_msg = re.escape(\n- 'The regex generator is not able to generate 6 new unique values (only 1 unique '\n- \"value left). Please use 'reset_randomization' in order to restart the generator.\"\n+ mock_warnings.warn.assert_called_once_with(\n+ 'The regex generator is not able to generate 6 new unique '\n+ 'values (only 1 unique values left).'\n )\n- with pytest.raises(TransformerProcessingError, match=error_msg):\n- instance._reverse_transform(columns_data)\n+ np.testing.assert_array_equal(out, np.array(['A', 'B', 'C', 'D', 'E', 'F']))\n \n @patch('rdt.transformers.text.LOGGER')\n def test__reverse_transform_info_message(self, mock_logger):\ndiff --git a/tests/unit/transformers/test_utils.py b/tests/unit/transformers/test_utils.py\nindex 475a32d..d902023 100644\n--- a/tests/unit/transformers/test_utils.py\n+++ b/tests/unit/transformers/test_utils.py\n@@ -1,7 +1,13 @@\n import sre_parse\n from sre_constants import MAXREPEAT\n \n-from rdt.transformers.utils import _any, _max_repeat, flatten_column_list, strings_from_regex\n+import numpy as np\n+import pandas as pd\n+import pytest\n+\n+from rdt.transformers.utils import (\n+ _any, _max_repeat, check_nan_in_transform, flatten_column_list, strings_from_regex,\n+ try_convert_to_dtype)\n \n \n def test_strings_from_regex_literal():\n@@ -66,3 +72,58 @@ def test_flatten_column_list():\n # Assert\n expected_flattened_list = ['column1', 'column2', 'column3', 'column4', 'column5', 'column6']\n assert flattened_list == expected_flattened_list\n+\n+\n+def test_check_nan_in_transform():\n+ \"\"\"Test ``check_nan_in_transform`` method.\n+\n+ If there nan in the data, a warning should be raised.\n+ If the data was integer, it should be converted to float.\n+ \"\"\"\n+ # Setup\n+ transformed = pd.Series([0.1026, 0.1651, np.nan, 0.3116, 0.6546, 0.8541, 0.7041])\n+ data_without_nans = pd.DataFrame({\n+ 'col 1': [1, 2, 3],\n+ 'col 2': [4, 5, 6],\n+ })\n+\n+ # Run and Assert\n+ check_nan_in_transform(data_without_nans, 'float')\n+ expected_message = (\n+ 'There are null values in the transformed data. The reversed '\n+ 'transformed data will contain null values'\n+ )\n+ expected_message_object = expected_message + '.'\n+ expected_message_integer = expected_message + \" of type 'float'.\"\n+ with pytest.warns(UserWarning, match=expected_message_object):\n+ check_nan_in_transform(transformed, 'object')\n+\n+ with pytest.warns(UserWarning, match=expected_message_integer):\n+ check_nan_in_transform(transformed, 'int')\n+\n+\n+def test_try_convert_to_dtype():\n+ \"\"\"Test ``try_convert_to_dtype`` method.\n+\n+ If the data can be converted to the specified dtype, it should be converted.\n+ If the data cannot be converted, a ValueError should be raised.\n+ Should allow to convert integer with NaNs to float.\n+ \"\"\"\n+ # Setup\n+ data_int_with_nan = pd.Series([1.0, 2.0, np.nan, 4.0, 5.0])\n+ data_not_convertible = pd.Series(['a', 'b', 'c', 'd', 'e'])\n+\n+ # Run\n+ output_convertibe = try_convert_to_dtype(data_int_with_nan, 'str')\n+ output_int_with_nan = try_convert_to_dtype(data_int_with_nan, 'int')\n+ with pytest.raises(ValueError, match=\"could not convert string to float: 'a'\"):\n+ try_convert_to_dtype(data_not_convertible, 'int')\n+\n+ with pytest.raises(ValueError, match=\"could not convert string to float: 'a'\"):\n+ try_convert_to_dtype(data_not_convertible, 'float')\n+\n+ # Assert\n+ expected_data_with_nan = pd.Series([1, 2, np.nan, 4, 5])\n+ expected_data_convertibe = pd.Series(['1.0', '2.0', 'nan', '4.0', '5.0'])\n+ pd.testing.assert_series_equal(output_int_with_nan, expected_data_with_nan)\n+ pd.testing.assert_series_equal(output_convertibe, expected_data_convertibe)\n", "FAIL_TO_PASS": ["tests/integration/transformers/test_base.py::test_dummy_transformer_series_output", "tests/integration/transformers/test_base.py::test_dummy_transformer_dataframe_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_same_number_of_columns_input_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_less_output_than_input_columns", "tests/integration/transformers/test_base.py::test_multi_column_transformer_more_output_than_input_columns", "tests/integration/transformers/test_text.py::TestIDGenerator::test_end_to_end", "tests/integration/transformers/test_text.py::test_regexgenerator", "tests/integration/transformers/test_text.py::test_regexgenerator_with_custom_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_with_nans", "tests/integration/transformers/test_text.py::test_regexgenerator_data_length_bigger_than_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_input_data_bigger_than_data_length", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times_enforce_uniqueness", "tests/integration/transformers/test_text.py::test_regexgenerator_pickled", "tests/integration/transformers/test_text.py::test_regexgenerator_with_many_possibilities", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_categorical", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_float_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_nonstring_object_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info_nan", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform_error", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___setstate__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__fit_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_false", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_series", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_category_from_start", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_empty_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_nested_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_list_of_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_pandas_series", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_encoded", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column_filled_with_ones", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_1d", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_unseen_categories", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_clips_values", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___add_noise_true", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___init__", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__with_parameters", "tests/unit/transformers/test_text.py::TestIDGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestIDGenerator::test__fit", "tests/unit/transformers/test_text.py::TestIDGenerator::test__transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform_with_everything", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___getstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__generated_and_generator_size", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__custom", "tests/unit/transformers/test_text.py::TestRegexGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__fit", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__transform", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_bigger_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_smaller_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_of_input_data", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_enforce_uniqueness", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_numerical", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_enforce_uniqueness_not_enough_remaining", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message", "tests/unit/transformers/test_utils.py::test_strings_from_regex_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_digit", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_digit", "tests/unit/transformers/test_utils.py::test__any", "tests/unit/transformers/test_utils.py::test___max_repeat", "tests/unit/transformers/test_utils.py::test_strings_from_regex_very_large_regex", "tests/unit/transformers/test_utils.py::test_flatten_column_list", "tests/unit/transformers/test_utils.py::test_check_nan_in_transform", "tests/unit/transformers/test_utils.py::test_try_convert_to_dtype"]}], "all_FAIL_TO_PASS": ["tests/integration/transformers/test_base.py::test_dummy_transformer_series_output", "tests/integration/transformers/test_base.py::test_dummy_transformer_dataframe_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_same_number_of_columns_input_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_less_output_than_input_columns", "tests/integration/transformers/test_base.py::test_multi_column_transformer_more_output_than_input_columns", "tests/integration/transformers/test_text.py::TestIDGenerator::test_end_to_end", "tests/integration/transformers/test_text.py::test_regexgenerator", "tests/integration/transformers/test_text.py::test_regexgenerator_with_custom_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_with_nans", "tests/integration/transformers/test_text.py::test_regexgenerator_data_length_bigger_than_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_input_data_bigger_than_data_length", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times_enforce_uniqueness", "tests/integration/transformers/test_text.py::test_regexgenerator_pickled", "tests/integration/transformers/test_text.py::test_regexgenerator_with_many_possibilities", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_categorical", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_float_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_nonstring_object_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info_nan", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform_error", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___setstate__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__fit_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_false", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_series", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_category_from_start", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_empty_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_nested_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_list_of_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_pandas_series", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_encoded", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column_filled_with_ones", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_1d", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_unseen_categories", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_clips_values", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___add_noise_true", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___init__", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__with_parameters", "tests/unit/transformers/test_text.py::TestIDGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestIDGenerator::test__fit", "tests/unit/transformers/test_text.py::TestIDGenerator::test__transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform_with_everything", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___getstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__generated_and_generator_size", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__custom", "tests/unit/transformers/test_text.py::TestRegexGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__fit", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__transform", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_bigger_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_smaller_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_of_input_data", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_enforce_uniqueness", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_numerical", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_enforce_uniqueness_not_enough_remaining", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message", "tests/unit/transformers/test_utils.py::test_strings_from_regex_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_digit", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_digit", "tests/unit/transformers/test_utils.py::test__any", "tests/unit/transformers/test_utils.py::test___max_repeat", "tests/unit/transformers/test_utils.py::test_strings_from_regex_very_large_regex", "tests/unit/transformers/test_utils.py::test_flatten_column_list", "tests/unit/transformers/test_utils.py::test_check_nan_in_transform", "tests/unit/transformers/test_utils.py::test_try_convert_to_dtype"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "robotpy__cxxheaderparser-108_x1", "level": 1, "source": "swerebenchv2", "repo": "robotpy/cxxheaderparser", "image": "swerebenchv2/robotpy-cxxheaderparser:108-5ed4baf", "base_commit": "5ed4baf63c000259f671fc86cba152f2dada98b0", "num_bugs": 1, "bugs": [{"instance_id": "robotpy__cxxheaderparser-108", "base_commit": "5ed4baf63c000259f671fc86cba152f2dada98b0", "gold_patch": "diff --git a/cxxheaderparser/parser.py b/cxxheaderparser/parser.py\nindex 8a51e81..45f7fb6 100644\n--- a/cxxheaderparser/parser.py\n+++ b/cxxheaderparser/parser.py\n@@ -719,11 +719,7 @@ class CxxParser:\n args.append(TemplateArgument(dtype, param_pack))\n else:\n # special case for sizeof...(thing)\n- if (\n- param_pack\n- and len(val.tokens) == 1\n- and val.tokens[0].value == \"sizeof\"\n- ):\n+ if param_pack and val.tokens[-1].value == \"sizeof\":\n val.tokens.append(Token(\"...\", \"ELLIPSIS\"))\n tok = self._next_token_must_be(\"(\")\n raw_toks = self._consume_balanced_tokens(tok)\n", "test_patch": "diff --git a/tests/test_template.py b/tests/test_template.py\nindex cee092d..2a13b66 100644\n--- a/tests/test_template.py\n+++ b/tests/test_template.py\n@@ -2352,3 +2352,68 @@ def test_sizeof_pack() -> None:\n ]\n )\n )\n+\n+\n+def test_deduction_sizeof_pack() -> None:\n+ content = \"\"\"\n+ template \n+ SwerveDriveKinematics(ModuleTranslation, ModuleTranslations...)\n+ -> SwerveDriveKinematics<1 + sizeof...(ModuleTranslations)>;\n+ \"\"\"\n+ data = parse_string(content, cleandoc=True)\n+\n+ assert data == ParsedData(\n+ namespace=NamespaceScope(\n+ deduction_guides=[\n+ DeductionGuide(\n+ result_type=Type(\n+ typename=PQName(\n+ segments=[\n+ NameSpecifier(\n+ name=\"SwerveDriveKinematics\",\n+ specialization=TemplateSpecialization(\n+ args=[\n+ TemplateArgument(\n+ arg=Value(\n+ tokens=[\n+ Token(value=\"1\"),\n+ Token(value=\"+\"),\n+ Token(value=\"sizeof\"),\n+ Token(value=\"...\"),\n+ Token(value=\"(\"),\n+ Token(\n+ value=\"ModuleTranslations\"\n+ ),\n+ Token(value=\")\"),\n+ ]\n+ ),\n+ param_pack=True,\n+ )\n+ ]\n+ ),\n+ )\n+ ]\n+ )\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"SwerveDriveKinematics\")]),\n+ parameters=[\n+ Parameter(\n+ type=Type(\n+ typename=PQName(\n+ segments=[NameSpecifier(name=\"ModuleTranslation\")]\n+ )\n+ )\n+ ),\n+ Parameter(\n+ type=Type(\n+ typename=PQName(\n+ segments=[NameSpecifier(name=\"ModuleTranslations\")]\n+ )\n+ ),\n+ param_pack=True,\n+ ),\n+ ],\n+ )\n+ ]\n+ )\n+ )\n", "FAIL_TO_PASS": ["tests/test_template.py::test_deduction_sizeof_pack"]}], "all_FAIL_TO_PASS": ["tests/test_template.py::test_deduction_sizeof_pack"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getmoto__moto-5853_x1", "level": 1, "source": "swerebenchv2", "repo": "getmoto/moto", "image": "swerebenchv2/getmoto-moto:5853-ba78420", "base_commit": "ba784203142a4e8a4e1c3e34987a29c159e3c231", "num_bugs": 1, "bugs": [{"instance_id": "getmoto__moto-5853", "base_commit": "ba784203142a4e8a4e1c3e34987a29c159e3c231", "gold_patch": "diff --git a/moto/dynamodb/parsing/key_condition_expression.py b/moto/dynamodb/parsing/key_condition_expression.py\nindex cb9953450..3bdbaa7e1 100644\n--- a/moto/dynamodb/parsing/key_condition_expression.py\n+++ b/moto/dynamodb/parsing/key_condition_expression.py\n@@ -1,70 +1,6 @@\n from enum import Enum\n from moto.dynamodb.exceptions import MockValidationException\n-\n-\n-class KeyConditionExpressionTokenizer:\n- \"\"\"\n- Tokenizer for a KeyConditionExpression. Should be used as an iterator.\n- The final character to be returned will be an empty string, to notify the caller that we've reached the end.\n- \"\"\"\n-\n- def __init__(self, expression):\n- self.expression = expression\n- self.token_pos = 0\n-\n- def __iter__(self):\n- self.token_pos = 0\n- return self\n-\n- def is_eof(self):\n- return self.peek() == \"\"\n-\n- def peek(self):\n- \"\"\"\n- Peek the next character without changing the position\n- \"\"\"\n- try:\n- return self.expression[self.token_pos]\n- except IndexError:\n- return \"\"\n-\n- def __next__(self):\n- \"\"\"\n- Returns the next character, or an empty string if we've reached the end of the string.\n- Calling this method again will result in a StopIterator\n- \"\"\"\n- try:\n- result = self.expression[self.token_pos]\n- self.token_pos += 1\n- return result\n- except IndexError:\n- if self.token_pos == len(self.expression):\n- self.token_pos += 1\n- return \"\"\n- raise StopIteration\n-\n- def skip_characters(self, phrase, case_sensitive=False) -> None:\n- \"\"\"\n- Skip the characters in the supplied phrase.\n- If any other character is encountered instead, this will fail.\n- If we've already reached the end of the iterator, this will fail.\n- \"\"\"\n- for ch in phrase:\n- if case_sensitive:\n- assert self.expression[self.token_pos] == ch\n- else:\n- assert self.expression[self.token_pos] in [ch.lower(), ch.upper()]\n- self.token_pos += 1\n-\n- def skip_white_space(self):\n- \"\"\"\n- Skip the any whitespace characters that are coming up\n- \"\"\"\n- try:\n- while self.peek() == \" \":\n- self.token_pos += 1\n- except IndexError:\n- pass\n+from moto.utilities.tokenizer import GenericTokenizer\n \n \n class EXPRESSION_STAGES(Enum):\n@@ -100,7 +36,7 @@ def parse_expression(\n key_name = comparison = None\n key_values = []\n results = []\n- tokenizer = KeyConditionExpressionTokenizer(key_condition_expression)\n+ tokenizer = GenericTokenizer(key_condition_expression)\n for crnt_char in tokenizer:\n if crnt_char == \" \":\n if current_stage == EXPRESSION_STAGES.INITIAL_STAGE:\ndiff --git a/moto/ses/models.py b/moto/ses/models.py\nindex 7227abe12..27e1e5fef 100644\n--- a/moto/ses/models.py\n+++ b/moto/ses/models.py\n@@ -1,4 +1,3 @@\n-import re\n import json\n import email\n import datetime\n@@ -23,9 +22,9 @@ from .exceptions import (\n RuleSetNameAlreadyExists,\n RuleSetDoesNotExist,\n RuleAlreadyExists,\n- MissingRenderingAttributeException,\n ConfigurationSetAlreadyExists,\n )\n+from .template import parse_template\n from .utils import get_random_message_id, is_valid_address\n from .feedback import COMMON_MAIL, BOUNCE, COMPLAINT, DELIVERY\n \n@@ -106,17 +105,6 @@ class SESQuota(BaseModel):\n return self.sent\n \n \n-def are_all_variables_present(template, template_data):\n- subject_part = template[\"subject_part\"]\n- text_part = template[\"text_part\"]\n- html_part = template[\"html_part\"]\n-\n- for var in re.findall(\"{{(.+?)}}\", subject_part + text_part + html_part):\n- if not template_data.get(var):\n- return var, False\n- return None, True\n-\n-\n class SESBackend(BaseBackend):\n \"\"\"\n Responsible for mocking calls to SES.\n@@ -469,18 +457,13 @@ class SESBackend(BaseBackend):\n \"Template rendering data is invalid\"\n )\n \n- var, are_variables_present = are_all_variables_present(template, template_data)\n- if not are_variables_present:\n- raise MissingRenderingAttributeException(var)\n-\n subject_part = template[\"subject_part\"]\n text_part = template[\"text_part\"]\n html_part = template[\"html_part\"]\n \n- for key, value in template_data.items():\n- subject_part = str.replace(str(subject_part), \"{{\" + key + \"}}\", value)\n- text_part = str.replace(str(text_part), \"{{\" + key + \"}}\", value)\n- html_part = str.replace(str(html_part), \"{{\" + key + \"}}\", value)\n+ subject_part = parse_template(str(subject_part), template_data)\n+ text_part = parse_template(str(text_part), template_data)\n+ html_part = parse_template(str(html_part), template_data)\n \n email_obj = MIMEMultipart(\"alternative\")\n \ndiff --git a/moto/ses/template.py b/moto/ses/template.py\nnew file mode 100644\nindex 000000000..ec34cd19c\n--- /dev/null\n+++ b/moto/ses/template.py\n@@ -0,0 +1,45 @@\n+from .exceptions import MissingRenderingAttributeException\n+from moto.utilities.tokenizer import GenericTokenizer\n+\n+\n+def parse_template(template, template_data, tokenizer=None, until=None):\n+ tokenizer = tokenizer or GenericTokenizer(template)\n+ state = \"\"\n+ parsed = \"\"\n+ var_name = \"\"\n+ for char in tokenizer:\n+ if until is not None and (char + tokenizer.peek(len(until) - 1)) == until:\n+ return parsed\n+ if char == \"{\":\n+ tokenizer.skip_characters(\"{\")\n+ tokenizer.skip_white_space()\n+ if tokenizer.peek() == \"#\":\n+ state = \"LOOP\"\n+ tokenizer.skip_characters(\"#each\")\n+ tokenizer.skip_white_space()\n+ else:\n+ state = \"VAR\"\n+ continue\n+ if char == \"}\":\n+ if state in [\"LOOP\", \"VAR\"]:\n+ tokenizer.skip_characters(\"}\")\n+ if state == \"VAR\":\n+ if template_data.get(var_name) is None:\n+ raise MissingRenderingAttributeException(var_name)\n+ parsed += template_data.get(var_name)\n+ else:\n+ current_position = tokenizer.token_pos\n+ for item in template_data.get(var_name, []):\n+ tokenizer.token_pos = current_position\n+ parsed += parse_template(\n+ template, item, tokenizer, until=\"{{/each}}\"\n+ )\n+ tokenizer.skip_characters(\"{/each}}\")\n+ var_name = \"\"\n+ state = \"\"\n+ continue\n+ if state in [\"LOOP\", \"VAR\"]:\n+ var_name += char\n+ continue\n+ parsed += char\n+ return parsed\ndiff --git a/moto/utilities/tokenizer.py b/moto/utilities/tokenizer.py\nnew file mode 100644\nindex 000000000..a6e76dc7f\n--- /dev/null\n+++ b/moto/utilities/tokenizer.py\n@@ -0,0 +1,62 @@\n+class GenericTokenizer:\n+ \"\"\"\n+ Tokenizer for a KeyConditionExpression. Should be used as an iterator.\n+ The final character to be returned will be an empty string, to notify the caller that we've reached the end.\n+ \"\"\"\n+\n+ def __init__(self, expression):\n+ self.expression = expression\n+ self.token_pos = 0\n+\n+ def __iter__(self):\n+ return self\n+\n+ def is_eof(self):\n+ return self.peek() == \"\"\n+\n+ def peek(self, length=1):\n+ \"\"\"\n+ Peek the next character without changing the position\n+ \"\"\"\n+ try:\n+ return self.expression[self.token_pos : self.token_pos + length]\n+ except IndexError:\n+ return \"\"\n+\n+ def __next__(self):\n+ \"\"\"\n+ Returns the next character, or an empty string if we've reached the end of the string.\n+ Calling this method again will result in a StopIterator\n+ \"\"\"\n+ try:\n+ result = self.expression[self.token_pos]\n+ self.token_pos += 1\n+ return result\n+ except IndexError:\n+ if self.token_pos == len(self.expression):\n+ self.token_pos += 1\n+ return \"\"\n+ raise StopIteration\n+\n+ def skip_characters(self, phrase, case_sensitive=False) -> None:\n+ \"\"\"\n+ Skip the characters in the supplied phrase.\n+ If any other character is encountered instead, this will fail.\n+ If we've already reached the end of the iterator, this will fail.\n+ \"\"\"\n+ for ch in phrase:\n+ if case_sensitive:\n+ assert self.expression[self.token_pos] == ch\n+ else:\n+ assert self.expression[self.token_pos] in [ch.lower(), ch.upper()]\n+ self.token_pos += 1\n+\n+ def skip_white_space(self):\n+ \"\"\"\n+ Skip any whitespace characters that are coming up\n+ \"\"\"\n+ try:\n+ while self.peek() == \" \":\n+ self.token_pos += 1\n+ except IndexError:\n+ pass\n", "test_patch": "diff --git a/tests/test_ses/test_ses_boto3.py b/tests/test_ses/test_ses_boto3.py\nindex c2c27cdb9..0ca55c7f8 100644\n--- a/tests/test_ses/test_ses_boto3.py\n+++ b/tests/test_ses/test_ses_boto3.py\n@@ -1268,6 +1268,35 @@ def test_render_template():\n )\n \n \n+@mock_ses\n+def test_render_template__with_foreach():\n+ conn = boto3.client(\"ses\", region_name=\"us-east-1\")\n+\n+ kwargs = dict(\n+ TemplateName=\"MTT\",\n+ TemplateData=json.dumps(\n+ {\n+ \"items\": [\n+ {\"type\": \"dog\", \"name\": \"bobby\"},\n+ {\"type\": \"cat\", \"name\": \"pedro\"},\n+ ]\n+ }\n+ ),\n+ )\n+\n+ conn.create_template(\n+ Template={\n+ \"TemplateName\": \"MTT\",\n+ \"SubjectPart\": \"..\",\n+ \"TextPart\": \"..\",\n+ \"HtmlPart\": \"{{#each items}} {{name}} is a {{type}}, {{/each}}\",\n+ }\n+ )\n+ result = conn.test_render_template(**kwargs)\n+ result[\"RenderedTemplate\"].should.contain(\"bobby is a dog\")\n+ result[\"RenderedTemplate\"].should.contain(\"pedro is a cat\")\n+\n+\n @mock_ses\n def test_update_ses_template():\n conn = boto3.client(\"ses\", region_name=\"us-east-1\")\ndiff --git a/tests/test_ses/test_templating.py b/tests/test_ses/test_templating.py\nnew file mode 100644\nindex 000000000..0883013b0\n--- /dev/null\n+++ b/tests/test_ses/test_templating.py\n@@ -0,0 +1,26 @@\n+from moto.ses.template import parse_template\n+import sure # noqa # pylint: disable=unused-import\n+\n+\n+def test_template_without_args():\n+ parse_template(\"some template\", template_data={}).should.equal(\"some template\")\n+\n+\n+def test_template_with_simple_arg():\n+ t = \"Dear {{name}},\"\n+ parse_template(t, template_data={\"name\": \"John\"}).should.equal(\"Dear John,\")\n+\n+\n+def test_template_with_foreach():\n+ t = \"List:{{#each l}} - {{obj}}{{/each}} and other things\"\n+ kwargs = {\"l\": [{\"obj\": \"it1\"}, {\"obj\": \"it2\"}]}\n+ parse_template(t, kwargs).should.equal(\"List: - it1 - it2 and other things\")\n+\n+\n+def test_template_with_multiple_foreach():\n+ t = \"{{#each l}} - {{obj}}{{/each}} and list 2 {{#each l2}} {{o1}} {{o2}} {{/each}}\"\n+ kwargs = {\n+ \"l\": [{\"obj\": \"it1\"}, {\"obj\": \"it2\"}],\n+ \"l2\": [{\"o1\": \"ob1\", \"o2\": \"ob2\"}, {\"o1\": \"oc1\", \"o2\": \"oc2\"}],\n+ }\n+ parse_template(t, kwargs).should.equal(\" - it1 - it2 and list 2 ob1 ob2 oc1 oc2 \")\n", "FAIL_TO_PASS": ["tests/test_ses/test_ses_boto3.py::test_verify_email_identity", "tests/test_ses/test_ses_boto3.py::test_verify_email_identity_idempotency", "tests/test_ses/test_ses_boto3.py::test_verify_email_address", "tests/test_ses/test_ses_boto3.py::test_domain_verify", "tests/test_ses/test_ses_boto3.py::test_delete_identity", "tests/test_ses/test_ses_boto3.py::test_send_email", "tests/test_ses/test_ses_boto3.py::test_send_email_when_verify_source", "tests/test_ses/test_ses_boto3.py::test_send_unverified_email_with_chevrons", "tests/test_ses/test_ses_boto3.py::test_send_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_bulk_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_html_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_validate_domain", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source_or_from", "tests/test_ses/test_ses_boto3.py::test_send_email_notification_with_encoded_sender", "tests/test_ses/test_ses_boto3.py::test_create_configuration_set", "tests/test_ses/test_ses_boto3.py::test_describe_configuration_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set_with_rules", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule_actions", "tests/test_ses/test_ses_boto3.py::test_create_ses_template", "tests/test_ses/test_ses_boto3.py::test_render_template", "tests/test_ses/test_ses_boto3.py::test_render_template__with_foreach", "tests/test_ses/test_ses_boto3.py::test_update_ses_template", "tests/test_ses/test_ses_boto3.py::test_domains_are_case_insensitive", "tests/test_ses/test_ses_boto3.py::test_get_send_statistics", "tests/test_ses/test_ses_boto3.py::test_set_identity_mail_from_domain", "tests/test_ses/test_ses_boto3.py::test_get_identity_mail_from_domain_attributes", "tests/test_ses/test_ses_boto3.py::test_get_identity_verification_attributes", "tests/test_ses/test_templating.py::test_template_without_args", "tests/test_ses/test_templating.py::test_template_with_simple_arg", "tests/test_ses/test_templating.py::test_template_with_foreach", "tests/test_ses/test_templating.py::test_template_with_multiple_foreach"]}], "all_FAIL_TO_PASS": ["tests/test_ses/test_ses_boto3.py::test_verify_email_identity", "tests/test_ses/test_ses_boto3.py::test_verify_email_identity_idempotency", "tests/test_ses/test_ses_boto3.py::test_verify_email_address", "tests/test_ses/test_ses_boto3.py::test_domain_verify", "tests/test_ses/test_ses_boto3.py::test_delete_identity", "tests/test_ses/test_ses_boto3.py::test_send_email", "tests/test_ses/test_ses_boto3.py::test_send_email_when_verify_source", "tests/test_ses/test_ses_boto3.py::test_send_unverified_email_with_chevrons", "tests/test_ses/test_ses_boto3.py::test_send_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_bulk_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_html_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_validate_domain", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source_or_from", "tests/test_ses/test_ses_boto3.py::test_send_email_notification_with_encoded_sender", "tests/test_ses/test_ses_boto3.py::test_create_configuration_set", "tests/test_ses/test_ses_boto3.py::test_describe_configuration_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set_with_rules", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule_actions", "tests/test_ses/test_ses_boto3.py::test_create_ses_template", "tests/test_ses/test_ses_boto3.py::test_render_template", "tests/test_ses/test_ses_boto3.py::test_render_template__with_foreach", "tests/test_ses/test_ses_boto3.py::test_update_ses_template", "tests/test_ses/test_ses_boto3.py::test_domains_are_case_insensitive", "tests/test_ses/test_ses_boto3.py::test_get_send_statistics", "tests/test_ses/test_ses_boto3.py::test_set_identity_mail_from_domain", "tests/test_ses/test_ses_boto3.py::test_get_identity_mail_from_domain_attributes", "tests/test_ses/test_ses_boto3.py::test_get_identity_verification_attributes", "tests/test_ses/test_templating.py::test_template_without_args", "tests/test_ses/test_templating.py::test_template_with_simple_arg", "tests/test_ses/test_templating.py::test_template_with_foreach", "tests/test_ses/test_templating.py::test_template_with_multiple_foreach"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pycqa__pyflakes-729_x1", "level": 1, "source": "swerebenchv2", "repo": "PyCQA/pyflakes", "image": "swerebenchv2/pycqa-pyflakes:729-7d6479e", "base_commit": "7d6479e46f8f3e9607c9ef7975cc892db023d413", "num_bugs": 1, "bugs": [{"instance_id": "pycqa__pyflakes-729", "base_commit": "7d6479e46f8f3e9607c9ef7975cc892db023d413", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex ae15621..56fc3ca 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -2265,7 +2265,6 @@ class Checker:\n self.scope[node.name] = prev_definition\n \n def ANNASSIGN(self, node):\n- self.handleNode(node.target, node)\n self.handleAnnotation(node.annotation, node)\n # If the assignment has value, handle the *value* now.\n if node.value:\n@@ -2274,6 +2273,7 @@ class Checker:\n self.handleAnnotation(node.value, node)\n else:\n self.handleNode(node.value, node)\n+ self.handleNode(node.target, node)\n \n def COMPARE(self, node):\n left = node.left\n", "test_patch": "diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py\nindex 3775cd3..d881205 100644\n--- a/pyflakes/test/test_type_annotations.py\n+++ b/pyflakes/test/test_type_annotations.py\n@@ -298,6 +298,11 @@ class TestTypeAnnotations(TestCase):\n a: 'a: \"A\"'\n ''', m.ForwardAnnotationSyntaxError)\n \n+ def test_variable_annotation_references_self_name_undefined(self):\n+ self.flakes(\"\"\"\n+ x: int = x\n+ \"\"\", m.UndefinedName)\n+\n def test_TypeAlias_annotations(self):\n self.flakes(\"\"\"\n from typing_extensions import TypeAlias\n", "FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "amaranth-lang__amaranth-1328_x1", "level": 1, "source": "swerebenchv2", "repo": "amaranth-lang/amaranth", "image": "swerebenchv2/amaranth-lang-amaranth:1328-16f187e", "base_commit": "16f187e7fa128fe013ea347c408772206583cb63", "num_bugs": 1, "bugs": [{"instance_id": "amaranth-lang__amaranth-1328", "base_commit": "16f187e7fa128fe013ea347c408772206583cb63", "gold_patch": "diff --git a/amaranth/sim/_base.py b/amaranth/sim/_base.py\nindex 046f690..cf0ca61 100644\n--- a/amaranth/sim/_base.py\n+++ b/amaranth/sim/_base.py\n@@ -19,6 +19,7 @@ class BaseSignalState:\n __slots__ = ()\n \n signal = NotImplemented\n+ is_comb = NotImplemented\n \n curr = NotImplemented\n next = NotImplemented\ndiff --git a/amaranth/sim/_pyeval.py b/amaranth/sim/_pyeval.py\nindex 10ecb64..be72cc3 100644\n--- a/amaranth/sim/_pyeval.py\n+++ b/amaranth/sim/_pyeval.py\n@@ -1,5 +1,6 @@\n from amaranth.hdl._ast import *\n from amaranth.hdl._mem import MemoryData\n+from amaranth.hdl._ir import DriverConflict\n \n \n def _eval_matches(test, patterns):\n@@ -165,6 +166,8 @@ def _eval_assign_inner(sim, lhs, lhs_start, rhs, rhs_len):\n if lhs_start >= len(lhs):\n return\n slot = sim.get_signal(lhs)\n+ if sim.slots[slot].is_comb:\n+ raise DriverConflict(\"Combinationally driven signals cannot be overriden by testbenches\")\n value = sim.slots[slot].next\n mask = (1 << lhs_stop) - (1 << lhs_start)\n value &= ~mask\ndiff --git a/amaranth/sim/_pyrtl.py b/amaranth/sim/_pyrtl.py\nindex 0483dfa..bbf75ea 100644\n--- a/amaranth/sim/_pyrtl.py\n+++ b/amaranth/sim/_pyrtl.py\n@@ -479,6 +479,7 @@ class _FragmentCompiler:\n if domain_name == \"comb\":\n for signal in domain_signals:\n signal_index = self.state.get_signal(signal)\n+ self.state.slots[signal_index].is_comb = True\n emitter.append(f\"next_{signal_index} = {signal.init}\")\n \n inputs = SignalSet()\ndiff --git a/amaranth/sim/pysim.py b/amaranth/sim/pysim.py\nindex 298fe99..dc8098d 100644\n--- a/amaranth/sim/pysim.py\n+++ b/amaranth/sim/pysim.py\n@@ -303,10 +303,11 @@ class _Timeline:\n \n \n class _PySignalState(BaseSignalState):\n- __slots__ = (\"signal\", \"curr\", \"next\", \"waiters\", \"pending\")\n+ __slots__ = (\"signal\", \"is_comb\", \"curr\", \"next\", \"waiters\", \"pending\")\n \n def __init__(self, signal, pending):\n self.signal = signal\n+ self.is_comb = False\n self.pending = pending\n self.waiters = {}\n self.curr = self.next = signal.init\n", "test_patch": "diff --git a/tests/test_sim.py b/tests/test_sim.py\nindex 6e43011..8dad613 100644\n--- a/tests/test_sim.py\n+++ b/tests/test_sim.py\n@@ -1395,3 +1395,15 @@ class SimulatorRegressionTestCase(FHDLTestCase):\n self.assertEqual((yield C(0b1111, 4) ^ ~C(1, 1)), 0b1111)\n sim.add_testbench(process)\n sim.run()\n+\n+ def test_comb_assign(self):\n+ c = Signal()\n+ m = Module()\n+ m.d.comb += c.eq(1)\n+ sim = Simulator(m)\n+ def testbench():\n+ with self.assertRaisesRegex(DriverConflict,\n+ r\"^Combinationally driven signals cannot be overriden by testbenches$\"):\n+ yield c.eq(0)\n+ sim.add_testbench(testbench)\n+ sim.run()\n", "FAIL_TO_PASS": ["tests/test_sim.py::SimulatorRegressionTestCase::test_comb_assign"]}], "all_FAIL_TO_PASS": ["tests/test_sim.py::SimulatorRegressionTestCase::test_comb_assign"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "meltano__sdk-1864_x1", "level": 1, "source": "swerebenchv2", "repo": "meltano/sdk", "image": "swerebenchv2/meltano-sdk:1864-b1b3bd2", "base_commit": "b1b3bd20f8e84a0582c6666de180f9a800086faa", "num_bugs": 1, "bugs": [{"instance_id": "meltano__sdk-1864", "base_commit": "b1b3bd20f8e84a0582c6666de180f9a800086faa", "gold_patch": "diff --git a/singer_sdk/target_base.py b/singer_sdk/target_base.py\nindex d62bbbfd..cf103883 100644\n--- a/singer_sdk/target_base.py\n+++ b/singer_sdk/target_base.py\n@@ -28,8 +28,9 @@ from singer_sdk.plugin_base import PluginBase\n if t.TYPE_CHECKING:\n from pathlib import PurePath\n \n+ from singer_sdk.connectors import SQLConnector\n from singer_sdk.mapper import PluginMapper\n- from singer_sdk.sinks import Sink\n+ from singer_sdk.sinks import Sink, SQLSink\n \n _MAX_PARALLELISM = 8\n \n@@ -48,7 +49,7 @@ class Target(PluginBase, SingerReader, metaclass=abc.ABCMeta):\n \n # Default class to use for creating new sink objects.\n # Required if `Target.get_sink_class()` is not defined.\n- default_sink_class: type[Sink] | None = None\n+ default_sink_class: type[Sink]\n \n def __init__(\n self,\n@@ -574,6 +575,23 @@ class Target(PluginBase, SingerReader, metaclass=abc.ABCMeta):\n class SQLTarget(Target):\n \"\"\"Target implementation for SQL destinations.\"\"\"\n \n+ _target_connector: SQLConnector | None = None\n+\n+ default_sink_class: type[SQLSink]\n+\n+ @property\n+ def target_connector(self) -> SQLConnector:\n+ \"\"\"The connector object.\n+\n+ Returns:\n+ The connector object.\n+ \"\"\"\n+ if self._target_connector is None:\n+ self._target_connector = self.default_sink_class.connector_class(\n+ dict(self.config),\n+ )\n+ return self._target_connector\n+\n @classproperty\n def capabilities(self) -> list[CapabilitiesEnum]:\n \"\"\"Get target capabilities.\n@@ -617,3 +635,114 @@ class SQLTarget(Target):\n super().append_builtin_config(config_jsonschema)\n \n pass\n+\n+ @final\n+ def add_sqlsink(\n+ self,\n+ stream_name: str,\n+ schema: dict,\n+ key_properties: list[str] | None = None,\n+ ) -> Sink:\n+ \"\"\"Create a sink and register it.\n+\n+ This method is internal to the SDK and should not need to be overridden.\n+\n+ Args:\n+ stream_name: Name of the stream.\n+ schema: Schema of the stream.\n+ key_properties: Primary key of the stream.\n+\n+ Returns:\n+ A new sink for the stream.\n+ \"\"\"\n+ self.logger.info(\"Initializing '%s' target sink...\", self.name)\n+ sink_class = self.get_sink_class(stream_name=stream_name)\n+ sink = sink_class(\n+ target=self,\n+ stream_name=stream_name,\n+ schema=schema,\n+ key_properties=key_properties,\n+ connector=self.target_connector,\n+ )\n+ sink.setup()\n+ self._sinks_active[stream_name] = sink\n+\n+ return sink\n+\n+ def get_sink_class(self, stream_name: str) -> type[SQLSink]:\n+ \"\"\"Get sink for a stream.\n+\n+ Developers can override this method to return a custom Sink type depending\n+ on the value of `stream_name`. Optional when `default_sink_class` is set.\n+\n+ Args:\n+ stream_name: Name of the stream.\n+\n+ Raises:\n+ ValueError: If no :class:`singer_sdk.sinks.Sink` class is defined.\n+\n+ Returns:\n+ The sink class to be used with the stream.\n+ \"\"\"\n+ if self.default_sink_class:\n+ return self.default_sink_class\n+\n+ msg = (\n+ f\"No sink class defined for '{stream_name}' and no default sink class \"\n+ \"available.\"\n+ )\n+ raise ValueError(msg)\n+\n+ def get_sink(\n+ self,\n+ stream_name: str,\n+ *,\n+ record: dict | None = None,\n+ schema: dict | None = None,\n+ key_properties: list[str] | None = None,\n+ ) -> Sink:\n+ \"\"\"Return a sink for the given stream name.\n+\n+ A new sink will be created if `schema` is provided and if either `schema` or\n+ `key_properties` has changed. If so, the old sink becomes archived and held\n+ until the next drain_all() operation.\n+\n+ Developers only need to override this method if they want to provide a different\n+ sink depending on the values within the `record` object. Otherwise, please see\n+ `default_sink_class` property and/or the `get_sink_class()` method.\n+\n+ Raises :class:`singer_sdk.exceptions.RecordsWithoutSchemaException` if sink does\n+ not exist and schema is not sent.\n+\n+ Args:\n+ stream_name: Name of the stream.\n+ record: Record being processed.\n+ schema: Stream schema.\n+ key_properties: Primary key of the stream.\n+\n+ Returns:\n+ The sink used for this target.\n+ \"\"\"\n+ _ = record # Custom implementations may use record in sink selection.\n+ if schema is None:\n+ self._assert_sink_exists(stream_name)\n+ return self._sinks_active[stream_name]\n+\n+ existing_sink = self._sinks_active.get(stream_name, None)\n+ if not existing_sink:\n+ return self.add_sqlsink(stream_name, schema, key_properties)\n+\n+ if (\n+ existing_sink.schema != schema\n+ or existing_sink.key_properties != key_properties\n+ ):\n+ self.logger.info(\n+ \"Schema or key properties for '%s' stream have changed. \"\n+ \"Initializing a new '%s' sink...\",\n+ stream_name,\n+ stream_name,\n+ )\n+ self._sinks_to_clear.append(self._sinks_active.pop(stream_name))\n+ return self.add_sqlsink(stream_name, schema, key_properties)\n+\n+ return existing_sink\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 25319c01..cf64e28d 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -10,9 +10,10 @@ import typing as t\n import pytest\n from sqlalchemy import __version__ as sqlalchemy_version\n \n+from singer_sdk import SQLConnector\n from singer_sdk import typing as th\n-from singer_sdk.sinks import BatchSink\n-from singer_sdk.target_base import Target\n+from singer_sdk.sinks import BatchSink, SQLSink\n+from singer_sdk.target_base import SQLTarget, Target\n \n if t.TYPE_CHECKING:\n from _pytest.config import Config\n@@ -116,3 +117,63 @@ class TargetMock(Target):\n \"\"\"Emit the stream's latest state.\"\"\"\n super()._write_state_message(state)\n self.state_messages_written.append(state)\n+\n+\n+class SQLConnectorMock(SQLConnector):\n+ \"\"\"A Mock SQLConnector class.\"\"\"\n+\n+\n+class SQLSinkMock(SQLSink):\n+ \"\"\"A mock Sink class.\"\"\"\n+\n+ name = \"sql-sink-mock\"\n+ connector_class = SQLConnectorMock\n+\n+ def __init__(\n+ self,\n+ target: SQLTargetMock,\n+ stream_name: str,\n+ schema: dict,\n+ key_properties: list[str] | None,\n+ connector: SQLConnector | None = None,\n+ ):\n+ \"\"\"Create the Mock batch-based sink.\"\"\"\n+ self._connector: SQLConnector\n+ self._connector = connector or self.connector_class(dict(target.config))\n+ super().__init__(target, stream_name, schema, key_properties, connector)\n+ self.target = target\n+\n+ def process_record(self, record: dict, context: dict) -> None:\n+ \"\"\"Tracks the count of processed records.\"\"\"\n+ self.target.num_records_processed += 1\n+ super().process_record(record, context)\n+\n+ def process_batch(self, context: dict) -> None:\n+ \"\"\"Write to mock trackers.\"\"\"\n+ self.target.records_written.extend(context[\"records\"])\n+ self.target.num_batches_processed += 1\n+\n+ @property\n+ def key_properties(self) -> list[str]:\n+ return [key.upper() for key in super().key_properties]\n+\n+\n+class SQLTargetMock(SQLTarget):\n+ \"\"\"A mock Target class.\"\"\"\n+\n+ name = \"sql-target-mock\"\n+ config_jsonschema = th.PropertiesList().to_dict()\n+ default_sink_class = SQLSinkMock\n+\n+ def __init__(self, *args, **kwargs):\n+ \"\"\"Create the Mock target sync.\"\"\"\n+ super().__init__(*args, **kwargs)\n+ self.state_messages_written: list[dict] = []\n+ self.records_written: list[dict] = []\n+ self.num_records_processed: int = 0\n+ self.num_batches_processed: int = 0\n+\n+ def _write_state_message(self, state: dict):\n+ \"\"\"Emit the stream's latest state.\"\"\"\n+ super()._write_state_message(state)\n+ self.state_messages_written.append(state)\ndiff --git a/tests/core/test_target_base.py b/tests/core/test_target_base.py\nindex 1fd6b9a9..ee00d35e 100644\n--- a/tests/core/test_target_base.py\n+++ b/tests/core/test_target_base.py\n@@ -4,8 +4,11 @@ import copy\n \n import pytest\n \n-from singer_sdk.exceptions import MissingKeyPropertiesError\n-from tests.conftest import BatchSinkMock, TargetMock\n+from singer_sdk.exceptions import (\n+ MissingKeyPropertiesError,\n+ RecordsWithoutSchemaException,\n+)\n+from tests.conftest import BatchSinkMock, SQLSinkMock, SQLTargetMock, TargetMock\n \n \n def test_get_sink():\n@@ -53,3 +56,68 @@ def test_validate_record():\n # Test invalid record\n with pytest.raises(MissingKeyPropertiesError):\n sink._singer_validate_message({\"name\": \"test\"})\n+\n+\n+def test_sql_get_sink():\n+ input_schema_1 = {\n+ \"properties\": {\n+ \"id\": {\n+ \"type\": [\"string\", \"null\"],\n+ },\n+ \"col_ts\": {\n+ \"format\": \"date-time\",\n+ \"type\": [\"string\", \"null\"],\n+ },\n+ },\n+ }\n+ input_schema_2 = copy.deepcopy(input_schema_1)\n+ key_properties = []\n+ target = SQLTargetMock(config={\"sqlalchemy_url\": \"sqlite:///\"})\n+ sink = SQLSinkMock(\n+ target=target,\n+ stream_name=\"foo\",\n+ schema=input_schema_1,\n+ key_properties=key_properties,\n+ connector=target.target_connector,\n+ )\n+ target._sinks_active[\"foo\"] = sink\n+ sink_returned = target.get_sink(\n+ \"foo\",\n+ schema=input_schema_2,\n+ key_properties=key_properties,\n+ )\n+ assert sink_returned is sink\n+\n+\n+def test_add_sqlsink_and_get_sink():\n+ input_schema_1 = {\n+ \"properties\": {\n+ \"id\": {\n+ \"type\": [\"string\", \"null\"],\n+ },\n+ \"col_ts\": {\n+ \"format\": \"date-time\",\n+ \"type\": [\"string\", \"null\"],\n+ },\n+ },\n+ }\n+ input_schema_2 = copy.deepcopy(input_schema_1)\n+ key_properties = []\n+ target = SQLTargetMock(config={\"sqlalchemy_url\": \"sqlite:///\"})\n+ sink = target.add_sqlsink(\n+ \"foo\",\n+ schema=input_schema_2,\n+ key_properties=key_properties,\n+ )\n+\n+ sink_returned = target.get_sink(\n+ \"foo\",\n+ )\n+\n+ assert sink_returned is sink\n+\n+ # Test invalid call\n+ with pytest.raises(RecordsWithoutSchemaException):\n+ target.get_sink(\n+ \"bar\",\n+ )\n", "FAIL_TO_PASS": ["tests/core/test_target_base.py::test_sql_get_sink", "tests/core/test_target_base.py::test_add_sqlsink_and_get_sink"]}], "all_FAIL_TO_PASS": ["tests/core/test_target_base.py::test_sql_get_sink", "tests/core/test_target_base.py::test_add_sqlsink_and_get_sink"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jnothman__upsetplot-264_x1", "level": 1, "source": "swerebenchv2", "repo": "jnothman/UpSetPlot", "image": "swerebenchv2/jnothman-upsetplot:264-da64c81", "base_commit": "da64c81a12f5e6c8283e10a4f6cd7a42ccda1491", "num_bugs": 1, "bugs": [{"instance_id": "jnothman__upsetplot-264", "base_commit": "da64c81a12f5e6c8283e10a4f6cd7a42ccda1491", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex a00b4d9..37a37ef 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -8,7 +8,10 @@ What's new in version 0.9\n shading of rows in the intersection matrix, and bars in the totals plot.\n (:issue:`261` with thanks to :user:`Marcel Albus `).\n - Ability to disable totals plot with `totals_plot_elements=0`. (:issue:`246`)\n+- Ability to set totals y axis label (:issue:`243`)\n - Added ``max_subset_rank`` to get only n most populous subsets. (:issue:`253`)\n+- Added support for ``min_subset_size`` and ``max_subset_size`` specified as\n+ percentage. (:issue:`264`)\n \n What's new in version 0.8\n -------------------------\ndiff --git a/upsetplot/plotting.py b/upsetplot/plotting.py\nindex e2f50bd..3d5630f 100644\n--- a/upsetplot/plotting.py\n+++ b/upsetplot/plotting.py\n@@ -191,17 +191,27 @@ class UpSet:\n If `subset_size='sum'` or `'auto'`, then the intersection size is the\n sum of the specified field in the `data` DataFrame. If a Series, only\n None is supported and its value is summed.\n- min_subset_size : int, optional\n+ min_subset_size : int or \"number%\", optional\n Minimum size of a subset to be shown in the plot. All subsets with\n a size smaller than this threshold will be omitted from plotting.\n+ This may be specified as a percentage\n+ using a string, like \"50%\".\n Size may be a sum of values, see `subset_size`.\n \n .. versionadded:: 0.5\n- max_subset_size : int, optional\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n+ max_subset_size : int or \"number%\", optional\n Maximum size of a subset to be shown in the plot. All subsets with\n a size greater than this threshold will be omitted from plotting.\n+ This may be specified as a percentage\n+ using a string, like \"50%\".\n \n .. versionadded:: 0.5\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n max_subset_rank : int, optional\n Limit to the top N ranked subsets in descending order of size.\n All tied subsets are included.\n@@ -379,10 +389,18 @@ class UpSet:\n absent : str or list of str, optional\n Category or categories that must not be present in subsets for\n styling.\n- min_subset_size : int, optional\n+ min_subset_size : int or \"number%\", optional\n Minimum size of a subset to be styled.\n- max_subset_size : int, optional\n+ This may be specified as a percentage using a string, like \"50%\".\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n+ max_subset_size : int or \"number%\", optional\n Maximum size of a subset to be styled.\n+ This may be specified as a percentage using a string, like \"50%\".\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n max_subset_rank : int, optional\n Limit to the top N ranked subsets in descending order of size.\n All tied subsets are included.\ndiff --git a/upsetplot/reformat.py b/upsetplot/reformat.py\nindex 821a359..5853729 100644\n--- a/upsetplot/reformat.py\n+++ b/upsetplot/reformat.py\n@@ -93,6 +93,19 @@ def _scalar_to_list(val):\n return val\n \n \n+def _check_percent(value, agg):\n+ if not isinstance(value, str):\n+ return value\n+ try:\n+ if value.endswith(\"%\") and 0 <= float(value[:-1]) <= 100:\n+ return float(value[:-1]) / 100 * agg.sum()\n+ except ValueError:\n+ pass\n+ raise ValueError(\n+ f\"String value must be formatted as percentage between 0 and 100. Got {value}\"\n+ )\n+\n+\n def _get_subset_mask(\n agg,\n min_subset_size,\n@@ -104,6 +117,8 @@ def _get_subset_mask(\n absent,\n ):\n \"\"\"Get a mask over subsets based on size, degree or category presence\"\"\"\n+ min_subset_size = _check_percent(min_subset_size, agg)\n+ max_subset_size = _check_percent(max_subset_size, agg)\n subset_mask = True\n if min_subset_size is not None:\n subset_mask = np.logical_and(subset_mask, agg >= min_subset_size)\n@@ -235,13 +250,20 @@ def query(\n absent : str or list of str, optional\n Category or categories that must not be present in subsets for\n styling.\n- min_subset_size : int, optional\n+ min_subset_size : int or \"number%\", optional\n Minimum size of a subset to be reported. All subsets with\n a size smaller than this threshold will be omitted from\n- category_totals and data.\n+ category_totals and data. This may be specified as a percentage\n+ using a string, like \"50%\".\n Size may be a sum of values, see `subset_size`.\n- max_subset_size : int, optional\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n+ max_subset_size : int or \"number%\", optional\n Maximum size of a subset to be reported.\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n max_subset_rank : int, optional\n Limit to the top N ranked subsets in descending order of size.\n All tied subsets are included.\n", "test_patch": "diff --git a/upsetplot/tests/test_upsetplot.py b/upsetplot/tests/test_upsetplot.py\nindex d96b42d..3c33dea 100644\n--- a/upsetplot/tests/test_upsetplot.py\n+++ b/upsetplot/tests/test_upsetplot.py\n@@ -768,6 +768,13 @@ def test_index_must_be_bool(x):\n (True, True, True): 990,\n },\n ),\n+ (\n+ {\"min_subset_size\": \"15%\", \"max_subset_size\": \"30.1%\"},\n+ {\n+ (True, False, False): 884,\n+ (True, True, True): 990,\n+ },\n+ ),\n (\n {\"min_degree\": 2},\n {\n@@ -853,6 +860,22 @@ def test_filter_subsets_max_subset_rank_tie():\n assert cur.shape[0] == full.shape[0]\n \n \n+@pytest.mark.parametrize(\n+ \"value\",\n+ [\n+ \"1\",\n+ \"-1%\",\n+ \"1%%\",\n+ \"%1\",\n+ \"hello\",\n+ ],\n+)\n+def test_bad_percentages(value):\n+ data = generate_samples(seed=0, n_samples=5, n_categories=3)\n+ with pytest.raises(ValueError, match=\"percentage\"):\n+ UpSet(data, min_subset_size=value)\n+\n+\n @pytest.mark.parametrize(\n \"x\",\n [\n", "FAIL_TO_PASS": ["upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[-1%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1%%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[%1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[hello]"]}], "all_FAIL_TO_PASS": ["upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[-1%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1%%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[%1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[hello]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pycqa__pyflakes-745_x1", "level": 1, "source": "swerebenchv2", "repo": "PyCQA/pyflakes", "image": "swerebenchv2/pycqa-pyflakes:745-2c64ae4", "base_commit": "2c64ae48e2b1984a16cf25d215c9f9d21146426d", "num_bugs": 1, "bugs": [{"instance_id": "pycqa__pyflakes-745", "base_commit": "2c64ae48e2b1984a16cf25d215c9f9d21146426d", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex b87bc88..15b4c2b 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -1068,7 +1068,7 @@ class Checker:\n )\n return handler\n \n- def handleNodeLoad(self, node):\n+ def handleNodeLoad(self, node, parent):\n name = getNodeName(node)\n if not name:\n return\n@@ -1093,7 +1093,6 @@ class Checker:\n continue\n \n if name == 'print' and isinstance(binding, Builtin):\n- parent = self.getParent(node)\n if (isinstance(parent, ast.BinOp) and\n isinstance(parent.op, ast.RShift)):\n self.report(messages.InvalidPrintSyntax, node)\n@@ -1880,7 +1879,7 @@ class Checker:\n \"\"\"\n # Locate the name in locals / function / globals scopes.\n if isinstance(node.ctx, ast.Load):\n- self.handleNodeLoad(node)\n+ self.handleNodeLoad(node, self.getParent(node))\n if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and\n isinstance(node._pyflakes_parent, ast.Call)):\n # we are doing locals() call in current scope\n@@ -2049,7 +2048,7 @@ class Checker:\n self.addBinding(node, ClassDefinition(node.name, node))\n \n def AUGASSIGN(self, node):\n- self.handleNodeLoad(node.target)\n+ self.handleNodeLoad(node.target, node)\n self.handleNode(node.value, node)\n self.handleNode(node.target, node)\n \n", "test_patch": "diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py\nindex b138cf6..ce742a5 100644\n--- a/pyflakes/test/test_other.py\n+++ b/pyflakes/test/test_other.py\n@@ -2052,6 +2052,10 @@ class TestIncompatiblePrintOperator(TestCase):\n self.assertEqual(exc.lineno, 4)\n self.assertEqual(exc.col, 0)\n \n+ def test_print_augmented_assign(self):\n+ # nonsense, but shouldn't crash pyflakes\n+ self.flakes('print += 1')\n+\n def test_print_function_assignment(self):\n \"\"\"\n A valid assignment, tested for catching false positives.\n", "FAIL_TO_PASS": ["pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_augmented_assign"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_augmented_assign"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "vmware__tern-250_x1", "level": 1, "source": "swerebenchv2", "repo": "vmware/tern", "image": "swerebenchv2/vmware-tern:250-a181c29", "base_commit": "a181c297f4915339435927b623f4d059a4e9bf8b", "num_bugs": 1, "bugs": [{"instance_id": "vmware__tern-250", "base_commit": "a181c297f4915339435927b623f4d059a4e9bf8b", "gold_patch": "diff --git a/tern/classes/package.py b/tern/classes/package.py\nindex edab9ae..36289c9 100644\n--- a/tern/classes/package.py\n+++ b/tern/classes/package.py\n@@ -4,6 +4,7 @@\n # SPDX-License-Identifier: BSD-2-Clause\n #\n \n+from tern.classes.notice import Notice\n from tern.classes.origins import Origins\n from tern.utils.general import prop_names\n \n@@ -13,7 +14,8 @@ class Package:\n attributes:\n name: package name\n version: package version\n- pkg_license: package license\n+ pkg_license: package license that is declared\n+ copyright: copyright text\n src_url: package source url\n origins: a list of NoticeOrigin objects\n \n@@ -25,6 +27,7 @@ class Package:\n self.__name = name\n self.__version = ''\n self.__pkg_license = ''\n+ self.__copyright = ''\n self.__src_url = ''\n self.__origins = Origins()\n \n@@ -45,8 +48,16 @@ class Package:\n return self.__pkg_license\n \n @pkg_license.setter\n- def pkg_license(self, pkg_license): \n- self.__pkg_license =pkg_license\n+ def pkg_license(self, pkg_license):\n+ self.__pkg_license = pkg_license\n+\n+ @property\n+ def copyright(self):\n+ return self.__copyright\n+\n+ @copyright.setter\n+ def copyright(self, text):\n+ self.__copyright = text\n \n @property\n def src_url(self):\n@@ -83,11 +94,25 @@ class Package:\n pkg_dict.update({'origins': self.origins.to_dict()})\n return pkg_dict\n \n+ def __fill_properties(self, package_dict):\n+ '''Check to see if the dictionary keys have all the properties\n+ listed. If not then put a Notice object in the list of Origins\n+ package_dict should not contain 'name' '''\n+ for key, prop in prop_names(self):\n+ if prop not in ('name', 'origins'):\n+ if prop not in package_dict.keys():\n+ self.origins.add_notice_to_origins(\n+ self.name, Notice(\n+ \"No metadata for key: {}\".format(prop), 'warning'))\n+ else:\n+ self.__dict__[key] = package_dict[prop]\n+\n def fill(self, package_dict):\n '''The package dict looks like this:\n name: \n version: \n- pkg_license: \n+ pkg_license: \n+ copyright: \n src_url: \n the way to use this method is to instantiate the class with the\n name and then give it a package dictionary to fill in the rest\n@@ -95,9 +120,7 @@ class Package:\n the object, false if not'''\n success = True\n if self.name == package_dict['name']:\n- self.version = package_dict['version']\n- self.pkg_license = package_dict['pkg_license']\n- self.src_url = package_dict['src_url']\n+ self.__fill_properties(package_dict)\n else:\n success = False\n return success\ndiff --git a/tern/command_lib/base.yml b/tern/command_lib/base.yml\nindex 7a02e6e..f14faea 100644\n--- a/tern/command_lib/base.yml\n+++ b/tern/command_lib/base.yml\n@@ -73,7 +73,7 @@ dpkg:\n - \"pkgs=`dpkg --get-selections | cut -f1 -d':' | awk '{print $1}'`\"\n - \"for p in $pkgs; do dpkg -l $p | awk 'NR>5 {print $3}'; done\"\n delimiter: \"\\n\"\n- licenses:\n+ copyrights:\n invoke:\n 1:\n container:\ndiff --git a/tern/command_lib/command_lib.py b/tern/command_lib/command_lib.py\nindex 5f73aac..b634794 100644\n--- a/tern/command_lib/command_lib.py\n+++ b/tern/command_lib/command_lib.py\n@@ -22,7 +22,8 @@ from tern.report import errors\n # base image command library\n base_file = pkg_resources.resource_filename('tern', 'command_lib/base.yml')\n # general snippets in command library\n-snippet_file = pkg_resources.resource_filename('tern', 'command_lib/snippets.yml')\n+snippet_file = pkg_resources.resource_filename('tern',\n+ 'command_lib/snippets.yml')\n # command library\n command_lib = {'base': {}, 'snippets': {}}\n with open(os.path.abspath(base_file)) as f:\n@@ -30,8 +31,8 @@ with open(os.path.abspath(base_file)) as f:\n with open(os.path.abspath(snippet_file)) as f:\n command_lib['snippets'] = yaml.safe_load(f)\n # list of package information keys that the command library can accomodate\n-base_keys = {'names', 'versions', 'licenses', 'src_urls', 'srcs'}\n-package_keys = {'name', 'version', 'src_url', 'license', 'src'}\n+base_keys = {'names', 'versions', 'licenses', 'copyrights', 'src_urls', 'srcs'}\n+package_keys = {'name', 'version', 'license', 'copyright', 'src_url', 'src'}\n \n # global logger\n logger = logging.getLogger(constants.logger_name)\ndiff --git a/tern/command_lib/snippets.yml b/tern/command_lib/snippets.yml\nindex 30a8911..aa35194 100644\n--- a/tern/command_lib/snippets.yml\n+++ b/tern/command_lib/snippets.yml\n@@ -11,41 +11,8 @@ apt-get:\n remove: 'purge' # subcommand to remove a package\n ignore: # list of subcommands that don't add or remove packages\n - 'update' \n- packages:\n- - name: default\n- version:\n- # either a version number or a script snippet\n- invoke:\n- 1:\n- container:\n- - \"dpkg -l {package} | awk 'NR>5 {print $3}'\"\n- src_url:\n- invoke:\n- 1:\n- container:\n- - \"apt-get download --print-uris {package}\"\n- license:\n- invoke:\n- 1:\n- container:\n- - \"cat /usr/share/doc/{package}/copyright\"\n- deps:\n- invoke:\n- 1:\n- container:\n- - \"apt-cache depends --installed --no-suggests {package} | awk 'NR>1 {print $2}'\"\n- delimiter: \"\\n\"\n- src:\n- # copy_in: used to copy into the running container\n- copy_in:\n- - from: 'config/{image}/{tag}/sources.list'\n- to: '/etc/apt/sources.list'\n- - from: 'config/image/apt_get_sources.sh'\n- to: '/'\n- invoke:\n- 1:\n- container:\n- - './apt_get_sources.sh {package}'\n+ packages: 'dpkg' # refer to base.yml's method of collection\n+\n tyum:\n install: 'install'\n remove: 'remove'\n@@ -65,31 +32,7 @@ tdnf:\n apk:\n install: 'add'\n remove: 'del'\n- # ignore:\n- packages:\n- - name: default\n- version:\n- invoke:\n- 1:\n- container:\n- # use double quotes when using awk\n- - \"apk info {package} 2>/dev/null | head -1 | awk '{print $1}'\"\n- license:\n- invoke:\n- 1:\n- container:\n- - 'apk -a info {package} 2>/dev/null | tail -2 | head -1'\n- src_url:\n- invoke:\n- 1:\n- container:\n- - 'apk info {package} 2>/dev/null | head -5 | tail -1'\n- deps:\n- invoke:\n- 1:\n- container:\n- - 'apk -R info python 2>/dev/null | tail -n +2 | head -n -1 | cut -f2 -d\":\" | cut -f1 -d\".\"'\n- delimiter: \"\\n\"\n+ packages: 'apk'\n \n pacman:\n install: '-Syu'\ndiff --git a/tern/common.py b/tern/common.py\nindex 62906f8..f5bf197 100644\n--- a/tern/common.py\n+++ b/tern/common.py\n@@ -81,7 +81,54 @@ def get_base_bin():\n return binary\n \n \n-def add_base_packages(image_layer, binary, shell): # pylint: disable=too-many-locals\n+def collate_list_metadata(shell, listing):\n+ '''Given the shell and the listing for the package manager, collect\n+ metadata that gets returned as a list'''\n+ pkg_dict = {}\n+ msgs = ''\n+ warnings = ''\n+ for item in command_lib.base_keys:\n+ if item in listing.keys():\n+ items, msg = command_lib.get_pkg_attr_list(shell, listing[item])\n+ msgs = msgs + msg\n+ pkg_dict.update({item: items})\n+ else:\n+ warnings = warnings + errors.no_listing_for_base_key.format(\n+ listing_key=item)\n+ return pkg_dict, msgs, warnings\n+\n+\n+def convert_to_pkg_dicts(pkg_dict):\n+ '''The pkg_dict is what gets returned after collecting individual\n+ metadata as a list. It looks like this if property collected:\n+ {'names': [....], 'versions': [...], 'licenses': [...], ....}\n+ Convert these into a package dictionary expected by the Package\n+ Object'''\n+ mapping = {'name': 'names',\n+ 'version': 'versions',\n+ 'pkg_license': 'licenses',\n+ 'copyright': 'copyrights',\n+ 'src_url': 'src_urls'}\n+ pkg_list = []\n+ len_names = len(pkg_dict['names'])\n+ # make a list of keys that correspond with package property names\n+ new_dict = {}\n+ for key, value in mapping.items():\n+ if value in pkg_dict.keys():\n+ if len(pkg_dict[value]) == len_names:\n+ new_dict.update({key: pkg_dict[value]})\n+ else:\n+ logger.warning(\"Inconsistent lengths for key: %s\", value)\n+ # convert each of the keys into package dictionaries\n+ for index, _ in enumerate(new_dict['name']):\n+ a_pkg = {}\n+ for key, value in new_dict.items():\n+ a_pkg.update({key: value[index]})\n+ pkg_list.append(a_pkg)\n+ return pkg_list\n+\n+\n+def add_base_packages(image_layer, binary, shell):\n '''Given the image layer, the binary to invoke and shell:\n 1. get the listing from the base.yml\n 2. Invoke any commands against the base layer\n@@ -107,27 +154,18 @@ def add_base_packages(image_layer, binary, shell): # pylint: disable=too-many-l\n if not shell:\n shell = constants.shell\n # get all the packages in the base layer\n- names, n_msg = command_lib.get_pkg_attr_list(shell, listing['names'])\n- versions, v_msg = command_lib.get_pkg_attr_list(\n- shell, listing['versions'])\n- licenses, l_msg = command_lib.get_pkg_attr_list(\n- shell, listing['licenses'])\n- src_urls, u_msg = command_lib.get_pkg_attr_list(\n- shell, listing['src_urls'])\n- # add a notice to the image if something went wrong\n- invoke_msg = n_msg + v_msg + l_msg + u_msg\n+ pkg_dict, invoke_msg, warnings = collate_list_metadata(shell, listing)\n if invoke_msg:\n image_layer.origins.add_notice_to_origins(\n origin_layer, Notice(invoke_msg, 'error'))\n- if names and len(names) > 1:\n- for index, name in enumerate(names):\n- pkg = Package(name)\n- if len(versions) == len(names):\n- pkg.version = versions[index]\n- if len(licenses) == len(names):\n- pkg.license = licenses[index]\n- if len(src_urls) == len(names):\n- pkg.src_url = src_urls[index]\n+ if warnings:\n+ image_layer.origins.add_notice_to_origins(\n+ origin_command_lib, Notice(warnings, 'warning'))\n+ if 'names' in pkg_dict and len(pkg_dict['names']) > 1:\n+ pkg_list = convert_to_pkg_dicts(pkg_dict)\n+ for pkg_dict in pkg_list:\n+ pkg = Package(pkg_dict['name'])\n+ pkg.fill(pkg_dict)\n image_layer.add_package(pkg)\n # if there is no listing add a notice\n else:\ndiff --git a/tern/report/content.py b/tern/report/content.py\nindex 0c9b0f9..2afe265 100644\n--- a/tern/report/content.py\n+++ b/tern/report/content.py\n@@ -18,7 +18,7 @@ def print_invoke_list(info_dict, info):\n package information.\n info_dict: get_base_listing or get_command_listing from\n command_lib/command_lib.py\n- info: the required key (niames, versions, licenses, etc)'''\n+ see command_lib/command_lib.py for a list of supported info items'''\n report = ''\n if 'invoke' in info_dict[info]:\n report = report + info + ':\\n'\n@@ -39,10 +39,9 @@ def print_base_invoke(key):\n the command_lib/base.yml'''\n info = command_lib.get_base_listing(key)\n report = ''\n- report = report + print_invoke_list(info, 'names')\n- report = report + print_invoke_list(info, 'versions')\n- report = report + print_invoke_list(info, 'licenses')\n- report = report + print_invoke_list(info, 'src_urls')\n+ for item in command_lib.base_keys:\n+ if item in info.keys():\n+ report = report + print_invoke_list(info, item)\n report = report + '\\n'\n return report\n \n@@ -74,7 +73,9 @@ def print_package(pkg_obj, prefix):\n package_url=pkg_obj.src_url)\n notes = notes + prefix + formats.package_license.format(\n package_license=pkg_obj.pkg_license)\n- notes = notes + '\\n'\n+ notes = notes + prefix + formats.package_copyright.format(\n+ package_copyright=pkg_obj.copyright)\n+ notes = notes + '\\n\\n'\n return notes\n \n \ndiff --git a/tern/report/formats.py b/tern/report/formats.py\nindex 8a296a6..d9afc1b 100644\n--- a/tern/report/formats.py\n+++ b/tern/report/formats.py\n@@ -41,7 +41,8 @@ invoke_on_host = '''\\ton host:\\n'''\n package_name = '''Package: {package_name}\\n'''\n package_version = '''Version: {package_version}\\n'''\n package_url = '''Project URL: {package_url}\\n'''\n-package_license = '''License: {package_license}\\n\\n'''\n+package_license = '''License: {package_license}\\n'''\n+package_copyright = '''Copyright Text: {package_copyright}\\n'''\n # notes\n package_notes = '''Errors: {package_info_retrieval_errors}\\n''' \\\n '''Improvements: {package_info_reporting_improvements}\\n'''\ndiff --git a/tern/report/report.py b/tern/report/report.py\nindex a6070b4..83ac3f8 100644\n--- a/tern/report/report.py\n+++ b/tern/report/report.py\n@@ -308,7 +308,8 @@ def generate_report(args, *images):\n \n def generate_verbose(is_summary, images):\n '''Generate a verbose report'''\n- report = formats.disclaimer.format(version_info=general.get_git_rev_or_version())\n+ report = formats.disclaimer.format(\n+ version_info=general.get_git_rev_or_version())\n if is_summary:\n logger.debug('Creating a summary of components in image...')\n for image in images:\n@@ -323,7 +324,8 @@ def generate_verbose(is_summary, images):\n def generate_yaml(images):\n '''Generate a yaml report'''\n logger.debug('Creating YAML report...')\n- report = formats.disclaimer_yaml.format(version_info=general.get_git_rev_or_version())\n+ report = formats.disclaimer_yaml.format(\n+ version_info=general.get_git_rev_or_version())\n for image in images:\n report = report + content.print_yaml_report(image)\n return report\n@@ -343,7 +345,7 @@ def check_docker_daemon():\n docker.from_env()\n except IOError as error:\n logger.error('Docker daemon is not running: %s',\n- error.output.decode('utf-8'))\n+ error.output.decode('utf-8'))\n sys.exit()\n \n \n", "test_patch": "diff --git a/tests/test_class_package.py b/tests/test_class_package.py\nindex aa59a42..847c6b4 100644\n--- a/tests/test_class_package.py\n+++ b/tests/test_class_package.py\n@@ -17,6 +17,7 @@ class TestClassPackage(unittest.TestCase):\n self.p1 = Package('p1')\n self.p1.version = '1.0'\n self.p1.pkg_license = 'Apache 2.0'\n+ self.p1.copyright = 'All Rights Reserved'\n self.p1.src_url = 'github.com'\n \n self.p2 = Package('p2')\n@@ -30,6 +31,7 @@ class TestClassPackage(unittest.TestCase):\n self.assertFalse(self.p2.version)\n self.assertFalse(self.p2.src_url)\n self.assertFalse(self.p2.pkg_license)\n+ self.assertFalse(self.p2.copyright)\n \n def testSetters(self):\n self.assertRaises(AttributeError, setattr, self.p2, 'name', 'y')\n@@ -37,6 +39,8 @@ class TestClassPackage(unittest.TestCase):\n self.assertEqual(self.p2.version, '2.0')\n self.p2.pkg_license = 'Apache 2.0'\n self.assertEqual(self.p2.pkg_license, 'Apache 2.0')\n+ self.p2.copyright = \"All Rights Reserved\"\n+ self.assertEqual(self.p2.copyright, 'All Rights Reserved')\n self.p2.src_url = 'github.com'\n self.assertEqual(self.p2.src_url, 'github.com')\n \n@@ -44,6 +48,7 @@ class TestClassPackage(unittest.TestCase):\n self.assertEqual(self.p1.name, 'p1')\n self.assertEqual(self.p1.version, '1.0')\n self.assertEqual(self.p1.pkg_license, 'Apache 2.0')\n+ self.assertEqual(self.p1.copyright, 'All Rights Reserved')\n self.assertEqual(self.p1.src_url, 'github.com')\n \n def testToDict(self):\n@@ -51,6 +56,7 @@ class TestClassPackage(unittest.TestCase):\n self.assertEqual(a_dict['name'], 'p1')\n self.assertEqual(a_dict['version'], '1.0')\n self.assertEqual(a_dict['pkg_license'], 'Apache 2.0')\n+ self.assertEqual(a_dict['copyright'], 'All Rights Reserved')\n self.assertEqual(a_dict['src_url'], 'github.com')\n self.assertFalse(a_dict['origins'])\n \n@@ -78,6 +84,26 @@ class TestClassPackage(unittest.TestCase):\n p.version = '2.0'\n self.assertTrue(self.p2.is_equal(p))\n \n+ def testFill(self):\n+ p_dict = {'name': 'p1',\n+ 'version': '1.0',\n+ 'pkg_license': 'Apache 2.0'}\n+ p = Package('p1')\n+ p.fill(p_dict)\n+ self.assertEqual(p.name, 'p1')\n+ self.assertEqual(p.version, '1.0')\n+ self.assertEqual(p.pkg_license, 'Apache 2.0')\n+ self.assertFalse(p.copyright)\n+ self.assertFalse(p.src_url)\n+ self.assertEqual(len(p.origins.origins), 1)\n+ self.assertEqual(p.origins.origins[0].origin_str, 'p1')\n+ self.assertEqual(len(p.origins.origins[0].notices), 2)\n+ self.assertEqual(p.origins.origins[0].notices[0].message,\n+ \"No metadata for key: copyright\")\n+ self.assertEqual(p.origins.origins[0].notices[0].level, 'warning')\n+ self.assertEqual(p.origins.origins[0].notices[1].message,\n+ \"No metadata for key: src_url\")\n+\n \n if __name__ == '__main__':\n unittest.main()\n", "FAIL_TO_PASS": ["tests/test_class_package.py::TestClassPackage::testFill", "tests/test_class_package.py::TestClassPackage::testInstance"]}], "all_FAIL_TO_PASS": ["tests/test_class_package.py::TestClassPackage::testFill", "tests/test_class_package.py::TestClassPackage::testInstance"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getmoto__moto-5862_x1", "level": 1, "source": "swerebenchv2", "repo": "getmoto/moto", "image": "swerebenchv2/getmoto-moto:5862-c81bd9a", "base_commit": "c81bd9a1aa93f2f7da9de3bdad27e0f4173b1054", "num_bugs": 1, "bugs": [{"instance_id": "getmoto__moto-5862", "base_commit": "c81bd9a1aa93f2f7da9de3bdad27e0f4173b1054", "gold_patch": "diff --git a/moto/ses/models.py b/moto/ses/models.py\nindex 27e1e5fef..dd9c94ae6 100644\n--- a/moto/ses/models.py\n+++ b/moto/ses/models.py\n@@ -115,7 +115,7 @@ class SESBackend(BaseBackend):\n \n from moto.core import DEFAULT_ACCOUNT_ID\n from moto.ses import ses_backends\n- ses_backend = ses_backends[DEFAULT_ACCOUNT_ID][\"global\"]\n+ ses_backend = ses_backends[DEFAULT_ACCOUNT_ID][region]\n messages = ses_backend.sent_messages # sent_messages is a List of Message objects\n \n Note that, as this is an internal API, the exact format may differ per versions.\n@@ -585,6 +585,4 @@ class SESBackend(BaseBackend):\n return attributes_by_identity\n \n \n-ses_backends: Mapping[str, SESBackend] = BackendDict(\n- SESBackend, \"ses\", use_boto3_regions=False, additional_regions=[\"global\"]\n-)\n+ses_backends: Mapping[str, SESBackend] = BackendDict(SESBackend, \"ses\")\ndiff --git a/moto/ses/responses.py b/moto/ses/responses.py\nindex 016ff3fc0..f36aa7601 100644\n--- a/moto/ses/responses.py\n+++ b/moto/ses/responses.py\n@@ -11,7 +11,7 @@ class EmailResponse(BaseResponse):\n \n @property\n def backend(self):\n- return ses_backends[self.current_account][\"global\"]\n+ return ses_backends[self.current_account][self.region]\n \n def verify_email_identity(self):\n address = self.querystring.get(\"EmailAddress\")[0]\n", "test_patch": "diff --git a/tests/test_ses/test_ses_boto3.py b/tests/test_ses/test_ses_boto3.py\nindex 0ca55c7f8..251c3d056 100644\n--- a/tests/test_ses/test_ses_boto3.py\n+++ b/tests/test_ses/test_ses_boto3.py\n@@ -19,6 +19,15 @@ def test_verify_email_identity():\n address.should.equal(\"test@example.com\")\n \n \n+@mock_ses\n+def test_identities_are_region_specific():\n+ us_east = boto3.client(\"ses\", region_name=\"us-east-1\")\n+ us_east.verify_email_identity(EmailAddress=\"test@example.com\")\n+\n+ us_west = boto3.client(\"ses\", region_name=\"us-west-1\")\n+ us_west.list_identities()[\"Identities\"].should.have.length_of(0)\n+\n+\n @mock_ses\n def test_verify_email_identity_idempotency():\n conn = boto3.client(\"ses\", region_name=\"us-east-1\")\n", "FAIL_TO_PASS": ["tests/test_ses/test_ses_boto3.py::test_identities_are_region_specific"]}], "all_FAIL_TO_PASS": ["tests/test_ses/test_ses_boto3.py::test_identities_are_region_specific"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "meltano__sdk-1881_x1", "level": 1, "source": "swerebenchv2", "repo": "meltano/sdk", "image": "swerebenchv2/meltano-sdk:1881-c3a8f90", "base_commit": "c3a8f90ac4d79eb5c655740d0fd88f393af7f306", "num_bugs": 1, "bugs": [{"instance_id": "meltano__sdk-1881", "base_commit": "c3a8f90ac4d79eb5c655740d0fd88f393af7f306", "gold_patch": "diff --git a/singer_sdk/helpers/capabilities.py b/singer_sdk/helpers/capabilities.py\nindex 55aff8ce..f5b5fa30 100644\n--- a/singer_sdk/helpers/capabilities.py\n+++ b/singer_sdk/helpers/capabilities.py\n@@ -99,6 +99,13 @@ TARGET_SCHEMA_CONFIG = PropertiesList(\n description=\"The default target database schema name to use for all streams.\",\n ),\n ).to_dict()\n+ADD_RECORD_METADATA_CONFIG = PropertiesList(\n+ Property(\n+ \"add_record_metadata\",\n+ BooleanType(),\n+ description=\"Add metadata to records.\",\n+ ),\n+).to_dict()\n \n \n class DeprecatedEnum(Enum):\ndiff --git a/singer_sdk/target_base.py b/singer_sdk/target_base.py\nindex 91bce652..a5386199 100644\n--- a/singer_sdk/target_base.py\n+++ b/singer_sdk/target_base.py\n@@ -17,6 +17,7 @@ from singer_sdk.helpers._batch import BaseBatchFileEncoding\n from singer_sdk.helpers._classproperty import classproperty\n from singer_sdk.helpers._compat import final\n from singer_sdk.helpers.capabilities import (\n+ ADD_RECORD_METADATA_CONFIG,\n BATCH_CONFIG,\n TARGET_SCHEMA_CONFIG,\n CapabilitiesEnum,\n@@ -595,6 +596,8 @@ class Target(PluginBase, SingerReader, metaclass=abc.ABCMeta):\n if k not in target_jsonschema[\"properties\"]:\n target_jsonschema[\"properties\"][k] = v\n \n+ _merge_missing(ADD_RECORD_METADATA_CONFIG, config_jsonschema)\n+\n capabilities = cls.capabilities\n \n if PluginCapabilities.BATCH in capabilities:\n", "test_patch": "diff --git a/tests/core/test_target_base.py b/tests/core/test_target_base.py\nindex f9b342d3..de344c7e 100644\n--- a/tests/core/test_target_base.py\n+++ b/tests/core/test_target_base.py\n@@ -75,6 +75,7 @@ def test_target_about_info():\n assert \"flattening_enabled\" in about.settings[\"properties\"]\n assert \"flattening_max_depth\" in about.settings[\"properties\"]\n assert \"batch_config\" in about.settings[\"properties\"]\n+ assert \"add_record_metadata\" in about.settings[\"properties\"]\n \n \n def test_sql_get_sink():\n", "FAIL_TO_PASS": ["tests/core/test_target_base.py::test_target_about_info"]}], "all_FAIL_TO_PASS": ["tests/core/test_target_base.py::test_target_about_info"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "meltano__sdk-1880_x1", "level": 1, "source": "swerebenchv2", "repo": "meltano/sdk", "image": "swerebenchv2/meltano-sdk:1880-759c77b", "base_commit": "759c77beb764be49b9a207635349b6d8ed420290", "num_bugs": 1, "bugs": [{"instance_id": "meltano__sdk-1880", "base_commit": "759c77beb764be49b9a207635349b6d8ed420290", "gold_patch": "diff --git a/singer_sdk/target_base.py b/singer_sdk/target_base.py\nindex cf103883..91bce652 100644\n--- a/singer_sdk/target_base.py\n+++ b/singer_sdk/target_base.py\n@@ -17,6 +17,7 @@ from singer_sdk.helpers._batch import BaseBatchFileEncoding\n from singer_sdk.helpers._classproperty import classproperty\n from singer_sdk.helpers._compat import final\n from singer_sdk.helpers.capabilities import (\n+ BATCH_CONFIG,\n TARGET_SCHEMA_CONFIG,\n CapabilitiesEnum,\n PluginCapabilities,\n@@ -571,6 +572,38 @@ class Target(PluginBase, SingerReader, metaclass=abc.ABCMeta):\n \n return command\n \n+ @classmethod\n+ def append_builtin_config(cls: type[Target], config_jsonschema: dict) -> None:\n+ \"\"\"Appends built-in config to `config_jsonschema` if not already set.\n+\n+ To customize or disable this behavior, developers may either override this class\n+ method or override the `capabilities` property to disabled any unwanted\n+ built-in capabilities.\n+\n+ For all except very advanced use cases, we recommend leaving these\n+ implementations \"as-is\", since this provides the most choice to users and is\n+ the most \"future proof\" in terms of taking advantage of built-in capabilities\n+ which may be added in the future.\n+\n+ Args:\n+ config_jsonschema: [description]\n+ \"\"\"\n+\n+ def _merge_missing(source_jsonschema: dict, target_jsonschema: dict) -> None:\n+ # Append any missing properties in the target with those from source.\n+ for k, v in source_jsonschema[\"properties\"].items():\n+ if k not in target_jsonschema[\"properties\"]:\n+ target_jsonschema[\"properties\"][k] = v\n+\n+ capabilities = cls.capabilities\n+\n+ if PluginCapabilities.BATCH in capabilities:\n+ _merge_missing(BATCH_CONFIG, config_jsonschema)\n+\n+ super().append_builtin_config(config_jsonschema)\n+\n+ pass\n+\n \n class SQLTarget(Target):\n \"\"\"Target implementation for SQL destinations.\"\"\"\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex cf64e28d..7e7c3995 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -12,12 +12,16 @@ from sqlalchemy import __version__ as sqlalchemy_version\n \n from singer_sdk import SQLConnector\n from singer_sdk import typing as th\n+from singer_sdk.helpers.capabilities import PluginCapabilities\n from singer_sdk.sinks import BatchSink, SQLSink\n from singer_sdk.target_base import SQLTarget, Target\n \n if t.TYPE_CHECKING:\n from _pytest.config import Config\n \n+ from singer_sdk.helpers.capabilities import CapabilitiesEnum\n+\n+\n SYSTEMS = {\"linux\", \"darwin\", \"windows\"}\n \n pytest_plugins = (\"singer_sdk.testing.pytest_plugin\",)\n@@ -104,6 +108,10 @@ class TargetMock(Target):\n name = \"target-mock\"\n config_jsonschema = th.PropertiesList().to_dict()\n default_sink_class = BatchSinkMock\n+ capabilities: t.ClassVar[list[CapabilitiesEnum]] = [\n+ *Target.capabilities,\n+ PluginCapabilities.BATCH,\n+ ]\n \n def __init__(self, *args, **kwargs):\n \"\"\"Create the Mock target sync.\"\"\"\ndiff --git a/tests/core/test_target_base.py b/tests/core/test_target_base.py\nindex ee00d35e..f9b342d3 100644\n--- a/tests/core/test_target_base.py\n+++ b/tests/core/test_target_base.py\n@@ -8,6 +8,7 @@ from singer_sdk.exceptions import (\n MissingKeyPropertiesError,\n RecordsWithoutSchemaException,\n )\n+from singer_sdk.helpers.capabilities import PluginCapabilities\n from tests.conftest import BatchSinkMock, SQLSinkMock, SQLTargetMock, TargetMock\n \n \n@@ -58,6 +59,24 @@ def test_validate_record():\n sink._singer_validate_message({\"name\": \"test\"})\n \n \n+def test_target_about_info():\n+ target = TargetMock()\n+ about = target._get_about_info()\n+\n+ assert about.capabilities == [\n+ PluginCapabilities.ABOUT,\n+ PluginCapabilities.STREAM_MAPS,\n+ PluginCapabilities.FLATTENING,\n+ PluginCapabilities.BATCH,\n+ ]\n+\n+ assert \"stream_maps\" in about.settings[\"properties\"]\n+ assert \"stream_map_config\" in about.settings[\"properties\"]\n+ assert \"flattening_enabled\" in about.settings[\"properties\"]\n+ assert \"flattening_max_depth\" in about.settings[\"properties\"]\n+ assert \"batch_config\" in about.settings[\"properties\"]\n+\n+\n def test_sql_get_sink():\n input_schema_1 = {\n \"properties\": {\n", "FAIL_TO_PASS": ["tests/core/test_target_base.py::test_target_about_info"]}], "all_FAIL_TO_PASS": ["tests/core/test_target_base.py::test_target_about_info"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3519_x1", "level": 1, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3519-7a8c5cf", "base_commit": "7a8c5cf8b10e4aaced0cbea17ae1194c00d9205a", "num_bugs": 1, "bugs": [{"instance_id": "openmdao__openmdao-3519", "base_commit": "7a8c5cf8b10e4aaced0cbea17ae1194c00d9205a", "gold_patch": "diff --git a/openmdao/core/system.py b/openmdao/core/system.py\nindex 75035a5e3..cf0a71465 100644\n--- a/openmdao/core/system.py\n+++ b/openmdao/core/system.py\n@@ -25,7 +25,7 @@ from openmdao.utils.mpi import MPI, multi_proc_exception_check\n from openmdao.utils.options_dictionary import OptionsDictionary\n from openmdao.utils.record_util import create_local_meta, check_path, has_match\n from openmdao.utils.units import is_compatible, unit_conversion, simplify_unit\n-from openmdao.utils.variable_table import write_var_table, NA\n+from openmdao.utils.variable_table import write_var_table, write_options_table, NA\n from openmdao.utils.array_utils import evenly_distrib_idxs, shape_to_len, get_tol_violation, \\\n sparsity_diff_viz, get_sparsity_diff_array\n from openmdao.utils.name_maps import name2abs_name, name2abs_names\n@@ -102,6 +102,10 @@ resp_size_checks = {\n }\n resp_types = {'con': 'constraint', 'obj': 'objective'}\n \n+default_options = ['always_opt', 'default_shape', 'derivs_method', 'distributed',\n+ 'run_root_only', 'use_jit', 'assembled_jac_type',\n+ 'auto_order']\n+\n \n class _MatchType(IntEnum):\n \"\"\"\n@@ -4954,6 +4958,104 @@ class System(object, metaclass=SystemMetaclass):\n \n return var_list\n \n+ def list_options(self,\n+ include_default=True,\n+ include_solvers=True,\n+ out_stream=_DEFAULT_OUT_STREAM,\n+ return_format='list'):\n+ \"\"\"\n+ Write a list of output names and other optional information to a specified stream.\n+\n+ Parameters\n+ ----------\n+ include_default : bool\n+ When True, include the built-in openmdao system options. Default is True.\n+ include_solvers : bool\n+ When True, include options from nonlinear_solver and linear_solver.\n+ out_stream : file-like\n+ Where to send human readable output. Default is sys.stdout.\n+ Set to None to suppress.\n+ return_format : str\n+ Indicates the desired format of the return value. Can have value of 'list' or 'dict'.\n+ If 'list', the return value is a list of tuples of the form: (pathname, system options\n+ , nonlinear solver options, linear solver options)\n+ if 'dict', the return value is a dictionary with the pathname as key, and a dictionary\n+ as the value. The dictionary contains 'options', 'nonlinear_solver', and\n+ 'linear_solver' keys, each of which isa dictionary of options.\n+\n+ Returns\n+ -------\n+ list of tuple\n+ List of tuples, one for each subsystem sorted by execution order. Each tuple contains\n+ the pathname string, a dictionary of system options, a dictionary of nonlinear solver\n+ options (only if include_solvers is True) or None, and a dictionary of nonlinear solver\n+ options (only if include_solvers is True) or None.\n+ \"\"\"\n+ name = self.pathname\n+\n+ opt_list = []\n+ opts = {}\n+ nl_opts = None\n+ ln_opts = None\n+ for opt_name, opt_value in self.options.items():\n+\n+ if not include_default and opt_name in default_options:\n+ continue\n+\n+ opt_meta = self.options._dict[opt_name]\n+\n+ if opt_meta['recordable']:\n+ opts[opt_name] = opt_value\n+\n+ if include_solvers:\n+ nl = self.nonlinear_solver\n+ if nl is not None:\n+ nl_opts = {}\n+ for opt_name, opt_value in nl.options.items():\n+\n+ opt_meta = nl.options._dict[opt_name]\n+\n+ if opt_meta['recordable']:\n+ nl_opts[opt_name] = opt_value\n+\n+ ln = self.linear_solver\n+ if ln is not None:\n+ ln_opts = {}\n+ for opt_name, opt_value in ln.options.items():\n+\n+ opt_meta = ln.options._dict[opt_name]\n+\n+ if opt_meta['recordable']:\n+ ln_opts[opt_name] = opt_value\n+\n+ opt_list.append((name, opts, nl_opts, ln_opts))\n+\n+ # For components, self._subsystems_allprocs is empty.\n+ if self._subsystems_allprocs:\n+ for subsys in self.system_iter(include_self=False, recurse=True):\n+\n+ if subsys.pathname != '_auto_ivc':\n+ sub_opts = subsys.list_options(out_stream=None,\n+ include_solvers=include_solvers,\n+ include_default=include_default)\n+ opt_list.extend(sub_opts)\n+\n+ write_options_table(self.pathname, opt_list, out_stream=out_stream)\n+\n+ if return_format == 'dict':\n+ opt_dict = {}\n+ for name, opts, nl_opts, ln_opts in opt_list:\n+ opt_dict[name] = {\n+ 'options': opts,\n+ }\n+ if include_solvers:\n+ opt_dict[name]['nonlinear_solver'] = nl_opts\n+ opt_dict[name]['linear_solver'] = ln_opts\n+\n+ return opt_dict\n+\n+ return opt_list\n+\n def run_solve_nonlinear(self):\n \"\"\"\n Compute outputs.\ndiff --git a/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb b/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb\nindex 6f7eabc25..c1c31e9c6 100644\n--- a/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb\n+++ b/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb\n@@ -774,6 +774,24 @@\n \"assert_near_equal(expected, c3y)\"\n ]\n },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"## Listing Options\\n\",\n+ \"\\n\",\n+ \"You can list all options in a `Group` or `Component` and their associated linear and nonlinear solvers by using the `list_options` method. This will return the options in a list of tuples of (system pathname, system dictionary of options, nonlinear_solver dictionary of options, linear_solver dictionary of options), and will also print them to stdout or any output stream that you request.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"myoptions = p.model.list_options(include_solvers=True, include_default=True)\"\n+ ]\n+ },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\ndiff --git a/openmdao/utils/variable_table.py b/openmdao/utils/variable_table.py\nindex d7e79f505..0bd6d8925 100644\n--- a/openmdao/utils/variable_table.py\n+++ b/openmdao/utils/variable_table.py\n@@ -308,3 +308,124 @@ def _write_variable(out_stream, row, column_names, var_dict, print_arrays):\n indented_lines = [(left_column_width + indent_inc) * ' ' +\n s for s in out_str.splitlines()]\n out_stream.write('\\n'.join(indented_lines) + '\\n')\n+\n+\n+def write_options_table(pathname, opt_list, out_stream=_DEFAULT_OUT_STREAM):\n+ \"\"\"\n+ Write table of options and values for a model.\n+\n+ For non-serializable datatypes, only the type is printed.\n+\n+ Parameters\n+ ----------\n+ pathname : str\n+ Pathname to be printed. If None, defaults to 'model'.\n+ opt_list : list\n+ List of systems options dictionaries.\n+ out_stream : file-like object\n+ Where to send human readable output.\n+ \"\"\"\n+ if out_stream is None:\n+ return\n+\n+ if out_stream is _DEFAULT_OUT_STREAM:\n+ out_stream = sys.stdout\n+ elif not isinstance(out_stream, TextIOBase):\n+ raise TypeError(\"Invalid output stream specified for 'out_stream'.\")\n+\n+ count = len(opt_list)\n+\n+ # Write header\n+ pathname = pathname if pathname else 'model'\n+\n+ header = f\"Options for {count} components in '{pathname}\"\n+\n+ out_stream.write(header + '\\n')\n+\n+ if not count:\n+ out_stream.write('\\n\\n')\n+ return\n+\n+ column_names = ['option name', 'option value']\n+\n+ # Find with width of the first column in the table\n+ # Need to look through all the possible varnames to find the max width\n+ max_varname_len = len(column_names[0])\n+ for sys_name, opt_dict, nl_dict, ln_dict in opt_list:\n+ stem_size = indent_inc * len(sys_name.split('.'))\n+ max_varname_len = max(max_varname_len, stem_size)\n+ for opt_name in opt_dict:\n+ total_len = stem_size + len(opt_name)\n+ max_varname_len = max(max_varname_len, total_len)\n+\n+ if nl_dict is not None:\n+ for opt_name in nl_dict:\n+ total_len = stem_size + len(opt_name) + 2\n+ max_varname_len = max(max_varname_len, total_len)\n+ if ln_dict is not None:\n+ for opt_name in ln_dict:\n+ total_len = stem_size + len(opt_name) + 2\n+ max_varname_len = max(max_varname_len, total_len)\n+\n+ # Write out the column headers\n+ opt_val_width = 30\n+ column_header = column_names[0] + (max_varname_len - len(column_names[0])) * ' '\n+ column_dashes = max_varname_len * '-'\n+\n+ column_header += column_spacing * ' ' + column_names[1]\n+ column_dashes += column_spacing * ' ' + opt_val_width * '-'\n+\n+ out_stream.write('\\n')\n+ out_stream.write(column_header + '\\n')\n+ out_stream.write(column_dashes + '\\n')\n+\n+ core_types = (int, float, tuple, list, np.ndarray, str, bool)\n+\n+ for sys_path, opt_dict, nl_dict, ln_dict in opt_list:\n+ sys_path_list = sys_path.split('.')\n+ stem_size = indent_inc * len(sys_path_list)\n+ out_stream.write(stem_size * ' ' + sys_path_list[-1] + '\\n')\n+ stem_size += 2\n+\n+ for opt_name, opt_val in opt_dict.items():\n+\n+ if not isinstance(opt_val, core_types):\n+ opt_val = type(opt_val)\n+\n+ row = stem_size * ' ' + opt_name\n+\n+ remaining = max_varname_len - len(row) + column_spacing + 2\n+ row += remaining * ' ' + str(opt_val)\n+ out_stream.write(row + '\\n')\n+\n+ if nl_dict is not None:\n+\n+ out_stream.write(stem_size * ' ' + 'nonlinear_solver' + '\\n')\n+\n+ for opt_name, opt_val in nl_dict.items():\n+\n+ if not isinstance(opt_val, core_types):\n+ opt_val = type(opt_val)\n+\n+ row = (stem_size + 2) * ' ' + opt_name\n+\n+ remaining = max_varname_len - len(row) + column_spacing + 2\n+ row += remaining * ' ' + str(opt_val)\n+ out_stream.write(row + '\\n')\n+\n+ if ln_dict is not None:\n+\n+ out_stream.write(stem_size * ' ' + 'linear_solver' + '\\n')\n+\n+ for opt_name, opt_val in ln_dict.items():\n+\n+ if not isinstance(opt_val, core_types):\n+ opt_val = type(opt_val)\n+\n+ row = (stem_size + 2) * ' ' + opt_name\n+\n+ remaining = max_varname_len - len(row) + column_spacing + 2\n+ row += remaining * ' ' + str(opt_val)\n+ out_stream.write(row + '\\n')\n+\n+ out_stream.write('\\n\\n')\n", "test_patch": "diff --git a/openmdao/core/tests/test_system.py b/openmdao/core/tests/test_system.py\nindex ad008bd13..d152f5b3e 100644\n--- a/openmdao/core/tests/test_system.py\n+++ b/openmdao/core/tests/test_system.py\n@@ -328,6 +328,35 @@ class TestSystem(unittest.TestCase):\n self.assertEqual(sorted([name for name, _ in nonDV_indeps]),\n ['_auto_ivc.v1'])\n \n+ def test_list_options(self):\n+ from openmdao.test_suite.components.sellar_feature import SellarMDA\n+\n+ model = SellarMDA()\n+\n+ prob = Problem(model)\n+ prob.setup()\n+ prob.final_setup()\n+\n+ opt_list = prob.model.list_options(out_stream=None)\n+\n+ self.assertEqual(len(opt_list), 9)\n+ self.assertTrue(opt_list[1][0] == 'cycle')\n+ self.assertTrue(opt_list[1][2]['maxiter'] == 10)\n+ self.assertTrue(opt_list[3][1]['use_jit'] is True)\n+\n+ opt_dict = prob.model.list_options(out_stream=None, return_format='dict')\n+ self.assertTrue(opt_dict['cycle']['nonlinear_solver']['maxiter'] == 10)\n+ self.assertTrue(opt_dict['cycle']['linear_solver']['use_aitken'] is False)\n+ self.assertTrue(opt_dict['cycle']['options']['auto_order'] is False)\n+\n+ opt_list = prob.model.list_options(out_stream=None, include_solvers=False)\n+ opt_list = prob.model.list_options(out_stream=None, include_solvers=False)\n+ self.assertTrue(opt_list[1][2] is None)\n+ self.assertTrue(opt_list[1][3] is None)\n+\n+ opt_list = prob.model.list_options(out_stream=None, include_solvers=False, include_default=False)\n+ self.assertEqual(len(opt_list[1][1]), 0)\n+\n def test_setup_check_group(self):\n \n class CustomGroup(Group):\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_system.py::TestSystem::test_list_options"]}], "all_FAIL_TO_PASS": ["openmdao/core/tests/test_system.py::TestSystem::test_list_options"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "python-markdown__markdown-743_x1", "level": 1, "source": "swerebenchv2", "repo": "Python-Markdown/markdown", "image": "swerebenchv2/python-markdown-markdown:743-7c78ac3", "base_commit": "7c78ac347b5dcad2be3d8d18b37ec33c96c1eb0b", "num_bugs": 1, "bugs": [{"instance_id": "python-markdown__markdown-743", "base_commit": "7c78ac347b5dcad2be3d8d18b37ec33c96c1eb0b", "gold_patch": "diff --git a/docs/change_log/release-3.1.md b/docs/change_log/release-3.1.md\nindex c05d70f..0e8e2b1 100644\n--- a/docs/change_log/release-3.1.md\n+++ b/docs/change_log/release-3.1.md\n@@ -35,3 +35,4 @@ The following bug fixes are included in the 3.1 release:\n * Block level elements are defined per instance, not as class attributes\n (#731).\n * Double escaping of block code has been eliminated (#725).\n+* Problems with newlines in references has been fixed (#742).\ndiff --git a/markdown/inlinepatterns.py b/markdown/inlinepatterns.py\nindex 3d3e65f..dc502c2 100644\n--- a/markdown/inlinepatterns.py\n+++ b/markdown/inlinepatterns.py\n@@ -617,7 +617,7 @@ class ImageInlineProcessor(LinkInlineProcessor):\n \n class ReferenceInlineProcessor(LinkInlineProcessor):\n \"\"\" Match to a stored reference and return link element. \"\"\"\n- NEWLINE_CLEANUP_RE = re.compile(r'[ ]?\\n', re.MULTILINE)\n+ NEWLINE_CLEANUP_RE = re.compile(r'\\s+', re.MULTILINE)\n \n RE_LINK = re.compile(r'\\s?\\[([^\\]]*)\\]', re.DOTALL | re.UNICODE)\n \n", "test_patch": "diff --git a/tests/test_syntax/inline/test_links.py b/tests/test_syntax/inline/test_links.py\nindex e147c82..988e041 100644\n--- a/tests/test_syntax/inline/test_links.py\n+++ b/tests/test_syntax/inline/test_links.py\n@@ -134,3 +134,40 @@ class TestAdvancedLinks(TestCase):\n '[title](http://example.com/?a=1&b=2)',\n '

    title

    '\n )\n+\n+ def test_reference_newlines(self):\n+ \"\"\"Test reference id whitespace cleanup.\"\"\"\n+\n+ self.assertMarkdownRenders(\n+ self.dedent(\n+ \"\"\"\n+ Two things:\n+\n+ - I would like to tell you about the [code of\n+ conduct][] we are using in this project.\n+ - Only one in fact.\n+\n+ [code of conduct]: https://github.com/Python-Markdown/markdown/blob/master/CODE_OF_CONDUCT.md\n+ \"\"\"\n+ ),\n+ '

    Two things:

    \\n
      \\n
    • I would like to tell you about the '\n+ 'code of\\n'\n+ ' conduct we are using in this project.
    • \\n
    • Only one in fact.
    • \\n
    '\n+ )\n+\n+ def test_reference_across_blocks(self):\n+ \"\"\"Test references across blocks.\"\"\"\n+\n+ self.assertMarkdownRenders(\n+ self.dedent(\n+ \"\"\"\n+ I would like to tell you about the [code of\n+\n+ conduct][] we are using in this project.\n+\n+ [code of conduct]: https://github.com/Python-Markdown/markdown/blob/master/CODE_OF_CONDUCT.md\n+ \"\"\"\n+ ),\n+ '

    I would like to tell you about the [code of

    \\n'\n+ '

    conduct][] we are using in this project.

    '\n+ )\n", "FAIL_TO_PASS": ["tests/test_syntax/inline/test_links.py::TestAdvancedLinks::test_reference_newlines"]}], "all_FAIL_TO_PASS": ["tests/test_syntax/inline/test_links.py::TestAdvancedLinks::test_reference_newlines"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "vmware__tern-255_x1", "level": 1, "source": "swerebenchv2", "repo": "vmware/tern", "image": "swerebenchv2/vmware-tern:255-43c0236", "base_commit": "43c0236e1282af8cb36c8008e015a48135139f2b", "num_bugs": 1, "bugs": [{"instance_id": "vmware__tern-255", "base_commit": "43c0236e1282af8cb36c8008e015a48135139f2b", "gold_patch": "diff --git a/tern/classes/package.py b/tern/classes/package.py\nindex 3e86e82..735202e 100644\n--- a/tern/classes/package.py\n+++ b/tern/classes/package.py\n@@ -17,6 +17,7 @@ class Package:\n pkg_license: package license that is declared\n copyright: copyright text\n src_url: package source url\n+ download_url: package download url\n origins: a list of NoticeOrigin objects\n \n methods:\n@@ -29,6 +30,7 @@ class Package:\n self.__pkg_license = ''\n self.__copyright = ''\n self.__src_url = ''\n+ self.__download_url = ''\n self.__origins = Origins()\n \n @property\n@@ -67,6 +69,14 @@ class Package:\n def src_url(self, src_url):\n self.__src_url = src_url\n \n+ @property\n+ def download_url(self):\n+ return self.__download_url\n+\n+ @download_url.setter\n+ def download_url(self, url):\n+ self.__download_url = url\n+\n @property\n def origins(self):\n return self.__origins\n", "test_patch": "diff --git a/tests/test_class_package.py b/tests/test_class_package.py\nindex 847c6b4..3cababd 100644\n--- a/tests/test_class_package.py\n+++ b/tests/test_class_package.py\n@@ -19,6 +19,7 @@ class TestClassPackage(unittest.TestCase):\n self.p1.pkg_license = 'Apache 2.0'\n self.p1.copyright = 'All Rights Reserved'\n self.p1.src_url = 'github.com'\n+ self.p1.download_url = 'https://github.com'\n \n self.p2 = Package('p2')\n \n@@ -32,6 +33,7 @@ class TestClassPackage(unittest.TestCase):\n self.assertFalse(self.p2.src_url)\n self.assertFalse(self.p2.pkg_license)\n self.assertFalse(self.p2.copyright)\n+ self.assertFalse(self.p2.download_url)\n \n def testSetters(self):\n self.assertRaises(AttributeError, setattr, self.p2, 'name', 'y')\n@@ -43,6 +45,8 @@ class TestClassPackage(unittest.TestCase):\n self.assertEqual(self.p2.copyright, 'All Rights Reserved')\n self.p2.src_url = 'github.com'\n self.assertEqual(self.p2.src_url, 'github.com')\n+ self.p2.download_url = 'https://github.com'\n+ self.assertEqual(self.p2.download_url, 'https://github.com')\n \n def testGetters(self):\n self.assertEqual(self.p1.name, 'p1')\n@@ -50,6 +54,7 @@ class TestClassPackage(unittest.TestCase):\n self.assertEqual(self.p1.pkg_license, 'Apache 2.0')\n self.assertEqual(self.p1.copyright, 'All Rights Reserved')\n self.assertEqual(self.p1.src_url, 'github.com')\n+ self.assertEqual(self.p1.download_url, 'https://github.com')\n \n def testToDict(self):\n a_dict = self.p1.to_dict()\n@@ -58,6 +63,7 @@ class TestClassPackage(unittest.TestCase):\n self.assertEqual(a_dict['pkg_license'], 'Apache 2.0')\n self.assertEqual(a_dict['copyright'], 'All Rights Reserved')\n self.assertEqual(a_dict['src_url'], 'github.com')\n+ self.assertEqual(a_dict['download_url'], 'https://github.com')\n self.assertFalse(a_dict['origins'])\n \n def testToDictTemplate(self):\n@@ -97,12 +103,14 @@ class TestClassPackage(unittest.TestCase):\n self.assertFalse(p.src_url)\n self.assertEqual(len(p.origins.origins), 1)\n self.assertEqual(p.origins.origins[0].origin_str, 'p1')\n- self.assertEqual(len(p.origins.origins[0].notices), 2)\n+ self.assertEqual(len(p.origins.origins[0].notices), 3)\n self.assertEqual(p.origins.origins[0].notices[0].message,\n \"No metadata for key: copyright\")\n self.assertEqual(p.origins.origins[0].notices[0].level, 'warning')\n self.assertEqual(p.origins.origins[0].notices[1].message,\n \"No metadata for key: src_url\")\n+ self.assertEqual(p.origins.origins[0].notices[2].message,\n+ \"No metadata for key: download_url\")\n \n \n if __name__ == '__main__':\n", "FAIL_TO_PASS": ["tests/test_class_package.py::TestClassPackage::testFill", "tests/test_class_package.py::TestClassPackage::testInstance"]}], "all_FAIL_TO_PASS": ["tests/test_class_package.py::TestClassPackage::testFill", "tests/test_class_package.py::TestClassPackage::testInstance"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "vmware__tern-259_x1", "level": 1, "source": "swerebenchv2", "repo": "vmware/tern", "image": "swerebenchv2/vmware-tern:259-fd1e531", "base_commit": "fd1e5319463f0a0dedf346cdd3b147dff2d4e844", "num_bugs": 1, "bugs": [{"instance_id": "vmware__tern-259", "base_commit": "fd1e5319463f0a0dedf346cdd3b147dff2d4e844", "gold_patch": "diff --git a/tern/classes/image.py b/tern/classes/image.py\nindex 4be9a2e..0048878 100644\n--- a/tern/classes/image.py\n+++ b/tern/classes/image.py\n@@ -136,3 +136,14 @@ class Image:\n image_dict.update({'layers': layer_list})\n image_dict.update({'origins': self.origins.to_dict()})\n return image_dict\n+\n+ def get_human_readable_id(self):\n+ '''Some reports like SPDX want a unique name for the full image\n+ and this is currently not supported by any image tool. So using\n+ a combination of image id, name and tag instead'''\n+ name = self.image_id\n+ if self.name:\n+ name = name + '-{}'.format(self.name)\n+ if self.tag:\n+ name = name + '-{}'.format(self.tag)\n+ return name\ndiff --git a/tern/report/content.py b/tern/report/content.py\nindex 6fa7c56..94066d3 100644\n--- a/tern/report/content.py\n+++ b/tern/report/content.py\n@@ -9,8 +9,19 @@ Functions to generate content for the report\n \n import json\n import yaml\n+\n from tern.command_lib import command_lib\n from tern.report import formats\n+from tern.utils.general import get_git_rev_or_version\n+from tern import Version\n+\n+\n+def get_tool_version():\n+ '''Return a string describing the version and where it came from'''\n+ ver_type, ver = get_git_rev_or_version()\n+ if ver_type == 'commit':\n+ return formats.commit_version.format(commit_sha=ver)\n+ return formats.packaged_version.format(version=Version)\n \n \n def print_invoke_list(info_dict, info):\ndiff --git a/tern/report/report.py b/tern/report/report.py\nindex 83ac3f8..5188976 100644\n--- a/tern/report/report.py\n+++ b/tern/report/report.py\n@@ -309,7 +309,7 @@ def generate_report(args, *images):\n def generate_verbose(is_summary, images):\n '''Generate a verbose report'''\n report = formats.disclaimer.format(\n- version_info=general.get_git_rev_or_version())\n+ version_info=content.get_tool_version())\n if is_summary:\n logger.debug('Creating a summary of components in image...')\n for image in images:\ndiff --git a/tern/report/spdxtagvalue/__init__.py b/tern/report/spdxtagvalue/__init__.py\nnew file mode 100644\nindex 0000000..21bda99\n--- /dev/null\n+++ b/tern/report/spdxtagvalue/__init__.py\n@@ -0,0 +1,5 @@\n+# -*- coding: utf-8 -*-\n+#\n+# Copyright (c) 2019 VMware, Inc. All Rights Reserved.\n+# SPDX-License-Identifier: BSD-2-Clause\n+#\ndiff --git a/tern/report/spdxtagvalue/formats.py b/tern/report/spdxtagvalue/formats.py\nnew file mode 100644\nindex 0000000..526fdec\n--- /dev/null\n+++ b/tern/report/spdxtagvalue/formats.py\n@@ -0,0 +1,31 @@\n+# -*- coding: utf-8 -*-\n+#\n+# Copyright (c) 2019 VMware, Inc. All Rights Reserved.\n+# SPDX-License-Identifier: BSD-2-Clause\n+#\n+\"\"\"\n+SPDX document formatting\n+\"\"\"\n+\n+# basic strings\n+tag_value = '{tag}: {value}'\n+\n+# document level strings\n+spdx_version = 'SPDXVersion: SPDX-2.1'\n+data_license = 'DataLicense: CC0-1.0'\n+spdx_id = 'SPDXID: SPDXRef-DOCUMENT'\n+document_name = 'DocumentName: Tern report for {image_name}'\n+document_comment = '''DocumentComment: This document was generated by '''\n+'''the Tern Project at https://github.com/vmware/tern'''\n+document_namespace = 'DocumentNamespace: https://spdx.org/spdxdocs/tern'\n+'-report-{image_id}-{version}'\n+license_list_version = 'LicenseListVersion: 3.4'\n+creator = 'Creator: Tool: tern-{version}'\n+created = 'Created: {timestamp}'\n+\n+# Package level strings\n+package_comment = 'PackageComment: {comment}'\n+\n+# Relationship strings\n+contains = '{outer} CONTAINS {inner}'\n+prereq = '{after} HAS_PREREQUISITE {before}'\ndiff --git a/tern/report/spdxtagvalue/generator.py b/tern/report/spdxtagvalue/generator.py\nnew file mode 100644\nindex 0000000..59b49b0\n--- /dev/null\n+++ b/tern/report/spdxtagvalue/generator.py\n@@ -0,0 +1,225 @@\n+# -*- coding: utf-8 -*-\n+#\n+# Copyright (c) 2019 VMware, Inc. All Rights Reserved.\n+# SPDX-License-Identifier: BSD-2-Clause\n+#\n+\"\"\"\n+SPDX document generator\n+\"\"\"\n+\n+import datetime\n+\n+from tern.classes.templates.spdx import SPDX\n+from tern.utils.general import get_git_rev_or_version\n+from tern.report import content\n+from tern.report.spdxtagvalue import formats as spdx_formats\n+\n+\n+def get_document_namespace(image_obj):\n+ '''Given the image object, return a unique SPDX document uri.\n+ This is a combination of the human readable id from the image\n+ object and the tool name'''\n+ return spdx_formats.document_namespace.format(\n+ image_id=image_obj.get_human_readable_id(),\n+ version=get_git_rev_or_version()[1])\n+\n+\n+def get_package_spdxref(package_obj):\n+ '''Given the package object, return an SPDX reference ID'''\n+ return 'SPDXRef-{}'.format(package_obj.get_package_id())\n+\n+\n+def get_layer_spdxref(layer_obj):\n+ '''Given the layer object, return an SPDX reference ID'''\n+ # here we return the shortened diff_id of the layer\n+ return 'SPDXRef-{}'.format(layer_obj.diff_id[:10])\n+\n+\n+def get_image_spdxref(image_obj):\n+ '''Given the image object, return an SPDX reference ID'''\n+ # here we return the image name, tag and id\n+ return 'SPDXRef-{}'.format(image_obj.get_human_readable_id())\n+\n+\n+def get_document_block(image_obj):\n+ '''Return document related SPDX tag-values'''\n+ block = ''\n+ block = spdx_formats.spdx_version + '\\n'\n+ block = block + spdx_formats.data_license + '\\n'\n+ block = block + spdx_formats.spdx_id + '\\n'\n+ block = block + spdx_formats.document_name.format(\n+ image_name=image_obj.get_human_readable_id()) + '\\n'\n+ block = block + get_document_namespace(image_obj) + '\\n'\n+ block = block + spdx_formats.license_list_version + '\\n'\n+ block = block + spdx_formats.creator.format(\n+ version=get_git_rev_or_version()[1]) + '\\n'\n+ block = block + spdx_formats.created.format(\n+ timestamp=datetime.datetime.utcnow().strftime(\n+ \"%Y-%m-%dT%H:%M:%SZ\")) + '\\n'\n+ return block\n+\n+\n+def get_package_comment(origins):\n+ '''Return a PackageComment tag-value text block for a list of\n+ NoticeOrigin objects'''\n+ comment = ''\n+ if origins:\n+ for notice_origin in origins:\n+ comment = comment + content.print_notices(\n+ notice_origin, '', '\\t')\n+ return spdx_formats.package_comment.format(comment=comment)\n+ return comment\n+\n+\n+def get_main_block(level_dict, origins, **kwargs):\n+ '''Given the dictionary for the level, the list of notices and a list of\n+ key-value pairs, return the SPDX tag-value information for this level'''\n+ block = ''\n+ # insert package comment first\n+ block = get_package_comment(origins) + '\\n'\n+ # list image key and values\n+ for key, value in level_dict.items():\n+ block = block + spdx_formats.tag_value.format(\n+ tag=key, value=value if value else 'NOASSERTION') + '\\n'\n+ # list image specific tag-values\n+ for key, value in kwargs.items():\n+ block = block + spdx_formats.tag_value.format(\n+ tag=key, value=value) + '\\n'\n+ return block\n+\n+\n+def get_image_relationships(image_obj):\n+ '''Given the image object, return the relationships to the layers'''\n+ block = ''\n+ image_reference = get_image_spdxref(image_obj)\n+ for layer in image_obj.layers:\n+ block = block + spdx_formats.contains.format(\n+ outer=image_reference, inner=get_layer_spdxref(layer)) + '\\n'\n+ return block\n+\n+\n+def get_layer_relationships(layer_obj, prev_layer_spdxref=None):\n+ '''Given the layer object, return the relationships of the layer\n+ objects to packages and to the previous layer'''\n+ block = ''\n+ layer_reference = get_layer_spdxref(layer_obj)\n+ if prev_layer_spdxref:\n+ block = block + spdx_formats.prereq.format(\n+ after=layer_reference, before=prev_layer_spdxref)\n+ for package in layer_obj.packages:\n+ block = block + spdx_formats.contains.format(\n+ outer=layer_reference, inner=get_package_spdxref(package)) + '\\n'\n+ return block\n+\n+\n+def generate(image_obj):\n+ '''Given an Image object, generate an SPDX document\n+ The whole document should be stored in a string which can be written\n+ to a file using the write_report function in report.py\n+ First convert the image object into a dictionary. The dictionary\n+ should be in this form:\n+ image:{\n+ origins: [...]\n+ layers: [\n+ {origins: [...],\n+ packages: [\n+ {origins: [...], package1: {...}},\n+ {origins: [...], package2: {...}}...]}, ...]}\n+ Then convert this into a flat format starting from top to bottom\n+ So:\n+ ## image\n+ List all the tag-values here\n+ make a PackageComment: \n+\n+ ## relationships\n+ spdx-ref CONTAINS layer1\n+ spdx-ref CONTAINS layer2\n+ ...\n+\n+ ## layer1\n+ List all the tag-values here\n+ make a PackageComment here\n+\n+ # relationships\n+ spdx-ref CONTAINS package1\n+ spdx-ref CONTAINS package2\n+ ....\n+\n+ # layer2\n+ tag-values\n+ PackageComment\n+\n+ # relationships\n+ spdx-ref HAS_PREREQUISITE layer1\n+ spdx-ref CONTAINS package3\n+ spdx-ref CONTAINS package4\n+\n+ ....\n+\n+ # package1\n+ tag-values\n+ PackageComment\n+\n+ # package2\n+\n+ # package3\n+\n+ # package4\n+\n+\n+ Everything in Origins can be in a tag-value format as\n+ PackageComment: \n+\n+ For the sake of SPDX, an image is a 'Package' which 'CONTAINS'\n+ each layer which is also a 'Package' which 'CONTAINS' the real Package'''\n+ report = ''\n+ template = SPDX()\n+ # The image's PackageDownloadLocation is from a container registry\n+ # This includes all the layers but the packages' download location\n+ # is unknown if the download_url is blank\n+ registry_repotag = image_obj.repotag if hasattr(\n+ image_obj, '__repotag') else 'NOASSERTION'\n+\n+ # first part is the document tag-value\n+ # this doesn't change at all\n+ report = report + get_document_block(image_obj)\n+\n+ # this part is the image part and needs\n+ # the image object\n+ report = report + get_main_block(\n+ image_obj.to_dict(template),\n+ image_obj.origins.origins,\n+ SPDXID=get_image_spdxref(image_obj),\n+ PackageDownloadLocation=registry_repotag,\n+ FilesAnalyzed='false') + '\\n'\n+ # Add image relationships\n+ report = report + get_image_relationships(image_obj) + '\\n'\n+\n+ # Add the layer part for each layer\n+ for index, layer_obj in enumerate(image_obj.layers):\n+ # this is the main block for the layer\n+ report = report + get_main_block(\n+ layer_obj.to_dict(template),\n+ layer_obj.origins.origins,\n+ SDPXID=get_layer_spdxref(layer_obj),\n+ PackageDownloadLocation=registry_repotag,\n+ FilesAnalyzed='false') + '\\n'\n+ # Add layer relationships\n+ if index == 0:\n+ report = report + get_layer_relationships(layer_obj)\n+ else:\n+ # block should contain previous layer dependency\n+ report = report + get_layer_relationships(\n+ layer_obj, get_layer_spdxref(image_obj.layers[index - 1]))\n+\n+ # Add the package part for each package\n+ # There are no relationships to be listed here\n+ for layer_obj in image_obj.layers:\n+ for package_obj in layer_obj.packages:\n+ report = report + get_main_block(\n+ package_obj.to_dict(template),\n+ package_obj.origins.origins,\n+ SPDXID=get_package_spdxref(package_obj),\n+ PackageDownloadLocation='NOASSERTION',\n+ FilesAnalyzed='false') + '\\n'\n+ return report\ndiff --git a/tern/utils/general.py b/tern/utils/general.py\nindex eb91ced..8d74d52 100644\n--- a/tern/utils/general.py\n+++ b/tern/utils/general.py\n@@ -9,7 +9,6 @@ import re\n import subprocess # nosec\n from contextlib import contextmanager\n \n-from tern.report.formats import commit_version, packaged_version\n from tern import Version\n from tern.utils import constants\n \n@@ -77,17 +76,17 @@ def parse_command(command):\n def get_git_rev_or_version():\n '''Assuming we are operating within a git repository, get the SHA\n of the current commit'''\n- command = ['git', 'show', '--format=%H', 'HEAD']\n+ command = ['git', 'rev-parse', 'HEAD']\n try:\n output = subprocess.check_output(command) # nosec\n if isinstance(output, bytes):\n output = output.decode('utf-8')\n-\n- output = commit_version.format(commit_sha=output)\n+ ver_type = 'commit'\n \n except subprocess.CalledProcessError:\n- output = packaged_version.format(version=Version)\n- return output.split('\\n').pop(0)\n+ ver_type = 'package'\n+ output = Version\n+ return ver_type, output.split('\\n').pop(0)\n \n \n def prop_names(obj):\n", "test_patch": "diff --git a/tests/test_class_image.py b/tests/test_class_image.py\nindex d352300..cd7d378 100644\n--- a/tests/test_class_image.py\n+++ b/tests/test_class_image.py\n@@ -36,7 +36,11 @@ class TestClassImage(unittest.TestCase):\n def testLoadImage(self):\n self.assertEqual(self.image2.image_id, '5678efgh')\n self.assertFalse(self.image2.layers)\n+ self.assertFalse(self.image2.name)\n+ self.assertFalse(self.image2.tag)\n self.image2.load_image()\n+ self.assertEqual(self.image2.name, 'testimage')\n+ self.assertEqual(self.image2.tag, 'testtag')\n self.assertEqual(len(self.image2.layers), 1)\n self.assertEqual(len(self.image2.layers[0].packages), 2)\n \n@@ -70,6 +74,12 @@ class TestClassImage(unittest.TestCase):\n self.assertFalse(dict2['image.layers'][0]['notes'])\n self.assertEqual(len(dict2['image.layers'][0]['layer.packages']), 2)\n \n+ def testGetHumanReadableId(self):\n+ self.assertEqual(self.image1.get_human_readable_id(), '1234abcd')\n+ self.image2.load_image()\n+ self.assertEqual(\n+ self.image2.get_human_readable_id(), '5678efgh-testimage-testtag')\n+\n \n if __name__ == '__main__':\n unittest.main()\ndiff --git a/tests/test_fixtures.py b/tests/test_fixtures.py\nindex 256957d..0d3a946 100644\n--- a/tests/test_fixtures.py\n+++ b/tests/test_fixtures.py\n@@ -19,6 +19,8 @@ class TestImage(Image):\n \n def load_image(self):\n l1 = ImageLayer('123abc', 'path/to/tar')\n+ self.name = 'testimage'\n+ self.tag = 'testtag'\n l1.add_package(Package('p1'))\n l1.add_package(Package('p2'))\n self._layers.append(l1)\n", "FAIL_TO_PASS": ["tests/test_class_image.py::TestClassImage::testGetHumanReadableId"]}], "all_FAIL_TO_PASS": ["tests/test_class_image.py::TestClassImage::testGetHumanReadableId"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tox-dev__pipdeptree-195_x1", "level": 1, "source": "swerebenchv2", "repo": "tox-dev/pipdeptree", "image": "swerebenchv2/tox-dev-pipdeptree:195-96a2341", "base_commit": "96a23415b0a86cc042a9cd80724dc6d89af09761", "num_bugs": 1, "bugs": [{"instance_id": "tox-dev__pipdeptree-195", "base_commit": "96a23415b0a86cc042a9cd80724dc6d89af09761", "gold_patch": "diff --git a/src/pipdeptree/__init__.py b/src/pipdeptree/__init__.py\nindex 7679212..e269d4c 100644\n--- a/src/pipdeptree/__init__.py\n+++ b/src/pipdeptree/__init__.py\n@@ -10,6 +10,7 @@ from collections import defaultdict, deque\n from collections.abc import Mapping\n from importlib import import_module\n from itertools import chain\n+from textwrap import dedent\n \n from pip._vendor import pkg_resources\n \n@@ -550,6 +551,44 @@ def render_json_tree(tree, indent):\n return json.dumps([aux(p) for p in nodes], indent=indent)\n \n \n+def render_mermaid(tree) -> str:\n+ \"\"\"Produce a Mermaid flowchart from the dependency graph.\n+\n+ :param dict tree: dependency graph\n+ \"\"\"\n+ # Use a sets to avoid duplicate entries.\n+ nodes: set[str] = set()\n+ edges: set[str] = set()\n+\n+ for pkg, deps in tree.items():\n+ pkg_label = f\"{pkg.project_name}\\\\n{pkg.version}\"\n+ nodes.add(f\"{pkg.key}[{pkg_label}]\")\n+ for dep in deps:\n+ edge_label = dep.version_spec or \"any\"\n+ if dep.is_missing:\n+ dep_label = f\"{dep.project_name}\\\\n(missing)\"\n+ nodes.add(f\"{dep.key}[{dep_label}]:::missing\")\n+ edges.add(f\"{pkg.key} -.-> {dep.key}\")\n+ else:\n+ edges.add(f\"{pkg.key} -- {edge_label} --> {dep.key}\")\n+\n+ # Produce the Mermaid Markdown.\n+ indent = \" \" * 4\n+ output = dedent(\n+ f\"\"\"\\\n+ flowchart TD\n+ {indent}classDef missing stroke-dasharray: 5\n+ \"\"\"\n+ )\n+ # Sort the nodes and edges to make the output deterministic.\n+ output += indent\n+ output += f\"\\n{indent}\".join(node for node in sorted(nodes))\n+ output += \"\\n\" + indent\n+ output += f\"\\n{indent}\".join(edge for edge in sorted(edges))\n+ output += \"\\n\"\n+ return output\n+\n+\n def dump_graphviz(tree, output_format=\"dot\", is_reverse=False):\n \"\"\"Output dependency graph as one of the supported GraphViz output formats.\n \n@@ -775,6 +814,12 @@ def get_parser():\n \"This option overrides all other options (except --json).\"\n ),\n )\n+ parser.add_argument(\n+ \"--mermaid\",\n+ action=\"store_true\",\n+ default=False,\n+ help=(\"Display dependency tree as a Maermaid graph. \" \"This option overrides all other options.\"),\n+ )\n parser.add_argument(\n \"--graph-output\",\n dest=\"output_format\",\n@@ -884,6 +929,8 @@ def main():\n print(render_json(tree, indent=4))\n elif args.json_tree:\n print(render_json_tree(tree, indent=4))\n+ elif args.output_format:\n+ print(render_mermaid(tree))\n elif args.output_format:\n output = dump_graphviz(tree, output_format=args.output_format, is_reverse=args.reverse)\n print_graphviz(output)\n", "test_patch": "diff --git a/tests/test_pipdeptree.py b/tests/test_pipdeptree.py\nindex 3a7aa01..ef95065 100644\n--- a/tests/test_pipdeptree.py\n+++ b/tests/test_pipdeptree.py\n@@ -306,8 +306,9 @@ def test_render_text(capsys, list_all, reverse, expected_output):\n # Tests for graph outputs\n \n \n-def test_render_dot(capsys):\n- # Extract the dependency graph from the package tree fixture and randomize it.\n+def randomized_dag_copy(t):\n+ \"\"\"Returns a copy of the package tree fixture with dependencies in randomized order.\"\"\"\n+ # Extract the dependency graph from the package tree and randomize it.\n randomized_graph = {}\n randomized_nodes = list(t._obj.keys())\n random.shuffle(randomized_nodes)\n@@ -320,10 +321,42 @@ def test_render_dot(capsys):\n # Create a randomized package tree.\n randomized_dag = p.PackageDAG(randomized_graph)\n assert len(t) == len(randomized_dag)\n+ return randomized_dag\n+\n+\n+def test_render_mermaid():\n+ # Check both the sorted and randomized package tree produces the same sorted\n+ # Mermaid output.\n+ for package_tree in (t, randomized_dag_copy(t)):\n+ output = p.render_mermaid(package_tree)\n+ assert output == dedent(\n+ \"\"\"\\\n+ flowchart TD\n+ classDef missing stroke-dasharray: 5\n+ a[a\\\\n3.4.0]\n+ b[b\\\\n2.3.1]\n+ c[c\\\\n5.10.0]\n+ d[d\\\\n2.35]\n+ e[e\\\\n0.12.1]\n+ f[f\\\\n3.1]\n+ g[g\\\\n6.8.3rc1]\n+ a -- >=2.0.0 --> b\n+ a -- >=5.7.1 --> c\n+ b -- >=2.30,<2.42 --> d\n+ c -- >=0.12.1 --> e\n+ c -- >=2.30 --> d\n+ d -- >=0.9.0 --> e\n+ f -- >=2.1.0 --> b\n+ g -- >=0.9.0 --> e\n+ g -- >=3.0.0 --> f\n+ \"\"\"\n+ )\n \n+\n+def test_render_dot(capsys):\n # Check both the sorted and randomized package tree produces the same sorted\n # graphviz output.\n- for package_tree in (t, randomized_dag):\n+ for package_tree in (t, randomized_dag_copy(t)):\n output = p.dump_graphviz(package_tree, output_format=\"dot\")\n p.print_graphviz(output)\n out, _ = capsys.readouterr()\n@@ -499,6 +532,14 @@ def test_parser_json_tree():\n assert args.output_format is None\n \n \n+def test_parser_mermaid():\n+ parser = p.get_parser()\n+ args = parser.parse_args([\"--mermaid\"])\n+ assert args.mermaid\n+ assert not args.json\n+ assert args.output_format is None\n+\n+\n def test_parser_pdf():\n parser = p.get_parser()\n args = parser.parse_args([\"--graph-output\", \"pdf\"])\n", "FAIL_TO_PASS": ["tests/test_pipdeptree.py::test_render_mermaid", "tests/test_pipdeptree.py::test_parser_mermaid"]}], "all_FAIL_TO_PASS": ["tests/test_pipdeptree.py::test_render_mermaid", "tests/test_pipdeptree.py::test_parser_mermaid"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getmoto__moto-5873_x1", "level": 1, "source": "swerebenchv2", "repo": "getmoto/moto", "image": "swerebenchv2/getmoto-moto:5873-667c40e", "base_commit": "667c40e58a1dbf4a2619660464a845d2b5195cf7", "num_bugs": 1, "bugs": [{"instance_id": "getmoto__moto-5873", "base_commit": "667c40e58a1dbf4a2619660464a845d2b5195cf7", "gold_patch": "diff --git a/moto/cognitoidp/models.py b/moto/cognitoidp/models.py\nindex e8857f510..3ddb8f113 100644\n--- a/moto/cognitoidp/models.py\n+++ b/moto/cognitoidp/models.py\n@@ -1429,7 +1429,7 @@ class CognitoIdpBackend(BaseBackend):\n }\n \n return self._log_user_in(user_pool, client, username)\n- elif auth_flow is AuthFlow.REFRESH_TOKEN:\n+ elif auth_flow in (AuthFlow.REFRESH_TOKEN, AuthFlow.REFRESH_TOKEN_AUTH):\n refresh_token: str = auth_parameters.get(\"REFRESH_TOKEN\") # type: ignore[assignment]\n (\n access_token,\ndiff --git a/moto/dynamodb/models/table.py b/moto/dynamodb/models/table.py\nindex 483897246..6c95500ce 100644\n--- a/moto/dynamodb/models/table.py\n+++ b/moto/dynamodb/models/table.py\n@@ -34,6 +34,7 @@ class SecondaryIndex(BaseModel):\n self.schema = schema\n self.table_key_attrs = table_key_attrs\n self.projection = projection\n+ self.schema_key_attrs = [k[\"AttributeName\"] for k in schema]\n \n def project(self, item: Item) -> Item:\n \"\"\"\ndiff --git a/moto/dynamodb/responses.py b/moto/dynamodb/responses.py\nindex 54f3abe72..2108f4b4f 100644\n--- a/moto/dynamodb/responses.py\n+++ b/moto/dynamodb/responses.py\n@@ -79,12 +79,17 @@ def include_consumed_capacity(\n return _inner\n \n \n-def get_empty_keys_on_put(field_updates: Dict[str, Any], table: Table) -> Optional[str]:\n+def validate_put_has_empty_keys(\n+ field_updates: Dict[str, Any], table: Table, custom_error_msg: Optional[str] = None\n+) -> None:\n \"\"\"\n- Return the first key-name that has an empty value. None if all keys are filled\n+ Error if any keys have an empty value. Checks Global index attributes as well\n \"\"\"\n if table:\n key_names = table.attribute_keys\n+ gsi_key_names = list(\n+ itertools.chain(*[gsi.schema_key_attrs for gsi in table.global_indexes])\n+ )\n \n # string/binary fields with empty string as value\n empty_str_fields = [\n@@ -92,10 +97,27 @@ def get_empty_keys_on_put(field_updates: Dict[str, Any], table: Table) -> Option\n for (key, val) in field_updates.items()\n if next(iter(val.keys())) in [\"S\", \"B\"] and next(iter(val.values())) == \"\"\n ]\n- return next(\n+\n+ # First validate that all of the GSI-keys are set\n+ empty_gsi_key = next(\n+ (kn for kn in gsi_key_names if kn in empty_str_fields), None\n+ )\n+ if empty_gsi_key:\n+ gsi_name = table.global_indexes[0].name\n+ raise MockValidationException(\n+ f\"One or more parameter values are not valid. A value specified for a secondary index key is not supported. The AttributeValue for a key attribute cannot contain an empty string value. IndexName: {gsi_name}, IndexKey: {empty_gsi_key}\"\n+ )\n+\n+ # Then validate that all of the regular keys are set\n+ empty_key = next(\n (keyname for keyname in key_names if keyname in empty_str_fields), None\n )\n- return None\n+ if empty_key:\n+ msg = (\n+ custom_error_msg\n+ or \"One or more parameter values were invalid: An AttributeValue may not contain an empty string. Key: {}\"\n+ )\n+ raise MockValidationException(msg.format(empty_key))\n \n \n def put_has_empty_attrs(field_updates: Dict[str, Any], table: Table) -> bool:\n@@ -401,11 +423,7 @@ class DynamoHandler(BaseResponse):\n raise MockValidationException(\"Return values set to invalid value\")\n \n table = self.dynamodb_backend.get_table(name)\n- empty_key = get_empty_keys_on_put(item, table)\n- if empty_key:\n- raise MockValidationException(\n- f\"One or more parameter values were invalid: An AttributeValue may not contain an empty string. Key: {empty_key}\"\n- )\n+ validate_put_has_empty_keys(item, table)\n if put_has_empty_attrs(item, table):\n raise MockValidationException(\n \"One or more parameter values were invalid: An number set may not be empty\"\n@@ -462,11 +480,11 @@ class DynamoHandler(BaseResponse):\n request = list(table_request.values())[0]\n if request_type == \"PutRequest\":\n item = request[\"Item\"]\n- empty_key = get_empty_keys_on_put(item, table)\n- if empty_key:\n- raise MockValidationException(\n- f\"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: {empty_key}\"\n- )\n+ validate_put_has_empty_keys(\n+ item,\n+ table,\n+ custom_error_msg=\"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: {}\",\n+ )\n put_requests.append((table_name, item))\n elif request_type == \"DeleteRequest\":\n keys = request[\"Key\"]\n@@ -1004,6 +1022,12 @@ class DynamoHandler(BaseResponse):\n \n def transact_write_items(self) -> str:\n transact_items = self.body[\"TransactItems\"]\n+ # Validate first - we should error before we start the transaction\n+ for item in transact_items:\n+ if \"Put\" in item:\n+ item_attrs = item[\"Put\"][\"Item\"]\n+ table = self.dynamodb_backend.get_table(item[\"Put\"][\"TableName\"])\n+ validate_put_has_empty_keys(item_attrs, table)\n self.dynamodb_backend.transact_write_items(transact_items)\n response: Dict[str, Any] = {\"ConsumedCapacity\": [], \"ItemCollectionMetrics\": {}}\n return dynamo_json_dump(response)\n", "test_patch": "diff --git a/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py b/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py\nindex ebb7c13cc..4f4cc7489 100644\n--- a/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py\n+++ b/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py\n@@ -803,6 +803,45 @@ def test_transact_write_items_multiple_operations_fail():\n )\n \n \n+@mock_dynamodb\n+def test_transact_write_items_with_empty_gsi_key():\n+ client = boto3.client(\"dynamodb\", \"us-east-2\")\n+\n+ client.create_table(\n+ TableName=\"test_table\",\n+ KeySchema=[{\"AttributeName\": \"unique_code\", \"KeyType\": \"HASH\"}],\n+ AttributeDefinitions=[\n+ {\"AttributeName\": \"unique_code\", \"AttributeType\": \"S\"},\n+ {\"AttributeName\": \"unique_id\", \"AttributeType\": \"S\"},\n+ ],\n+ GlobalSecondaryIndexes=[\n+ {\n+ \"IndexName\": \"gsi_index\",\n+ \"KeySchema\": [{\"AttributeName\": \"unique_id\", \"KeyType\": \"HASH\"}],\n+ \"Projection\": {\"ProjectionType\": \"ALL\"},\n+ }\n+ ],\n+ ProvisionedThroughput={\"ReadCapacityUnits\": 5, \"WriteCapacityUnits\": 5},\n+ )\n+\n+ transact_items = [\n+ {\n+ \"Put\": {\n+ \"Item\": {\"unique_code\": {\"S\": \"some code\"}, \"unique_id\": {\"S\": \"\"}},\n+ \"TableName\": \"test_table\",\n+ }\n+ }\n+ ]\n+\n+ with pytest.raises(ClientError) as exc:\n+ client.transact_write_items(TransactItems=transact_items)\n+ err = exc.value.response[\"Error\"]\n+ err[\"Code\"].should.equal(\"ValidationException\")\n+ err[\"Message\"].should.equal(\n+ \"One or more parameter values are not valid. A value specified for a secondary index key is not supported. The AttributeValue for a key attribute cannot contain an empty string value. IndexName: gsi_index, IndexKey: unique_id\"\n+ )\n+\n+\n @mock_dynamodb\n def test_update_primary_key_with_sortkey():\n dynamodb = boto3.resource(\"dynamodb\", region_name=\"us-east-1\")\n", "FAIL_TO_PASS": ["tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py::test_transact_write_items_with_empty_gsi_key"]}], "all_FAIL_TO_PASS": ["tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py::test_transact_write_items_with_empty_gsi_key"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "python-markdown__markdown-785_x1", "level": 1, "source": "swerebenchv2", "repo": "Python-Markdown/markdown", "image": "swerebenchv2/python-markdown-markdown:785-9ec83c4", "base_commit": "9ec83c4c414f27bc8aa490dbac1fe30b49058ae6", "num_bugs": 1, "bugs": [{"instance_id": "python-markdown__markdown-785", "base_commit": "9ec83c4c414f27bc8aa490dbac1fe30b49058ae6", "gold_patch": "diff --git a/docs/change_log/release-3.1.md b/docs/change_log/release-3.1.md\nindex 5c225cf..c5f0433 100644\n--- a/docs/change_log/release-3.1.md\n+++ b/docs/change_log/release-3.1.md\n@@ -31,6 +31,7 @@ The following new features have been included in the release:\n \n The following bug fixes are included in the 3.1 release:\n \n+* Emphasis patterns now recognize newline characters as whitespace (#783).\n * Version format had been updated to be PEP 440 compliant (#736).\n * Block level elements are defined per instance, not as class attributes\n (#731).\ndiff --git a/markdown/inlinepatterns.py b/markdown/inlinepatterns.py\nindex dc502c2..88e8ead 100644\n--- a/markdown/inlinepatterns.py\n+++ b/markdown/inlinepatterns.py\n@@ -144,7 +144,7 @@ REFERENCE_RE = LINK_RE\n IMAGE_REFERENCE_RE = IMAGE_LINK_RE\n \n # stand-alone * or _\n-NOT_STRONG_RE = r'((^| )(\\*|_)( |$))'\n+NOT_STRONG_RE = r'((^|\\s)(\\*|_)(\\s|$))'\n \n # \n AUTOLINK_RE = r'<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^>]*)>'\n", "test_patch": "diff --git a/tests/test_syntax/inline/test_emphasis.py b/tests/test_syntax/inline/test_emphasis.py\nnew file mode 100644\nindex 0000000..d96861b\n--- /dev/null\n+++ b/tests/test_syntax/inline/test_emphasis.py\n@@ -0,0 +1,86 @@\n+# -*- coding: utf-8 -*-\n+\"\"\"\n+Python Markdown\n+\n+A Python implementation of John Gruber's Markdown.\n+\n+Documentation: https://python-markdown.github.io/\n+GitHub: https://github.com/Python-Markdown/markdown/\n+PyPI: https://pypi.org/project/Markdown/\n+\n+Started by Manfred Stienstra (http://www.dwerg.net/).\n+Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).\n+Currently maintained by Waylan Limberg (https://github.com/waylan),\n+Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).\n+\n+Copyright 2007-2019 The Python Markdown Project (v. 1.7 and later)\n+Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)\n+Copyright 2004 Manfred Stienstra (the original version)\n+\n+License: BSD (see LICENSE.md for details).\n+\"\"\"\n+\n+from markdown.test_tools import TestCase\n+\n+\n+class TestNotEmphasis(TestCase):\n+\n+ def test_standalone_asterisk(self):\n+ self.assertMarkdownRenders(\n+ '*',\n+ '

    *

    '\n+ )\n+\n+ def test_standalone_understore(self):\n+ self.assertMarkdownRenders(\n+ '_',\n+ '

    _

    '\n+ )\n+\n+ def test_standalone_asterisk_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo * bar',\n+ '

    foo * bar

    '\n+ )\n+\n+ def test_standalone_understore_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo _ bar',\n+ '

    foo _ bar

    '\n+ )\n+\n+ def test_standalone_asterisks_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo * bar * baz',\n+ '

    foo * bar * baz

    '\n+ )\n+\n+ def test_standalone_understores_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo _ bar _ baz',\n+ '

    foo _ bar _ baz

    '\n+ )\n+\n+ def test_standalone_asterisks_with_newlines(self):\n+ self.assertMarkdownRenders(\n+ 'foo\\n* bar *\\nbaz',\n+ '

    foo\\n* bar *\\nbaz

    '\n+ )\n+\n+ def test_standalone_understores_with_newlines(self):\n+ self.assertMarkdownRenders(\n+ 'foo\\n_ bar _\\nbaz',\n+ '

    foo\\n_ bar _\\nbaz

    '\n+ )\n+\n+ def test_standalone_asterisks_at_end(self):\n+ self.assertMarkdownRenders(\n+ 'foo * bar *',\n+ '

    foo * bar *

    '\n+ )\n+\n+ def test_standalone_understores_at_begin_end(self):\n+ self.assertMarkdownRenders(\n+ '_ bar _',\n+ '

    _ bar _

    '\n+ )\n", "FAIL_TO_PASS": ["tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_asterisks_with_newlines", "tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_understores_with_newlines"]}], "all_FAIL_TO_PASS": ["tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_asterisks_with_newlines", "tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_understores_with_newlines"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3522_x1", "level": 1, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3522-97f89e5", "base_commit": "97f89e58f032013f7fa7f6a7da45880b45059bd9", "num_bugs": 1, "bugs": [{"instance_id": "openmdao__openmdao-3522", "base_commit": "97f89e58f032013f7fa7f6a7da45880b45059bd9", "gold_patch": "diff --git a/openmdao/core/problem.py b/openmdao/core/problem.py\nindex a3b496ba0..ad35a6a6d 100644\n--- a/openmdao/core/problem.py\n+++ b/openmdao/core/problem.py\n@@ -492,7 +492,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n \"\"\"\n return self.get_val(name, get_remote=None)\n \n- def get_val(self, name, units=None, indices=None, get_remote=False):\n+ def get_val(self, name, units=None, indices=None, get_remote=False, copy=False):\n \"\"\"\n Get an output/input variable.\n \n@@ -513,6 +513,8 @@ class Problem(object, metaclass=ProblemMetaclass):\n If False, only retrieve the value if it is on the current process, or only the part\n of the value that's on the current process for a distributed variable.\n If None and the variable is remote or distributed, a RuntimeError will be raised.\n+ copy : bool, optional\n+ If True, return a copy of the value. If False, return a reference to the value.\n \n Returns\n -------\n@@ -539,7 +541,10 @@ class Problem(object, metaclass=ProblemMetaclass):\n f\"rank {self.comm.rank}. You can retrieve values from \"\n \"other processes using `get_val(, get_remote=True)`.\")\n \n- return val\n+ if copy:\n+ return deepcopy(val)\n+ else:\n+ return val\n \n def __setitem__(self, name, value):\n \"\"\"\ndiff --git a/openmdao/core/system.py b/openmdao/core/system.py\nindex c75ec7ffa..c656dcb80 100644\n--- a/openmdao/core/system.py\n+++ b/openmdao/core/system.py\n@@ -5,6 +5,7 @@ import hashlib\n import pathlib\n import time\n import functools\n+from copy import deepcopy\n from contextlib import contextmanager\n from collections import defaultdict\n from itertools import chain\n@@ -5544,7 +5545,7 @@ class System(object, metaclass=SystemMetaclass):\n return val\n \n def get_val(self, name, units=None, indices=None, get_remote=False, rank=None,\n- vec_name='nonlinear', kind=None, flat=False, from_src=True):\n+ vec_name='nonlinear', kind=None, flat=False, from_src=True, copy=False):\n \"\"\"\n Get an output/input/residual variable.\n \n@@ -5576,6 +5577,8 @@ class System(object, metaclass=SystemMetaclass):\n If True, return the flattened version of the value.\n from_src : bool\n If True, retrieve value of an input variable from its connected source.\n+ copy : bool, optional\n+ If True, return a copy of the value. If False, return a reference to the value.\n \n Returns\n -------\n@@ -5597,9 +5600,9 @@ class System(object, metaclass=SystemMetaclass):\n else:\n # src is outside of this system so get the value from the model\n caller = self._problem_meta['model_ref']()\n- return caller._get_input_from_src(name, abs_names, conns, units=simp_units,\n- indices=indices, get_remote=get_remote, rank=rank,\n- vec_name=vec_name, flat=flat, scope_sys=self)\n+ val = caller._get_input_from_src(name, abs_names, conns, units=simp_units,\n+ indices=indices, get_remote=get_remote, rank=rank,\n+ vec_name=vec_name, flat=flat, scope_sys=self)\n else:\n val = self._abs_get_val(abs_names[0], get_remote, rank, vec_name, kind, flat)\n \n@@ -5609,7 +5612,10 @@ class System(object, metaclass=SystemMetaclass):\n if units is not None:\n val = self.convert2units(abs_names[0], val, simp_units)\n \n- return val\n+ if copy:\n+ return deepcopy(val)\n+ else:\n+ return val\n \n def _get_cached_val(self, name, abs_names, get_remote=False):\n # We have set and cached already\n", "test_patch": "diff --git a/openmdao/core/tests/test_problem.py b/openmdao/core/tests/test_problem.py\nindex 1fa86e3f6..bb5e1eeba 100644\n--- a/openmdao/core/tests/test_problem.py\n+++ b/openmdao/core/tests/test_problem.py\n@@ -31,6 +31,56 @@ except ImportError:\n \n @use_tempdirs\n class TestProblem(unittest.TestCase):\n+\n+ def test_get_val(self):\n+ class TestComp(om.ExplicitComponent):\n+ def setup(self):\n+ self.add_input('foo', shape=(3,))\n+ self.add_discrete_input('mul', val=1)\n+\n+ self.add_output('bar', shape=(3,))\n+ # add a mutable NumPy array as an output\n+ self.add_discrete_output('obj', val=np.array([1, 'm', [2, 3, 4]], dtype=object))\n+\n+ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n+ outputs['bar'] = discrete_inputs['mul']*inputs['foo']\n+\n+ p = om.Problem()\n+ p.model.add_subsystem('comp', TestComp(), promotes=['*'])\n+ p.setup()\n+\n+ p.set_val('foo', np.array([5., 5., 5.]))\n+ p.set_val('mul', 100)\n+ p.run_model()\n+\n+ foo = p.get_val('foo')\n+ mul = p.get_val('mul')\n+ bar = p.get_val('bar')\n+ obj = p.get_val('obj')\n+\n+ self.assertTrue(np.array_equal(foo, np.array([5., 5., 5.])))\n+ self.assertEqual(mul, 100)\n+ self.assertTrue(np.array_equal(bar, np.array([500., 500., 500.])))\n+\n+ foo_copy = p.get_val('foo', copy=True)\n+ mul_copy = p.get_val('mul', copy=True)\n+ bar_copy = p.get_val('bar', copy=True)\n+ obj_copy = p.get_val('obj', copy=True)\n+\n+ self.assertTrue(np.array_equal(foo_copy, np.array([5., 5., 5.])))\n+ self.assertEqual(mul_copy, 100)\n+ self.assertTrue(np.array_equal(bar_copy, np.array([500., 500., 500.])))\n+\n+ self.assertTrue(id(foo) != id(foo_copy), f\"'foo' is not a copy, {id(foo)=} {id(foo_copy)=}\")\n+ self.assertTrue(id(mul) == id(mul_copy), f\"'mul' is a copy, {id(foo)=} {id(foo_copy)=}\") # mul is a scalar\n+ self.assertTrue(id(bar) != id(bar_copy), f\"'bar' is not a copy, {id(bar)=} {id(bar_copy)=}\")\n+ self.assertTrue(id(obj) != id(obj_copy), f\"'obj' is not a copy, {id(obj)=} {id(obj_copy)=}\")\n+\n+ obj[2][0] = 10\n+ self.assertEqual(obj[2][0], 10)\n+ self.assertEqual(p.get_val('obj')[2][0], 10) # the value in the problem was modified\n+ self.assertEqual(obj_copy[2][0], 2) # the value in the copy was not modified\n+\n def test_simple_component_model_with_units(self):\n class TestComp(om.ExplicitComponent):\n def setup(self):\ndiff --git a/openmdao/core/tests/test_system.py b/openmdao/core/tests/test_system.py\nindex 4f5ad1637..f69348752 100644\n--- a/openmdao/core/tests/test_system.py\n+++ b/openmdao/core/tests/test_system.py\n@@ -13,6 +13,57 @@ from openmdao.utils.file_utils import _get_work_dir\n @use_tempdirs\n class TestSystem(unittest.TestCase):\n \n+ def test_get_val(self):\n+ import openmdao.api as om\n+\n+ class TestComp(om.ExplicitComponent):\n+ def setup(self):\n+ self.add_input('foo', shape=(3,))\n+ self.add_discrete_input('mul', val=1)\n+\n+ self.add_output('bar', shape=(3,))\n+ # add a mutable NumPy array as an output\n+ self.add_discrete_output('obj', val=np.array([1, 'm', [2, 3, 4]], dtype=object))\n+\n+ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n+ outputs['bar'] = discrete_inputs['mul']*inputs['foo']\n+\n+ p = om.Problem()\n+ comp = p.model.add_subsystem('comp', TestComp(), promotes=['*'])\n+ p.setup()\n+\n+ p.set_val('foo', np.array([5., 5., 5.]))\n+ p.set_val('mul', 100)\n+ p.run_model()\n+\n+ foo = comp.get_val('foo')\n+ mul = comp.get_val('mul')\n+ bar = comp.get_val('bar')\n+ obj = comp.get_val('obj')\n+\n+ self.assertTrue(np.array_equal(foo, np.array([5., 5., 5.])))\n+ self.assertEqual(mul, 100)\n+ self.assertTrue(np.array_equal(bar, np.array([500., 500., 500.])))\n+\n+ foo_copy = comp.get_val('foo', copy=True)\n+ mul_copy = comp.get_val('mul', copy=True)\n+ bar_copy = comp.get_val('bar', copy=True)\n+ obj_copy = comp.get_val('obj', copy=True)\n+\n+ self.assertTrue(np.array_equal(foo_copy, np.array([5., 5., 5.])))\n+ self.assertEqual(mul_copy, 100)\n+ self.assertTrue(np.array_equal(bar_copy, np.array([500., 500., 500.])))\n+\n+ self.assertTrue(id(foo) != id(foo_copy), f\"'foo' is not a copy, {id(foo)=} {id(foo_copy)=}\")\n+ self.assertTrue(id(mul) == id(mul_copy), f\"'mul' is a copy, {id(foo)=} {id(foo_copy)=}\") # mul is a scalar\n+ self.assertTrue(id(bar) != id(bar_copy), f\"'bar' is not a copy, {id(bar)=} {id(bar_copy)=}\")\n+ self.assertTrue(id(obj) != id(obj_copy), f\"'obj' is not a copy, {id(obj)=} {id(obj_copy)=}\")\n+\n+ obj[2][0] = 10\n+ self.assertEqual(obj[2][0], 10)\n+ self.assertEqual(comp.get_val('obj')[2][0], 10) # the value in the system was modified\n+ self.assertEqual(obj_copy[2][0], 2) # the value in the copy was not modified\n+\n def test_vector_context_managers(self):\n g1 = Group()\n g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a'])\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_get_val", "openmdao/core/tests/test_system.py::TestSystem::test_get_val"]}], "all_FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_get_val", "openmdao/core/tests/test_system.py::TestSystem::test_get_val"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tox-dev__pipdeptree-239_x1", "level": 1, "source": "swerebenchv2", "repo": "tox-dev/pipdeptree", "image": "swerebenchv2/tox-dev-pipdeptree:239-c23f8a3", "base_commit": "c23f8a32aa53c6d3829dd3d3d13a8a1f8fc15713", "num_bugs": 1, "bugs": [{"instance_id": "tox-dev__pipdeptree-239", "base_commit": "c23f8a32aa53c6d3829dd3d3d13a8a1f8fc15713", "gold_patch": "diff --git a/src/pipdeptree/__init__.py b/src/pipdeptree/__init__.py\nindex 3c9b424..8b9fa09 100644\n--- a/src/pipdeptree/__init__.py\n+++ b/src/pipdeptree/__init__.py\n@@ -462,16 +462,90 @@ def render_text(tree, list_all=True, frozen=False):\n :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies\n :param bool frozen: show the names of the pkgs in the output that's favourable to pip --freeze\n :returns: None\n-\n \"\"\"\n tree = tree.sort()\n nodes = tree.keys()\n branch_keys = {r.key for r in chain.from_iterable(tree.values())}\n- use_bullets = not frozen\n \n if not list_all:\n nodes = [p for p in nodes if p.key not in branch_keys]\n \n+ if sys.stdout.encoding.lower() in (\"utf-8\", \"utf-16\", \"utf-32\"):\n+ _render_text_with_unicode(tree, nodes, frozen)\n+ else:\n+ _render_text_without_unicode(tree, nodes, frozen)\n+\n+\n+def _render_text_with_unicode(tree, nodes, frozen):\n+ use_bullets = not frozen\n+\n+ def aux(\n+ node,\n+ parent=None,\n+ indent=0,\n+ cur_chain=None,\n+ prefix=\"\",\n+ depth=0,\n+ has_grand_parent=False,\n+ is_last_child=False,\n+ parent_is_last_child=False,\n+ ):\n+ cur_chain = cur_chain or []\n+ node_str = node.render(parent, frozen)\n+ next_prefix = \"\"\n+ next_indent = indent + 2\n+\n+ if parent:\n+ bullet = \"\u251c\u2500\u2500 \"\n+ if is_last_child:\n+ bullet = \"\u2514\u2500\u2500 \"\n+\n+ line_char = \"\u2502\"\n+ if not use_bullets:\n+ line_char = \"\"\n+ # Add 2 spaces so direct dependencies to a project are indented\n+ bullet = \" \"\n+\n+ if has_grand_parent:\n+ next_indent -= 1\n+ if parent_is_last_child:\n+ offset = 0 if len(line_char) == 1 else 1\n+ prefix += \" \" * (indent + 1 - offset - depth)\n+ else:\n+ prefix += line_char + \" \" * (indent - depth)\n+ # Without this extra space, bullets will point to the space just before the project name\n+ prefix += \" \" if use_bullets else \"\"\n+ next_prefix = prefix\n+ node_str = prefix + bullet + node_str\n+ result = [node_str]\n+\n+ children = tree.get_children(node.key)\n+ children_strings = [\n+ aux(\n+ c,\n+ node,\n+ indent=next_indent,\n+ cur_chain=cur_chain + [c.project_name],\n+ prefix=next_prefix,\n+ depth=depth + 1,\n+ has_grand_parent=parent is not None,\n+ is_last_child=c is children[-1],\n+ parent_is_last_child=is_last_child,\n+ )\n+ for c in children\n+ if c.project_name not in cur_chain\n+ ]\n+\n+ result += list(chain.from_iterable(children_strings))\n+ return result\n+\n+ lines = chain.from_iterable([aux(p) for p in nodes])\n+ print(\"\\n\".join(lines))\n+\n+\n+def _render_text_without_unicode(tree, nodes, frozen):\n+ use_bullets = not frozen\n+\n def aux(node, parent=None, indent=0, cur_chain=None):\n cur_chain = cur_chain or []\n node_str = node.render(parent, frozen)\n", "test_patch": "diff --git a/tests/test_pipdeptree.py b/tests/test_pipdeptree.py\nindex 34fa339..473eaa3 100644\n--- a/tests/test_pipdeptree.py\n+++ b/tests/test_pipdeptree.py\n@@ -224,12 +224,139 @@ def test_req_package_as_dict():\n # Tests for render_text\n \n \n+class MockStdout:\n+ \"\"\"\n+ A wrapper to stdout that mocks the `encoding` attribute (to have `render_text()` render with unicode/non-unicode)\n+ and `write()` (so that `print()` calls can write to stdout).\n+ \"\"\"\n+\n+ def __init__(self, encoding):\n+ self.stdout = sys.stdout\n+ self.encoding = encoding\n+\n+ def encoding(self):\n+ return self.encoding\n+\n+ def write(self, text):\n+ self.stdout.write(text)\n+\n+\n @pytest.mark.parametrize(\n- (\"list_all\", \"reverse\", \"expected_output\"),\n+ (\"list_all\", \"reverse\", \"unicode\", \"expected_output\"),\n [\n (\n True,\n False,\n+ True,\n+ [\n+ \"a==3.4.0\",\n+ \"\u251c\u2500\u2500 b [required: >=2.0.0, installed: 2.3.1]\",\n+ \"\u2502 \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \"\u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 c [required: >=5.7.1, installed: 5.10.0]\",\n+ \" \u251c\u2500\u2500 d [required: >=2.30, installed: 2.35]\",\n+ \" \u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.12.1, installed: 0.12.1]\",\n+ \"b==2.3.1\",\n+ \"\u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"c==5.10.0\",\n+ \"\u251c\u2500\u2500 d [required: >=2.30, installed: 2.35]\",\n+ \"\u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 e [required: >=0.12.1, installed: 0.12.1]\",\n+ \"d==2.35\",\n+ \"\u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"e==0.12.1\",\n+ \"f==3.1\",\n+ \"\u2514\u2500\u2500 b [required: >=2.1.0, installed: 2.3.1]\",\n+ \" \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"g==6.8.3rc1\",\n+ \"\u251c\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 f [required: >=3.0.0, installed: 3.1]\",\n+ \" \u2514\u2500\u2500 b [required: >=2.1.0, installed: 2.3.1]\",\n+ \" \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ ],\n+ ),\n+ (\n+ True,\n+ True,\n+ True,\n+ [\n+ \"a==3.4.0\",\n+ \"b==2.3.1\",\n+ \"\u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \" \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"c==5.10.0\",\n+ \"\u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"d==2.35\",\n+ \"\u251c\u2500\u2500 b==2.3.1 [requires: d>=2.30,<2.42]\",\n+ \"\u2502 \u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2502 \u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \"\u2502 \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"\u2514\u2500\u2500 c==5.10.0 [requires: d>=2.30]\",\n+ \" \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"e==0.12.1\",\n+ \"\u251c\u2500\u2500 c==5.10.0 [requires: e>=0.12.1]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u251c\u2500\u2500 d==2.35 [requires: e>=0.9.0]\",\n+ \"\u2502 \u251c\u2500\u2500 b==2.3.1 [requires: d>=2.30,<2.42]\",\n+ \"\u2502 \u2502 \u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"\u2502 \u2514\u2500\u2500 c==5.10.0 [requires: d>=2.30]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u2514\u2500\u2500 g==6.8.3rc1 [requires: e>=0.9.0]\",\n+ \"f==3.1\",\n+ \"\u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"g==6.8.3rc1\",\n+ ],\n+ ),\n+ (\n+ False,\n+ False,\n+ True,\n+ [\n+ \"a==3.4.0\",\n+ \"\u251c\u2500\u2500 b [required: >=2.0.0, installed: 2.3.1]\",\n+ \"\u2502 \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \"\u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 c [required: >=5.7.1, installed: 5.10.0]\",\n+ \" \u251c\u2500\u2500 d [required: >=2.30, installed: 2.35]\",\n+ \" \u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.12.1, installed: 0.12.1]\",\n+ \"g==6.8.3rc1\",\n+ \"\u251c\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 f [required: >=3.0.0, installed: 3.1]\",\n+ \" \u2514\u2500\u2500 b [required: >=2.1.0, installed: 2.3.1]\",\n+ \" \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ ],\n+ ),\n+ (\n+ False,\n+ True,\n+ True,\n+ [\n+ \"e==0.12.1\",\n+ \"\u251c\u2500\u2500 c==5.10.0 [requires: e>=0.12.1]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u251c\u2500\u2500 d==2.35 [requires: e>=0.9.0]\",\n+ \"\u2502 \u251c\u2500\u2500 b==2.3.1 [requires: d>=2.30,<2.42]\",\n+ \"\u2502 \u2502 \u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"\u2502 \u2514\u2500\u2500 c==5.10.0 [requires: d>=2.30]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u2514\u2500\u2500 g==6.8.3rc1 [requires: e>=0.9.0]\",\n+ ],\n+ ),\n+ (\n+ True,\n+ False,\n+ False,\n [\n \"a==3.4.0\",\n \" - b [required: >=2.0.0, installed: 2.3.1]\",\n@@ -264,6 +391,7 @@ def test_req_package_as_dict():\n (\n True,\n True,\n+ False,\n [\n \"a==3.4.0\",\n \"b==2.3.1\",\n@@ -296,6 +424,7 @@ def test_req_package_as_dict():\n ],\n ),\n (\n+ False,\n False,\n False,\n [\n@@ -318,6 +447,7 @@ def test_req_package_as_dict():\n (\n False,\n True,\n+ False,\n [\n \"e==0.12.1\",\n \" - c==5.10.0 [requires: e>=0.12.1]\",\n@@ -334,11 +464,13 @@ def test_req_package_as_dict():\n ),\n ],\n )\n-def test_render_text(capsys, list_all, reverse, expected_output):\n+def test_render_text(capsys, list_all, reverse, unicode, expected_output):\n tree = t.reverse() if reverse else t\n- p.render_text(tree, list_all=list_all, frozen=False)\n- captured = capsys.readouterr()\n- assert \"\\n\".join(expected_output).strip() == captured.out.strip()\n+ encoding = \"utf-8\" if unicode else \"ascii\"\n+ with mock.patch(\"sys.stdout\", MockStdout(encoding)):\n+ p.render_text(tree, list_all=list_all, frozen=False)\n+ captured = capsys.readouterr()\n+ assert \"\\n\".join(expected_output).strip() == captured.out.strip()\n \n \n # Tests for graph outputs\n", "FAIL_TO_PASS": ["tests/test_pipdeptree.py::test_render_text[True-False-True-expected_output0]", "tests/test_pipdeptree.py::test_render_text[True-True-True-expected_output1]", "tests/test_pipdeptree.py::test_render_text[False-False-True-expected_output2]", "tests/test_pipdeptree.py::test_render_text[False-True-True-expected_output3]"]}], "all_FAIL_TO_PASS": ["tests/test_pipdeptree.py::test_render_text[True-False-True-expected_output0]", "tests/test_pipdeptree.py::test_render_text[True-True-True-expected_output1]", "tests/test_pipdeptree.py::test_render_text[False-False-True-expected_output2]", "tests/test_pipdeptree.py::test_render_text[False-True-True-expected_output3]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pycqa__pyflakes-765_x1", "level": 1, "source": "swerebenchv2", "repo": "PyCQA/pyflakes", "image": "swerebenchv2/pycqa-pyflakes:765-e932464", "base_commit": "e9324649874a7124a08c3826d4cf78a4dc3aa32c", "num_bugs": 1, "bugs": [{"instance_id": "pycqa__pyflakes-765", "base_commit": "e9324649874a7124a08c3826d4cf78a4dc3aa32c", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex 4d778a8..e654afa 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -1068,7 +1068,7 @@ class Checker:\n \n binding = scope.get(name, None)\n if isinstance(binding, Annotation) and not self._in_postponed_annotation:\n- scope[name].used = True\n+ scope[name].used = (self.scope, node)\n continue\n \n if name == 'print' and isinstance(binding, Builtin):\n", "test_patch": "diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py\nindex f0fd3b9..396d676 100644\n--- a/pyflakes/test/test_type_annotations.py\n+++ b/pyflakes/test/test_type_annotations.py\n@@ -367,6 +367,13 @@ class TestTypeAnnotations(TestCase):\n x = 3\n ''', m.UnusedVariable)\n \n+ def test_unused_annotation_in_outer_scope_reassigned_in_local_scope(self):\n+ self.flakes('''\n+ x: int\n+ x.__dict__\n+ def f(): x = 1\n+ ''', m.UndefinedName, m.UnusedVariable)\n+\n def test_unassigned_annotation_is_undefined(self):\n self.flakes('''\n name: str\n", "FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation_in_outer_scope_reassigned_in_local_scope"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation_in_outer_scope_reassigned_in_local_scope"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cuthbertlab__music21-1066_x1", "level": 1, "source": "swerebenchv2", "repo": "cuthbertLab/music21", "image": "swerebenchv2/cuthbertlab-music21:1066-5d566a8", "base_commit": "5d566a8089fdc50b3053d9071a24b9db157a31d4", "num_bugs": 1, "bugs": [{"instance_id": "cuthbertlab__music21-1066", "base_commit": "5d566a8089fdc50b3053d9071a24b9db157a31d4", "gold_patch": "diff --git a/music21/_version.py b/music21/_version.py\nindex 7651c8d0c..b4949ae8b 100644\n--- a/music21/_version.py\n+++ b/music21/_version.py\n@@ -42,7 +42,7 @@ When changing, update the single test case in base.py.\n Changing this number invalidates old pickles -- do it if the old pickles create a problem.\n '''\n \n-__version_info__ = (7, 0, 7, 'b1') # can be 4-tuple: (7, 0, 5, 'a2')\n+__version_info__ = (7, 0, 8) # can be 4-tuple: (7, 0, 5, 'a2')\n \n v = '.'.join(str(x) for x in __version_info__[0:3])\n if len(__version_info__) > 3 and __version_info__[3]:\ndiff --git a/music21/base.py b/music21/base.py\nindex 3330d787c..1c930b143 100644\n--- a/music21/base.py\n+++ b/music21/base.py\n@@ -28,7 +28,7 @@ available after importing `music21`.\n \n \n >>> music21.VERSION_STR\n-'7.0.7b1'\n+'7.0.8'\n \n Alternatively, after doing a complete import, these classes are available\n under the module \"base\":\ndiff --git a/music21/meter/base.py b/music21/meter/base.py\nindex 98d4d016f..ef4ac52c6 100644\n--- a/music21/meter/base.py\n+++ b/music21/meter/base.py\n@@ -1293,6 +1293,14 @@ class TimeSignature(base.Music21Object):\n >,\n >,\n >]\n+\n+ Fixed in v.7 -- incomplete final measures in 6/8:\n+\n+ >>> sixEight = meter.TimeSignature('6/8')\n+ >>> nList = [note.Note(type='quarter'), note.Note(type='eighth'), note.Note(type='eighth')]\n+ >>> beamList = sixEight.getBeams(nList)\n+ >>> print(beamList)\n+ [None, None, None]\n '''\n from music21 import stream\n if isinstance(srcList, stream.Stream):\n@@ -1352,8 +1360,11 @@ class TimeSignature(base.Music21Object):\n \n # watch for a special case where a duration completely fills\n # the archetype; this generally should not be beamed\n- if (start == archetypeSpanStart\n- and end == archetypeSpanEnd):\n+ # same if beamPrevious is None and beamNumber == 1 (quarter-eighth in 6/8)\n+ if end == archetypeSpanEnd and (\n+ start == archetypeSpanStart\n+ or (beamPrevious is None and beamNumber == 1)\n+ ):\n # increment position and continue loop\n beamsList[i] = None # replace with None!\n return\n@@ -1368,7 +1379,7 @@ class TimeSignature(base.Music21Object):\n \n elif isLast: # last is always stop\n beamType = 'stop'\n- # get a partial beam if we cannot come form a beam\n+ # get a partial beam if we cannot form a beam\n if (beamPrevious is None\n or beamNumber not in beamPrevious.getNumbers()):\n # environLocal.warn(['triggering partial left where a stop normally falls'])\ndiff --git a/music21/musicxml/xmlToM21.py b/music21/musicxml/xmlToM21.py\nindex f84960122..050e8e405 100644\n--- a/music21/musicxml/xmlToM21.py\n+++ b/music21/musicxml/xmlToM21.py\n@@ -1989,8 +1989,8 @@ class PartParser(XMLParserBase):\n Fills an empty measure with a measure of rest (bug in PDFtoMusic and\n other MusicXML writers).\n \n- sets self.lastMeasureWasShort to True or False if it is an incomplete measure\n- that is not a pickup.\n+ Sets self.lastMeasureWasShort to True or False if it is an incomplete measure\n+ that is not a pickup and sets paddingRight.\n \n >>> m = stream.Measure([meter.TimeSignature('4/4'), harmony.ChordSymbol('C7')])\n >>> m.highestTime\n@@ -2002,6 +2002,17 @@ class PartParser(XMLParserBase):\n 4.0\n >>> PP.lastMeasureWasShort\n False\n+\n+ Incomplete final measure:\n+\n+ >>> m = stream.Measure([meter.TimeSignature('6/8'), note.Note(), note.Note()])\n+ >>> m.offset = 24.0\n+ >>> PP = musicxml.xmlToM21.PartParser()\n+ >>> PP.lastMeasureOffset = 21.0\n+ >>> PP.setLastMeasureInfo(m)\n+ >>> PP.adjustTimeAttributesFromMeasure(m)\n+ >>> m.paddingRight\n+ 1.0\n '''\n # note: we cannot assume that the time signature properly\n # describes the offsets w/n this bar. need to look at\n@@ -2049,6 +2060,9 @@ class PartParser(XMLParserBase):\n # or something\n self.lastMeasureWasShort = False\n else:\n+ # Incomplete measure that is likely NOT an anacrusis, set paddingRight\n+ if m.barDurationProportion() < 1.0:\n+ m.paddingRight = m.barDuration.quarterLength - m.highestTime\n if mHighestTime < lastTimeSignatureQuarterLength:\n self.lastMeasureWasShort = True\n else:\ndiff --git a/music21/stream/makeNotation.py b/music21/stream/makeNotation.py\nindex f1a71b5e2..ab47aeca8 100644\n--- a/music21/stream/makeNotation.py\n+++ b/music21/stream/makeNotation.py\n@@ -188,6 +188,9 @@ def makeBeams(\n offset = 0.0\n if m.paddingLeft != 0.0:\n offset = opFrac(m.paddingLeft)\n+ elif m.paddingRight != 0.0:\n+ pass\n+ # Incomplete measure without any padding set: assume paddingLeft\n elif noteStream.highestTime < barQL:\n offset = barQL - noteStream.highestTime\n \n@@ -1727,9 +1730,11 @@ def setStemDirectionOneGroup(\n if not group: # pragma: no cover\n return # should not happen\n \n- up_down_stem_directions = set(n.stemDirection for n in group\n- if n.stemDirection in ('up', 'down'))\n- if len(up_down_stem_directions) < 2:\n+ stem_directions = {n.stemDirection for n in group\n+ if n.stemDirection in ('up', 'down', 'unspecified')}\n+ if 'unspecified' in stem_directions:\n+ has_consistent_stem_directions = False\n+ elif len(stem_directions) < 2:\n has_consistent_stem_directions = True\n else:\n has_consistent_stem_directions = False\n@@ -1760,8 +1765,6 @@ def setStemDirectionOneGroup(\n \n \n \n-\n-\n # -----------------------------------------------------------------------------\n \n class Test(unittest.TestCase):\n@@ -1837,6 +1840,31 @@ class Test(unittest.TestCase):\n + ['down', 'noStem', 'double', 'down']\n )\n \n+ def testSetStemDirectionConsistency(self):\n+ \"\"\"\n+ Stems that would all be up starting from scratch,\n+ but because of overrideConsistentStemDirections=False,\n+ we only change the first group with an \"unspecified\" direction\n+ \"\"\"\n+ from music21 import converter\n+ p = converter.parse('tinyNotation: 2/4 b8 f8 a8 b8')\n+ p.makeBeams(inPlace=True)\n+ self.assertEqual(\n+ [n.stemDirection for n in p.flat.notes],\n+ ['up', 'up', 'up', 'up']\n+ )\n+\n+ # make manual changes\n+ dStems = ['down', 'unspecified', 'down', 'down']\n+ for n, stemDir in zip(p.flat.notes, dStems):\n+ n.stemDirection = stemDir\n+\n+ setStemDirectionForBeamGroups(p, setNewStems=True, overrideConsistentStemDirections=False)\n+ self.assertEqual(\n+ [n.stemDirection for n in p.flat.notes],\n+ ['up', 'up', 'down', 'down']\n+ )\n+\n def testMakeBeamsWithStemDirection(self):\n from music21 import converter\n p = converter.parse(self.allaBreveBeamTest)\n", "test_patch": "diff --git a/music21/stream/tests.py b/music21/stream/tests.py\nindex 58eb22af6..5b763f437 100644\n--- a/music21/stream/tests.py\n+++ b/music21/stream/tests.py\n@@ -8303,6 +8303,33 @@ class Test(unittest.TestCase):\n self.assertEqual(beams[3], continue_beam) # fourth should be continue\n self.assertEqual(beams[4], stop_beam) # last should be stop\n \n+ def test_makeBeams__paddingRight(self):\n+ m = Measure()\n+ m.timeSignature = meter.TimeSignature('6/8')\n+ m.paddingRight = 1.0\n+ m.append(note.Note(type='quarter'))\n+ m.append(note.Note(type='eighth'))\n+ m.append(note.Note(type='eighth'))\n+\n+ m.makeBeams(inPlace=True)\n+ beams = self.get_beams_from_stream(m)\n+\n+ no_beam = beam.Beams()\n+ start_beam = beam.Beams()\n+ start_beam.append('start')\n+ stop_beam = beam.Beams()\n+ stop_beam.append('stop')\n+\n+ self.assertEqual(beams, [no_beam, no_beam, no_beam])\n+\n+ m.paddingRight = 0.5\n+ m.append(note.Note(type='eighth'))\n+\n+ m.makeBeams(inPlace=True)\n+ beams = self.get_beams_from_stream(m)\n+\n+ self.assertEqual(beams, [no_beam, no_beam, start_beam, stop_beam])\n+\n def testWrite(self):\n import os\n \n", "FAIL_TO_PASS": ["music21/stream/tests.py::Test::test_makeBeams__paddingRight"]}], "all_FAIL_TO_PASS": ["music21/stream/tests.py::Test::test_makeBeams__paddingRight"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pycqa__pyflakes-772_x1", "level": 1, "source": "swerebenchv2", "repo": "PyCQA/pyflakes", "image": "swerebenchv2/pycqa-pyflakes:772-e19886e", "base_commit": "e19886e583637a7e2eec428cc036094b9630f2d0", "num_bugs": 1, "bugs": [{"instance_id": "pycqa__pyflakes-772", "base_commit": "e19886e583637a7e2eec428cc036094b9630f2d0", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex e654afa..db4da49 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -29,8 +29,10 @@ parse_format_string = string.Formatter().parse\n def getAlternatives(n):\n if isinstance(n, ast.If):\n return [n.body]\n- if isinstance(n, ast.Try):\n+ elif isinstance(n, ast.Try):\n return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]\n+ elif sys.version_info >= (3, 10) and isinstance(n, ast.Match):\n+ return [mc.body for mc in n.cases]\n \n \n FOR_TYPES = (ast.For, ast.AsyncFor)\n", "test_patch": "diff --git a/pyflakes/test/test_match.py b/pyflakes/test/test_match.py\nindex 89826e3..b237523 100644\n--- a/pyflakes/test/test_match.py\n+++ b/pyflakes/test/test_match.py\n@@ -81,3 +81,14 @@ class TestMatch(TestCase):\n case {'foo': k1, **rest}:\n print(f'{k1=} {rest=}')\n ''')\n+\n+ def test_defined_in_different_branches(self):\n+ self.flakes('''\n+ def f(x):\n+ match x:\n+ case 1:\n+ def y(): pass\n+ case _:\n+ def y(): print(1)\n+ return y\n+ ''')\n", "FAIL_TO_PASS": ["pyflakes/test/test_match.py::TestMatch::test_defined_in_different_branches"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_match.py::TestMatch::test_defined_in_different_branches"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3455_x1", "level": 1, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3455-aacbc54", "base_commit": "aacbc54f633cacd60235e027ee16efa6af2d900e", "num_bugs": 1, "bugs": [{"instance_id": "openmdao__openmdao-3455", "base_commit": "aacbc54f633cacd60235e027ee16efa6af2d900e", "gold_patch": "diff --git a/openmdao/core/problem.py b/openmdao/core/problem.py\nindex 67eb07195..112d880f8 100644\n--- a/openmdao/core/problem.py\n+++ b/openmdao/core/problem.py\n@@ -54,7 +54,7 @@ from openmdao.utils.general_utils import pad_name, _find_dict_meta, env_truthy,\n from openmdao.utils.om_warnings import issue_warning, DerivativesWarning, warn_deprecation, \\\n OMInvalidCheckDerivativesOptionsWarning\n import openmdao.utils.coloring as coloring_mod\n-from openmdao.utils.file_utils import _get_outputs_dir, text2html, get_work_dir\n+from openmdao.utils.file_utils import _get_outputs_dir, text2html, _get_work_dir\n from openmdao.utils.testing_utils import _fix_comp_check_data\n \n try:\n@@ -264,8 +264,11 @@ class Problem(object, metaclass=ProblemMetaclass):\n \n # General options\n self.options = OptionsDictionary(parent_name=type(self).__name__)\n+ default_workdir = options['work_dir'] if 'work_dir' in options else _get_work_dir()\n+ self.options.declare('work_dir', default=default_workdir,\n+ desc='Working directory for the problem.')\n self.options.declare('coloring_dir', types=str,\n- default=os.path.join(get_work_dir(), 'coloring_files'),\n+ default=os.path.join(default_workdir, 'coloring_files'),\n desc='Directory containing coloring files (if any) for this Problem.')\n self.options.declare('group_by_pre_opt_post', types=bool,\n default=False,\n@@ -962,6 +965,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n 'name': self._name, # the name of this Problem\n 'pathname': None, # the pathname of this Problem in the current tree of Problems\n 'comm': comm,\n+ 'work_dir': pathlib.Path(self.options['work_dir']),\n 'coloring_dir': _DEFAULT_COLORING_DIR, # directory for input coloring files\n 'recording_iter': _RecIteration(comm.rank), # manager of recorder iterations\n 'local_vector_class': local_vector_class,\ndiff --git a/openmdao/devtools/iprofile.py b/openmdao/devtools/iprofile.py\nindex 53b72323e..d6e280ba5 100644\n--- a/openmdao/devtools/iprofile.py\n+++ b/openmdao/devtools/iprofile.py\n@@ -9,7 +9,7 @@ from openmdao.utils.mpi import MPI\n \n from openmdao.devtools.iprof_utils import func_group, find_qualified_name, _collect_methods, \\\n _setup_func_group, _get_methods, _Options\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n \n \n def _prof_node(fpath, parts):\n@@ -44,7 +44,7 @@ def _setup(options, finalize=True):\n if _profile_setup:\n raise RuntimeError(\"profiling is already set up.\")\n \n- _profile_prefix = os.path.join(get_work_dir(), 'iprof')\n+ _profile_prefix = os.path.join(_get_work_dir(), 'iprof')\n _profile_setup = True\n \n methods = _get_methods(options, default='openmdao')\ndiff --git a/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb b/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb\nindex b563dbba0..83a6e4f1e 100644\n--- a/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb\n+++ b/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb\n@@ -103,7 +103,9 @@\n \"\\n\",\n \"1. The user has the option of setting a common output directory for ALL problems using the `OPENMDAO_WORKDIR` environment variable. Thus there is a single directory that contains all OpenMDAO output data.\\n\",\n \"\\n\",\n- \"2. The [openmdao clean](om-command-clean) or `openmdao.api.clean_outputs` function can be used to remove these directories.\\n\"\n+ \"2. The [openmdao clean](om-command-clean) or `openmdao.api.clean_outputs` function can be used to remove these directories.\\n\",\n+ \"\\n\",\n+ \"As an alternative to setting `OPENMDAO_WORKDIR` to set the top level output directory for all problems, a user can set `work_dir` as an option of Problem in order to set the top level output directory under which that problem's `'{problem_name}_out'` directory will be placed. If provided, the value of the `work_dir` option takes precedence.\\n\"\n ]\n },\n {\n@@ -351,7 +353,7 @@\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n- \"display_name\": \"Python 3\",\n+ \"display_name\": \"py311\",\n \"language\": \"python\",\n \"name\": \"python3\"\n },\ndiff --git a/openmdao/utils/file_utils.py b/openmdao/utils/file_utils.py\nindex 96959fe4f..7461e9234 100644\n--- a/openmdao/utils/file_utils.py\n+++ b/openmdao/utils/file_utils.py\n@@ -433,7 +433,7 @@ def image2html(imagefile, title='', alt=''):\n \"\"\"\n \n \n-def get_work_dir():\n+def _get_work_dir():\n \"\"\"\n Return either os.getcwd() or the value of the OPENMDAO_WORKDIR environment variable.\n \n@@ -494,7 +494,7 @@ def _get_outputs_dir(obj, *subdirs, mkdir=True):\n \n prob_pathname = prob_meta['pathname']\n \n- work_dir = pathlib.Path(get_work_dir())\n+ work_dir = prob_meta['work_dir']\n if mkdir and not work_dir.exists():\n work_dir.mkdir(exist_ok=True)\n \n", "test_patch": "diff --git a/openmdao/core/tests/test_problem.py b/openmdao/core/tests/test_problem.py\nindex 8e2b39d8d..db8dc7534 100644\n--- a/openmdao/core/tests/test_problem.py\n+++ b/openmdao/core/tests/test_problem.py\n@@ -4,6 +4,7 @@ import pathlib\n import sys\n import unittest\n import itertools\n+import tempfile\n \n from io import StringIO\n import numpy as np\n@@ -19,7 +20,7 @@ import openmdao.utils.hooks as hooks\n from openmdao.utils.units import convert_units\n from openmdao.utils.om_warnings import DerivativesWarning, OMDeprecationWarning, OpenMDAOWarning\n from openmdao.utils.testing_utils import use_tempdirs, set_env_vars\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n from openmdao.utils.tests.test_hooks import hooks_active\n \n try:\n@@ -2231,6 +2232,28 @@ class TestProblem(unittest.TestCase):\n except RuntimeError:\n self.fail(\"'setup raised RuntimeError unexpectedly\")\n \n+ def test_set_work_dir(self):\n+\n+ with tempfile.TemporaryDirectory() as temp_dir_name:\n+ prob = om.Problem(name='prob_name', work_dir=temp_dir_name)\n+ model = prob.model\n+\n+ model.add_subsystem('comp', Paraboloid())\n+\n+ model.set_input_defaults('comp.x', 3.0)\n+ model.set_input_defaults('comp.y', -4.0)\n+\n+ with self.assertRaises(RuntimeError) as e:\n+ prob.get_outputs_dir()\n+\n+ self.assertEqual('The output directory cannot be accessed before setup.',\n+ str(e.exception))\n+\n+ prob.setup()\n+\n+ d = prob.get_outputs_dir('subdir')\n+ self.assertEqual(str(pathlib.Path(temp_dir_name, 'prob_name_out', 'subdir')), str(d))\n+\n def test_get_outputs_dir(self):\n \n prob = om.Problem(name='prob_name')\n@@ -2250,7 +2273,7 @@ class TestProblem(unittest.TestCase):\n prob.setup()\n \n d = prob.get_outputs_dir('subdir')\n- self.assertEqual(str(pathlib.Path(get_work_dir(), 'prob_name_out', 'subdir')), str(d))\n+ self.assertEqual(str(pathlib.Path(_get_work_dir(), 'prob_name_out', 'subdir')), str(d))\n \n def test_duplicate_prob_name(self):\n \ndiff --git a/openmdao/core/tests/test_system.py b/openmdao/core/tests/test_system.py\nindex 4a4b2d4a4..ad008bd13 100644\n--- a/openmdao/core/tests/test_system.py\n+++ b/openmdao/core/tests/test_system.py\n@@ -7,7 +7,7 @@ import numpy as np\n from openmdao.api import Problem, Group, IndepVarComp, ExecComp, ExplicitComponent\n from openmdao.utils.assert_utils import assert_near_equal, assert_warning, assert_warnings\n from openmdao.utils.testing_utils import use_tempdirs\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n \n \n @use_tempdirs\n@@ -694,7 +694,7 @@ class TestSystem(unittest.TestCase):\n prob.setup()\n \n d = prob.get_outputs_dir('subdir')\n- self.assertEqual(str(pathlib.Path(get_work_dir(), 'test_prob_name_out', 'subdir')), str(d))\n+ self.assertEqual(str(pathlib.Path(_get_work_dir(), 'test_prob_name_out', 'subdir')), str(d))\n \n \n if __name__ == \"__main__\":\ndiff --git a/openmdao/recorders/tests/test_distrib_sqlite_recorder.py b/openmdao/recorders/tests/test_distrib_sqlite_recorder.py\nindex 9fce3adb5..f9ad9115e 100644\n--- a/openmdao/recorders/tests/test_distrib_sqlite_recorder.py\n+++ b/openmdao/recorders/tests/test_distrib_sqlite_recorder.py\n@@ -12,7 +12,7 @@ from openmdao.utils.mpi import MPI\n import openmdao.api as om\n \n from openmdao.utils.array_utils import evenly_distrib_idxs\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n from openmdao.recorders.tests.sqlite_recorder_test_utils import \\\n assertDriverIterDataRecorded, assertProblemDataRecorded\n from openmdao.recorders.tests.recorder_test_utils import run_driver\n@@ -408,7 +408,7 @@ class DistributedRecorderTest(unittest.TestCase):\n \n def run_parallel():\n # process cases.sql in parallel\n- cr = om.CaseReader(os.path.join(get_work_dir(), 'test_record_on_one_proc_out/cases.sql'))\n+ cr = om.CaseReader(os.path.join(_get_work_dir(), 'test_record_on_one_proc_out/cases.sql'))\n \n cases = cr.list_cases()\n self.assertEqual(len(cases), 9)\ndiff --git a/openmdao/utils/tests/test_file_utils.py b/openmdao/utils/tests/test_file_utils.py\nindex be3f7218f..889514edf 100644\n--- a/openmdao/utils/tests/test_file_utils.py\n+++ b/openmdao/utils/tests/test_file_utils.py\n@@ -11,7 +11,7 @@ import sys\n \n import openmdao.api as om\n from openmdao.utils.testing_utils import use_tempdirs\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n from openmdao.core.problem import _clear_problem_names\n from openmdao.utils.reports_system import clear_reports\n \n@@ -62,14 +62,14 @@ class TestCleanOutputs(unittest.TestCase):\n with redirect_stdout(ss):\n om.clean_outputs(p1)\n \n- self.assertEqual(len(os.listdir(get_work_dir())), 1)\n+ self.assertEqual(len(os.listdir(_get_work_dir())), 1)\n \n # Now specify p2 with the output directory.\n ss = io.StringIO()\n with redirect_stdout(ss):\n om.clean_outputs(p2)\n \n- self.assertEqual(len(os.listdir(get_work_dir())), 0)\n+ self.assertEqual(len(os.listdir(_get_work_dir())), 0)\n \n def test_specify_non_output_dir_no_prompt(self):\n \n@@ -86,7 +86,7 @@ class TestCleanOutputs(unittest.TestCase):\n # First Test that a dryrun on '.' works as expected.\n ss = io.StringIO()\n cwd = os.getcwd()\n- os.chdir(get_work_dir())\n+ os.chdir(_get_work_dir())\n try:\n with redirect_stdout(ss):\n om.clean_outputs('.', dryrun=True)\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_args", "openmdao/core/tests/test_problem.py::TestProblem::test_check_totals_user_detect", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_0_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_1_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic_return_dict", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_cleanup", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_desvar", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_response", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_promoted", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_indep_var", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_input_output", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_alias_duplicate_errors", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_ellipses_slice_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_slice_with_negative_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output_as_input_err", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_prob_name", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_problem_name", "openmdao/core/tests/test_problem.py::TestProblem::test_error_msg_set_val_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_basic_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_cs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_compact", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_manual", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_suppress", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_user_detect_forced", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_slicer", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_list_driver_vars", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_not_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_petsc_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_inputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_residuals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_run_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_get_array", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps_auto", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_input_input", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_no_promote", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_set_deriv_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_get_outputs_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_exhaustive", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_before_final_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling_bounds", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_vars_deprecated", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_w_multi_constraints", "openmdao/core/tests/test_problem.py::TestProblem::test_post_final_setup_hook", "openmdao/core/tests/test_problem.py::TestProblem::test_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_relevance", "openmdao/core/tests/test_problem.py::TestProblem::test_run_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_run_with_invalid_prefix", "openmdao/core/tests/test_problem.py::TestProblem::test_set_2d_array", "openmdao/core/tests/test_problem.py::TestProblem::test_set_checks_shape", "openmdao/core/tests/test_problem.py::TestProblem::test_set_cs_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_set_work_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_simple_component_model_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_single_string_wrt_of", "openmdao/core/tests/test_problem.py::TestProblem::test_system_setup_and_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_two_var_single_string_error", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_duplicate_inputs", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_no_auto_ivc", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance2", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance3", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance4", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance5", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance_approx", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_cs_across_nested", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob_default_naming", "openmdao/core/tests/test_problem.py::SystemInTwoProblemsTestCase::test_2problems", "openmdao/core/tests/test_system.py::TestSystem::test_get_io_metadata", "openmdao/core/tests/test_system.py::TestSystem::test_get_outputs_dir", "openmdao/core/tests/test_system.py::TestSystem::test_group_modifies_model_options", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_before_final_setup", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_output_with_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_invalid_return_format", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_is_indep_is_des_var", "openmdao/core/tests/test_system.py::TestSystem::test_missing_source", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_override", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_set_all", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_with_filter", "openmdao/core/tests/test_system.py::TestSystem::test_record_residuals_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_recording_options_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_set_checks_shape", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_component", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_group", "openmdao/core/tests/test_system.py::TestSystem::test_vector_context_managers", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_multiple_paths", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_norecurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_pattern", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_recurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_no_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_prob"]}], "all_FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_args", "openmdao/core/tests/test_problem.py::TestProblem::test_check_totals_user_detect", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_0_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_1_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic_return_dict", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_cleanup", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_desvar", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_response", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_promoted", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_indep_var", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_input_output", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_alias_duplicate_errors", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_ellipses_slice_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_slice_with_negative_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output_as_input_err", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_prob_name", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_problem_name", "openmdao/core/tests/test_problem.py::TestProblem::test_error_msg_set_val_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_basic_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_cs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_compact", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_manual", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_suppress", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_user_detect_forced", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_slicer", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_list_driver_vars", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_not_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_petsc_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_inputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_residuals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_run_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_get_array", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps_auto", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_input_input", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_no_promote", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_set_deriv_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_get_outputs_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_exhaustive", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_before_final_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling_bounds", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_vars_deprecated", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_w_multi_constraints", "openmdao/core/tests/test_problem.py::TestProblem::test_post_final_setup_hook", "openmdao/core/tests/test_problem.py::TestProblem::test_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_relevance", "openmdao/core/tests/test_problem.py::TestProblem::test_run_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_run_with_invalid_prefix", "openmdao/core/tests/test_problem.py::TestProblem::test_set_2d_array", "openmdao/core/tests/test_problem.py::TestProblem::test_set_checks_shape", "openmdao/core/tests/test_problem.py::TestProblem::test_set_cs_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_set_work_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_simple_component_model_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_single_string_wrt_of", "openmdao/core/tests/test_problem.py::TestProblem::test_system_setup_and_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_two_var_single_string_error", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_duplicate_inputs", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_no_auto_ivc", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance2", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance3", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance4", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance5", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance_approx", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_cs_across_nested", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob_default_naming", "openmdao/core/tests/test_problem.py::SystemInTwoProblemsTestCase::test_2problems", "openmdao/core/tests/test_system.py::TestSystem::test_get_io_metadata", "openmdao/core/tests/test_system.py::TestSystem::test_get_outputs_dir", "openmdao/core/tests/test_system.py::TestSystem::test_group_modifies_model_options", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_before_final_setup", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_output_with_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_invalid_return_format", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_is_indep_is_des_var", "openmdao/core/tests/test_system.py::TestSystem::test_missing_source", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_override", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_set_all", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_with_filter", "openmdao/core/tests/test_system.py::TestSystem::test_record_residuals_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_recording_options_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_set_checks_shape", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_component", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_group", "openmdao/core/tests/test_system.py::TestSystem::test_vector_context_managers", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_multiple_paths", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_norecurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_pattern", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_recurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_no_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_prob"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3098_x1", "level": 1, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3098-157a109", "base_commit": "157a10944aa62cd88d7cb9566435055106892f8d", "num_bugs": 1, "bugs": [{"instance_id": "openmdao__openmdao-3098", "base_commit": "157a10944aa62cd88d7cb9566435055106892f8d", "gold_patch": "diff --git a/openmdao/drivers/scipy_optimizer.py b/openmdao/drivers/scipy_optimizer.py\nindex 49b890e18..1268bfe54 100644\n--- a/openmdao/drivers/scipy_optimizer.py\n+++ b/openmdao/drivers/scipy_optimizer.py\n@@ -25,7 +25,7 @@ _gradient_optimizers = {'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP', '\n 'trust-ncg', 'trust-constr', 'basinhopping', 'shgo'}\n _hessian_optimizers = {'trust-constr', 'trust-ncg'}\n _bounds_optimizers = {'L-BFGS-B', 'TNC', 'SLSQP', 'trust-constr', 'dual_annealing', 'shgo',\n- 'differential_evolution', 'basinhopping'}\n+ 'differential_evolution', 'basinhopping', 'Nelder-Mead'}\n if Version(scipy_version) >= Version(\"1.11\"):\n # COBYLA supports bounds starting with SciPy Version 1.11\n _bounds_optimizers |= {'COBYLA'}\n", "test_patch": "diff --git a/openmdao/drivers/tests/test_scipy_optimizer.py b/openmdao/drivers/tests/test_scipy_optimizer.py\nindex 5330e3aba..a60df5f56 100644\n--- a/openmdao/drivers/tests/test_scipy_optimizer.py\n+++ b/openmdao/drivers/tests/test_scipy_optimizer.py\n@@ -2224,6 +2224,42 @@ class TestScipyOptimizeDriver(unittest.TestCase):\n assert_near_equal(p.get_val('exec.z')[0], 25)\n assert_near_equal(p.get_val('exec.z')[50], -75)\n \n+ def test_nelder_mead_bounded(self):\n+\n+ class dummy_function(om.ExplicitComponent):\n+ def setup(self):\n+ self.add_input('x', val=0.)\n+ self.add_output('y', val=0.)\n+\n+ def compute(self, inputs, outputs):\n+ x = inputs['x']\n+\n+ outputs['y'] = 2*x + 1\n+\n+ model = om.Group()\n+ model.add_subsystem('dummy_function',\n+ dummy_function(),\n+ promotes=['*'])\n+ prob = om.Problem(model=model)\n+\n+ model.add_objective('y')\n+ model.add_design_var('x', lower=0, upper=100)\n+ model.set_input_defaults('x', 25)\n+\n+ driver = prob.driver = om.ScipyOptimizeDriver()\n+ driver.options[\"optimizer\"] = 'Nelder-Mead'\n+\n+ driver.options['debug_print'] = ['desvars',\n+ 'nl_cons', 'ln_cons', 'objs', 'totals']\n+\n+ prob.setup()\n+\n+ prob.run_driver()\n+\n+ y_out = prob.get_val('y')\n+\n+ assert_near_equal(y_out, 1.0, tolerance=1.0E-3)\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["openmdao/drivers/tests/test_scipy_optimizer.py::TestScipyOptimizeDriver::test_nelder_mead_bounded"]}], "all_FAIL_TO_PASS": ["openmdao/drivers/tests/test_scipy_optimizer.py::TestScipyOptimizeDriver::test_nelder_mead_bounded"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3461_x1", "level": 1, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3461-160303f", "base_commit": "160303f311abb94e3b5ec147360cdb7fef3923da", "num_bugs": 1, "bugs": [{"instance_id": "openmdao__openmdao-3461", "base_commit": "160303f311abb94e3b5ec147360cdb7fef3923da", "gold_patch": "diff --git a/openmdao/core/problem.py b/openmdao/core/problem.py\nindex 67eb07195..ef93e82c0 100644\n--- a/openmdao/core/problem.py\n+++ b/openmdao/core/problem.py\n@@ -6,6 +6,7 @@ import shutil\n import sys\n import pprint\n import os\n+from copy import deepcopy\n import weakref\n import pathlib\n import textwrap\n@@ -1791,7 +1792,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n desvars = self.driver._designvars\n vals = self.driver.get_design_var_values(get_remote=True, driver_scaling=driver_scaling)\n if not driver_scaling:\n- desvars = desvars.copy()\n+ desvars = deepcopy(desvars)\n for meta in desvars.values():\n scaler = meta['scaler'] if meta.get('scaler') is not None else 1.\n adder = meta['adder'] if meta.get('adder') is not None else 0.\n@@ -1819,7 +1820,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n cons = self.driver._cons\n vals = self.driver.get_constraint_values(driver_scaling=driver_scaling)\n if not driver_scaling:\n- cons = cons.copy()\n+ cons = deepcopy(cons)\n for meta in cons.values():\n scaler = meta['scaler'] if meta.get('scaler') is not None else 1.\n adder = meta['adder'] if meta.get('adder') is not None else 0.\n", "test_patch": "diff --git a/openmdao/core/tests/test_problem.py b/openmdao/core/tests/test_problem.py\nindex 8e2b39d8d..1d55fc76a 100644\n--- a/openmdao/core/tests/test_problem.py\n+++ b/openmdao/core/tests/test_problem.py\n@@ -1878,6 +1878,49 @@ class TestProblem(unittest.TestCase):\n # make sure the deprecated function still returns tha data\n self.assertEqual(set(prob_vars.keys()), {'constraints', 'design_vars', 'objectives'})\n \n+ def test_list_driver_vars_bounds_bug(self):\n+\n+ model = SellarDerivatives()\n+ model.nonlinear_solver = om.NonlinearBlockGS()\n+\n+ prob = om.Problem(model)\n+ prob.driver = om.ScipyOptimizeDriver()\n+ prob.driver.options['optimizer'] = 'SLSQP'\n+ prob.driver.options['tol'] = 1e-9\n+\n+ model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), scaler=2.0)\n+ model.add_objective('obj', scaler=0.1)\n+ model.add_constraint('con1', upper=1.0, scaler=7.0)\n+\n+ prob.setup()\n+ prob.run_driver()\n+\n+ info = prob.list_driver_vars(\n+ driver_scaling=False,\n+ desvar_opts=['lower', 'upper', 'scaler', 'adder'],\n+ cons_opts=['lower', 'upper', 'scaler', 'adder'],\n+ objs_opts=['scaler', 'adder'],\n+ )\n+\n+ upper = info['design_vars'][0][1]['upper']\n+ assert_near_equal(upper, np.array([10., 10.]))\n+\n+ upper = info['constraints'][0][1]['upper']\n+ assert_near_equal(upper, 1.0)\n+\n+ info = prob.list_driver_vars(\n+ driver_scaling=False,\n+ desvar_opts=['lower', 'upper', 'scaler', 'adder'],\n+ cons_opts=['lower', 'upper', 'scaler', 'adder'],\n+ objs_opts=['scaler', 'adder'],\n+ )\n+\n+ upper = info['design_vars'][0][1]['upper']\n+ assert_near_equal(upper, np.array([10., 10.]))\n+\n+ upper = info['constraints'][0][1]['upper']\n+ assert_near_equal(upper, 1.0)\n+\n def test_list_driver_vars_before_final_setup(self):\n prob = om.Problem()\n prob.model.add_subsystem('parab', Paraboloid(), promotes_inputs=['x', 'y'])\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_bounds_bug"]}], "all_FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_bounds_bug"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cuthbertlab__music21-1138_x1", "level": 1, "source": "swerebenchv2", "repo": "cuthbertLab/music21", "image": "swerebenchv2/cuthbertlab-music21:1138-546683a", "base_commit": "546683ad59a0368908a4325537d468f22f084acd", "num_bugs": 1, "bugs": [{"instance_id": "cuthbertlab__music21-1138", "base_commit": "546683ad59a0368908a4325537d468f22f084acd", "gold_patch": "diff --git a/music21/meter/base.py b/music21/meter/base.py\nindex b9592f17c..ec239a2e4 100644\n--- a/music21/meter/base.py\n+++ b/music21/meter/base.py\n@@ -1178,7 +1178,10 @@ class TimeSignature(base.Music21Object):\n # create a scratch MeterSequence for structure\n tsStr = f'{self.numerator}/{self.denominator}'\n if self.beatSequence.isUniformPartition():\n- firstPartitionForm = len(self.beatSequence)\n+ if len(self.beatSequence) > 1:\n+ firstPartitionForm = len(self.beatSequence)\n+ else:\n+ firstPartitionForm = None\n cacheKey = (tsStr, firstPartitionForm, depth)\n else: # derive from meter sequence\n firstPartitionForm = self.beatSequence\n", "test_patch": "diff --git a/music21/meter/tests.py b/music21/meter/tests.py\nindex 493f6c3f4..5ee71b264 100644\n--- a/music21/meter/tests.py\n+++ b/music21/meter/tests.py\n@@ -388,6 +388,9 @@ class Test(unittest.TestCase):\n 0.5, 0.125, 0.25, 0.125, 0.25, 0.125,\n 0.5, 0.125, 0.25, 0.125, 0.25, 0.125]),\n \n+ ('3/8', [1.0, 0.125, 0.25, 0.125, 0.5, 0.125,\n+ 0.25, 0.125, 0.5, 0.125, 0.25, 0.125]),\n+\n ('11/8',\n [1.0, 0.125, 0.25, 0.125,\n 0.5, 0.125, 0.25, 0.125,\n", "FAIL_TO_PASS": ["music21/meter/tests.py::Test::testSetDefaultAccentWeights"]}], "all_FAIL_TO_PASS": ["music21/meter/tests.py::Test::testSetDefaultAccentWeights"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cs-si__eodag-790_x1", "level": 1, "source": "swerebenchv2", "repo": "CS-SI/eodag", "image": "swerebenchv2/cs-si-eodag:790-9acf017", "base_commit": "9acf017451f71c5488011f3add086a9936cfffc8", "num_bugs": 1, "bugs": [{"instance_id": "cs-si__eodag-790", "base_commit": "9acf017451f71c5488011f3add086a9936cfffc8", "gold_patch": "diff --git a/eodag/api/core.py b/eodag/api/core.py\nindex 0d589122..9b394f4a 100644\n--- a/eodag/api/core.py\n+++ b/eodag/api/core.py\n@@ -832,6 +832,7 @@ class EODataAccessGateway(object):\n end=None,\n geom=None,\n locations=None,\n+ provider=None,\n **kwargs,\n ):\n \"\"\"Look for products matching criteria on known providers.\n@@ -877,6 +878,9 @@ class EODataAccessGateway(object):\n :type locations: dict\n :param kwargs: Some other criteria that will be used to do the search,\n using paramaters compatibles with the provider\n+ :param provider: (optional) the provider to be used, if not set, the configured\n+ default provider will be used\n+ :type provider: str\n :type kwargs: Union[int, str, bool, dict]\n :returns: A collection of EO products matching the criteria and the total\n number of results found\n@@ -888,7 +892,12 @@ class EODataAccessGateway(object):\n enforced here.\n \"\"\"\n search_kwargs = self._prepare_search(\n- start=start, end=end, geom=geom, locations=locations, **kwargs\n+ start=start,\n+ end=end,\n+ geom=geom,\n+ locations=locations,\n+ provider=provider,\n+ **kwargs,\n )\n search_plugins = search_kwargs.pop(\"search_plugins\", [])\n if search_kwargs.get(\"id\"):\n@@ -899,7 +908,9 @@ class EODataAccessGateway(object):\n )\n # remove auth from search_kwargs as a loop over providers will be performed\n search_kwargs.pop(\"auth\", None)\n- return self._search_by_id(search_kwargs.pop(\"id\"), **search_kwargs)\n+ return self._search_by_id(\n+ search_kwargs.pop(\"id\"), provider=provider, **search_kwargs\n+ )\n search_kwargs.update(\n page=page,\n items_per_page=items_per_page,\n@@ -1254,12 +1265,16 @@ class EODataAccessGateway(object):\n of EO products retrieved (0 or 1)\n :rtype: tuple(:class:`~eodag.api.search_result.SearchResult`, int)\n \"\"\"\n+ if not provider:\n+ provider = self.get_preferred_provider()[0]\n get_search_plugins_kwargs = dict(\n provider=provider, product_type=kwargs.get(\"productType\", None)\n )\n- for plugin in self._plugins_manager.get_search_plugins(\n+ search_plugins = self._plugins_manager.get_search_plugins(\n **get_search_plugins_kwargs\n- ):\n+ )\n+\n+ for plugin in search_plugins:\n logger.info(\n \"Searching product with id '%s' on provider: %s\", uid, plugin.provider\n )\n@@ -1294,7 +1309,7 @@ class EODataAccessGateway(object):\n return SearchResult([]), 0\n \n def _prepare_search(\n- self, start=None, end=None, geom=None, locations=None, **kwargs\n+ self, start=None, end=None, geom=None, locations=None, provider=None, **kwargs\n ):\n \"\"\"Internal method to prepare the search kwargs and get the search\n and auth plugins.\n@@ -1323,6 +1338,9 @@ class EODataAccessGateway(object):\n :type geom: Union[str, dict, shapely.geometry.base.BaseGeometry]\n :param locations: (optional) Location filtering by name using locations configuration\n :type locations: dict\n+ :param provider: provider to be used, if no provider is given or the product type\n+ is not available for the provider, the preferred provider is used\n+ :type provider: str\n :param kwargs: Some other criteria\n * id and/or a provider for a search by\n * search criteria to guess the product type\n@@ -1400,15 +1418,23 @@ class EODataAccessGateway(object):\n ):\n search_plugins.append(plugin)\n \n- if search_plugins[0].provider != self.get_preferred_provider()[0]:\n+ if not provider:\n+ provider = self.get_preferred_provider()[0]\n+ providers = [plugin.provider for plugin in search_plugins]\n+ if provider not in providers:\n logger.warning(\n \"Product type '%s' is not available with provider '%s'. \"\n \"Searching it on provider '%s' instead.\",\n product_type,\n- self.get_preferred_provider()[0],\n+ provider,\n search_plugins[0].provider,\n )\n else:\n+ provider_plugin = list(\n+ filter(lambda p: p.provider == provider, search_plugins)\n+ )[0]\n+ search_plugins.remove(provider_plugin)\n+ search_plugins.insert(0, provider_plugin)\n logger.info(\n \"Searching product type '%s' on provider: %s\",\n product_type,\n@@ -1440,9 +1466,6 @@ class EODataAccessGateway(object):\n # Remove the ID since this is equal to productType.\n search_plugin.config.product_type_config.pop(\"ID\", None)\n \n- logger.debug(\n- \"Using plugin class for search: %s\", search_plugin.__class__.__name__\n- )\n auth_plugin = self._plugins_manager.get_auth_plugin(search_plugin.provider)\n auth_plugins[search_plugin.provider] = auth_plugin\n \n@@ -1493,6 +1516,7 @@ class EODataAccessGateway(object):\n \n results = SearchResult([])\n total_results = 0\n+\n try:\n if \"auth\" in kwargs:\n if isinstance(kwargs[\"auth\"], dict):\n@@ -1586,6 +1610,7 @@ class EODataAccessGateway(object):\n pass\n else:\n eo_product.product_type = guesses[0]\n+\n if eo_product.search_intersection is not None:\n download_plugin = self._plugins_manager.get_download_plugin(\n eo_product\ndiff --git a/eodag/plugins/authentication/token.py b/eodag/plugins/authentication/token.py\nindex b1032426..377268c7 100644\n--- a/eodag/plugins/authentication/token.py\n+++ b/eodag/plugins/authentication/token.py\n@@ -15,19 +15,28 @@\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n+import logging\n \n import requests\n from requests import RequestException\n+from requests.adapters import HTTPAdapter\n+from urllib3 import Retry\n \n from eodag.plugins.authentication.base import Authentication\n from eodag.utils import USER_AGENT, RequestsTokenAuth\n from eodag.utils.exceptions import AuthenticationError, MisconfiguredError\n from eodag.utils.stac_reader import HTTP_REQ_TIMEOUT\n \n+logger = logging.getLogger(\"eodag.authentication.token\")\n+\n \n class TokenAuth(Authentication):\n \"\"\"TokenAuth authentication plugin\"\"\"\n \n+ def __init__(self, provider, config):\n+ super(TokenAuth, self).__init__(provider, config)\n+ self.token = \"\"\n+\n def validate_config_credentials(self):\n \"\"\"Validate configured credentials\"\"\"\n super(TokenAuth, self).validate_config_credentials()\n@@ -56,10 +65,15 @@ class TokenAuth(Authentication):\n if hasattr(self.config, \"headers\")\n else {\"headers\": USER_AGENT}\n )\n+ s = requests.Session()\n+ retries = Retry(\n+ total=3, backoff_factor=2, status_forcelist=[401, 429, 500, 502, 503, 504]\n+ )\n+ s.mount(self.config.auth_uri, HTTPAdapter(max_retries=retries))\n try:\n # First get the token\n if getattr(self.config, \"request_method\", \"POST\") == \"POST\":\n- response = requests.post(\n+ response = s.post(\n self.config.auth_uri,\n data=self.config.credentials,\n timeout=HTTP_REQ_TIMEOUT,\n@@ -67,7 +81,7 @@ class TokenAuth(Authentication):\n )\n else:\n cred = self.config.credentials\n- response = requests.get(\n+ response = s.get(\n self.config.auth_uri,\n auth=(cred[\"username\"], cred[\"password\"]),\n timeout=HTTP_REQ_TIMEOUT,\n@@ -84,11 +98,21 @@ class TokenAuth(Authentication):\n token = response.json()[self.config.token_key]\n else:\n token = response.text\n+ headers = self._get_headers(token)\n+ self.token = token\n # Return auth class set with obtained token\n- return RequestsTokenAuth(token, \"header\", headers=self._get_headers(token))\n+ return RequestsTokenAuth(token, \"header\", headers=headers)\n \n def _get_headers(self, token):\n headers = self.config.headers\n if \"Authorization\" in headers and \"$\" in headers[\"Authorization\"]:\n headers[\"Authorization\"] = headers[\"Authorization\"].replace(\"$token\", token)\n+ if (\n+ self.token\n+ and token != self.token\n+ and self.token in headers[\"Authorization\"]\n+ ):\n+ headers[\"Authorization\"] = headers[\"Authorization\"].replace(\n+ self.token, token\n+ )\n return headers\ndiff --git a/eodag/plugins/download/base.py b/eodag/plugins/download/base.py\nindex dce4db23..1e040cef 100644\n--- a/eodag/plugins/download/base.py\n+++ b/eodag/plugins/download/base.py\n@@ -373,7 +373,7 @@ class Download(PluginTopic):\n shutil.move(extraction_dir, outputs_dir)\n \n elif fs_path.endswith(\".tar.gz\"):\n- with tarfile.open(fs_path, \"r:gz\") as zfile:\n+ with tarfile.open(fs_path, \"r\") as zfile:\n progress_callback.reset(total=1)\n zfile.extractall(path=extraction_dir)\n progress_callback(1)\ndiff --git a/eodag/plugins/search/data_request_search.py b/eodag/plugins/search/data_request_search.py\nindex 1f6c586e..0bf2b043 100644\n--- a/eodag/plugins/search/data_request_search.py\n+++ b/eodag/plugins/search/data_request_search.py\n@@ -11,6 +11,7 @@ from eodag.api.product.metadata_mapping import (\n )\n from eodag.plugins.search.base import Search\n from eodag.utils import GENERIC_PRODUCT_TYPE, string_to_jsonpath\n+from eodag.utils.exceptions import RequestError\n \n logger = logging.getLogger(\"eodag.search.data_request_search\")\n \n@@ -91,10 +92,9 @@ class DataRequestSearch(Search):\n metadata = requests.get(metadata_url, headers=headers)\n metadata.raise_for_status()\n except requests.RequestException:\n- logger.error(\n- \"metadata for product_type %s could not be retrieved\", product_type\n+ raise RequestError(\n+ f\"metadata for product_type {product_type} could not be retrieved\"\n )\n- raise\n else:\n try:\n url = self.config.data_request_url\n@@ -107,11 +107,8 @@ class DataRequestSearch(Search):\n request_job = requests.post(url, json=request_body, headers=headers)\n request_job.raise_for_status()\n except requests.RequestException as e:\n- logger.error(\n- \"search job for product_type %s could not be created: %s, %s\",\n- product_type,\n- str(e),\n- request_job.text,\n+ raise RequestError(\n+ f\"search job for product_type {product_type} could not be created: {str(e)}, {request_job.text}\"\n )\n else:\n logger.info(\"search job for product_type %s created\", product_type)\n@@ -122,13 +119,11 @@ class DataRequestSearch(Search):\n status_url = self.config.status_url + data_request_id\n status_data = requests.get(status_url, headers=self.auth.headers).json()\n if \"status_code\" in status_data and status_data[\"status_code\"] == 403:\n- logger.error(\"authentication token expired during request\")\n- raise requests.RequestException\n+ raise RequestError(\"authentication token expired during request\")\n if status_data[\"status\"] == \"failed\":\n- logger.error(\n- \"data request job has failed, message: %s\", status_data[\"message\"]\n+ raise RequestError(\n+ f\"data request job has failed, message: {status_data['message']}\"\n )\n- raise requests.RequestException\n return status_data[\"status\"] == \"completed\"\n \n def _get_result_data(self, data_request_id):\ndiff --git a/eodag/rest/server.py b/eodag/rest/server.py\nindex 0c9ecbda..57cc4381 100755\n--- a/eodag/rest/server.py\n+++ b/eodag/rest/server.py\n@@ -233,12 +233,13 @@ async def handle_resource_not_found(request: Request, error):\n \n @app.exception_handler(AuthenticationError)\n async def handle_auth_error(request: Request, error):\n- \"\"\"Unauthorized [401] errors handle\"\"\"\n+ \"\"\"AuthenticationError should be sent as internal server error to the client\"\"\"\n+ logger.error(f\"{type(error).__name__}: {str(error)}\")\n return await default_exception_handler(\n request,\n HTTPException(\n- status_code=401,\n- detail=f\"{type(error).__name__}: {str(error)}\",\n+ status_code=500,\n+ detail=\"Internal server error: please contact the administrator\",\n ),\n )\n \n@@ -409,12 +410,9 @@ def stac_collections_item_download(collection_id, item_id, request: Request):\n body = {}\n arguments = dict(request.query_params, **body)\n provider = arguments.pop(\"provider\", None)\n- zipped = \"True\"\n- if \"zip\" in arguments:\n- zipped = arguments[\"zip\"]\n \n return download_stac_item_by_id_stream(\n- catalogs=[collection_id], item_id=item_id, provider=provider, zip=zipped\n+ catalogs=[collection_id], item_id=item_id, provider=provider\n )\n \n \ndiff --git a/eodag/rest/stac.py b/eodag/rest/stac.py\nindex 6e8fcbe5..afbcbce1 100644\n--- a/eodag/rest/stac.py\n+++ b/eodag/rest/stac.py\n@@ -83,9 +83,6 @@ class StacCommon(object):\n \n self.data = {}\n \n- if self.provider and self.eodag_api.get_preferred_provider() != self.provider:\n- self.eodag_api.set_preferred_provider(self.provider)\n-\n def update_data(self, data):\n \"\"\"Updates data using given input STAC dict data\n \ndiff --git a/eodag/rest/utils.py b/eodag/rest/utils.py\nindex afa872ae..8fbda850 100644\n--- a/eodag/rest/utils.py\n+++ b/eodag/rest/utils.py\n@@ -393,6 +393,10 @@ def search_products(product_type, arguments, stac_formatted=True):\n \n try:\n arg_product_type = arguments.pop(\"product_type\", None)\n+ provider = arguments.pop(\"provider\", None)\n+ if not provider:\n+ provider = eodag_api.get_preferred_provider()[0]\n+\n unserialized = arguments.pop(\"unserialized\", None)\n \n page, items_per_page = get_pagination_info(arguments)\n@@ -407,6 +411,7 @@ def search_products(product_type, arguments, stac_formatted=True):\n \"start\": dtstart,\n \"end\": dtend,\n \"geom\": geom,\n+ \"provider\": provider,\n }\n \n if stac_formatted:\n@@ -455,20 +460,24 @@ def search_products(product_type, arguments, stac_formatted=True):\n return response\n \n \n-def search_product_by_id(uid, product_type=None):\n+def search_product_by_id(uid, product_type=None, provider=None):\n \"\"\"Search a product by its id\n \n :param uid: The uid of the EO product\n :type uid: str\n :param product_type: (optional) The product type\n :type product_type: str\n+ :param provider: (optional) The provider to be used\n+ :type provider: str\n :returns: A search result\n :rtype: :class:`~eodag.api.search_result.SearchResult`\n :raises: :class:`~eodag.utils.exceptions.ValidationError`\n :raises: RuntimeError\n \"\"\"\n try:\n- products, total = eodag_api.search(id=uid, productType=product_type)\n+ products, total = eodag_api.search(\n+ id=uid, productType=product_type, provider=provider\n+ )\n return products\n except ValidationError:\n raise\n@@ -573,7 +582,7 @@ def get_stac_item_by_id(url, item_id, catalogs, root=\"/\", provider=None):\n return None\n \n \n-def download_stac_item_by_id_stream(catalogs, item_id, provider=None, zip=\"True\"):\n+def download_stac_item_by_id_stream(catalogs, item_id, provider=None):\n \"\"\"Download item\n \n :param catalogs: Catalogs list (only first is used as product_type)\n@@ -587,17 +596,16 @@ def download_stac_item_by_id_stream(catalogs, item_id, provider=None, zip=\"True\"\n :returns: a stream of the downloaded data (either as a zip or the individual assets)\n :rtype: StreamingResponse\n \"\"\"\n- if provider:\n- eodag_api.set_preferred_provider(provider)\n-\n- product = search_product_by_id(item_id, product_type=catalogs[0])[0]\n-\n+ product = search_product_by_id(\n+ item_id, product_type=catalogs[0], provider=provider\n+ )[0]\n if product.downloader is None:\n download_plugin = eodag_api._plugins_manager.get_download_plugin(product)\n auth_plugin = eodag_api._plugins_manager.get_auth_plugin(\n download_plugin.provider\n )\n product.register_downloader(download_plugin, auth_plugin)\n+\n auth = (\n product.downloader_auth.authenticate()\n if product.downloader_auth is not None\n@@ -664,7 +672,7 @@ def get_stac_catalogs(url, root=\"/\", catalogs=[], provider=None, fetch_providers\n :param fetch_providers: (optional) Whether to fetch providers for new product\n types or not\n :type fetch_providers: bool\n- :returns: Catalog dictionnary\n+ :returns: Catalog dictionary\n :rtype: dict\n \"\"\"\n return StacCatalog(\n@@ -734,10 +742,10 @@ def search_stac_items(url, arguments, root=\"/\", catalogs=[], provider=None):\n ids = [ids]\n if ids:\n search_results = SearchResult([])\n- if provider:\n- eodag_api.set_preferred_provider(provider)\n for item_id in ids:\n- found_products = search_product_by_id(item_id, product_type=collections[0])\n+ found_products = search_product_by_id(\n+ item_id, product_type=collections[0], provider=provider\n+ )\n if len(found_products) == 1:\n search_results.extend(found_products)\n search_results.properties = {\n@@ -769,7 +777,9 @@ def search_stac_items(url, arguments, root=\"/\", catalogs=[], provider=None):\n arguments.pop(\"datetime\")\n \n search_products_arguments = dict(\n- arguments, **result_catalog.search_args, **{\"unserialized\": \"true\"}\n+ arguments,\n+ **result_catalog.search_args,\n+ **{\"unserialized\": \"true\", \"provider\": provider},\n )\n \n # check if time filtering appears twice\n@@ -825,7 +835,6 @@ def search_stac_items(url, arguments, root=\"/\", catalogs=[], provider=None):\n **{\"url\": result_catalog.url, \"root\": result_catalog.root},\n ),\n )\n-\n search_results = search_products(\n product_type=result_catalog.search_args[\"product_type\"],\n arguments=search_products_arguments,\n", "test_patch": "diff --git a/tests/integration/test_core_search_results.py b/tests/integration/test_core_search_results.py\nindex 8d94a465..1fff5fe7 100644\n--- a/tests/integration/test_core_search_results.py\n+++ b/tests/integration/test_core_search_results.py\n@@ -264,3 +264,23 @@ class TestCoreSearchResults(EODagTestCase):\n for search_result in search_results:\n self.assertIsInstance(search_result.downloader, PluginTopic)\n self.assertIsInstance(search_result.downloader_auth, PluginTopic)\n+\n+ @mock.patch(\n+ \"eodag.plugins.search.qssearch.QueryStringSearch.do_search\",\n+ autospec=True,\n+ )\n+ def test_core_search_with_provider(self, mock_query):\n+ \"\"\"The core api must register search results downloaders\"\"\"\n+ self.dag.set_preferred_provider(\"creodias\")\n+ search_results_file = os.path.join(\n+ TEST_RESOURCES_PATH, \"provider_responses/peps_search.json\"\n+ )\n+ with open(search_results_file, encoding=\"utf-8\") as f:\n+ search_results_peps = json.load(f)\n+\n+ mock_query.return_value = search_results_peps[\"features\"]\n+ search_results, count = self.dag.search(\n+ productType=\"S2_MSI_L1C\", provider=\"peps\"\n+ )\n+ # use given provider and not preferred provider\n+ self.assertEqual(\"peps\", search_results[0].provider)\ndiff --git a/tests/units/test_auth_plugins.py b/tests/units/test_auth_plugins.py\nindex 93c8d71d..70cf6c2d 100644\n--- a/tests/units/test_auth_plugins.py\n+++ b/tests/units/test_auth_plugins.py\n@@ -129,7 +129,9 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n auth_plugin.config.credentials = {\"foo\": \"bar\", \"username\": \"john\"}\n auth_plugin.validate_config_credentials()\n \n- @mock.patch(\"eodag.plugins.authentication.token.requests.post\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.post\", autospec=True\n+ )\n def test_plugins_auth_tokenauth_text_token_authenticate(self, mock_requests_post):\n \"\"\"TokenAuth.authenticate must return a RequestsTokenAuth object using text token\"\"\"\n auth_plugin = self.get_auth_plugin(\"provider_text_token_header\")\n@@ -146,7 +148,7 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n \n # check token post request call arguments\n args, kwargs = mock_requests_post.call_args\n- assert args[0] == auth_plugin.config.auth_uri\n+ assert args[1] == auth_plugin.config.auth_uri\n assert kwargs[\"data\"] == auth_plugin.config.credentials\n assert kwargs[\"headers\"] == dict(auth_plugin.config.headers, **USER_AGENT)\n \n@@ -156,7 +158,9 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n assert req.headers[\"Authorization\"] == \"Bearer this_is_test_token\"\n assert req.headers[\"foo\"] == \"bar\"\n \n- @mock.patch(\"eodag.plugins.authentication.token.requests.post\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.post\", autospec=True\n+ )\n def test_plugins_auth_tokenauth_json_token_authenticate(self, mock_requests_post):\n \"\"\"TokenAuth.authenticate must return a RequestsTokenAuth object using json token\"\"\"\n auth_plugin = self.get_auth_plugin(\"provider_json_token_simple_url\")\n@@ -179,7 +183,9 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n auth(req)\n assert req.headers[\"Authorization\"] == \"Bearer this_is_test_token\"\n \n- @mock.patch(\"eodag.plugins.authentication.token.requests.post\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.post\", autospec=True\n+ )\n def test_plugins_auth_tokenauth_request_error(self, mock_requests_post):\n \"\"\"TokenAuth.authenticate must raise an AuthenticationError if a request error occurs\"\"\"\n auth_plugin = self.get_auth_plugin(\"provider_json_token_simple_url\")\ndiff --git a/tests/units/test_core.py b/tests/units/test_core.py\nindex 092beac5..c3b4347e 100644\n--- a/tests/units/test_core.py\n+++ b/tests/units/test_core.py\n@@ -1292,7 +1292,7 @@ class TestCoreSearch(TestCoreBase):\n \"\"\"_prepare_search must handle a search by id\"\"\"\n base = {\"id\": \"dummy-id\", \"provider\": \"creodias\"}\n prepared_search = self.dag._prepare_search(**base)\n- expected = base\n+ expected = {\"id\": \"dummy-id\"}\n self.assertDictEqual(expected, prepared_search)\n \n def test__prepare_search_preserve_additional_kwargs(self):\ndiff --git a/tests/units/test_http_server.py b/tests/units/test_http_server.py\nindex d1a8a9aa..9a144cd8 100644\n--- a/tests/units/test_http_server.py\n+++ b/tests/units/test_http_server.py\n@@ -317,6 +317,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"search?collections={self.tested_product_type}\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -326,6 +327,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=0,43,1,44\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -344,22 +346,26 @@ class RequestTestCase(unittest.TestCase):\n side_effect=AuthenticationError(\"you are no authorized\"),\n )\n def test_auth_error(self, mock_search):\n- \"\"\"A request to eodag server raising a Authentication error must return a 401 HTTP error code\"\"\"\n- response = self.app.get(\n- f\"search?collections={self.tested_product_type}\", follow_redirects=True\n- )\n- response_content = json.loads(response.content.decode(\"utf-8\"))\n+ \"\"\"A request to eodag server raising a Authentication error must return a 500 HTTP error code\"\"\"\n \n- self.assertEqual(401, response.status_code)\n- self.assertIn(\"description\", response_content)\n- self.assertIn(\"AuthenticationError\", response_content[\"description\"])\n- self.assertIn(\"you are no authorized\", response_content[\"description\"])\n+ with self.assertLogs(level=\"ERROR\") as cm_logs:\n+ response = self.app.get(\n+ f\"search?collections={self.tested_product_type}\", follow_redirects=True\n+ )\n+ response_content = json.loads(response.content.decode(\"utf-8\"))\n+\n+ self.assertIn(\"description\", response_content)\n+ self.assertIn(\"AuthenticationError\", str(cm_logs.output))\n+ self.assertIn(\"you are no authorized\", str(cm_logs.output))\n+\n+ self.assertEqual(500, response.status_code)\n \n def test_filter(self):\n \"\"\"latestIntersect filter should only keep the latest products once search area is fully covered\"\"\"\n result1 = self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=89.65,2.65,89.7,2.7\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -371,6 +377,7 @@ class RequestTestCase(unittest.TestCase):\n result2 = self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=89.65,2.65,89.7,2.7&filter=latestIntersect\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -386,6 +393,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -401,6 +409,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"collections/{self.tested_product_type}/items?bbox=0,43,1,44\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -411,6 +420,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"collections/{self.tested_product_type}/items?bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -426,6 +436,7 @@ class RequestTestCase(unittest.TestCase):\n results = self._request_valid(\n f\"catalogs/{self.tested_product_type}/year/2018/month/01/items?bbox=0,43,1,44\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -441,6 +452,7 @@ class RequestTestCase(unittest.TestCase):\n f\"catalogs/{self.tested_product_type}/year/2018/month/01/items\"\n \"?bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -456,6 +468,7 @@ class RequestTestCase(unittest.TestCase):\n f\"catalogs/{self.tested_product_type}/year/2018/month/01/items\"\n \"?bbox=0,43,1,44&datetime=2018-01-20/2019-01-01\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -489,6 +502,7 @@ class RequestTestCase(unittest.TestCase):\n f\"catalogs/{self.tested_product_type}/items/foo\",\n expected_search_kwargs={\n \"id\": \"foo\",\n+ \"provider\": None,\n \"productType\": self.tested_product_type,\n },\n )\n@@ -499,6 +513,7 @@ class RequestTestCase(unittest.TestCase):\n f\"collections/{self.tested_product_type}/items/foo\",\n expected_search_kwargs={\n \"id\": \"foo\",\n+ \"provider\": None,\n \"productType\": self.tested_product_type,\n },\n )\n@@ -521,6 +536,7 @@ class RequestTestCase(unittest.TestCase):\n \"query\": {\"eo:cloud_cover\": {\"lte\": 10}},\n },\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\ndiff --git a/tests/units/test_search_plugins.py b/tests/units/test_search_plugins.py\nindex 9e09dc6f..9d99ea9f 100644\n--- a/tests/units/test_search_plugins.py\n+++ b/tests/units/test_search_plugins.py\n@@ -22,7 +22,6 @@ import unittest\n from pathlib import Path\n from unittest import mock\n \n-import requests\n import responses\n from requests import RequestException\n \n@@ -936,10 +935,11 @@ class MockResponse:\n \n \n class TestSearchPluginDataRequestSearch(BaseSearchPluginTest):\n- @mock.patch(\"eodag.plugins.authentication.token.requests.get\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.get\", autospec=True\n+ )\n def setUp(self, mock_requests_get):\n \n- # One of the providers that has a BuildPostSearchResult Search plugin\n provider = \"wekeo\"\n self.search_plugin = self.get_search_plugin(self.product_type, provider)\n self.auth_plugin = self.get_auth_plugin(provider)\n@@ -973,7 +973,7 @@ class TestSearchPluginDataRequestSearch(BaseSearchPluginTest):\n mock_requests_get.return_value = MockResponse(\n {\"status\": \"failed\", \"message\": \"failed\"}, 500\n )\n- with self.assertRaises(requests.RequestException):\n+ with self.assertRaises(RequestError):\n self.search_plugin._check_request_status(\"123\")\n \n @mock.patch(\"eodag.plugins.search.data_request_search.requests.get\", autospec=True)\ndiff --git a/tests/units/test_stac_utils.py b/tests/units/test_stac_utils.py\nindex 0c8f618d..50ea9dff 100644\n--- a/tests/units/test_stac_utils.py\n+++ b/tests/units/test_stac_utils.py\n@@ -447,6 +447,7 @@ class TestStacUtils(unittest.TestCase):\n mock__request.return_value.json.return_value = (\n self.earth_search_resp_search_json\n )\n+ self.rest_utils.eodag_api.set_preferred_provider(\"peps\")\n \n response = self.rest_utils.search_stac_items(\n url=\"http://foo/search\",\n@@ -467,6 +468,8 @@ class TestStacUtils(unittest.TestCase):\n \"assets\"\n ].items():\n self.assertIn((k, v), response[\"features\"][0][\"assets\"].items())\n+ # preferred provider should not be changed\n+ self.assertEqual(\"peps\", self.rest_utils.eodag_api.get_preferred_provider()[0])\n \n @mock.patch(\n \"eodag.plugins.search.qssearch.QueryStringSearch._request\",\n", "FAIL_TO_PASS": ["tests/integration/test_core_search_results.py::TestCoreSearchResults::test_core_search_with_provider", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_json_token_authenticate", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_text_token_authenticate", "tests/units/test_core.py::TestCoreSearch::test__prepare_search_with_id", "tests/units/test_http_server.py::RequestTestCase::test_auth_error", "tests/units/test_http_server.py::RequestTestCase::test_cloud_cover_post_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_catalog_items", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_items", "tests/units/test_http_server.py::RequestTestCase::test_filter", "tests/units/test_http_server.py::RequestTestCase::test_request_params", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_catalog", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_collection", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_check_request_status", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_create_data_request", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_get_result_data", "tests/units/test_stac_utils.py::TestStacUtils::test_search_stac_items_with_stac_providers"]}], "all_FAIL_TO_PASS": ["tests/integration/test_core_search_results.py::TestCoreSearchResults::test_core_search_with_provider", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_json_token_authenticate", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_text_token_authenticate", "tests/units/test_core.py::TestCoreSearch::test__prepare_search_with_id", "tests/units/test_http_server.py::RequestTestCase::test_auth_error", "tests/units/test_http_server.py::RequestTestCase::test_cloud_cover_post_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_catalog_items", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_items", "tests/units/test_http_server.py::RequestTestCase::test_filter", "tests/units/test_http_server.py::RequestTestCase::test_request_params", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_catalog", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_collection", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_check_request_status", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_create_data_request", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_get_result_data", "tests/units/test_stac_utils.py::TestStacUtils::test_search_stac_items_with_stac_providers"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getmoto__moto-5876_x1", "level": 1, "source": "swerebenchv2", "repo": "getmoto/moto", "image": "swerebenchv2/getmoto-moto:5876-6d41ad7", "base_commit": "6d41ad72e09b49f61e54d47880f8a65026e7c0e4", "num_bugs": 1, "bugs": [{"instance_id": "getmoto__moto-5876", "base_commit": "6d41ad72e09b49f61e54d47880f8a65026e7c0e4", "gold_patch": "diff --git a/moto/cognitoidp/exceptions.py b/moto/cognitoidp/exceptions.py\nindex b234a5238..8271af59e 100644\n--- a/moto/cognitoidp/exceptions.py\n+++ b/moto/cognitoidp/exceptions.py\n@@ -2,6 +2,13 @@ from moto.core.exceptions import JsonRESTError\n from typing import Optional\n \n \n+class AliasExistsException(JsonRESTError):\n+ def __init__(self) -> None:\n+ super().__init__(\n+ \"AliasExistsException\", \"An account with the given email already exists.\"\n+ )\n+\n+\n class ResourceNotFoundError(JsonRESTError):\n def __init__(self, message: Optional[str]):\n super().__init__(error_type=\"ResourceNotFoundException\", message=message or \"\")\ndiff --git a/moto/cognitoidp/models.py b/moto/cognitoidp/models.py\nindex 3ddb8f113..3c6e97c62 100644\n--- a/moto/cognitoidp/models.py\n+++ b/moto/cognitoidp/models.py\n@@ -11,6 +11,7 @@ from typing import Any, Dict, List, Tuple, Optional, Set\n from moto.core import BaseBackend, BackendDict, BaseModel\n from moto.moto_api._internal import mock_random as random\n from .exceptions import (\n+ AliasExistsException,\n GroupExistsException,\n NotAuthorizedError,\n ResourceNotFoundError,\n@@ -1636,6 +1637,9 @@ class CognitoIdpBackend(BaseBackend):\n ) -> None:\n user = self.admin_get_user(user_pool_id, username)\n \n+ email = self._find_attr(\"email\", attributes)\n+ self._verify_email_is_not_used(user_pool_id, email)\n+\n user.update_attributes(attributes)\n \n def admin_delete_user_attributes(\n@@ -2031,11 +2035,32 @@ class CognitoIdpBackend(BaseBackend):\n _, username = user_pool.access_tokens[access_token]\n user = self.admin_get_user(user_pool.id, username)\n \n+ email = self._find_attr(\"email\", attributes)\n+ self._verify_email_is_not_used(user_pool.id, email)\n+\n user.update_attributes(attributes)\n return\n \n raise NotAuthorizedError(access_token)\n \n+ def _find_attr(self, name: str, attrs: List[Dict[str, str]]) -> Optional[str]:\n+ return next((a[\"Value\"] for a in attrs if a[\"Name\"] == name), None)\n+\n+ def _verify_email_is_not_used(\n+ self, user_pool_id: str, email: Optional[str]\n+ ) -> None:\n+ if not email:\n+ # We're not updating emails\n+ return\n+ user_pool = self.describe_user_pool(user_pool_id)\n+ if \"email\" not in user_pool.extended_config.get(\"UsernameAttributes\", []):\n+ # email is not used as a username - duplicate emails are allowed\n+ return\n+\n+ for user in user_pool.users.values():\n+ if user.attribute_lookup.get(\"email\", \"\") == email:\n+ raise AliasExistsException\n+\n \n class RegionAgnosticBackend:\n # Some operations are unauthenticated\n", "test_patch": "diff --git a/tests/test_cognitoidp/test_cognitoidp_exceptions.py b/tests/test_cognitoidp/test_cognitoidp_exceptions.py\nindex ec19de0a0..0cd827bdc 100644\n--- a/tests/test_cognitoidp/test_cognitoidp_exceptions.py\n+++ b/tests/test_cognitoidp/test_cognitoidp_exceptions.py\n@@ -1,6 +1,8 @@\n from unittest import TestCase\n \n import boto3\n+import pytest\n+\n from moto import mock_cognitoidp\n from botocore.exceptions import ClientError\n \n@@ -49,3 +51,47 @@ class TestCognitoUserDeleter(TestCase):\n },\n )\n exc.exception.response[\"Error\"][\"Code\"].should.equal(\"NotAuthorizedException\")\n+\n+\n+@mock_cognitoidp\n+class TestCognitoUserPoolDuplidateEmails(TestCase):\n+ def setUp(self) -> None:\n+ self.client = boto3.client(\"cognito-idp\", \"us-east-1\")\n+\n+ self.pool_id1 = self.client.create_user_pool(PoolName=\"test\")[\"UserPool\"][\"Id\"]\n+ self.pool_id2 = self.client.create_user_pool(\n+ PoolName=\"test\", UsernameAttributes=[\"email\"]\n+ )[\"UserPool\"][\"Id\"]\n+\n+ # create two users\n+ for user in [\"user1\", \"user2\"]:\n+ self.client.admin_create_user(\n+ UserPoolId=self.pool_id1,\n+ Username=user,\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": f\"{user}@test.com\"}],\n+ )\n+ self.client.admin_create_user(\n+ UserPoolId=self.pool_id2,\n+ Username=f\"{user}@test.com\",\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": f\"{user}@test.com\"}],\n+ )\n+\n+ def test_use_existing_email__when_email_is_login(self):\n+ with pytest.raises(ClientError) as exc:\n+ self.client.admin_update_user_attributes(\n+ UserPoolId=self.pool_id2,\n+ Username=\"user1@test.com\",\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": \"user2@test.com\"}],\n+ )\n+ err = exc.value.response[\"Error\"]\n+ err[\"Code\"].should.equal(\"AliasExistsException\")\n+ err[\"Message\"].should.equal(\"An account with the given email already exists.\")\n+\n+ def test_use_existing_email__when_username_is_login(self):\n+ # Because we cannot use the email as username,\n+ # multiple users can have the same email address\n+ self.client.admin_update_user_attributes(\n+ UserPoolId=self.pool_id1,\n+ Username=\"user1\",\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": \"user2@test.com\"}],\n+ )\n", "FAIL_TO_PASS": ["tests/test_cognitoidp/test_cognitoidp_exceptions.py::TestCognitoUserPoolDuplidateEmails::test_use_existing_email__when_email_is_login"]}], "all_FAIL_TO_PASS": ["tests/test_cognitoidp/test_cognitoidp_exceptions.py::TestCognitoUserPoolDuplidateEmails::test_use_existing_email__when_email_is_login"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "litestar-org__polyfactory-472_x1", "level": 1, "source": "swerebenchv2", "repo": "litestar-org/polyfactory", "image": "swerebenchv2/litestar-org-polyfactory:472-fb4e50a", "base_commit": "fb4e50acaa0796ed7164457c6c767c3351530a81", "num_bugs": 1, "bugs": [{"instance_id": "litestar-org__polyfactory-472", "base_commit": "fb4e50acaa0796ed7164457c6c767c3351530a81", "gold_patch": "diff --git a/docs/usage/configuration.rst b/docs/usage/configuration.rst\nindex d38d53c..2905556 100644\n--- a/docs/usage/configuration.rst\n+++ b/docs/usage/configuration.rst\n@@ -92,7 +92,7 @@ Set of fields that allow you to generate a collection with random lengths. By de\n :language: python\n \n Allow None Optionals\n-----------------------------\n+--------------------\n \n Allow `None` to be generated as a value for types marked as optional. When set to `True`, the outputted value will be randomly chosen between `None` and other allowed types. By default, this is set to `True`.\n \n@@ -113,3 +113,20 @@ Any other field definition will not be checked.\n .. literalinclude:: /examples/configuration/test_example_8.py\n :caption: Enable Check Factory Fields\n :language: python\n+\n+Use Default Values\n+------------------\n+\n+If ``__use_default__`` is set to ``True``, then the default value will be used instead of creating a random value\n+for a given field, provided there's a default value for that field.\n+\n+By default, ``__use_default__`` is set to ``False.`` If you need more fine grained control, you can override the\n+:meth:`~polyfactory.factories.base.BaseFactory.should_use_default_value` classmethod.\n+\n+.. note::\n+ Setting ``__use_default__`` has no effect for ``TypedDictFactory`` since you cannot set default values for\n+ ``TypedDict``.\n+\n+.. literalinclude:: /examples/configuration/test_example_9.py\n+ :caption: Use Default Values\n+ :language: python\ndiff --git a/polyfactory/factories/base.py b/polyfactory/factories/base.py\nindex 242b73c..3893b7b 100644\n--- a/polyfactory/factories/base.py\n+++ b/polyfactory/factories/base.py\n@@ -23,6 +23,8 @@ from os.path import realpath\n from pathlib import Path\n from random import Random\n \n+from polyfactory.field_meta import Null\n+\n try:\n from types import NoneType\n except ImportError:\n@@ -167,6 +169,10 @@ class BaseFactory(ABC, Generic[T]):\n \"\"\"\n An integer value that defines maximum length of a collection.\n \"\"\"\n+ __use_defaults__: ClassVar[bool] = False\n+ \"\"\"\n+ Flag indicating whether to use the default value on a specific field, if provided.\n+ \"\"\"\n \n # cached attributes\n _fields_metadata: list[FieldMeta]\n@@ -774,6 +780,20 @@ class BaseFactory(ABC, Generic[T]):\n and create_random_boolean(random=cls.__random__)\n )\n \n+ @classmethod\n+ def should_use_default_value(cls, field_meta: FieldMeta) -> bool:\n+ \"\"\"Determine whether to use the default value for the given field.\n+\n+ :param field_meta: FieldMeta instance.\n+\n+ :notes:\n+ - This method is distinct to allow overriding.\n+\n+ :returns: A boolean determining whether the default value should be used for the given field_meta.\n+\n+ \"\"\"\n+ return cls.__use_defaults__ and field_meta.default is not Null\n+\n @classmethod\n def should_set_field_value(cls, field_meta: FieldMeta, **kwargs: Any) -> bool:\n \"\"\"Determine whether to set a value for a given field_name.\n@@ -846,7 +866,7 @@ class BaseFactory(ABC, Generic[T]):\n \n for field_meta in cls.get_model_fields():\n field_build_parameters = cls.extract_field_build_parameters(field_meta=field_meta, build_args=kwargs)\n- if cls.should_set_field_value(field_meta, **kwargs):\n+ if cls.should_set_field_value(field_meta, **kwargs) and not cls.should_use_default_value(field_meta):\n if hasattr(cls, field_meta.name) and not hasattr(BaseFactory, field_meta.name):\n field_value = getattr(cls, field_meta.name)\n if isinstance(field_value, Ignore):\n", "test_patch": "diff --git a/docs/examples/configuration/test_example_9.py b/docs/examples/configuration/test_example_9.py\nnew file mode 100644\nindex 0000000..50371cd\n--- /dev/null\n+++ b/docs/examples/configuration/test_example_9.py\n@@ -0,0 +1,28 @@\n+from dataclasses import dataclass\n+from enum import Enum\n+\n+from polyfactory.factories import DataclassFactory\n+\n+\n+class Species(str, Enum):\n+ CAT = \"Cat\"\n+ DOG = \"Dog\"\n+\n+\n+@dataclass\n+class Pet:\n+ name: str\n+ sound: str = \"meow\"\n+ species: Species = Species.CAT\n+\n+\n+class PetFactory(DataclassFactory[Pet]):\n+ __model__ = Pet\n+ __use_defaults__ = True\n+\n+\n+def test_use_default() -> None:\n+ pet = PetFactory.build()\n+\n+ assert pet.species == Species.CAT\n+ assert pet.sound == \"meow\"\ndiff --git a/tests/test_attrs_factory.py b/tests/test_attrs_factory.py\nindex fbbae97..be5b8d6 100644\n--- a/tests/test_attrs_factory.py\n+++ b/tests/test_attrs_factory.py\n@@ -191,3 +191,31 @@ def test_with_init_false() -> None:\n __model__ = Foo\n \n assert FooFactory.build()\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ @define\n+ class Foo:\n+ default_field: int = attrs.field(default=attrs.Factory(lambda: 10, takes_self=False))\n+\n+ class FooFactory(AttrsFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ @define\n+ class Foo:\n+ default_field: int = attrs.field(default=10)\n+\n+ class FooFactory(AttrsFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\ndiff --git a/tests/test_dataclass_factory.py b/tests/test_dataclass_factory.py\nindex eb06199..6dd7e1b 100644\n--- a/tests/test_dataclass_factory.py\n+++ b/tests/test_dataclass_factory.py\n@@ -1,3 +1,4 @@\n+import dataclasses\n from dataclasses import dataclass as vanilla_dataclass\n from dataclasses import field\n from types import ModuleType\n@@ -205,3 +206,31 @@ def test_dataclass_with_init_false() -> None:\n result = MyFactory.build()\n \n assert result\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ @vanilla_dataclass\n+ class Foo:\n+ default_field: int = dataclasses.field(default_factory=lambda: 10)\n+\n+ class FooFactory(DataclassFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ @vanilla_dataclass\n+ class Foo:\n+ default_field: int = 10\n+\n+ class FooFactory(DataclassFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\ndiff --git a/tests/test_msgspec_factory.py b/tests/test_msgspec_factory.py\nindex 02ebe60..de2f981 100644\n--- a/tests/test_msgspec_factory.py\n+++ b/tests/test_msgspec_factory.py\n@@ -249,3 +249,29 @@ def test_mapping_with_constrained_item_types() -> None:\n validated_foo = msgspec.convert(structs.asdict(foo), Foo)\n \n assert validated_foo == foo\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ class Foo(Struct):\n+ default_field: int = msgspec.field(default_factory=lambda: 10)\n+\n+ class FooFactory(MsgspecFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ class Foo(Struct):\n+ default_field: int = 10\n+\n+ class FooFactory(MsgspecFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\ndiff --git a/tests/test_pydantic_factory.py b/tests/test_pydantic_factory.py\nindex b15a7d7..f04fb1f 100644\n--- a/tests/test_pydantic_factory.py\n+++ b/tests/test_pydantic_factory.py\n@@ -107,3 +107,29 @@ def test_mapping_with_annotated_item_types() -> None:\n __model__ = Foo\n \n assert FooFactory.build()\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ class Foo(BaseModel):\n+ default_field: int = Field(default_factory=lambda: 10)\n+\n+ class FooFactory(ModelFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ class Foo(BaseModel):\n+ default_field: int = Field(default=10)\n+\n+ class FooFactory(ModelFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n", "FAIL_TO_PASS": ["docs/examples/configuration/test_example_9.py::test_use_default", "tests/test_attrs_factory.py::test_use_default_with_callable_default", "tests/test_attrs_factory.py::test_use_default_with_non_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_non_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_non_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_non_callable_default"]}], "all_FAIL_TO_PASS": ["docs/examples/configuration/test_example_9.py::test_use_default", "tests/test_attrs_factory.py::test_use_default_with_callable_default", "tests/test_attrs_factory.py::test_use_default_with_non_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_non_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_non_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_non_callable_default"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3117_x1", "level": 1, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3117-e093a00", "base_commit": "e093a00f61fbda25c17d24658522f2c7a7e2dc53", "num_bugs": 1, "bugs": [{"instance_id": "openmdao__openmdao-3117", "base_commit": "e093a00f61fbda25c17d24658522f2c7a7e2dc53", "gold_patch": "diff --git a/openmdao/core/component.py b/openmdao/core/component.py\nindex bf56bbd27..8f34070dc 100644\n--- a/openmdao/core/component.py\n+++ b/openmdao/core/component.py\n@@ -386,7 +386,7 @@ class Component(System):\n \n def _get_missing_partials(self, missing):\n \"\"\"\n- Return a list of (of, wrt) tuples for which derivatives have not been declared.\n+ Provide (of, wrt) tuples for which derivatives have not been declared in the component.\n \n Parameters\n ----------\ndiff --git a/openmdao/core/driver.py b/openmdao/core/driver.py\nindex 68347a26c..f48048433 100644\n--- a/openmdao/core/driver.py\n+++ b/openmdao/core/driver.py\n@@ -8,6 +8,7 @@ import weakref\n \n import numpy as np\n \n+from openmdao.core.group import Group\n from openmdao.core.total_jac import _TotalJacInfo\n from openmdao.core.constants import INT_DTYPE, _SetupStatus\n from openmdao.recorders.recording_manager import RecordingManager\n@@ -949,6 +950,13 @@ class Driver(object):\n return\n \n problem = self._problem()\n+\n+ # Do not perform this check if any subgroup uses approximated partials.\n+ # This causes the relevance graph to be invalid.\n+ for system in problem.model.system_iter(include_self=True, recurse=True, typ=Group):\n+ if system._has_approx:\n+ return\n+\n relevant = problem.model._relevant\n fwd = problem._mode == 'fwd'\n \ndiff --git a/openmdao/core/group.py b/openmdao/core/group.py\nindex 0839e0f0e..9eea60b42 100644\n--- a/openmdao/core/group.py\n+++ b/openmdao/core/group.py\n@@ -4026,13 +4026,15 @@ class Group(System):\n \n def _get_missing_partials(self, missing):\n \"\"\"\n- Return a list of (of, wrt) tuples for which derivatives have not been declared.\n+ Provide (of, wrt) tuples for which derivatives have not been declared in the system.\n \n Parameters\n ----------\n missing : dict\n Dictionary containing list of missing derivatives keyed by system pathname.\n \"\"\"\n+ if self._has_approx:\n+ return\n for subsys in self._subsystems_myproc:\n subsys._get_missing_partials(missing)\n \ndiff --git a/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb b/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb\nindex 4e3d8c11a..bc565d584 100644\n--- a/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb\n+++ b/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb\n@@ -325,6 +325,88 @@\n \"\\n\",\n \"assert_near_equal(derivs['z', 'x'], np.array([[300.]]), tolerance=1e-8)\"\n ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"id\": \"f9510c93\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"(approx_totals_relevance)=\\n\",\n+ \"## Approx-Totals and Relevance\\n\",\n+ \"\\n\",\n+ \"OpenMDAO builds a relevancy-graph that helps it be more efficient when executing complex models.\\n\",\n+ \"\\n\",\n+ \"One feature that uses this graph is the `relevance check` that is performed when a Driver begins to run.\\n\",\n+ \"The relevance check is used to verify that each constraint can be impacted by a design variable.\\n\",\n+ \"\\n\",\n+ \"However, when `approx_totals` is used, users often omit the declaration of any partials.\\n\",\n+ \"In this situation, the relevance check would normally fail, so OpenMDAO skips this check if any Group\\n\",\n+ \"in the system tree is found to use approximated derivatives.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"id\": \"bb70c742\",\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"import numpy as np\\n\",\n+ \"\\n\",\n+ \"import openmdao.api as om\\n\",\n+ \"\\n\",\n+ \"class AComp(om.ExplicitComponent):\\n\",\n+ \"\\n\",\n+ \" def setup(self):\\n\",\n+ \" self.add_input('x', val=0.0)\\n\",\n+ \" self.add_output('y', val=0.0)\\n\",\n+ \"\\n\",\n+ \" def compute(self, inputs, outputs):\\n\",\n+ \" outputs['y'] = inputs['x'] - 5.0\\n\",\n+ \"\\n\",\n+ \"class BComp(om.ExplicitComponent):\\n\",\n+ \"\\n\",\n+ \" def setup(self):\\n\",\n+ \" self.add_input('y', val=0.0)\\n\",\n+ \" self.add_output('z', val=0.0)\\n\",\n+ \"\\n\",\n+ \" def compute(self, inputs, outputs):\\n\",\n+ \" outputs['z'] = inputs['y'] ** 2\\n\",\n+ \"\\n\",\n+ \"prob = om.Problem()\\n\",\n+ \"prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP')\\n\",\n+ \"model = prob.model\\n\",\n+ \"model.set_input_defaults('x', 0.0)\\n\",\n+ \"\\n\",\n+ \"model.add_subsystem('a', AComp(), promotes=['x', 'y'])\\n\",\n+ \"model.add_subsystem('b', BComp(), promotes=['y', 'z'])\\n\",\n+ \"\\n\",\n+ \"model.add_design_var('x', lower=-100, upper=100)\\n\",\n+ \"model.add_objective('z')\\n\",\n+ \"\\n\",\n+ \"model.approx_totals(method='cs')\\n\",\n+ \"\\n\",\n+ \"prob.setup()\\n\",\n+ \"prob.run_driver()\\n\",\n+ \"\\n\",\n+ \"of = ['z']\\n\",\n+ \"wrt = ['x']\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"id\": \"d9c771d4\",\n+ \"metadata\": {\n+ \"tags\": [\n+ \"remove-input\",\n+ \"remove-output\"\n+ ]\n+ },\n+ \"outputs\": [],\n+ \"source\": [\n+ \"assert_near_equal(prob.get_val('x'), 5.0)\"\n+ ]\n }\n ],\n \"metadata\": {\n@@ -344,7 +426,7 @@\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n- \"version\": \"3.8.10\"\n+ \"version\": \"3.11.4\"\n },\n \"orphan\": true\n },\ndiff --git a/openmdao/drivers/pyoptsparse_driver.py b/openmdao/drivers/pyoptsparse_driver.py\nindex 0f87c1f97..3a28fb306 100644\n--- a/openmdao/drivers/pyoptsparse_driver.py\n+++ b/openmdao/drivers/pyoptsparse_driver.py\n@@ -25,6 +25,7 @@ except Exception as err:\n from openmdao.core.constants import INT_DTYPE, _DEFAULT_REPORTS_DIR, _ReprClass\n from openmdao.core.analysis_error import AnalysisError\n from openmdao.core.driver import Driver, RecordingDebugging\n+from openmdao.core.group import Group\n from openmdao.utils.class_util import WeakMethodWrapper\n from openmdao.utils.mpi import FakeComm, MPI\n from openmdao.utils.om_warnings import issue_warning, warn_deprecation\n@@ -838,9 +839,13 @@ class pyOptSparseDriver(Driver):\n \n # First time through, check for zero row/col.\n if self._check_jac and self._total_jac is not None:\n- raise_error = self.options['singular_jac_behavior'] == 'error'\n- self._total_jac.check_total_jac(raise_error=raise_error,\n- tol=self.options['singular_jac_tol'])\n+ for subsys in model.system_iter(include_self=True, recurse=True, typ=Group):\n+ if subsys._has_approx:\n+ break\n+ else:\n+ raise_error = self.options['singular_jac_behavior'] == 'error'\n+ self._total_jac.check_total_jac(raise_error=raise_error,\n+ tol=self.options['singular_jac_tol'])\n self._check_jac = False\n \n # Let the optimizer try to handle the error\ndiff --git a/openmdao/drivers/scipy_optimizer.py b/openmdao/drivers/scipy_optimizer.py\nindex 1268bfe54..45f3f3bab 100644\n--- a/openmdao/drivers/scipy_optimizer.py\n+++ b/openmdao/drivers/scipy_optimizer.py\n@@ -11,6 +11,7 @@ from scipy.optimize import minimize\n \n from openmdao.core.constants import INF_BOUND\n from openmdao.core.driver import Driver, RecordingDebugging\n+from openmdao.core.group import Group\n from openmdao.utils.class_util import WeakMethodWrapper\n from openmdao.utils.mpi import MPI\n \n@@ -719,6 +720,9 @@ class ScipyOptimizeDriver(Driver):\n ndarray\n Gradient of objective with respect to input array.\n \"\"\"\n+ prob = self._problem()\n+ model = prob.model\n+\n try:\n grad = self._compute_totals(of=self._obj_and_nlcons, wrt=self._dvlist,\n return_format=self._total_jac_format)\n@@ -726,9 +730,13 @@ class ScipyOptimizeDriver(Driver):\n \n # First time through, check for zero row/col.\n if self._check_jac and self._total_jac is not None:\n- raise_error = self.options['singular_jac_behavior'] == 'error'\n- self._total_jac.check_total_jac(raise_error=raise_error,\n- tol=self.options['singular_jac_tol'])\n+ for subsys in model.system_iter(include_self=True, recurse=True, typ=Group):\n+ if subsys._has_approx:\n+ break\n+ else:\n+ raise_error = self.options['singular_jac_behavior'] == 'error'\n+ self._total_jac.check_total_jac(raise_error=raise_error,\n+ tol=self.options['singular_jac_tol'])\n self._check_jac = False\n \n except Exception as msg:\n", "test_patch": "diff --git a/openmdao/core/tests/test_semitotals.py b/openmdao/core/tests/test_semitotals.py\nindex a4508b63f..c75f46f45 100644\n--- a/openmdao/core/tests/test_semitotals.py\n+++ b/openmdao/core/tests/test_semitotals.py\n@@ -199,6 +199,7 @@ class FakeGeomComp(om.ExplicitComponent):\n \n def initialize(self):\n self.options.declare(\"n\", types=int)\n+ self.options.declare('declare_partials', types=(bool,), default=True)\n \n def setup(self):\n n = self.options[\"n\"]\n@@ -206,7 +207,8 @@ class FakeGeomComp(om.ExplicitComponent):\n self.add_input(\"feather\", val=0.0, units=\"deg\")\n self.add_output(\"x\", val=np.zeros(n), units=\"m\")\n \n- self.declare_partials(\"*\", \"*\", method=\"fd\")\n+ if self.options['declare_partials']:\n+ self.declare_partials(\"*\", \"*\", method=\"fd\")\n \n self._counter = 0\n \n@@ -222,6 +224,7 @@ class FakeAeroComp(om.ExplicitComponent):\n \n def initialize(self):\n self.options.declare(\"n\", types=int)\n+ self.options.declare('declare_partials', types=(bool,), default=True)\n \n def setup(self):\n n = self.options[\"n\"]\n@@ -232,7 +235,8 @@ class FakeAeroComp(om.ExplicitComponent):\n self.add_output(\"CT\", val=0.5)\n self.add_output(\"CP\", val=0.5)\n \n- self.declare_partials(\"*\", \"*\", method=\"fd\")\n+ if self.options['declare_partials']:\n+ self.declare_partials(\"*\", \"*\", method=\"fd\")\n \n self._counter = 0\n \n@@ -251,15 +255,19 @@ class GeometryAndAero2(om.Group):\n self.options.declare(\"n\", types=int)\n self.options.declare(\"rho\", types=float)\n self.options.declare(\"vinf\", types=float)\n+ self.options.declare('declare_partials', types=(bool,), default=True)\n \n def setup(self):\n n = self.options[\"n\"]\n+ dp = self.options['declare_partials']\n \n comp = self.add_subsystem(\"init_geom\", om.IndepVarComp(), promotes_outputs=[\"x0\"])\n comp.add_output(\"x0\", val=np.arange(n) + 1.0, units=\"m\")\n \n- self.add_subsystem(\"geom\", FakeGeomComp(n=n), promotes_inputs=[\"x0\", \"feather\"], promotes_outputs=[\"x\"])\n- self.add_subsystem(\"aero\", FakeAeroComp(n=n), promotes_inputs=[\"x\", \"omega\"], promotes_outputs=[\"CT\", \"CP\"])\n+ self.add_subsystem(\"geom\", FakeGeomComp(n=n, declare_partials=dp),\n+ promotes_inputs=[\"x0\", \"feather\"], promotes_outputs=[\"x\"])\n+ self.add_subsystem(\"aero\", FakeAeroComp(n=n, declare_partials=dp),\n+ promotes_inputs=[\"x\", \"omega\"], promotes_outputs=[\"CT\", \"CP\"])\n \n def reset_count(self):\n self.geom._counter = 0\n@@ -310,3 +318,45 @@ class TestSemiTotalsNumCalls(unittest.TestCase):\n assert_check_totals(data, atol=1e-6, rtol=1e-6)\n \n self.assertEqual(geom_and_aero.geom._counter, 4)\n+\n+ def test_check_relevance_approx_totals(self):\n+\n+ size = 10\n+ rho = 1.17573\n+ minf = 0.111078231621482\n+ speedofsound = 344.5760217432\n+ vinf = minf*speedofsound\n+\n+ prob = om.Problem()\n+ prob.driver = om.ScipyOptimizeDriver()\n+ prob.driver.options[\"optimizer\"] = \"SLSQP\"\n+\n+ omega = 7199.759242*2*np.pi/60\n+ ivc = prob.model.add_subsystem(\"ivc\", om.IndepVarComp(), promotes_outputs=[\"*\"])\n+ ivc.add_output(\"feather\", val=0.0, units=\"deg\")\n+ ivc.add_output(\"omega\", val=omega, units=\"rad/s\")\n+\n+ geom_and_aero = prob.model.add_subsystem('geom_and_aero',\n+ GeometryAndAero2(n=size, rho=rho, vinf=vinf, declare_partials=False),\n+ promotes_inputs=[\"feather\", \"omega\"],\n+ promotes_outputs=[\"CT\", \"CP\"])\n+ geom_and_aero.approx_totals(step=step, step_calc=\"abs\", method=\"fd\", form=\"forward\")\n+\n+ prob.model.add_design_var(\"feather\", lower=-5.0, upper=25.0, units=\"deg\", ref=1.0)\n+ prob.model.add_design_var(\"omega\", lower=3000*2*np.pi/60, upper=7500*2*np.pi/60, units=\"rad/s\", ref=1.0)\n+ prob.model.add_objective(\"CP\", ref=1e0)\n+ prob.model.add_constraint(\"CT\", lower=0.0)\n+\n+ prob.setup(force_alloc_complex=False)\n+\n+ omega = (6245.096992023524*2*np.pi/60) + step\n+ feather = 0.6362159381168669\n+ prob.set_val(\"omega\", omega, units=\"rad/s\")\n+ prob.set_val(\"feather\", feather, units=\"deg\")\n+ fail = prob.run_driver()\n+\n+ self.assertEqual(fail, False)\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_semitotals.py::TestSemiTotalsNumCalls::test_check_relevance_approx_totals"]}], "all_FAIL_TO_PASS": ["openmdao/core/tests/test_semitotals.py::TestSemiTotalsNumCalls::test_check_relevance_approx_totals"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "rigetticomputing__pyquil-156_x1", "level": 1, "source": "swerebenchv2", "repo": "rigetticomputing/pyquil", "image": "swerebenchv2/rigetticomputing-pyquil:156-b871e5d", "base_commit": "b871e5de5bac62bf5fde62c96d6e5b20078c9e35", "num_bugs": 1, "bugs": [{"instance_id": "rigetticomputing__pyquil-156", "base_commit": "b871e5de5bac62bf5fde62c96d6e5b20078c9e35", "gold_patch": "diff --git a/pyquil/quil.py b/pyquil/quil.py\nindex bc94cf9..1939d67 100644\n--- a/pyquil/quil.py\n+++ b/pyquil/quil.py\n@@ -16,14 +16,18 @@\n \"\"\"\n Module for creating and defining Quil programs.\n \"\"\"\n+from six import integer_types\n \n from .quilbase import (InstructionGroup,\n+ Instr,\n Addr,\n While,\n If,\n DefGate,\n Gate,\n Measurement,\n+ issubinstance,\n+ AbstractQubit,\n merge_resource_managers)\n \n from .gates import MEASURE, STANDARD_GATES\n@@ -75,21 +79,38 @@ class Program(InstructionGroup):\n \n def get_qubits(self):\n \"\"\"\n- :return: a set of all the qubit indices allocated in this program, synthesizing freely\n- allocated qubits if neccessary.\n+ Returns all of the qubit indices used in this program, including gate applications and\n+ allocated qubits. e.g.\n+ >>> p = Program()\n+ >>> p.inst((\"H\", 1))\n+ >>> p.get_qubits()\n+ {1}\n+ >>> q = p.alloc()\n+ >>> len(p.get_qubits())\n+ 2\n+\n+ :return: A set of all the qubit indices used in this program, synthesizing freely\n+ allocated qubits if neccessary.\n :rtype: set\n \"\"\"\n- allocated_qubits = set()\n+ qubits = set()\n self.synthesize()\n for ii, action in self:\n if isinstance(action, Gate):\n qubit_indices = {qq.index() for qq in action.arguments}\n elif isinstance(action, Measurement):\n qubit_indices = {action.arguments[0].index()}\n+ elif isinstance(action, Instr):\n+ qubit_indices = set()\n+ for arg in action.arguments:\n+ if isinstance(arg, integer_types):\n+ qubit_indices.add(arg)\n+ elif isinstance(arg, AbstractQubit):\n+ qubit_indices.add(arg.index())\n else:\n continue\n- allocated_qubits = set.union(allocated_qubits, qubit_indices)\n- return allocated_qubits\n+ qubits = set.union(qubits, qubit_indices)\n+ return qubits\n \n def defgate(self, name, matrix):\n \"\"\"\ndiff --git a/pyquil/quilbase.py b/pyquil/quilbase.py\nindex 26b09fa..239b965 100644\n--- a/pyquil/quilbase.py\n+++ b/pyquil/quilbase.py\n@@ -668,6 +668,8 @@ class Instr(AbstractInstruction):\n for arg in self.arguments:\n if issubinstance(arg, AbstractQubit):\n qubits.add(arg.index())\n+ elif isinstance(arg, int):\n+ qubits.add(arg)\n return qubits\n \n \n", "test_patch": "diff --git a/pyquil/tests/test_quil.py b/pyquil/tests/test_quil.py\nindex 2383453..e328faf 100644\n--- a/pyquil/tests/test_quil.py\n+++ b/pyquil/tests/test_quil.py\n@@ -462,3 +462,11 @@ def test_get_qubits():\n qq = pq.alloc()\n pq.inst(Y(2), X(qq))\n assert pq.get_qubits() == {0, 1, 2, 4, 5} # this synthesizes the allocation\n+\n+ qubit_index = 1\n+ p = Program((\"H\", qubit_index))\n+ assert p.get_qubits() == {qubit_index}\n+ q1 = p.alloc()\n+ q2 = p.alloc()\n+ p.inst((\"CNOT\", q1, q2))\n+ assert p.get_qubits() == {qubit_index, q1.index(), q2.index()}\n", "FAIL_TO_PASS": ["pyquil/tests/test_quil.py::test_get_qubits"]}], "all_FAIL_TO_PASS": ["pyquil/tests/test_quil.py::test_get_qubits"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3125_x1", "level": 1, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3125-56f4bb7", "base_commit": "56f4bb77c196fc568bde910120ee0ae68470d904", "num_bugs": 1, "bugs": [{"instance_id": "openmdao__openmdao-3125", "base_commit": "56f4bb77c196fc568bde910120ee0ae68470d904", "gold_patch": "diff --git a/openmdao/core/driver.py b/openmdao/core/driver.py\nindex f48048433..1c6126151 100644\n--- a/openmdao/core/driver.py\n+++ b/openmdao/core/driver.py\n@@ -200,9 +200,6 @@ class Driver(object):\n \n self._has_scaling = False\n \n- # Want to allow the setting of hooks on Drivers\n- _setup_hooks(self)\n-\n def _get_inst_id(self):\n if self._problem is None:\n return None\ndiff --git a/openmdao/utils/hooks.py b/openmdao/utils/hooks.py\nindex d60b8ca87..eb4a28e4e 100644\n--- a/openmdao/utils/hooks.py\n+++ b/openmdao/utils/hooks.py\n@@ -2,10 +2,10 @@\n Functions for handling runtime function hooks.\n \"\"\"\n \n-from functools import wraps\n-import inspect\n-import warnings\n import sys\n+import warnings\n+import weakref\n+from inspect import getmro\n \n from openmdao.utils.om_warnings import issue_warning\n \n@@ -19,6 +19,9 @@ from openmdao.utils.om_warnings import issue_warning\n # 'fname'.\n _hooks = {}\n \n+# use this to keep hook ordering consistent across multiple calls to register_hook\n+_hook_counter = 0\n+\n # global switch that turns hook machinery on/off. Need it on in general for the default\n # reporting system\n use_hooks = True\n@@ -26,10 +29,130 @@ use_hooks = True\n \n def _reset_all_hooks():\n global _hooks\n-\n _hooks = {}\n \n \n+class _HookMeta(object):\n+ def __init__(self, class_name, inst_id, hook, ncalls=None, exit=False, **kwargs):\n+ global _hook_counter\n+ self._stamp = _hook_counter\n+ _hook_counter += 1\n+\n+ self.class_name = class_name\n+ self.inst_id = inst_id\n+ self.hook = hook\n+ self.ncalls = ncalls\n+ self.exit = exit\n+ self.kwargs = kwargs\n+ self.children = [] # if we're a 'None' inst_id hook, keep track of our child hooks\n+\n+ def __repr__(self):\n+ return f\"<_HookMeta {self.class_name} {self.inst_id} {self.hook} {self.ncalls} \"\\\n+ f\"{self.exit} {self.kwargs}>\"\n+\n+ def __call__(self, inst):\n+ if self.ncalls is None:\n+ self.hook(inst, **self.kwargs)\n+ if self.exit:\n+ sys.exit()\n+ else:\n+ if self.ncalls > 0:\n+ self.ncalls -= 1\n+ self.hook(inst, **self.kwargs)\n+ if self.exit:\n+ sys.exit()\n+\n+ def copy(self):\n+ hm = _HookMeta(self.class_name, self.inst_id, self.hook, self.ncalls,\n+ self.exit, **self.kwargs)\n+ # keep the same stamp so that the order of hooks doesn't change\n+ hm._stamp = self._stamp\n+ if self.inst_id is None:\n+ self.children.append(hm)\n+\n+ return hm\n+\n+ def deactivate(self):\n+ self.ncalls = 0\n+ for child in self.children:\n+ child.deactivate()\n+\n+\n+class _HookDecorator(object):\n+ def __init__(self, inst, func, hooks):\n+ self.__name__ = func.__name__\n+ self.__doc__ = func.__doc__\n+\n+ self.inst = weakref.ref(inst)\n+ self.func = func\n+ self.pre_hooks = []\n+ self.post_hooks = []\n+ self.add_hooks(hooks)\n+\n+ def add_hooks(self, hooks):\n+ \"\"\"\n+ Add additional pre and/or post hooks to this method.\n+\n+ Parameters\n+ ----------\n+ hooks : list\n+ List of hook data.\n+ \"\"\"\n+ # copy any hooks with inst_id of None so we can modify them without modifying the original\n+ for prehook, posthook in hooks:\n+ if prehook is not None:\n+ if prehook.inst_id is None:\n+ prehook = prehook.copy()\n+ self.pre_hooks.append(prehook)\n+ if posthook is not None:\n+ if posthook.inst_id is None:\n+ posthook = posthook.copy()\n+ self.post_hooks.append(posthook)\n+\n+ # put the hooks in order by stamp\n+ self.pre_hooks = sorted(self.pre_hooks, key=lambda x: x._stamp)\n+ self.post_hooks = sorted(self.post_hooks, key=lambda x: x._stamp)\n+\n+ def _run_hooks(self, hooks):\n+ \"\"\"\n+ Run the given list of hooks.\n+\n+ Parameters\n+ ----------\n+ hooks : list\n+ List of hook data.\n+ inst : object\n+ Object instance to pass to hook functions.\n+ \"\"\"\n+ inst = self.inst()\n+ if inst is None:\n+ return\n+\n+ for hook in hooks:\n+ hook(inst)\n+\n+ def __call__(self, *args, **kwargs):\n+ \"\"\"\n+ Run the function with any pre and post hooks.\n+\n+ Parameters\n+ ----------\n+ *args : list\n+ Positional arguments.\n+ **kwargs : dict\n+ Keyword arguments.\n+\n+ Returns\n+ -------\n+ object\n+ The return value of the function.\n+ \"\"\"\n+ self._run_hooks(self.pre_hooks)\n+ ret = self.func(*args, **kwargs)\n+ self._run_hooks(self.post_hooks)\n+ return ret\n+\n+\n def _setup_hooks(obj):\n \"\"\"\n Wrap object's methods with a hook checking function if hooks are defined for any of them.\n@@ -47,151 +170,43 @@ def _setup_hooks(obj):\n # valid pathname.\n if use_hooks:\n \n- classes = inspect.getmro(obj.__class__)\n- for c in classes:\n- if c.__name__ in _hooks:\n- classmeta = _hooks[c.__name__]\n- break\n- else:\n- return\n-\n # any object where we register hooks must define the '_get_inst_id' method.\n ident = obj._get_inst_id()\n \n- instmetas = []\n-\n- if ident in classmeta:\n- instmetas.append(classmeta[ident])\n-\n- # ident of None applies to all instances of a class\n- if ident is not None and None in classmeta:\n- instmetas.append(classmeta[None])\n-\n- if not instmetas:\n- return\n-\n- for instmeta in instmetas:\n- for funcname, fmeta in instmeta.items():\n- method = getattr(obj, funcname, None)\n- # We don't need to combine pre/post hook data for inst and None hooks here\n- # because it has already been done earlier (in register_hook/_get_hook_list_iters).\n- if method is not None and not hasattr(method, '_hashook_'):\n- setattr(obj, funcname, _hook_decorator(method, obj, fmeta))\n-\n-\n-def _run_hooks(hooks, inst):\n- \"\"\"\n- Run the given list of hooks.\n-\n- Parameters\n- ----------\n- hooks : list\n- List of hook data.\n- inst : object\n- Object instance to pass to hook functions.\n- \"\"\"\n- for hookmeta in hooks:\n- hook, ncalls, ex, kwargs, _ = hookmeta\n- if ncalls is None:\n- hook(inst, **kwargs)\n- if ex:\n- sys.exit()\n- else:\n- inst_id = inst._get_inst_id()\n- if inst_id not in ncalls:\n- # must have been registered with 'None', meaning all instances, so get initial value\n- # for this instance\n- ncalls[inst_id] = ncalls[None]\n-\n- if ncalls[inst_id] > 0:\n- ncalls[inst_id] -= 1\n- hook(inst, **kwargs)\n- if ex:\n- sys.exit()\n-\n-\n-def _hook_decorator(f, inst, hookmeta):\n- \"\"\"\n- Wrap a method with pre and/or post hook checks.\n-\n- Parameters\n- ----------\n- f : method\n- The method being wrapped.\n- inst : object\n- The instance that owns the method.\n- hookmeta : dict\n- A dict with information about the hooks.\n- \"\"\"\n- pre_hooks, post_hooks = hookmeta\n-\n- # args and kwargs are arguments to the method that is being wrapped\n- def execute_hooks(*args, **kwargs):\n- _run_hooks(pre_hooks, inst)\n- ret = f(*args, **kwargs)\n- _run_hooks(post_hooks, inst)\n- return ret\n-\n- execute_hooks._hashook_ = f # to prevent multiple decoration of same function\n-\n- return wraps(f)(execute_hooks)\n-\n-\n-def _get_hook_list_iters(class_name, inst_id, fname):\n- \"\"\"\n- Retrieve the pre and post hook list iterators for the given class, instance, and function name.\n-\n- They are iterators of lists because under some circumstances, e.g., when adding a 'None'\n- hook after non-None instance hooks were already added, the 'None' hook will need to be added\n- to *all* of the existing non-None instance hook lists.\n-\n- Parameters\n- ----------\n- class_name : str\n- The name of the class owning the method where the hook will be applied.\n- inst_id : str, optional\n- The name of the instance owning the method where the hook will be applied.\n- fname : str\n- The name of the function where the pre and/or post hook will be applied.\n-\n- Yields\n- ------\n- tuple of (list, list)\n- Pre and post hook lists.\n- \"\"\"\n- global _hooks\n- if class_name in _hooks:\n- cmeta = _hooks[class_name]\n- else:\n- _hooks[class_name] = cmeta = {}\n-\n- if inst_id in cmeta:\n- imeta = cmeta[inst_id]\n- else:\n- cmeta[inst_id] = imeta = {}\n-\n- if fname not in imeta:\n- # check for any existing None hooks because we need to add those first\n- nonehooks = None\n- if None in cmeta:\n- nonemeta = cmeta[None]\n- if fname in nonemeta:\n- nonehooks = nonemeta[fname]\n-\n- if nonehooks is None:\n- imeta[fname] = ([], [])\n- else:\n- imeta[fname] = ([h.copy() for h in nonehooks[0]], [h.copy() for h in nonehooks[1]])\n-\n- if inst_id is None:\n- # special case where we have to add the None hook to all existing non-None hook lists\n- # that match the fname\n- for n, meta in cmeta.items():\n- if fname in meta:\n- yield meta[fname]\n- return\n-\n- yield imeta[fname]\n+ if ident is None:\n+ raise RuntimeError(f\"Object {obj} must define a '_get_inst_id' method that returns \"\n+ \"a unique identifier for the object.\")\n+\n+ all_hooks = {}\n+\n+ for c in getmro(obj.__class__):\n+ if c.__qualname__ in _hooks:\n+ classmeta = _hooks[c.__qualname__]\n+\n+ if ident in classmeta:\n+ instmeta = classmeta[ident]\n+ for funcname, hooklist in instmeta.items():\n+ method = getattr(obj, funcname, None)\n+ if method is not None and callable(method):\n+ if funcname not in all_hooks:\n+ all_hooks[funcname] = []\n+ all_hooks[funcname].extend(hooklist)\n+\n+ if None in classmeta:\n+ instmeta = classmeta[None]\n+ for funcname, hooklist in instmeta.items():\n+ method = getattr(obj, funcname, None)\n+ if method is not None and callable(method):\n+ if funcname not in all_hooks:\n+ all_hooks[funcname] = []\n+ all_hooks[funcname].extend(hooklist)\n+\n+ for funcname, hooks in all_hooks.items():\n+ method = getattr(obj, funcname)\n+ if isinstance(method, _HookDecorator):\n+ method.add_hooks(hooks)\n+ else:\n+ setattr(obj, funcname, _HookDecorator(obj, method, hooks))\n \n \n def _register_hook(fname, class_name, inst_id=None, pre=None, post=None, ncalls=None, exit=False,\n@@ -199,6 +214,10 @@ def _register_hook(fname, class_name, inst_id=None, pre=None, post=None, ncalls=\n \"\"\"\n Register a hook function.\n \n+ Note that the 'class_name' arg should be the __qualname__ of the class, so for a nested class,\n+ the name would include the names of any containing classes as well, with each class name\n+ separated by a '.'.\n+\n Parameters\n ----------\n fname : str\n@@ -223,101 +242,88 @@ def _register_hook(fname, class_name, inst_id=None, pre=None, post=None, ncalls=\n if pre is None and post is None:\n raise RuntimeError(\"In _register_hook you must specify pre or post.\")\n \n- for pre_hooks, post_hooks in _get_hook_list_iters(class_name, inst_id, fname):\n- if pre is not None and (ncalls is None or ncalls > 0):\n- ncallsdict = {inst_id: ncalls} if ncalls is not None else ncalls\n- pre_hooks.append([pre, ncallsdict, exit and post is None, kwargs, inst_id])\n- if post is not None and (ncalls is None or ncalls > 0):\n- ncallsdict = {inst_id: ncalls} if ncalls is not None else ncalls\n- post_hooks.append([post, ncallsdict, exit, kwargs, inst_id])\n+ global _hooks\n+ if class_name in _hooks:\n+ cmeta = _hooks[class_name]\n+ else:\n+ _hooks[class_name] = cmeta = {}\n+\n+ if inst_id in cmeta:\n+ imeta = cmeta[inst_id]\n+ else:\n+ cmeta[inst_id] = imeta = {}\n+\n+ if fname not in imeta:\n+ imeta[fname] = []\n \n+ if pre is None:\n+ pre_hook = None\n+ else:\n+ pre_exit = exit if post is None else False\n+ pre_hook = _HookMeta(class_name, inst_id, pre, ncalls, pre_exit, **kwargs)\n+\n+ if post is None:\n+ post_hook = None\n+ else:\n+ post_hook = _HookMeta(class_name, inst_id, post, ncalls, exit, **kwargs)\n \n-def _remove_hook(to_remove, hooks, class_name, fname, hook_loc, inst_id):\n+ imeta[fname].append((pre_hook, post_hook))\n+\n+\n+def _deactivate_hook(to_remove, hook):\n \"\"\"\n- Remove a hook function.\n+ Deactivate a hook function.\n \n Parameters\n ----------\n to_remove : bool or function\n If True, all hook functions in 'hooks' will be removed. If a function, any function\n in 'hooks' that matches will be removed.\n- hooks : list\n- List of (hook_func, ncalls, exit, kwargs, inst_id) tuples.\n- class_name : str\n- The name of the class owning the method where the hook will be removed.\n- fname : str\n- The name of the function where the hooks are located.\n- hook_loc : str\n- Either 'pre' or 'post', indicating the hooks run before or after respectively the\n- function specified by fname.\n- inst_id : str or None\n- The name of the instance owning the method where the hook will be applied.\n+ hook : _HookMeta or None\n+ Hook metadata object.\n \"\"\"\n- if to_remove and hooks:\n+ if to_remove and hook is not None:\n if to_remove is True:\n- hooks[:] = []\n- else:\n- for hook in hooks:\n- p, _, _, _, iid = hook\n- if p is to_remove and iid == inst_id:\n- hooks.remove(hook)\n- break\n- else:\n- issue_warning(f\"Couldn't find the given '{hook_loc}' function in the \"\n- f\"{hook_loc} hooks for {class_name}.{fname}.\")\n+ hook.deactivate()\n+ else: # to_remove is a hook function\n+ if to_remove is hook.hook:\n+ hook.deactivate()\n \n \n def _unregister_hook(fname, class_name, inst_id=None, pre=True, post=True):\n \"\"\"\n Unregister a hook function.\n \n- By default, both pre and post hooks will be removed if they are present. To avoid\n+ By default, both pre and post hooks will be deactivated if they are present. To avoid\n removal of pre or post, you must set the pre or post arg to False.\n \n Parameters\n ----------\n fname : str\n- The name of the function where the pre and/or post hook will be removed.\n+ The name of the function where the pre and/or post hook will be deactivated.\n class_name : str\n- The name of the class owning the method where the hook will be removed.\n+ The name of the class owning the method where the hook will be deactivated.\n inst_id : str, optional\n- The name of the instance owning the method where the hook will be removed.\n+ The name of the instance owning the method where the hook will be deactivated.\n pre : bool or function, (True)\n- If True, hooks that run before the named function runs will be removed. If a\n- function then that function, if found, will be removed from the pre list, else\n- an exception will be raised.\n+ If True, hooks that run before the named function runs will be deactivated. If pre is a\n+ function, then that function will have its hook(s) deactivated.\n post : bool or function, (True)\n- If True, hooks that run after the named function runs will be removed. If a\n- function then that function, if found, will be removed from the post list, else\n- an exception will be raised.\n+ If True, hooks that run after the named function runs will be deactivated. If post is a\n+ function, then that function will have its hook(s) deactivated.\n \"\"\"\n try:\n classhooks = _hooks[class_name]\n except KeyError:\n return\n \n- todel = []\n for instkey, hookdict in classhooks.items():\n if not (inst_id is None or instkey == inst_id):\n continue\n if fname in hookdict:\n- pre_hooks, post_hooks = hookdict[fname]\n- _remove_hook(pre, pre_hooks, class_name, fname, 'pre', inst_id)\n- _remove_hook(post, post_hooks, class_name, fname, 'post', inst_id)\n-\n- if not (pre_hooks or post_hooks):\n- del hookdict[fname]\n- if not hookdict: # we just removed the last hook entry for this inst\n- todel.append(inst_id)\n+ for pre_hook, post_hook in hookdict[fname]:\n+ _deactivate_hook(pre, pre_hook)\n+ _deactivate_hook(post, post_hook)\n else:\n warnings.warn(f\"No hook found for method '{fname}' for class '{class_name}' and \"\n f\"instance '{inst_id}'.\")\n-\n- if todel:\n- for name in todel:\n- try:\n- del classhooks[name]\n- except KeyError:\n- pass\n- if not classhooks: # removed last entry for this class\n- del _hooks[class_name]\n", "test_patch": "diff --git a/openmdao/utils/tests/test_hooks.py b/openmdao/utils/tests/test_hooks.py\nindex 09ba64e93..5f7c56f0a 100644\n--- a/openmdao/utils/tests/test_hooks.py\n+++ b/openmdao/utils/tests/test_hooks.py\n@@ -29,8 +29,9 @@ class HooksTestCase(unittest.TestCase):\n def setUp(self):\n openmdao.core.problem._clear_problem_names() # need to reset these to simulate separate runs\n \n- def build_model(self, name='problem1'):\n- prob = om.Problem(name=name)\n+ def build_model(self, name='problem1', prob=None):\n+ if prob is None:\n+ prob = om.Problem(name=name)\n prob.calls = []\n model = prob.model\n \n@@ -75,8 +76,8 @@ class HooksTestCase(unittest.TestCase):\n \n @hooks_active\n def test_multiwrap(self):\n- pre_final = make_hook('pre_final')\n post_final = make_hook('post_final')\n+ pre_final = make_hook('pre_final')\n hooks._register_hook('final_setup', 'Problem', pre=pre_final, post=post_final)\n hooks._register_hook('final_setup', 'Problem', pre=make_hook('pre_final2'), post=make_hook('post_final2'))\n \n@@ -228,10 +229,6 @@ class HooksTestCase(unittest.TestCase):\n \n msg = \"No hook found for method 'final_setup' for class 'Problem' and instance 'None'.\"\n \n- # already removed final_setup hooks earlier, so expect a warning here\n- with assert_warning(UserWarning, msg):\n- hooks._unregister_hook('final_setup', 'Problem')\n-\n hooks._unregister_hook('run_model', 'Problem')\n prob.calls = []\n \n@@ -240,7 +237,6 @@ class HooksTestCase(unittest.TestCase):\n prob.run_model()\n \n self.assertEqual(prob.calls, [])\n- self.assertEqual(len(hooks._hooks), 0) # should be no hooks left\n \n @hooks_active\n def test_problem_hooks_kwargs(self):\n@@ -263,6 +259,51 @@ class HooksTestCase(unittest.TestCase):\n self.assertEqual(prob['comp.x'], x0)\n self.assertEqual(prob['comp.y'], y0)\n \n+ @hooks_active\n+ def test_inherited_class_hooks(self):\n+ def inherited_hook_pre(prob, **kwargs):\n+ prob.calls.append('inherited_pre')\n+ \n+ def inherited_hook_post(prob, **kwargs):\n+ prob.calls.append('inherited_post')\n+ \n+ def base_hook_pre(prob, **kwargs):\n+ prob.calls.append('base_pre')\n+ \n+ def base_hook_post(prob, **kwargs):\n+ prob.calls.append('base_post')\n+\n+ hooks._register_hook('final_setup', 'MyProblem', pre=inherited_hook_pre, post=inherited_hook_post)\n+ hooks._register_hook('final_setup', 'Problem', pre=base_hook_pre, post=base_hook_post)\n+\n+ prob = MyProblem()\n+ self.build_model(prob=prob)\n+\n+ prob.run_model()\n+ prob.run_model()\n+ prob.run_model()\n+\n+ self.assertEqual(prob.calls, ['inherited_pre', 'base_pre', 'inherited_post', 'base_post', 'inherited_pre',\n+ 'base_pre', 'inherited_post', 'base_post', 'inherited_pre', 'base_pre', 'inherited_post', 'base_post'])\n+ \n+ hooks._unregister_hook('final_setup', 'Problem', pre=base_hook_pre, post=False)\n+\n+ prob.calls = []\n+\n+ prob.run_model()\n+ prob.run_model()\n+\n+ self.assertEqual(prob.calls, ['inherited_pre', 'inherited_post', 'base_post', 'inherited_pre', 'inherited_post', 'base_post'])\n+\n+\n+class MyProblem(om.Problem):\n+ def __init__(self, *args, **kwargs):\n+ super().__init__(*args, **kwargs)\n+ self.calls = []\n+\n+ def run_model(self):\n+ super().run_model()\n+\n \n if __name__ == '__main__':\n unittest.main()\n", "FAIL_TO_PASS": ["openmdao/utils/tests/test_hooks.py::HooksTestCase::test_inherited_class_hooks"]}], "all_FAIL_TO_PASS": ["openmdao/utils/tests/test_hooks.py::HooksTestCase::test_inherited_class_hooks"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cs-si__eodag-795_x1", "level": 1, "source": "swerebenchv2", "repo": "CS-SI/eodag", "image": "swerebenchv2/cs-si-eodag:795-2eb52b8", "base_commit": "2eb52b8300e3859712c74412a97d15181865ce97", "num_bugs": 1, "bugs": [{"instance_id": "cs-si__eodag-795", "base_commit": "2eb52b8300e3859712c74412a97d15181865ce97", "gold_patch": "diff --git a/eodag/rest/server.py b/eodag/rest/server.py\nindex 57cc4381..541da3a8 100755\n--- a/eodag/rest/server.py\n+++ b/eodag/rest/server.py\n@@ -18,11 +18,12 @@\n import io\n import logging\n import os\n+import re\n import traceback\n from contextlib import asynccontextmanager\n from distutils import dist\n from json.decoder import JSONDecodeError\n-from typing import List, Union\n+from typing import List, Optional, Union\n \n import pkg_resources\n from fastapi import APIRouter as FastAPIRouter\n@@ -37,8 +38,11 @@ from starlette.exceptions import HTTPException as StarletteHTTPException\n \n from eodag.config import load_stac_api_config\n from eodag.rest.utils import (\n+ QueryableProperty,\n+ Queryables,\n download_stac_item_by_id_stream,\n eodag_api_init,\n+ fetch_collection_queryable_properties,\n get_detailled_collections_list,\n get_stac_api_version,\n get_stac_catalogs,\n@@ -61,6 +65,7 @@ from eodag.utils.exceptions import (\n )\n \n logger = logging.getLogger(\"eodag.rest.server\")\n+CAMEL_TO_SPACE_TITLED = re.compile(r\"[:_-]|(?<=[a-z])(?=[A-Z])\")\n \n \n class APIRouter(FastAPIRouter):\n@@ -595,4 +600,57 @@ async def stac_catalogs(catalogs, request: Request):\n return jsonable_encoder(response)\n \n \n+@router.get(\"/queryables\", tags=[\"Capabilities\"], response_model_exclude_none=True)\n+def list_queryables(request: Request) -> Queryables:\n+ \"\"\"Returns the list of terms available for use when writing filter expressions.\n+\n+ This endpoint provides a list of terms that can be used as filters when querying\n+ the data. These terms correspond to properties that can be filtered using comparison\n+ operators.\n+\n+ :param request: The incoming request object.\n+ :type request: fastapi.Request\n+ :returns: An object containing the list of available queryable terms.\n+ :rtype: eodag.rest.utils.Queryables\n+ \"\"\"\n+\n+ return Queryables(q_id=request.state.url)\n+\n+\n+@router.get(\n+ \"/collections/{collection_id}/queryables\",\n+ tags=[\"Capabilities\"],\n+ response_model_exclude_none=True,\n+)\n+def list_collection_queryables(\n+ request: Request, collection_id: str, provider: Optional[str] = None\n+) -> Queryables:\n+ \"\"\"Returns the list of queryable properties for a specific collection.\n+\n+ This endpoint provides a list of properties that can be used as filters when querying\n+ the specified collection. These properties correspond to characteristics of the data\n+ that can be filtered using comparison operators.\n+\n+ :param request: The incoming request object.\n+ :type request: fastapi.Request\n+ :param collection_id: The identifier of the collection for which to retrieve queryable properties.\n+ :type collection_id: str\n+ :param provider: (optional) The provider for which to retrieve additional properties.\n+ :type provider: str\n+ :returns: An object containing the list of available queryable properties for the specified collection.\n+ :rtype: eodag.rest.utils.Queryables\n+ \"\"\"\n+\n+ queryables = Queryables(q_id=request.state.url, additional_properties=False)\n+ conf_args = [collection_id, provider] if provider else [collection_id]\n+\n+ provider_properties = set(fetch_collection_queryable_properties(*conf_args))\n+\n+ for prop in provider_properties:\n+ titled_name = re.sub(CAMEL_TO_SPACE_TITLED, \" \", prop).title()\n+ queryables[prop] = QueryableProperty(description=titled_name)\n+\n+ return queryables\n+\n+\n app.include_router(router)\ndiff --git a/eodag/rest/utils.py b/eodag/rest/utils.py\nindex 8fbda850..76ab874c 100644\n--- a/eodag/rest/utils.py\n+++ b/eodag/rest/utils.py\n@@ -9,10 +9,12 @@ import os\n import re\n from collections import namedtuple\n from shutil import make_archive, rmtree\n+from typing import Dict, Optional\n \n import dateutil.parser\n from dateutil import tz\n from fastapi.responses import StreamingResponse\n+from pydantic import BaseModel, Field\n from shapely.geometry import Polygon, shape\n \n import eodag\n@@ -145,7 +147,6 @@ def search_bbox(request_bbox):\n search_bbox_keys = [\"lonmin\", \"latmin\", \"lonmax\", \"latmax\"]\n \n if request_bbox:\n-\n try:\n request_bbox_list = [float(coord) for coord in request_bbox.split(\",\")]\n except ValueError as e:\n@@ -883,6 +884,135 @@ def get_stac_extension_oseo(url):\n )\n \n \n+class QueryableProperty(BaseModel):\n+ \"\"\"A class representing a queryable property.\n+\n+ :param description: The description of the queryables property\n+ :type description: str\n+ :param ref: (optional) A reference link to the schema of the property.\n+ :type ref: str\n+ \"\"\"\n+\n+ description: str\n+ ref: Optional[str] = Field(default=None, serialization_alias=\"$ref\")\n+\n+\n+class Queryables(BaseModel):\n+ \"\"\"A class representing queryable properties for the STAC API.\n+\n+ :param json_schema: The URL of the JSON schema.\n+ :type json_schema: str\n+ :param q_id: (optional) The identifier of the queryables.\n+ :type q_id: str\n+ :param q_type: The type of the object.\n+ :type q_type: str\n+ :param title: The title of the queryables.\n+ :type title: str\n+ :param description: The description of the queryables\n+ :type description: str\n+ :param properties: A dictionary of queryable properties.\n+ :type properties: dict\n+ :param additional_properties: Whether additional properties are allowed.\n+ :type additional_properties: bool\n+ \"\"\"\n+\n+ json_schema: str = Field(\n+ default=\"https://json-schema.org/draft/2019-09/schema\",\n+ serialization_alias=\"$schema\",\n+ )\n+ q_id: Optional[str] = Field(default=None, serialization_alias=\"$id\")\n+ q_type: str = Field(default=\"object\", serialization_alias=\"type\")\n+ title: str = Field(default=\"Queryables for EODAG STAC API\")\n+ description: str = Field(\n+ default=\"Queryable names for the EODAG STAC API Item Search filter.\"\n+ )\n+ properties: Dict[str, QueryableProperty] = Field(\n+ default={\n+ \"id\": QueryableProperty(\n+ description=\"ID\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/id\",\n+ ),\n+ \"collection\": QueryableProperty(\n+ description=\"Collection\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/collection\",\n+ ),\n+ \"geometry\": QueryableProperty(\n+ description=\"Geometry\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/geometry\",\n+ ),\n+ \"bbox\": QueryableProperty(\n+ description=\"Bbox\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/bbox\",\n+ ),\n+ \"datetime\": QueryableProperty(\n+ description=\"Datetime\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/datetime.json#/properties/datetime\",\n+ ),\n+ \"ids\": QueryableProperty(description=\"IDs\"),\n+ }\n+ )\n+ additional_properties: bool = Field(\n+ default=True, serialization_alias=\"additionalProperties\"\n+ )\n+\n+ def get_properties(self) -> Dict[str, QueryableProperty]:\n+ \"\"\"Get the queryable properties.\n+\n+ :returns: A dictionary containing queryable properties.\n+ :rtype: typing.Dict[str, QueryableProperty]\n+ \"\"\"\n+ return self.properties\n+\n+ def __contains__(self, name: str):\n+ return name in self.properties\n+\n+ def __setitem__(self, name: str, qprop: QueryableProperty):\n+ self.properties[name] = qprop\n+\n+\n+def rename_to_stac_standard(key: str) -> str:\n+ \"\"\"Fetch the queryable properties for a collection.\n+\n+ :param key: The camelCase key name obtained from a collection's metadata mapping.\n+ :type key: str\n+ :returns: The STAC-standardized property name if it exists, else the default camelCase queryable name\n+ :rtype: str\n+ \"\"\"\n+ # Load the stac config properties for renaming the properties\n+ # to their STAC standard\n+ stac_config_properties = stac_config[\"item\"][\"properties\"]\n+\n+ for stac_property, value in stac_config_properties.items():\n+ if str(value).endswith(key):\n+ return stac_property\n+ return key\n+\n+\n+def fetch_collection_queryable_properties(\n+ collection_id: str, provider: Optional[str] = None\n+) -> set:\n+ \"\"\"Fetch the queryable properties for a collection.\n+\n+ :param collection_id: The ID of the collection.\n+ :type collection_id: str\n+ :param provider: (optional) The provider.\n+ :type provider: str\n+ :returns queryable_properties: A set containing the STAC standardized queryable properties for a collection.\n+ :rtype queryable_properties: set\n+ \"\"\"\n+ # Fetch the metadata mapping for collection-specific queryables\n+ args = [collection_id, provider] if provider else [collection_id]\n+ search_plugin = next(eodag_api._plugins_manager.get_search_plugins(*args))\n+ mapping = dict(search_plugin.config.metadata_mapping)\n+\n+ # list of all the STAC standardized collection-specific queryables\n+ queryable_properties = set()\n+ for key, value in mapping.items():\n+ if isinstance(value, list) and \"TimeFromAscendingNode\" not in key:\n+ queryable_properties.add(rename_to_stac_standard(key))\n+ return queryable_properties\n+\n+\n def eodag_api_init():\n \"\"\"Init EODataAccessGateway server instance, pre-running all time consuming tasks\"\"\"\n eodag_api.fetch_product_types_list()\n", "test_patch": "diff --git a/tests/units/test_http_server.py b/tests/units/test_http_server.py\nindex 9a144cd8..8cfe0926 100644\n--- a/tests/units/test_http_server.py\n+++ b/tests/units/test_http_server.py\n@@ -760,3 +760,18 @@ class RequestTestCase(unittest.TestCase):\n response = self._request_valid(\"/extensions/oseo/json-schema/schema.json\")\n self.assertEqual(response[\"title\"], \"OpenSearch for Earth Observation\")\n self.assertEqual(response[\"allOf\"][0][\"$ref\"], \"#/definitions/oseo\")\n+\n+ def test_queryables(self):\n+ \"\"\"Request to /queryables should return a valid response.\"\"\"\n+ self._request_valid(\"queryables\")\n+\n+ def test_product_type_queryables(self):\n+ \"\"\"Request to /collections/{collection_id}/queryables should return a valid response.\"\"\"\n+ self._request_valid(f\"collections/{self.tested_product_type}/queryables\")\n+\n+ def test_product_type_queryables_with_provider(self):\n+ \"\"\"Request a collection-specific list of queryables for a given provider.\"\"\"\n+\n+ self._request_valid(\n+ f\"collections/{self.tested_product_type}/queryables?provider=peps\"\n+ )\n", "FAIL_TO_PASS": ["tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables", "tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables_with_provider", "tests/units/test_http_server.py::RequestTestCase::test_queryables"]}], "all_FAIL_TO_PASS": ["tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables", "tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables_with_provider", "tests/units/test_http_server.py::RequestTestCase::test_queryables"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "litestar-org__polyfactory-479_x1", "level": 1, "source": "swerebenchv2", "repo": "litestar-org/polyfactory", "image": "swerebenchv2/litestar-org-polyfactory:479-c22633c", "base_commit": "c22633ccf76e0fa58bc53795dfedb78a6abfb807", "num_bugs": 1, "bugs": [{"instance_id": "litestar-org__polyfactory-479", "base_commit": "c22633ccf76e0fa58bc53795dfedb78a6abfb807", "gold_patch": "diff --git a/polyfactory/factories/base.py b/polyfactory/factories/base.py\nindex 3893b7b..71b0407 100644\n--- a/polyfactory/factories/base.py\n+++ b/polyfactory/factories/base.py\n@@ -223,7 +223,7 @@ class BaseFactory(ABC, Generic[T]):\n if random_seed is not None:\n cls.seed_random(random_seed)\n \n- if cls.__set_as_default_factory_for_type__:\n+ if cls.__set_as_default_factory_for_type__ and hasattr(cls, \"__model__\"):\n BaseFactory._factory_type_mapping[cls.__model__] = cls\n \n @classmethod\n", "test_patch": "diff --git a/tests/test_factory_configuration.py b/tests/test_factory_configuration.py\nnew file mode 100644\nindex 0000000..aa92869\n--- /dev/null\n+++ b/tests/test_factory_configuration.py\n@@ -0,0 +1,20 @@\n+from typing import Any, Type\n+\n+from typing_extensions import TypeGuard\n+\n+from polyfactory.factories.base import BaseFactory, T\n+\n+\n+def test_setting_set_as_default_factory_for_type_on_base_factory() -> None:\n+ \"\"\"Setting the value to `True` shouldn't raise exception when initializing.\"\"\"\n+\n+ class CustomBaseFactory(BaseFactory[T]):\n+ __is_base_factory__ = True\n+ __set_as_default_factory_for_type__ = True\n+\n+ @classmethod\n+ def is_supported_type(cls, value: Any) -> TypeGuard[Type[T]]:\n+ # Set this as false since this factory will be injected into the\n+ # list of base factories, but this obviously shouldn't be ran\n+ # for any of the types.\n+ return False\n", "FAIL_TO_PASS": ["tests/test_factory_configuration.py::test_setting_set_as_default_factory_for_type_on_base_factory"]}], "all_FAIL_TO_PASS": ["tests/test_factory_configuration.py::test_setting_set_as_default_factory_for_type_on_base_factory"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "amaranth-lang__amaranth-1395_x1", "level": 1, "source": "swerebenchv2", "repo": "amaranth-lang/amaranth", "image": "swerebenchv2/amaranth-lang-amaranth:1395-c9de103", "base_commit": "c9de103c4ff8da859ea2cfef47951bef1e80136e", "num_bugs": 1, "bugs": [{"instance_id": "amaranth-lang__amaranth-1395", "base_commit": "c9de103c4ff8da859ea2cfef47951bef1e80136e", "gold_patch": "diff --git a/amaranth/__init__.py b/amaranth/__init__.py\nindex b968958..f9c20d8 100644\n--- a/amaranth/__init__.py\n+++ b/amaranth/__init__.py\n@@ -20,6 +20,5 @@ __all__ = [\n \"Module\",\n \"ClockDomain\",\n \"Elaboratable\", \"Fragment\", \"Instance\",\n- \"Memory\",\n \"DomainRenamer\", \"ResetInserter\", \"EnableInserter\",\n ]\ndiff --git a/amaranth/hdl/__init__.py b/amaranth/hdl/__init__.py\nindex 0eab602..0a1f753 100644\n--- a/amaranth/hdl/__init__.py\n+++ b/amaranth/hdl/__init__.py\n@@ -8,7 +8,7 @@ from ._dsl import Module\n from ._cd import DomainError, ClockDomain\n from ._ir import AlreadyElaborated, UnusedElaboratable, Elaboratable, DriverConflict, Fragment\n from ._ir import Instance, IOBufferInstance\n-from ._mem import MemoryData, MemoryInstance, Memory, ReadPort, WritePort, DummyPort\n+from ._mem import MemoryData, MemoryInstance\n from ._nir import CombinationalCycle\n from ._xfrm import DomainRenamer, ResetInserter, EnableInserter\n \n@@ -31,7 +31,7 @@ __all__ = [\n # _nir\n \"CombinationalCycle\",\n # _mem\n- \"MemoryData\", \"MemoryInstance\", \"Memory\", \"ReadPort\", \"WritePort\", \"DummyPort\",\n+ \"MemoryData\", \"MemoryInstance\",\n # _xfrm\n \"DomainRenamer\", \"ResetInserter\", \"EnableInserter\",\n ]\ndiff --git a/amaranth/hdl/_ast.py b/amaranth/hdl/_ast.py\nindex c192384..58d57e9 100644\n--- a/amaranth/hdl/_ast.py\n+++ b/amaranth/hdl/_ast.py\n@@ -253,9 +253,8 @@ class ShapeCastable:\n raise TypeError(f\"Class '{cls.__name__}' deriving from 'ShapeCastable' must override \"\n f\"the '__call__' method\")\n if cls.from_bits is ShapeCastable.from_bits:\n- warnings.warn(f\"Class '{cls.__name__}' deriving from 'ShapeCastable' does not override \"\n- f\"the 'from_bits' method, which will be required in Amaranth 0.6\",\n- DeprecationWarning, stacklevel=2)\n+ raise TypeError(f\"Class '{cls.__name__}' deriving from 'ShapeCastable' must override \"\n+ f\"the 'from_bits' method\")\n \n # The signatures and definitions of these methods are weird because they are present here for\n # documentation (and error checking above) purpose only and should not affect control flow.\n@@ -321,8 +320,10 @@ class ShapeCastable:\n \"\"\"\n return super().const(*args, **kwargs) # :nocov:\n \n- def from_bits(self, raw):\n- \"\"\"Lift a bit pattern to a higher-level representation.\n+ def from_bits(self, *args, **kwargs):\n+ \"\"\"from_bits(raw)\n+\n+ Lift a bit pattern to a higher-level representation.\n \n This method is called by the Amaranth language to lift :py:`raw`, which is an :class:`int`,\n to a higher-level representation, which may be any object accepted by :meth:`const`.\n@@ -353,7 +354,7 @@ class ShapeCastable:\n either directly or as a cause of another exception. While not constrained here,\n usually the exception class will be :exc:`ValueError`.\n \"\"\"\n- return raw\n+ return super().from_bits(*args, **kwargs) # :nocov:\n \n def __call__(self, *args, **kwargs):\n \"\"\"__call__(obj)\ndiff --git a/amaranth/hdl/_mem.py b/amaranth/hdl/_mem.py\nindex add1a89..0554f73 100644\n--- a/amaranth/hdl/_mem.py\n+++ b/amaranth/hdl/_mem.py\n@@ -1,15 +1,14 @@\n import operator\n-from collections import OrderedDict\n from collections.abc import MutableSequence\n \n from .. import tracer\n from ._ast import *\n-from ._ir import Elaboratable, Fragment, AlreadyElaborated\n+from ._ir import Fragment, AlreadyElaborated\n from ..utils import ceil_log2\n-from .._utils import deprecated, final\n+from .._utils import final\n \n \n-__all__ = [\"MemoryData\", \"Memory\", \"ReadPort\", \"WritePort\", \"DummyPort\"]\n+__all__ = [\"MemoryData\", \"MemoryInstance\"]\n \n \n @final\n@@ -270,260 +269,3 @@ class MemoryInstance(Fragment):\n assert len(port._addr) == ceil_log2(self._data.depth)\n self._write_ports.append(port)\n return len(self._write_ports) - 1\n-\n-\n-class Memory(Elaboratable):\n- \"\"\"A word addressable storage.\n-\n- Parameters\n- ----------\n- width : int\n- Access granularity. Each storage element of this memory is ``width`` bits in size.\n- depth : int\n- Word count. This memory contains ``depth`` storage elements.\n- init : list of int\n- Initial values. At power on, each storage element in this memory is initialized to\n- the corresponding element of ``init``, if any, or to zero otherwise.\n- Uninitialized memories are not currently supported.\n- name : str\n- Name hint for this memory. If ``None`` (default) the name is inferred from the variable\n- name this ``Signal`` is assigned to.\n- attrs : dict\n- Dictionary of synthesis attributes.\n-\n- Attributes\n- ----------\n- width : int\n- depth : int\n- init : list of int\n- attrs : dict\n- \"\"\"\n- # TODO(amaranth-0.6): remove\n- @deprecated(\"`amaranth.hdl.Memory` is deprecated, use `amaranth.lib.memory.Memory` instead\")\n- def __init__(self, *, width, depth, init=None, name=None, attrs=None, simulate=True):\n- if not isinstance(width, int) or width < 0:\n- raise TypeError(\"Memory width must be a non-negative integer, not {!r}\"\n- .format(width))\n- if not isinstance(depth, int) or depth < 0:\n- raise TypeError(\"Memory depth must be a non-negative integer, not {!r}\"\n- .format(depth))\n-\n- self.name = name or tracer.get_var_name(depth=3, default=\"$memory\")\n- self.src_loc = tracer.get_src_loc(src_loc_at=1)\n-\n- self.width = width\n- self.depth = depth\n- self.attrs = OrderedDict(() if attrs is None else attrs)\n-\n- self._read_ports = []\n- self._write_ports = []\n- self._data = MemoryData(shape=width, depth=depth, init=init or [])\n-\n- @property\n- def init(self):\n- return self._data.init\n-\n- @init.setter\n- def init(self, new_init):\n- self._data.init = new_init\n-\n- def read_port(self, *, src_loc_at=0, **kwargs):\n- \"\"\"Get a read port.\n-\n- See :class:`ReadPort` for details.\n-\n- Arguments\n- ---------\n- domain : str\n- transparent : bool\n-\n- Returns\n- -------\n- An instance of :class:`ReadPort` associated with this memory.\n- \"\"\"\n- return ReadPort(self, src_loc_at=1 + src_loc_at, **kwargs)\n-\n- def write_port(self, *, src_loc_at=0, **kwargs):\n- \"\"\"Get a write port.\n-\n- See :class:`WritePort` for details.\n-\n- Arguments\n- ---------\n- domain : str\n- granularity : int\n-\n- Returns\n- -------\n- An instance of :class:`WritePort` associated with this memory.\n- \"\"\"\n- return WritePort(self, src_loc_at=1 + src_loc_at, **kwargs)\n-\n- def __getitem__(self, index):\n- return self._data[index]\n-\n- def elaborate(self, platform):\n- f = MemoryInstance(data=self._data, attrs=self.attrs, src_loc=self.src_loc)\n- write_ports = {}\n- for port in self._write_ports:\n- port._MustUse__used = True\n- iport = f.write_port(domain=port.domain, addr=port.addr, data=port.data, en=port.en)\n- write_ports.setdefault(port.domain, []).append(iport)\n- for port in self._read_ports:\n- port._MustUse__used = True\n- if port.domain == \"comb\":\n- f.read_port(domain=\"comb\", addr=port.addr, data=port.data, en=Const(1), transparent_for=())\n- else:\n- transparent_for = []\n- if port.transparent:\n- transparent_for = write_ports.get(port.domain, [])\n- f.read_port(domain=port.domain, addr=port.addr, data=port.data, en=port.en, transparent_for=transparent_for)\n- return f\n-\n-\n-class ReadPort(Elaboratable):\n- \"\"\"A memory read port.\n-\n- Parameters\n- ----------\n- memory : :class:`Memory`\n- Memory associated with the port.\n- domain : str\n- Clock domain. Defaults to ``\"sync\"``. If set to ``\"comb\"``, the port is asynchronous.\n- Otherwise, the read data becomes available on the next clock cycle.\n- transparent : bool\n- Port transparency. If set (default), a read at an address that is also being written to in\n- the same clock cycle will output the new value. Otherwise, the old value will be output\n- first. This behavior only applies to ports in the same domain.\n-\n- Attributes\n- ----------\n- memory : :class:`Memory`\n- domain : str\n- transparent : bool\n- addr : Signal(range(memory.depth)), in\n- Read address.\n- data : Signal(memory.width), out\n- Read data.\n- en : Signal or Const, in\n- Read enable. If asserted, ``data`` is updated with the word stored at ``addr``.\n-\n- Exceptions\n- ----------\n- Raises :exn:`ValueError` if the read port is simultaneously asynchronous and non-transparent.\n- \"\"\"\n- def __init__(self, memory, *, domain=\"sync\", transparent=True, src_loc_at=0):\n- if domain == \"comb\" and not transparent:\n- raise ValueError(\"Read port cannot be simultaneously asynchronous and non-transparent\")\n-\n- self.memory = memory\n- self.domain = domain\n- self.transparent = transparent\n-\n- self.addr = Signal(range(memory.depth),\n- name=f\"{memory.name}_r_addr\", src_loc_at=1 + src_loc_at)\n- self.data = Signal(memory.width,\n- name=f\"{memory.name}_r_data\", src_loc_at=1 + src_loc_at)\n- if self.domain != \"comb\":\n- self.en = Signal(name=f\"{memory.name}_r_en\", init=1,\n- src_loc_at=1 + src_loc_at)\n- else:\n- self.en = Const(1)\n-\n- memory._read_ports.append(self)\n-\n- def elaborate(self, platform):\n- if self is self.memory._read_ports[0]:\n- return self.memory\n- else:\n- return Fragment()\n-\n-\n-class WritePort(Elaboratable):\n- \"\"\"A memory write port.\n-\n- Parameters\n- ----------\n- memory : :class:`Memory`\n- Memory associated with the port.\n- domain : str\n- Clock domain. Defaults to ``\"sync\"``. Writes have a latency of 1 clock cycle.\n- granularity : int\n- Port granularity. Defaults to ``memory.width``. Write data is split evenly in\n- ``memory.width // granularity`` chunks, which can be updated independently.\n-\n- Attributes\n- ----------\n- memory : :class:`Memory`\n- domain : str\n- granularity : int\n- addr : Signal(range(memory.depth)), in\n- Write address.\n- data : Signal(memory.width), in\n- Write data.\n- en : Signal(memory.width // granularity), in\n- Write enable. Each bit selects a non-overlapping chunk of ``granularity`` bits on the\n- ``data`` signal, which is written to memory at ``addr``. Unselected chunks are ignored.\n-\n- Exceptions\n- ----------\n- Raises :exn:`ValueError` if the write port granularity is greater than memory width, or does not\n- divide memory width evenly.\n- \"\"\"\n- def __init__(self, memory, *, domain=\"sync\", granularity=None, src_loc_at=0):\n- if granularity is None:\n- granularity = memory.width\n- if not isinstance(granularity, int) or granularity < 0:\n- raise TypeError(\"Write port granularity must be a non-negative integer, not {!r}\"\n- .format(granularity))\n- if granularity > memory.width:\n- raise ValueError(\"Write port granularity must not be greater than memory width \"\n- \"({} > {})\"\n- .format(granularity, memory.width))\n- if memory.width // granularity * granularity != memory.width:\n- raise ValueError(\"Write port granularity must divide memory width evenly\")\n-\n- self.memory = memory\n- self.domain = domain\n- self.granularity = granularity\n-\n- self.addr = Signal(range(memory.depth),\n- name=f\"{memory.name}_w_addr\", src_loc_at=1 + src_loc_at)\n- self.data = Signal(memory.width,\n- name=f\"{memory.name}_w_data\", src_loc_at=1 + src_loc_at)\n- self.en = Signal(memory.width // granularity,\n- name=f\"{memory.name}_w_en\", src_loc_at=1 + src_loc_at)\n-\n- memory._write_ports.append(self)\n-\n- def elaborate(self, platform):\n- if not self.memory._read_ports and self is self.memory._write_ports[0]:\n- return self.memory\n- else:\n- return Fragment()\n-\n-\n-class DummyPort:\n- \"\"\"Dummy memory port.\n-\n- This port can be used in place of either a read or a write port for testing and verification.\n- It does not include any read/write port specific attributes, i.e. none besides ``\"domain\"``;\n- any such attributes may be set manually.\n- \"\"\"\n- # TODO(amaranth-0.6): remove\n- @deprecated(\"`DummyPort` is deprecated, use `amaranth.lib.memory.ReadPort` or \"\n- \"`amaranth.lib.memory.WritePort` instead\")\n- def __init__(self, *, data_width, addr_width, domain=\"sync\", name=None, granularity=None):\n- self.domain = domain\n-\n- if granularity is None:\n- granularity = data_width\n- if name is None:\n- name = tracer.get_var_name(depth=3, default=\"dummy\")\n-\n- self.addr = Signal(addr_width,\n- name=f\"{name}_addr\", src_loc_at=1)\n- self.data = Signal(data_width,\n- name=f\"{name}_data\", src_loc_at=1)\n- self.en = Signal(data_width // granularity,\n- name=f\"{name}_en\", src_loc_at=1)\ndiff --git a/amaranth/lib/data.py b/amaranth/lib/data.py\nindex 623d327..5ef38d9 100644\n--- a/amaranth/lib/data.py\n+++ b/amaranth/lib/data.py\n@@ -922,8 +922,8 @@ class Const(ValueCastable):\n Slicing a constant or accessing its attributes returns a part of the underlying value\n corresponding to the field with that index or name. If the shape of the field is\n a :class:`Layout`, the returned value is a :class:`Const`; if it is a different\n- :ref:`shape-like ` object implementing :meth:`~.ShapeCastable.from_bits`,\n- it will be the result of calling that method; otherwise, it is an :class:`int`.\n+ :ref:`shape-like ` object, it will be the result of calling\n+ :meth:`~.ShapeCastable.from_bits`; otherwise, it is an :class:`int`.\n \n Slicing a constant whose layout is an :class:`ArrayLayout` can be done with an index that is\n an Amaranth value rather than a constant integer. The returned element is chosen dynamically\n@@ -990,8 +990,8 @@ class Const(ValueCastable):\n \"\"\"Slice the underlying value.\n \n A field corresponding to :py:`key` is looked up in the layout. If the field's shape is\n- a shape-castable object that has a :meth:`~.ShapeCastable.from_bits` method, returns\n- the result of calling that method. Otherwise, returns an :class:`int`.\n+ a shape-castable object, returns the result of calling :meth:`~.ShapeCastable.from_bits`.\n+ Otherwise, returns an :class:`int`.\n \n Arguments\n ---------\ndiff --git a/docs/changes.rst b/docs/changes.rst\nindex 4087686..be9539f 100644\n--- a/docs/changes.rst\n+++ b/docs/changes.rst\n@@ -28,7 +28,9 @@ Language changes\n \n .. currentmodule:: amaranth.hdl\n \n+* Changed: overriding :meth:`ValueCastable.from_bits` is now mandatory. (`RFC 51`_)\n * Removed: (deprecated in 0.4) :class:`Record`.\n+* Removed: (deprecated in 0.5) :class:`Memory` (`RFC 45`_)\n * Removed: (deprecated in 0.5) public submodules of :mod:`amaranth.hdl`.\n * Removed: (deprecated in 0.5) :meth:`Value.implies`.\n \n", "test_patch": "diff --git a/tests/test_hdl_ast.py b/tests/test_hdl_ast.py\nindex 4ec8618..cdb0367 100644\n--- a/tests/test_hdl_ast.py\n+++ b/tests/test_hdl_ast.py\n@@ -211,25 +211,6 @@ class ShapeCastableTestCase(FHDLTestCase):\n r\"^Can't instantiate abstract class ShapeCastable$\"):\n ShapeCastable()\n \n- def test_no_from_bits(self):\n- with self.assertWarnsRegex(DeprecationWarning,\n- r\"^Class 'MockShapeCastableNoFromBits' deriving from 'ShapeCastable' does \"\n- r\"not override the 'from_bits' method, which will be required in Amaranth 0.6$\"):\n- class MockShapeCastableNoFromBits(ShapeCastable):\n- def __init__(self, dest):\n- self.dest = dest\n-\n- def as_shape(self):\n- return self.dest\n-\n- def __call__(self, value):\n- return value\n-\n- def const(self, init):\n- return Const(init, self.dest)\n-\n- self.assertEqual(MockShapeCastableNoFromBits(unsigned(2)).from_bits(123), 123)\n-\n \n class ShapeLikeTestCase(FHDLTestCase):\n def test_construct(self):\ndiff --git a/tests/test_hdl_mem.py b/tests/test_hdl_mem.py\nindex f165622..504e598 100644\n--- a/tests/test_hdl_mem.py\n+++ b/tests/test_hdl_mem.py\n@@ -2,7 +2,6 @@\n \n from amaranth.hdl import *\n from amaranth.hdl._mem import *\n-from amaranth._utils import _ignore_deprecated\n \n from .utils import *\n \n@@ -32,160 +31,3 @@ class MemoryDataTestCase(FHDLTestCase):\n with self.assertRaisesRegex(ValueError,\n r\"^Value \\(memory-row \\(memory-data data\\) 0\\) can only be used in simulator processes$\"):\n m.d.comb += data[0].eq(1)\n-\n-class MemoryTestCase(FHDLTestCase):\n- def test_name(self):\n- with _ignore_deprecated():\n- m1 = Memory(width=8, depth=4)\n- self.assertEqual(m1.name, \"m1\")\n- m2 = [Memory(width=8, depth=4)][0]\n- self.assertEqual(m2.name, \"$memory\")\n- m3 = Memory(width=8, depth=4, name=\"foo\")\n- self.assertEqual(m3.name, \"foo\")\n-\n- def test_geometry(self):\n- with _ignore_deprecated():\n- m = Memory(width=8, depth=4)\n- self.assertEqual(m.width, 8)\n- self.assertEqual(m.depth, 4)\n-\n- def test_geometry_wrong(self):\n- with _ignore_deprecated():\n- with self.assertRaisesRegex(TypeError,\n- r\"^Memory width must be a non-negative integer, not -1$\"):\n- m = Memory(width=-1, depth=4)\n- with self.assertRaisesRegex(TypeError,\n- r\"^Memory depth must be a non-negative integer, not -1$\"):\n- m = Memory(width=8, depth=-1)\n-\n- def test_init(self):\n- with _ignore_deprecated():\n- m = Memory(width=8, depth=4, init=range(4))\n- self.assertEqual(list(m.init), [0, 1, 2, 3])\n-\n- def test_init_wrong_count(self):\n- with _ignore_deprecated():\n- with self.assertRaisesRegex(ValueError,\n- r\"^Memory initialization value count exceeds memory depth \\(8 > 4\\)$\"):\n- m = Memory(width=8, depth=4, init=range(8))\n-\n- def test_init_wrong_type(self):\n- with _ignore_deprecated():\n- with self.assertRaisesRegex(TypeError,\n- (r\"^Memory initialization value at address 1: \"\n- r\"'str' object cannot be interpreted as an integer$\")):\n- m = Memory(width=8, depth=4, init=[1, \"0\"])\n-\n- def test_attrs(self):\n- with _ignore_deprecated():\n- m1 = Memory(width=8, depth=4)\n- self.assertEqual(m1.attrs, {})\n- m2 = Memory(width=8, depth=4, attrs={\"ram_block\": True})\n- self.assertEqual(m2.attrs, {\"ram_block\": True})\n-\n- def test_read_port_transparent(self):\n- with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- rdport = mem.read_port()\n- self.assertEqual(rdport.memory, mem)\n- self.assertEqual(rdport.domain, \"sync\")\n- self.assertEqual(rdport.transparent, True)\n- self.assertEqual(len(rdport.addr), 2)\n- self.assertEqual(len(rdport.data), 8)\n- self.assertEqual(len(rdport.en), 1)\n- self.assertIsInstance(rdport.en, Signal)\n- self.assertEqual(rdport.en.init, 1)\n-\n- def test_read_port_non_transparent(self):\n- with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- rdport = mem.read_port(transparent=False)\n- self.assertEqual(rdport.memory, mem)\n- self.assertEqual(rdport.domain, \"sync\")\n- self.assertEqual(rdport.transparent, False)\n- self.assertEqual(len(rdport.en), 1)\n- self.assertIsInstance(rdport.en, Signal)\n- self.assertEqual(rdport.en.init, 1)\n-\n- def test_read_port_asynchronous(self):\n- with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- rdport = mem.read_port(domain=\"comb\")\n- self.assertEqual(rdport.memory, mem)\n- self.assertEqual(rdport.domain, \"comb\")\n- self.assertEqual(rdport.transparent, True)\n- self.assertEqual(len(rdport.en), 1)\n- self.assertIsInstance(rdport.en, Const)\n- self.assertEqual(rdport.en.value, 1)\n-\n- def test_read_port_wrong(self):\n- with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- with self.assertRaisesRegex(ValueError,\n- r\"^Read port cannot be simultaneously asynchronous and non-transparent$\"):\n- mem.read_port(domain=\"comb\", transparent=False)\n-\n- def test_write_port(self):\n- with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- wrport = mem.write_port()\n- self.assertEqual(wrport.memory, mem)\n- self.assertEqual(wrport.domain, \"sync\")\n- self.assertEqual(wrport.granularity, 8)\n- self.assertEqual(len(wrport.addr), 2)\n- self.assertEqual(len(wrport.data), 8)\n- self.assertEqual(len(wrport.en), 1)\n-\n- def test_write_port_granularity(self):\n- with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- wrport = mem.write_port(granularity=2)\n- self.assertEqual(wrport.memory, mem)\n- self.assertEqual(wrport.domain, \"sync\")\n- self.assertEqual(wrport.granularity, 2)\n- self.assertEqual(len(wrport.addr), 2)\n- self.assertEqual(len(wrport.data), 8)\n- self.assertEqual(len(wrport.en), 4)\n-\n- def test_write_port_granularity_wrong(self):\n- with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- with self.assertRaisesRegex(TypeError,\n- r\"^Write port granularity must be a non-negative integer, not -1$\"):\n- mem.write_port(granularity=-1)\n- with self.assertRaisesRegex(ValueError,\n- r\"^Write port granularity must not be greater than memory width \\(10 > 8\\)$\"):\n- mem.write_port(granularity=10)\n- with self.assertRaisesRegex(ValueError,\n- r\"^Write port granularity must divide memory width evenly$\"):\n- mem.write_port(granularity=3)\n-\n- def test_deprecated(self):\n- with self.assertWarnsRegex(DeprecationWarning,\n- r\"^`amaranth.hdl.Memory` is deprecated.*$\"):\n- mem = Memory(width=8, depth=4)\n-\n-\n-class DummyPortTestCase(FHDLTestCase):\n- def test_name(self):\n- with _ignore_deprecated():\n- p1 = DummyPort(data_width=8, addr_width=2)\n- self.assertEqual(p1.addr.name, \"p1_addr\")\n- p2 = [DummyPort(data_width=8, addr_width=2)][0]\n- self.assertEqual(p2.addr.name, \"dummy_addr\")\n- p3 = DummyPort(data_width=8, addr_width=2, name=\"foo\")\n- self.assertEqual(p3.addr.name, \"foo_addr\")\n-\n- def test_sizes(self):\n- with _ignore_deprecated():\n- p1 = DummyPort(data_width=8, addr_width=2)\n- self.assertEqual(p1.addr.width, 2)\n- self.assertEqual(p1.data.width, 8)\n- self.assertEqual(p1.en.width, 1)\n- p2 = DummyPort(data_width=8, addr_width=2, granularity=2)\n- self.assertEqual(p2.en.width, 4)\n-\n- def test_deprecated(self):\n- with self.assertWarnsRegex(DeprecationWarning,\n- r\"^`DummyPort` is deprecated.*$\"):\n- DummyPort(data_width=8, addr_width=2)\ndiff --git a/tests/test_hdl_xfrm.py b/tests/test_hdl_xfrm.py\nindex 0ab2eee..4c2ff63 100644\n--- a/tests/test_hdl_xfrm.py\n+++ b/tests/test_hdl_xfrm.py\n@@ -6,7 +6,7 @@ from amaranth.hdl._dsl import *\n from amaranth.hdl._ir import *\n from amaranth.hdl._xfrm import *\n from amaranth.hdl._mem import *\n-from amaranth.hdl._mem import MemoryInstance\n+from amaranth.lib.memory import Memory\n \n from .utils import *\n from amaranth._utils import _ignore_deprecated\n@@ -120,7 +120,7 @@ class DomainRenamerTestCase(FHDLTestCase):\n def test_rename_mem_ports(self):\n m = Module()\n with _ignore_deprecated():\n- mem = Memory(depth=4, width=16)\n+ mem = Memory(depth=4, shape=16, init=[])\n m.submodules.mem = mem\n mem.read_port(domain=\"a\")\n mem.read_port(domain=\"b\")\n@@ -362,23 +362,23 @@ class EnableInserterTestCase(FHDLTestCase):\n \n def test_enable_read_port(self):\n with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- mem.read_port(transparent=False)\n+ mem = Memory(shape=8, depth=4, init=[])\n+ mem_r = mem.read_port()\n f = EnableInserter(self.c1)(mem).elaborate(platform=None)\n self.assertRepr(f._read_ports[0]._en, \"\"\"\n- (& (sig mem_r_en) (sig c1))\n+ (& (sig mem_r__en) (sig c1))\n \"\"\")\n \n def test_enable_write_port(self):\n with _ignore_deprecated():\n- mem = Memory(width=8, depth=4)\n- mem.write_port(granularity=2)\n+ mem = Memory(shape=8, depth=4, init=[])\n+ mem_w = mem.write_port(granularity=2)\n f = EnableInserter(self.c1)(mem).elaborate(platform=None)\n self.assertRepr(f._write_ports[0]._en, \"\"\"\n (switch-value\n (sig c1)\n (case 0 (const 4'd0))\n- (default (sig mem_w_en))\n+ (default (sig mem_w__en))\n )\n \"\"\")\n \n", "FAIL_TO_PASS": ["tests/test_hdl_xfrm.py::DomainRenamerTestCase::test_rename_mem_ports"]}], "all_FAIL_TO_PASS": ["tests/test_hdl_xfrm.py::DomainRenamerTestCase::test_rename_mem_ports"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pvlib__pvlib-python-278_x1", "level": 1, "source": "swerebenchv2", "repo": "pvlib/pvlib-python", "image": "swerebenchv2/pvlib-pvlib-python:278-6a41299", "base_commit": "6a4129905f59dd3c7173f9cdf9c0c59b46b5dcfd", "num_bugs": 1, "bugs": [{"instance_id": "pvlib__pvlib-python-278", "base_commit": "6a4129905f59dd3c7173f9cdf9c0c59b46b5dcfd", "gold_patch": "diff --git a/.gitignore b/.gitignore\nindex 658fe2d..f18eba0 100644\n--- a/.gitignore\n+++ b/.gitignore\n@@ -22,6 +22,7 @@ var/\n Drafts/\n */build/\n build/\n+venv/\n \n *.egg-info/\n .installed.cfg\n@@ -58,6 +59,8 @@ coverage.xml\n .pydevproject\n .spyderproject\n .idea/\n+*.sublime-project\n+*.sublime-workspace\n \n # Rope\n .ropeproject\ndiff --git a/docs/sphinx/source/api.rst b/docs/sphinx/source/api.rst\nindex 332b1b7..ff34b7c 100644\n--- a/docs/sphinx/source/api.rst\n+++ b/docs/sphinx/source/api.rst\n@@ -87,6 +87,10 @@ Airmass and atmospheric models\n atmosphere.alt2pres\n atmosphere.gueymard94_pw\n atmosphere.first_solar_spectral_correction\n+ atmosphere.bird_hulstrom80_aod_bb\n+ atmosphere.kasten96_lt\n+ atmosphere.angstrom_aod_at_lambda\n+ atmosphere.angstrom_alpha\n \n \n Irradiance\ndiff --git a/docs/sphinx/source/conf.py b/docs/sphinx/source/conf.py\nindex 546e61c..21d3cd5 100644\n--- a/docs/sphinx/source/conf.py\n+++ b/docs/sphinx/source/conf.py\n@@ -270,7 +270,8 @@ latex_documents = [\n extlinks = {'issue': ('https://github.com/pvlib/pvlib-python/issues/%s',\n 'GH'),\n 'wiki': ('https://github.com/pvlib/pvlib-python/wiki/%s',\n- 'wiki ')}\n+ 'wiki '),\n+ 'doi': ('http://dx.doi.org/%s', 'DOI: ')}\n \n # -- Options for manual page output ---------------------------------------\n \ndiff --git a/docs/sphinx/source/whatsnew/v0.4.4.txt b/docs/sphinx/source/whatsnew/v0.4.4.txt\nindex 48ff7da..e2be6a7 100644\n--- a/docs/sphinx/source/whatsnew/v0.4.4.txt\n+++ b/docs/sphinx/source/whatsnew/v0.4.4.txt\n@@ -6,6 +6,9 @@ v0.4.4 (January xx, 2017)\n Enhancements\n ~~~~~~~~~~~~\n \n+* Added Kasten pyrheliometric formula to calculate Linke turbidity factors with\n+ improvements by Ineichen and Perez to extend range of air mass (:issue:`278`)\n+\n \n Documentation\n ~~~~~~~~~~~~~\n@@ -19,3 +22,4 @@ Contributors\n ~~~~~~~~~~~~\n \n * Will Holmgren\n+* Mark Mikofski\ndiff --git a/pvlib/atmosphere.py b/pvlib/atmosphere.py\nindex 7ea4b5e..0b90094 100644\n--- a/pvlib/atmosphere.py\n+++ b/pvlib/atmosphere.py\n@@ -292,7 +292,7 @@ def gueymard94_pw(temp_air, relative_humidity):\n ----------\n .. [1] W. M. Keogh and A. W. Blakers, Accurate Measurement, Using Natural\n Sunlight, of Silicon Solar Cells, Prog. in Photovoltaics: Res.\n- and Appl. 2004, vol 12, pp. 1-19 (DOI: 10.1002/pip.517)\n+ and Appl. 2004, vol 12, pp. 1-19 (:doi:`10.1002/pip.517`)\n \n .. [2] C. Gueymard, Analysis of Monthly Average Atmospheric Precipitable\n Water and Turbidity in Canada and Northern United States,\n@@ -467,3 +467,193 @@ def first_solar_spectral_correction(pw, airmass_absolute, module_type=None,\n coeff[4]*np.sqrt(pw) + coeff[5]*ama/np.sqrt(pw))\n \n return modifier\n+\n+\n+def bird_hulstrom80_aod_bb(aod380, aod500):\n+ \"\"\"\n+ Approximate broadband aerosol optical depth.\n+\n+ Bird and Hulstrom developed a correlation for broadband aerosol optical\n+ depth (AOD) using two wavelengths, 380 nm and 500 nm.\n+\n+ Parameters\n+ ----------\n+ aod380 : numeric\n+ AOD measured at 380 nm\n+ aod500 : numeric\n+ AOD measured at 500 nm\n+\n+ Returns\n+ -------\n+ aod_bb : numeric\n+ broadband AOD\n+\n+ See also\n+ --------\n+ kasten96_lt\n+\n+ References\n+ ----------\n+ [1] Bird and Hulstrom, \"Direct Insolation Models\" (1980)\n+ `SERI/TR-335-344 `_\n+\n+ [2] R. E. Bird and R. L. Hulstrom, \"Review, Evaluation, and Improvement of\n+ Direct Irradiance Models\", Journal of Solar Energy Engineering 103(3),\n+ pp. 182-192 (1981)\n+ :doi:`10.1115/1.3266239`\n+ \"\"\"\n+ # approximate broadband AOD using (Bird-Hulstrom 1980)\n+ return 0.27583 * aod380 + 0.35 * aod500\n+\n+\n+def kasten96_lt(airmass_absolute, precipitable_water, aod_bb):\n+ \"\"\"\n+ Calculate Linke turbidity factor using Kasten pyrheliometric formula.\n+\n+ Note that broadband aerosol optical depth (AOD) can be approximated by AOD\n+ measured at 700 nm according to Molineaux [4] . Bird and Hulstrom offer an\n+ alternate approximation using AOD measured at 380 nm and 500 nm.\n+\n+ Based on original implementation by Armel Oumbe.\n+\n+ .. warning::\n+ These calculations are only valid for air mass less than 5 atm and\n+ precipitable water less than 5 cm.\n+\n+ Parameters\n+ ----------\n+ airmass_absolute : numeric\n+ airmass, pressure corrected in atmospheres\n+ precipitable_water : numeric\n+ precipitable water or total column water vapor in centimeters\n+ aod_bb : numeric\n+ broadband AOD\n+\n+ Returns\n+ -------\n+ lt : numeric\n+ Linke turbidity\n+\n+ See also\n+ --------\n+ bird_hulstrom80_aod_bb\n+ angstrom_aod_at_lambda\n+\n+ References\n+ ----------\n+ [1] F. Linke, \"Transmissions-Koeffizient und Trubungsfaktor\", Beitrage\n+ zur Physik der Atmosphare, Vol 10, pp. 91-103 (1922)\n+\n+ [2] F. Kasten, \"A simple parameterization of the pyrheliometric formula for\n+ determining the Linke turbidity factor\", Meteorologische Rundschau 33,\n+ pp. 124-127 (1980)\n+\n+ [3] Kasten, \"The Linke turbidity factor based on improved values of the\n+ integral Rayleigh optical thickness\", Solar Energy, Vol. 56, No. 3,\n+ pp. 239-244 (1996)\n+ :doi:`10.1016/0038-092X(95)00114-7`\n+\n+ [4] B. Molineaux, P. Ineichen, N. O'Neill, \"Equivalence of pyrheliometric\n+ and monochromatic aerosol optical depths at a single key wavelength\",\n+ Applied Optics Vol. 37, issue 10, 7008-7018 (1998)\n+ :doi:`10.1364/AO.37.007008`\n+\n+ [5] P. Ineichen, \"Conversion function between the Linke turbidity and the\n+ atmospheric water vapor and aerosol content\", Solar Energy 82,\n+ pp. 1095-1097 (2008)\n+ :doi:`10.1016/j.solener.2008.04.010`\n+\n+ [6] P. Ineichen and R. Perez, \"A new airmass independent formulation for\n+ the Linke Turbidity coefficient\", Solar Energy, Vol. 73, no. 3, pp. 151-157\n+ (2002)\n+ :doi:`10.1016/S0038-092X(02)00045-2`\n+ \"\"\"\n+ # \"From numerically integrated spectral simulations done with Modtran\n+ # (Berk, 1989), Molineaux (1998) obtained for the broadband optical depth\n+ # of a clean and dry atmospshere (fictitious atmosphere that comprises only\n+ # the effects of Rayleigh scattering and absorption by the atmosphere gases\n+ # other than the water vapor) the following expression\"\n+ # - P. Ineichen (2008)\n+ delta_cda = -0.101 + 0.235 * airmass_absolute ** (-0.16)\n+ # \"and the broadband water vapor optical depth where pwat is the integrated\n+ # precipitable water vapor content of the atmosphere expressed in cm and am\n+ # the optical air mass. The precision of these fits is better than 1% when\n+ # compared with Modtran simulations in the range 1 < am < 5 and\n+ # 0 < pwat < 5 cm at sea level\" - P. Ineichen (2008)\n+ delta_w = 0.112 * airmass_absolute ** (-0.55) * precipitable_water ** 0.34\n+ # broadband AOD\n+ delta_a = aod_bb\n+ # \"Then using the Kasten pyrheliometric formula (1980, 1996), the Linke\n+ # turbidity at am = 2 can be written. The extension of the Linke turbidity\n+ # coefficient to other values of air mass was published by Ineichen and\n+ # Perez (2002)\" - P. Ineichen (2008)\n+ lt = -(9.4 + 0.9 * airmass_absolute) * np.log(\n+ np.exp(-airmass_absolute * (delta_cda + delta_w + delta_a))\n+ ) / airmass_absolute\n+ # filter out of extrapolated values\n+ return lt\n+\n+\n+def angstrom_aod_at_lambda(aod0, lambda0, alpha, lambda1=700.0):\n+ r\"\"\"\n+ Get AOD at specified wavelength using Angstrom turbidity model.\n+\n+ Parameters\n+ ----------\n+ aod0 : numeric\n+ aerosol optical depth (AOD) measured at known wavelength\n+ lambda0 : numeric\n+ wavelength in nanometers corresponding to ``aod0``\n+ alpha : numeric\n+ Angstrom :math:`\\alpha` exponent corresponding to ``aod0``\n+ lambda1 : numeric\n+ desired wavelength in nanometers, defaults to 700 nm\n+\n+ Returns\n+ -------\n+ aod1 : numeric\n+ AOD at desired wavelength, ``lambda1``\n+\n+ See also\n+ --------\n+ angstrom_alpha\n+\n+ References\n+ ----------\n+ [1] Anders Angstrom, \"On the Atmospheric Transmission of Sun Radiation and\n+ On Dust in the Air\", Geografiska Annaler Vol. 11, pp. 156-166 (1929) JSTOR\n+ :doi:`10.2307/519399`\n+\n+ [2] Anders Angstrom, \"Techniques of Determining the Turbidity of the\n+ Atmosphere\", Tellus 13:2, pp. 214-223 (1961) Taylor & Francis\n+ :doi:`10.3402/tellusa.v13i2.9493` and Co-Action Publishing\n+ :doi:`10.1111/j.2153-3490.1961.tb00078.x`\n+ \"\"\"\n+ return aod0 * ((lambda1 / lambda0) ** (-alpha))\n+\n+\n+def angstrom_alpha(aod1, lambda1, aod2, lambda2):\n+ r\"\"\"\n+ Calculate Angstrom alpha exponent.\n+\n+ Parameters\n+ ----------\n+ aod1 : numeric\n+ first aerosol optical depth\n+ lambda1 : numeric\n+ wavelength in nanometers corresponding to ``aod1``\n+ aod2 : numeric\n+ second aerosol optical depth\n+ lambda2 : numeric\n+ wavelength in nanometers corresponding to ``aod2``\n+\n+ Returns\n+ -------\n+ alpha : numeric\n+ Angstrom :math:`\\alpha` exponent for AOD in ``(lambda1, lambda2)``\n+\n+ See also\n+ --------\n+ angstrom_aod_at_lambda\n+ \"\"\"\n+ return - np.log(aod1 / aod2) / np.log(lambda1 / lambda2)\n", "test_patch": "diff --git a/pvlib/test/test_atmosphere.py b/pvlib/test/test_atmosphere.py\nindex 5522fa3..40e58c7 100644\n--- a/pvlib/test/test_atmosphere.py\n+++ b/pvlib/test/test_atmosphere.py\n@@ -1,4 +1,3 @@\n-import datetime\n import itertools\n \n import numpy as np\n@@ -7,10 +6,8 @@ import pandas as pd\n import pytest\n from numpy.testing import assert_allclose\n \n-from pvlib.location import Location\n-from pvlib import solarposition\n from pvlib import atmosphere\n-\n+from pvlib import solarposition\n \n latitude, longitude, tz, altitude = 32.2, -111, 'US/Arizona', 700\n \n@@ -113,3 +110,43 @@ def test_first_solar_spectral_correction_supplied():\n def test_first_solar_spectral_correction_ambiguous():\n with pytest.raises(TypeError):\n atmosphere.first_solar_spectral_correction(1, 1)\n+\n+\n+def test_kasten96_lt():\n+ \"\"\"Test Linke turbidity factor calculated from AOD, Pwat and AM\"\"\"\n+ amp = np.array([1, 3, 5])\n+ pwat = np.array([0, 2.5, 5])\n+ aod_bb = np.array([0, 0.1, 1])\n+ lt_expected = np.array(\n+ [[[1.3802, 2.4102, 11.6802],\n+ [1.16303976, 2.37303976, 13.26303976],\n+ [1.12101907, 2.51101907, 15.02101907]],\n+\n+ [[2.95546945, 3.98546945, 13.25546945],\n+ [2.17435443, 3.38435443, 14.27435443],\n+ [1.99821967, 3.38821967, 15.89821967]],\n+\n+ [[3.37410769, 4.40410769, 13.67410769],\n+ [2.44311797, 3.65311797, 14.54311797],\n+ [2.23134152, 3.62134152, 16.13134152]]]\n+ )\n+ lt = atmosphere.kasten96_lt(*np.meshgrid(amp, pwat, aod_bb))\n+ assert np.allclose(lt, lt_expected, 1e-3)\n+ return lt\n+\n+\n+def test_angstrom_aod():\n+ \"\"\"Test Angstrom turbidity model functions.\"\"\"\n+ aod550 = 0.15\n+ aod1240 = 0.05\n+ alpha = atmosphere.angstrom_alpha(aod550, 550, aod1240, 1240)\n+ assert np.isclose(alpha, 1.3513924317859232)\n+ aod700 = atmosphere.angstrom_aod_at_lambda(aod550, 550, alpha)\n+ assert np.isclose(aod700, 0.10828110997681031)\n+\n+\n+def test_bird_hulstrom80_aod_bb():\n+ \"\"\"Test Bird_Hulstrom broadband AOD.\"\"\"\n+ aod380, aod500 = 0.22072480948195175, 0.1614279181106312\n+ bird_hulstrom = atmosphere.bird_hulstrom80_aod_bb(aod380, aod500)\n+ assert np.isclose(0.11738229553812768, bird_hulstrom)\n", "FAIL_TO_PASS": ["pvlib/test/test_atmosphere.py::test_kasten96_lt", "pvlib/test/test_atmosphere.py::test_angstrom_aod", "pvlib/test/test_atmosphere.py::test_bird_hulstrom80_aod_bb"]}], "all_FAIL_TO_PASS": ["pvlib/test/test_atmosphere.py::test_kasten96_lt", "pvlib/test/test_atmosphere.py::test_angstrom_aod", "pvlib/test/test_atmosphere.py::test_bird_hulstrom80_aod_bb"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pvlib__pvlib-python-304_x1", "level": 1, "source": "swerebenchv2", "repo": "pvlib/pvlib-python", "image": "swerebenchv2/pvlib-pvlib-python:304-be65117", "base_commit": "be65117d9cc14f8afc9b2c0a629fe54573771062", "num_bugs": 1, "bugs": [{"instance_id": "pvlib__pvlib-python-304", "base_commit": "be65117d9cc14f8afc9b2c0a629fe54573771062", "gold_patch": "diff --git a/.gitattributes b/.gitattributes\nindex 4488f4c..81490a9 100644\n--- a/.gitattributes\n+++ b/.gitattributes\n@@ -1,1 +1,4 @@\n pvlib/version.py export-subst\n+\n+# reduce the number of merge conflicts\n+docs/sphinx/source/whatsnew/v*.txt merge=union\ndiff --git a/docs/sphinx/source/whatsnew/v0.4.4.txt b/docs/sphinx/source/whatsnew/v0.4.4.txt\nindex 4356814..b0aff39 100644\n--- a/docs/sphinx/source/whatsnew/v0.4.4.txt\n+++ b/docs/sphinx/source/whatsnew/v0.4.4.txt\n@@ -10,6 +10,14 @@ Enhancements\n improvements by Ineichen and Perez to extend range of air mass (:issue:`278`)\n \n \n+API Changes\n+~~~~~~~~~~~\n+\n+* Change PVSystem default module_parameters and inverter_parameters to\n+ empty dict. Code that relied on these attributes being None or raising\n+ a TypeError will need to be updated. (issue:`294`)\n+\n+\n Documentation\n ~~~~~~~~~~~~~\n \ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\nindex ba64fc2..ce5947e 100644\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -133,13 +133,19 @@ class PVSystem(object):\n \n # could tie these together with @property\n self.module = module\n- self.module_parameters = module_parameters\n+ if module_parameters is None:\n+ self.module_parameters = {}\n+ else:\n+ self.module_parameters = module_parameters\n \n self.modules_per_string = modules_per_string\n self.strings_per_inverter = strings_per_inverter\n \n self.inverter = inverter\n- self.inverter_parameters = inverter_parameters\n+ if inverter_parameters is None:\n+ self.inverter_parameters = {}\n+ else:\n+ self.inverter_parameters = inverter_parameters\n \n self.racking_model = racking_model\n \n", "test_patch": "diff --git a/pvlib/test/test_pvsystem.py b/pvlib/test/test_pvsystem.py\nindex ba9372f..4fbc9b1 100644\n--- a/pvlib/test/test_pvsystem.py\n+++ b/pvlib/test/test_pvsystem.py\n@@ -615,6 +615,9 @@ def test_snlinverter_Pnt_micro(sam_data):\n \n def test_PVSystem_creation():\n pv_system = pvsystem.PVSystem(module='blah', inverter='blarg')\n+ # ensure that parameter attributes are dict-like. GH 294\n+ pv_system.module_parameters['pdc0'] = 1\n+ pv_system.inverter_parameters['Paco'] = 1\n \n \n def test_PVSystem_get_aoi():\n", "FAIL_TO_PASS": ["pvlib/test/test_pvsystem.py::test_PVSystem_creation"]}], "all_FAIL_TO_PASS": ["pvlib/test/test_pvsystem.py::test_PVSystem_creation"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "rigetticomputing__pyquil-166_x1", "level": 1, "source": "swerebenchv2", "repo": "rigetticomputing/pyquil", "image": "swerebenchv2/rigetticomputing-pyquil:166-b7aee5b", "base_commit": "b7aee5b8476d17c6375e185f2f30ee1a9a6ca6eb", "num_bugs": 1, "bugs": [{"instance_id": "rigetticomputing__pyquil-166", "base_commit": "b7aee5b8476d17c6375e185f2f30ee1a9a6ca6eb", "gold_patch": "diff --git a/pyquil/quilbase.py b/pyquil/quilbase.py\nindex 82aad3c..ff40289 100644\n--- a/pyquil/quilbase.py\n+++ b/pyquil/quilbase.py\n@@ -254,6 +254,9 @@ class InstructionGroup(QuilAction):\n \n return synthesized\n \n+ def __len__(self):\n+ return len(self.synthesize())\n+\n def __str__(self):\n return self.out()\n \n", "test_patch": "diff --git a/pyquil/tests/test_quil.py b/pyquil/tests/test_quil.py\nindex 482f374..e4dfefb 100644\n--- a/pyquil/tests/test_quil.py\n+++ b/pyquil/tests/test_quil.py\n@@ -108,6 +108,23 @@ def test_program_pop():\n assert Program(instruction).out() == \"X 1\\n\"\n \n \n+def test_len_zero():\n+ prog = Program()\n+ assert len(prog) == 0\n+\n+\n+def test_len_one():\n+ prog = Program(X(0))\n+ assert len(prog) == 1\n+\n+\n+def test_len_nested():\n+ p = Program(H(0)).measure(0, 0)\n+ q = Program(H(0), CNOT(0, 1))\n+ p.if_then(0, q)\n+ assert len(p) == 8\n+\n+\n def test_plus_operator():\n p = Program()\n p += H(0)\n", "FAIL_TO_PASS": ["pyquil/tests/test_quil.py::test_len_zero", "pyquil/tests/test_quil.py::test_len_one", "pyquil/tests/test_quil.py::test_len_nested"]}], "all_FAIL_TO_PASS": ["pyquil/tests/test_quil.py::test_len_zero", "pyquil/tests/test_quil.py::test_len_one", "pyquil/tests/test_quil.py::test_len_nested"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "sdv-dev__rdt-610_x1", "level": 1, "source": "swerebenchv2", "repo": "sdv-dev/RDT", "image": "swerebenchv2/sdv-dev-rdt:610-a8aacd1", "base_commit": "a8aacd1df1d1c9598e913f96cb022197eca0948a", "num_bugs": 1, "bugs": [{"instance_id": "sdv-dev__rdt-610", "base_commit": "a8aacd1df1d1c9598e913f96cb022197eca0948a", "gold_patch": "diff --git a/rdt/performance/datasets/categorical.py b/rdt/performance/datasets/categorical.py\nindex d747211..13b43d8 100644\n--- a/rdt/performance/datasets/categorical.py\n+++ b/rdt/performance/datasets/categorical.py\n@@ -331,7 +331,7 @@ class UniqueIntegerGenerator(CategoricalGenerator):\n 'memory': 2000.0\n },\n 'transform': {\n- 'time': 0.0003,\n+ 'time': 0.0004,\n 'memory': 500000.0\n },\n 'reverse_transform': {\n@@ -358,11 +358,11 @@ class UniqueIntegerNaNsGenerator(CategoricalGenerator):\n 'memory': 1000.0\n },\n 'transform': {\n- 'time': 0.0002,\n+ 'time': 0.0004,\n 'memory': 1000000.0\n },\n 'reverse_transform': {\n- 'time': 0.0002,\n+ 'time': 0.0004,\n 'memory': 1000000.0,\n }\n }\n@@ -385,7 +385,7 @@ class UniqueStringGenerator(CategoricalGenerator):\n 'memory': 2000.0\n },\n 'transform': {\n- 'time': 0.0002,\n+ 'time': 0.0004,\n 'memory': 500000.0\n },\n 'reverse_transform': {\n@@ -416,7 +416,7 @@ class UniqueStringNaNsGenerator(CategoricalGenerator):\n 'memory': 1000000.0\n },\n 'reverse_transform': {\n- 'time': 0.0002,\n+ 'time': 0.0005,\n 'memory': 1000000.0,\n }\n }\ndiff --git a/rdt/transformers/base.py b/rdt/transformers/base.py\nindex 137dff7..a534c6e 100644\n--- a/rdt/transformers/base.py\n+++ b/rdt/transformers/base.py\n@@ -100,6 +100,8 @@ class BaseTransformer:\n \n def reset_randomization(self):\n \"\"\"Reset the random state for ``reverse_transform``.\"\"\"\n+ self.set_random_state(self.INITIAL_FIT_STATE, 'fit')\n+ self.set_random_state(self.INITIAL_TRANSFORM_STATE, 'transform')\n self.set_random_state(self.INITIAL_REVERSE_TRANSFORM_STATE, 'reverse_transform')\n \n def _set_missing_value_replacement(self, default, missing_value_replacement):\ndiff --git a/rdt/transformers/categorical.py b/rdt/transformers/categorical.py\nindex edbb759..ec6e7e5 100644\n--- a/rdt/transformers/categorical.py\n+++ b/rdt/transformers/categorical.py\n@@ -566,6 +566,22 @@ class CustomLabelEncoder(LabelEncoder):\n self.order = pd.Series(order).fillna(np.nan)\n super().__init__(add_noise=add_noise)\n \n+ def __repr__(self):\n+ \"\"\"Represent initialization of transformer as text.\n+\n+ Returns:\n+ str:\n+ The name of the transformer followed by any non-default parameters.\n+ \"\"\"\n+ class_name = self.__class__.get_name()\n+ custom_args = []\n+ custom_args.append('order=')\n+ if self.add_noise:\n+ custom_args.append(f'add_noise={self.add_noise}')\n+\n+ args_string = ', '.join(custom_args)\n+ return f'{class_name}({args_string})'\n+\n def _fit(self, data):\n \"\"\"Fit the transformer to the data.\n \n", "test_patch": "diff --git a/tests/unit/transformers/test_base.py b/tests/unit/transformers/test_base.py\nindex 7d35c10..633d7c5 100644\n--- a/tests/unit/transformers/test_base.py\n+++ b/tests/unit/transformers/test_base.py\n@@ -117,14 +117,20 @@ class TestBaseTransformer:\n \"\"\"Test that the random seed for ``reverse_transform`` is reset.\"\"\"\n # Setup\n transformer = BaseTransformer()\n+ transformer.random_states['fit'] = 0\n+ transformer.random_states['transform'] = 2\n transformer.random_states['reverse_transform'] = None\n \n # Run\n transformer.reset_randomization()\n \n # Assert\n- expected_state = transformer.INITIAL_REVERSE_TRANSFORM_STATE\n- assert transformer.random_states['reverse_transform'] == expected_state\n+ fit_state = transformer.INITIAL_FIT_STATE\n+ transform_state = transformer.INITIAL_TRANSFORM_STATE\n+ reverse_transform_state = transformer.INITIAL_REVERSE_TRANSFORM_STATE\n+ assert transformer.random_states['fit'] == fit_state\n+ assert transformer.random_states['transform'] == transform_state\n+ assert transformer.random_states['reverse_transform'] == reverse_transform_state\n \n def test_get_subclasses(self):\n \"\"\"Test the ``get_subclasses`` method.\ndiff --git a/tests/unit/transformers/test_categorical.py b/tests/unit/transformers/test_categorical.py\nindex cffafad..800f9a2 100644\n--- a/tests/unit/transformers/test_categorical.py\n+++ b/tests/unit/transformers/test_categorical.py\n@@ -1808,6 +1808,35 @@ class TestCustomLabelEncoder:\n assert transformer.add_noise == 'add_noise_value'\n pd.testing.assert_series_equal(transformer.order, pd.Series(['b', 'c', 'a', np.nan]))\n \n+ def test___repr___default(self):\n+ \"\"\"Test that the ``__repr__`` method prints the custom order.\n+\n+ The order should be printed as instead of the actual order.\n+ \"\"\"\n+ # Setup\n+ transformer = CustomLabelEncoder(order=['VISA', 'AMEX', 'DISCOVER', None])\n+\n+ # Run\n+ stringified_transformer = transformer.__repr__()\n+\n+ # Assert\n+ assert stringified_transformer == 'CustomLabelEncoder(order=)'\n+\n+ def test___repr___add_noise_true(self):\n+ \"\"\"Test that the ``__repr__`` method prints the custom order with ``add_noise``.\n+\n+ The order should be printed as instead of the actual order. If ``add_noise``\n+ is provided, it should be printed too.\n+ \"\"\"\n+ # Setup\n+ transformer = CustomLabelEncoder(order=['VISA', 'AMEX', 'DISCOVER', None], add_noise=True)\n+\n+ # Run\n+ stringified_transformer = transformer.__repr__()\n+\n+ # Assert\n+ assert stringified_transformer == 'CustomLabelEncoder(order=, add_noise=True)'\n+\n def test__fit(self):\n \"\"\"Test the ``_fit`` method.\n \n", "FAIL_TO_PASS": ["tests/unit/transformers/test_base.py::TestBaseTransformer::test_reset_randomization", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___add_noise_true"]}], "all_FAIL_TO_PASS": ["tests/unit/transformers/test_base.py::TestBaseTransformer::test_reset_randomization", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___add_noise_true"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pyccel__pyccel-2072_x1", "level": 1, "source": "swerebenchv2", "repo": "pyccel/pyccel", "image": "swerebenchv2/pyccel-pyccel:2072-0341065", "base_commit": "03410656a3336afa229ff4c604d497e0999c5750", "num_bugs": 1, "bugs": [{"instance_id": "pyccel__pyccel-2072", "base_commit": "03410656a3336afa229ff4c604d497e0999c5750", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex ca6291ca..bcf2cb4f 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -44,6 +44,7 @@ All notable changes to this project will be documented in this file.\n - #1918 : Add support for set method `clear()`.\n - #1918 : Add support for set method `copy()`.\n - #1753 : Add support for set method `union()`.\n+- #1744 : Add Python support for set method `intersection()`.\n - #1884 : Add support for dict method `items()`.\n - #1936 : Add missing C output for inline decorator example in documentation\n - #1937 : Optimise `pyccel.ast.basic.PyccelAstNode.substitute` method.\ndiff --git a/docs/builtin-functions.md b/docs/builtin-functions.md\nindex cc613789..b7ca91c6 100644\n--- a/docs/builtin-functions.md\n+++ b/docs/builtin-functions.md\n@@ -102,7 +102,7 @@ Python contains a limited number of builtin functions defined [here](https://doc\n | `difference` | No |\n | `difference_update` | No |\n | `discard` | Python-only |\n-| `intersection` | No |\n+| `intersection` | Python-only |\n | `intersection_update` | No |\n | `isdisjoint` | No |\n | `issubset` | No |\ndiff --git a/pyccel/ast/builtin_methods/set_methods.py b/pyccel/ast/builtin_methods/set_methods.py\nindex 782fee7d..85630e80 100644\n--- a/pyccel/ast/builtin_methods/set_methods.py\n+++ b/pyccel/ast/builtin_methods/set_methods.py\n@@ -18,6 +18,7 @@ __all__ = (\n 'SetClear',\n 'SetCopy',\n 'SetDiscard',\n+ 'SetIntersection',\n 'SetMethod',\n 'SetPop',\n 'SetUnion',\n@@ -232,3 +233,32 @@ class SetUnion(SetMethod):\n raise TypeError(f\"Argument of type {o.class_type} cannot be used to build set of type {self._class_type}\")\n self._shape = (None,)*self._class_type.rank\n super().__init__(set_obj, *others)\n+\n+#==============================================================================\n+\n+class SetIntersection(SetMethod):\n+ \"\"\"\n+ Represents a call to the set method .intersection.\n+\n+ Represents a call to the set method .intersection. This method builds a new set\n+ by including all elements which appear in \"both\" of the iterables\n+ (the set object and the arguments).\n+\n+ Parameters\n+ ----------\n+ set_obj : TypedAstNode\n+ The set object which the method is called from.\n+ *others : TypedAstNode\n+ The iterables which will be combined (common elements) with this set.\n+ \"\"\"\n+ __slots__ = ('_other','_class_type', '_shape')\n+ name = 'intersection'\n+\n+ def __init__(self, set_obj, *others):\n+ self._class_type = set_obj.class_type\n+ element_type = self._class_type.element_type\n+ for o in others:\n+ if element_type != o.class_type.element_type:\n+ raise TypeError(f\"Argument fo type {o.type_class} cannot be used to build set of type {self._class_type}\")\n+ self._shape = (None,)*self.rank\n+ super().__init__(set_obj, *others)\ndiff --git a/pyccel/ast/class_defs.py b/pyccel/ast/class_defs.py\nindex da4bee0b..9ecdc16d 100644\n--- a/pyccel/ast/class_defs.py\n+++ b/pyccel/ast/class_defs.py\n@@ -7,7 +7,7 @@ This module contains all types which define a python class which is automaticall\n \"\"\"\n \n from pyccel.ast.builtin_methods.set_methods import (SetAdd, SetClear, SetCopy, SetPop,\n- SetDiscard, SetUpdate, SetUnion)\n+ SetDiscard, SetUpdate, SetUnion, SetIntersection)\n from pyccel.ast.builtin_methods.list_methods import (ListAppend, ListInsert, ListPop,\n ListClear, ListExtend, ListRemove,\n ListCopy, ListSort)\n@@ -166,8 +166,10 @@ SetClass = ClassDef('set',\n PyccelFunctionDef('pop', func_class = SetPop),\n PyccelFunctionDef('remove', func_class = SetDiscard),\n PyccelFunctionDef('union', func_class = SetUnion),\n+ PyccelFunctionDef('intersection', func_class = SetIntersection),\n PyccelFunctionDef('update', func_class = SetUpdate),\n PyccelFunctionDef('__or__', func_class = SetUnion),\n+ PyccelFunctionDef('__and__', func_class = SetIntersection),\n PyccelFunctionDef('__ior__', func_class = SetUpdate),\n ])\n \ndiff --git a/pyccel/parser/syntactic.py b/pyccel/parser/syntactic.py\nindex 8e32cd9f..8546eb35 100644\n--- a/pyccel/parser/syntactic.py\n+++ b/pyccel/parser/syntactic.py\n@@ -442,6 +442,8 @@ class SyntaxParser(BasicParser):\n return AugAssign(lhs, '%', rhs)\n elif isinstance(stmt.op, ast.BitOr):\n return AugAssign(lhs, '|', rhs)\n+ elif isinstance(stmt.op, ast.BitAnd):\n+ return AugAssign(lhs, '&', rhs)\n else:\n return errors.report(PYCCEL_RESTRICTION_TODO, symbol = stmt,\n severity='error')\n", "test_patch": "diff --git a/tests/epyccel/test_epyccel_sets.py b/tests/epyccel/test_epyccel_sets.py\nindex e54f45ff..acb045b2 100644\n--- a/tests/epyccel/test_epyccel_sets.py\n+++ b/tests/epyccel/test_epyccel_sets.py\n@@ -425,6 +425,46 @@ def test_set_union_2_args(language):\n assert python_result[0] == pyccel_result[0]\n assert set(python_result[1:]) == set(pyccel_result[1:])\n \n+def test_set_intersection_int(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3}\n+ b = {2,3,4}\n+ c = a.intersection(b)\n+ return len(c), c.pop(), c.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_no_args(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4}\n+ c = a.intersection()\n+ a.add(5)\n+ return len(c), c.pop(), c.pop(), c.pop(), c.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_2_args(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4}\n+ b = {5,6,7,2,1,3}\n+ c = {7,6,10,4,2,3,1}\n+ d = a.intersection(b, c)\n+ return len(d), d.pop(), d.pop(), d.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n @pytest.mark.parametrize( 'language', (\n pytest.param(\"fortran\", marks = pytest.mark.fortran),\n pytest.param(\"c\", marks = [\n@@ -485,6 +525,57 @@ def test_set_union_operator(language):\n assert python_result[0] == pyccel_result[0]\n assert set(python_result[1:]) == set(pyccel_result[1:])\n \n+def test_temporary_set_intersection(python_only_language):\n+ def intersection_int():\n+ a = {1,2}\n+ b = {2}\n+ d = a.intersection(b).pop()\n+ return d\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result == pyccel_result\n+\n+def test_set_intersection_list(python_only_language):\n+ def intersection_list():\n+ a = {1.2, 2.3, 5.0}\n+ b = [1.2, 5.0, 4.0]\n+ d = a.intersection(b)\n+ return len(d), d.pop(), d.pop()\n+\n+ epyccel_func = epyccel(intersection_list, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_list()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_tuple(python_only_language):\n+ def intersection_tuple():\n+ a = {True}\n+ b = (False, True)\n+ d = a.intersection(b)\n+ return len(d), d.pop()\n+\n+ epyccel_func = epyccel(intersection_tuple, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_tuple()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_operator(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4,8}\n+ b = {5,2,3,7,8}\n+ c = a & b\n+ return len(c), c.pop(), c.pop(), c.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n @pytest.mark.parametrize( 'language', (\n pytest.param(\"fortran\", marks = [\n pytest.mark.xfail(reason=\"Update not fully implemented yet. See #2022\"),\n@@ -521,6 +612,19 @@ def test_set_contains(language):\n python_result = union_int()\n assert python_result == pyccel_result\n \n+def test_set_intersection_augoperator(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4}\n+ b = {2,3,4}\n+ a &= b\n+ return len(a), a.pop(), a.pop(), a.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n def test_set_ptr(language):\n def set_ptr():\n a = {1,2,3,4,5,6,7,8}\n", "FAIL_TO_PASS": ["tests/epyccel/test_epyccel_sets.py::test_set_intersection_int[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_no_args[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_2_args[python]", "tests/epyccel/test_epyccel_sets.py::test_temporary_set_intersection[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_list[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_tuple[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_operator[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_augoperator[python]"]}], "all_FAIL_TO_PASS": ["tests/epyccel/test_epyccel_sets.py::test_set_intersection_int[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_no_args[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_2_args[python]", "tests/epyccel/test_epyccel_sets.py::test_temporary_set_intersection[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_list[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_tuple[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_operator[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_augoperator[python]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "amaranth-lang__amaranth-1406_x1", "level": 1, "source": "swerebenchv2", "repo": "amaranth-lang/amaranth", "image": "swerebenchv2/amaranth-lang-amaranth:1406-0915b9a", "base_commit": "0915b9a043f8c8c6511a8e398948d93b82f92bbf", "num_bugs": 1, "bugs": [{"instance_id": "amaranth-lang__amaranth-1406", "base_commit": "0915b9a043f8c8c6511a8e398948d93b82f92bbf", "gold_patch": "diff --git a/amaranth/lib/data.py b/amaranth/lib/data.py\nindex 6135bb0..8c77cc2 100644\n--- a/amaranth/lib/data.py\n+++ b/amaranth/lib/data.py\n@@ -850,6 +850,12 @@ class View(ValueCastable):\n f\"may only be accessed by indexing\")\n return item\n \n+ def __len__(self):\n+ if not isinstance(self.__layout, ArrayLayout):\n+ raise TypeError(\n+ f\"`len()` can only be used on views of array layout, not {self.__layout!r}\")\n+ return self.__layout.length\n+\n def __eq__(self, other):\n if isinstance(other, View) and self.__layout == other.__layout:\n return self.__target == other.__target\n", "test_patch": "diff --git a/tests/test_lib_data.py b/tests/test_lib_data.py\nindex 697f366..ceafd63 100644\n--- a/tests/test_lib_data.py\n+++ b/tests/test_lib_data.py\n@@ -763,6 +763,14 @@ class ViewTestCase(FHDLTestCase):\n r\"with the same layout, not .*$\"):\n s1 != Const(0, 2)\n \n+ def test_len(self):\n+ s1 = Signal(data.StructLayout({\"a\": unsigned(2)}))\n+ with self.assertRaisesRegex(TypeError,\n+ r\"^`len\\(\\)` can only be used on views of array layout, not StructLayout.*$\"):\n+ len(s1)\n+ s2 = Signal(data.ArrayLayout(2, 3))\n+ self.assertEqual(len(s2), 3)\n+\n def test_operator(self):\n s1 = Signal(data.StructLayout({\"a\": unsigned(2)}))\n s2 = Signal(unsigned(2))\n", "FAIL_TO_PASS": ["tests/test_lib_data.py::ViewTestCase::test_len"]}], "all_FAIL_TO_PASS": ["tests/test_lib_data.py::ViewTestCase::test_len"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "amaranth-lang__amaranth-1420_x1", "level": 1, "source": "swerebenchv2", "repo": "amaranth-lang/amaranth", "image": "swerebenchv2/amaranth-lang-amaranth:1420-94becb5", "base_commit": "94becb521ab7537f05d6facb1e32ea3e99a94873", "num_bugs": 1, "bugs": [{"instance_id": "amaranth-lang__amaranth-1420", "base_commit": "94becb521ab7537f05d6facb1e32ea3e99a94873", "gold_patch": "diff --git a/amaranth/lib/data.py b/amaranth/lib/data.py\nindex 8c77cc2..69ca86c 100644\n--- a/amaranth/lib/data.py\n+++ b/amaranth/lib/data.py\n@@ -219,12 +219,16 @@ class Layout(ShapeCastable, metaclass=ABCMeta):\n elif isinstance(init, Sequence):\n iterator = enumerate(init)\n else:\n- raise TypeError(\"Layout constant initializer must be a mapping or a sequence, not {!r}\"\n- .format(init))\n+ raise TypeError(f\"Layout constant initializer must be a mapping or a sequence, not \"\n+ f\"{init!r}\")\n \n int_value = 0\n for key, key_value in iterator:\n- field = self[key]\n+ try:\n+ field = self[key]\n+ except KeyError:\n+ raise ValueError(f\"Layout constant initializer refers to key {key!r}, which is not \"\n+ f\"a part of the layout\")\n cast_field_shape = Shape.cast(field.shape)\n if isinstance(field.shape, ShapeCastable):\n key_value = hdl.Const.cast(hdl.Const(key_value, field.shape))\n@@ -1079,9 +1083,18 @@ class Const(ValueCastable):\n elif isinstance(other, Const) and self.__layout == other.__layout:\n return self.__target == other.__target\n else:\n+ cause = None\n+ if isinstance(other, (dict, list)):\n+ try:\n+ other_as_const = self.__layout.const(other)\n+ except (TypeError, ValueError) as exc:\n+ cause = exc\n+ else:\n+ return self == other_as_const\n raise TypeError(\n- f\"Constant with layout {self.__layout!r} can only be compared to another view or \"\n- f\"constant with the same layout, not {other!r}\")\n+ f\"Constant with layout {self.__layout!r} can only be compared to another view, \"\n+ f\"a constant with the same layout, or a dictionary or a list that can be converted \"\n+ f\"to a constant with the same layout, not {other!r}\") from cause\n \n def __ne__(self, other):\n if isinstance(other, View) and self.__layout == other._View__layout:\n@@ -1089,9 +1102,18 @@ class Const(ValueCastable):\n elif isinstance(other, Const) and self.__layout == other.__layout:\n return self.__target != other.__target\n else:\n+ cause = None\n+ if isinstance(other, (dict, list)):\n+ try:\n+ other_as_const = self.__layout.const(other)\n+ except (TypeError, ValueError) as exc:\n+ cause = exc\n+ else:\n+ return self != other_as_const\n raise TypeError(\n- f\"Constant with layout {self.__layout!r} can only be compared to another view or \"\n- f\"constant with the same layout, not {other!r}\")\n+ f\"Constant with layout {self.__layout!r} can only be compared to another view, \"\n+ f\"a constant with the same layout, or a dictionary or a list that can be converted \"\n+ f\"to a constant with the same layout, not {other!r}\") from cause\n \n def __add__(self, other):\n raise TypeError(\"Cannot perform arithmetic operations on a lib.data.Const\")\n", "test_patch": "diff --git a/tests/test_lib_data.py b/tests/test_lib_data.py\nindex ceafd63..86a75c1 100644\n--- a/tests/test_lib_data.py\n+++ b/tests/test_lib_data.py\n@@ -477,6 +477,10 @@ class LayoutTestCase(FHDLTestCase):\n r\"^Layout constant initializer must be a mapping or a sequence, not \"\n r\"<.+?object.+?>$\"):\n sl.const(object())\n+ with self.assertRaisesRegex(ValueError,\n+ r\"^Layout constant initializer refers to key 'g', which is not a part \"\n+ r\"of the layout$\"):\n+ sl.const({\"g\": 1})\n sl2 = data.StructLayout({\"f\": unsigned(2)})\n with self.assertRaisesRegex(ValueError,\n r\"^Const layout StructLayout.* differs from shape layout StructLayout.*$\"):\n@@ -740,7 +744,7 @@ class ViewTestCase(FHDLTestCase):\n r\"^View with an array layout does not have fields$\"):\n Signal(data.ArrayLayout(unsigned(1), 1), init=[0]).init\n \n- def test_eq(self):\n+ def test_compare(self):\n s1 = Signal(data.StructLayout({\"a\": unsigned(2)}))\n s2 = Signal(data.StructLayout({\"a\": unsigned(2)}))\n s3 = Signal(data.StructLayout({\"a\": unsigned(1), \"b\": unsigned(1)}))\n@@ -969,11 +973,12 @@ class ConstTestCase(FHDLTestCase):\n r\"^Constant with an array layout does not have fields$\"):\n data.Const(data.ArrayLayout(unsigned(1), 1), 0).init\n \n- def test_eq(self):\n+ def test_compare(self):\n c1 = data.Const(data.StructLayout({\"a\": unsigned(2)}), 1)\n c2 = data.Const(data.StructLayout({\"a\": unsigned(2)}), 1)\n c3 = data.Const(data.StructLayout({\"a\": unsigned(2)}), 2)\n c4 = data.Const(data.StructLayout({\"a\": unsigned(1), \"b\": unsigned(1)}), 2)\n+ c5 = data.Const(data.ArrayLayout(2, 4), 0b11100100)\n s1 = Signal(data.StructLayout({\"a\": unsigned(2)}))\n self.assertTrue(c1 == c2)\n self.assertFalse(c1 != c2)\n@@ -983,13 +988,23 @@ class ConstTestCase(FHDLTestCase):\n self.assertRepr(c1 != s1, \"(!= (const 2'd1) (sig s1))\")\n self.assertRepr(s1 == c1, \"(== (sig s1) (const 2'd1))\")\n self.assertRepr(s1 != c1, \"(!= (sig s1) (const 2'd1))\")\n+ self.assertTrue(c1 == {\"a\": 1})\n+ self.assertFalse(c1 == {\"a\": 2})\n+ self.assertFalse(c1 != {\"a\": 1})\n+ self.assertTrue(c1 != {\"a\": 2})\n+ self.assertTrue(c5 == [0,1,2,3])\n+ self.assertFalse(c5 == [0,1,3,3])\n+ self.assertFalse(c5 != [0,1,2,3])\n+ self.assertTrue(c5 != [0,1,3,3])\n with self.assertRaisesRegex(TypeError,\n- r\"^Constant with layout .* can only be compared to another view or constant with \"\n- r\"the same layout, not .*$\"):\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n c1 == c4\n with self.assertRaisesRegex(TypeError,\n- r\"^Constant with layout .* can only be compared to another view or constant with \"\n- r\"the same layout, not .*$\"):\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n c1 != c4\n with self.assertRaisesRegex(TypeError,\n r\"^View with layout .* can only be compared to another view or constant with \"\n@@ -1000,21 +1015,45 @@ class ConstTestCase(FHDLTestCase):\n r\"the same layout, not .*$\"):\n s1 != c4\n with self.assertRaisesRegex(TypeError,\n- r\"^Constant with layout .* can only be compared to another view or constant with \"\n- r\"the same layout, not .*$\"):\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n c4 == s1\n with self.assertRaisesRegex(TypeError,\n- r\"^Constant with layout .* can only be compared to another view or constant with \"\n- r\"the same layout, not .*$\"):\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n c4 != s1\n with self.assertRaisesRegex(TypeError,\n- r\"^Constant with layout .* can only be compared to another view or constant with \"\n- r\"the same layout, not .*$\"):\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n c1 == Const(0, 2)\n with self.assertRaisesRegex(TypeError,\n- r\"^Constant with layout .* can only be compared to another view or constant with \"\n- r\"the same layout, not .*$\"):\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n c1 != Const(0, 2)\n+ with self.assertRaisesRegex(TypeError,\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n+ c1 == {\"b\": 1}\n+ with self.assertRaisesRegex(TypeError,\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n+ c1 != {\"b\": 1}\n+ with self.assertRaisesRegex(TypeError,\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n+ c5 == [0,1,2,3,4]\n+ with self.assertRaisesRegex(TypeError,\n+ r\"^Constant with layout .* can only be compared to another view, a constant \"\n+ r\"with the same layout, or a dictionary or a list that can be converted to \"\n+ r\"a constant with the same layout, not .*$\"):\n+ c5 != [0,1,2,3,4]\n \n def test_operator(self):\n s1 = data.Const(data.StructLayout({\"a\": unsigned(2)}), 2)\n", "FAIL_TO_PASS": ["tests/test_lib_data.py::LayoutTestCase::test_const_wrong", "tests/test_lib_data.py::ConstTestCase::test_compare"]}], "all_FAIL_TO_PASS": ["tests/test_lib_data.py::LayoutTestCase::test_const_wrong", "tests/test_lib_data.py::ConstTestCase::test_compare"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "takluyver__flit-168_x2", "level": 2, "source": "swerebenchv2", "repo": "takluyver/flit", "image": "swerebenchv2/takluyver-flit:168-29dbe93", "base_commit": "29dbe93af9005487e14a85da4e0e7c408f536231", "num_bugs": 2, "bugs": [{"instance_id": "takluyver__flit-168", "base_commit": "29dbe93af9005487e14a85da4e0e7c408f536231", "gold_patch": "diff --git a/doc/history.rst b/doc/history.rst\nindex 650ad1e..4effcd6 100644\n--- a/doc/history.rst\n+++ b/doc/history.rst\n@@ -1,6 +1,13 @@\n Release history\n ===============\n \n+Version 0.14\n+------------\n+\n+- Multiple links (e.g. documentation, bug tracker) can now be specified in a\n+ new :ref:`[tool.flit.metadata.urls] section ` of\n+ ``pyproject.toml``.\n+\n Version 0.13\n ------------\n \ndiff --git a/doc/pyproject_toml.rst b/doc/pyproject_toml.rst\nindex 422cda7..09dfcf4 100644\n--- a/doc/pyproject_toml.rst\n+++ b/doc/pyproject_toml.rst\n@@ -115,6 +115,25 @@ Here's the full metadata section from flit itself:\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ]\n \n+.. _pyproject_toml_urls:\n+\n+URLs subsection\n+~~~~~~~~~~~~~~~\n+\n+Your project's page on `pypi.org `_ can show a number of\n+links, in addition to the required ``home-page`` URL described above. You can\n+point people to documentation or a bug tracker, for example.\n+\n+This section is called ``[tool.flit.metadata.urls]`` in the file. You can use\n+any names inside it. Here it is for flit:\n+\n+.. code-block:: toml\n+\n+ [tool.flit.metadata.urls]\n+ Documentation = \"https://flit.readthedocs.io/en/latest/\"\n+\n+.. versionadded:: 0.14\n+\n .. _pyproject_toml_scripts:\n \n Scripts section\ndiff --git a/flit/common.py b/flit/common.py\nindex 833f31a..5def1f9 100644\n--- a/flit/common.py\n+++ b/flit/common.py\n@@ -277,6 +277,9 @@ class Metadata:\n for req in self.requires_dist:\n fp.write('Requires-Dist: {}\\n'.format(req))\n \n+ for url in self.project_urls:\n+ fp.write('Project-URL: {}\\n'.format(url))\n+\n if self.description is not None:\n fp.write('\\n' + self.description + '\\n')\n \ndiff --git a/flit/inifile.py b/flit/inifile.py\nindex 3c1b9e0..234683f 100644\n--- a/flit/inifile.py\n+++ b/flit/inifile.py\n@@ -198,6 +198,11 @@ def _prep_metadata(md_sect, path):\n log.warning(stream.getvalue())\n md_dict['description'] = raw_desc\n \n+ if 'urls' in md_sect:\n+ project_urls = md_dict['project_urls'] = []\n+ for label, url in md_sect.pop('urls').items():\n+ project_urls.append(\"{}, {}\".format(label, url))\n+\n for key, value in md_sect.items():\n if key in {'description-file', 'module'}:\n continue\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 0299700..276ef75 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -25,5 +25,8 @@ classifiers=[\"Intended Audience :: Developers\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ]\n \n+[tool.flit.metadata.urls]\n+Documentation = \"https://flit.readthedocs.io/en/latest/\"\n+\n [tool.flit.scripts]\n flit = \"flit:main\"\n", "test_patch": "diff --git a/tests/samples/module1-pkg.toml b/tests/samples/module1-pkg.toml\nindex f7dc8f1..740ec87 100644\n--- a/tests/samples/module1-pkg.toml\n+++ b/tests/samples/module1-pkg.toml\n@@ -7,3 +7,6 @@ author = \"Sir Robin\"\n author-email = \"robin@camelot.uk\"\n home-page = \"http://github.com/sirrobin/module1\"\n description-file = \"EG_README.rst\"\n+\n+[tool.flit.metadata.urls]\n+Documentation = \"https://example.com/module1\"\n", "FAIL_TO_PASS": ["tests/test_build.py::test_build_main", "tests/test_inifile.py::test_load_toml"]}, {"instance_id": "takluyver__flit-169", "base_commit": "08dcf993229894901e33b88ab9b8c0cf19c88415", "gold_patch": "diff --git a/.gitignore b/.gitignore\nindex c2acbe3..d64b220 100644\n--- a/.gitignore\n+++ b/.gitignore\n@@ -6,3 +6,4 @@ __pycache__/\n /tests/samples/dist/\n /htmlcov/\n /.coverage\n+/.pytest_cache\ndiff --git a/.travis.yml b/.travis.yml\nindex 8afc588..b43c127 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -4,6 +4,7 @@ python:\n - \"3.5\"\n - \"3.4\"\n install:\n+ - pip install --upgrade pytest\n - pip install -r requirements-test.txt\n - pip install codecov\n script: py.test --cov=flit\ndiff --git a/doc/history.rst b/doc/history.rst\nindex 4effcd6..a9375e7 100644\n--- a/doc/history.rst\n+++ b/doc/history.rst\n@@ -4,6 +4,10 @@ Release history\n Version 0.14\n ------------\n \n+- The description file may now be written in reStructuredText, Markdown or\n+ plain text. The file extension should indicate which of these formats it is\n+ (``.rst``, ``.md`` or ``.txt``). Previously, only reStructuredText was\n+ officially supported.\n - Multiple links (e.g. documentation, bug tracker) can now be specified in a\n new :ref:`[tool.flit.metadata.urls] section ` of\n ``pyproject.toml``.\ndiff --git a/doc/pyproject_toml.rst b/doc/pyproject_toml.rst\nindex 09dfcf4..8e7a826 100644\n--- a/doc/pyproject_toml.rst\n+++ b/doc/pyproject_toml.rst\n@@ -71,11 +71,11 @@ dev-requires\n These are not (yet) encoded in the wheel, but are used when doing\n ``flit install``.\n description-file\n- A path (relative to the .ini file) to a file containing a longer description\n+ A path (relative to the .toml file) to a file containing a longer description\n of your package to show on PyPI. This should be written in `reStructuredText\n- `_, if your long\n- description is not valid reStructuredText, a warning will be printed,\n- and it will be interpreted as plain text on PyPI.\n+ `_, Markdown or\n+ plain text, and the filename should have the appropriate extension\n+ (``.rst``, ``.md`` or ``.txt``).\n classifiers\n A list of `Trove classifiers `_.\n requires-python\ndiff --git a/flit/common.py b/flit/common.py\nindex ad79813..b73ebc9 100644\n--- a/flit/common.py\n+++ b/flit/common.py\n@@ -212,6 +212,7 @@ class Metadata:\n keywords = None\n download_url = None\n requires_python = None\n+ description_content_type = None\n \n platform = ()\n supported_platform = ()\n@@ -224,8 +225,9 @@ class Metadata:\n requires_dist = ()\n obsoletes_dist = ()\n requires_external = ()\n+ provides_extra = ()\n \n- metadata_version=\"1.2\"\n+ metadata_version=\"2.1\"\n \n # this is part of metadata spec 2, we are using it for installation but it\n # doesn't actually get written to the metadata file\n@@ -244,7 +246,7 @@ class Metadata:\n return n.lower().replace('-', '_')\n \n def write_metadata_file(self, fp):\n- \"\"\"Write out metadata in the 1.x format (email like)\"\"\"\n+ \"\"\"Write out metadata in the email headers format\"\"\"\n fields = [\n 'Metadata-Version',\n 'Name',\n@@ -260,6 +262,7 @@ class Metadata:\n 'Maintainer',\n 'Maintainer-email',\n 'Requires-Python',\n+ 'Description-Content-Type',\n ]\n \n for field in fields:\n@@ -280,6 +283,9 @@ class Metadata:\n for url in self.project_urls:\n fp.write('Project-URL: {}\\n'.format(url))\n \n+ for extra in self.provides_extra:\n+ fp.write('Provides-Extra: {}\\n'.format(extra))\n+\n if self.description is not None:\n fp.write('\\n' + self.description + '\\n')\n \ndiff --git a/flit/inifile.py b/flit/inifile.py\nindex 234683f..2af1ae2 100644\n--- a/flit/inifile.py\n+++ b/flit/inifile.py\n@@ -157,6 +157,12 @@ def _read_pkg_ini(path):\n \n return cp\n \n+readme_ext_to_content_type = {\n+ '.rst': 'text/x-rst',\n+ '.md': 'text/markdown',\n+ '.txt': 'text/plain',\n+}\n+\n def _prep_metadata(md_sect, path):\n \"\"\"Process & verify the metadata from a config file\n \n@@ -180,23 +186,26 @@ def _prep_metadata(md_sect, path):\n description_file = path.parent / md_sect.get('description-file')\n with description_file.open(encoding='utf-8') as f:\n raw_desc = f.read()\n- if description_file.suffix == '.md':\n- try:\n- import pypandoc\n- log.debug('will convert %s to rst', description_file)\n- raw_desc = pypandoc.convert(raw_desc, 'rst', format='markdown')\n- except Exception:\n- log.warning('Unable to convert markdown to rst. Please install '\n- '`pypandoc` and `pandoc` to use markdown long description.')\n-\n- # rst check\n- stream = io.StringIO()\n- res = render(raw_desc, stream)\n- if not res:\n- log.warning(\"The file description seems not to be valid rst for PyPI;\"\n- \" it will be interpreted as plain text\")\n- log.warning(stream.getvalue())\n+ ext = description_file.suffix\n+ try:\n+ mimetype = readme_ext_to_content_type[ext]\n+ except KeyError:\n+ log.warning(\"Unknown extension %r for description file.\", ext)\n+ log.warning(\" Recognised extensions: %s\",\n+ \" \".join(readme_ext_to_content_type))\n+ mimetype = None\n+\n+ if mimetype == 'text/x-rst':\n+ # rst check\n+ stream = io.StringIO()\n+ res = render(raw_desc, stream)\n+ if not res:\n+ log.warning(\"The file description seems not to be valid rst for PyPI;\"\n+ \" it will be interpreted as plain text\")\n+ log.warning(stream.getvalue())\n+\n md_dict['description'] = raw_desc\n+ md_dict['description_content_type'] = mimetype\n \n if 'urls' in md_sect:\n project_urls = md_dict['project_urls'] = []\n", "test_patch": "diff --git a/tests/samples/bad-description-ext.toml b/tests/samples/bad-description-ext.toml\nnew file mode 100644\nindex 0000000..1062829\n--- /dev/null\n+++ b/tests/samples/bad-description-ext.toml\n@@ -0,0 +1,9 @@\n+[build-system]\n+requires = [\"flit\"]\n+\n+[tool.flit.metadata]\n+module = \"module1\"\n+author = \"Sir Robin\"\n+author-email = \"robin@camelot.uk\"\n+home-page = \"http://github.com/sirrobin/module1\"\n+description-file = \"module1.py\" # WRONG\ndiff --git a/tests/test_inifile.py b/tests/test_inifile.py\nindex d506651..c7d3e5f 100644\n--- a/tests/test_inifile.py\n+++ b/tests/test_inifile.py\n@@ -1,3 +1,4 @@\n+import logging\n import pathlib\n \n import pytest\n@@ -48,4 +49,10 @@ def test_description_file():\n info = read_pkg_ini(samples_dir / 'package1-pkg.ini')\n assert info['metadata']['description'] == \\\n \"Sample description for test.\\n\"\n+ assert info['metadata']['description_content_type'] == 'text/x-rst'\n \n+def test_bad_description_extension(caplog):\n+ info = read_pkg_ini(samples_dir / 'bad-description-ext.toml')\n+ assert info['metadata']['description_content_type'] is None\n+ assert any((r.levelno == logging.WARN and \"Unknown extension\" in r.msg)\n+ for r in caplog.records)\n", "FAIL_TO_PASS": ["tests/test_inifile.py::test_description_file", "tests/test_inifile.py::test_bad_description_extension"]}], "all_FAIL_TO_PASS": ["tests/test_build.py::test_build_main", "tests/test_inifile.py::test_load_toml", "tests/test_inifile.py::test_description_file", "tests/test_inifile.py::test_bad_description_extension"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pypa__pipx-1267_x2", "level": 2, "source": "swerebenchv2", "repo": "pypa/pipx", "image": "swerebenchv2/pypa-pipx:1267-6eb7773", "base_commit": "6eb777318996e3ec1b3a9ac5da427feae37cdf76", "num_bugs": 2, "bugs": [{"instance_id": "pypa__pipx-1267", "base_commit": "6eb777318996e3ec1b3a9ac5da427feae37cdf76", "gold_patch": "diff --git a/changelog.d/1262.feature.md b/changelog.d/1262.feature.md\nnew file mode 100644\nindex 0000000..1452b72\n--- /dev/null\n+++ b/changelog.d/1262.feature.md\n@@ -0,0 +1,3 @@\n+Add `--install` option to `pipx upgrade` command.\n+\n+This will install the package given as argument if it is not already installed.\ndiff --git a/src/pipx/commands/upgrade.py b/src/pipx/commands/upgrade.py\nindex 1530a30..5cc23f1 100644\n--- a/src/pipx/commands/upgrade.py\n+++ b/src/pipx/commands/upgrade.py\n@@ -1,8 +1,9 @@\n import logging\n+import os\n from pathlib import Path\n-from typing import List, Sequence\n+from typing import List, Optional, Sequence\n \n-from pipx import constants\n+from pipx import commands, constants\n from pipx.colors import bold, red\n from pipx.commands.common import expose_resources_globally\n from pipx.constants import EXIT_CODE_OK, ExitCode\n@@ -101,15 +102,38 @@ def _upgrade_venv(\n include_injected: bool,\n upgrading_all: bool,\n force: bool,\n+ install: bool = False,\n+ python: Optional[str] = None,\n ) -> int:\n- \"\"\"Returns number of packages with changed versions.\"\"\"\n+ \"\"\"Return number of packages with changed versions.\"\"\"\n if not venv_dir.is_dir():\n- raise PipxError(\n- f\"\"\"\n- Package is not installed. Expected to find {str(venv_dir)}, but it\n- does not exist.\n- \"\"\"\n- )\n+ if install:\n+ commands.install(\n+ venv_dir=None,\n+ venv_args=[],\n+ package_names=None,\n+ package_specs=[str(venv_dir).split(os.path.sep)[-1]],\n+ local_bin_dir=constants.LOCAL_BIN_DIR,\n+ local_man_dir=constants.LOCAL_MAN_DIR,\n+ python=python,\n+ pip_args=pip_args,\n+ verbose=verbose,\n+ force=force,\n+ reinstall=False,\n+ include_dependencies=False,\n+ preinstall_packages=None,\n+ )\n+ return 0\n+ else:\n+ raise PipxError(\n+ f\"\"\"\n+ Package is not installed. Expected to find {str(venv_dir)}, but it\n+ does not exist.\n+ \"\"\"\n+ )\n+\n+ if python and not install:\n+ logger.info(\"Ignoring --python as not combined with --install\")\n \n venv = Venv(venv_dir, verbose=verbose)\n \n@@ -154,13 +178,15 @@ def _upgrade_venv(\n \n def upgrade(\n venv_dir: Path,\n+ python: Optional[str],\n pip_args: List[str],\n verbose: bool,\n *,\n include_injected: bool,\n force: bool,\n+ install: bool,\n ) -> ExitCode:\n- \"\"\"Returns pipx exit code.\"\"\"\n+ \"\"\"Return pipx exit code.\"\"\"\n \n _ = _upgrade_venv(\n venv_dir,\n@@ -169,6 +195,8 @@ def upgrade(\n include_injected=include_injected,\n upgrading_all=False,\n force=force,\n+ install=install,\n+ python=python,\n )\n \n # Any error in upgrade will raise PipxError (e.g. from venv.upgrade_package())\n@@ -194,7 +222,7 @@ def upgrade_all(\n venvs_upgraded += _upgrade_venv(\n venv_dir,\n venv.pipx_metadata.main_package.pip_args,\n- verbose,\n+ verbose=verbose,\n include_injected=include_injected,\n upgrading_all=True,\n force=force,\ndiff --git a/src/pipx/main.py b/src/pipx/main.py\nindex b8a13f9..f3f4859 100644\n--- a/src/pipx/main.py\n+++ b/src/pipx/main.py\n@@ -268,10 +268,12 @@ def run_pipx_command(args: argparse.Namespace, subparsers: Dict[str, argparse.Ar\n elif args.command == \"upgrade\":\n return commands.upgrade(\n venv_dir,\n+ args.python,\n pip_args,\n verbose,\n include_injected=args.include_injected,\n force=args.force,\n+ install=args.install,\n )\n elif args.command == \"upgrade-all\":\n return commands.upgrade_all(\n@@ -497,6 +499,12 @@ def _add_upgrade(subparsers, venv_completer: VenvCompleter, shared_parser: argpa\n help=\"Modify existing virtual environment and files in PIPX_BIN_DIR and PIPX_MAN_DIR\",\n )\n add_pip_venv_args(p)\n+ p.add_argument(\n+ \"--install\",\n+ action=\"store_true\",\n+ help=\"Install package spec if missing\",\n+ )\n+ add_python_options(p)\n \n \n def _add_upgrade_all(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:\n", "test_patch": "diff --git a/tests/test_upgrade.py b/tests/test_upgrade.py\nindex 816b7c4..c89629d 100644\n--- a/tests/test_upgrade.py\n+++ b/tests/test_upgrade.py\n@@ -73,3 +73,9 @@ def test_upgrade_no_include_injected(pipx_temp_env, capsys):\n captured = capsys.readouterr()\n assert \"upgraded package pylint\" in captured.out\n assert \"upgraded package black\" not in captured.out\n+\n+\n+def test_upgrade_install_missing(pipx_temp_env, capsys):\n+ assert not run_pipx_cli([\"upgrade\", \"pycowsay\", \"--install\"])\n+ captured = capsys.readouterr()\n+ assert \"installed package pycowsay\" in captured.out\n", "FAIL_TO_PASS": ["tests/test_upgrade.py::test_upgrade_install_missing"]}, {"instance_id": "pypa__pipx-1284", "base_commit": "f3b4abc1087b63724369fbcf5baa5220fdb60900", "gold_patch": "diff --git a/changelog.d/1283.bugfix.md b/changelog.d/1283.bugfix.md\nnew file mode 100644\nindex 0000000..482f8af\n--- /dev/null\n+++ b/changelog.d/1283.bugfix.md\n@@ -0,0 +1,1 @@\n+Fix crashes due to superfluous `-q ` flags by discarding exceeding values\ndiff --git a/src/pipx/main.py b/src/pipx/main.py\nindex f3f4859..9e43784 100644\n--- a/src/pipx/main.py\n+++ b/src/pipx/main.py\n@@ -758,11 +758,20 @@ def get_command_parser() -> Tuple[argparse.ArgumentParser, Dict[str, argparse.Ar\n default=0,\n help=(\n \"Give less output. May be used multiple times corresponding to the\"\n- \" WARNING, ERROR, and CRITICAL logging levels.\"\n+ \" ERROR and CRITICAL logging levels. The count maxes out at 2.\"\n ),\n )\n \n- shared_parser.add_argument(\"--verbose\", \"-v\", action=\"count\", default=0, help=(\"Give more output.\"))\n+ shared_parser.add_argument(\n+ \"--verbose\",\n+ \"-v\",\n+ action=\"count\",\n+ default=0,\n+ help=(\n+ \"Give more output. May be used multiple times corresponding to the\"\n+ \" INFO, DEBUG and NOTSET logging levels. The count maxes out at 3.\"\n+ ),\n+ )\n \n parser = argparse.ArgumentParser(\n prog=prog_name(),\n@@ -843,8 +852,8 @@ def setup_logging(verbose: int) -> None:\n pipx_str = bold(green(\"pipx >\")) if sys.stdout.isatty() else \"pipx >\"\n pipx.constants.pipx_log_file = setup_log_file()\n \n- # Determine logging level\n- level_number = max(0, logging.WARNING - 10 * verbose)\n+ # Determine logging level, a value between 0 and 50\n+ level_number = min(max(0, logging.WARNING - 10 * verbose), 50)\n \n level = logging.getLevelName(level_number)\n \n", "test_patch": "diff --git a/tests/test_main.py b/tests/test_main.py\nindex 3a8bd53..a8e2a43 100644\n--- a/tests/test_main.py\n+++ b/tests/test_main.py\n@@ -35,3 +35,8 @@ def test_prog_name(monkeypatch, argv, executable, expected):\n monkeypatch.setattr(\"pipx.main.sys.argv\", [argv])\n monkeypatch.setattr(\"pipx.main.sys.executable\", executable)\n assert main.prog_name() == expected\n+\n+\n+def test_limit_verbosity():\n+ assert not run_pipx_cli([\"list\", \"-qqq\"])\n+ assert not run_pipx_cli([\"list\", \"-vvvv\"])\n", "FAIL_TO_PASS": ["tests/test_main.py::test_limit_verbosity"]}], "all_FAIL_TO_PASS": ["tests/test_upgrade.py::test_upgrade_install_missing", "tests/test_main.py::test_limit_verbosity"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pybamm-team__pybamm-1020_x2", "level": 2, "source": "swerebenchv2", "repo": "pybamm-team/PyBaMM", "image": "swerebenchv2/pybamm-team-pybamm:1020-1007c87", "base_commit": "1007c87379a6364384d30db315d4a99bc30a7173", "num_bugs": 2, "bugs": [{"instance_id": "pybamm-team__pybamm-1020", "base_commit": "1007c87379a6364384d30db315d4a99bc30a7173", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 7a68ee6a5..59560dc9d 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -2,6 +2,7 @@\n \n ## Features\n \n+- Allowed `ProcessedVariable` to handle cases where `len(solution.t)=1` ([#1020](https://github.com/pybamm-team/PyBaMM/pull/1020))\n - Added `BackwardIndefiniteIntegral` symbol ([#1014](https://github.com/pybamm-team/PyBaMM/pull/1014))\n - Added `plot` and `plot2D` to enable easy plotting of `pybamm.Array` objects ([#1008](https://github.com/pybamm-team/PyBaMM/pull/1008))\n - Updated effective current collector models and added example notebook ([#1007](https://github.com/pybamm-team/PyBaMM/pull/1007))\n@@ -41,6 +42,7 @@\n \n ## Breaking changes\n \n+- For variables discretised using finite elements the result returned by calling `ProcessedVariable` is now transposed ([#1020](https://github.com/pybamm-team/PyBaMM/pull/1020))\n - Renamed \"surface area density\" to \"surface area to volume ratio\" ([#975](https://github.com/pybamm-team/PyBaMM/pull/975))\n - Replaced \"reaction rate\" with \"exchange-current density\" ([#975](https://github.com/pybamm-team/PyBaMM/pull/975))\n - Changed the implementation of reactions in submodels ([#948](https://github.com/pybamm-team/PyBaMM/pull/948))\ndiff --git a/pybamm/solvers/base_solver.py b/pybamm/solvers/base_solver.py\nindex ad34a98ff..4b4286b4b 100644\n--- a/pybamm/solvers/base_solver.py\n+++ b/pybamm/solvers/base_solver.py\n@@ -616,6 +616,15 @@ class BaseSolver(object):\n timer.format(solution.total_time),\n )\n )\n+\n+ # Raise error if solution only contains one timestep (except for algebraic\n+ # solvers, where we may only expect one time in the solution)\n+ if self.algebraic_solver is False and len(solution.t) == 1:\n+ raise pybamm.SolverError(\n+ \"Solution time vector has length 1. \"\n+ \"Check whether simulation terminated too early.\"\n+ )\n+\n return solution\n \n def step(\ndiff --git a/pybamm/solvers/processed_variable.py b/pybamm/solvers/processed_variable.py\nindex 9133a6e3d..f324b0068 100644\n--- a/pybamm/solvers/processed_variable.py\n+++ b/pybamm/solvers/processed_variable.py\n@@ -7,6 +7,26 @@ import pybamm\n import scipy.interpolate as interp\n \n \n+def make_interp2D_fun(input, interpolant):\n+ \"\"\"\n+ Calls and returns a 2D interpolant of the correct shape depending on the\n+ shape of the input\n+ \"\"\"\n+ first_dim, second_dim, _ = input\n+ if isinstance(first_dim, np.ndarray) and isinstance(second_dim, np.ndarray):\n+ first_dim = first_dim[:, 0, 0]\n+ second_dim = second_dim[:, 0]\n+ return interpolant(second_dim, first_dim)\n+ elif isinstance(first_dim, np.ndarray):\n+ first_dim = first_dim[:, 0]\n+ return interpolant(second_dim, first_dim)[:, 0]\n+ elif isinstance(second_dim, np.ndarray):\n+ second_dim = second_dim[:, 0]\n+ return interpolant(second_dim, first_dim)\n+ else:\n+ return interpolant(second_dim, first_dim)[0]\n+\n+\n class ProcessedVariable(object):\n \"\"\"\n An object that can be evaluated at arbitrary (scalars or vectors) t and x, and\n@@ -55,48 +75,11 @@ class ProcessedVariable(object):\n and \"current collector\" in self.domain\n and isinstance(self.mesh[0], pybamm.ScikitSubMesh2D)\n ):\n- if len(solution.t) == 1:\n- # space only (steady solution)\n- self.initialise_2D_fixed_t_scikit_fem()\n- else:\n- self.initialise_2D_scikit_fem()\n+ self.initialise_2D_scikit_fem()\n \n # check variable shape\n else:\n- if len(solution.t) == 1:\n- # Implementing a workaround for 0D and 1D variables. Processing\n- # variables that are functions of space only needs to be implemented\n- # properly, see #1006\n- if (\n- isinstance(self.base_eval, numbers.Number)\n- or len(self.base_eval.shape) == 0\n- or self.base_eval.shape[0] == 1\n- ):\n- # Scalar value\n- t = self.t_sol\n- u = self.u_sol\n- inputs = {name: inp[0] for name, inp in self.inputs.items()}\n-\n- entries = self.base_variable.evaluate(t, u, inputs=inputs)\n-\n- def fun(t):\n- return entries\n-\n- self._interpolation_function = fun\n- self.entries = entries\n- self.dimensions = 0\n- else:\n- # 1D function of space only\n- n = self.mesh[0].npts\n- base_shape = self.base_eval.shape[0]\n- if base_shape in [n, n + 1]:\n- self.initialise_1D(fixed_t=True)\n- else:\n- raise pybamm.SolverError(\n- \"Solution time vector must have length > 1. Check whether \"\n- \"simulation terminated too early.\"\n- )\n- elif (\n+ if (\n isinstance(self.base_eval, numbers.Number)\n or len(self.base_eval.shape) == 0\n or self.base_eval.shape[0] == 1\n@@ -141,9 +124,21 @@ class ProcessedVariable(object):\n entries[idx] = self.base_variable.evaluate(t, u, inputs=inputs)\n \n # No discretisation provided, or variable has no domain (function of t only)\n- self._interpolation_function = interp.interp1d(\n- self.t_sol, entries, kind=\"linear\", fill_value=np.nan, bounds_error=False\n- )\n+ if len(self.t_sol) == 1:\n+ # Variable is just a scalar value, but we need to create a callable\n+ # function to be consitent with other processed variables\n+ def fun(t):\n+ return entries\n+\n+ self._interpolation_function = fun\n+ else:\n+ self._interpolation_function = interp.interp1d(\n+ self.t_sol,\n+ entries,\n+ kind=\"linear\",\n+ fill_value=np.nan,\n+ bounds_error=False,\n+ )\n \n self.entries = entries\n self.dimensions = 0\n@@ -208,19 +203,22 @@ class ProcessedVariable(object):\n self.internal_boundaries = self.mesh[0].internal_boundaries\n \n # set up interpolation\n- # note that the order of 't' and 'space' is the reverse of what you'd expect\n- # TODO: fix processing when variable is a function of space only\n- if fixed_t:\n- # Hack for 1D space only\n+ if len(self.t_sol) == 1:\n+ # function of space only\n interpolant = interp.interp1d(\n space, entries_for_interp[:, 0], kind=\"linear\", fill_value=np.nan\n )\n \n def interp_fun(t, z):\n- return interpolant(z)[:, np.newaxis]\n+ if isinstance(z, np.ndarray):\n+ return interpolant(z)[:, np.newaxis]\n+ else:\n+ return interpolant(z)\n \n self._interpolation_function = interp_fun\n else:\n+ # function of space and time. Note that the order of 't' and 'space'\n+ # is the reverse of what you'd expect\n self._interpolation_function = interp.interp2d(\n self.t_sol, space, entries_for_interp, kind=\"linear\", fill_value=np.nan\n )\n@@ -297,40 +295,29 @@ class ProcessedVariable(object):\n self.second_dim_pts = second_dim_pts\n \n # set up interpolation\n- self._interpolation_function = interp.RegularGridInterpolator(\n- (first_dim_pts, second_dim_pts, self.t_sol),\n- entries,\n- method=\"linear\",\n- fill_value=np.nan,\n- )\n-\n- def initialise_2D_fixed_t_scikit_fem(self):\n- y_sol = self.mesh[0].edges[\"y\"]\n- len_y = len(y_sol)\n- z_sol = self.mesh[0].edges[\"z\"]\n- len_z = len(z_sol)\n-\n- # Evaluate the base_variable\n- inputs = {name: inp[0] for name, inp in self.inputs.items()}\n+ if len(self.t_sol) == 1:\n+ # function of space only. Note the order of the points is the reverse\n+ # of what you'd expect\n+ interpolant = interp.interp2d(\n+ second_dim_pts,\n+ first_dim_pts,\n+ entries[:, :, 0],\n+ kind=\"linear\",\n+ fill_value=np.nan,\n+ )\n \n- entries = np.reshape(\n- self.base_variable.evaluate(0, self.u_sol, inputs=inputs), [len_y, len_z]\n- )\n+ def interp_fun(input):\n+ return make_interp2D_fun(input, interpolant)\n \n- # assign attributes for reference\n- self.entries = entries\n- self.dimensions = 2\n- self.y_sol = y_sol\n- self.z_sol = z_sol\n- self.first_dimension = \"y\"\n- self.second_dimension = \"z\"\n- self.first_dim_pts = y_sol\n- self.second_dim_pts = z_sol\n-\n- # set up interpolation\n- self._interpolation_function = interp.interp2d(\n- y_sol, z_sol, entries, kind=\"linear\", fill_value=np.nan\n- )\n+ self._interpolation_function = interp_fun\n+ else:\n+ # function of space and time.\n+ self._interpolation_function = interp.RegularGridInterpolator(\n+ (first_dim_pts, second_dim_pts, self.t_sol),\n+ entries,\n+ method=\"linear\",\n+ fill_value=np.nan,\n+ )\n \n def initialise_2D_scikit_fem(self):\n y_sol = self.mesh[0].edges[\"y\"]\n@@ -349,11 +336,15 @@ class ProcessedVariable(object):\n eval_and_known_evals = self.base_variable.evaluate(\n t, u, inputs=inputs, known_evals=self.known_evals[t]\n )\n- entries[:, :, idx] = np.reshape(eval_and_known_evals[0], [len_y, len_z])\n+ entries[:, :, idx] = np.reshape(\n+ eval_and_known_evals[0], [len_y, len_z], order=\"F\"\n+ )\n self.known_evals[t] = eval_and_known_evals[1]\n else:\n entries[:, :, idx] = np.reshape(\n- self.base_variable.evaluate(t, u, inputs=inputs), [len_y, len_z]\n+ self.base_variable.evaluate(t, u, inputs=inputs),\n+ [len_y, len_z],\n+ order=\"F\",\n )\n \n # assign attributes for reference\n@@ -367,23 +358,49 @@ class ProcessedVariable(object):\n self.second_dim_pts = z_sol\n \n # set up interpolation\n- self._interpolation_function = interp.RegularGridInterpolator(\n- (y_sol, z_sol, self.t_sol), entries, method=\"linear\", fill_value=np.nan\n- )\n+ if len(self.t_sol) == 1:\n+ # function of space only. Note the order of the points is the reverse\n+ # of what you'd expect\n+ interpolant = interp.interp2d(\n+ z_sol, y_sol, entries, kind=\"linear\", fill_value=np.nan\n+ )\n+\n+ def interp_fun(input):\n+ return make_interp2D_fun(input, interpolant)\n+\n+ self._interpolation_function = interp_fun\n+ else:\n+ # function of space and time.\n+ self._interpolation_function = interp.RegularGridInterpolator(\n+ (y_sol, z_sol, self.t_sol), entries, method=\"linear\", fill_value=np.nan\n+ )\n \n def __call__(self, t=None, x=None, r=None, y=None, z=None, warn=True):\n \"\"\"\n Evaluate the variable at arbitrary t (and x, r, y and/or z), using interpolation\n \"\"\"\n+ # If t is None and there is only one value of time in the soluton (i.e.\n+ # the solution is independent of time) then we set t equal to the value\n+ # stored in the solution. If the variable is constant (doesn't depend on\n+ # time) evaluate arbitrarily at the first value of t. Otherwise, raise\n+ # an error\n+ if t is None:\n+ if len(self.t_sol) == 1:\n+ t = self.t_sol\n+ elif self.base_variable.is_constant():\n+ t = self.t_sol[0]\n+ else:\n+ raise ValueError(\n+ \"t cannot be None for variable {}\".format(self.base_variable)\n+ )\n+\n+ # Call interpolant of correct spatial dimension\n if self.dimensions == 0:\n out = self._interpolation_function(t)\n elif self.dimensions == 1:\n out = self.call_1D(t, x, r, z)\n elif self.dimensions == 2:\n- if t is None:\n- out = self._interpolation_function(y, z)\n- else:\n- out = self.call_2D(t, x, r, y, z)\n+ out = self.call_2D(t, x, r, y, z)\n if warn is True and np.isnan(out).any():\n pybamm.logger.warning(\n \"Calling variable outside interpolation range (returns 'nan')\"\n", "test_patch": "diff --git a/tests/unit/test_solvers/test_base_solver.py b/tests/unit/test_solvers/test_base_solver.py\nindex 885032e5c..99e9ed3aa 100644\n--- a/tests/unit/test_solvers/test_base_solver.py\n+++ b/tests/unit/test_solvers/test_base_solver.py\n@@ -71,6 +71,17 @@ class TestBaseSolver(unittest.TestCase):\n ):\n solver.solve(model, np.array([1, 2, 3, 2]))\n \n+ def test_solution_time_length_fail(self):\n+ model = pybamm.BaseModel()\n+ v = pybamm.Scalar(1)\n+ model.variables = {\"v\": v}\n+ solver = pybamm.DummySolver()\n+ t_eval = np.array([0])\n+ with self.assertRaisesRegex(\n+ pybamm.SolverError, \"Solution time vector has length 1\"\n+ ):\n+ solver.solve(model, t_eval)\n+\n def test_block_symbolic_inputs(self):\n solver = pybamm.BaseSolver(rtol=1e-2, atol=1e-4)\n model = pybamm.BaseModel()\n@@ -203,13 +214,13 @@ class TestBaseSolver(unittest.TestCase):\n solver.calculate_consistent_state(Model())\n solver = pybamm.BaseSolver(root_method=\"lm\")\n with self.assertRaisesRegex(\n- pybamm.SolverError, \"Could not find acceptable solution: solver terminated\",\n+ pybamm.SolverError, \"Could not find acceptable solution: solver terminated\"\n ):\n solver.calculate_consistent_state(Model())\n # with casadi\n solver = pybamm.BaseSolver(root_method=\"casadi\")\n with self.assertRaisesRegex(\n- pybamm.SolverError, \"Could not find acceptable solution: .../casadi\",\n+ pybamm.SolverError, \"Could not find acceptable solution: .../casadi\"\n ):\n solver.calculate_consistent_state(Model())\n \ndiff --git a/tests/unit/test_solvers/test_processed_variable.py b/tests/unit/test_solvers/test_processed_variable.py\nindex d9e6a1a50..d7c583a26 100644\n--- a/tests/unit/test_solvers/test_processed_variable.py\n+++ b/tests/unit/test_solvers/test_processed_variable.py\n@@ -20,6 +20,14 @@ class TestProcessedVariable(unittest.TestCase):\n processed_var = pybamm.ProcessedVariable(var, pybamm.Solution(t_sol, y_sol))\n np.testing.assert_array_equal(processed_var.entries, t_sol * y_sol[0])\n \n+ # scalar value\n+ var = y\n+ var.mesh = None\n+ t_sol = np.array([0])\n+ y_sol = np.array([1])[:, np.newaxis]\n+ processed_var = pybamm.ProcessedVariable(var, pybamm.Solution(t_sol, y_sol))\n+ np.testing.assert_array_equal(processed_var.entries, y_sol[0])\n+\n def test_processed_variable_1D(self):\n t = pybamm.t\n var = pybamm.Variable(\"var\", domain=[\"negative electrode\", \"separator\"])\n@@ -59,6 +67,18 @@ class TestProcessedVariable(unittest.TestCase):\n x_s_edge.entries[:, 0], processed_x_s_edge.entries[:, 0]\n )\n \n+ # space only\n+ eqn = var + x\n+ eqn_sol = disc.process_symbol(eqn)\n+ t_sol = np.array([0])\n+ y_sol = np.ones_like(x_sol)[:, np.newaxis]\n+ processed_eqn2 = pybamm.ProcessedVariable(\n+ eqn_sol, pybamm.Solution(t_sol, y_sol)\n+ )\n+ np.testing.assert_array_equal(\n+ processed_eqn2.entries, y_sol + x_sol[:, np.newaxis]\n+ )\n+\n def test_processed_variable_1D_unknown_domain(self):\n x = pybamm.SpatialVariable(\"x\", domain=\"SEI layer\", coord_sys=\"cartesian\")\n geometry = pybamm.Geometry()\n@@ -150,6 +170,31 @@ class TestProcessedVariable(unittest.TestCase):\n x_s_edge.entries.flatten(), processed_x_s_edge.entries[:, :, 0].T.flatten()\n )\n \n+ def test_processed_variable_2D_space_only(self):\n+ var = pybamm.Variable(\n+ \"var\",\n+ domain=[\"negative particle\"],\n+ auxiliary_domains={\"secondary\": [\"negative electrode\"]},\n+ )\n+ x = pybamm.SpatialVariable(\"x\", domain=[\"negative electrode\"])\n+ r = pybamm.SpatialVariable(\"r\", domain=[\"negative particle\"])\n+\n+ disc = tests.get_p2d_discretisation_for_testing()\n+ disc.set_variable_slices([var])\n+ x_sol = disc.process_symbol(x).entries[:, 0]\n+ r_sol = disc.process_symbol(r).entries[:, 0]\n+ # Keep only the first iteration of entries\n+ r_sol = r_sol[: len(r_sol) // len(x_sol)]\n+ var_sol = disc.process_symbol(var)\n+ t_sol = np.array([0])\n+ y_sol = np.ones(len(x_sol) * len(r_sol))[:, np.newaxis]\n+\n+ processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, y_sol))\n+ np.testing.assert_array_equal(\n+ processed_var.entries,\n+ np.reshape(y_sol, [len(r_sol), len(x_sol), len(t_sol)]),\n+ )\n+\n def test_processed_variable_2D_scikit(self):\n var = pybamm.Variable(\"var\", domain=[\"current collector\"])\n \n@@ -181,7 +226,7 @@ class TestProcessedVariable(unittest.TestCase):\n \n processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, u_sol))\n np.testing.assert_array_equal(\n- processed_var.entries, np.reshape(u_sol, [len(y), len(z)])\n+ processed_var.entries, np.reshape(u_sol, [len(y), len(z), len(t_sol)])\n )\n \n def test_processed_var_0D_interpolation(self):\n@@ -211,6 +256,19 @@ class TestProcessedVariable(unittest.TestCase):\n np.testing.assert_array_equal(processed_eqn(2), np.nan)\n pybamm.set_logging_level(\"WARNING\")\n \n+ def test_processed_var_0D_fixed_t_interpolation(self):\n+ y = pybamm.StateVector(slice(0, 1))\n+ var = y\n+ eqn = 2 * y\n+ var.mesh = None\n+ eqn.mesh = None\n+\n+ t_sol = np.array([10])\n+ y_sol = np.array([[100]])\n+ processed_var = pybamm.ProcessedVariable(eqn, pybamm.Solution(t_sol, y_sol))\n+\n+ np.testing.assert_array_equal(processed_var(), 200)\n+\n def test_processed_var_1D_interpolation(self):\n t = pybamm.t\n var = pybamm.Variable(\"var\", domain=[\"negative electrode\", \"separator\"])\n@@ -250,6 +308,12 @@ class TestProcessedVariable(unittest.TestCase):\n # 2 scalars\n self.assertEqual(processed_eqn(0.5, x_sol[-1]).shape, (1,))\n \n+ # test x\n+ processed_x = pybamm.ProcessedVariable(\n+ disc.process_symbol(x), pybamm.Solution(t_sol, y_sol)\n+ )\n+ np.testing.assert_array_almost_equal(processed_x(x=x_sol), x_sol[:, np.newaxis])\n+\n # On microscale\n r_n = pybamm.Matrix(\n disc.mesh[\"negative particle\"][0].nodes, domain=\"negative particle\"\n@@ -261,6 +325,27 @@ class TestProcessedVariable(unittest.TestCase):\n processed_r_n(0, r=np.linspace(0, 1))[:, 0], np.linspace(0, 1)\n )\n \n+ def test_processed_var_1D_fixed_t_interpolation(self):\n+ var = pybamm.Variable(\"var\", domain=[\"negative electrode\", \"separator\"])\n+ x = pybamm.SpatialVariable(\"x\", domain=[\"negative electrode\", \"separator\"])\n+ eqn = var + x\n+\n+ disc = tests.get_discretisation_for_testing()\n+ disc.set_variable_slices([var])\n+ x_sol = disc.process_symbol(x).entries[:, 0]\n+ eqn_sol = disc.process_symbol(eqn)\n+ t_sol = np.array([1])\n+ y_sol = x_sol[:, np.newaxis]\n+\n+ processed_var = pybamm.ProcessedVariable(eqn_sol, pybamm.Solution(t_sol, y_sol))\n+\n+ # vector\n+ np.testing.assert_array_almost_equal(\n+ processed_var(x=x_sol), 2 * x_sol[:, np.newaxis]\n+ )\n+ # scalar\n+ np.testing.assert_array_almost_equal(processed_var(x=0.5), 1)\n+\n def test_processed_var_2D_interpolation(self):\n var = pybamm.Variable(\n \"var\",\n@@ -324,6 +409,34 @@ class TestProcessedVariable(unittest.TestCase):\n processed_var(t_sol, x_sol, r_sol).shape, (10, 35, 50)\n )\n \n+ def test_processed_var_2D_fixed_t_interpolation(self):\n+ var = pybamm.Variable(\n+ \"var\",\n+ domain=[\"negative particle\"],\n+ auxiliary_domains={\"secondary\": [\"negative electrode\"]},\n+ )\n+ x = pybamm.SpatialVariable(\"x\", domain=[\"negative electrode\"])\n+ r = pybamm.SpatialVariable(\"r\", domain=[\"negative particle\"])\n+\n+ disc = tests.get_p2d_discretisation_for_testing()\n+ disc.set_variable_slices([var])\n+ x_sol = disc.process_symbol(x).entries[:, 0]\n+ r_sol = disc.process_symbol(r).entries[:, 0]\n+ # Keep only the first iteration of entries\n+ r_sol = r_sol[: len(r_sol) // len(x_sol)]\n+ var_sol = disc.process_symbol(var)\n+ t_sol = np.array([0])\n+ y_sol = np.ones(len(x_sol) * len(r_sol))[:, np.newaxis]\n+\n+ processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, y_sol))\n+ # 2 vectors\n+ np.testing.assert_array_equal(processed_var(x=x_sol, r=r_sol).shape, (10, 40))\n+ # 1 vector, 1 scalar\n+ np.testing.assert_array_equal(processed_var(x=0.2, r=r_sol).shape, (10,))\n+ np.testing.assert_array_equal(processed_var(x=x_sol, r=0.5).shape, (40,))\n+ # 2 scalars\n+ np.testing.assert_array_equal(processed_var(x=0.2, r=0.2).shape, ())\n+\n def test_processed_var_2D_secondary_broadcast(self):\n var = pybamm.Variable(\"var\", domain=[\"negative particle\"])\n broad_var = pybamm.SecondaryBroadcast(var, \"negative electrode\")\n@@ -429,18 +542,12 @@ class TestProcessedVariable(unittest.TestCase):\n \n processed_var = pybamm.ProcessedVariable(var_sol, pybamm.Solution(t_sol, u_sol))\n # 2 vectors\n- np.testing.assert_array_equal(\n- processed_var(t=None, y=y_sol, z=z_sol).shape, (15, 15)\n- )\n+ np.testing.assert_array_equal(processed_var(y=y_sol, z=z_sol).shape, (15, 15))\n # 1 vector, 1 scalar\n- np.testing.assert_array_equal(\n- processed_var(t=None, y=0.2, z=z_sol).shape, (15, 1)\n- )\n- np.testing.assert_array_equal(\n- processed_var(t=None, y=y_sol, z=0.5).shape, (15,)\n- )\n+ np.testing.assert_array_equal(processed_var(y=0.2, z=z_sol).shape, (15,))\n+ np.testing.assert_array_equal(processed_var(y=y_sol, z=0.5).shape, (15,))\n # 2 scalars\n- np.testing.assert_array_equal(processed_var(t=None, y=0.2, z=0.2).shape, (1,))\n+ np.testing.assert_array_equal(processed_var(t=None, y=0.2, z=0.2).shape, ())\n \n def test_processed_variable_ode_pde_solution(self):\n # without space\n@@ -518,18 +625,9 @@ class TestProcessedVariable(unittest.TestCase):\n with self.assertRaisesRegex(ValueError, \"r cannot be None\"):\n processed_var(0, 1)\n \n- def test_solution_too_short(self):\n- t = pybamm.t\n- y = pybamm.StateVector(slice(0, 3))\n- var = t * y\n- disc = tests.get_2p1d_discretisation_for_testing()\n- var.mesh = disc.mesh[\"current collector\"]\n- t_sol = np.array([1])\n- y_sol = np.linspace(0, 5)[:, np.newaxis]\n- with self.assertRaisesRegex(\n- pybamm.SolverError, \"Solution time vector must have length > 1\"\n- ):\n- pybamm.ProcessedVariable(var, pybamm.Solution(t_sol, y_sol))\n+ # t is None but len(solution.t) > 1\n+ with self.assertRaisesRegex(ValueError, \"t cannot be None\"):\n+ processed_var()\n \n def test_3D_raises_error(self):\n var = pybamm.Variable(\n", "FAIL_TO_PASS": ["tests/unit/test_solvers/test_base_solver.py::TestBaseSolver::test_solution_time_length_fail", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_var_1D_fixed_t_interpolation", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_variable_0D"]}, {"instance_id": "pybamm-team__pybamm-1025", "base_commit": "1007c87379a6364384d30db315d4a99bc30a7173", "gold_patch": "diff --git a/pybamm/simulation.py b/pybamm/simulation.py\nindex e32421b18..003b03895 100644\n--- a/pybamm/simulation.py\n+++ b/pybamm/simulation.py\n@@ -298,13 +298,16 @@ class Simulation:\n \n if self.built_model:\n return None\n-\n- self.set_parameters()\n- self._mesh = pybamm.Mesh(self._geometry, self._submesh_types, self._var_pts)\n- self._disc = pybamm.Discretisation(self._mesh, self._spatial_methods)\n- self._built_model = self._disc.process_model(\n- self._model_with_set_params, inplace=False, check_model=check_model\n- )\n+ elif self.model.is_discretised:\n+ self._model_with_set_params = self.model\n+ self._built_model = self.model\n+ else:\n+ self.set_parameters()\n+ self._mesh = pybamm.Mesh(self._geometry, self._submesh_types, self._var_pts)\n+ self._disc = pybamm.Discretisation(self._mesh, self._spatial_methods)\n+ self._built_model = self._disc.process_model(\n+ self._model_with_set_params, inplace=False, check_model=check_model\n+ )\n \n def solve(\n self,\n", "test_patch": "diff --git a/tests/unit/test_simulation.py b/tests/unit/test_simulation.py\nindex 8a59951fd..7cb8fc40a 100644\n--- a/tests/unit/test_simulation.py\n+++ b/tests/unit/test_simulation.py\n@@ -103,6 +103,27 @@ class TestSimulation(unittest.TestCase):\n sim.solution[\"v\"].entries, np.exp(-np.linspace(0, 1, 100))\n )\n \n+ def test_solve_already_partially_processed_model(self):\n+\n+ model = pybamm.lithium_ion.SPM()\n+\n+ # Process model manually\n+ geometry = model.default_geometry\n+ param = model.default_parameter_values\n+ param.process_model(model)\n+ param.process_geometry(geometry)\n+ # Let simulation take over\n+ sim = pybamm.Simulation(model)\n+ sim.solve()\n+\n+ # Discretised manually\n+ mesh = pybamm.Mesh(geometry, model.default_submesh_types, model.default_var_pts)\n+ disc = pybamm.Discretisation(mesh, model.default_spatial_methods)\n+ disc.process_model(model)\n+ # Let simulation take over\n+ sim = pybamm.Simulation(model)\n+ sim.solve()\n+\n def test_reuse_commands(self):\n \n sim = pybamm.Simulation(pybamm.lithium_ion.SPM())\n", "FAIL_TO_PASS": ["tests/unit/test_simulation.py::TestSimulation::test_solve_already_partially_processed_model"]}], "all_FAIL_TO_PASS": ["tests/unit/test_solvers/test_base_solver.py::TestBaseSolver::test_solution_time_length_fail", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_var_1D_fixed_t_interpolation", "tests/unit/test_solvers/test_processed_variable.py::TestProcessedVariable::test_processed_variable_0D", "tests/unit/test_simulation.py::TestSimulation::test_solve_already_partially_processed_model"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "modin-project__modin-6751_x2", "level": 2, "source": "swerebenchv2", "repo": "modin-project/modin", "image": "swerebenchv2/modin-project-modin:6751-adfd2bb", "base_commit": "adfd2bb3b1347a618039e28ae3504a7d808b792f", "num_bugs": 2, "bugs": [{"instance_id": "modin-project__modin-6751", "base_commit": "adfd2bb3b1347a618039e28ae3504a7d808b792f", "gold_patch": "diff --git a/modin/core/dataframe/pandas/dataframe/dataframe.py b/modin/core/dataframe/pandas/dataframe/dataframe.py\nindex 7031b269..b9a57271 100644\n--- a/modin/core/dataframe/pandas/dataframe/dataframe.py\n+++ b/modin/core/dataframe/pandas/dataframe/dataframe.py\n@@ -1323,11 +1323,13 @@ class PandasDataframe(ClassLogger):\n if \"index\" not in self.columns\n else \"level_{}\".format(0)\n ]\n- new_dtypes = None\n- if self.has_materialized_dtypes:\n- names = tuple(level_names) if len(level_names) > 1 else level_names[0]\n- new_dtypes = self.index.to_frame(name=names).dtypes\n- new_dtypes = pandas.concat([new_dtypes, self.dtypes])\n+ names = tuple(level_names) if len(level_names) > 1 else level_names[0]\n+ new_dtypes = self.index.to_frame(name=names).dtypes\n+ try:\n+ new_dtypes = ModinDtypes.concat([new_dtypes, self._dtypes])\n+ except NotImplementedError:\n+ # can raise on duplicated labels\n+ new_dtypes = None\n \n # We will also use the `new_column_names` in the calculation of the internal metadata, so this is a\n # lightweight way of ensuring the metadata matches.\n@@ -2587,7 +2589,7 @@ class PandasDataframe(ClassLogger):\n return df\n \n # If this df is empty, we don't want to try and shuffle or sort.\n- if len(self.get_axis(0)) == 0 or len(self.get_axis(1)) == 0:\n+ if len(self.get_axis(1)) == 0 or len(self) == 0:\n return self.copy()\n \n axis = Axis(axis)\ndiff --git a/modin/core/dataframe/pandas/metadata/dtypes.py b/modin/core/dataframe/pandas/metadata/dtypes.py\nindex fc6cc211..ffd81eb7 100644\n--- a/modin/core/dataframe/pandas/metadata/dtypes.py\n+++ b/modin/core/dataframe/pandas/metadata/dtypes.py\n@@ -260,13 +260,15 @@ class DtypesDescriptor:\n DtypesDescriptor\n \"\"\"\n return type(self)(\n- self._known_dtypes.copy(),\n- self._cols_with_unknown_dtypes.copy(),\n- self._remaining_dtype,\n- self._parent_df,\n- columns_order=None\n- if self.columns_order is None\n- else self.columns_order.copy(),\n+ # should access '.columns_order' first, as it may compute columns order\n+ # and complete the metadata for 'self'\n+ columns_order=(\n+ None if self.columns_order is None else self.columns_order.copy()\n+ ),\n+ known_dtypes=self._known_dtypes.copy(),\n+ cols_with_unknown_dtypes=self._cols_with_unknown_dtypes.copy(),\n+ remaining_dtype=self._remaining_dtype,\n+ parent_df=self._parent_df,\n know_all_names=self._know_all_names,\n _schema_is_known=self._schema_is_known,\n )\n@@ -646,7 +648,16 @@ class ModinDtypes:\n else:\n raise NotImplementedError(type(val))\n \n- desc = DtypesDescriptor.concat(preprocessed_vals)\n+ try:\n+ desc = DtypesDescriptor.concat(preprocessed_vals)\n+ except NotImplementedError as e:\n+ # 'DtypesDescriptor' doesn't support duplicated labels, however, if all values are pandas Serieses,\n+ # we still can perform concatenation using pure pandas\n+ if \"duplicated\" not in e.args[0].lower() or not all(\n+ isinstance(val, pandas.Series) for val in values\n+ ):\n+ raise e\n+ desc = pandas.concat(values)\n return ModinDtypes(desc)\n \n def set_index(self, new_index: Union[pandas.Index, \"ModinIndex\"]) -> \"ModinDtypes\":\ndiff --git a/modin/core/storage_formats/pandas/query_compiler.py b/modin/core/storage_formats/pandas/query_compiler.py\nindex ba907a8b..0565a7d1 100644\n--- a/modin/core/storage_formats/pandas/query_compiler.py\n+++ b/modin/core/storage_formats/pandas/query_compiler.py\n@@ -58,6 +58,7 @@ from modin.core.dataframe.algebra.default2pandas.groupby import (\n SeriesGroupByDefault,\n )\n from modin.core.dataframe.base.dataframe.utils import join_columns\n+from modin.core.dataframe.pandas.metadata import ModinDtypes\n from modin.core.storage_formats.base.query_compiler import BaseQueryCompiler\n from modin.error_message import ErrorMessage\n from modin.utils import (\n@@ -719,10 +720,20 @@ class PandasQueryCompiler(BaseQueryCompiler):\n df.index = pandas.RangeIndex(start, stop)\n return df\n \n- if self._modin_frame.has_columns_cache and kwargs[\"drop\"]:\n- new_columns = self._modin_frame.copy_columns_cache(copy_lengths=True)\n+ new_columns = None\n+ if kwargs[\"drop\"]:\n+ dtypes = self._modin_frame.copy_dtypes_cache()\n+ if self._modin_frame.has_columns_cache:\n+ new_columns = self._modin_frame.copy_columns_cache(\n+ copy_lengths=True\n+ )\n else:\n- new_columns = None\n+ # concat index dtypes (None, since they're unknown) with column dtypes\n+ try:\n+ dtypes = ModinDtypes.concat([None, self._modin_frame._dtypes])\n+ except NotImplementedError:\n+ # may raise on duplicated names in materialized 'self.dtypes'\n+ dtypes = None\n \n return self.__constructor__(\n self._modin_frame.apply_full_axis(\n@@ -730,9 +741,7 @@ class PandasQueryCompiler(BaseQueryCompiler):\n func=_reset,\n enumerate_partitions=True,\n new_columns=new_columns,\n- dtypes=(\n- self._modin_frame._dtypes if kwargs.get(\"drop\", False) else None\n- ),\n+ dtypes=dtypes,\n sync_labels=False,\n pass_axis_lengths_to_partitions=True,\n )\n", "test_patch": "diff --git a/modin/test/storage_formats/pandas/test_internals.py b/modin/test/storage_formats/pandas/test_internals.py\nindex b459f050..5279614b 100644\n--- a/modin/test/storage_formats/pandas/test_internals.py\n+++ b/modin/test/storage_formats/pandas/test_internals.py\n@@ -21,6 +21,7 @@ import pytest\n \n import modin.pandas as pd\n from modin.config import Engine, ExperimentalGroupbyImpl, MinPartitionSize, NPartitions\n+from modin.core.dataframe.pandas.dataframe.dataframe import PandasDataframe\n from modin.core.dataframe.pandas.dataframe.utils import ColumnInfo, ShuffleSortFunctions\n from modin.core.dataframe.pandas.metadata import (\n DtypesDescriptor,\n@@ -1814,6 +1815,24 @@ class TestModinDtypes:\n )\n assert res.equals(exp)\n \n+ def test_ModinDtypes_duplicated_concat(self):\n+ # test that 'ModinDtypes' is able to perform dtypes concatenation on duplicated labels\n+ # if all of them are Serieses\n+ res = ModinDtypes.concat([pandas.Series([np.dtype(int)], index=[\"a\"])] * 2)\n+ assert isinstance(res._value, pandas.Series)\n+ assert res._value.equals(\n+ pandas.Series([np.dtype(int), np.dtype(int)], index=[\"a\", \"a\"])\n+ )\n+\n+ # test that 'ModinDtypes.concat' with duplicated labels raises when not all dtypes are materialized\n+ with pytest.raises(NotImplementedError):\n+ res = ModinDtypes.concat(\n+ [\n+ pandas.Series([np.dtype(int)], index=[\"a\"]),\n+ DtypesDescriptor(cols_with_unknown_dtypes=[\"a\"]),\n+ ]\n+ )\n+\n def test_update_parent(self):\n \"\"\"\n Test that updating parents in ``DtypesDescriptor`` also propagates to stored lazy categoricals.\n@@ -1947,8 +1966,6 @@ class TestZeroComputationDtypes:\n \"\"\"\n \n def test_get_dummies_case(self):\n- from modin.core.dataframe.pandas.dataframe.dataframe import PandasDataframe\n-\n with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n df = pd.DataFrame(\n {\"items\": [1, 2, 3, 4], \"b\": [3, 3, 4, 4], \"c\": [1, 0, 0, 1]}\n@@ -1960,3 +1977,91 @@ class TestZeroComputationDtypes:\n assert res._query_compiler._modin_frame.has_materialized_dtypes\n \n patch.assert_not_called()\n+\n+ @pytest.mark.parametrize(\"has_materialized_index\", [True, False])\n+ @pytest.mark.parametrize(\"drop\", [True, False])\n+ def test_preserve_dtypes_reset_index(self, drop, has_materialized_index):\n+ with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n+ # case 1: 'df' has complete dtype by default\n+ df = pd.DataFrame({\"a\": [1, 2, 3]})\n+ if has_materialized_index:\n+ assert df._query_compiler._modin_frame.has_materialized_index\n+ else:\n+ df._query_compiler._modin_frame.set_index_cache(None)\n+ assert not df._query_compiler._modin_frame.has_materialized_index\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+\n+ res = df.reset_index(drop=drop)\n+ if drop:\n+ # we droped the index, so columns and dtypes shouldn't change\n+ assert res._query_compiler._modin_frame.has_materialized_dtypes\n+ assert res.dtypes.equals(df.dtypes)\n+ else:\n+ if has_materialized_index:\n+ # we should have inserted index dtype into the descriptor,\n+ # and since both of them are materialized, the result should be\n+ # materialized too\n+ assert res._query_compiler._modin_frame.has_materialized_dtypes\n+ assert res.dtypes.equals(\n+ pandas.Series(\n+ [np.dtype(int), np.dtype(int)], index=[\"index\", \"a\"]\n+ )\n+ )\n+ else:\n+ # we now know that there are cols with unknown name and dtype in our dataframe,\n+ # so the resulting dtypes should contain information only about original column\n+ expected_dtypes = DtypesDescriptor(\n+ {\"a\": np.dtype(int)},\n+ know_all_names=False,\n+ )\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ expected_dtypes\n+ )\n+\n+ # case 2: 'df' has partial dtype by default\n+ df = pd.DataFrame({\"a\": [1, 2, 3], \"b\": [3, 4, 5]})\n+ df._query_compiler._modin_frame.set_dtypes_cache(\n+ ModinDtypes(\n+ DtypesDescriptor(\n+ {\"a\": np.dtype(int)}, cols_with_unknown_dtypes=[\"b\"]\n+ )\n+ )\n+ )\n+ if has_materialized_index:\n+ assert df._query_compiler._modin_frame.has_materialized_index\n+ else:\n+ df._query_compiler._modin_frame.set_index_cache(None)\n+ assert not df._query_compiler._modin_frame.has_materialized_index\n+\n+ res = df.reset_index(drop=drop)\n+ if drop:\n+ # we droped the index, so columns and dtypes shouldn't change\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ df._query_compiler._modin_frame._dtypes._value\n+ )\n+ else:\n+ if has_materialized_index:\n+ # we should have inserted index dtype into the descriptor,\n+ # the resulted dtype should have information about 'index' and 'a' columns,\n+ # and miss dtype info for 'b' column\n+ expected_dtypes = DtypesDescriptor(\n+ {\"index\": np.dtype(int), \"a\": np.dtype(int)},\n+ cols_with_unknown_dtypes=[\"b\"],\n+ columns_order={0: \"index\", 1: \"a\", 2: \"b\"},\n+ )\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ expected_dtypes\n+ )\n+ else:\n+ # we miss info about the 'index' column since it wasn't materialized at\n+ # the time of 'reset_index()' and we're still missing dtype info for 'b' column\n+ expected_dtypes = DtypesDescriptor(\n+ {\"a\": np.dtype(int)},\n+ cols_with_unknown_dtypes=[\"b\"],\n+ know_all_names=False,\n+ )\n+ assert res._query_compiler._modin_frame._dtypes._value.equals(\n+ expected_dtypes\n+ )\n+\n+ patch.assert_not_called()\n", "FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestModinDtypes::test_ModinDtypes_duplicated_concat", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-True]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-False]"]}, {"instance_id": "modin-project__modin-6757", "base_commit": "0ba2a46218ecbc6f4b7d0d9e54c25e437e5e0b23", "gold_patch": "diff --git a/modin/core/dataframe/pandas/dataframe/dataframe.py b/modin/core/dataframe/pandas/dataframe/dataframe.py\nindex b9a57271..88c97843 100644\n--- a/modin/core/dataframe/pandas/dataframe/dataframe.py\n+++ b/modin/core/dataframe/pandas/dataframe/dataframe.py\n@@ -2804,6 +2804,7 @@ class PandasDataframe(ClassLogger):\n new_index=None,\n new_columns=None,\n keep_remaining=False,\n+ new_dtypes=None,\n ):\n \"\"\"\n Apply a function across an entire axis for a subset of the data.\n@@ -2826,6 +2827,10 @@ class PandasDataframe(ClassLogger):\n advance, and if not provided it must be computed.\n keep_remaining : boolean, default: False\n Whether or not to drop the data that is not computed over.\n+ new_dtypes : ModinDtypes or pandas.Series, optional\n+ The data types of the result. This is an optimization\n+ because there are functions that always result in a particular data\n+ type, and allows us to avoid (re)computing it.\n \n Returns\n -------\n@@ -2854,7 +2859,9 @@ class PandasDataframe(ClassLogger):\n new_index = self.index if axis == 1 else None\n if new_columns is None:\n new_columns = self.columns if axis == 0 else None\n- return self.__constructor__(new_partitions, new_index, new_columns, None, None)\n+ return self.__constructor__(\n+ new_partitions, new_index, new_columns, None, None, dtypes=new_dtypes\n+ )\n \n @lazy_metadata_decorator(apply_axis=\"both\")\n def apply_select_indices(\ndiff --git a/modin/core/storage_formats/pandas/query_compiler.py b/modin/core/storage_formats/pandas/query_compiler.py\nindex 0565a7d1..a6b9fd1a 100644\n--- a/modin/core/storage_formats/pandas/query_compiler.py\n+++ b/modin/core/storage_formats/pandas/query_compiler.py\n@@ -58,7 +58,7 @@ from modin.core.dataframe.algebra.default2pandas.groupby import (\n SeriesGroupByDefault,\n )\n from modin.core.dataframe.base.dataframe.utils import join_columns\n-from modin.core.dataframe.pandas.metadata import ModinDtypes\n+from modin.core.dataframe.pandas.metadata import DtypesDescriptor, ModinDtypes\n from modin.core.storage_formats.base.query_compiler import BaseQueryCompiler\n from modin.error_message import ErrorMessage\n from modin.utils import (\n@@ -3112,6 +3112,23 @@ class PandasQueryCompiler(BaseQueryCompiler):\n df.insert(internal_idx, column, value)\n return df\n \n+ if hasattr(value, \"dtype\"):\n+ value_dtype = value.dtype\n+ elif is_scalar(value):\n+ value_dtype = np.dtype(type(value))\n+ else:\n+ value_dtype = np.array(value).dtype\n+\n+ new_columns = self.columns.insert(loc, column)\n+ new_dtypes = ModinDtypes.concat(\n+ [\n+ self._modin_frame._dtypes,\n+ DtypesDescriptor({column: value_dtype}, cols_with_unknown_dtypes=[]),\n+ ]\n+ ).lazy_get(\n+ new_columns\n+ ) # get dtypes in a proper order\n+\n # TODO: rework by passing list-like values to `apply_select_indices`\n # as an item to distribute\n new_modin_frame = self._modin_frame.apply_full_axis_select_indices(\n@@ -3120,7 +3137,8 @@ class PandasQueryCompiler(BaseQueryCompiler):\n numeric_indices=[loc],\n keep_remaining=True,\n new_index=self.index,\n- new_columns=self.columns.insert(loc, column),\n+ new_columns=new_columns,\n+ new_dtypes=new_dtypes,\n )\n return self.__constructor__(new_modin_frame)\n \n", "test_patch": "diff --git a/modin/test/storage_formats/pandas/test_internals.py b/modin/test/storage_formats/pandas/test_internals.py\nindex 5279614b..243a496c 100644\n--- a/modin/test/storage_formats/pandas/test_internals.py\n+++ b/modin/test/storage_formats/pandas/test_internals.py\n@@ -1965,6 +1965,61 @@ class TestZeroComputationDtypes:\n Test cases that shouldn't trigger dtypes computation during their execution.\n \"\"\"\n \n+ @pytest.mark.parametrize(\"self_dtype\", [\"materialized\", \"partial\", \"unknown\"])\n+ @pytest.mark.parametrize(\n+ \"value, value_dtype\",\n+ [\n+ [3.5, np.dtype(float)],\n+ [[3.5, 2.4], np.dtype(float)],\n+ [np.array([3.5, 2.4]), np.dtype(float)],\n+ [pd.Series([3.5, 2.4]), np.dtype(float)],\n+ ],\n+ )\n+ def test_preserve_dtypes_insert(self, self_dtype, value, value_dtype):\n+ with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n+ df = pd.DataFrame({\"a\": [1, 2], \"b\": [3, 4]})\n+ if self_dtype == \"materialized\":\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+ elif self_dtype == \"partial\":\n+ df._query_compiler._modin_frame.set_dtypes_cache(\n+ ModinDtypes(\n+ DtypesDescriptor(\n+ {\"a\": np.dtype(int)}, cols_with_unknown_dtypes=[\"b\"]\n+ )\n+ )\n+ )\n+ elif self_dtype == \"unknown\":\n+ df._query_compiler._modin_frame.set_dtypes_cache(None)\n+ else:\n+ raise NotImplementedError(self_dtype)\n+\n+ df.insert(loc=0, column=\"c\", value=value)\n+\n+ if self_dtype == \"materialized\":\n+ result_dtype = pandas.Series(\n+ [value_dtype, np.dtype(int), np.dtype(int)], index=[\"c\", \"a\", \"b\"]\n+ )\n+ assert df._query_compiler._modin_frame.has_materialized_dtypes\n+ assert df.dtypes.equals(result_dtype)\n+ elif self_dtype == \"partial\":\n+ result_dtype = DtypesDescriptor(\n+ {\"a\": np.dtype(int), \"c\": value_dtype},\n+ cols_with_unknown_dtypes=[\"b\"],\n+ columns_order={0: \"c\", 1: \"a\", 2: \"b\"},\n+ )\n+ df._query_compiler._modin_frame._dtypes._value.equals(result_dtype)\n+ elif self_dtype == \"unknown\":\n+ result_dtype = DtypesDescriptor(\n+ {\"c\": value_dtype},\n+ cols_with_unknown_dtypes=[\"a\", \"b\"],\n+ columns_order={0: \"c\", 1: \"a\", 2: \"b\"},\n+ )\n+ df._query_compiler._modin_frame._dtypes._value.equals(result_dtype)\n+ else:\n+ raise NotImplementedError(self_dtype)\n+\n+ patch.assert_not_called()\n+\n def test_get_dummies_case(self):\n with mock.patch.object(PandasDataframe, \"_compute_dtypes\") as patch:\n df = pd.DataFrame(\n", "FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_insert[3.5-value_dtype0-materialized]"]}], "all_FAIL_TO_PASS": ["modin/test/storage_formats/pandas/test_internals.py::TestModinDtypes::test_ModinDtypes_duplicated_concat", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-True]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_reset_index[False-False]", "modin/test/storage_formats/pandas/test_internals.py::TestZeroComputationDtypes::test_preserve_dtypes_insert[3.5-value_dtype0-materialized]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "oceanparcels__parcels-476_x2", "level": 2, "source": "swerebenchv2", "repo": "OceanParcels/parcels", "image": "swerebenchv2/oceanparcels-parcels:476-fea6b8e", "base_commit": "fea6b8e3b2f61317ee5d8bde00c9112ac7e9ea20", "num_bugs": 2, "bugs": [{"instance_id": "oceanparcels__parcels-476", "base_commit": "fea6b8e3b2f61317ee5d8bde00c9112ac7e9ea20", "gold_patch": "diff --git a/environment_py2_linux.yml b/environment_py2_linux.yml\nindex c51502b1..a0882889 100644\n--- a/environment_py2_linux.yml\n+++ b/environment_py2_linux.yml\n@@ -23,6 +23,7 @@ dependencies:\n - scipy>=0.16.0\n - six >=1.10.0\n - xarray>=0.10.8\n+ - dask\n - cftime\n - pip:\n - pytest>=2.7.0\ndiff --git a/environment_py2_osx.yml b/environment_py2_osx.yml\nindex 8a0a25b3..84a57995 100644\n--- a/environment_py2_osx.yml\n+++ b/environment_py2_osx.yml\n@@ -23,6 +23,7 @@ dependencies:\n - scipy>=0.16.0\n - six>=1.10.0\n - xarray>=0.10.8\n+ - dask\n - cftime\n - pip:\n - pytest>=2.7.0\ndiff --git a/environment_py3_linux.yml b/environment_py3_linux.yml\nindex ac9a13c5..eecb2c43 100644\n--- a/environment_py3_linux.yml\n+++ b/environment_py3_linux.yml\n@@ -23,6 +23,7 @@ dependencies:\n - six >=1.10.0\n - xarray>=0.10.8\n - cftime\n+ - dask\n - pip:\n - pytest>=2.7.0\n - nbval\ndiff --git a/environment_py3_osx.yml b/environment_py3_osx.yml\nindex 41760b19..393488f1 100644\n--- a/environment_py3_osx.yml\n+++ b/environment_py3_osx.yml\n@@ -22,6 +22,7 @@ dependencies:\n - scipy>=0.16.0\n - six>=1.10.0\n - xarray>=0.10.8\n+ - dask\n - cftime\n - pip:\n - pytest>=2.7.0\ndiff --git a/parcels/examples/example_globcurrent.py b/parcels/examples/example_globcurrent.py\nindex 2d15e0a0..d511ceda 100644\n--- a/parcels/examples/example_globcurrent.py\n+++ b/parcels/examples/example_globcurrent.py\n@@ -4,29 +4,35 @@ from os import path\n from glob import glob\n import numpy as np\n import pytest\n+import xarray as xr\n \n \n ptype = {'scipy': ScipyParticle, 'jit': JITParticle}\n \n \n-def set_globcurrent_fieldset(filename=None, indices=None, full_load=False):\n+def set_globcurrent_fieldset(filename=None, indices=None, full_load=False, use_xarray=False):\n if filename is None:\n filename = path.join(path.dirname(__file__), 'GlobCurrent_example_data',\n '20*-GLOBCURRENT-L4-CUReul_hs-ALT_SUM-v02.0-fv01.0.nc')\n variables = {'U': 'eastward_eulerian_current_velocity', 'V': 'northward_eulerian_current_velocity'}\n dimensions = {'lat': 'lat', 'lon': 'lon', 'time': 'time'}\n- return FieldSet.from_netcdf(filename, variables, dimensions, indices, full_load=full_load)\n+ if use_xarray:\n+ ds = xr.open_mfdataset(filename)\n+ return FieldSet.from_xarray_dataset(ds, variables, dimensions, indices, full_load=full_load)\n+ else:\n+ return FieldSet.from_netcdf(filename, variables, dimensions, indices, full_load=full_load)\n \n \n-def test_globcurrent_fieldset():\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_fieldset(use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n assert(fieldset.U.lon.size == 81)\n assert(fieldset.U.lat.size == 41)\n assert(fieldset.V.lon.size == 81)\n assert(fieldset.V.lat.size == 41)\n \n indices = {'lon': [5], 'lat': range(20, 30)}\n- fieldsetsub = set_globcurrent_fieldset(indices=indices)\n+ fieldsetsub = set_globcurrent_fieldset(indices=indices, use_xarray=use_xarray)\n assert np.allclose(fieldsetsub.U.lon, fieldset.U.lon[indices['lon']])\n assert np.allclose(fieldsetsub.U.lat, fieldset.U.lat[indices['lat']])\n assert np.allclose(fieldsetsub.V.lon, fieldset.V.lon[indices['lon']])\n@@ -34,34 +40,32 @@ def test_globcurrent_fieldset():\n \n \n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-@pytest.mark.parametrize('dt, substart, subend, lonstart, latstart, irange', [\n- (3600., 0, 3, 25, -35, range(3, 9, 1)),\n- (-3600., 8, 10, 20, -39, range(7, 2, -1))\n-])\n-def test_globcurrent_fieldset_advancetime(mode, dt, substart, subend, lonstart, latstart, irange):\n+@pytest.mark.parametrize('dt, lonstart, latstart', [(3600., 25, -35), (-3600., 20, -39)])\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_fieldset_advancetime(mode, dt, lonstart, latstart, use_xarray):\n basepath = path.join(path.dirname(__file__), 'GlobCurrent_example_data',\n '20*-GLOBCURRENT-L4-CUReul_hs-ALT_SUM-v02.0-fv01.0.nc')\n files = sorted(glob(str(basepath)))\n \n- fieldsetsub = set_globcurrent_fieldset(files[0:10])\n+ fieldsetsub = set_globcurrent_fieldset(files[0:10], use_xarray=use_xarray)\n psetsub = ParticleSet.from_list(fieldset=fieldsetsub, pclass=ptype[mode], lon=[lonstart], lat=[latstart])\n \n- fieldsetall = set_globcurrent_fieldset(files[0:10], full_load=True)\n+ fieldsetall = set_globcurrent_fieldset(files[0:10], full_load=True, use_xarray=use_xarray)\n psetall = ParticleSet.from_list(fieldset=fieldsetall, pclass=ptype[mode], lon=[lonstart], lat=[latstart])\n if dt < 0:\n psetsub[0].time = fieldsetsub.U.grid.time[-1]\n psetall[0].time = fieldsetall.U.grid.time[-1]\n \n- for i in irange:\n- psetsub.execute(AdvectionRK4, runtime=delta(days=1), dt=dt)\n- psetall.execute(AdvectionRK4, runtime=delta(days=1), dt=dt)\n+ psetsub.execute(AdvectionRK4, runtime=delta(days=7), dt=dt)\n+ psetall.execute(AdvectionRK4, runtime=delta(days=7), dt=dt)\n \n assert abs(psetsub[0].lon - psetall[0].lon) < 1e-4\n \n \n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-def test_globcurrent_particles(mode):\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_particles(mode, use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n \n lonstart = [25]\n latstart = [-35]\n@@ -74,6 +78,22 @@ def test_globcurrent_particles(mode):\n assert(abs(pset[0].lat - -35.3) < 1)\n \n \n+@pytest.mark.parametrize('dt', [-300, 300])\n+def test_globcurrent_xarray_vs_netcdf(dt):\n+ fieldsetNetcdf = set_globcurrent_fieldset(use_xarray=False)\n+ fieldsetxarray = set_globcurrent_fieldset(use_xarray=True)\n+ lonstart, latstart, runtime = (25, -35, delta(days=7))\n+\n+ psetN = ParticleSet(fieldsetNetcdf, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetN.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ psetX = ParticleSet(fieldsetxarray, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetX.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ assert np.allclose(psetN[0].lon, psetX[0].lon)\n+ assert np.allclose(psetN[0].lat, psetX[0].lat)\n+\n+\n def test__particles_init_time():\n fieldset = set_globcurrent_fieldset()\n \n@@ -92,8 +112,9 @@ def test__particles_init_time():\n \n @pytest.mark.xfail(reason=\"Time extrapolation error expected to be thrown\", strict=True)\n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-def test_globcurrent_time_extrapolation_error(mode):\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_time_extrapolation_error(mode, use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n \n pset = ParticleSet(fieldset, pclass=ptype[mode], lon=[25], lat=[-35],\n time=fieldset.U.time[0]-delta(days=1).total_seconds())\n@@ -103,8 +124,9 @@ def test_globcurrent_time_extrapolation_error(mode):\n \n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n @pytest.mark.parametrize('dt', [-300, 300])\n-def test_globcurrent_variable_fromfield(mode, dt):\n- fieldset = set_globcurrent_fieldset()\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_variable_fromfield(mode, dt, use_xarray):\n+ fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)\n \n class MyParticle(ptype[mode]):\n sample_var = Variable('sample_var', initial=fieldset.U)\n@@ -115,8 +137,9 @@ def test_globcurrent_variable_fromfield(mode, dt):\n \n \n @pytest.mark.parametrize('full_load', [True, False])\n-def test_globcurrent_deferred_fieldset_gradient(full_load):\n- fieldset = set_globcurrent_fieldset(full_load=full_load)\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_globcurrent_deferred_fieldset_gradient(full_load, use_xarray):\n+ fieldset = set_globcurrent_fieldset(full_load=full_load, use_xarray=use_xarray)\n (dU_dx, dU_dy) = fieldset.U.gradient()\n fieldset.add_field(dU_dy)\n \ndiff --git a/parcels/examples/example_ofam.py b/parcels/examples/example_ofam.py\nindex f7c318cd..5fdf63b9 100644\n--- a/parcels/examples/example_ofam.py\n+++ b/parcels/examples/example_ofam.py\n@@ -1,30 +1,54 @@\n from parcels import FieldSet, ParticleSet, ScipyParticle, JITParticle, AdvectionRK4\n from datetime import timedelta as delta\n import pytest\n+import xarray as xr\n+import numpy as np\n from os import path\n \n \n ptype = {'scipy': ScipyParticle, 'jit': JITParticle}\n \n \n-def set_ofam_fieldset(full_load=False):\n+def set_ofam_fieldset(full_load=False, use_xarray=False):\n filenames = {'U': path.join(path.dirname(__file__), 'OFAM_example_data', 'OFAM_simple_U.nc'),\n 'V': path.join(path.dirname(__file__), 'OFAM_example_data', 'OFAM_simple_V.nc')}\n variables = {'U': 'u', 'V': 'v'}\n dimensions = {'lat': 'yu_ocean', 'lon': 'xu_ocean', 'depth': 'st_ocean',\n 'time': 'Time'}\n- return FieldSet.from_netcdf(filenames, variables, dimensions, allow_time_extrapolation=True, full_load=full_load)\n+ if use_xarray:\n+ ds = xr.open_mfdataset([filenames['U'], filenames['V']])\n+ return FieldSet.from_xarray_dataset(ds, variables, dimensions, allow_time_extrapolation=True, full_load=full_load)\n+ else:\n+ return FieldSet.from_netcdf(filenames, variables, dimensions, allow_time_extrapolation=True, full_load=full_load)\n \n \n-def test_ofam_fieldset_fillvalues():\n- fieldset = set_ofam_fieldset(full_load=True)\n+@pytest.mark.parametrize('use_xarray', [True, False])\n+def test_ofam_fieldset_fillvalues(use_xarray):\n+ fieldset = set_ofam_fieldset(full_load=True, use_xarray=use_xarray)\n # V.data[0, 0, 150] is a landpoint, that makes NetCDF4 generate a masked array, instead of an ndarray\n assert(fieldset.V.data[0, 0, 150] == 0)\n \n \n+@pytest.mark.parametrize('dt', [delta(minutes=-5), delta(minutes=5)])\n+def test_ofam_xarray_vs_netcdf(dt):\n+ fieldsetNetcdf = set_ofam_fieldset(use_xarray=False)\n+ fieldsetxarray = set_ofam_fieldset(use_xarray=True)\n+ lonstart, latstart, runtime = (180, 10, delta(days=7))\n+\n+ psetN = ParticleSet(fieldsetNetcdf, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetN.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ psetX = ParticleSet(fieldsetxarray, pclass=JITParticle, lon=lonstart, lat=latstart)\n+ psetX.execute(AdvectionRK4, runtime=runtime, dt=dt)\n+\n+ assert np.allclose(psetN[0].lon, psetX[0].lon)\n+ assert np.allclose(psetN[0].lat, psetX[0].lat)\n+\n+\n+@pytest.mark.parametrize('use_xarray', [True, False])\n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n-def test_ofam_particles(mode):\n- fieldset = set_ofam_fieldset()\n+def test_ofam_particles(mode, use_xarray):\n+ fieldset = set_ofam_fieldset(use_xarray=use_xarray)\n \n lonstart = [180]\n latstart = [10]\ndiff --git a/parcels/field.py b/parcels/field.py\nindex 22003f49..73dfd838 100644\n--- a/parcels/field.py\n+++ b/parcels/field.py\n@@ -155,30 +155,35 @@ class Field(object):\n :param netcdf_engine: engine to use for netcdf reading in xarray. Default is 'netcdf',\n but in cases where this doesn't work, setting netcdf_engine='scipy' could help\n \"\"\"\n-\n- if not isinstance(filenames, Iterable) or isinstance(filenames, str):\n- filenames = [filenames]\n-\n- data_filenames = filenames['data'] if type(filenames) is dict else filenames\n- if type(filenames) == dict:\n- for k in filenames.keys():\n- assert k in ['lon', 'lat', 'depth', 'data'], \\\n- 'filename dimension keys must be lon, lat, depth or data'\n- assert len(filenames['lon']) == 1\n- if filenames['lon'] != filenames['lat']:\n- raise NotImplementedError('longitude and latitude dimensions are currently processed together from one single file')\n- lonlat_filename = filenames['lon'][0]\n- if 'depth' in dimensions:\n- if len(filenames['depth']) != 1:\n- raise NotImplementedError('Vertically adaptive meshes not implemented for from_netcdf()')\n- depth_filename = filenames['depth'][0]\n-\n+ if isinstance(variable, xr.core.dataarray.DataArray):\n+ lonlat_filename = variable\n+ depth_filename = variable\n+ data_filenames = variable\n+ netcdf_engine = 'xarray'\n else:\n- lonlat_filename = filenames[0]\n- depth_filename = filenames[0]\n+ if not isinstance(filenames, Iterable) or isinstance(filenames, str):\n+ filenames = [filenames]\n+\n+ data_filenames = filenames['data'] if type(filenames) is dict else filenames\n+ if type(filenames) == dict:\n+ for k in filenames.keys():\n+ assert k in ['lon', 'lat', 'depth', 'data'], \\\n+ 'filename dimension keys must be lon, lat, depth or data'\n+ assert len(filenames['lon']) == 1\n+ if filenames['lon'] != filenames['lat']:\n+ raise NotImplementedError('longitude and latitude dimensions are currently processed together from one single file')\n+ lonlat_filename = filenames['lon'][0]\n+ if 'depth' in dimensions:\n+ if len(filenames['depth']) != 1:\n+ raise NotImplementedError('Vertically adaptive meshes not implemented for from_netcdf()')\n+ depth_filename = filenames['depth'][0]\n+ else:\n+ lonlat_filename = filenames[0]\n+ depth_filename = filenames[0]\n+ netcdf_engine = kwargs.pop('netcdf_engine', 'netcdf4')\n \n indices = {} if indices is None else indices.copy()\n- netcdf_engine = kwargs.pop('netcdf_engine', 'netcdf4')\n+\n with NetcdfFileBuffer(lonlat_filename, dimensions, indices, netcdf_engine) as filebuffer:\n lon, lat = filebuffer.read_lonlat\n indices = filebuffer.indices\n@@ -199,16 +204,22 @@ class Field(object):\n if grid is None:\n # Concatenate time variable to determine overall dimension\n # across multiple files\n- timeslices = []\n- dataFiles = []\n- for fname in data_filenames:\n- with NetcdfFileBuffer(fname, dimensions, indices, netcdf_engine) as filebuffer:\n- ftime = filebuffer.time\n- timeslices.append(ftime)\n- dataFiles.append([fname] * len(ftime))\n- timeslices = np.array(timeslices)\n- time = np.concatenate(timeslices)\n- dataFiles = np.concatenate(np.array(dataFiles))\n+ if netcdf_engine == 'xarray':\n+ with NetcdfFileBuffer(data_filenames, dimensions, indices, netcdf_engine) as filebuffer:\n+ time = filebuffer.time\n+ timeslices = time if isinstance(time, (list, np.ndarray)) else [time]\n+ dataFiles = data_filenames if isinstance(data_filenames, (list, np.ndarray)) else [data_filenames] * len(time)\n+ else:\n+ timeslices = []\n+ dataFiles = []\n+ for fname in data_filenames:\n+ with NetcdfFileBuffer(fname, dimensions, indices, netcdf_engine) as filebuffer:\n+ ftime = filebuffer.time\n+ timeslices.append(ftime)\n+ dataFiles.append([fname] * len(ftime))\n+ timeslices = np.array(timeslices)\n+ time = np.concatenate(timeslices)\n+ dataFiles = np.concatenate(np.array(dataFiles))\n if time.size == 1 and time[0] is None:\n time[0] = 0\n time_origin = TimeConverter(time[0])\n@@ -239,17 +250,20 @@ class Field(object):\n with NetcdfFileBuffer(fname, dimensions, indices, netcdf_engine) as filebuffer:\n # If Field.from_netcdf is called directly, it may not have a 'data' dimension\n # In that case, assume that 'name' is the data dimension\n- filebuffer.name = filebuffer.parse_name(dimensions, variable)\n+ if netcdf_engine == 'xarray':\n+ tslice = [tslice]\n+ else:\n+ filebuffer.name = filebuffer.parse_name(dimensions, variable)\n \n- if len(filebuffer.dataset[filebuffer.name].shape) == 2:\n- data[ti:ti+len(tslice), 0, :, :] = filebuffer.data[:, :]\n- elif len(filebuffer.dataset[filebuffer.name].shape) == 3:\n+ if len(filebuffer.data.shape) == 2:\n+ data[ti:ti+len(tslice), 0, :, :] = filebuffer.data\n+ elif len(filebuffer.data.shape) == 3:\n if len(filebuffer.indices['depth']) > 1:\n- data[ti:ti+len(tslice), :, :, :] = filebuffer.data[:, :, :]\n+ data[ti:ti+len(tslice), :, :, :] = filebuffer.data\n else:\n- data[ti:ti+len(tslice), 0, :, :] = filebuffer.data[:, :, :]\n+ data[ti:ti+len(tslice), 0, :, :] = filebuffer.data\n else:\n- data[ti:ti+len(tslice), :, :, :] = filebuffer.data[:, :, :, :]\n+ data[ti:ti+len(tslice), :, :, :] = filebuffer.data\n ti += len(tslice)\n else:\n grid.defer_load = True\n@@ -264,6 +278,7 @@ class Field(object):\n kwargs['time_periodic'] = time_periodic\n kwargs['netcdf_engine'] = netcdf_engine\n \n+ variable = kwargs['var_name'] if netcdf_engine == 'xarray' else variable\n return cls(variable, data, grid=grid,\n allow_time_extrapolation=allow_time_extrapolation, **kwargs)\n \n@@ -866,21 +881,20 @@ class Field(object):\n def computeTimeChunk(self, data, tindex):\n g = self.grid\n with NetcdfFileBuffer(self.dataFiles[g.ti+tindex], self.dimensions, self.indices, self.netcdf_engine) as filebuffer:\n- filebuffer.name = filebuffer.parse_name(self.dimensions, self.name)\n time_data = filebuffer.time\n time_data = g.time_origin.reltime(time_data)\n- ti = (time_data <= g.time[tindex]).argmin() - 1\n- if len(filebuffer.dataset[filebuffer.name].shape) == 2:\n- data[tindex, 0, :, :] = filebuffer.data[:, :]\n- elif len(filebuffer.dataset[filebuffer.name].shape) == 3:\n+ filebuffer.ti = (time_data <= g.time[tindex]).argmin() - 1\n+ if self.netcdf_engine != 'xarray':\n+ filebuffer.name = filebuffer.parse_name(self.dimensions, self.name)\n+ if len(filebuffer.data.shape) == 2:\n+ data[tindex, 0, :, :] = filebuffer.data\n+ elif len(filebuffer.data.shape) == 3:\n if g.zdim > 1:\n- data[tindex, :, :, :] = filebuffer.data[:, :, :]\n+ data[tindex, :, :, :] = filebuffer.data\n else:\n- data[tindex, 0, :, :] = filebuffer.data[ti, :, :]\n+ data[tindex, 0, :, :] = filebuffer.data\n else:\n- data[tindex, :, :, :] = filebuffer.data[ti, :, :, :]\n-\n- return data\n+ data[tindex, :, :, :] = filebuffer.data\n \n def __add__(self, field):\n if isinstance(self, Field) and isinstance(field, Field):\n@@ -1139,12 +1153,16 @@ class NetcdfFileBuffer(object):\n \n def __init__(self, filename, dimensions, indices, netcdf_engine):\n self.filename = filename\n- self.dimensions = dimensions # Dict with dimension keyes for file data\n+ self.dimensions = dimensions # Dict with dimension keys for file data\n self.indices = indices\n self.dataset = None\n self.netcdf_engine = netcdf_engine\n+ self.ti = None\n \n def __enter__(self):\n+ if self.netcdf_engine == 'xarray':\n+ self.dataset = self.filename\n+ return self\n try:\n self.dataset = xr.open_dataset(str(self.filename), decode_cf=True, engine=self.netcdf_engine)\n self.dataset['decoded'] = True\n@@ -1159,7 +1177,10 @@ class NetcdfFileBuffer(object):\n return self\n \n def __exit__(self, type, value, traceback):\n- self.dataset.close()\n+ if self.netcdf_engine == 'xarray':\n+ pass\n+ else:\n+ self.dataset.close()\n \n def parse_name(self, dimensions, variable):\n name = dimensions['data'] if 'data' in dimensions else variable\n@@ -1228,16 +1249,20 @@ class NetcdfFileBuffer(object):\n \n @property\n def data(self):\n- data = self.dataset[self.name]\n+ if self.netcdf_engine == 'xarray':\n+ data = self.dataset\n+ else:\n+ data = self.dataset[self.name]\n+ ti = range(data.shape[0]) if self.ti is None else self.ti\n if len(data.shape) == 2:\n data = data[self.indices['lat'], self.indices['lon']]\n elif len(data.shape) == 3:\n if len(self.indices['depth']) > 1:\n data = data[self.indices['depth'], self.indices['lat'], self.indices['lon']]\n else:\n- data = data[:, self.indices['lat'], self.indices['lon']]\n+ data = data[ti, self.indices['lat'], self.indices['lon']]\n else:\n- data = data[:, self.indices['depth'], self.indices['lat'], self.indices['lon']]\n+ data = data[ti, self.indices['depth'], self.indices['lat'], self.indices['lon']]\n \n if np.ma.is_masked(data): # convert masked array to ndarray\n data = np.ma.filled(data, np.nan)\n@@ -1247,7 +1272,7 @@ class NetcdfFileBuffer(object):\n def time(self):\n try:\n time_da = self.dataset[self.dimensions['time']]\n- if self.dataset['decoded'] and 'Unit' not in time_da.attrs:\n+ if self.netcdf_engine != 'xarray' and (self.dataset['decoded'] and 'Unit' not in time_da.attrs):\n time = np.array([time_da]) if len(time_da.shape) == 0 else np.array(time_da)\n else:\n if 'units' not in time_da.attrs and 'Unit' in time_da.attrs:\ndiff --git a/parcels/fieldset.py b/parcels/fieldset.py\nindex 6232ce73..012cd2df 100644\n--- a/parcels/fieldset.py\n+++ b/parcels/fieldset.py\n@@ -331,6 +331,51 @@ class FieldSet(object):\n dimensions=dimensions, allow_time_extrapolation=allow_time_extrapolation,\n time_periodic=time_periodic, full_load=full_load, **kwargs)\n \n+ @classmethod\n+ def from_xarray_dataset(cls, ds, variables, dimensions, indices=None, mesh='spherical', allow_time_extrapolation=None,\n+ time_periodic=False, full_load=False, **kwargs):\n+ \"\"\"Initialises FieldSet data from xarray Datasets.\n+\n+ :param ds: xarray Dataset\n+ :param dimensions: Dictionary mapping data dimensions (lon,\n+ lat, depth, time, data) to dimensions in the xarray Dataset.\n+ Note that dimensions can also be a dictionary of dictionaries if\n+ dimension names are different for each variable\n+ (e.g. dimensions['U'], dimensions['V'], etc).\n+ :param indices: Optional dictionary of indices for each dimension\n+ to read from file(s), to allow for reading of subset of data.\n+ Default is to read the full extent of each dimension.\n+ :param mesh: String indicating the type of mesh coordinates and\n+ units used during velocity interpolation:\n+\n+ 1. spherical (default): Lat and lon in degree, with a\n+ correction for zonal velocity U near the poles.\n+ 2. flat: No conversion, lat/lon are assumed to be in m.\n+ :param allow_time_extrapolation: boolean whether to allow for extrapolation\n+ (i.e. beyond the last available time snapshot)\n+ Default is False if dimensions includes time, else True\n+ :param time_periodic: boolean whether to loop periodically over the time component of the FieldSet\n+ This flag overrides the allow_time_interpolation and sets it to False\n+ :param full_load: boolean whether to fully load the data or only pre-load them. (default: False)\n+ It is advised not to fully load the data, since in that case Parcels deals with\n+ a better memory management during particle set execution.\n+ full_load is however sometimes necessary for plotting the fields.\n+ \"\"\"\n+\n+ fields = {}\n+ for var, name in variables.items():\n+\n+ # Use dimensions[var] and indices[var] if either of them is a dict of dicts\n+ dims = dimensions[var] if var in dimensions else dimensions\n+ inds = indices[var] if (indices and var in indices) else indices\n+\n+ fields[var] = Field.from_netcdf(None, ds[name], dimensions=dims, indices=inds, grid=None, mesh=mesh,\n+ allow_time_extrapolation=allow_time_extrapolation, var_name=var,\n+ time_periodic=time_periodic, full_load=full_load, **kwargs)\n+ u = fields.pop('U', None)\n+ v = fields.pop('V', None)\n+ return cls(u, v, fields=fields)\n+\n @property\n def fields(self):\n \"\"\"Returns a list of all the :class:`parcels.field.Field` objects\n@@ -446,7 +491,7 @@ class FieldSet(object):\n data = np.empty((g.tdim, g.zdim, g.ydim-2*g.meridional_halo, g.xdim-2*g.zonal_halo), dtype=np.float32)\n f.loaded_time_indices = range(3)\n for tind in f.loaded_time_indices:\n- data = f.computeTimeChunk(data, tind)\n+ f.computeTimeChunk(data, tind)\n f.data = f.reshape(data)\n elif g.update_status == 'updated':\n data = np.empty((g.tdim, g.zdim, g.ydim-2*g.meridional_halo, g.xdim-2*g.zonal_halo), dtype=np.float32)\n@@ -456,7 +501,7 @@ class FieldSet(object):\n else:\n f.data[1:, :] = f.data[:2, :]\n f.loaded_time_indices = [0]\n- data = f.computeTimeChunk(data, f.loaded_time_indices[0])\n+ f.computeTimeChunk(data, f.loaded_time_indices[0])\n f.data[f.loaded_time_indices[0], :] = f.reshape(data)[f.loaded_time_indices[0], :]\n else:\n f.loaded_time_indices = []\n", "test_patch": "diff --git a/tests/test_fieldset.py b/tests/test_fieldset.py\nindex d4f897f2..bebcda16 100644\n--- a/tests/test_fieldset.py\n+++ b/tests/test_fieldset.py\n@@ -4,6 +4,7 @@ from parcels.tools.converters import TimeConverter\n from datetime import timedelta as delta\n import datetime\n import numpy as np\n+import xarray as xr\n import math\n import pytest\n from os import path\n@@ -365,3 +366,31 @@ def test_fieldset_defer_loading_function(zdim, scale_fac, tmpdir, filename='test\n pset.execute(DoNothing, dt=3600)\n assert np.allclose(fieldset.U.data, scale_fac*(zdim-1.)/zdim)\n assert np.allclose(dFdx.data, 0)\n+\n+\n+@pytest.mark.parametrize('maxlatind', [3, pytest.param(2, marks=pytest.mark.xfail(strict=True))])\n+def test_fieldset_from_xarray(maxlatind):\n+ def generate_dataset(xdim, ydim, zdim=1, tdim=1):\n+ lon = np.linspace(0., 12, xdim, dtype=np.float32)\n+ lat = np.linspace(0., 12, ydim, dtype=np.float32)\n+ depth = np.linspace(0., 20., zdim, dtype=np.float32)\n+ time = np.linspace(0., 10, tdim, dtype=np.float64)\n+ Uxr = np.ones((tdim, zdim, ydim, xdim), dtype=np.float32)\n+ Vxr = np.ones((tdim, zdim, ydim, xdim), dtype=np.float32)\n+ for t in range(Uxr.shape[0]):\n+ Uxr[t, :, :, :] = t/10.\n+ coords = {'lat': lat, 'lon': lon, 'depth': depth, 'time': time}\n+ dims = ('time', 'depth', 'lat', 'lon')\n+ return xr.Dataset({'Uxr': xr.DataArray(Uxr, coords=coords, dims=dims),\n+ 'Vxr': xr.DataArray(Vxr, coords=coords, dims=dims)})\n+\n+ ds = generate_dataset(3, 3, 2, 10)\n+ variables = {'U': 'Uxr', 'V': 'Vxr'}\n+ dimensions = {'lat': 'lat', 'lon': 'lon', 'depth': 'depth', 'time': 'time'}\n+ indices = {'lat': range(0, maxlatind)}\n+ fieldset = FieldSet.from_xarray_dataset(ds, variables, dimensions, indices, mesh='flat')\n+\n+ pset = ParticleSet(fieldset, JITParticle, 0, 0)\n+\n+ pset.execute(AdvectionRK4, dt=1)\n+ assert pset[0].lon == 4.5 and pset[0].lat == 10\n", "FAIL_TO_PASS": ["tests/test_fieldset.py::test_fieldset_from_xarray[3]"]}, {"instance_id": "oceanparcels__parcels-541", "base_commit": "1ba77703fb2ff32311f5a948af64130e960cb84c", "gold_patch": "diff --git a/parcels/codegenerator.py b/parcels/codegenerator.py\nindex 47695ea7..08001043 100644\n--- a/parcels/codegenerator.py\n+++ b/parcels/codegenerator.py\n@@ -209,7 +209,7 @@ class IntrinsicTransformer(ast.NodeTransformer):\n \n def get_tmp(self):\n \"\"\"Create a new temporary veriable name\"\"\"\n- tmp = \"tmp%d\" % self._tmp_counter\n+ tmp = \"parcels_tmpvar%d\" % self._tmp_counter\n self._tmp_counter += 1\n self.tmp_vars += [tmp]\n return tmp\n@@ -228,6 +228,8 @@ class IntrinsicTransformer(ast.NodeTransformer):\n node = RandomNode(math, ccode='')\n elif node.id == 'print':\n node = PrintNode()\n+ elif 'parcels_tmpvar' in node.id:\n+ raise NotImplementedError(\"Custom Kernels cannot contain string 'parcels_tmpvar'; please change your kernel\")\n return node\n \n def visit_Attribute(self, node):\n@@ -542,7 +544,7 @@ class KernelGenerator(ast.NodeVisitor):\n self.visit(b)\n # field evals are replaced by a tmp variable is added to the stack.\n # Here it means field evals passes from node.test to node.body. We take it out manually\n- fieldInTestCount = node.test.ccode.count('tmp')\n+ fieldInTestCount = node.test.ccode.count('parcels_tmpvar')\n body0 = c.Block([b.ccode for b in node.body[:fieldInTestCount]])\n body = c.Block([b.ccode for b in node.body[fieldInTestCount:]])\n orelse = c.Block([b.ccode for b in node.orelse]) if len(node.orelse) > 0 else None\n", "test_patch": "diff --git a/tests/test_kernel_language.py b/tests/test_kernel_language.py\nindex a87f4d56..874bc981 100644\n--- a/tests/test_kernel_language.py\n+++ b/tests/test_kernel_language.py\n@@ -110,6 +110,39 @@ def test_while_if_break(fieldset, mode):\n assert np.allclose(np.array([p.p for p in pset]), 20., rtol=1e-12)\n \n \n+@pytest.mark.parametrize('mode', ['scipy', 'jit'])\n+def test_nested_if(fieldset, mode):\n+ \"\"\"Test nested if commands\"\"\"\n+ class TestParticle(ptype[mode]):\n+ p0 = Variable('p0', dtype=np.int32, initial=0)\n+ p1 = Variable('p1', dtype=np.int32, initial=1)\n+ pset = ParticleSet(fieldset, pclass=TestParticle, lon=0, lat=0)\n+\n+ def kernel(particle, fieldset, time):\n+ if particle.p1 >= particle.p0:\n+ var = particle.p0\n+ if var + 1 < particle.p1:\n+ particle.p1 = -1\n+\n+ pset.execute(kernel, endtime=10, dt=1.)\n+ assert np.allclose([pset[0].p0, pset[0].p1], [0, 1])\n+\n+\n+def test_parcels_tmpvar_in_kernel(fieldset):\n+ \"\"\"Tests for error thrown if vartiable with 'tmp' defined in custom kernel\"\"\"\n+ error_thrown = False\n+ pset = ParticleSet(fieldset, pclass=JITParticle, lon=0, lat=0)\n+\n+ def kernel_tmpvar(particle, fieldset, time):\n+ parcels_tmpvar0 = 0 # noqa\n+\n+ try:\n+ pset.execute(kernel_tmpvar, endtime=1, dt=1.)\n+ except NotImplementedError:\n+ error_thrown = True\n+ assert error_thrown\n+\n+\n @pytest.mark.parametrize('mode', ['scipy', 'jit'])\n def test_if_withfield(fieldset, mode):\n \"\"\"Test combination of if and Field sampling commands\"\"\"\n", "FAIL_TO_PASS": ["tests/test_kernel_language.py::test_parcels_tmpvar_in_kernel"]}], "all_FAIL_TO_PASS": ["tests/test_fieldset.py::test_fieldset_from_xarray[3]", "tests/test_kernel_language.py::test_parcels_tmpvar_in_kernel"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aws-cloudformation__cfn-lint-3898_x2", "level": 2, "source": "swerebenchv2", "repo": "aws-cloudformation/cfn-lint", "image": "swerebenchv2/aws-cloudformation-cfn-lint:3898-e087f10", "base_commit": "e087f1037b067288e377d197d6b855cd481d6a47", "num_bugs": 2, "bugs": [{"instance_id": "aws-cloudformation__cfn-lint-3898", "base_commit": "e087f1037b067288e377d197d6b855cd481d6a47", "gold_patch": "diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py\nindex 03846af54..a9f4aa5e4 100644\n--- a/src/cfnlint/config.py\n+++ b/src/cfnlint/config.py\n@@ -313,7 +313,7 @@ class RuleConfigurationAction(argparse.Action):\n setattr(namespace, self.dest, items)\n except Exception: # pylint: disable=W0703\n parser.print_help()\n- parser.exit()\n+ parser.exit(1)\n \n \n class CliArgs:\n@@ -331,7 +331,7 @@ class CliArgs:\n \n def error(self, message):\n self.print_help(sys.stderr)\n- self.exit(32, f\"{self.prog}: error: {message}\\n\")\n+ self.exit(1, f\"{self.prog}: error: {message}\\n\")\n \n class ExtendAction(argparse.Action):\n \"\"\"Support argument types that are lists and can\n@@ -620,7 +620,6 @@ class ManualArgs(TypedDict, total=False):\n \n # pylint: disable=too-many-public-methods\n class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n- \"\"\"Mixin for the Configs\"\"\"\n \n def __init__(self, cli_args: list[str] | None = None, **kwargs: Unpack[ManualArgs]):\n self._manual_args = kwargs or ManualArgs()\n@@ -721,7 +720,7 @@ class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n \n @property\n def debug(self):\n- return self._get_argument_value(\"debug\", False, False)\n+ return self._get_argument_value(\"debug\", False, True)\n \n @property\n def info(self):\ndiff --git a/src/cfnlint/core.py b/src/cfnlint/core.py\nindex e1e231d76..899e06cbe 100644\n--- a/src/cfnlint/core.py\n+++ b/src/cfnlint/core.py\n@@ -9,9 +9,10 @@ import os\n from typing import Sequence\n \n from cfnlint.config import _DEFAULT_RULESDIR, ConfigMixIn, ManualArgs\n+from cfnlint.exceptions import UnexpectedRuleException\n from cfnlint.match import Match\n from cfnlint.rules import RulesCollection\n-from cfnlint.runner import TemplateRunner, UnexpectedRuleException\n+from cfnlint.runner import TemplateRunner\n \n \n def get_rules(\ndiff --git a/src/cfnlint/data/CfnLintCli/config/schema.json b/src/cfnlint/data/CfnLintCli/config/schema.json\nindex f72fc6189..e87f1234b 100644\n--- a/src/cfnlint/data/CfnLintCli/config/schema.json\n+++ b/src/cfnlint/data/CfnLintCli/config/schema.json\n@@ -58,6 +58,10 @@\n \"description\": \"custom rule file to use\",\n \"type\": \"string\"\n },\n+ \"debug\": {\n+ \"description\": \"Debug mode\",\n+ \"type\": \"boolean\"\n+ },\n \"ignore_bad_template\": {\n \"description\": \"Ignore bad templates\",\n \"type\": \"boolean\"\ndiff --git a/src/cfnlint/exceptions.py b/src/cfnlint/exceptions.py\nindex cedb10369..993106ab0 100644\n--- a/src/cfnlint/exceptions.py\n+++ b/src/cfnlint/exceptions.py\n@@ -1,21 +1,57 @@\n-class CfnLintError(Exception):\n+class CfnLintExitException(Exception):\n \"\"\"\n- The base exception class for cfn-lint exceptions.\n- :ivar msg: The descriptive message associated with the error.\n+ An exception that is raised to indicate that the CloudFormation linter should exit.\n+\n+ This exception is used to signal that the linter should exit\n+ with a specific exit code, typically indicating the severity\n+ of the issues found in the CloudFormation template.\n+\n+ Attributes:\n+ exit_code (int): The exit code to be used when the linter exits.\n+\n+ Methods:\n+ __init__(self, exit_code: int) -> None:\n+ Initialize a new CfnLintExitException instance with the specified exit code.\n \"\"\"\n \n- fmt = \"An unspecified error occurred\"\n+ def __init__(self, msg=None, exit_code=1):\n+ \"\"\"\n+ Initialize a new CfnLintExitException instance with the specified exit code.\n+\n+ Args:\n+ exit_code (int): The exit code to be used when the linter exits.\n+ \"\"\"\n+ if msg is None:\n+ msg = f\"process failed with exit code {exit_code}\"\n+ super().__init__(msg)\n+ self.exit_code = exit_code\n+\n+\n+class InvalidRegionException(CfnLintExitException):\n+ \"\"\"\n+ An exception that is raised when an invalid AWS region is encountered.\n \n- def __init__(self, **kwargs):\n- msg = self.fmt.format(**kwargs)\n- Exception.__init__(self, msg)\n- self.kwargs = kwargs\n+ This exception is raised when the CloudFormation linter encounters a resource\n+ or parameter that references an AWS region that is not valid or supported.\n+ \"\"\"\n+\n+\n+class UnexpectedRuleException(CfnLintExitException):\n+ \"\"\"\n+ An exception that is raised when an unexpected error occurs while loading rules.\n+\n+ This exception is raised when the CloudFormation linter encounters an error\n+ while attempting to load custom rules or rules from a specified directory or\n+ module. This could be due to a variety of reasons, such as a missing file,\n+ a syntax error in the rule code, or an issue with the rule implementation.\n+ \"\"\"\n \n \n-class DuplicateRuleError(CfnLintError):\n+class DuplicateRuleError(CfnLintExitException):\n \"\"\"\n The data associated with a particular path could not be loaded.\n :ivar data_path: The data path that the user attempted to load.\n \"\"\"\n \n- fmt = \"Rule already included: {rule_id}\"\n+ def __init__(self, rule_id: str):\n+ super().__init__(f\"Rule already included: {rule_id}\")\ndiff --git a/src/cfnlint/runner.py b/src/cfnlint/runner.py\nindex 6b8acabd5..a334fba12 100644\n--- a/src/cfnlint/runner.py\n+++ b/src/cfnlint/runner.py\n@@ -15,6 +15,11 @@ import cfnlint.formatters\n import cfnlint.maintenance\n from cfnlint.config import ConfigMixIn, configure_logging\n from cfnlint.decode.decode import decode\n+from cfnlint.exceptions import (\n+ CfnLintExitException,\n+ InvalidRegionException,\n+ UnexpectedRuleException,\n+)\n from cfnlint.helpers import REGIONS\n from cfnlint.rules import Match, Rules\n from cfnlint.rules.errors import ConfigError, ParseError, TransformError\n@@ -452,55 +457,10 @@ class Runner:\n \n \n def main() -> None:\n- config = ConfigMixIn(sys.argv[1:])\n+ try:\n+ config = ConfigMixIn(sys.argv[1:])\n+ except Exception as e:\n+ print(e)\n+ sys.exit(1)\n runner = Runner(config)\n runner.cli()\n-\n-\n-class CfnLintExitException(Exception):\n- \"\"\"\n- An exception that is raised to indicate that the CloudFormation linter should exit.\n-\n- This exception is used to signal that the linter should exit\n- with a specific exit code, typically indicating the severity\n- of the issues found in the CloudFormation template.\n-\n- Attributes:\n- exit_code (int): The exit code to be used when the linter exits.\n-\n- Methods:\n- __init__(self, exit_code: int) -> None:\n- Initialize a new CfnLintExitException instance with the specified exit code.\n- \"\"\"\n-\n- def __init__(self, msg=None, exit_code=1):\n- \"\"\"\n- Initialize a new CfnLintExitException instance with the specified exit code.\n-\n- Args:\n- exit_code (int): The exit code to be used when the linter exits.\n- \"\"\"\n- if msg is None:\n- msg = f\"process failed with exit code {exit_code}\"\n- super().__init__(msg)\n- self.exit_code = exit_code\n-\n-\n-class InvalidRegionException(CfnLintExitException):\n- \"\"\"\n- An exception that is raised when an invalid AWS region is encountered.\n-\n- This exception is raised when the CloudFormation linter encounters a resource\n- or parameter that references an AWS region that is not valid or supported.\n- \"\"\"\n-\n-\n-class UnexpectedRuleException(CfnLintExitException):\n- \"\"\"\n- An exception that is raised when an unexpected error occurs while loading rules.\n-\n- This exception is raised when the CloudFormation linter encounters an error\n- while attempting to load custom rules or rules from a specified directory or\n- module. This could be due to a variety of reasons, such as a missing file,\n- a syntax error in the rule code, or an issue with the rule implementation.\n- \"\"\"\n", "test_patch": "diff --git a/test/unit/module/config/test_config_file_args.py b/test/unit/module/config/test_config_file_args.py\nindex 86144086c..2541f599d 100644\n--- a/test/unit/module/config/test_config_file_args.py\n+++ b/test/unit/module/config/test_config_file_args.py\n@@ -8,7 +8,7 @@ from pathlib import Path\n from test.testlib.testcase import BaseTestCase\n from unittest.mock import patch\n \n-import cfnlint.config # pylint: disable=E0401\n+import cfnlint.config\n from cfnlint.jsonschema import ValidationError\n \n LOGGER = logging.getLogger(\"cfnlint\")\ndiff --git a/test/unit/module/runner/test_rule_configuration.py b/test/unit/module/runner/test_rule_configuration.py\nindex 444ad341e..7a58e8b99 100644\n--- a/test/unit/module/runner/test_rule_configuration.py\n+++ b/test/unit/module/runner/test_rule_configuration.py\n@@ -7,7 +7,8 @@ import os\n from test.testlib.testcase import BaseTestCase\n \n from cfnlint.config import ConfigMixIn\n-from cfnlint.runner import Runner, UnexpectedRuleException\n+from cfnlint.exceptions import UnexpectedRuleException\n+from cfnlint.runner import Runner\n \n \n class TestGetRules(BaseTestCase):\n", "FAIL_TO_PASS": ["test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_bad_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_config_rules", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yaml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config_only_one_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_merge", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_directory", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_module", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_invalid_rule"]}, {"instance_id": "aws-cloudformation__cfn-lint-3900", "base_commit": "3ae39419c050c54df37dfb79107cd93c3598e116", "gold_patch": "diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py\nindex a9f4aa5e4..244d8df77 100644\n--- a/src/cfnlint/config.py\n+++ b/src/cfnlint/config.py\n@@ -785,9 +785,11 @@ class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n if isinstance(filenames, str):\n filenames = [filenames]\n \n- return self._glob_filenames(filenames)\n+ return self._glob_filenames(filenames, False)\n \n- def _glob_filenames(self, filenames: Sequence[str]) -> list[str]:\n+ def _glob_filenames(\n+ self, filenames: Sequence[str], raise_exception: bool = True\n+ ) -> list[str]:\n # handle different shells and Config files\n # some shells don't expand * and configparser won't expand wildcards\n all_filenames = []\n@@ -796,7 +798,8 @@ class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs):\n add_filenames = glob.glob(filename, recursive=True)\n \n if not add_filenames and not self.ignore_bad_template:\n- raise ValueError(f\"{filename} could not be processed by glob.glob\")\n+ if raise_exception:\n+ raise ValueError(f\"{filename} could not be processed by glob.glob\")\n \n all_filenames.extend(add_filenames)\n \n", "test_patch": "diff --git a/test/unit/module/config/test_config_mixin.py b/test/unit/module/config/test_config_mixin.py\nindex 9e584ead0..cbed4b458 100644\n--- a/test/unit/module/config/test_config_mixin.py\n+++ b/test/unit/module/config/test_config_mixin.py\n@@ -247,6 +247,28 @@ class TestConfigMixIn(BaseTestCase):\n )\n self.assertEqual(len(config.templates), 3)\n \n+ @patch(\"cfnlint.config.ConfigFileArgs._read_config\", create=True)\n+ def test_config_expand_and_ignore_templates_with_bad_path(self, yaml_mock):\n+ \"\"\"Test ignore templates\"\"\"\n+\n+ yaml_mock.side_effect = [\n+ {\n+ \"templates\": [\"test/fixtures/templates/bad/resources/iam/*.yaml\"],\n+ \"ignore_templates\": [\n+ \"dne/fixtures/templates/bad/resources/iam/resource_*.yaml\"\n+ ],\n+ },\n+ {},\n+ ]\n+ config = cfnlint.config.ConfigMixIn([])\n+\n+ # test defaults\n+ self.assertIn(\n+ str(Path(\"test/fixtures/templates/bad/resources/iam/resource_policy.yaml\")),\n+ config.templates,\n+ )\n+ self.assertEqual(len(config.templates), 4)\n+\n @patch(\"cfnlint.config.ConfigFileArgs._read_config\", create=True)\n def test_config_merge(self, yaml_mock):\n \"\"\"Test merging lists\"\"\"\n", "FAIL_TO_PASS": ["test/unit/module/config/test_config_mixin.py::TestConfigMixIn::test_config_expand_and_ignore_templates_with_bad_path"]}], "all_FAIL_TO_PASS": ["test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_bad_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_fail_on_config_rules", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yaml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_is_file_both_yml", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_config_only_one_read", "test/unit/module/config/test_config_file_args.py::TestConfigFileArgs::test_config_parser_read_merge", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_directory", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_append_module", "test/unit/module/runner/test_rule_configuration.py::TestGetRules::test_invalid_rule", "test/unit/module/config/test_config_mixin.py::TestConfigMixIn::test_config_expand_and_ignore_templates_with_bad_path"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tornadoweb__tornado-3488_x2", "level": 2, "source": "swerebenchv2", "repo": "tornadoweb/tornado", "image": "swerebenchv2/tornadoweb-tornado:3488-1a8c152", "base_commit": "1a8c15283af6bfc5b5944a3f2c6df4ff067e56a7", "num_bugs": 2, "bugs": [{"instance_id": "tornadoweb__tornado-3488", "base_commit": "1a8c15283af6bfc5b5944a3f2c6df4ff067e56a7", "gold_patch": "diff --git a/tornado/httputil.py b/tornado/httputil.py\nindex 0f443cdd..5d05cacb 100644\n--- a/tornado/httputil.py\n+++ b/tornado/httputil.py\n@@ -248,7 +248,7 @@ class HTTPHeaders(StrMutableMapping):\n if not line:\n # Empty line, or the final CRLF of a header block.\n return\n- if line[0].isspace():\n+ if line[0] in HTTP_WHITESPACE:\n # continuation of a multi-line header\n # TODO(7.0): Remove support for line folding.\n if self._last_key is None:\n", "test_patch": "diff --git a/tornado/test/httputil_test.py b/tornado/test/httputil_test.py\nindex 53ae4607..221c1dcb 100644\n--- a/tornado/test/httputil_test.py\n+++ b/tornado/test/httputil_test.py\n@@ -287,13 +287,22 @@ Foo: even\n [(\"Asdf\", \"qwer zxcv\"), (\"Foo\", \"bar baz\"), (\"Foo\", \"even more lines\")],\n )\n \n- def test_malformed_continuation(self):\n+ def test_continuation(self):\n+ data = \"Foo: bar\\r\\n\\tasdf\"\n+ headers = HTTPHeaders.parse(data)\n+ self.assertEqual(headers[\"Foo\"], \"bar asdf\")\n+\n # If the first line starts with whitespace, it's a\n # continuation line with nothing to continue, so reject it\n # (with a proper error).\n data = \" Foo: bar\"\n self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n \n+ # \\f (formfeed) is whitespace according to str.isspace, but\n+ # not according to the HTTP spec.\n+ data = \"Foo: bar\\r\\n\\fasdf\"\n+ self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n+\n def test_unicode_newlines(self):\n # Ensure that only \\r\\n is recognized as a header separator, and not\n # the other newline-like unicode characters.\n", "FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_continuation"]}, {"instance_id": "tornadoweb__tornado-3489", "base_commit": "5976db7db6796ea75bfaec9d620b4ba3ff6f2023", "gold_patch": "diff --git a/tornado/httputil.py b/tornado/httputil.py\nindex 5d05cacb..7044aca0 100644\n--- a/tornado/httputil.py\n+++ b/tornado/httputil.py\n@@ -33,7 +33,7 @@ import time\n import unicodedata\n from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl\n \n-from tornado.escape import native_str, parse_qs_bytes, utf8\n+from tornado.escape import native_str, parse_qs_bytes, utf8, to_unicode\n from tornado.log import gen_log\n from tornado.util import ObjectDict, unicode_type\n \n@@ -100,6 +100,12 @@ class _ABNF:\n # RFC 9110 (HTTP Semantics)\n obs_text = re.compile(r\"[\\x80-\\xFF]\")\n field_vchar = re.compile(rf\"(?:{VCHAR.pattern}|{obs_text.pattern})\")\n+ # Not exactly from the RFC to simplify and combine field-content and field-value.\n+ field_value = re.compile(\n+ rf\"|\"\n+ rf\"{field_vchar.pattern}|\"\n+ rf\"{field_vchar.pattern}(?:{field_vchar.pattern}| |\\t)*{field_vchar.pattern}\"\n+ )\n tchar = re.compile(r\"[!#$%&'*+\\-.^_`|~0-9A-Za-z]\")\n token = re.compile(rf\"{tchar.pattern}+\")\n field_name = token\n@@ -195,6 +201,10 @@ class HTTPHeaders(StrMutableMapping):\n \"\"\"Adds a new value for the given key.\"\"\"\n if not _ABNF.field_name.fullmatch(name):\n raise HTTPInputError(\"Invalid header name %r\" % name)\n+ if not _ABNF.field_value.fullmatch(to_unicode(value)):\n+ # TODO: the fact we still support bytes here (contrary to type annotations)\n+ # and still test for it should probably be changed.\n+ raise HTTPInputError(\"Invalid header value %r\" % value)\n norm_name = _normalize_header(name)\n self._last_key = norm_name\n if norm_name in self:\n@@ -254,6 +264,8 @@ class HTTPHeaders(StrMutableMapping):\n if self._last_key is None:\n raise HTTPInputError(\"first header line cannot start with whitespace\")\n new_part = \" \" + line.strip(HTTP_WHITESPACE)\n+ if not _ABNF.field_value.fullmatch(new_part[1:]):\n+ raise HTTPInputError(\"Invalid header continuation %r\" % new_part)\n self._as_list[self._last_key][-1] += new_part\n self._dict[self._last_key] += new_part\n else:\n", "test_patch": "diff --git a/tornado/test/httputil_test.py b/tornado/test/httputil_test.py\nindex 221c1dcb..30fbec4d 100644\n--- a/tornado/test/httputil_test.py\n+++ b/tornado/test/httputil_test.py\n@@ -303,6 +303,17 @@ Foo: even\n data = \"Foo: bar\\r\\n\\fasdf\"\n self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n \n+ def test_forbidden_ascii_characters(self):\n+ # Control characters and ASCII whitespace other than space, tab, and CRLF are not allowed in\n+ # headers.\n+ for c in range(0xFF):\n+ data = f\"Foo: bar{chr(c)}baz\\r\\n\"\n+ if c == 0x09 or (c >= 0x20 and c != 0x7F):\n+ headers = HTTPHeaders.parse(data)\n+ self.assertEqual(headers[\"Foo\"], f\"bar{chr(c)}baz\")\n+ else:\n+ self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n+\n def test_unicode_newlines(self):\n # Ensure that only \\r\\n is recognized as a header separator, and not\n # the other newline-like unicode characters.\n@@ -311,10 +322,13 @@ Foo: even\n # and cpython's unicodeobject.c (which defines the implementation\n # of unicode_type.splitlines(), and uses a different list than TR13).\n newlines = [\n- \"\\u001b\", # VERTICAL TAB\n- \"\\u001c\", # FILE SEPARATOR\n- \"\\u001d\", # GROUP SEPARATOR\n- \"\\u001e\", # RECORD SEPARATOR\n+ # The following ascii characters are sometimes treated as newline-like,\n+ # but they're disallowed in HTTP headers. This test covers unicode\n+ # characters that are permitted in headers (under the obs-text rule).\n+ # \"\\u001b\", # VERTICAL TAB\n+ # \"\\u001c\", # FILE SEPARATOR\n+ # \"\\u001d\", # GROUP SEPARATOR\n+ # \"\\u001e\", # RECORD SEPARATOR\n \"\\u0085\", # NEXT LINE\n \"\\u2028\", # LINE SEPARATOR\n \"\\u2029\", # PARAGRAPH SEPARATOR\n@@ -363,13 +377,16 @@ Foo: even\n self.assertEqual(expected, list(headers.get_all()))\n \n def test_optional_cr(self):\n+ # Bare CR is not a valid line separator\n+ with self.assertRaises(HTTPInputError):\n+ HTTPHeaders.parse(\"CRLF: crlf\\r\\nLF: lf\\nCR: cr\\rMore: more\\r\\n\")\n+\n # Both CRLF and LF should be accepted as separators. CR should not be\n- # part of the data when followed by LF, but it is a normal char\n- # otherwise (or should bare CR be an error?)\n- headers = HTTPHeaders.parse(\"CRLF: crlf\\r\\nLF: lf\\nCR: cr\\rMore: more\\r\\n\")\n+ # part of the data when followed by LF.\n+ headers = HTTPHeaders.parse(\"CRLF: crlf\\r\\nLF: lf\\nMore: more\\r\\n\")\n self.assertEqual(\n sorted(headers.get_all()),\n- [(\"Cr\", \"cr\\rMore: more\"), (\"Crlf\", \"crlf\"), (\"Lf\", \"lf\")],\n+ [(\"Crlf\", \"crlf\"), (\"Lf\", \"lf\"), (\"More\", \"more\")],\n )\n \n def test_copy(self):\n", "FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_forbidden_ascii_characters", "tornado/test/httputil_test.py::HTTPHeadersTest::test_optional_cr"]}], "all_FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_continuation", "tornado/test/httputil_test.py::HTTPHeadersTest::test_forbidden_ascii_characters", "tornado/test/httputil_test.py::HTTPHeadersTest::test_optional_cr"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "enthought__traits-1550_x2", "level": 2, "source": "swerebenchv2", "repo": "enthought/traits", "image": "swerebenchv2/enthought-traits:1550-eb62eb6", "base_commit": "eb62eb6aa0eb30ff4540c1d07cfb36bdeccfe946", "num_bugs": 2, "bugs": [{"instance_id": "enthought__traits-1550", "base_commit": "eb62eb6aa0eb30ff4540c1d07cfb36bdeccfe946", "gold_patch": "diff --git a/traits/has_traits.py b/traits/has_traits.py\nindex 883619b3..12d3cee6 100644\n--- a/traits/has_traits.py\n+++ b/traits/has_traits.py\n@@ -36,7 +36,7 @@ from .traits import (\n Trait,\n generic_trait,\n )\n-from .trait_types import Any, Bool, Disallow, Event, Python\n+from .trait_types import Any, Bool, Disallow, Event, Python, Str\n from .trait_notifiers import (\n ExtendedTraitChangeNotifyWrapper,\n FastUITraitChangeNotifyWrapper,\n@@ -417,13 +417,25 @@ class MetaHasTraits(type):\n \n If the class name is the empty string then the listener will be called\n when *any* class is created.\n+\n+ .. deprecated:: 6.3.0\n \"\"\"\n+ warnings.warn(\n+ \"add_listener is deprecated\", DeprecationWarning, stacklevel=2\n+ )\n+\n MetaHasTraits._listeners.setdefault(class_name, []).append(listener)\n \n @classmethod\n def remove_listener(cls, listener, class_name=\"\"):\n \"\"\" Removes a class creation listener.\n+\n+ .. deprecated:: 6.3.0\n \"\"\"\n+ warnings.warn(\n+ \"remove_listener is deprecated\", DeprecationWarning, stacklevel=2\n+ )\n+\n MetaHasTraits._listeners[class_name].remove(listener)\n \n \n@@ -1111,12 +1123,13 @@ class HasTraits(CHasTraits, metaclass=MetaHasTraits):\n \n # -- Trait Definitions ----------------------------------------------------\n \n- #: An event fired when a new trait is dynamically added to the object\n- trait_added = Event(str)\n+ #: An event fired when a new trait is dynamically added to the object. The\n+ #: value is the name of the trait that was added.\n+ trait_added = Event(Str())\n \n #: An event that can be fired to indicate that the state of the object has\n- #: been modified\n- trait_modified = Event\n+ #: been modified.\n+ trait_modified = Event()\n \n def _trait_added_changed(self, name):\n \"\"\" Handles a 'trait_added' event being fired.\n", "test_patch": "diff --git a/traits/tests/test_has_traits.py b/traits/tests/test_has_traits.py\nindex e94432f7..5e39f9e2 100644\n--- a/traits/tests/test_has_traits.py\n+++ b/traits/tests/test_has_traits.py\n@@ -26,6 +26,7 @@ from traits.has_traits import (\n SingletonHasTraits,\n SingletonHasStrictTraits,\n SingletonHasPrivateTraits,\n+ MetaHasTraits,\n )\n from traits.ctrait import CTrait\n from traits.observation.api import (\n@@ -55,6 +56,21 @@ def _dummy_validator(self, value):\n pass\n \n \n+class TestMetaHasTraits(unittest.TestCase):\n+ def test_add_listener_and_remove_listener_deprecated(self):\n+ def listener(cls):\n+ pass\n+\n+ with self.assertWarnsRegex(\n+ DeprecationWarning, \"add_listener is deprecated\"\n+ ):\n+ MetaHasTraits.add_listener(listener)\n+ with self.assertWarnsRegex(\n+ DeprecationWarning, \"remove_listener is deprecated\"\n+ ):\n+ MetaHasTraits.remove_listener(listener)\n+\n+\n class TestCreateTraitsMetaDict(unittest.TestCase):\n def test_class_attributes(self):\n # Given\n", "FAIL_TO_PASS": ["traits/tests/test_has_traits.py::TestMetaHasTraits::test_add_listener_and_remove_listener_deprecated"]}, {"instance_id": "enthought__traits-1560", "base_commit": "5c775b49c4fb7ed10478b9b58e08856406fba7c1", "gold_patch": "diff --git a/docs/source/traits_user_manual/index.rst b/docs/source/traits_user_manual/index.rst\nindex 9ef76d03..81e2042b 100644\n--- a/docs/source/traits_user_manual/index.rst\n+++ b/docs/source/traits_user_manual/index.rst\n@@ -13,6 +13,7 @@ Contents\n :maxdepth: 3\n \n intro.rst\n+ installation.rst\n defining.rst\n notification.rst\n deferring.rst\ndiff --git a/docs/source/traits_user_manual/installation.rst b/docs/source/traits_user_manual/installation.rst\nnew file mode 100644\nindex 00000000..65842ef3\n--- /dev/null\n+++ b/docs/source/traits_user_manual/installation.rst\n@@ -0,0 +1,30 @@\n+.. index:: installation\n+\n+.. _installation:\n+\n+============\n+Installation\n+============\n+\n+The latest release of Traits is available from the Python Package Index (PyPI),\n+and the normal way to install Traits into your Python environment is using\n+pip::\n+\n+ python -m pip install traits\n+\n+Traits includes a C extension module. Binary wheels are provided on PyPI for\n+common platforms, but some platforms may need to compile Traits from source. On\n+those platforms, a suitable C compiler will be needed.\n+\n+\n+Installation from source on macOS\n+---------------------------------\n+\n+The system Python 3.8 on macOS Catalina has trouble installing Traits from\n+source, due to an apparent mismatch in architecture settings. This issue can\n+be worked around by specifying the \"ARCHFLAGS\" environment variable for\n+the install::\n+\n+ ARCHFLAGS=\"-arch x86_64\" python -m pip install traits\n+\n+See https://github.com/enthought/traits/issues/1337 for more details.\ndiff --git a/docs/source/traits_user_manual/listening.rst b/docs/source/traits_user_manual/listening.rst\nindex 274e468f..6ae7fc6f 100644\n--- a/docs/source/traits_user_manual/listening.rst\n+++ b/docs/source/traits_user_manual/listening.rst\n@@ -539,6 +539,17 @@ The arguments that are passed to the trait attribute change notification\n method depend on the method signature and on which type of static notification\n handler it is.\n \n+.. note::\n+ The :func:`~.on_trait_change` and :func:`~.observe` decorators nullify\n+ the effect of special naming. A method that looks like::\n+\n+ @observe(\"foo\")\n+ def _foo_changed(self, event):\n+ do_something_with(event)\n+\n+ will only be called once when ``foo`` changes, as a result of the\n+ ``observe`` decorator.\n+\n .. _attribute-specific-handler-signatures:\n \n Attribute-specific Handler Signatures\ndiff --git a/traits/has_traits.py b/traits/has_traits.py\nindex 12d3cee6..0962098d 100644\n--- a/traits/has_traits.py\n+++ b/traits/has_traits.py\n@@ -162,6 +162,7 @@ def _get_def(class_name, class_dict, bases, method):\n (result is not None)\n and is_unbound_method_type(result)\n and (getattr(result, \"on_trait_change\", None) is None)\n+ and (getattr(result, \"_observe_inputs\", None) is None)\n ):\n return result\n \n@@ -171,6 +172,7 @@ def _get_def(class_name, class_dict, bases, method):\n (result is not None)\n and is_unbound_method_type(result)\n and (getattr(result, \"on_trait_change\", None) is None)\n+ and (getattr(result, \"_observe_inputs\", None) is None)\n ):\n return result\n \n", "test_patch": "diff --git a/traits/tests/test_has_traits.py b/traits/tests/test_has_traits.py\nindex 5e39f9e2..3c98ff45 100644\n--- a/traits/tests/test_has_traits.py\n+++ b/traits/tests/test_has_traits.py\n@@ -604,6 +604,68 @@ class TestHasTraits(unittest.TestCase):\n {\"foo\": A.class_traits()[\"foo\"]},\n )\n \n+ def test_decorated_changed_method(self):\n+ # xref: enthought/traits#527\n+ # Traits should ignore the _changed magic naming.\n+\n+ events = []\n+\n+ class A(HasTraits):\n+ foo = Int()\n+\n+ @on_trait_change(\"foo\")\n+ def _foo_changed(self, obj, name, old, new):\n+ events.append((obj, name, old, new))\n+\n+ a = A()\n+ a.foo = 23\n+ self.assertEqual(\n+ events,\n+ [(a, \"foo\", 0, 23)],\n+ )\n+\n+ def test_observed_changed_method(self):\n+ events = []\n+\n+ class A(HasTraits):\n+ foo = Int()\n+\n+ @observe(\"foo\")\n+ def _foo_changed(self, event):\n+ events.append(event)\n+\n+ a = A()\n+ a.foo = 23\n+ self.assertEqual(len(events), 1)\n+ event = events[0]\n+ self.assertEqual(event.object, a)\n+ self.assertEqual(event.name, \"foo\")\n+ self.assertEqual(event.old, 0)\n+ self.assertEqual(event.new, 23)\n+\n+ def test_decorated_changed_method_subclass(self):\n+ # xref: enthought/traits#527\n+ # Traits should ignore the _changed magic naming.\n+\n+ events = []\n+\n+ class A(HasTraits):\n+ foo = Int()\n+\n+ @on_trait_change(\"foo\")\n+ def _foo_changed(self, obj, name, old, new):\n+ events.append((obj, name, old, new))\n+\n+ class B(A):\n+ pass\n+\n+ a = B()\n+ a.foo = 23\n+ self.assertEqual(\n+ events,\n+ [(a, \"foo\", 0, 23)],\n+ )\n+\n \n class TestObjectNotifiers(unittest.TestCase):\n \"\"\" Test calling object notifiers. \"\"\"\n", "FAIL_TO_PASS": ["traits/tests/test_has_traits.py::TestHasTraits::test_observed_changed_method"]}], "all_FAIL_TO_PASS": ["traits/tests/test_has_traits.py::TestMetaHasTraits::test_add_listener_and_remove_listener_deprecated", "traits/tests/test_has_traits.py::TestHasTraits::test_observed_changed_method"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "rochacbruno__dynaconf-292_x2", "level": 2, "source": "swerebenchv2", "repo": "rochacbruno/dynaconf", "image": "swerebenchv2/rochacbruno-dynaconf:292-b0bc78d", "base_commit": "b0bc78de719fc8c3a0180be9aaea1d233a3dab86", "num_bugs": 2, "bugs": [{"instance_id": "rochacbruno__dynaconf-292", "base_commit": "b0bc78de719fc8c3a0180be9aaea1d233a3dab86", "gold_patch": "diff --git a/Makefile b/Makefile\nindex 62c0e41..2880947 100644\n--- a/Makefile\n+++ b/Makefile\n@@ -14,6 +14,7 @@ test_examples:\n \tcd example/;pwd;python compat.py\n \tcd example/app;pwd;python app.py\n \tcd example/dunder;pwd;python app.py\n+\tcd example/format;pwd;python app.py\n \tcd example/app_with_dotenv;pwd;python app.py\n \tcd example/merge_enabled;pwd;python app.py\n \tcd example/new_merge;pwd;python app.py\ndiff --git a/docs/guides/environment_variables.md b/docs/guides/environment_variables.md\nindex 5c92425..46675b7 100644\n--- a/docs/guides/environment_variables.md\n+++ b/docs/guides/environment_variables.md\n@@ -54,6 +54,14 @@ DYNACONF_NONE='@none None'\n \n # toml syntax does not allow mixed type arrays so use @json\n DYNACONF_ARRAY='@json [42, 3.14, \"hello\", true, [\"otherarray\"], {\"foo\": \"bar\"}]'\n+\n+# Lazily formatted string can access env vars and settings variables.\n+\n+# using str.format\n+DYNACONF_DATABASE_PATH=\"@format {env[HOME]}/.config/databases/{this.DB_NAME}\"\n+\n+# using jinja2\n+DYNACONF_DATABASE_PATH=\"@jinja {{env.HOME}}/.config/databases/{{this.DB_NAME}}\"\n ```\n \n > **NOTE**: Older versions of Dynaconf used the `@casting` prefixes for env vars like `export DYNACONF_INTEGER='@int 123'` still works but this casting is deprecated in favor of using TOML syntax described above. To disable the `@casting` do `export AUTO_CAST_FOR_DYNACONF=false`\ndiff --git a/docs/guides/usage.md b/docs/guides/usage.md\nindex 6cb3890..8cc02dd 100644\n--- a/docs/guides/usage.md\n+++ b/docs/guides/usage.md\n@@ -501,7 +501,85 @@ settings.load_file(path=\"/path/to/file.toml\") # list or `;/,` separated allowed\n \n > **NOTE**: programmatically loaded file is not persisted, once `env` is changed via `setenv|ugin_env`, or a `reload` or `configure` is invoked it will be cleaned, to persist it needs to go to `INCLUDES_FOR_DYNACONF` variable or you need to load it programmatically again.\n \n-## Merging existing values\n+## Template substitutions\n+\n+Dynaconf has 2 tokens to enable string substitutions `@format` and `@jinja`.\n+\n+### @format token\n+\n+Dynaconf allows template substitutions for strings values, by using the `@format` token prefix and including placeholders accepted by Python's `str.format` method Dynaconf will call\n+it lazily upon access time.\n+\n+The call will be like:\n+\n+```py\n+\"\".format(env=os.environ, this=dynaconf.settings)\n+```\n+\n+So in your string you can refer to environment variables via `env` object, and also to variables defined int the settings object itself via `this` reference. It is lazily evaluated on access it will use the final value for a settings regardless the order of load.\n+\n+Example:\n+\n+```bash\n+export PROGRAM_NAME=calculator\n+```\n+\n+settings.toml\n+\n+```toml\n+[default]\n+DB_NAME = \"mydb.db\"\n+\n+[development]\n+DB_PATH = \"@format {env[HOME]}/{this.current_env}/{env[PROGRAM_NAME]}/{this.DB_NAME}\"\n+```\n+\n+- `{env[HOME]}` is the same as `os.environ[\"HOME\"]` or `$HOME` in the shell.\n+- `{this.current_env}` is the same as `settings.current_env`\n+- `{env[PROGRAM_NAME]}` is the same as `os.environ[\"PROGRAM_NAME\"]` or `$PROGRAM_NAME` in the shell.\n+- `{this.DB_NAME}` is the same as `settins.DB_NAME` or `settings[\"DB_NAME\"]`\n+\n+so in your `program`\n+\n+```py\n+from dynaconf import settings\n+\n+settings.DB_PATH == '~/DEVELOPMENT/calculator/mydb.db'\n+```\n+\n+### @jinja token\n+\n+If `jinja2` package is installed then dynaconf will also allow the use jinja to render string values.\n+\n+Example:\n+\n+```bash\n+export PROGRAM_NAME=calculator\n+```\n+\n+settings.toml\n+\n+```toml\n+[default]\n+DB_NAME = \"mydb.db\"\n+\n+[development]\n+DB_PATH = \"@jinja {{env.HOME}}/{{this.current_env | lower}}/{{env['PROGRAM_NAME']}}/{{this.DB_NAME}}\"\n+```\n+\n+so in your `program`\n+\n+```py\n+from dynaconf import settings\n+\n+settings.DB_PATH == '~/development/calculator/mydb.db'\n+```\n+\n+The main difference is that Jinja allows some Python expressions to be avaluated such as `{% for, if, while %}` and also supports calling methods and has lots of filters like `| lower`.\n+\n+Jinja supports its built-in filters listed in [Builtin Filters Page](http://jinja.palletsprojects.com/en/master/templates/#builtin-filters) and Dynaconf includes aditional filters for `os.path` module: `abspath`. `realpath`, `relpath`, `basename` and `dirname` and usage is like: `VALUE = \"@jinja {{this.FOO | abspath}}\"`\n+\n+## Merging existing data structures\n \n If your settings has existing variables of types `list` ot `dict` and you want to `merge` instead of `override` then \n the `dynaconf_merge` and `dynaconf_merge_unique` stanzas can mark that variable as a candidate for merging.\ndiff --git a/dynaconf/base.py b/dynaconf/base.py\nindex db7fef5..b6a96d1 100644\n--- a/dynaconf/base.py\n+++ b/dynaconf/base.py\n@@ -25,6 +25,7 @@ from dynaconf.utils.files import find_file\n from dynaconf.utils.functional import empty\n from dynaconf.utils.functional import LazyObject\n from dynaconf.utils.parse_conf import converters\n+from dynaconf.utils.parse_conf import evaluate_lazy_format\n from dynaconf.utils.parse_conf import parse_conf_data\n from dynaconf.utils.parse_conf import true_values\n from dynaconf.validator import ValidatorList\n@@ -90,6 +91,7 @@ class LazySettings(LazyObject):\n self._kwargs = kwargs\n super(LazySettings, self).__init__()\n \n+ @evaluate_lazy_format\n def __getattr__(self, name):\n \"\"\"Allow getting keys from self.store using dot notation\"\"\"\n if self._wrapped is empty:\n@@ -276,6 +278,7 @@ class Settings(object):\n \".\".join(keys), default=default, parent=result, **kwargs\n )\n \n+ @evaluate_lazy_format\n def get(\n self,\n key,\ndiff --git a/dynaconf/utils/parse_conf.py b/dynaconf/utils/parse_conf.py\nindex d9fc4c5..d33673f 100644\n--- a/dynaconf/utils/parse_conf.py\n+++ b/dynaconf/utils/parse_conf.py\n@@ -1,11 +1,21 @@\n import json\n import os\n+from functools import wraps\n \n import toml\n from box import BoxKeyError\n \n from dynaconf.utils.boxing import DynaBox\n \n+try:\n+ from jinja2 import Environment\n+\n+ jinja_env = Environment()\n+ for p_method in (\"abspath\", \"realpath\", \"relpath\", \"dirname\", \"basename\"):\n+ jinja_env.filters[p_method] = getattr(os.path, p_method)\n+except ImportError: # pragma: no cover\n+ jinja_env = None\n+\n true_values = (\"t\", \"true\", \"enabled\", \"1\", \"on\", \"yes\", \"True\")\n false_values = (\"f\", \"false\", \"disabled\", \"0\", \"off\", \"no\", \"False\", \"\")\n \n@@ -42,13 +52,55 @@ class Merge(MetaValue):\n dynaconf_merge = True\n \n \n+class LazyFormat:\n+ \"\"\"Holds data to format lazily.\"\"\"\n+\n+ dynaconf_lazy_format = True\n+\n+ def __init__(self, value, formatter=str.format):\n+ self.value = value\n+ self.formatter = formatter\n+\n+ @property\n+ def context(self):\n+ \"\"\"Builds a context for formatting.\"\"\"\n+ return {\"env\": os.environ, \"this\": self.settings}\n+\n+ def __call__(self, settings):\n+ \"\"\"LazyValue triggers format lazily.\"\"\"\n+ self.settings = settings\n+ return self.formatter(self.value, **self.context)\n+\n+\n+def evaluate_lazy_format(f):\n+ \"\"\"Marks a method on Settings instance to\n+ lazily evaluate LazyFormat objects upon access.\"\"\"\n+\n+ @wraps(f)\n+ def evaluate(settings, *args, **kwargs):\n+ value = f(settings, *args, **kwargs)\n+ if getattr(value, \"dynaconf_lazy_format\", None):\n+ return value(settings)\n+ return value\n+\n+ return evaluate\n+\n+\n+def jinja_formatter(value, **context):\n+ if jinja_env is None: # pragma: no cover\n+ raise ImportError(\n+ \"jinja2 must be installed to enable '@jinja' settings in dynaconf\"\n+ )\n+ return jinja_env.from_string(value).render(**context)\n+\n+\n converters = {\n \"@int\": int,\n \"@float\": float,\n- \"@bool\": (\n- lambda value: True if str(value).lower() in true_values else False\n- ),\n+ \"@bool\": lambda value: str(value).lower() in true_values,\n \"@json\": json.loads,\n+ \"@format\": lambda value: LazyFormat(value),\n+ \"@jinja\": lambda value: LazyFormat(value, formatter=jinja_formatter),\n # Meta Values to trigger pre assignment actions\n \"@reset\": lambda value: Reset(value),\n \"@del\": lambda value: Del(value),\ndiff --git a/example/format/.env b/example/format/.env\nnew file mode 100644\nindex 0000000..bf7bb51\n--- /dev/null\n+++ b/example/format/.env\n@@ -0,0 +1,1 @@\n+USERNAME='robert_plant'\ndiff --git a/example/format/app.py b/example/format/app.py\nnew file mode 100644\nindex 0000000..234dd3d\n--- /dev/null\n+++ b/example/format/app.py\n@@ -0,0 +1,18 @@\n+import os\n+\n+from dynaconf import settings\n+\n+assert settings.get(\"USERNAME\") is None\n+assert settings.DATABASE_NAME == \"my_database.db\"\n+assert os.environ[\"USERNAME\"] == \"robert_plant\"\n+\n+DB_PATH = \"/home/robert_plant/databases/my_database.db\"\n+assert settings.DATABASE_PATH == DB_PATH, settings.DATABASE_PATH\n+print(settings.DATABASE_PATH)\n+\n+\n+DB_PATH_JINJA = \"/home/robert_plant/development/my_database.db\"\n+assert (\n+ settings.DATABASE_PATH_JINJA == DB_PATH_JINJA\n+), settings.DATABASE_PATH_JINJA\n+print(settings.DATABASE_PATH_JINJA)\ndiff --git a/example/format/settings.toml b/example/format/settings.toml\nnew file mode 100644\nindex 0000000..4b90106\n--- /dev/null\n+++ b/example/format/settings.toml\n@@ -0,0 +1,6 @@\n+[default]\n+database_name = 'my_database.db'\n+\n+[development]\n+database_path = '@format /home/{env[USERNAME]}/databases/{this[database_name]}'\n+database_path_jinja = '@jinja /home/{{env.USERNAME}}/{{this.current_env | lower}}/{{this[\"database_name\"] }}'\n", "test_patch": "diff --git a/tests/test_utils.py b/tests/test_utils.py\nindex 1abc3cd..a5e28a5 100644\n--- a/tests/test_utils.py\n+++ b/tests/test_utils.py\n@@ -12,6 +12,9 @@ from dynaconf.utils import trimmed_split\n from dynaconf.utils import upperfy\n from dynaconf.utils.files import find_file\n from dynaconf.utils.files import get_local_filename\n+from dynaconf.utils.parse_conf import evaluate_lazy_format\n+from dynaconf.utils.parse_conf import jinja_formatter\n+from dynaconf.utils.parse_conf import LazyFormat\n from dynaconf.utils.parse_conf import parse_conf_data\n from dynaconf.utils.parse_conf import unparse_conf_data\n \n@@ -242,3 +245,59 @@ def test_upperfy():\n )\n assert upperfy(\"foo_bar\") == \"FOO_BAR\"\n assert upperfy(\"foo_BAR\") == \"FOO_BAR\"\n+\n+\n+def test_lazy_format_class():\n+ value = LazyFormat(\"{this[FOO]}/bar\")\n+ settings = {\"FOO\": \"foo\"}\n+ assert value(settings) == \"foo/bar\"\n+\n+\n+def test_evaluate_lazy_format_decorator():\n+ class Settings:\n+ FOO = \"foo\"\n+\n+ @evaluate_lazy_format\n+ def get(self):\n+ return parse_conf_data(\"@format {this.FOO}/bar\")\n+\n+ settings = Settings()\n+ assert settings.get() == \"foo/bar\"\n+\n+\n+def test_lazy_format_on_settings(settings):\n+ os.environ[\"ENV_THING\"] = \"LazyFormat\"\n+ settings.set(\"set_1\", \"really\")\n+ settings.set(\"lazy\", \"@format {env[ENV_THING]}/{this[set_1]}/{this.SET_2}\")\n+ settings.set(\"set_2\", \"works\")\n+\n+ assert settings.LAZY == settings.get(\"lazy\") == \"LazyFormat/really/works\"\n+\n+\n+def test_lazy_format_class_jinja():\n+ value = LazyFormat(\"{{this['FOO']}}/bar\", formatter=jinja_formatter)\n+ settings = {\"FOO\": \"foo\"}\n+ assert value(settings) == \"foo/bar\"\n+\n+\n+def test_evaluate_lazy_format_decorator_jinja():\n+ class Settings:\n+ FOO = \"foo\"\n+\n+ @evaluate_lazy_format\n+ def get(self):\n+ return parse_conf_data(\"@jinja {{this.FOO}}/bar\")\n+\n+ settings = Settings()\n+ assert settings.get() == \"foo/bar\"\n+\n+\n+def test_lazy_format_on_settings_jinja(settings):\n+ os.environ[\"ENV_THING\"] = \"LazyFormat\"\n+ settings.set(\"set_1\", \"really\")\n+ settings.set(\n+ \"lazy\", \"@jinja {{env.ENV_THING}}/{{this['set_1']}}/{{this.SET_2}}\"\n+ )\n+ settings.set(\"set_2\", \"works\")\n+\n+ assert settings.LAZY == settings.get(\"lazy\") == \"LazyFormat/really/works\"\n", "FAIL_TO_PASS": ["tests/test_utils.py::test_unparse", "tests/test_utils.py::test_cast_bool", "tests/test_utils.py::test_find_file", "tests/test_utils.py::test_disable_cast", "tests/test_utils.py::test_tomlfy", "tests/test_utils.py::test_tomlfy_unparseable[something=42]", "tests/test_utils.py::test_missing_sentinel", "tests/test_utils.py::test_meta_values", "tests/test_utils.py::test_merge_existing_list", "tests/test_utils.py::test_merge_existing_list_unique", "tests/test_utils.py::test_merge_existing_dict", "tests/test_utils.py::test_merge_dict_with_meta_values", "tests/test_utils.py::test_trimmed_split", "tests/test_utils.py::test_ensure_a_list", "tests/test_utils.py::test_get_local_filename", "tests/test_utils.py::test_upperfy", "tests/test_utils.py::test_lazy_format_class", "tests/test_utils.py::test_evaluate_lazy_format_decorator", "tests/test_utils.py::test_lazy_format_on_settings"]}, {"instance_id": "rochacbruno__dynaconf-300", "base_commit": "c4d93e2e481808309d75a0288e6053699859f32a", "gold_patch": "diff --git a/Makefile b/Makefile\nindex 65139e5..3a9136d 100644\n--- a/Makefile\n+++ b/Makefile\n@@ -91,6 +91,7 @@ test_examples:\n \tcd example/issues/228_nested_toml_bool/django_app;pwd;python manage.py test\n \tcd example/issues/251_dotted_unexistent;pwd;python app.py\n \tcd example/issues/266_envvar_from_env_override;pwd;python app.py\n+\tcd example/issues/288_null_values;pwd;python app.py\n test_vault:\n \t# @cd example/vault;pwd;python write.py\n \tdocker run --rm --name dynaconf_with_vault -d -e 'VAULT_DEV_ROOT_TOKEN_ID=myroot' -p 8200:8200 vault\ndiff --git a/azure-pipelines.yml b/azure-pipelines.yml\nindex 0cd90b4..9e7ef19 100644\n--- a/azure-pipelines.yml\n+++ b/azure-pipelines.yml\n@@ -3,6 +3,10 @@\n # Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more:\n # https://docs.microsoft.com/azure/devops/pipelines/languages/python\n \n+pr:\n+- master\n+- releases/*\n+\n trigger:\n - master\n \ndiff --git a/dynaconf/base.py b/dynaconf/base.py\nindex 57f9aa7..99b44ba 100644\n--- a/dynaconf/base.py\n+++ b/dynaconf/base.py\n@@ -219,9 +219,9 @@ class Settings(object):\n \n def __getitem__(self, item):\n \"\"\"Allow getting variables as dict keys `settings['KEY']`\"\"\"\n- value = self.get(item)\n- if value is None:\n- raise KeyError(\"{0} does not exists\".format(item))\n+ value = self.get(item, default=empty)\n+ if value is empty:\n+ raise KeyError(\"{0} does not exist\".format(item))\n return value\n \n def __setitem__(self, key, value):\ndiff --git a/dynaconf/loaders/__init__.py b/dynaconf/loaders/__init__.py\nindex d0a9939..ae7fb03 100644\n--- a/dynaconf/loaders/__init__.py\n+++ b/dynaconf/loaders/__init__.py\n@@ -196,7 +196,7 @@ def write(filename, data, env=None):\n raise IOError(\"{0} cannot be found.\".format(loader_name))\n \n data = DynaBox(data).to_dict()\n- if env and env not in data:\n+ if loader is not py_loader and env and env not in data:\n data = {env: data}\n \n loader.write(filename, data, merge=False)\ndiff --git a/dynaconf/loaders/toml_loader.py b/dynaconf/loaders/toml_loader.py\nindex 86892b1..17cfc0d 100644\n--- a/dynaconf/loaders/toml_loader.py\n+++ b/dynaconf/loaders/toml_loader.py\n@@ -57,4 +57,15 @@ def write(settings_path, settings_data, merge=True):\n \"w\",\n encoding=default_settings.ENCODING_FOR_DYNACONF,\n ) as open_file:\n- toml.dump(settings_data, open_file)\n+ toml.dump(encode_nulls(settings_data), open_file)\n+\n+\n+def encode_nulls(data):\n+ \"\"\"TOML does not support `None` so this function transforms to '@none '.\"\"\"\n+ if data is None:\n+ return \"@none \"\n+ if isinstance(data, dict):\n+ return {key: encode_nulls(value) for key, value in data.items()}\n+ elif isinstance(data, (list, tuple)):\n+ return [encode_nulls(item) for item in data]\n+ return data\ndiff --git a/dynaconf/utils/boxing.py b/dynaconf/utils/boxing.py\nindex f163b56..1613bd9 100644\n--- a/dynaconf/utils/boxing.py\n+++ b/dynaconf/utils/boxing.py\n@@ -28,8 +28,6 @@ class DynaBox(Box):\n return self.__class__(super(Box, self).copy())\n \n def get(self, item, default=None, *args, **kwargs):\n- value = super(DynaBox, self).get(item, default, *args, **kwargs)\n- if value is None or value == default:\n- n_item = item.lower() if item.isupper() else upperfy(item)\n- value = super(DynaBox, self).get(n_item, default, *args, **kwargs)\n- return value\n+ if item not in self: # toggle case\n+ item = item.lower() if item.isupper() else upperfy(item)\n+ return super(DynaBox, self).get(item, default, *args, **kwargs)\ndiff --git a/example/issues/288_null_values/.env b/example/issues/288_null_values/.env\nnew file mode 100644\nindex 0000000..e69de29\ndiff --git a/example/issues/288_null_values/app.py b/example/issues/288_null_values/app.py\nnew file mode 100644\nindex 0000000..016ef07\n--- /dev/null\n+++ b/example/issues/288_null_values/app.py\n@@ -0,0 +1,8 @@\n+from dynaconf import settings\n+\n+assert settings[\"NULLED_VALUE_PYTHON\"] is None\n+assert settings[\"nulled_value_json\"] is None\n+assert settings[\"nulled_value_yaml\"] is None\n+assert settings[\"nulled_value_toml\"] is None\n+\n+print(\"#288 PASSED\")\ndiff --git a/example/issues/288_null_values/settings.json b/example/issues/288_null_values/settings.json\nnew file mode 100644\nindex 0000000..eef4cf1\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.json\n@@ -0,0 +1,5 @@\n+{\n+ \"default\": {\n+ \"nulled_value_json\": null\n+ }\n+}\ndiff --git a/example/issues/288_null_values/settings.py b/example/issues/288_null_values/settings.py\nnew file mode 100644\nindex 0000000..c82da42\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.py\n@@ -0,0 +1,1 @@\n+NULLED_VALUE_PYTHON = None\ndiff --git a/example/issues/288_null_values/settings.toml b/example/issues/288_null_values/settings.toml\nnew file mode 100644\nindex 0000000..9a04eee\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.toml\n@@ -0,0 +1,2 @@\n+[default]\n+nulled_value_toml = \"@none \"\ndiff --git a/example/issues/288_null_values/settings.yaml b/example/issues/288_null_values/settings.yaml\nnew file mode 100644\nindex 0000000..25a1cb4\n--- /dev/null\n+++ b/example/issues/288_null_values/settings.yaml\n@@ -0,0 +1,2 @@\n+default:\n+ nulled_value_yaml: null\n", "test_patch": "diff --git a/tests/test_toml_loader.py b/tests/test_toml_loader.py\nindex 6694798..6dd2609 100644\n--- a/tests/test_toml_loader.py\n+++ b/tests/test_toml_loader.py\n@@ -1,6 +1,7 @@\n import pytest\n \n from dynaconf import LazySettings\n+from dynaconf.loaders.toml_loader import encode_nulls\n from dynaconf.loaders.toml_loader import load\n \n settings = LazySettings(ENV_FOR_DYNACONF=\"PRODUCTION\")\n@@ -179,3 +180,16 @@ def test_load_dunder():\n load(settings, filename=toml, env=\"FOO\")\n assert settings.COLORS.gray.code == \"#CCCCCC\"\n assert settings.COLORS.gray.name == \"Gray\"\n+\n+\n+def test_encode_nulls():\n+ assert encode_nulls(None) == \"@none \"\n+ assert encode_nulls([None, None]) == [\"@none \", \"@none \"]\n+ assert encode_nulls((None, None)) == [\"@none \", \"@none \"]\n+ assert encode_nulls({\"nullable\": None}) == {\"nullable\": \"@none \"}\n+ assert encode_nulls(1) == 1\n+ assert encode_nulls(1.1) == 1.1\n+ assert encode_nulls(True) is True\n+ assert encode_nulls(False) is False\n+ assert encode_nulls(\"\") == \"\"\n+ assert encode_nulls(\"text\") == \"text\"\n", "FAIL_TO_PASS": ["tests/test_toml_loader.py::test_load_from_toml", "tests/test_toml_loader.py::test_load_from_multiple_toml", "tests/test_toml_loader.py::test_no_filename_is_none", "tests/test_toml_loader.py::test_key_error_on_invalid_env", "tests/test_toml_loader.py::test_no_key_error_on_invalid_env", "tests/test_toml_loader.py::test_load_single_key", "tests/test_toml_loader.py::test_empty_value", "tests/test_toml_loader.py::test_multiple_filenames", "tests/test_toml_loader.py::test_cleaner", "tests/test_toml_loader.py::test_using_env", "tests/test_toml_loader.py::test_load_dunder", "tests/test_toml_loader.py::test_encode_nulls"]}], "all_FAIL_TO_PASS": ["tests/test_utils.py::test_unparse", "tests/test_utils.py::test_cast_bool", "tests/test_utils.py::test_find_file", "tests/test_utils.py::test_disable_cast", "tests/test_utils.py::test_tomlfy", "tests/test_utils.py::test_tomlfy_unparseable[something=42]", "tests/test_utils.py::test_missing_sentinel", "tests/test_utils.py::test_meta_values", "tests/test_utils.py::test_merge_existing_list", "tests/test_utils.py::test_merge_existing_list_unique", "tests/test_utils.py::test_merge_existing_dict", "tests/test_utils.py::test_merge_dict_with_meta_values", "tests/test_utils.py::test_trimmed_split", "tests/test_utils.py::test_ensure_a_list", "tests/test_utils.py::test_get_local_filename", "tests/test_utils.py::test_upperfy", "tests/test_utils.py::test_lazy_format_class", "tests/test_utils.py::test_evaluate_lazy_format_decorator", "tests/test_utils.py::test_lazy_format_on_settings", "tests/test_toml_loader.py::test_load_from_toml", "tests/test_toml_loader.py::test_load_from_multiple_toml", "tests/test_toml_loader.py::test_no_filename_is_none", "tests/test_toml_loader.py::test_key_error_on_invalid_env", "tests/test_toml_loader.py::test_no_key_error_on_invalid_env", "tests/test_toml_loader.py::test_load_single_key", "tests/test_toml_loader.py::test_empty_value", "tests/test_toml_loader.py::test_multiple_filenames", "tests/test_toml_loader.py::test_cleaner", "tests/test_toml_loader.py::test_using_env", "tests/test_toml_loader.py::test_load_dunder", "tests/test_toml_loader.py::test_encode_nulls"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pytask-dev__pytask-285_x2", "level": 2, "source": "swerebenchv2", "repo": "pytask-dev/pytask", "image": "swerebenchv2/pytask-dev-pytask:285-3575ede", "base_commit": "3575ede210b182494dc918cd7097245e7721e4ba", "num_bugs": 2, "bugs": [{"instance_id": "pytask-dev__pytask-285", "base_commit": "3575ede210b182494dc918cd7097245e7721e4ba", "gold_patch": "diff --git a/docs/source/changes.md b/docs/source/changes.md\nindex 5f30e3a..c05fd9e 100644\n--- a/docs/source/changes.md\n+++ b/docs/source/changes.md\n@@ -5,7 +5,15 @@ chronological order. Releases follow [semantic versioning](https://semver.org/)\n releases are available on [PyPI](https://pypi.org/project/pytask) and\n [Anaconda.org](https://anaconda.org/conda-forge/pytask).\n \n-## 0.2.3 - 2022-xx-xx\n+## 0.2.4 - 2022-xx-xx\n+\n+- {pull}`279` enhances some tutorials with spell and grammar checking.\n+- {pull}`282` updates the tox configuration.\n+- {pull}`283` fixes an issue with coverage and tests using pexpect + `pdb.set_trace()`.\n+- {pull}`285` implements that pytask does not show the traceback of tasks which are\n+ skipped because its previous task failed. Fixes {issue}`284`.\n+\n+## 0.2.3 - 2022-05-30\n \n - {pull}`276` fixes `pytask clean` when git is not installed. Fixes {issue}`275`.\n - {pull}`277` ignores `DeprecationWarning` and `PendingDeprecationWarning` by default.\ndiff --git a/src/_pytask/execute.py b/src/_pytask/execute.py\nindex 8c1609e..320bda7 100644\n--- a/src/_pytask/execute.py\n+++ b/src/_pytask/execute.py\n@@ -250,7 +250,10 @@ def pytask_execute_log_end(session: Session, reports: list[ExecutionReport]) ->\n console.print()\n \n for report in reports:\n- if report.outcome in (TaskOutcome.FAIL, TaskOutcome.SKIP_PREVIOUS_FAILED):\n+ if report.outcome == TaskOutcome.FAIL or (\n+ report.outcome == TaskOutcome.SKIP_PREVIOUS_FAILED\n+ and session.config[\"verbose\"] >= 2\n+ ):\n _print_errored_task_report(session, report)\n \n console.rule(style=\"dim\")\n", "test_patch": "diff --git a/tests/test_execute.py b/tests/test_execute.py\nindex 672efbc..aa1e80a 100644\n--- a/tests/test_execute.py\n+++ b/tests/test_execute.py\n@@ -308,3 +308,25 @@ def test_show_errors_immediately(runner, tmp_path, show_errors_immediately):\n assert len(matches_traceback) == 2\n else:\n assert len(matches_traceback) == 1\n+\n+\n+@pytest.mark.end_to_end\n+@pytest.mark.parametrize(\"verbose\", [1, 2])\n+def test_traceback_of_previous_task_failed_is_not_shown(runner, tmp_path, verbose):\n+ source = \"\"\"\n+ import pytask\n+\n+ @pytask.mark.produces(\"in.txt\")\n+ def task_first(): raise ValueError\n+\n+ @pytask.mark.depends_on(\"in.txt\")\n+ def task_second(): pass\n+ \"\"\"\n+ tmp_path.joinpath(\"task_example.py\").write_text(textwrap.dedent(source))\n+\n+ result = runner.invoke(cli, [tmp_path.as_posix(), \"--verbose\", str(verbose)])\n+\n+ assert result.exit_code == ExitCode.FAILED\n+ assert (\"Task task_example.py::task_second failed\" in result.output) is (\n+ verbose == 2\n+ )\n", "FAIL_TO_PASS": ["tests/test_execute.py::test_traceback_of_previous_task_failed_is_not_shown[1]"]}, {"instance_id": "pytask-dev__pytask-287", "base_commit": "74ad361c5aeb85909afd0f4fd37c92f1c09af184", "gold_patch": "diff --git a/docs/source/changes.md b/docs/source/changes.md\nindex c05fd9e..be3ae4f 100644\n--- a/docs/source/changes.md\n+++ b/docs/source/changes.md\n@@ -12,6 +12,8 @@ releases are available on [PyPI](https://pypi.org/project/pytask) and\n - {pull}`283` fixes an issue with coverage and tests using pexpect + `pdb.set_trace()`.\n - {pull}`285` implements that pytask does not show the traceback of tasks which are\n skipped because its previous task failed. Fixes {issue}`284`.\n+- {pull}`287` changes that all files that are not produced by a task are displayed in\n+ the error message. Fixes {issue}`262`.\n \n ## 0.2.3 - 2022-05-30\n \ndiff --git a/src/_pytask/execute.py b/src/_pytask/execute.py\nindex 320bda7..f7380fb 100644\n--- a/src/_pytask/execute.py\n+++ b/src/_pytask/execute.py\n@@ -11,6 +11,7 @@ from _pytask.config_utils import ShowCapture\n from _pytask.console import console\n from _pytask.console import create_summary_panel\n from _pytask.console import create_url_style_for_task\n+from _pytask.console import format_strings_as_flat_tree\n from _pytask.console import format_task_id\n from _pytask.console import unify_styles\n from _pytask.dag import descending_tasks\n@@ -27,6 +28,7 @@ from _pytask.outcomes import TaskOutcome\n from _pytask.report import ExecutionReport\n from _pytask.session import Session\n from _pytask.shared import get_first_non_none_value\n+from _pytask.shared import reduce_node_name\n from _pytask.traceback import format_exception_without_traceback\n from _pytask.traceback import remove_traceback_from_exc_info\n from _pytask.traceback import render_exc_info\n@@ -167,15 +169,23 @@ def pytask_execute_task(task: Task) -> bool:\n \n @hookimpl\n def pytask_execute_task_teardown(session: Session, task: Task) -> None:\n- \"\"\"Check if each produced node was indeed produced.\"\"\"\n+ \"\"\"Check if :class:`_pytask.nodes.FilePathNode` are produced by a task.\"\"\"\n+ missing_nodes = []\n for product in session.dag.successors(task.name):\n node = session.dag.nodes[product][\"node\"]\n- try:\n- node.state()\n- except NodeNotFoundError as e:\n- raise NodeNotFoundError(\n- f\"{node.name} was not produced by {task.name}.\"\n- ) from e\n+ if isinstance(node, FilePathNode):\n+\n+ try:\n+ node.state()\n+ except NodeNotFoundError:\n+ missing_nodes.append(node)\n+\n+ if missing_nodes:\n+ paths = [reduce_node_name(i, session.config[\"paths\"]) for i in missing_nodes]\n+ formatted = format_strings_as_flat_tree(\n+ paths, \"The task did not produce the following files:\\n\", \"\"\n+ )\n+ raise NodeNotFoundError(formatted)\n \n \n @hookimpl(trylast=True)\n", "test_patch": "diff --git a/tests/test_execute.py b/tests/test_execute.py\nindex aa1e80a..333ba9f 100644\n--- a/tests/test_execute.py\n+++ b/tests/test_execute.py\n@@ -36,6 +36,25 @@ def test_task_did_not_produce_node(tmp_path):\n assert isinstance(session.execution_reports[0].exc_info[1], NodeNotFoundError)\n \n \n+@pytest.mark.end_to_end\n+def test_task_did_not_produce_multiple_nodes_and_all_are_shown(runner, tmp_path):\n+ source = \"\"\"\n+ import pytask\n+\n+ @pytask.mark.produces([\"1.txt\", \"2.txt\"])\n+ def task_example():\n+ pass\n+ \"\"\"\n+ tmp_path.joinpath(\"task_module.py\").write_text(textwrap.dedent(source))\n+\n+ result = runner.invoke(cli, [tmp_path.as_posix()])\n+\n+ assert result.exit_code == ExitCode.FAILED\n+ assert \"NodeNotFoundError\" in result.output\n+ assert \"1.txt\" in result.output\n+ assert \"2.txt\" in result.output\n+\n+\n @pytest.mark.end_to_end\n def test_node_not_found_in_task_setup(tmp_path):\n \"\"\"Test for :class:`_pytask.exceptions.NodeNotFoundError` in task setup.\n", "FAIL_TO_PASS": ["tests/test_execute.py::test_task_did_not_produce_multiple_nodes_and_all_are_shown"]}], "all_FAIL_TO_PASS": ["tests/test_execute.py::test_traceback_of_previous_task_failed_is_not_shown[1]", "tests/test_execute.py::test_task_did_not_produce_multiple_nodes_and_all_are_shown"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "toblerity__shapely-1166_x2", "level": 2, "source": "swerebenchv2", "repo": "Toblerity/Shapely", "image": "swerebenchv2/toblerity-shapely:1166-1991a72", "base_commit": "1991a72e94d7c7e5583407e4bb576c2e81292fe7", "num_bugs": 2, "bugs": [{"instance_id": "toblerity__shapely-1166", "base_commit": "1991a72e94d7c7e5583407e4bb576c2e81292fe7", "gold_patch": "diff --git a/CHANGES.txt b/CHANGES.txt\nindex a22880a..8b12c78 100644\n--- a/CHANGES.txt\n+++ b/CHANGES.txt\n@@ -10,6 +10,8 @@ Shapely 1.8 will support only Python versions >= 3.6.\n \n New features:\n \n+- The STRtree nearest*() methods now take an optional argument that\n+ specifies exclusion of the input geometry from results (#1115).\n - A GeometryTypeError has been added to shapely.errors and is consistently\n raised instead of TypeError or ValueError as in version 1.7. For backwards\n compatibility, the new exception will derive from TypeError and Value error\n@@ -23,6 +25,8 @@ New features:\n \n Bug fixes:\n \n+- We no longer attempt to load libc to get the free function on Linux, but get\n+ it from the global symbol table.\n - GEOS error messages printed when GEOS_getCoordSeq() is passed an empty\n geometry are avoided by never passing an empty geometry (#1134).\n - Python's builtin super() is now used only as described in PEP 3135 (#1109).\ndiff --git a/_vendor/packaging/specifiers.py b/_vendor/packaging/specifiers.py\nindex 902f6de..a538a62 100644\n--- a/_vendor/packaging/specifiers.py\n+++ b/_vendor/packaging/specifiers.py\n@@ -503,7 +503,7 @@ class Specifier(_IndividualSpecifier):\n return False\n \n # Ensure that we do not allow a local version of the version mentioned\n- # in the specifier, which is techincally greater than, to match.\n+ # in the specifier, which is technically greater than, to match.\n if prospective.local is not None:\n if Version(prospective.base_version) == Version(spec.base_version):\n return False\n@@ -589,7 +589,7 @@ def _pad_version(left, right):\n class SpecifierSet(BaseSpecifier):\n \n def __init__(self, specifiers=\"\", prereleases=None):\n- # Split on , to break each indidivual specifier into it's own item, and\n+ # Split on , to break each individual specifier into it's own item, and\n # strip each item to remove leading/trailing whitespace.\n specifiers = [s.strip() for s in specifiers.split(\",\") if s.strip()]\n \ndiff --git a/docs/design.rst b/docs/design.rst\nindex 0c768f0..9a6ccf4 100644\n--- a/docs/design.rst\n+++ b/docs/design.rst\n@@ -3,7 +3,7 @@ Design Notes\n ============\n \n Shapely provides classes that implement, more or less, the interfaces in the\n-OGC's simple feature acess specification [1]_. The classes are defined in\n+OGC's simple feature access specification [1]_. The classes are defined in\n similarly named modules under ``shapely.geometry``: ``Point`` is in\n ``shapely.geometry.point``, ``MultiPolygon`` is in\n ``shapely.geometry.multipolygon``. These classes derive from\ndiff --git a/shapely/geometry/base.py b/shapely/geometry/base.py\nindex 1b128ca..1ad0d07 100644\n--- a/shapely/geometry/base.py\n+++ b/shapely/geometry/base.py\n@@ -101,7 +101,7 @@ def deserialize_wkb(data):\n def geos_geom_from_py(ob, create_func=None):\n \"\"\"Helper function for geos_*_from_py functions in each geom type.\n \n- If a create_func is specified the coodinate sequence is cloned and a new\n+ If a create_func is specified the coordinate sequence is cloned and a new\n geometry is created with it, otherwise the geometry is cloned directly.\n This behaviour is useful for converting between LineString and LinearRing\n objects.\ndiff --git a/shapely/geos.py b/shapely/geos.py\nindex dea6147..fe73419 100644\n--- a/shapely/geos.py\n+++ b/shapely/geos.py\n@@ -97,11 +97,12 @@ if sys.platform.startswith('linux'):\n 'libgeos_c.so',\n ]\n _lgeos = load_dll('libgeos_c', fallbacks=alt_paths)\n- # Necessary for environments with only libc.musl\n- c_alt_paths = [\n- 'libc.musl-x86_64.so.1'\n- ]\n- free = load_dll('c', fallbacks=c_alt_paths).free\n+\n+ # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n+ # manpage says, \"If filename is NULL, then the returned handle is for the\n+ # main program\". This way we can let the linker do the work to figure out\n+ # which libc Python is actually using.\n+ free = CDLL(None).free\n free.argtypes = [c_void_p]\n free.restype = None\n \n@@ -147,10 +148,6 @@ elif sys.platform == 'darwin':\n ]\n _lgeos = load_dll('geos_c', fallbacks=alt_paths)\n \n- # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n- # manpage says, \"If filename is NULL, then the returned handle is for the\n- # main program\". This way we can let the linker do the work to figure out\n- # which libc Python is actually using.\n free = CDLL(None).free\n free.argtypes = [c_void_p]\n free.restype = None\n@@ -187,12 +184,13 @@ elif sys.platform == 'win32':\n \n elif sys.platform == 'sunos5':\n _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])\n- free = CDLL('libc.so.1').free\n+ free.restype = None\n free.argtypes = [c_void_p]\n free.restype = None\n+\n else: # other *nix systems\n _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])\n- free = load_dll('c', fallbacks=['libc.so.6']).free\n+ free = CDLL(None).free\n free.argtypes = [c_void_p]\n free.restype = None\n \ndiff --git a/shapely/ops.py b/shapely/ops.py\nindex 720d7c3..ba21ab7 100644\n--- a/shapely/ops.py\n+++ b/shapely/ops.py\n@@ -145,7 +145,7 @@ class CollectionOperator:\n \"\"\"Returns the union of a sequence of geometries\n \n This method replaces :meth:`cascaded_union` as the\n- prefered method for dissolving many polygons.\n+ preferred method for dissolving many polygons.\n \"\"\"\n try:\n if isinstance(geoms, BaseMultipartGeometry):\ndiff --git a/shapely/speedups/__init__.py b/shapely/speedups/__init__.py\nindex 1bbb04c..88ec30e 100644\n--- a/shapely/speedups/__init__.py\n+++ b/shapely/speedups/__init__.py\n@@ -33,7 +33,7 @@ def enable():\n \"\"\"Enable Cython speedups\n \n The shapely.speedups module contains performance enhancements written in C.\n- They are automaticaly installed when Python has access to a compiler and\n+ They are automatically installed when Python has access to a compiler and\n GEOS development headers during installation, and are enabled by default.\n \n You can check if speedups are installed with the `available` attribute, and\ndiff --git a/shapely/strtree.py b/shapely/strtree.py\nindex 75b0f2c..ac1008f 100644\n--- a/shapely/strtree.py\n+++ b/shapely/strtree.py\n@@ -21,6 +21,7 @@ References\n import ctypes\n import logging\n from typing import Any, ItemsView, Iterable, Iterator, Sequence, Tuple, Union\n+import sys\n from warnings import warn\n \n from shapely.errors import ShapelyDeprecationWarning\n@@ -249,7 +250,9 @@ class STRtree:\n \"\"\"\n return self.query_geoms(geom)\n \n- def nearest_item(self, geom: BaseGeometry) -> Union[Any, None]:\n+ def nearest_item(\n+ self, geom: BaseGeometry, exclusive: bool = False\n+ ) -> Union[Any, None]:\n \"\"\"Query the tree for the node nearest to geom and get the item\n stored in the node.\n \n@@ -259,6 +262,9 @@ class STRtree:\n ----------\n geom : geometry object\n The query geometry.\n+ exclusive : bool, optional\n+ Whether to exclude the item corresponding to the given geom\n+ from results or not. Default: False.\n \n Returns\n -------\n@@ -289,10 +295,14 @@ class STRtree:\n \n def callback(item1, item2, distance, userdata):\n try:\n+ callback_userdata = ctypes.cast(userdata, ctypes.py_object).value\n idx = ctypes.cast(item1, ctypes.py_object).value\n geom2 = ctypes.cast(item2, ctypes.py_object).value\n dist = ctypes.cast(distance, ctypes.POINTER(ctypes.c_double))\n- lgeos.GEOSDistance(self._rev[idx]._geom, geom2._geom, dist)\n+ if callback_userdata[\"exclusive\"] and self._rev[idx].equals(geom2):\n+ dist[0] = sys.float_info.max\n+ else:\n+ lgeos.GEOSDistance(self._rev[idx]._geom, geom2._geom, dist)\n return 1\n except Exception:\n log.exception(\"Caught exception\")\n@@ -303,12 +313,14 @@ class STRtree:\n ctypes.py_object(geom),\n envelope._geom,\n lgeos.GEOSDistanceCallback(callback),\n- None,\n+ ctypes.py_object({\"exclusive\": exclusive}),\n )\n result = ctypes.cast(item, ctypes.py_object).value\n return result\n \n- def nearest_geom(self, geom: BaseGeometry) -> Union[BaseGeometry, None]:\n+ def nearest_geom(\n+ self, geom: BaseGeometry, exclusive: bool = False\n+ ) -> Union[BaseGeometry, None]:\n \"\"\"Query the tree for the node nearest to geom and get the\n geometry corresponding to the item stored in the node.\n \n@@ -316,6 +328,9 @@ class STRtree:\n ----------\n geom : geometry object\n The query geometry.\n+ exclusive : bool, optional\n+ Whether to exclude the given geom from results or not.\n+ Default: False.\n \n Returns\n -------\n@@ -325,13 +340,15 @@ class STRtree:\n version 2.0.\n \n \"\"\"\n- item = self.nearest_item(geom)\n+ item = self.nearest_item(geom, exclusive=exclusive)\n if item is None:\n return None\n else:\n return self._rev[item]\n \n- def nearest(self, geom: BaseGeometry) -> Union[BaseGeometry, None]:\n+ def nearest(\n+ self, geom: BaseGeometry, exclusive: bool = False\n+ ) -> Union[BaseGeometry, None]:\n \"\"\"Query the tree for the node nearest to geom and get the\n geometry corresponding to the item stored in the node.\n \n@@ -342,6 +359,9 @@ class STRtree:\n ----------\n geom : geometry object\n The query geometry.\n+ exclusive : bool, optional\n+ Whether to exclude the given geom from results or not.\n+ Default: False.\n \n Returns\n -------\n@@ -351,4 +371,4 @@ class STRtree:\n version 2.0.\n \n \"\"\"\n- return self.nearest_geom(geom)\n+ return self.nearest_geom(geom, exclusive=exclusive)\n", "test_patch": "diff --git a/tests/test_strtree.py b/tests/test_strtree.py\nindex 04d5742..55b61c4 100644\n--- a/tests/test_strtree.py\n+++ b/tests/test_strtree.py\n@@ -177,3 +177,22 @@ def test_nearest_items(geoms, items):\n with pytest.warns(ShapelyDeprecationWarning):\n tree = STRtree(geoms, items)\n assert tree.nearest_item(None) is None\n+\n+\n+@pytest.mark.skipif(geos_version < (3, 6, 0), reason=\"GEOS 3.6.0 required\")\n+@pytest.mark.parametrize(\n+ \"geoms\",\n+ [\n+ [\n+ Point(0, 0.5),\n+ Polygon([(1, 0), (2, 0), (2, 1), (1, 1)]),\n+ Polygon([(0, 2), (1, 2), (1, 3), (0, 3)]),\n+ ]\n+ ],\n+)\n+@pytest.mark.parametrize(\"items\", [list(range(1, 4)), list(\"abc\")])\n+@pytest.mark.parametrize(\"query_geom\", [Point(0, 0.5)])\n+def test_nearest_item_exclusive(geoms, items, query_geom):\n+ with pytest.warns(ShapelyDeprecationWarning):\n+ tree = STRtree(geoms, items)\n+ assert tree.nearest_item(query_geom, exclusive=True) != items[0]\n", "FAIL_TO_PASS": ["tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items0-geoms0]", "tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items1-geoms0]"]}, {"instance_id": "toblerity__shapely-1174", "base_commit": "a2288360b5b4664f645199a7a605c3a062e426eb", "gold_patch": "diff --git a/shapely/coords.py b/shapely/coords.py\nindex df673b0..ce526ef 100644\n--- a/shapely/coords.py\n+++ b/shapely/coords.py\n@@ -116,7 +116,10 @@ class CoordinateSequence:\n def _ctypes(self):\n self._update()\n has_z = self._ndim == 3\n- n = self._ndim\n+ n = self._ndim or 0\n+ if n == 0:\n+ # ignore with NumPy 1.21 __array_interface__\n+ raise AttributeError(\"empty geometry sequence\")\n m = self.__len__()\n array_type = c_double * (m * n)\n data = array_type()\ndiff --git a/shapely/geometry/base.py b/shapely/geometry/base.py\nindex 1ad0d07..2a5eacb 100644\n--- a/shapely/geometry/base.py\n+++ b/shapely/geometry/base.py\n@@ -849,8 +849,8 @@ class BaseMultipartGeometry(BaseGeometry):\n @property\n def __array_interface__(self):\n \"\"\"Provide the Numpy array protocol.\"\"\"\n- raise NotImplementedError(\"Multi-part geometries do not themselves \"\n- \"provide the array interface\")\n+ raise AttributeError(\"Multi-part geometries do not themselves \"\n+ \"provide the array interface\")\n \n def _get_coords(self):\n raise NotImplementedError(\"Sub-geometries may have coordinate \"\ndiff --git a/shapely/geometry/polygon.py b/shapely/geometry/polygon.py\nindex 4386eb4..fabb6f2 100644\n--- a/shapely/geometry/polygon.py\n+++ b/shapely/geometry/polygon.py\n@@ -317,7 +317,7 @@ class Polygon(BaseGeometry):\n \n @property\n def __array_interface__(self):\n- raise NotImplementedError(\n+ raise AttributeError(\n \"A polygon does not itself provide the array interface. Its rings do.\")\n \n def _get_coords(self):\ndiff --git a/shapely/speedups/_speedups.pyx b/shapely/speedups/_speedups.pyx\nindex f5b6dc2..0b49959 100644\n--- a/shapely/speedups/_speedups.pyx\n+++ b/shapely/speedups/_speedups.pyx\n@@ -421,7 +421,10 @@ def coordseq_ctypes(self):\n cdef GEOSCoordSequence *cs\n cdef double *data_p\n self._update()\n- n = self._ndim\n+ n = self._ndim or 0\n+ if n == 0:\n+ # ignore with NumPy 1.21 __array_interface__\n+ raise AttributeError(\"empty geometry sequence\")\n m = self.__len__()\n array_type = ctypes.c_double * (m * n)\n data = array_type()\ndiff --git a/shapely/strtree.py b/shapely/strtree.py\nindex ac1008f..30c79a5 100644\n--- a/shapely/strtree.py\n+++ b/shapely/strtree.py\n@@ -20,7 +20,7 @@ References\n \n import ctypes\n import logging\n-from typing import Any, ItemsView, Iterable, Iterator, Sequence, Tuple, Union\n+from typing import Any, ItemsView, Iterable, Iterator, Optional, Sequence, Tuple, Union\n import sys\n from warnings import warn\n \n@@ -108,27 +108,24 @@ class STRtree:\n self.node_capacity = node_capacity\n self._rev = {\n item: geom\n- for geom, item in self._iterinitdata(\n- zip(geoms, items) if items is not None else geoms\n- )\n+ for geom, item in self._iterinitdata(geoms, items)\n if not geom.is_empty\n }\n-\n if self._rev:\n self._init_tree(self._rev.items())\n \n def _iterinitdata(\n self,\n- initdata: Union[Iterable[Tuple[BaseGeometry, Any]], Iterable[BaseGeometry]],\n+ geoms: Iterable[BaseGeometry], items: Optional[Iterable[BaseGeometry]],\n ) -> Iterator[Tuple[BaseGeometry, Any]]:\n- if not initdata:\n- return\n-\n- for enum_idx, item in enumerate(initdata):\n- if isinstance(item, tuple):\n- yield item[0], item[1]\n- elif isinstance(item, BaseGeometry):\n- yield (item, enum_idx)\n+ if items is not None:\n+ for geom, item in zip(geoms, items):\n+ if isinstance(geom, BaseGeometry):\n+ yield (geom, item)\n+ else:\n+ for enum_idx, geom in enumerate(geoms):\n+ if isinstance(geom, BaseGeometry):\n+ yield (geom, enum_idx)\n \n def _init_tree(self, rev_initdata: ItemsView[Any, BaseGeometry]):\n if rev_initdata:\n", "test_patch": "diff --git a/tests/test_collection.py b/tests/test_collection.py\nindex 09b5c11..5ba176b 100644\n--- a/tests/test_collection.py\n+++ b/tests/test_collection.py\n@@ -114,3 +114,14 @@ def test_len_deprecated(geometrycollection_geojson):\n geom = shape(geometrycollection_geojson)\n with pytest.warns(ShapelyDeprecationWarning, match=\"__len__\"):\n assert len(geom) == 2\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = GeometryCollection([LineString([(0, 0), (1, 1)])])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_linestring.py b/tests/test_linestring.py\nindex 2b6e7f9..a452ff7 100644\n--- a/tests/test_linestring.py\n+++ b/tests/test_linestring.py\n@@ -87,6 +87,7 @@ def test_from_numpy():\n assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)]\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n def test_numpy_empty_linestring_coords():\n np = pytest.importorskip(\"numpy\")\n \n@@ -97,6 +98,17 @@ def test_numpy_empty_linestring_coords():\n assert la.shape == (0,)\n \n \n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = LineString([(0.0, 0.0), (0.0, 1.0)])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\n+\n+\n def test_from_invalid_dim():\n with pytest.raises(ValueError, match=\"at least 2 coordinate tuples\"):\n LineString([(1, 2)])\ndiff --git a/tests/test_multilinestring.py b/tests/test_multilinestring.py\nindex bf79ddf..c6475dc 100644\n--- a/tests/test_multilinestring.py\n+++ b/tests/test_multilinestring.py\n@@ -117,3 +117,14 @@ def test_getitem_deprecated():\n geom = MultiLineString([[[5.0, 6.0], [7.0, 8.0]]])\n with pytest.warns(ShapelyDeprecationWarning, match=\"__getitem__\"):\n part = geom[0]\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = MultiLineString([[[5.0, 6.0], [7.0, 8.0]]])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_multipoint.py b/tests/test_multipoint.py\nindex afbffaf..a3e2914 100644\n--- a/tests/test_multipoint.py\n+++ b/tests/test_multipoint.py\n@@ -129,6 +129,17 @@ def test_multipoint_array_interface_numpy_deprecated():\n np.array(geom)\n \n \n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = MultiPoint(((1.0, 2.0), (3.0, 4.0)))\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\n+\n+\n def test_iteration_deprecated():\n geom = MultiPoint([[5.0, 6.0], [7.0, 8.0]])\n with pytest.warns(ShapelyDeprecationWarning, match=\"Iteration\"):\ndiff --git a/tests/test_multipolygon.py b/tests/test_multipolygon.py\nindex c3982a8..878211a 100644\n--- a/tests/test_multipolygon.py\n+++ b/tests/test_multipolygon.py\n@@ -110,3 +110,16 @@ def test_getitem_deprecated():\n [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))])])\n with pytest.warns(ShapelyDeprecationWarning, match=\"__getitem__\"):\n part = geom[0]\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = MultiPolygon(\n+ [(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)),\n+ [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))])])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_point.py b/tests/test_point.py\nindex 264118c..4a80564 100644\n--- a/tests/test_point.py\n+++ b/tests/test_point.py\n@@ -262,6 +262,7 @@ def test_point_array_interface_numpy_deprecated():\n np.array(p)\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n def test_numpy_empty_point_coords():\n np = pytest.importorskip(\"numpy\")\n \n@@ -270,3 +271,14 @@ def test_numpy_empty_point_coords():\n # Access the coords\n a = np.asarray(pe.coords)\n assert a.shape == (0,)\n+\n+\n+@shapely20_deprecated\n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = Point(3.0, 4.0)\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\ndiff --git a/tests/test_polygon.py b/tests/test_polygon.py\nindex 863b623..62b2f96 100644\n--- a/tests/test_polygon.py\n+++ b/tests/test_polygon.py\n@@ -109,6 +109,7 @@ def test_numpy_linearring_coords():\n assert_array_equal(ra, expected)\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n def test_numpy_empty_linearring_coords():\n np = pytest.importorskip(\"numpy\")\n \n@@ -116,6 +117,16 @@ def test_numpy_empty_linearring_coords():\n assert np.asarray(ring.coords).shape == (0,)\n \n \n+@pytest.mark.filterwarnings(\"error:An exception was ignored\") # NumPy 1.21\n+def test_numpy_object_array():\n+ np = pytest.importorskip(\"numpy\")\n+\n+ geom = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)])\n+ ar = np.empty(1, object)\n+ ar[:] = [geom]\n+ assert ar[0] == geom\n+\n+\n def test_polygon_from_coordinate_sequence():\n coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]\n \ndiff --git a/tests/test_strtree.py b/tests/test_strtree.py\nindex 55b61c4..e1402cc 100644\n--- a/tests/test_strtree.py\n+++ b/tests/test_strtree.py\n@@ -7,14 +7,19 @@ import sys\n import pytest\n \n from shapely.errors import ShapelyDeprecationWarning\n-from shapely.geometry import Point, Polygon\n+from shapely.geometry import Point, Polygon, box\n from shapely.geos import geos_version\n from shapely import strtree\n from shapely.strtree import STRtree\n+from shapely import wkt\n \n from .conftest import requires_geos_342\n \n \n+point = Point(2, 3)\n+empty = wkt.loads(\"GEOMETRYCOLLECTION EMPTY\")\n+\n+\n @requires_geos_342\n @pytest.mark.parametrize(\"geoms\", [[Point(i, i) for i in range(10)]])\n @pytest.mark.parametrize(\n@@ -37,11 +42,43 @@ def test_query(geoms, query_geom, num_results):\n def test_query_enumeration_idx(geoms, query_geom, expected):\n \"\"\"Store enumeration idx\"\"\"\n with pytest.warns(ShapelyDeprecationWarning):\n- tree = STRtree((g, i) for i, g in enumerate(geoms))\n+ tree = STRtree(geoms, range(len(geoms)))\n results = tree.query_items(query_geom)\n assert sorted(results) == sorted(expected)\n \n \n+@requires_geos_342\n+@pytest.mark.parametrize(\"geoms\", [[Point(i, i) for i in range(5)]])\n+@pytest.mark.parametrize(\"items\", [None, list(range(1, 6)), list(\"abcde\")])\n+@pytest.mark.parametrize(\n+ \"query_geom,expected\",\n+ [(Point(2, 2).buffer(0.99), [2]), (Point(2, 2).buffer(1.0), [1, 2, 3])],\n+)\n+def test_query_items(geoms, items, query_geom, expected):\n+ \"\"\"Store enumeration idx\"\"\"\n+ with pytest.warns(ShapelyDeprecationWarning):\n+ tree = STRtree(geoms, items)\n+ results = tree.query_items(query_geom)\n+ expected = [items[idx] for idx in expected] if items is not None else expected\n+ assert sorted(results) == sorted(expected)\n+\n+\n+@pytest.mark.parametrize(\n+ \"tree_geometry, geometry,expected\",\n+ [\n+ ([point], box(0, 0, 10, 10), [0]),\n+ # None/empty is ignored in the tree, but the index of the valid geometry\n+ # should be retained.\n+ ([None, point], box(0, 0, 10, 10), [1]),\n+ ([None, empty, point], box(0, 0, 10, 10), [2]),\n+ ],\n+)\n+def test_query_items_with_empty(tree_geometry, geometry, expected):\n+ with pytest.warns(ShapelyDeprecationWarning):\n+ tree = STRtree(tree_geometry)\n+ assert tree.query_items(geometry) == expected\n+\n+\n @requires_geos_342\n def test_insert_empty_geometry():\n \"\"\"\n@@ -112,7 +149,7 @@ def test_pickle_persistence():\n Don't crash trying to use unpickled GEOS handle.\n \"\"\"\n with pytest.warns(ShapelyDeprecationWarning):\n- tree = STRtree([(Point(i, i).buffer(0.1), i) for i in range(3)])\n+ tree = STRtree([Point(i, i).buffer(0.1) for i in range(3)], range(3))\n \n pickled_strtree = pickle.dumps(tree)\n unpickle_script_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"unpickle-strtree.py\")\n@@ -165,14 +202,14 @@ def test_nearest_item(geoms, items, query_geom):\n assert tree.nearest_item(query_geom) == items[0]\n \n \n-@pytest.mark.parametrize([\"geoms\", \"items\"], [(None, None), ([], None)])\n+@pytest.mark.parametrize([\"geoms\", \"items\"], [([], None), ([], [])])\n def test_nearest_empty(geoms, items):\n with pytest.warns(ShapelyDeprecationWarning):\n tree = STRtree(geoms, items)\n assert tree.nearest_item(None) is None\n \n \n-@pytest.mark.parametrize([\"geoms\", \"items\"], [(None, None), ([], None)])\n+@pytest.mark.parametrize([\"geoms\", \"items\"], [([], None), ([], [])])\n def test_nearest_items(geoms, items):\n with pytest.warns(ShapelyDeprecationWarning):\n tree = STRtree(geoms, items)\n", "FAIL_TO_PASS": ["tests/test_collection.py::test_numpy_object_array", "tests/test_linestring.py::test_numpy_empty_linestring_coords", "tests/test_multilinestring.py::test_numpy_object_array", "tests/test_multipolygon.py::test_numpy_object_array", "tests/test_point.py::test_numpy_empty_point_coords", "tests/test_polygon.py::test_numpy_empty_linearring_coords", "tests/test_polygon.py::test_numpy_object_array"]}], "all_FAIL_TO_PASS": ["tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items0-geoms0]", "tests/test_strtree.py::test_nearest_item_exclusive[query_geom0-items1-geoms0]", "tests/test_collection.py::test_numpy_object_array", "tests/test_linestring.py::test_numpy_empty_linestring_coords", "tests/test_multilinestring.py::test_numpy_object_array", "tests/test_multipolygon.py::test_numpy_object_array", "tests/test_point.py::test_numpy_empty_point_coords", "tests/test_polygon.py::test_numpy_empty_linearring_coords", "tests/test_polygon.py::test_numpy_object_array"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "drivendataorg__cloudpathlib-432_x2", "level": 2, "source": "swerebenchv2", "repo": "drivendataorg/cloudpathlib", "image": "swerebenchv2/drivendataorg-cloudpathlib:432-fabb0e4", "base_commit": "fabb0e43d677e518b5918db9db8d41c56d477071", "num_bugs": 2, "bugs": [{"instance_id": "drivendataorg__cloudpathlib-432", "base_commit": "fabb0e43d677e518b5918db9db8d41c56d477071", "gold_patch": "diff --git a/HISTORY.md b/HISTORY.md\nindex c56f815..a21d821 100644\n--- a/HISTORY.md\n+++ b/HISTORY.md\n@@ -6,6 +6,7 @@\n - Fix `CloudPath` cleanup via `CloudPath.__del__` when `Client` encounters an exception during initialization and does not create a `file_cache_mode` attribute. (Issue [#372](https://github.com/drivendataorg/cloudpathlib/issues/372), thanks to [@bryanwweber](https://github.com/bryanwweber)) \n - Drop support for Python 3.7; pin minimal `boto3` version to Python 3.8+ versions. (PR [#407](https://github.com/drivendataorg/cloudpathlib/pull/407))\n - fix: use native `exists()` method in `GSClient`. (PR [#420](https://github.com/drivendataorg/cloudpathlib/pull/420))\n+- Enhancement: lazy instantiation of default client (PR [#432](https://github.com/drivendataorg/cloudpathlib/issues/432), Issue [#428](https://github.com/drivendataorg/cloudpathlib/issues/428))\n \n ## v0.18.1 (2024-02-26)\n \ndiff --git a/cloudpathlib/cloudpath.py b/cloudpathlib/cloudpath.py\nindex 0c17a4e..afca5cb 100644\n--- a/cloudpathlib/cloudpath.py\n+++ b/cloudpathlib/cloudpath.py\n@@ -214,8 +214,10 @@ class CloudPath(metaclass=CloudPathMeta):\n # handle if local file gets opened. must be set at the top of the method in case any code\n # below raises an exception, this prevents __del__ from raising an AttributeError\n self._handle: Optional[IO] = None\n+ self._client: Optional[\"Client\"] = None\n \n self.is_valid_cloudpath(cloud_path, raise_on_error=True)\n+ self._cloud_meta.validate_completeness()\n \n # versions of the raw string that provide useful methods\n self._str = str(cloud_path)\n@@ -225,27 +227,34 @@ class CloudPath(metaclass=CloudPathMeta):\n # setup client\n if client is None:\n if isinstance(cloud_path, CloudPath):\n- client = cloud_path.client\n- else:\n- client = self._cloud_meta.client_class.get_default_client()\n- if not isinstance(client, self._cloud_meta.client_class):\n+ self._client = cloud_path.client\n+ else:\n+ self._client = client\n+\n+ if client is not None and not isinstance(client, self._cloud_meta.client_class):\n raise ClientMismatchError(\n f\"Client of type [{client.__class__}] is not valid for cloud path of type \"\n f\"[{self.__class__}]; must be instance of [{self._cloud_meta.client_class}], or \"\n f\"None to use default client for this cloud path class.\"\n )\n- self.client: Client = client\n \n # track if local has been written to, if so it may need to be uploaded\n self._dirty = False\n \n+ @property\n+ def client(self):\n+ if getattr(self, \"_client\", None) is None:\n+ self._client = self._cloud_meta.client_class.get_default_client()\n+\n+ return self._client\n+\n def __del__(self) -> None:\n # make sure that file handle to local path is closed\n if self._handle is not None:\n self._handle.close()\n \n # ensure file removed from cache when cloudpath object deleted\n- client = getattr(self, \"client\", None)\n+ client = getattr(self, \"_client\", None)\n if getattr(client, \"file_cache_mode\", None) == FileCacheMode.cloudpath_object:\n self.clear_cache()\n \n@@ -253,13 +262,11 @@ class CloudPath(metaclass=CloudPathMeta):\n state = self.__dict__.copy()\n \n # don't pickle client\n- del state[\"client\"]\n+ del state[\"_client\"]\n \n return state\n \n def __setstate__(self, state: Dict[str, Any]) -> None:\n- client = self._cloud_meta.client_class.get_default_client()\n- state[\"client\"] = client\n self.__dict__.update(state)\n \n @property\n", "test_patch": "diff --git a/tests/test_cloudpath_instantiation.py b/tests/test_cloudpath_instantiation.py\nindex fe0ca3f..b625a47 100644\n--- a/tests/test_cloudpath_instantiation.py\n+++ b/tests/test_cloudpath_instantiation.py\n@@ -59,6 +59,13 @@ def test_instantiation(rig, path):\n assert str(p._path) == expected.split(\":/\", 1)[-1]\n \n \n+def test_default_client_lazy(rig):\n+ cp = rig.path_class(rig.cloud_prefix + \"testing/file.txt\")\n+ assert cp._client is None\n+ assert cp.client is not None\n+ assert cp._client is not None\n+\n+\n def test_instantiation_errors(rig):\n with pytest.raises(TypeError):\n rig.path_class()\n", "FAIL_TO_PASS": ["tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_gs_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/custom_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/gs_rig]"]}, {"instance_id": "drivendataorg__cloudpathlib-433", "base_commit": "71331d31aec68c1a4e49fc59d30b613de2d1e657", "gold_patch": "diff --git a/HISTORY.md b/HISTORY.md\nindex a21d821..046ab12 100644\n--- a/HISTORY.md\n+++ b/HISTORY.md\n@@ -7,6 +7,7 @@\n - Drop support for Python 3.7; pin minimal `boto3` version to Python 3.8+ versions. (PR [#407](https://github.com/drivendataorg/cloudpathlib/pull/407))\n - fix: use native `exists()` method in `GSClient`. (PR [#420](https://github.com/drivendataorg/cloudpathlib/pull/420))\n - Enhancement: lazy instantiation of default client (PR [#432](https://github.com/drivendataorg/cloudpathlib/issues/432), Issue [#428](https://github.com/drivendataorg/cloudpathlib/issues/428))\n+- Adds existence check before downloading in `download_to` (Issue [#430](https://github.com/drivendataorg/cloudpathlib/issues/430), PR [#432](https://github.com/drivendataorg/cloudpathlib/pull/432))\n \n ## v0.18.1 (2024-02-26)\n \ndiff --git a/cloudpathlib/cloudpath.py b/cloudpathlib/cloudpath.py\nindex afca5cb..8bad810 100644\n--- a/cloudpathlib/cloudpath.py\n+++ b/cloudpathlib/cloudpath.py\n@@ -63,6 +63,7 @@ from .exceptions import (\n CloudPathFileExistsError,\n CloudPathIsADirectoryError,\n CloudPathNotADirectoryError,\n+ CloudPathNotExistsError,\n CloudPathNotImplementedError,\n DirectoryNotEmptyError,\n IncompleteImplementationError,\n@@ -899,6 +900,10 @@ class CloudPath(metaclass=CloudPathMeta):\n # =========== public cloud methods, not in pathlib ===============\n def download_to(self, destination: Union[str, os.PathLike]) -> Path:\n destination = Path(destination)\n+\n+ if not self.exists():\n+ raise CloudPathNotExistsError(f\"Cannot download because path does not exist: {self}\")\n+\n if self.is_file():\n if destination.is_dir():\n destination = destination / self.name\ndiff --git a/cloudpathlib/exceptions.py b/cloudpathlib/exceptions.py\nindex 802f71e..1b4499f 100644\n--- a/cloudpathlib/exceptions.py\n+++ b/cloudpathlib/exceptions.py\n@@ -20,6 +20,10 @@ class CloudPathFileExistsError(CloudPathException, FileExistsError):\n pass\n \n \n+class CloudPathNotExistsError(CloudPathException):\n+ pass\n+\n+\n class CloudPathIsADirectoryError(CloudPathException, IsADirectoryError):\n pass\n \n", "test_patch": "diff --git a/tests/test_cloudpath_file_io.py b/tests/test_cloudpath_file_io.py\nindex af8f9e6..e5546f0 100644\n--- a/tests/test_cloudpath_file_io.py\n+++ b/tests/test_cloudpath_file_io.py\n@@ -10,6 +10,7 @@ import pytest\n from cloudpathlib import CloudPath\n \n from cloudpathlib.exceptions import (\n+ CloudPathNotExistsError,\n CloudPathIsADirectoryError,\n CloudPathNotImplementedError,\n DirectoryNotEmptyError,\n@@ -396,6 +397,9 @@ def test_file_read_writes(rig, tmp_path):\n )\n assert cloud_rel_paths == dled_rel_paths\n \n+ with pytest.raises(CloudPathNotExistsError):\n+ (p / \"not_exists_file\").download_to(dl_file)\n+\n \n def test_dispatch_to_local_cache(rig):\n p = rig.create_cloud_path(\"dir_0/file0_1.txt\")\n", "FAIL_TO_PASS": ["tests/test_cloudpath_file_io.py::test_glob_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/azure_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/azure_rig]", "tests/test_cloudpath_file_io.py::test_walk[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/azure_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/custom_s3_rig]"]}], "all_FAIL_TO_PASS": ["tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_gs_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/local_azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/custom_s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/azure_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/s3_rig]", "tests/test_cloudpath_instantiation.py::test_default_client_lazy[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/gs_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/azure_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/gs_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/azure_rig]", "tests/test_cloudpath_file_io.py::test_walk[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/azure_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/s3_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/s3_rig]", "tests/test_cloudpath_file_io.py::test_dispatch_to_local_cache[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/gs_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_is_dir_is_file[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/gs_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/s3_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/s3_rig]", "tests/test_cloudpath_file_io.py::test_fspath[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_list_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_cloud_path_download_to[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_iterdir[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_file_discovery[/gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_walk[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/gs_rig]", "tests/test_cloudpath_file_io.py::test_os_open[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_buckets[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/azure_rig]", "tests/test_cloudpath_file_io.py::test_drive_exists[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/azure_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_close_file_idempotent[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/custom_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_glob_exceptions[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/azure_rig]", "tests/test_cloudpath_file_io.py::test_pickle[/azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_gs_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/s3_rig]", "tests/test_cloudpath_file_io.py::test_file_read_writes[/local_azure_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/local_s3_rig]", "tests/test_cloudpath_file_io.py::test_glob_many_open_files[/custom_s3_rig]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "materials-consortia__optimade-python-tools-547_x2", "level": 2, "source": "swerebenchv2", "repo": "Materials-Consortia/optimade-python-tools", "image": "swerebenchv2/materials-consortia-optimade-python-tools:547-6f34399", "base_commit": "6f3439900630d71f6e23400e4a2aea11d8c5eefd", "num_bugs": 2, "bugs": [{"instance_id": "materials-consortia__optimade-python-tools-547", "base_commit": "6f3439900630d71f6e23400e4a2aea11d8c5eefd", "gold_patch": "diff --git a/openapi/openapi.json b/openapi/openapi.json\nindex ad33b329..98f07741 100644\n--- a/openapi/openapi.json\n+++ b/openapi/openapi.json\n@@ -3050,16 +3050,19 @@\n },\n \"chemical_formula_reduced\": {\n \"title\": \"Chemical Formula Reduced\",\n+ \"pattern\": \"^([A-Z][a-z]?\\\\d*)*$\",\n \"type\": \"string\",\n \"description\": \"The reduced chemical formula for a structure as a string with element symbols and integer chemical proportion numbers.\\nThe proportion number MUST be omitted if it is 1.\\n\\n- **Type**: string\\n\\n- **Requirements/Conventions**:\\n - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.\\n - **Query**: MUST be a queryable property.\\n However, support for filters using partial string matching with this property is OPTIONAL (i.e., BEGINS WITH, ENDS WITH, and CONTAINS).\\n Intricate queries on formula components are instead suggested to be formulated using set-type filter operators on the multi valued `elements` and `elements_ratios` properties.\\n - Element names MUST have proper capitalization (e.g., `\\\"Si\\\"`, not `\\\"SI\\\"` for \\\"silicon\\\").\\n - Elements MUST be placed in alphabetical order, followed by their integer chemical proportion number.\\n - For structures with no partial occupation, the chemical proportion numbers are the smallest integers for which the chemical proportion is exactly correct.\\n - For structures with partial occupation, the chemical proportion numbers are integers that within reasonable approximation indicate the correct chemical proportions. The precise details of how to perform the rounding is chosen by the API implementation.\\n - No spaces or separators are allowed.\\n\\n- **Examples**:\\n - `\\\"H2NaO\\\"`\\n - `\\\"ClNa\\\"`\\n - `\\\"CCaO3\\\"`\\n\\n- **Query examples**:\\n - A filter that matches an exactly given formula is `chemical_formula_reduced=\\\"H2NaO\\\"`.\"\n },\n \"chemical_formula_hill\": {\n \"title\": \"Chemical Formula Hill\",\n+ \"pattern\": \"^([A-Z][a-z]?\\\\d*)*$\",\n \"type\": \"string\",\n \"description\": \"The chemical formula for a structure in [Hill form](https://dx.doi.org/10.1021/ja02046a005) with element symbols followed by integer chemical proportion numbers. The proportion number MUST be omitted if it is 1.\\n\\n- **Type**: string\\n\\n- **Requirements/Conventions**:\\n - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`.\\n - **Query**: Support for queries on this property is OPTIONAL.\\n If supported, only a subset of the filter features MAY be supported.\\n - The overall scale factor of the chemical proportions is chosen such that the resulting values are integers that indicate the most chemically relevant unit of which the system is composed.\\n For example, if the structure is a repeating unit cell with four hydrogens and four oxygens that represents two hydroperoxide molecules, `chemical_formula_hill` is `\\\"H2O2\\\"` (i.e., not `\\\"HO\\\"`, nor `\\\"H4O4\\\"`).\\n - If the chemical insight needed to ascribe a Hill formula to the system is not present, the property MUST be handled as unset.\\n - Element names MUST have proper capitalization (e.g., `\\\"Si\\\"`, not `\\\"SI\\\"` for \\\"silicon\\\").\\n - Elements MUST be placed in [Hill order](https://dx.doi.org/10.1021/ja02046a005), followed by their integer chemical proportion number.\\n Hill order means: if carbon is present, it is placed first, and if also present, hydrogen is placed second.\\n After that, all other elements are ordered alphabetically.\\n If carbon is not present, all elements are ordered alphabetically.\\n - If the system has sites with partial occupation and the total occupations of each element do not all sum up to integers, then the Hill formula SHOULD be handled as unset.\\n - No spaces or separators are allowed.\\n\\n- **Examples**:\\n - `\\\"H2O2\\\"`\\n\\n- **Query examples**:\\n - A filter that matches an exactly given formula is `chemical_formula_hill=\\\"H2O2\\\"`.\"\n },\n \"chemical_formula_anonymous\": {\n \"title\": \"Chemical Formula Anonymous\",\n+ \"pattern\": \"^([A-Z][a-z]?\\\\d*)*$\",\n \"type\": \"string\",\n \"description\": \"The anonymous formula is the `chemical_formula_reduced`, but where the elements are instead first ordered by their chemical proportion number, and then, in order left to right, replaced by anonymous symbols A, B, C, ..., Z, Aa, Ba, ..., Za, Ab, Bb, ... and so on.\\n\\n- **Type**: string\\n\\n- **Requirements/Conventions**:\\n - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.\\n - **Query**: MUST be a queryable property.\\n However, support for filters using partial string matching with this property is OPTIONAL (i.e., BEGINS WITH, ENDS WITH, and CONTAINS).\\n\\n- **Examples**:\\n - `\\\"A2B\\\"`\\n - `\\\"A42B42C16D12E10F9G5\\\"`\\n\\n- **Querying**:\\n - A filter that matches an exactly given formula is `chemical_formula_anonymous=\\\"A2B\\\"`.\"\n },\ndiff --git a/optimade/models/structures.py b/optimade/models/structures.py\nindex bb5483f7..4203824a 100644\n--- a/optimade/models/structures.py\n+++ b/optimade/models/structures.py\n@@ -1,4 +1,5 @@\n # pylint: disable=no-self-argument,line-too-long,no-name-in-module\n+import re\n from enum import IntEnum, Enum\n from sys import float_info\n from typing import List, Optional, Union\n@@ -12,6 +13,8 @@ from optimade.models.utils import (\n OptimadeField,\n StrictField,\n SupportLevel,\n+ ANONYMOUS_ELEMENTS,\n+ CHEMICAL_FORMULA_REGEXP,\n )\n \n EXTENDED_CHEMICAL_SYMBOLS = CHEMICAL_SYMBOLS + EXTRA_SYMBOLS\n@@ -366,6 +369,7 @@ The proportion number MUST be omitted if it is 1.\n - A filter that matches an exactly given formula is `chemical_formula_reduced=\"H2NaO\"`.\"\"\",\n support=SupportLevel.SHOULD,\n queryable=SupportLevel.MUST,\n+ regex=CHEMICAL_FORMULA_REGEXP,\n )\n \n chemical_formula_hill: Optional[str] = OptimadeField(\n@@ -396,6 +400,7 @@ The proportion number MUST be omitted if it is 1.\n - A filter that matches an exactly given formula is `chemical_formula_hill=\"H2O2\"`.\"\"\",\n support=SupportLevel.OPTIONAL,\n queryable=SupportLevel.OPTIONAL,\n+ regex=CHEMICAL_FORMULA_REGEXP,\n )\n \n chemical_formula_anonymous: str = OptimadeField(\n@@ -417,6 +422,7 @@ The proportion number MUST be omitted if it is 1.\n - A filter that matches an exactly given formula is `chemical_formula_anonymous=\"A2B\"`.\"\"\",\n support=SupportLevel.SHOULD,\n queryable=SupportLevel.MUST,\n+ regex=CHEMICAL_FORMULA_REGEXP,\n )\n \n dimension_types: conlist(Periodicity, min_items=3, max_items=3) = OptimadeField(\n@@ -758,6 +764,62 @@ The properties of the species are found in the property `species`.\n queryable=SupportLevel.MUST,\n )\n \n+ @validator(\"chemical_formula_reduced\", \"chemical_formula_hill\")\n+ def check_ordered_formula(cls, v, field):\n+ if v is None:\n+ return v\n+\n+ numbers = re.findall(r\"(\\d+\\.?)+\", v)\n+ elements = re.findall(r\"[A-Z][a-z]?\", v)\n+ expected_elements = sorted(elements)\n+\n+ if field.name == \"chemical_formula_hill\":\n+ for elem in (\"C\", \"H\"):\n+ if elem in expected_elements:\n+ expected_elements.pop(expected_elements.index(elem))\n+ expected_elements.insert(0, elem)\n+\n+ if any(elem not in CHEMICAL_SYMBOLS for elem in elements):\n+ raise ValueError(\n+ f\"Cannot use unknown chemical symbols {[elem for elem in elements if elem not in CHEMICAL_SYMBOLS]} in {field.name!r}\"\n+ )\n+\n+ if \"1\" in numbers:\n+ raise ValueError(\n+ \"Must omit proportion '1' from formula {v} in {field.name!r}\"\n+ )\n+ if expected_elements != elements:\n+ order = \"Hill\" if field == \"chemical_formula_hill\" else \"alphabetical\"\n+ raise ValueError(\n+ f\"Elements in {field.name!r} must appear in {order} order: {expected_elements} not {elements}.\"\n+ )\n+\n+ return v\n+\n+ @validator(\"chemical_formula_anonymous\")\n+ def check_anonymous_formula(cls, v):\n+ elements = tuple(re.findall(r\"[A-Z][a-z]*\", v))\n+ numbers = [int(n.strip()) for n in re.split(r\"[A-Z][a-z]*\", v) if n.strip()]\n+\n+ if any(n == 1 for n in numbers):\n+ raise ValueError(\n+ \"'chemical_formula_anonymous' {v} must omit proportion '1'\"\n+ )\n+\n+ expected_labels = ANONYMOUS_ELEMENTS[: len(elements)]\n+ expected_numbers = sorted(numbers, reverse=True)\n+\n+ if expected_numbers != numbers:\n+ raise ValueError(\n+ f\"'chemical_formula_anonymous' {v} has wrong order: elements with highest proportion should appear first: {numbers} vs expected {expected_numbers}\"\n+ )\n+ if elements != expected_labels:\n+ raise ValueError(\n+ f\"'chemical_formula_anonymous' {v} has wrong labels: {elements} vs expected {expected_labels}.\"\n+ )\n+\n+ return v\n+\n @validator(\"elements\", each_item=True)\n def element_must_be_chemical_symbol(cls, v):\n if v not in CHEMICAL_SYMBOLS:\n@@ -778,12 +840,6 @@ The properties of the species are found in the property `species`.\n )\n return v\n \n- @validator(\"chemical_formula_reduced\", \"chemical_formula_hill\")\n- def no_spaces_in_reduced(cls, v):\n- if v and \" \" in v:\n- raise ValueError(f\"Spaces are not allowed, you passed: {v}\")\n- return v\n-\n @validator(\"nperiodic_dimensions\")\n def check_periodic_dimensions(cls, v, values):\n if values.get(\"dimension_types\", []) and v is None:\ndiff --git a/optimade/models/utils.py b/optimade/models/utils.py\nindex 5f02f3c1..f3765e41 100644\n--- a/optimade/models/utils.py\n+++ b/optimade/models/utils.py\n@@ -1,6 +1,7 @@\n import inspect\n import warnings\n import re\n+import itertools\n from enum import Enum\n from typing import Optional\n \n@@ -182,6 +183,22 @@ class SemanticVersion(str):\n return f\"{self.major}.{self.minor}.{self.patch}\"\n \n \n+def anonymous_element_generator():\n+ \"\"\" Generator that yields the next symbol in the A, B, Aa, ... Az naming scheme. \"\"\"\n+ from string import ascii_lowercase\n+\n+ for size in itertools.count(1):\n+ for s in itertools.product(ascii_lowercase, repeat=size):\n+ s = list(s)\n+ s[0] = s[0].upper()\n+ yield \"\".join(s)\n+\n+\n+ANONYMOUS_ELEMENTS = tuple(itertools.islice(anonymous_element_generator(), 150))\n+\"\"\" Returns the first 150 values of the anonymous element generator. \"\"\"\n+\n+CHEMICAL_FORMULA_REGEXP = r\"^([A-Z][a-z]?\\d*)*$\"\n+\n EXTRA_SYMBOLS = [\"X\", \"vacancy\"]\n \n CHEMICAL_SYMBOLS = [\ndiff --git a/setup.py b/setup.py\nindex 9db85cfd..a222f209 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -89,7 +89,7 @@ setup(\n install_requires=[\n \"lark-parser~=0.10.1\",\n \"fastapi~=0.61.1\",\n- \"pydantic~=1.6\",\n+ \"pydantic~=1.6.1\",\n \"email_validator~=1.1\",\n \"requests~=2.24\",\n 'typing-extensions~=3.7;python_version<\"3.8\"',\n", "test_patch": "diff --git a/optimade/server/data/test_structures.json b/optimade/server/data/test_structures.json\nindex 65bf537a..6bd7d291 100644\n--- a/optimade/server/data/test_structures.json\n+++ b/optimade/server/data/test_structures.json\n@@ -64,11 +64,14 @@\n \"structure_features\": [],\n \"task_id\": \"mpf_1\",\n \"relationships\": {\n- \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"dijkstra1968\"}\n- ]\n- }\n+ \"references\": {\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"dijkstra1968\"\n+ }\n+ ]\n+ }\n }\n },\n {\n@@ -176,11 +179,14 @@\n \"structure_features\": [],\n \"task_id\": \"mpf_2\",\n \"relationships\": {\n- \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"dijkstra1968\"}\n- ]\n- }\n+ \"references\": {\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"dijkstra1968\"\n+ }\n+ ]\n+ }\n }\n },\n {\n@@ -288,11 +294,14 @@\n \"structure_features\": [],\n \"task_id\": \"mpf_3\",\n \"relationships\": {\n- \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"maddox1988\"}\n- ]\n- }\n+ \"references\": {\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"maddox1988\"\n+ }\n+ ]\n+ }\n }\n },\n {\n@@ -556,7 +565,7 @@\n ],\n \"nelements\": 4,\n \"nsites\": 5,\n- \"pretty_formula\": \"AcCuO2F\",\n+ \"pretty_formula\": \"AcCuFO2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -798,7 +807,7 @@\n ],\n \"nelements\": 4,\n \"nsites\": 16,\n- \"pretty_formula\": \"Ag10Te4BrCl\",\n+ \"pretty_formula\": \"Ag10BrClTe4\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -960,7 +969,7 @@\n ],\n \"nelements\": 6,\n \"nsites\": 10,\n- \"pretty_formula\": \"Ag2CSNClO4\",\n+ \"pretty_formula\": \"Ag2CClNO4S\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1202,7 +1211,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 24,\n- \"pretty_formula\": \"Ag2H12C6N3Cl\",\n+ \"pretty_formula\": \"Ag2C6ClH12N3\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1454,7 +1463,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 25,\n- \"pretty_formula\": \"Ag2H2C2N6O13\",\n+ \"pretty_formula\": \"Ag2C2H2N6O13\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1701,7 +1710,7 @@\n ],\n \"nelements\": 7,\n \"nsites\": 23,\n- \"pretty_formula\": \"Ag2H8C2S2N5ClO3\",\n+ \"pretty_formula\": \"Ag2C2ClH8N5O3S2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1937,7 +1946,7 @@\n ],\n \"nelements\": 6,\n \"nsites\": 18,\n- \"pretty_formula\": \"Ag4Hg5S5IBrCl2\",\n+ \"pretty_formula\": \"Ag4BrCl2Hg5IS5\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -2443,7 +2452,7 @@\n ],\n \"nelements\": 8,\n \"nsites\": 74,\n- \"pretty_formula\": \"AgB10P2H40C15NCl2O3\",\n+ \"pretty_formula\": \"AgB10C15Cl2H40NO3P2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -2796,7 +2805,7 @@\n ],\n \"nelements\": 7,\n \"nsites\": 29,\n- \"pretty_formula\": \"AgH14C3S3N6ClO\",\n+ \"pretty_formula\": \"AgC3ClH14N6OS3\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -3172,7 +3181,7 @@\n ],\n \"nelements\": 8,\n \"nsites\": 44,\n- \"pretty_formula\": \"Ba2NaCe2Ti2FeSi8HO27\",\n+ \"pretty_formula\": \"Ba2Ce2FeHNaO27Si8Ti2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -3574,7 +3583,7 @@\n ],\n \"nelements\": 9,\n \"nsites\": 44,\n- \"pretty_formula\": \"Ba2NaTi2MnRe2Si8HO26F\",\n+ \"pretty_formula\": \"Ba2FHMnNaO26Re2Si8Ti2\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -3708,9 +3717,12 @@\n \"task_id\": \"mpf_3819\",\n \"relationships\": {\n \"references\": {\n- \"data\": [\n- {\"type\": \"references\", \"id\": \"dummy/2019\"}\n- ]\n+ \"data\": [\n+ {\n+ \"type\": \"references\",\n+ \"id\": \"dummy/2019\"\n+ }\n+ ]\n }\n }\n }\ndiff --git a/tests/adapters/structures/raw_test_structures.json b/tests/adapters/structures/raw_test_structures.json\nindex 082d55e0..be13ed70 100644\n--- a/tests/adapters/structures/raw_test_structures.json\n+++ b/tests/adapters/structures/raw_test_structures.json\n@@ -506,7 +506,7 @@\n 0.4\n ],\n \"chemical_formula_descriptive\": \"AcCuO2F\",\n- \"chemical_formula_reduced\": \"AcCuO2F\",\n+ \"chemical_formula_reduced\": \"AcCuFO2\",\n \"chemical_formula_anonymous\": \"A2BCD\",\n \"dimension_types\": [\n 1,\n@@ -691,7 +691,7 @@\n 0.25\n ],\n \"chemical_formula_descriptive\": \"Ag10Te4BrCl\",\n- \"chemical_formula_reduced\": \"Ag10Te4BrCl\",\n+ \"chemical_formula_reduced\": \"Ag10BrClTe4\",\n \"chemical_formula_anonymous\": \"A10B4CD\",\n \"dimension_types\": [\n 1,\n@@ -882,7 +882,7 @@\n 0.1\n ],\n \"chemical_formula_descriptive\": \"Ag2CSNClO4\",\n- \"chemical_formula_reduced\": \"Ag2CSNClO4\",\n+ \"chemical_formula_reduced\": \"Ag2CClNO4S\",\n \"chemical_formula_anonymous\": \"A4B2CDEF\",\n \"dimension_types\": [\n 1,\n@@ -1053,7 +1053,7 @@\n 0.125\n ],\n \"chemical_formula_descriptive\": \"Ag2H12C6N3Cl\",\n- \"chemical_formula_reduced\": \"Ag2H12C6N3Cl\",\n+ \"chemical_formula_reduced\": \"Ag2C6ClH12N3\",\n \"chemical_formula_anonymous\": \"A12B6C3D2E\",\n \"dimension_types\": [\n 1,\n@@ -1299,7 +1299,7 @@\n 0.52\n ],\n \"chemical_formula_descriptive\": \"Ag2H2C2N6O13\",\n- \"chemical_formula_reduced\": \"Ag2H2C2N6O13\",\n+ \"chemical_formula_reduced\": \"Ag2C2H2N6O13\",\n \"chemical_formula_anonymous\": \"A13B6C2D2E2\",\n \"dimension_types\": [\n 1,\n@@ -1555,7 +1555,7 @@\n 0.08695652173913043\n ],\n \"chemical_formula_descriptive\": \"Ag2H8C2S2N5ClO3\",\n- \"chemical_formula_reduced\": \"Ag2H8C2S2N5ClO3\",\n+ \"chemical_formula_reduced\": \"Ag2C2ClH8N5O3S2\",\n \"chemical_formula_anonymous\": \"A8B5C3D2E2F2G\",\n \"dimension_types\": [\n 1,\n@@ -1815,7 +1815,7 @@\n 0.2777777777777778\n ],\n \"chemical_formula_descriptive\": \"Ag4Hg5S5IBrCl2\",\n- \"chemical_formula_reduced\": \"Ag4Hg5S5IBrCl2\",\n+ \"chemical_formula_reduced\": \"Ag4BrCl2Hg5IS5\",\n \"chemical_formula_anonymous\": \"A5B5C4D2EF\",\n \"dimension_types\": [\n 1,\n@@ -2040,7 +2040,7 @@\n 0.02702702702702703\n ],\n \"chemical_formula_descriptive\": \"AgB10P2H40C15NCl2O3\",\n- \"chemical_formula_reduced\": \"AgB10P2H40C15NCl2O3\",\n+ \"chemical_formula_reduced\": \"AgB10C15Cl2H40NO3P2\",\n \"chemical_formula_anonymous\": \"A40B15C10D3E2F2GH\",\n \"dimension_types\": [\n 1,\n@@ -2617,7 +2617,7 @@\n 0.10344827586206896\n ],\n \"chemical_formula_descriptive\": \"AgH14C3S3N6ClO\",\n- \"chemical_formula_reduced\": \"AgH14C3S3N6ClO\",\n+ \"chemical_formula_reduced\": \"AgC3ClH14N6OS3\",\n \"chemical_formula_anonymous\": \"A14B6C3D3EFG\",\n \"dimension_types\": [\n 1,\n@@ -2917,7 +2917,7 @@\n 0.045454545454545456\n ],\n \"chemical_formula_descriptive\": \"Ba2NaCe2Ti2FeSi8HO27\",\n- \"chemical_formula_reduced\": \"Ba2NaCe2Ti2FeSi8HO27\",\n+ \"chemical_formula_reduced\": \"Ba2Ce2FeHNaO27Si8Ti2\",\n \"chemical_formula_anonymous\": \"A27B8C2D2E2FGH\",\n \"dimension_types\": [\n 1,\n@@ -3318,7 +3318,7 @@\n 0.045454545454545456\n ],\n \"chemical_formula_descriptive\": \"Ba2NaTi2MnRe2Si8HO26F\",\n- \"chemical_formula_reduced\": \"Ba2NaTi2MnRe2Si8HO26F\",\n+ \"chemical_formula_reduced\": \"Ba2FHMnNaO26Re2Si8Ti2\",\n \"chemical_formula_anonymous\": \"A26B8C2D2E2FGHI\",\n \"dimension_types\": [\n 1,\ndiff --git a/tests/models/conftest.py b/tests/models/conftest.py\nindex cb964f4b..ff0daebe 100644\n--- a/tests/models/conftest.py\n+++ b/tests/models/conftest.py\n@@ -63,3 +63,49 @@ def starting_links() -> dict:\n \"aggregate\": \"test\",\n \"no_aggregate_reason\": \"This is a test database\",\n }\n+\n+\n+@pytest.fixture(scope=\"function\")\n+def good_structure() -> dict:\n+ \"\"\"Returns a 'good' structure that does not need to be mapped, which can be\n+ deformed to test different validators.\n+\n+ \"\"\"\n+ import datetime\n+\n+ return {\n+ \"id\": \"db/1234567\",\n+ \"type\": \"structures\",\n+ \"attributes\": {\n+ \"last_modified\": datetime.datetime.now(),\n+ \"elements\": [\"Ge\", \"Si\"],\n+ \"nsites\": 3,\n+ \"nelements\": 2,\n+ \"elements_ratios\": [0.5, 0.5],\n+ \"chemical_formula_reduced\": \"GeSi\",\n+ \"chemical_formula_hill\": \"GeSi\",\n+ \"chemical_formula_descriptive\": \"GeSi\",\n+ \"chemical_formula_anonymous\": \"AB\",\n+ \"dimension_types\": [1, 1, 1],\n+ \"nperiodic_dimensions\": 3,\n+ \"lattice_vectors\": [[4.0, 0.0, 0.0], [0.0, 4.0, 0.0], [0.0, 1.0, 4.0]],\n+ \"cartesian_site_positions\": [[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n+ \"species\": [\n+ {\"name\": \"Si\", \"chemical_symbols\": [\"Si\"], \"concentration\": [1.0]},\n+ {\"name\": \"Ge\", \"chemical_symbols\": [\"Ge\"], \"concentration\": [1.0]},\n+ {\n+ \"name\": \"vac\",\n+ \"chemical_symbols\": [\"vacancy\"],\n+ \"concentration\": [1.0],\n+ },\n+ ],\n+ \"species_at_sites\": [\"Si\", \"Ge\", \"vac\"],\n+ \"assemblies\": [\n+ {\n+ \"sites_in_groups\": [[0], [1], [2]],\n+ \"group_probabilities\": [0.3, 0.5, 0.2],\n+ }\n+ ],\n+ \"structure_features\": [\"assemblies\"],\n+ },\n+ }\ndiff --git a/tests/models/test_data/test_bad_structures.json b/tests/models/test_data/test_bad_structures.json\nindex 12697659..100feb90 100644\n--- a/tests/models/test_data/test_bad_structures.json\n+++ b/tests/models/test_data/test_bad_structures.json\n@@ -772,7 +772,7 @@\n ],\n \"nelements\": 4,\n \"nsites\": 16,\n- \"pretty_formula\": \"Ag10Te4BrCl\",\n+ \"pretty_formula\": \"Ag10BrClTe4\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -934,7 +934,7 @@\n ],\n \"nelements\": 6,\n \"nsites\": 10,\n- \"pretty_formula\": \"Ag2CSNClO4\",\n+ \"pretty_formula\": \"Ag2CClNO4S\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1176,7 +1176,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 24,\n- \"pretty_formula\": \"Ag2H12C6N3Cl\",\n+ \"pretty_formula\": \"Ag2C6ClH12N3\",\n \"species\": [\n {\n \"chemical_symbols\": [\n@@ -1428,7 +1428,7 @@\n ],\n \"nelements\": 5,\n \"nsites\": 25,\n- \"pretty_formula\": \"Ag2H2C2N6O13\",\n+ \"pretty_formula\": \"Ag2C2H2N6O13\",\n \"species\": [\n {\n \"chemical_symbols\": [\ndiff --git a/tests/models/test_structures.py b/tests/models/test_structures.py\nindex 31ad9d2f..24d63877 100644\n--- a/tests/models/test_structures.py\n+++ b/tests/models/test_structures.py\n@@ -39,3 +39,44 @@ def test_bad_structures(bad_structures, mapper):\n print(f\"Trying structure number {index} from 'test_bad_structures.json'\")\n with pytest.raises(ValidationError):\n StructureResource(**mapper(MAPPER).map_back(structure))\n+\n+\n+deformities = (\n+ None,\n+ {\"chemical_formula_anonymous\": \"AaBC\"},\n+ {\"chemical_formula_anonymous\": \"BC\"},\n+ {\"chemical_formula_anonymous\": \"A1B1\"},\n+ {\"chemical_formula_anonymous\": \"BC1\"},\n+ {\"chemical_formula_anonymous\": \"A9C\"},\n+ {\"chemical_formula_anonymous\": \"A9.2B\"},\n+ {\"chemical_formula_anonymous\": \"A2B90\"},\n+ {\"chemical_formula_anonymous\": \"A2B10\"},\n+ {\"chemical_formula_hill\": \"SiGe\"},\n+ {\"chemical_formula_hill\": \"GeHSi\"},\n+ {\"chemical_formula_hill\": \"CGeHSi\"},\n+ {\"chemical_formula_reduced\": \"Ge1.0Si1.0\"},\n+ {\"chemical_formula_reduced\": \"GeSi2.0\"},\n+ {\"chemical_formula_reduced\": \"GeSi.2\"},\n+ {\"chemical_formula_reduced\": \"Ge1Si\"},\n+ {\"chemical_formula_reduced\": \"GeSi1\"},\n+ {\"chemical_formula_reduced\": \"SiGe2\"},\n+ {\"chemical_formula_reduced\": \"FaKeElEmENtS\"},\n+ {\"chemical_formula_reduced\": \"abcd\"},\n+ {\"chemical_formula_reduced\": \"a2BeH\"},\n+ {\"chemical_formula_reduced\": \"............\"},\n+ {\"chemical_formula_reduced\": \"Ag6 Cl2\"},\n+)\n+\n+\n+@pytest.mark.parametrize(\"deformity\", deformities)\n+def test_structure_deformities(good_structure, deformity):\n+ \"\"\"Make specific checks upon performing single invalidating deformations\n+ of the data of a good structure.\n+\n+ \"\"\"\n+ if deformity is None:\n+ StructureResource(**good_structure)\n+ else:\n+ good_structure[\"attributes\"].update(deformity)\n+ with pytest.raises(ValidationError, match=fr\".*{list(deformity.keys())[0]}.*\"):\n+ StructureResource(**good_structure)\ndiff --git a/tests/models/test_utils.py b/tests/models/test_utils.py\nindex 279d4d68..61d10d47 100644\n--- a/tests/models/test_utils.py\n+++ b/tests/models/test_utils.py\n@@ -1,5 +1,5 @@\n import pytest\n-from pydantic import BaseModel\n+from pydantic import BaseModel, ValidationError, Field\n from optimade.models.utils import OptimadeField, StrictField, SupportLevel\n from typing import List, Callable\n \n@@ -74,3 +74,40 @@ def test_compatible_strict_optimade_field():\n strict_schema = CorrectModelWithStrictField.schema()\n strict_schema[\"title\"] = optimade_schema[\"title\"]\n assert strict_schema == optimade_schema\n+\n+\n+def test_formula_regexp():\n+ \"\"\"This test checks some simple chemical formulae with the\n+ `CHEMICAL_FORMULA_REGEXP`.\n+\n+ \"\"\"\n+ import re\n+ from optimade.models.utils import CHEMICAL_FORMULA_REGEXP\n+\n+ class DummyModel(BaseModel):\n+ formula: str = Field(regex=CHEMICAL_FORMULA_REGEXP)\n+\n+ good_formulae = (\n+ \"AgCl\",\n+ \"H5F\",\n+ \"LiP5\",\n+ \"Jn7Qb4\", # Regexp does not care about the actual existence of elements\n+ \"A5B213CeD3E65F12G\",\n+ \"A1Be2\",\n+ )\n+\n+ bad_formulae = (\n+ \"Ag...Cl\",\n+ \"123123\",\n+ \"Ag Cl\",\n+ \"abcd\",\n+ \"6F7G\",\n+ )\n+\n+ for formula in good_formulae:\n+ assert re.match(CHEMICAL_FORMULA_REGEXP, formula)\n+ assert DummyModel(formula=formula)\n+\n+ for formula in bad_formulae:\n+ with pytest.raises(ValidationError):\n+ assert DummyModel(formula=formula)\ndiff --git a/tests/server/query_params/test_filter.py b/tests/server/query_params/test_filter.py\nindex 213ca68b..2633d162 100644\n--- a/tests/server/query_params/test_filter.py\n+++ b/tests/server/query_params/test_filter.py\n@@ -208,13 +208,13 @@ def test_string_contains(check_response):\n \n \n def test_string_start(check_response):\n- request = '/structures?filter=chemical_formula_descriptive STARTS WITH \"Ag2CSNCl\"'\n+ request = '/structures?filter=chemical_formula_descriptive STARTS WITH \"Ag2CClN\"'\n expected_ids = [\"mpf_259\"]\n check_response(request, expected_ids)\n \n \n def test_string_end(check_response):\n- request = '/structures?filter=chemical_formula_descriptive ENDS WITH \"NClO4\"'\n+ request = '/structures?filter=chemical_formula_descriptive ENDS WITH \"ClNO4S\"'\n expected_ids = [\"mpf_259\"]\n check_response(request, expected_ids)\n \n@@ -237,7 +237,7 @@ def test_awkward_not_queries(check_response, client):\n \"\"\"\n expected_ids = [\"mpf_3819\"]\n request = (\n- '/structures?filter=chemical_formula_descriptive=\"Ba2NaTi2MnRe2Si8HO26F\" AND '\n+ '/structures?filter=chemical_formula_descriptive=\"Ba2FHMnNaO26Re2Si8Ti2\" AND '\n 'chemical_formula_anonymous = \"A26B8C2D2E2FGHI\" '\n )\n check_response(request, expected_ids)\n@@ -260,7 +260,7 @@ def test_awkward_not_queries(check_response, client):\n request = (\n \"/structures?filter=\"\n \"NOT ( \"\n- 'chemical_formula_descriptive = \"Ba2NaTi2MnRe2Si8HO26F\" AND '\n+ 'chemical_formula_descriptive = \"Ba2FHMnNaO26Re2Si8Ti2\" AND '\n 'chemical_formula_anonymous = \"A26B8C2D2E2FGHI\" OR '\n 'chemical_formula_anonymous = \"A2BC\" AND '\n 'NOT chemical_formula_descriptive = \"Ac2AgPb\" '\n", "FAIL_TO_PASS": ["tests/models/test_structures.py::test_structure_deformities[deformity1]", "tests/models/test_structures.py::test_structure_deformities[deformity2]", "tests/models/test_structures.py::test_structure_deformities[deformity3]", "tests/models/test_structures.py::test_structure_deformities[deformity4]", "tests/models/test_structures.py::test_structure_deformities[deformity5]", "tests/models/test_structures.py::test_structure_deformities[deformity6]", "tests/models/test_structures.py::test_structure_deformities[deformity7]", "tests/models/test_structures.py::test_structure_deformities[deformity8]", "tests/models/test_structures.py::test_structure_deformities[deformity9]", "tests/models/test_structures.py::test_structure_deformities[deformity10]", "tests/models/test_structures.py::test_structure_deformities[deformity11]", "tests/models/test_structures.py::test_structure_deformities[deformity12]", "tests/models/test_structures.py::test_structure_deformities[deformity13]", "tests/models/test_structures.py::test_structure_deformities[deformity14]", "tests/models/test_structures.py::test_structure_deformities[deformity15]", "tests/models/test_structures.py::test_structure_deformities[deformity16]", "tests/models/test_structures.py::test_structure_deformities[deformity17]", "tests/models/test_structures.py::test_structure_deformities[deformity18]", "tests/models/test_structures.py::test_structure_deformities[deformity19]", "tests/models/test_structures.py::test_structure_deformities[deformity20]", "tests/models/test_structures.py::test_structure_deformities[deformity21]", "tests/models/test_utils.py::test_formula_regexp"]}, {"instance_id": "materials-consortia__optimade-python-tools-582", "base_commit": "e7a8de9822da1edd8a2432e8d562982e27f00255", "gold_patch": "diff --git a/optimade/models/structures.py b/optimade/models/structures.py\nindex 4203824a..e1aebb19 100644\n--- a/optimade/models/structures.py\n+++ b/optimade/models/structures.py\n@@ -774,7 +774,8 @@ The properties of the species are found in the property `species`.\n expected_elements = sorted(elements)\n \n if field.name == \"chemical_formula_hill\":\n- for elem in (\"C\", \"H\"):\n+ # Make sure C is first and H is second.\n+ for elem in (\"H\", \"C\"):\n if elem in expected_elements:\n expected_elements.pop(expected_elements.index(elem))\n expected_elements.insert(0, elem)\n@@ -786,10 +787,10 @@ The properties of the species are found in the property `species`.\n \n if \"1\" in numbers:\n raise ValueError(\n- \"Must omit proportion '1' from formula {v} in {field.name!r}\"\n+ f\"Must omit proportion '1' from formula {v} in {field.name!r}\"\n )\n if expected_elements != elements:\n- order = \"Hill\" if field == \"chemical_formula_hill\" else \"alphabetical\"\n+ order = \"Hill\" if field.name == \"chemical_formula_hill\" else \"alphabetical\"\n raise ValueError(\n f\"Elements in {field.name!r} must appear in {order} order: {expected_elements} not {elements}.\"\n )\n@@ -803,7 +804,7 @@ The properties of the species are found in the property `species`.\n \n if any(n == 1 for n in numbers):\n raise ValueError(\n- \"'chemical_formula_anonymous' {v} must omit proportion '1'\"\n+ f\"'chemical_formula_anonymous' {v} must omit proportion '1'\"\n )\n \n expected_labels = ANONYMOUS_ELEMENTS[: len(elements)]\n", "test_patch": "diff --git a/tests/models/test_data/test_bad_structures.json b/tests/models/test_data/test_bad_structures.json\nindex 100feb90..1204198b 100644\n--- a/tests/models/test_data/test_bad_structures.json\n+++ b/tests/models/test_data/test_bad_structures.json\n@@ -2403,5 +2403,37 @@\n }\n ],\n \"structure_features\": [\"assemblies\"]\n+ },\n+ {\n+ \"task_id\": \"db/1234567\",\n+ \"type\": \"structure\",\n+ \"last_modified\": {\n+ \"$date\": \"2019-06-08T05:13:37.331Z\"\n+ },\n+ \"band_gap\": 1.23456,\n+ \"chemsys\": \"C-H-Cl-N-Na-O-Os-P\",\n+ \"elements\": [\"C\", \"Cl\", \"H\", \"N\", \"Na\", \"O\", \"Os\", \"P\"],\n+ \"nelements\": 8,\n+ \"nsites\": 7,\n+ \"elements_ratios\": [0.09090909091, 0.36363636363, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091],\n+ \"chemical_formula_reduced\": \"CClH4NNaOOsP\",\n+ \"chemical_formula_hill\": \"H4CClNNaOOsP\",\n+ \"chemical_formula_descriptive\": \"Methyl-ClNNaOOsP\",\n+ \"formula_anonymous\": \"A4BCDEFGH\",\n+ \"dimension_types\": [1, 1, 1],\n+ \"nperiodic_dimensions\": 3,\n+ \"lattice_vectors\": [[4.0,0.0,0.0],[0.0, 4.0, 0.0],[0.0,1.0,4.0]],\n+ \"cartesian_site_positions\": [ [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0] ],\n+ \"species_at_sites\": [\"Cl\", \"O\", \"N\", \"met\", \"Os\", \"Na\", \"P\"],\n+ \"species\": [\n+ {\"name\": \"Cl\", \"chemical_symbols\": [\"Cl\"], \"concentration\": [1.0] },\n+ {\"name\": \"O\", \"chemical_symbols\": [\"O\"], \"concentration\": [1.0] },\n+ {\"name\": \"N\", \"chemical_symbols\": [\"N\"], \"concentration\": [1.0] },\n+ {\"name\": \"met\", \"chemical_symbols\": [\"C\"], \"concentration\": [1.0], \"attached\": [\"H\"], \"nattached\": [4] },\n+ {\"name\": \"Os\", \"chemical_symbols\": [\"Os\"], \"concentration\": [1.0] },\n+ {\"name\": \"Na\", \"chemical_symbols\": [\"Na\"], \"concentration\": [1.0] },\n+ {\"name\": \"P\", \"chemical_symbols\": [\"P\"], \"concentration\": [1.0] }\n+ ],\n+ \"structure_features\": [\"site_attachments\"]\n }\n ]\ndiff --git a/tests/models/test_data/test_good_structures.json b/tests/models/test_data/test_good_structures.json\nindex a44bb018..09478ba6 100644\n--- a/tests/models/test_data/test_good_structures.json\n+++ b/tests/models/test_data/test_good_structures.json\n@@ -158,5 +158,37 @@\n }\n ],\n \"structure_features\": [\"assemblies\", \"site_attachments\"]\n+ },\n+ {\n+ \"task_id\": \"db/1234567\",\n+ \"type\": \"structure\",\n+ \"last_modified\": {\n+ \"$date\": \"2019-06-08T05:13:37.331Z\"\n+ },\n+ \"band_gap\": 1.23456,\n+ \"chemsys\": \"C-H-Cl-N-Na-O-Os-P\",\n+ \"elements\": [\"C\", \"Cl\", \"H\", \"N\", \"Na\", \"O\", \"Os\", \"P\"],\n+ \"nelements\": 8,\n+ \"nsites\": 7,\n+ \"elements_ratios\": [0.09090909091, 0.36363636363, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091],\n+ \"chemical_formula_reduced\": \"CClH4NNaOOsP\",\n+ \"chemical_formula_hill\": \"CH4ClNNaOOsP\",\n+ \"chemical_formula_descriptive\": \"Methyl-ClNNaOOsP\",\n+ \"formula_anonymous\": \"A4BCDEFGH\",\n+ \"dimension_types\": [1, 1, 1],\n+ \"nperiodic_dimensions\": 3,\n+ \"lattice_vectors\": [[4.0,0.0,0.0],[0.0, 4.0, 0.0],[0.0,1.0,4.0]],\n+ \"cartesian_site_positions\": [ [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0] ],\n+ \"species_at_sites\": [\"Cl\", \"O\", \"N\", \"met\", \"Os\", \"Na\", \"P\"],\n+ \"species\": [\n+ {\"name\": \"Cl\", \"chemical_symbols\": [\"Cl\"], \"concentration\": [1.0] },\n+ {\"name\": \"O\", \"chemical_symbols\": [\"O\"], \"concentration\": [1.0] },\n+ {\"name\": \"N\", \"chemical_symbols\": [\"N\"], \"concentration\": [1.0] },\n+ {\"name\": \"met\", \"chemical_symbols\": [\"C\"], \"concentration\": [1.0], \"attached\": [\"H\"], \"nattached\": [4] },\n+ {\"name\": \"Os\", \"chemical_symbols\": [\"Os\"], \"concentration\": [1.0] },\n+ {\"name\": \"Na\", \"chemical_symbols\": [\"Na\"], \"concentration\": [1.0] },\n+ {\"name\": \"P\", \"chemical_symbols\": [\"P\"], \"concentration\": [1.0] }\n+ ],\n+ \"structure_features\": [\"site_attachments\"]\n }\n ]\ndiff --git a/tests/models/test_structures.py b/tests/models/test_structures.py\nindex 24d63877..ca72018d 100644\n--- a/tests/models/test_structures.py\n+++ b/tests/models/test_structures.py\n@@ -54,6 +54,7 @@ deformities = (\n {\"chemical_formula_hill\": \"SiGe\"},\n {\"chemical_formula_hill\": \"GeHSi\"},\n {\"chemical_formula_hill\": \"CGeHSi\"},\n+ {\"chemical_formula_hill\": \"HCGeSi\"},\n {\"chemical_formula_reduced\": \"Ge1.0Si1.0\"},\n {\"chemical_formula_reduced\": \"GeSi2.0\"},\n {\"chemical_formula_reduced\": \"GeSi.2\"},\n", "FAIL_TO_PASS": ["tests/models/test_structures.py::test_more_good_structures", "tests/models/test_structures.py::test_bad_structures", "tests/models/test_structures.py::test_structure_deformities[deformity12]"]}], "all_FAIL_TO_PASS": ["tests/models/test_structures.py::test_structure_deformities[deformity1]", "tests/models/test_structures.py::test_structure_deformities[deformity2]", "tests/models/test_structures.py::test_structure_deformities[deformity3]", "tests/models/test_structures.py::test_structure_deformities[deformity4]", "tests/models/test_structures.py::test_structure_deformities[deformity5]", "tests/models/test_structures.py::test_structure_deformities[deformity6]", "tests/models/test_structures.py::test_structure_deformities[deformity7]", "tests/models/test_structures.py::test_structure_deformities[deformity8]", "tests/models/test_structures.py::test_structure_deformities[deformity9]", "tests/models/test_structures.py::test_structure_deformities[deformity10]", "tests/models/test_structures.py::test_structure_deformities[deformity11]", "tests/models/test_structures.py::test_structure_deformities[deformity12]", "tests/models/test_structures.py::test_structure_deformities[deformity13]", "tests/models/test_structures.py::test_structure_deformities[deformity14]", "tests/models/test_structures.py::test_structure_deformities[deformity15]", "tests/models/test_structures.py::test_structure_deformities[deformity16]", "tests/models/test_structures.py::test_structure_deformities[deformity17]", "tests/models/test_structures.py::test_structure_deformities[deformity18]", "tests/models/test_structures.py::test_structure_deformities[deformity19]", "tests/models/test_structures.py::test_structure_deformities[deformity20]", "tests/models/test_structures.py::test_structure_deformities[deformity21]", "tests/models/test_utils.py::test_formula_regexp", "tests/models/test_structures.py::test_more_good_structures", "tests/models/test_structures.py::test_bad_structures", "tests/models/test_structures.py::test_structure_deformities[deformity12]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "yt-project__unyt-102_x2", "level": 2, "source": "swerebenchv2", "repo": "yt-project/unyt", "image": "swerebenchv2/yt-project-unyt:102-b779d0a", "base_commit": "b779d0a31ed3e5f8d1c035c90e4878a5078b39fc", "num_bugs": 2, "bugs": [{"instance_id": "yt-project__unyt-102", "base_commit": "b779d0a31ed3e5f8d1c035c90e4878a5078b39fc", "gold_patch": "diff --git a/tox.ini b/tox.ini\nindex 6350941..56ee095 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -12,7 +12,7 @@ setenv =\n PYTHONPATH = {toxinidir}\n depends = begin\n deps =\n- pytest\n+ pytest<5.1\n sympy\n numpy\n h5py\n@@ -30,7 +30,7 @@ commands =\n \n [testenv:py35-versions]\n deps =\n- pytest\n+ pytest<5.1\n sympy==1.2\n numpy==1.13.3\n h5py==2.6.0\n@@ -46,7 +46,7 @@ commands =\n \n [testenv:py35-dependencies]\n deps =\n- pytest\n+ pytest<5.1\n sympy\n numpy\n coverage\ndiff --git a/unyt/array.py b/unyt/array.py\nindex d601e85..ac7e643 100644\n--- a/unyt/array.py\n+++ b/unyt/array.py\n@@ -106,6 +106,11 @@ from numpy import (\n matmul,\n )\n from numpy.core.umath import _ones_like\n+\n+try:\n+ from numpy.core.umath import clip\n+except ImportError:\n+ clip = None\n from sympy import Rational\n import warnings\n \n@@ -457,6 +462,7 @@ class unyt_array(np.ndarray):\n heaviside: _preserve_units,\n _ones_like: _preserve_units,\n matmul: _multiply_units,\n+ clip: _passthrough_unit,\n }\n \n __array_priority__ = 2.0\n@@ -1705,10 +1711,21 @@ class unyt_array(np.ndarray):\n \"cannot by multiplied, divide, subtracted or added.\"\n )\n else:\n- raise RuntimeError(\n- \"Support for the %s ufunc with %i inputs has not been\"\n- \"added to unyt_array.\" % (str(ufunc), len(inputs))\n- )\n+ if ufunc is clip:\n+ inp = (inputs[0].view(np.ndarray), inputs[1], inputs[2])\n+ if out is not None:\n+ _out = out.view(np.ndarray)\n+ else:\n+ _out = None\n+ out_arr = ufunc(*inp, out=_out)\n+ unit = inputs[0].units\n+ ret_class = type(inputs[0])\n+ mul = 1\n+ else:\n+ raise RuntimeError(\n+ \"Support for the %s ufunc with %i inputs has not been \"\n+ \"added to unyt_array.\" % (str(ufunc), len(inputs))\n+ )\n if unit is None:\n out_arr = np.array(out_arr, copy=False)\n elif ufunc in (modf, divmod_):\n", "test_patch": "diff --git a/unyt/tests/test_unyt_array.py b/unyt/tests/test_unyt_array.py\nindex e588c5a..18b0f09 100644\n--- a/unyt/tests/test_unyt_array.py\n+++ b/unyt/tests/test_unyt_array.py\n@@ -2264,3 +2264,19 @@ def test_input_units_deprecation():\n unyt_array([1, 2, 3], \"mile\"), unyt_array([1, 2, 3], input_units=\"mile\")\n )\n assert unyt_quantity(3, \"mile\") == unyt_quantity(3, input_units=\"mile\")\n+\n+\n+def test_clip():\n+ from unyt import km\n+\n+ data = [1, 2, 3, 4, 5, 6] * km\n+ answer = [2, 2, 3, 4, 4, 4] * km\n+\n+ ret = np.clip(data, 2, 4)\n+ assert_array_equal(ret, answer)\n+ assert ret.units == answer.units\n+\n+ np.clip(data, 2, 4, out=data)\n+\n+ assert_array_equal(data, answer)\n+ assert data.units == answer.units\n", "FAIL_TO_PASS": ["unyt/tests/test_unyt_array.py::test_clip"]}, {"instance_id": "yt-project__unyt-109", "base_commit": "0e465e494ddff446324547c2756ee51313dae7ff", "gold_patch": "diff --git a/unyt/array.py b/unyt/array.py\nindex 6a655e3..c389812 100644\n--- a/unyt/array.py\n+++ b/unyt/array.py\n@@ -1673,7 +1673,26 @@ class unyt_array(np.ndarray):\n elif u1.is_dimensionless:\n u1 = u0\n else:\n- raise UnitOperationError(ufunc, u0, u1)\n+ # comparison with different units, so need to check if\n+ # this is == and != which we allow and handle in a\n+ # special way using an early return from __array_ufunc__\n+ if ufunc in (equal, not_equal):\n+ if ufunc is equal:\n+ func = np.zeros_like\n+ else:\n+ func = np.ones_like\n+ ret = func(np.asarray(inp1), dtype=bool)\n+ if out is not None:\n+ out[:] = ret[:]\n+ if isinstance(out, unyt_array):\n+ out.units = Unit(\n+ \"\", registry=self.units.registry\n+ )\n+ if ret.shape == ():\n+ ret = bool(ret)\n+ return ret\n+ else:\n+ raise UnitOperationError(ufunc, u0, u1)\n else:\n raise UnitOperationError(ufunc, u0, u1)\n conv, offset = u1.get_conversion_factor(u0, inp1.dtype)\n", "test_patch": "diff --git a/unyt/tests/test_unyt_array.py b/unyt/tests/test_unyt_array.py\nindex 78b6caf..5c031cc 100644\n--- a/unyt/tests/test_unyt_array.py\n+++ b/unyt/tests/test_unyt_array.py\n@@ -509,6 +509,7 @@ def test_comparisons():\n a1 = unyt_array([1, 2, 3], \"cm\")\n a2 = unyt_array([2, 1, 3], \"cm\")\n a3 = unyt_array([0.02, 0.01, 0.03], \"m\")\n+ a4 = unyt_array([1, 2, 3], \"g\")\n dimless = np.array([2, 1, 3])\n \n ops = (np.less, np.less_equal, np.greater, np.greater_equal, np.equal, np.not_equal)\n@@ -542,6 +543,26 @@ def test_comparisons():\n assert_equal(2 < a1, [False, False, True])\n assert_equal(2 < a1, np.less(2, a1))\n \n+ # Check that comparisons with arrays that have different units with\n+ # different dimensions work properly\n+ operate_and_compare(a1, a4, np.equal, [False, False, False])\n+ operate_and_compare(a1, a4, np.not_equal, [True, True, True])\n+\n+ # check that comparing quantities returns bools and not 0-D arrays\n+ el1, el4 = a1[0], a4[0]\n+ assert (el1 == el4) is False\n+ assert (el1 != el4) is True\n+\n+ # comparisons that aren't == and !=\n+ with pytest.raises(UnitOperationError):\n+ np.greater(a1, a4)\n+ with pytest.raises(UnitOperationError):\n+ a1 > a4\n+ with pytest.raises(UnitOperationError):\n+ np.greater(el1, el4)\n+ with pytest.raises(UnitOperationError):\n+ el1 > el4\n+\n \n def test_unit_conversions():\n \"\"\"\n@@ -1003,8 +1024,6 @@ def binary_ufunc_comparison(ufunc, a, b):\n \"greater_equal\",\n \"less\",\n \"less_equal\",\n- \"equal\",\n- \"not_equal\",\n \"logical_and\",\n \"logical_or\",\n \"logical_xor\",\n", "FAIL_TO_PASS": ["unyt/tests/test_unyt_array.py::test_comparisons"]}], "all_FAIL_TO_PASS": ["unyt/tests/test_unyt_array.py::test_clip", "unyt/tests/test_unyt_array.py::test_comparisons"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "aio-libs__aiohttp-8858_x2", "level": 2, "source": "swerebenchv2", "repo": "aio-libs/aiohttp", "image": "swerebenchv2/aio-libs-aiohttp:8858-9fffd8b", "base_commit": "9fffd8b3dfd8a899de2996228d6ca8d0e38b0747", "num_bugs": 2, "bugs": [{"instance_id": "aio-libs__aiohttp-8858", "base_commit": "9fffd8b3dfd8a899de2996228d6ca8d0e38b0747", "gold_patch": "diff --git a/CHANGES/8858.bugfix.rst b/CHANGES/8858.bugfix.rst\nnew file mode 100644\nindex 000000000..e4efa91a2\n--- /dev/null\n+++ b/CHANGES/8858.bugfix.rst\n@@ -0,0 +1,1 @@\n+Stopped adding a default Content-Type header when response has no content -- by :user:`Dreamsorcerer`.\ndiff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py\nindex 785b8d15d..678fe453a 100644\n--- a/aiohttp/client_reqrep.py\n+++ b/aiohttp/client_reqrep.py\n@@ -662,9 +662,8 @@ class ClientRequest:\n self.headers[hdrs.CONNECTION] = connection\n \n # status + headers\n- status_line = \"{0} {1} HTTP/{v.major}.{v.minor}\".format(\n- self.method, path, v=self.version\n- )\n+ v = self.version\n+ status_line = f\"{self.method} {path} HTTP/{v.major}.{v.minor}\"\n await writer.write_headers(status_line, self.headers)\n coro = self.write_bytes(writer, conn)\n \ndiff --git a/aiohttp/helpers.py b/aiohttp/helpers.py\nindex 26b953ea7..2be5977c4 100644\n--- a/aiohttp/helpers.py\n+++ b/aiohttp/helpers.py\n@@ -49,7 +49,7 @@ from typing import (\n from urllib.parse import quote\n from urllib.request import getproxies, proxy_bypass\n \n-from multidict import CIMultiDict, MultiDict, MultiDictProxy\n+from multidict import CIMultiDict, MultiDict, MultiDictProxy, MultiMapping\n from yarl import URL\n \n from . import hdrs\n@@ -753,13 +753,15 @@ def ceil_timeout(\n class HeadersMixin:\n __slots__ = (\"_content_type\", \"_content_dict\", \"_stored_content_type\")\n \n+ _headers: MultiMapping[str]\n+\n def __init__(self) -> None:\n super().__init__()\n self._content_type: Optional[str] = None\n self._content_dict: Optional[Dict[str, str]] = None\n- self._stored_content_type: Union[str, _SENTINEL] = sentinel\n+ self._stored_content_type: Union[str, None, _SENTINEL] = sentinel\n \n- def _parse_content_type(self, raw: str) -> None:\n+ def _parse_content_type(self, raw: Optional[str]) -> None:\n self._stored_content_type = raw\n if raw is None:\n # default value according to RFC 2616\n@@ -774,25 +776,25 @@ class HeadersMixin:\n @property\n def content_type(self) -> str:\n \"\"\"The value of content part for Content-Type HTTP header.\"\"\"\n- raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined]\n+ raw = self._headers.get(hdrs.CONTENT_TYPE)\n if self._stored_content_type != raw:\n self._parse_content_type(raw)\n- return self._content_type # type: ignore[return-value]\n+ assert self._content_type is not None\n+ return self._content_type\n \n @property\n def charset(self) -> Optional[str]:\n \"\"\"The value of charset part for Content-Type HTTP header.\"\"\"\n- raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined]\n+ raw = self._headers.get(hdrs.CONTENT_TYPE)\n if self._stored_content_type != raw:\n self._parse_content_type(raw)\n- return self._content_dict.get(\"charset\") # type: ignore[union-attr]\n+ assert self._content_dict is not None\n+ return self._content_dict.get(\"charset\")\n \n @property\n def content_length(self) -> Optional[int]:\n \"\"\"The value of Content-Length HTTP header.\"\"\"\n- content_length = self._headers.get( # type: ignore[attr-defined]\n- hdrs.CONTENT_LENGTH\n- )\n+ content_length = self._headers.get(hdrs.CONTENT_LENGTH)\n \n if content_length is not None:\n return int(content_length)\ndiff --git a/aiohttp/web_request.py b/aiohttp/web_request.py\nindex 828776d82..4dbc19a48 100644\n--- a/aiohttp/web_request.py\n+++ b/aiohttp/web_request.py\n@@ -82,7 +82,7 @@ class FileField:\n filename: str\n file: io.BufferedReader\n content_type: str\n- headers: \"CIMultiDictProxy[str]\"\n+ headers: CIMultiDictProxy[str]\n \n \n _TCHAR: Final[str] = string.digits + string.ascii_letters + r\"!#$%&'*+.^_`|~-\"\n@@ -171,7 +171,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):\n self._payload_writer = payload_writer\n \n self._payload = payload\n- self._headers = message.headers\n+ self._headers: CIMultiDictProxy[str] = message.headers\n self._method = message.method\n self._version = message.version\n self._cache: Dict[str, Any] = {}\n@@ -483,7 +483,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):\n return self._rel_url.query_string\n \n @reify\n- def headers(self) -> \"CIMultiDictProxy[str]\":\n+ def headers(self) -> CIMultiDictProxy[str]:\n \"\"\"A case-insensitive multidict proxy with all headers.\"\"\"\n return self._headers\n \ndiff --git a/aiohttp/web_response.py b/aiohttp/web_response.py\nindex 47d75675d..a0ee89d67 100644\n--- a/aiohttp/web_response.py\n+++ b/aiohttp/web_response.py\n@@ -402,7 +402,8 @@ class StreamResponse(BaseClass, HeadersMixin, CookieMixin):\n # https://datatracker.ietf.org/doc/html/rfc9112#section-6.1-13\n if hdrs.TRANSFER_ENCODING in headers:\n del headers[hdrs.TRANSFER_ENCODING]\n- else:\n+ elif self.content_length != 0:\n+ # https://www.rfc-editor.org/rfc/rfc9110#section-8.3-5\n headers.setdefault(hdrs.CONTENT_TYPE, \"application/octet-stream\")\n headers.setdefault(hdrs.DATE, rfc822_formatted_time())\n headers.setdefault(hdrs.SERVER, SERVER_SOFTWARE)\n@@ -423,9 +424,7 @@ class StreamResponse(BaseClass, HeadersMixin, CookieMixin):\n assert writer is not None\n # status line\n version = request.version\n- status_line = \"HTTP/{}.{} {} {}\".format(\n- version[0], version[1], self._status, self._reason\n- )\n+ status_line = f\"HTTP/{version[0]}.{version[1]} {self._status} {self._reason}\"\n await writer.write_headers(status_line, self._headers)\n \n async def write(self, data: bytes) -> None:\n", "test_patch": "diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py\nindex 3ab798771..ce530eb61 100644\n--- a/tests/test_client_functional.py\n+++ b/tests/test_client_functional.py\n@@ -759,7 +759,6 @@ async def test_raw_headers(aiohttp_client: AiohttpClient) -> None:\n raw_headers = tuple((bytes(h), bytes(v)) for h, v in resp.raw_headers)\n assert raw_headers == (\n (b\"Content-Length\", b\"0\"),\n- (b\"Content-Type\", b\"application/octet-stream\"),\n (b\"Date\", mock.ANY),\n (b\"Server\", mock.ANY),\n )\n@@ -792,7 +791,6 @@ async def test_empty_header_values(aiohttp_client: AiohttpClient) -> None:\n assert raw_headers == (\n (b\"X-Empty\", b\"\"),\n (b\"Content-Length\", b\"0\"),\n- (b\"Content-Type\", b\"application/octet-stream\"),\n (b\"Date\", mock.ANY),\n (b\"Server\", mock.ANY),\n )\ndiff --git a/tests/test_web_functional.py b/tests/test_web_functional.py\nindex d82fee436..565efc7b4 100644\n--- a/tests/test_web_functional.py\n+++ b/tests/test_web_functional.py\n@@ -150,6 +150,21 @@ async def test_head_returns_empty_body(aiohttp_client: Any) -> None:\n assert resp.headers[\"Content-Length\"] == \"4\"\n \n \n+@pytest.mark.parametrize(\"status\", (201, 204, 404))\n+async def test_default_content_type_no_body(aiohttp_client: Any, status: int) -> None:\n+ async def handler(request):\n+ return web.Response(status=status)\n+\n+ app = web.Application()\n+ app.router.add_get(\"/\", handler)\n+ client = await aiohttp_client(app)\n+\n+ async with client.get(\"/\") as resp:\n+ assert resp.status == status\n+ assert await resp.read() == b\"\"\n+ assert \"Content-Type\" not in resp.headers\n+\n+\n async def test_response_before_complete(aiohttp_client: Any) -> None:\n async def handler(request):\n return web.Response(body=b\"OK\")\ndiff --git a/tests/test_web_response.py b/tests/test_web_response.py\nindex 74c2990cc..f90eb4b11 100644\n--- a/tests/test_web_response.py\n+++ b/tests/test_web_response.py\n@@ -1006,7 +1006,6 @@ async def test_send_headers_for_empty_body(buf: Any, writer: Any) -> None:\n Matches(\n \"HTTP/1.1 200 OK\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n- \"Content-Type: application/octet-stream\\r\\n\"\n \"Date: .+\\r\\n\"\n \"Server: .+\\r\\n\\r\\n\"\n )\n@@ -1049,7 +1048,6 @@ async def test_send_set_cookie_header(buf: Any, writer: Any) -> None:\n \"HTTP/1.1 200 OK\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"Set-Cookie: name=value\\r\\n\"\n- \"Content-Type: application/octet-stream\\r\\n\"\n \"Date: .+\\r\\n\"\n \"Server: .+\\r\\n\\r\\n\"\n )\n", "FAIL_TO_PASS": ["tests/test_client_functional.py::test_raw_headers[pyloop]", "tests/test_client_functional.py::test_empty_header_values[pyloop]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-201]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-404]", "tests/test_web_response.py::test_send_headers_for_empty_body", "tests/test_web_response.py::test_render_with_body", "tests/test_web_response.py::test_send_set_cookie_header", "tests/test_web_response.py::test_consecutive_write_eof"]}, {"instance_id": "aio-libs__aiohttp-8874", "base_commit": "48a5e07ad833bd1a8fcb2ce6f85a41ad0cef9dc6", "gold_patch": "diff --git a/CHANGES/5343.bugfix b/CHANGES/5343.bugfix\nnew file mode 100644\nindex 000000000..4e33071ea\n--- /dev/null\n+++ b/CHANGES/5343.bugfix\n@@ -0,0 +1,1 @@\n+Fixed StreamResponse.prepared to return True after EOF is sent -- by :user:`arthurdarcet`.\ndiff --git a/aiohttp/web_response.py b/aiohttp/web_response.py\nindex a0ee89d67..238c31277 100644\n--- a/aiohttp/web_response.py\n+++ b/aiohttp/web_response.py\n@@ -121,7 +121,7 @@ class StreamResponse(BaseClass, HeadersMixin, CookieMixin):\n \n @property\n def prepared(self) -> bool:\n- return self._payload_writer is not None\n+ return self._eof_sent or self._payload_writer is not None\n \n @property\n def task(self) -> \"Optional[asyncio.Task[None]]\":\ndiff --git a/requirements/constraints.txt b/requirements/constraints.txt\nindex 661595d82..11f6d4af1 100644\n--- a/requirements/constraints.txt\n+++ b/requirements/constraints.txt\n@@ -38,13 +38,13 @@ cffi==1.17.0\n # via\n # cryptography\n # pycares\n-cfgv==3.3.1\n+cfgv==3.4.0\n # via pre-commit\n charset-normalizer==3.3.2\n # via requests\n cherry-picker==2.2.0\n # via -r requirements/dev.in\n-click==8.1.6\n+click==8.1.7\n # via\n # cherry-picker\n # pip-tools\n@@ -107,8 +107,12 @@ jinja2==3.1.4\n # via\n # sphinx\n # towncrier\n+markdown-it-py==3.0.0\n+ # via rich\n markupsafe==2.1.5\n # via jinja2\n+mdurl==0.1.2\n+ # via markdown-it-py\n multidict==6.0.5\n # via\n # -r requirements/multidict.in\n@@ -155,7 +159,9 @@ pydantic-core==2.20.1\n pyenchant==3.2.2\n # via sphinxcontrib-spelling\n pygments==2.18.0\n- # via sphinx\n+ # via\n+ # rich\n+ # sphinx\n pyjwt==2.8.0\n # via\n # gidgethub\n@@ -195,8 +201,12 @@ requests==2.32.3\n # cherry-picker\n # python-on-whales\n # sphinx\n+rich==13.7.1\n+ # via typer\n setuptools-git==1.2\n # via -r requirements/test.in\n+shellingham==1.5.4\n+ # via typer\n six==1.16.0\n # via python-dateutil\n slotscheck==0.19.0\n@@ -248,9 +258,9 @@ trustme==1.1.0 ; platform_machine != \"i686\"\n # via\n # -r requirements/lint.in\n # -r requirements/test.in\n-typer==0.9.0\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # aioredis\n # annotated-types\n@@ -258,6 +268,7 @@ typing-extensions==4.10.0\n # pydantic\n # pydantic-core\n # python-on-whales\n+ # rich\n # typer\n uritemplate==4.1.1\n # via gidgethub\ndiff --git a/requirements/dev.txt b/requirements/dev.txt\nindex 898d52f9f..181f939fb 100644\n--- a/requirements/dev.txt\n+++ b/requirements/dev.txt\n@@ -38,13 +38,13 @@ cffi==1.17.0\n # via\n # cryptography\n # pycares\n-cfgv==3.3.1\n+cfgv==3.4.0\n # via pre-commit\n charset-normalizer==3.3.2\n # via requests\n cherry-picker==2.2.0\n # via -r requirements/dev.in\n-click==8.1.6\n+click==8.1.7\n # via\n # cherry-picker\n # pip-tools\n@@ -105,8 +105,12 @@ jinja2==3.1.4\n # via\n # sphinx\n # towncrier\n+markdown-it-py==3.0.0\n+ # via rich\n markupsafe==2.1.5\n # via jinja2\n+mdurl==0.1.2\n+ # via markdown-it-py\n multidict==6.0.5\n # via\n # -r requirements/runtime-deps.in\n@@ -150,7 +154,9 @@ pydantic==2.8.2\n pydantic-core==2.20.1\n # via pydantic\n pygments==2.18.0\n- # via sphinx\n+ # via\n+ # rich\n+ # sphinx\n pyjwt==2.8.0\n # via\n # gidgethub\n@@ -190,8 +196,12 @@ requests==2.32.3\n # cherry-picker\n # python-on-whales\n # sphinx\n+rich==13.7.1\n+ # via typer\n setuptools-git==1.2\n # via -r requirements/test.in\n+shellingham==1.5.4\n+ # via typer\n six==1.16.0\n # via python-dateutil\n slotscheck==0.19.0\n@@ -240,9 +250,9 @@ trustme==1.1.0 ; platform_machine != \"i686\"\n # via\n # -r requirements/lint.in\n # -r requirements/test.in\n-typer==0.9.0\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # aioredis\n # annotated-types\n@@ -250,6 +260,7 @@ typing-extensions==4.10.0\n # pydantic\n # pydantic-core\n # python-on-whales\n+ # rich\n # typer\n uritemplate==4.1.1\n # via gidgethub\ndiff --git a/requirements/doc-spelling.txt b/requirements/doc-spelling.txt\nindex 4d55d216a..5108b7743 100644\n--- a/requirements/doc-spelling.txt\n+++ b/requirements/doc-spelling.txt\n@@ -16,7 +16,7 @@ certifi==2024.7.4\n # via requests\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via towncrier\n docutils==0.20.1\n # via sphinx\ndiff --git a/requirements/doc.txt b/requirements/doc.txt\nindex fbfc99f68..1382a7bb8 100644\n--- a/requirements/doc.txt\n+++ b/requirements/doc.txt\n@@ -16,7 +16,7 @@ certifi==2024.7.4\n # via requests\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via towncrier\n docutils==0.20.1\n # via sphinx\ndiff --git a/requirements/lint.txt b/requirements/lint.txt\nindex f9633be1b..aafe0260d 100644\n--- a/requirements/lint.txt\n+++ b/requirements/lint.txt\n@@ -18,11 +18,11 @@ cffi==1.17.0\n # via\n # cryptography\n # pycares\n-cfgv==3.3.1\n+cfgv==3.4.0\n # via pre-commit\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via\n # slotscheck\n # typer\n@@ -105,9 +105,9 @@ tqdm==4.66.5\n # via python-on-whales\n trustme==1.1.0\n # via -r requirements/lint.in\n-typer==0.12.3\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # aioredis\n # annotated-types\n", "test_patch": "diff --git a/docs/testing.rst b/docs/testing.rst\nindex 966bc4cad..1d29f3354 100644\n--- a/docs/testing.rst\n+++ b/docs/testing.rst\n@@ -496,14 +496,12 @@ Framework Agnostic Utilities\n \n High level test creation::\n \n- from aiohttp.test_utils import TestClient, TestServer, loop_context\n+ from aiohttp.test_utils import TestClient, TestServer\n from aiohttp import request\n \n- # loop_context is provided as a utility. You can use any\n- # asyncio.BaseEventLoop class in its place.\n- with loop_context() as loop:\n+ async def test():\n app = _create_example_app()\n- with TestClient(TestServer(app), loop=loop) as client:\n+ async with TestClient(TestServer(app)) as client:\n \n async def test_get_route():\n nonlocal client\n@@ -512,7 +510,7 @@ High level test creation::\n text = await resp.text()\n assert \"Hello, world\" in text\n \n- loop.run_until_complete(test_get_route())\n+ await test_get_route()\n \n \n If it's preferred to handle the creation / teardown on a more granular\n@@ -520,10 +518,10 @@ basis, the TestClient object can be used directly::\n \n from aiohttp.test_utils import TestClient, TestServer\n \n- with loop_context() as loop:\n+ async def test():\n app = _create_example_app()\n- client = TestClient(TestServer(app), loop=loop)\n- loop.run_until_complete(client.start_server())\n+ client = TestClient(TestServer(app))\n+ await client.start_server()\n root = \"http://127.0.0.1:{}\".format(port)\n \n async def test_get_route():\n@@ -532,8 +530,8 @@ basis, the TestClient object can be used directly::\n text = await resp.text()\n assert \"Hello, world\" in text\n \n- loop.run_until_complete(test_get_route())\n- loop.run_until_complete(client.close())\n+ await test_get_route()\n+ await client.close()\n \n \n A full list of the utilities provided can be found at the\ndiff --git a/requirements/test.txt b/requirements/test.txt\nindex a6d8ebab7..15aebd3d1 100644\n--- a/requirements/test.txt\n+++ b/requirements/test.txt\n@@ -24,7 +24,7 @@ cffi==1.17.0\n # pycares\n charset-normalizer==3.3.2\n # via requests\n-click==8.1.6\n+click==8.1.7\n # via\n # typer\n # wait-for-it\n@@ -51,6 +51,10 @@ idna==3.4\n # yarl\n iniconfig==2.0.0\n # via pytest\n+markdown-it-py==3.0.0\n+ # via rich\n+mdurl==0.1.2\n+ # via markdown-it-py\n multidict==6.0.5\n # via\n # -r requirements/runtime-deps.in\n@@ -75,6 +79,8 @@ pydantic==2.8.2\n # via python-on-whales\n pydantic-core==2.20.1\n # via pydantic\n+pygments==2.18.0\n+ # via rich\n pytest==8.1.1\n # via\n # -r requirements/test.in\n@@ -94,8 +100,12 @@ regex==2024.7.24\n # via re-assert\n requests==2.32.3\n # via python-on-whales\n+rich==13.7.1\n+ # via typer\n setuptools-git==1.2\n # via -r requirements/test.in\n+shellingham==1.5.4\n+ # via typer\n six==1.16.0\n # via python-dateutil\n tomli==2.0.1\n@@ -107,15 +117,16 @@ tqdm==4.66.5\n # via python-on-whales\n trustme==1.1.0 ; platform_machine != \"i686\"\n # via -r requirements/test.in\n-typer==0.9.0\n+typer==0.12.5\n # via python-on-whales\n-typing-extensions==4.10.0\n+typing-extensions==4.12.2\n # via\n # annotated-types\n # mypy\n # pydantic\n # pydantic-core\n # python-on-whales\n+ # rich\n # typer\n urllib3==2.2.2\n # via requests\ndiff --git a/tests/test_web_response.py b/tests/test_web_response.py\nindex f90eb4b11..d1226f277 100644\n--- a/tests/test_web_response.py\n+++ b/tests/test_web_response.py\n@@ -734,11 +734,8 @@ async def test___repr___after_eof() -> None:\n resp = StreamResponse()\n await resp.prepare(make_request(\"GET\", \"/\"))\n \n- assert resp.prepared\n-\n await resp.write(b\"data\")\n await resp.write_eof()\n- assert not resp.prepared\n resp_repr = repr(resp)\n assert resp_repr == \"\"\n \n@@ -1110,14 +1107,22 @@ def test_content_type_with_set_body() -> None:\n assert resp.content_type == \"application/octet-stream\"\n \n \n-def test_started_when_not_started() -> None:\n+def test_prepared_when_not_started() -> None:\n resp = StreamResponse()\n assert not resp.prepared\n \n \n-async def test_started_when_started() -> None:\n+async def test_prepared_when_started() -> None:\n+ resp = StreamResponse()\n+ await resp.prepare(make_request(\"GET\", \"/\"))\n+ assert resp.prepared\n+\n+\n+async def test_prepared_after_eof() -> None:\n resp = StreamResponse()\n await resp.prepare(make_request(\"GET\", \"/\"))\n+ await resp.write(b\"data\")\n+ await resp.write_eof()\n assert resp.prepared\n \n \n", "FAIL_TO_PASS": ["tests/test_web_response.py::test_prepared_after_eof", "tests/test_web_response.py::test_drain_before_start"]}], "all_FAIL_TO_PASS": ["tests/test_client_functional.py::test_raw_headers[pyloop]", "tests/test_client_functional.py::test_empty_header_values[pyloop]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-201]", "tests/test_web_functional.py::test_default_content_type_no_body[pyloop-404]", "tests/test_web_response.py::test_send_headers_for_empty_body", "tests/test_web_response.py::test_render_with_body", "tests/test_web_response.py::test_send_set_cookie_header", "tests/test_web_response.py::test_consecutive_write_eof", "tests/test_web_response.py::test_prepared_after_eof", "tests/test_web_response.py::test_drain_before_start"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "sdv-dev__rdt-754_x2", "level": 2, "source": "swerebenchv2", "repo": "sdv-dev/RDT", "image": "swerebenchv2/sdv-dev-rdt:754-de011e2", "base_commit": "de011e2efe5478b8c9020275893a601063364a33", "num_bugs": 2, "bugs": [{"instance_id": "sdv-dev__rdt-754", "base_commit": "de011e2efe5478b8c9020275893a601063364a33", "gold_patch": "diff --git a/rdt/transformers/text.py b/rdt/transformers/text.py\nindex 7cae7a2..ca1887a 100644\n--- a/rdt/transformers/text.py\n+++ b/rdt/transformers/text.py\n@@ -1,5 +1,5 @@\n \"\"\"Transformers for text data.\"\"\"\n-import warnings\n+import logging\n \n import numpy as np\n import pandas as pd\n@@ -8,6 +8,8 @@ from rdt.errors import TransformerProcessingError\n from rdt.transformers.base import BaseTransformer\n from rdt.transformers.utils import strings_from_regex\n \n+LOGGER = logging.getLogger(__name__)\n+\n \n class IDGenerator(BaseTransformer):\n \"\"\"Generate an ID column.\n@@ -161,10 +163,10 @@ class RegexGenerator(BaseTransformer):\n f\"Please use a different regex for column ('{self.get_input_column()}').\"\n )\n \n- warnings.warn(\n- f\"The data has {sample_size} rows but the regex for '{self.get_input_column()}' \"\n- f'can only create {self.generator_size} unique values. Some values in '\n- f\"'{self.get_input_column()}' may be repeated.\"\n+ LOGGER.info(\n+ \"The data has %s rows but the regex for '%s' can only create %s unique values.\"\n+ \" Some values in '%s' may be repeated.\",\n+ sample_size, self.get_input_column(), self.generator_size, self.get_input_column()\n )\n \n remaining = self.generator_size - self.generated\ndiff --git a/rdt/transformers/utils.py b/rdt/transformers/utils.py\nindex fe26476..240b829 100644\n--- a/rdt/transformers/utils.py\n+++ b/rdt/transformers/utils.py\n@@ -149,7 +149,7 @@ def strings_from_regex(regex, max_repeat=16):\n generators.append((generator, option, args))\n sizes.append(size)\n \n- return _from_generators(generators, max_repeat), np.prod(sizes, dtype=np.complex128)\n+ return _from_generators(generators, max_repeat), np.prod(sizes, dtype=np.complex128).real\n \n \n def fill_nan_with_none(data):\n", "test_patch": "diff --git a/tests/unit/transformers/test_text.py b/tests/unit/transformers/test_text.py\nindex 511c351..ff208b2 100644\n--- a/tests/unit/transformers/test_text.py\n+++ b/tests/unit/transformers/test_text.py\n@@ -485,3 +485,31 @@ class TestRegexGenerator:\n )\n with pytest.raises(TransformerProcessingError, match=error_msg):\n instance._reverse_transform(columns_data)\n+\n+ @patch('rdt.transformers.text.LOGGER')\n+ def test__reverse_transform_info_message(self, mock_logger):\n+ \"\"\"Test the ``_reverse_transform`` method.\n+\n+ Validate that the ``_reverse_transform`` method logs an info message when\n+ ``enforce_uniqueness`` is ``False`` and the ``instance.data_length`` is bigger than\n+ ``instance.generator_size``.\n+ \"\"\"\n+ # Setup\n+ instance = RegexGenerator('[A-Z]', enforce_uniqueness=False)\n+ instance.data_length = 6\n+ instance.generator_size = 5\n+ instance.generated = 0\n+ instance.columns = ['a']\n+ columns_data = pd.Series()\n+\n+ # Run\n+ instance._reverse_transform(columns_data)\n+\n+ # Assert\n+ expected_format = (\n+ \"The data has %s rows but the regex for '%s' can only create %s unique values. Some \"\n+ \"values in '%s' may be repeated.\"\n+ )\n+ expected_args = (6, 'a', 5, 'a')\n+\n+ mock_logger.info.assert_called_once_with(expected_format, *expected_args)\n", "FAIL_TO_PASS": ["tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message"]}, {"instance_id": "sdv-dev__rdt-755", "base_commit": "9f37fb4db6d16e5d72e42cc7fa1ba100f3878e0a", "gold_patch": "diff --git a/rdt/transformers/categorical.py b/rdt/transformers/categorical.py\nindex fef1242..13d4e03 100644\n--- a/rdt/transformers/categorical.py\n+++ b/rdt/transformers/categorical.py\n@@ -9,7 +9,7 @@ from scipy.stats import norm\n \n from rdt.errors import TransformerInputError\n from rdt.transformers.base import BaseTransformer\n-from rdt.transformers.utils import fill_nan_with_none\n+from rdt.transformers.utils import check_nan_in_transform, fill_nan_with_none, try_convert_to_dtype\n \n LOGGER = logging.getLogger(__name__)\n \n@@ -177,6 +177,7 @@ class UniformEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n data = data.clip(0, 1)\n bins = [0]\n labels = []\n@@ -192,7 +193,10 @@ class UniformEncoder(BaseTransformer):\n labels.append(key)\n \n result = pd.cut(data, bins=bins, labels=labels, include_lowest=True)\n- return result.replace(nan_name, np.nan).astype(self.dtype)\n+ result = result.replace(nan_name, np.nan)\n+ result = try_convert_to_dtype(result, self.dtype)\n+\n+ return result\n \n \n class OrderedUniformEncoder(UniformEncoder):\n@@ -333,6 +337,7 @@ class FrequencyEncoder(BaseTransformer):\n )\n super().__init__()\n self.add_noise = add_noise\n+ self._is_integer = None\n \n @staticmethod\n def _get_intervals(data):\n@@ -516,6 +521,7 @@ class FrequencyEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n data = data.clip(0, 1)\n num_rows = len(data)\n num_categories = len(self.means)\n@@ -545,6 +551,7 @@ class OneHotEncoder(BaseTransformer):\n _dummy_encoded = False\n _indexer = None\n _uniques = None\n+ dtype = None\n \n @staticmethod\n def _prepare_data(data):\n@@ -582,6 +589,7 @@ class OneHotEncoder(BaseTransformer):\n data (pandas.Series or pandas.DataFrame):\n Data to fit the transformer to.\n \"\"\"\n+ self.dtype = data.dtype\n data = self._prepare_data(data)\n \n null = pd.isna(data).to_numpy()\n@@ -657,6 +665,7 @@ class OneHotEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n if not isinstance(data, np.ndarray):\n data = data.to_numpy()\n \n@@ -664,8 +673,10 @@ class OneHotEncoder(BaseTransformer):\n data = data.reshape(-1, 1)\n \n indices = np.argmax(data, axis=1)\n+ result = pd.Series(indices).map(self.dummies.__getitem__)\n+ result = try_convert_to_dtype(result, self.dtype)\n \n- return pd.Series(indices).map(self.dummies.__getitem__)\n+ return result\n \n \n class LabelEncoder(BaseTransformer):\n@@ -801,13 +812,15 @@ class LabelEncoder(BaseTransformer):\n Returns:\n pandas.Series\n \"\"\"\n+ check_nan_in_transform(data, self.dtype)\n if self.add_noise:\n data = np.floor(data)\n \n data = data.clip(min(self.values_to_categories), max(self.values_to_categories))\n data = data.round().map(self.values_to_categories)\n+ data = try_convert_to_dtype(data, self.dtype)\n \n- return data.astype(self.dtype)\n+ return data\n \n \n class OrderedLabelEncoder(LabelEncoder):\n@@ -865,6 +878,7 @@ class OrderedLabelEncoder(LabelEncoder):\n data (pandas.Series):\n Data to fit the transformer to.\n \"\"\"\n+ self.dtype = data.dtype\n data = data.fillna(np.nan)\n missing = list(data[~data.isin(self.order)].unique())\n if len(missing) > 0:\ndiff --git a/rdt/transformers/text.py b/rdt/transformers/text.py\nindex ca1887a..bb7fd9e 100644\n--- a/rdt/transformers/text.py\n+++ b/rdt/transformers/text.py\n@@ -1,10 +1,10 @@\n \"\"\"Transformers for text data.\"\"\"\n import logging\n+import warnings\n \n import numpy as np\n import pandas as pd\n \n-from rdt.errors import TransformerProcessingError\n from rdt.transformers.base import BaseTransformer\n from rdt.transformers.utils import strings_from_regex\n \n@@ -141,6 +141,37 @@ class RegexGenerator(BaseTransformer):\n \"\"\"Drop the input column by returning ``None``.\"\"\"\n return None\n \n+ def _warn_not_enough_unique_values(self, sample_size):\n+ \"\"\"Warn the user that the regex cannot generate enough unique values.\n+\n+ Args:\n+ sample_size (int):\n+ Number of samples to be generated.\n+ \"\"\"\n+ warned = False\n+ if sample_size > self.generator_size:\n+ if self.enforce_uniqueness:\n+ warnings.warn(\n+ f\"The regex for '{self.get_input_column()}' can only generate \"\n+ f'{self.generator_size} unique values. Additional values may not exactly '\n+ 'follow the provided regex.'\n+ )\n+ warned = True\n+ else:\n+ LOGGER.info(\n+ \"The data has %s rows but the regex for '%s' can only create %s unique values.\"\n+ \" Some values in '%s' may be repeated.\",\n+ sample_size, self.get_input_column(), self.generator_size,\n+ self.get_input_column()\n+ )\n+\n+ remaining = self.generator_size - self.generated\n+ if sample_size > remaining and self.enforce_uniqueness and not warned:\n+ warnings.warn(\n+ f'The regex generator is not able to generate {sample_size} new unique '\n+ f'values (only {max(remaining, 0)} unique values left).'\n+ )\n+\n def _reverse_transform(self, data):\n \"\"\"Generate new data using the provided ``regex_format``.\n \n@@ -156,47 +187,39 @@ class RegexGenerator(BaseTransformer):\n else:\n sample_size = self.data_length\n \n- if sample_size > self.generator_size:\n- if self.enforce_uniqueness:\n- raise TransformerProcessingError(\n- f'The regex is not able to generate {sample_size} unique values. '\n- f\"Please use a different regex for column ('{self.get_input_column()}').\"\n- )\n-\n- LOGGER.info(\n- \"The data has %s rows but the regex for '%s' can only create %s unique values.\"\n- \" Some values in '%s' may be repeated.\",\n- sample_size, self.get_input_column(), self.generator_size, self.get_input_column()\n- )\n+ self._warn_not_enough_unique_values(sample_size)\n \n remaining = self.generator_size - self.generated\n- if sample_size > self.generator_size - self.generated:\n- if self.enforce_uniqueness:\n- raise TransformerProcessingError(\n- f'The regex generator is not able to generate {sample_size} new unique '\n- f'values (only {remaining} unique value left). Please use '\n- \"'reset_randomization' in order to restart the generator.\"\n- )\n-\n+ if sample_size > remaining:\n self.reset_randomization()\n remaining = self.generator_size\n \n if remaining >= sample_size:\n- reverse_transformed = np.array([\n- next(self.generator)\n- for _ in range(sample_size)\n- ], dtype=object)\n-\n+ reverse_transformed = [next(self.generator) for _ in range(sample_size)]\n self.generated += sample_size\n \n else:\n- self.generated = self.generator_size\n generated_values = list(self.generator)\n- reverse_transformed = []\n- while len(reverse_transformed) < sample_size:\n- remaining_samples = sample_size - len(reverse_transformed)\n- reverse_transformed.extend(generated_values[:remaining_samples])\n-\n- reverse_transformed = np.array(reverse_transformed, dtype=object)\n-\n- return reverse_transformed\n+ reverse_transformed = generated_values[:]\n+ self.generated = self.generator_size\n+ if self.enforce_uniqueness:\n+ try:\n+ remaining_samples = sample_size - len(reverse_transformed)\n+ start = int(generated_values[-1]) + 1\n+ reverse_transformed.extend(\n+ [str(i) for i in range(start, start + remaining_samples)])\n+\n+ except ValueError:\n+ counter = 0\n+ while len(reverse_transformed) < sample_size:\n+ remaining_samples = sample_size - len(reverse_transformed)\n+ reverse_transformed.extend(\n+ [f'{i}({counter})' for i in generated_values[:remaining_samples]])\n+ counter += 1\n+\n+ else:\n+ while len(reverse_transformed) < sample_size:\n+ remaining_samples = sample_size - len(reverse_transformed)\n+ reverse_transformed.extend(generated_values[:remaining_samples])\n+\n+ return np.array(reverse_transformed, dtype=object)\ndiff --git a/rdt/transformers/utils.py b/rdt/transformers/utils.py\nindex 240b829..4e78685 100644\n--- a/rdt/transformers/utils.py\n+++ b/rdt/transformers/utils.py\n@@ -2,8 +2,10 @@\n \n import re\n import string\n+import warnings\n \n import numpy as np\n+import pandas as pd\n \n import sre_parse # isort:skip\n \n@@ -184,3 +186,51 @@ def flatten_column_list(column_list):\n flattened.append(column)\n \n return flattened\n+\n+\n+def check_nan_in_transform(data, dtype):\n+ \"\"\"Check if there are null values in the transformed data.\n+\n+ Args:\n+ data (pd.Series or numpy.ndarray):\n+ Data that has been transformed.\n+ dtype (str):\n+ Data type of the transformed data.\n+ \"\"\"\n+ if pd.isna(data).any().any():\n+ message = (\n+ 'There are null values in the transformed data. The reversed '\n+ 'transformed data will contain null values'\n+ )\n+ is_integer = pd.api.types.is_integer_dtype(dtype)\n+ if is_integer:\n+ message += \" of type 'float'.\"\n+ else:\n+ message += '.'\n+\n+ warnings.warn(message)\n+\n+\n+def try_convert_to_dtype(data, dtype):\n+ \"\"\"Try to convert data to a given dtype.\n+\n+ Args:\n+ data (pd.Series or numpy.ndarray):\n+ Data to convert.\n+ dtype (str):\n+ Data type to convert to.\n+\n+ Returns:\n+ data:\n+ Data converted to the given dtype.\n+ \"\"\"\n+ try:\n+ data = data.astype(dtype)\n+ except ValueError as error:\n+ is_integer = pd.api.types.is_integer_dtype(dtype)\n+ if is_integer:\n+ data = data.astype(float)\n+ else:\n+ raise error\n+\n+ return data\n", "test_patch": "diff --git a/tests/integration/transformers/test_base.py b/tests/integration/transformers/test_base.py\nindex cff4869..02a4ef7 100644\n--- a/tests/integration/transformers/test_base.py\n+++ b/tests/integration/transformers/test_base.py\n@@ -136,6 +136,7 @@ def test_multi_column_transformer_same_number_of_columns_input_output():\n # Setup\n class AdditionTransformer(BaseMultiColumnTransformer):\n \"\"\"This transformer takes 3 columns and return the cumulative sum of each row.\"\"\"\n+\n def _fit(self, columns_data):\n self.output_properties = {\n f'{self.columns[0]}': {'sdtype': 'numerical'},\n@@ -188,6 +189,7 @@ def test_multi_column_transformer_less_output_than_input_columns():\n \"\"\"This transformer takes 4 columns and concatenate them into 2 columns.\n The two first and last columns are concatenated together.\n \"\"\"\n+\n def _fit(self, columns_data):\n self.name_1 = self.columns[0] + '#' + self.columns[1]\n self.name_2 = self.columns[2] + '#' + self.columns[3]\ndiff --git a/tests/integration/transformers/test_text.py b/tests/integration/transformers/test_text.py\nindex ff143d8..2111186 100644\n--- a/tests/integration/transformers/test_text.py\n+++ b/tests/integration/transformers/test_text.py\n@@ -303,3 +303,37 @@ def test_regexgenerator_with_many_possibilities():\n \n pd.testing.assert_frame_equal(transformed, expected_transformed)\n pd.testing.assert_frame_equal(reverse_transform, expected_reverse_transformed)\n+\n+\n+def test_regexgenerator_enforce_uniqueness_not_enough_values_categorical():\n+ \"\"\"Test the ``RegexGenerator`` with enforce_uniqueness=True but insufficient regex values.\"\"\"\n+ # Setup\n+ data = pd.DataFrame({\n+ 'id': [1, 2, 3, 4, 5],\n+ })\n+ instance = RegexGenerator('id_[a-b]{1}', enforce_uniqueness=True)\n+\n+ # Run\n+ transformed = instance.fit_transform(data, 'id')\n+ reverse_transform = instance.reverse_transform(transformed)\n+\n+ # Assert\n+ expected = pd.DataFrame({'id': ['id_a', 'id_b', 'id_a(0)', 'id_b(0)', 'id_a(1)']})\n+ pd.testing.assert_frame_equal(reverse_transform, expected)\n+\n+\n+def test_regexgenerator_enforce_uniqueness_not_enough_values_numerical():\n+ \"\"\"Test the ``RegexGenerator`` with enforce_uniqueness=True but insufficient regex values.\"\"\"\n+ # Setup\n+ data = pd.DataFrame({\n+ 'id': [1, 2, 3, 4, 5],\n+ })\n+ instance = RegexGenerator('[2-3]{1}', enforce_uniqueness=True)\n+\n+ # Run\n+ transformed = instance.fit_transform(data, 'id')\n+ reverse_transform = instance.reverse_transform(transformed)\n+\n+ # Assert\n+ expected = pd.DataFrame({'id': ['2', '3', '4', '5', '6']}, dtype=object)\n+ pd.testing.assert_frame_equal(reverse_transform, expected)\ndiff --git a/tests/unit/transformers/test_categorical.py b/tests/unit/transformers/test_categorical.py\nindex afd9d16..dbad53a 100644\n--- a/tests/unit/transformers/test_categorical.py\n+++ b/tests/unit/transformers/test_categorical.py\n@@ -271,7 +271,9 @@ class TestUniformEncoder:\n assert transformed.iloc[4] >= 0\n assert transformed.iloc[4] < 1\n \n- def test__reverse_transform(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ @patch('rdt.transformers.categorical.try_convert_to_dtype')\n+ def test__reverse_transform(self, mock_convert_dtype, mock_check_nan):\n \"\"\"Test the ``_reverse_transform``.\"\"\"\n # Setup\n data = pd.Series([1, 2, 3, 2, 2, 1, 3, 3, 2])\n@@ -289,12 +291,18 @@ class TestUniformEncoder:\n }\n \n transformed = pd.Series([0.12, 0.254, 0.789, 0.43, 0.56, 0.08, 0.67, 0.98, 0.36])\n+ mock_convert_dtype.return_value = pd.Series([1, 2, 3, 2, 2, 1, 3, 3, 2])\n \n # Run\n output = transformer._reverse_transform(transformed)\n \n # Asserts\n pd.testing.assert_series_equal(output, data)\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, transformed)\n+ assert mock_input_dtype == transformer.dtype\n+ mock_convert_dtype.assert_called_once()\n \n def test__reverse_transform_nans(self):\n \"\"\"Test ``_reverse_transform`` for data with NaNs.\"\"\"\n@@ -323,6 +331,25 @@ class TestUniformEncoder:\n # Asserts\n pd.testing.assert_series_equal(output, data)\n \n+ def test__reverse_transform_integer_and_nans(self):\n+ \"\"\"Test the ``reverse_transform`` method with integers and nans.\n+\n+ Test that the method correctly reverse transforms the data\n+ when the initial data is integers and the transformed data has nans.\n+ \"\"\"\n+ # Setup\n+ transformer = UniformEncoder()\n+ transformer.frequencies = {11: 0.2, 12: 0.3, 13: 0.5}\n+ transformer.intervals = {11: [0, 0.2], 12: [0.2, 0.5], 13: [0.5, 1]}\n+ transformer.dtype = np.int64\n+ data = pd.Series([0.1, 0.25, np.nan, 0.65])\n+\n+ # Run\n+ out = transformer._reverse_transform(data)\n+\n+ # Assert\n+ pd.testing.assert_series_equal(out, pd.Series([11, 12, np.nan, 13]))\n+\n \n @pytest.fixture(autouse=True)\n def _setup_caplog(caplog):\n@@ -718,7 +745,8 @@ class TestFrequencyEncoder:\n # Asserts\n assert result == 0.2745\n \n- def test__reverse_transform_series(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ def test__reverse_transform_series(self, mock_check_nan):\n \"\"\"Test reverse_transform a pandas Series\"\"\"\n # Setup\n data = pd.Series(['foo', 'bar', 'bar', 'foo', 'foo', 'tar'])\n@@ -730,6 +758,10 @@ class TestFrequencyEncoder:\n result = transformer._reverse_transform(rt_data)\n \n # Asserts\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, rt_data)\n+ assert mock_input_dtype == transformer.dtype\n expected_intervals = {\n 'foo': (\n 0,\n@@ -1123,7 +1155,8 @@ class TestFrequencyEncoder:\n np.testing.assert_array_equal(reverse_arg, data.clip(0, 1))\n assert reverse == categorical_transformer_mock._reverse_transform_by_row.return_value\n \n- def test__reverse_transform_by_row(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ def test__reverse_transform_by_row(self, mock_check_nan):\n \"\"\"Test the _reverse_transform_by_row method with numerical data.\n \n Expect that the transformed data is correctly reverse transformed.\n@@ -1156,6 +1189,10 @@ class TestFrequencyEncoder:\n reverse = transformer._reverse_transform(transformed)\n \n # Assert\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, transformed)\n+ assert mock_input_dtype == data.dtype\n pd.testing.assert_series_equal(data, reverse)\n \n \n@@ -1222,6 +1259,7 @@ class TestOneHotEncoder:\n \n # Assert\n np.testing.assert_array_equal(ohe.dummies, ['a', 2, 'c'])\n+ assert ohe.dtype == 'object'\n \n def test__fit_dummies_nans(self):\n \"\"\"Test the ``_fit`` method without nans.\n@@ -1776,11 +1814,14 @@ class TestOneHotEncoder:\n assert not ohe._dummy_encoded\n np.testing.assert_array_equal(out, expected)\n \n- def test__reverse_transform_no_nans(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ @patch('rdt.transformers.categorical.try_convert_to_dtype')\n+ def test__reverse_transform_no_nans(self, mock_convert_dtype, mock_check_nan):\n # Setup\n ohe = OneHotEncoder()\n data = pd.Series(['a', 'b', 'c'])\n ohe._fit(data)\n+ mock_convert_dtype.return_value = data\n \n # Run\n transformed = np.array([\n@@ -1793,6 +1834,11 @@ class TestOneHotEncoder:\n # Assert\n expected = pd.Series(['a', 'b', 'c'])\n pd.testing.assert_series_equal(out, expected)\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ np.testing.assert_array_equal(mock_input_data, transformed)\n+ assert mock_input_dtype == 'O'\n+ mock_convert_dtype.assert_called_once()\n \n def test__reverse_transform_nans(self):\n # Setup\n@@ -2168,7 +2214,9 @@ class TestLabelEncoder:\n # Assert\n pd.testing.assert_series_equal(out, pd.Series(['a', 'b', 'c']))\n \n- def test__reverse_transform_add_noise(self):\n+ @patch('rdt.transformers.categorical.check_nan_in_transform')\n+ @patch('rdt.transformers.categorical.try_convert_to_dtype')\n+ def test__reverse_transform_add_noise(self, mock_convert_dtype, mock_check_nan):\n \"\"\"Test the ``_reverse_transform`` method with ``add_noise``.\n \n Test that the method correctly reverse transforms the data\n@@ -2183,12 +2231,36 @@ class TestLabelEncoder:\n transformer = LabelEncoder(add_noise=True)\n transformer.values_to_categories = {0: 'a', 1: 'b', 2: 'c'}\n data = pd.Series([0.5, 1.0, 10.9])\n+ mock_convert_dtype.return_value = pd.Series(['a', 'b', 'c'])\n \n # Run\n out = transformer._reverse_transform(data)\n \n # Assert\n pd.testing.assert_series_equal(out, pd.Series(['a', 'b', 'c']))\n+ mock_input_data = mock_check_nan.call_args.args[0]\n+ mock_input_dtype = mock_check_nan.call_args.args[1]\n+ pd.testing.assert_series_equal(mock_input_data, data)\n+ assert mock_input_dtype == 'O'\n+ mock_convert_dtype.assert_called_once()\n+\n+ def test__reverse_transform_integer_and_nans(self):\n+ \"\"\"Test the ``reverse_transform`` method with integers and nans.\n+\n+ Test that the method correctly reverse transforms the data\n+ when the initial data is integers and the transformed data has nans.\n+ \"\"\"\n+ # Setup\n+ transformer = LabelEncoder()\n+ transformer.values_to_categories = {0: 11, 1: 12, 2: 13}\n+ transformer.dtype = 'int'\n+ data = pd.Series([0, 1, np.nan])\n+\n+ # Run\n+ out = transformer._reverse_transform(data)\n+\n+ # Assert\n+ pd.testing.assert_series_equal(out, pd.Series([11, 12, np.nan]))\n \n \n class TestOrderedLabelEncoder:\n@@ -2272,6 +2344,7 @@ class TestOrderedLabelEncoder:\n transformer._fit(data)\n \n # Assert\n+ assert transformer.dtype == 'float'\n expected_values_to_categories = {0: 2, 1: 3, 2: np.nan, 3: 1}\n expected_categories_to_values = {2: 0, 3: 1, 1: 3, np.nan: 2}\n for key, value in transformer.values_to_categories.items():\ndiff --git a/tests/unit/transformers/test_text.py b/tests/unit/transformers/test_text.py\nindex ff208b2..9d1bf3b 100644\n--- a/tests/unit/transformers/test_text.py\n+++ b/tests/unit/transformers/test_text.py\n@@ -1,14 +1,11 @@\n \"\"\"Test Text Transformers.\"\"\"\n \n-import re\n from string import ascii_uppercase\n from unittest.mock import Mock, patch\n \n import numpy as np\n import pandas as pd\n-import pytest\n \n-from rdt.errors import TransformerProcessingError\n from rdt.transformers.text import IDGenerator, RegexGenerator\n \n \n@@ -428,23 +425,33 @@ class TestRegexGenerator:\n np.testing.assert_array_equal(result, expected_result)\n assert instance.generated == 4\n \n- def test__reverse_transform_not_enough_unique_values(self):\n- \"\"\"Test the ``_reverse_transform`` method.\n+ @patch('rdt.transformers.text.warnings')\n+ def test__reverse_transform_not_enough_unique_values_enforce_uniqueness(self, mock_warnings):\n+ \"\"\"Test it when there are not enough unique values to generate.\"\"\"\n+ # Setup\n+ instance = RegexGenerator('[A-E]', enforce_uniqueness=True)\n+ instance.data_length = 6\n+ generator = AsciiGenerator(5)\n+ instance.generator = generator\n+ instance.generator_size = 5\n+ instance.generated = 0\n+ instance.columns = ['a']\n+ columns_data = pd.Series()\n \n- Validate that the ``_reverse_transform`` method calls the ``strings_from_regex``\n- function using the ``instance.regex_format`` and then generates the\n- ``instance.data_length`` number of data.\n+ # Run\n+ out = instance._reverse_transform(columns_data)\n \n- Setup:\n- - Initialize a ``RegexGenerator`` instance with ``enforce_uniqueness`` to ``True``.\n- - Set ``data_length`` to 6.\n- - Initialize a generator.\n+ # Assert\n+ mock_warnings.warn.assert_called_once_with(\n+ \"The regex for 'a' can only generate 5 \"\n+ 'unique values. Additional values may not exactly follow the provided regex.'\n+ )\n+ np.testing.assert_array_equal(out, np.array(['A', 'B', 'C', 'D', 'E', 'A(0)']))\n \n- Side Effects:\n- - An error is being raised as not enough unique values can be generated.\n- \"\"\"\n+ def test__reverse_transform_not_enough_unique_values(self):\n+ \"\"\"Test it when there are not enough unique values to generate.\"\"\"\n # Setup\n- instance = RegexGenerator('[A-Z]', enforce_uniqueness=True)\n+ instance = RegexGenerator('[A-E]', enforce_uniqueness=False)\n instance.data_length = 6\n generator = AsciiGenerator(5)\n instance.generator = generator\n@@ -453,21 +460,38 @@ class TestRegexGenerator:\n instance.columns = ['a']\n columns_data = pd.Series()\n \n+ # Run\n+ out = instance._reverse_transform(columns_data)\n+\n # Assert\n- error_msg = re.escape(\n- 'The regex is not able to generate 6 unique values. Please use a different regex '\n- \"for column ('a').\"\n- )\n- with pytest.raises(TransformerProcessingError, match=error_msg):\n- instance._reverse_transform(columns_data)\n+ np.testing.assert_array_equal(out, np.array(['A', 'B', 'C', 'D', 'E', 'A']))\n+\n+ @patch('rdt.transformers.text.warnings')\n+ def test__reverse_transform_not_enough_unique_values_numerical(self, mock_warnings):\n+ \"\"\"Test it when there are not enough unique values to generate.\"\"\"\n+ # Setup\n+ instance = RegexGenerator('[1-3]', enforce_uniqueness=True)\n+ instance.data_length = 6\n+ generator = AsciiGenerator(5)\n+ instance.generator = generator\n+ instance.generator_size = 3\n+ instance.generated = 0\n+ instance.columns = ['a']\n+ columns_data = pd.Series()\n \n- def test__reverse_transform_enforce_uniqueness_not_enough_remaining(self):\n- \"\"\"Test the case when ``_reverse_transform`` can't generate enough new values.\n+ # Run\n+ out = instance._reverse_transform(columns_data)\n \n- Validate that an error is being raised stating that not enough new values can be\n- generated and that the user can use ``reset_randomization`` in order to restart the\n- generator.\n- \"\"\"\n+ # Assert\n+ mock_warnings.warn.assert_called_once_with(\n+ \"The regex for 'a' can only generate 3 \"\n+ 'unique values. Additional values may not exactly follow the provided regex.'\n+ )\n+ np.testing.assert_array_equal(out, np.array(['1', '2', '3', '4', '5', '6']))\n+\n+ @patch('rdt.transformers.text.warnings')\n+ def test__reverse_transform_enforce_uniqueness_not_enough_remaining(self, mock_warnings):\n+ \"\"\"Test the case when there are not enough unique values remaining.\"\"\"\n # Setup\n instance = RegexGenerator('[A-Z]', enforce_uniqueness=True)\n instance.data_length = 6\n@@ -478,13 +502,15 @@ class TestRegexGenerator:\n instance.columns = ['a']\n columns_data = pd.Series()\n \n+ # Run\n+ out = instance._reverse_transform(columns_data)\n+\n # Assert\n- error_msg = re.escape(\n- 'The regex generator is not able to generate 6 new unique values (only 1 unique '\n- \"value left). Please use 'reset_randomization' in order to restart the generator.\"\n+ mock_warnings.warn.assert_called_once_with(\n+ 'The regex generator is not able to generate 6 new unique '\n+ 'values (only 1 unique values left).'\n )\n- with pytest.raises(TransformerProcessingError, match=error_msg):\n- instance._reverse_transform(columns_data)\n+ np.testing.assert_array_equal(out, np.array(['A', 'B', 'C', 'D', 'E', 'F']))\n \n @patch('rdt.transformers.text.LOGGER')\n def test__reverse_transform_info_message(self, mock_logger):\ndiff --git a/tests/unit/transformers/test_utils.py b/tests/unit/transformers/test_utils.py\nindex 475a32d..d902023 100644\n--- a/tests/unit/transformers/test_utils.py\n+++ b/tests/unit/transformers/test_utils.py\n@@ -1,7 +1,13 @@\n import sre_parse\n from sre_constants import MAXREPEAT\n \n-from rdt.transformers.utils import _any, _max_repeat, flatten_column_list, strings_from_regex\n+import numpy as np\n+import pandas as pd\n+import pytest\n+\n+from rdt.transformers.utils import (\n+ _any, _max_repeat, check_nan_in_transform, flatten_column_list, strings_from_regex,\n+ try_convert_to_dtype)\n \n \n def test_strings_from_regex_literal():\n@@ -66,3 +72,58 @@ def test_flatten_column_list():\n # Assert\n expected_flattened_list = ['column1', 'column2', 'column3', 'column4', 'column5', 'column6']\n assert flattened_list == expected_flattened_list\n+\n+\n+def test_check_nan_in_transform():\n+ \"\"\"Test ``check_nan_in_transform`` method.\n+\n+ If there nan in the data, a warning should be raised.\n+ If the data was integer, it should be converted to float.\n+ \"\"\"\n+ # Setup\n+ transformed = pd.Series([0.1026, 0.1651, np.nan, 0.3116, 0.6546, 0.8541, 0.7041])\n+ data_without_nans = pd.DataFrame({\n+ 'col 1': [1, 2, 3],\n+ 'col 2': [4, 5, 6],\n+ })\n+\n+ # Run and Assert\n+ check_nan_in_transform(data_without_nans, 'float')\n+ expected_message = (\n+ 'There are null values in the transformed data. The reversed '\n+ 'transformed data will contain null values'\n+ )\n+ expected_message_object = expected_message + '.'\n+ expected_message_integer = expected_message + \" of type 'float'.\"\n+ with pytest.warns(UserWarning, match=expected_message_object):\n+ check_nan_in_transform(transformed, 'object')\n+\n+ with pytest.warns(UserWarning, match=expected_message_integer):\n+ check_nan_in_transform(transformed, 'int')\n+\n+\n+def test_try_convert_to_dtype():\n+ \"\"\"Test ``try_convert_to_dtype`` method.\n+\n+ If the data can be converted to the specified dtype, it should be converted.\n+ If the data cannot be converted, a ValueError should be raised.\n+ Should allow to convert integer with NaNs to float.\n+ \"\"\"\n+ # Setup\n+ data_int_with_nan = pd.Series([1.0, 2.0, np.nan, 4.0, 5.0])\n+ data_not_convertible = pd.Series(['a', 'b', 'c', 'd', 'e'])\n+\n+ # Run\n+ output_convertibe = try_convert_to_dtype(data_int_with_nan, 'str')\n+ output_int_with_nan = try_convert_to_dtype(data_int_with_nan, 'int')\n+ with pytest.raises(ValueError, match=\"could not convert string to float: 'a'\"):\n+ try_convert_to_dtype(data_not_convertible, 'int')\n+\n+ with pytest.raises(ValueError, match=\"could not convert string to float: 'a'\"):\n+ try_convert_to_dtype(data_not_convertible, 'float')\n+\n+ # Assert\n+ expected_data_with_nan = pd.Series([1, 2, np.nan, 4, 5])\n+ expected_data_convertibe = pd.Series(['1.0', '2.0', 'nan', '4.0', '5.0'])\n+ pd.testing.assert_series_equal(output_int_with_nan, expected_data_with_nan)\n+ pd.testing.assert_series_equal(output_convertibe, expected_data_convertibe)\n", "FAIL_TO_PASS": ["tests/integration/transformers/test_base.py::test_dummy_transformer_series_output", "tests/integration/transformers/test_base.py::test_dummy_transformer_dataframe_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_same_number_of_columns_input_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_less_output_than_input_columns", "tests/integration/transformers/test_base.py::test_multi_column_transformer_more_output_than_input_columns", "tests/integration/transformers/test_text.py::TestIDGenerator::test_end_to_end", "tests/integration/transformers/test_text.py::test_regexgenerator", "tests/integration/transformers/test_text.py::test_regexgenerator_with_custom_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_with_nans", "tests/integration/transformers/test_text.py::test_regexgenerator_data_length_bigger_than_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_input_data_bigger_than_data_length", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times_enforce_uniqueness", "tests/integration/transformers/test_text.py::test_regexgenerator_pickled", "tests/integration/transformers/test_text.py::test_regexgenerator_with_many_possibilities", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_categorical", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_float_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_nonstring_object_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info_nan", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform_error", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___setstate__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__fit_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_false", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_series", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_category_from_start", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_empty_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_nested_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_list_of_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_pandas_series", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_encoded", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column_filled_with_ones", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_1d", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_unseen_categories", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_clips_values", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___add_noise_true", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___init__", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__with_parameters", "tests/unit/transformers/test_text.py::TestIDGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestIDGenerator::test__fit", "tests/unit/transformers/test_text.py::TestIDGenerator::test__transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform_with_everything", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___getstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__generated_and_generator_size", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__custom", "tests/unit/transformers/test_text.py::TestRegexGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__fit", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__transform", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_bigger_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_smaller_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_of_input_data", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_enforce_uniqueness", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_numerical", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_enforce_uniqueness_not_enough_remaining", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message", "tests/unit/transformers/test_utils.py::test_strings_from_regex_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_digit", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_digit", "tests/unit/transformers/test_utils.py::test__any", "tests/unit/transformers/test_utils.py::test___max_repeat", "tests/unit/transformers/test_utils.py::test_strings_from_regex_very_large_regex", "tests/unit/transformers/test_utils.py::test_flatten_column_list", "tests/unit/transformers/test_utils.py::test_check_nan_in_transform", "tests/unit/transformers/test_utils.py::test_try_convert_to_dtype"]}], "all_FAIL_TO_PASS": ["tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message", "tests/integration/transformers/test_base.py::test_dummy_transformer_series_output", "tests/integration/transformers/test_base.py::test_dummy_transformer_dataframe_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_same_number_of_columns_input_output", "tests/integration/transformers/test_base.py::test_multi_column_transformer_less_output_than_input_columns", "tests/integration/transformers/test_base.py::test_multi_column_transformer_more_output_than_input_columns", "tests/integration/transformers/test_text.py::TestIDGenerator::test_end_to_end", "tests/integration/transformers/test_text.py::test_regexgenerator", "tests/integration/transformers/test_text.py::test_regexgenerator_with_custom_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_with_nans", "tests/integration/transformers/test_text.py::test_regexgenerator_data_length_bigger_than_regex", "tests/integration/transformers/test_text.py::test_regexgenerator_input_data_bigger_than_data_length", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times", "tests/integration/transformers/test_text.py::test_regexgenerator_called_multiple_times_enforce_uniqueness", "tests/integration/transformers/test_text.py::test_regexgenerator_pickled", "tests/integration/transformers/test_text.py::test_regexgenerator_with_many_possibilities", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_categorical", "tests/integration/transformers/test_text.py::test_regexgenerator_enforce_uniqueness_not_enough_values_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_float_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_alphabetical_nonstring_object_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestUniformEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__fit_info_nan", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestOrderedUniformEncoder::test__transform_error", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___setstate__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_intervals_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__fit_intervals", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_false", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_value_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_series", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_user_warning", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_nans", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_category_add_noise_true", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__transform_by_row", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_category", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__get_category_from_start", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row_called", "tests/unit/transformers/test_categorical.py::TestFrequencyEncoder::test__reverse_transform_by_row", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_empty_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_nested_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_list_of_lists", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__prepare_data_pandas_series", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_dummies_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_no_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_nans_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__fit_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nan_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_encoded", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_zeros_categorical", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown_nan", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_single_column_filled_with_ones", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_unknown", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__transform_numeric", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_no_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_nans", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_single", "tests/unit/transformers/test_categorical.py::TestOneHotEncoder::test__reverse_transform_1d", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test___init___bad_order_by", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_with_nans", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_alphabetical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__order_categories_numerical_different_dtype_error", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__transform_unseen_categories", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_clips_values", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_add_noise", "tests/unit/transformers/test_categorical.py::TestLabelEncoder::test__reverse_transform_integer_and_nans", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init__", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___init___duplicate_categories", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test___repr___add_noise_true", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit", "tests/unit/transformers/test_categorical.py::TestOrderedLabelEncoder::test__fit_error", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___init__", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestIDGenerator::test___init__with_parameters", "tests/unit/transformers/test_text.py::TestIDGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestIDGenerator::test__fit", "tests/unit/transformers/test_text.py::TestIDGenerator::test__transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform", "tests/unit/transformers/test_text.py::TestIDGenerator::test__reverse_transform_with_everything", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___getstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__generated_and_generator_size", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___setstate__", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__default", "tests/unit/transformers/test_text.py::TestRegexGenerator::test___init__custom", "tests/unit/transformers/test_text.py::TestRegexGenerator::test_reset_randomization", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__fit", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__transform", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_bigger_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_smaller_than_data_length", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_generator_size_of_input_data", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_enforce_uniqueness", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_not_enough_unique_values_numerical", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_enforce_uniqueness_not_enough_remaining", "tests/unit/transformers/test_text.py::TestRegexGenerator::test__reverse_transform_info_message", "tests/unit/transformers/test_utils.py::test_strings_from_regex_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_digit", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_literal", "tests/unit/transformers/test_utils.py::test_strings_from_regex_repeat_digit", "tests/unit/transformers/test_utils.py::test__any", "tests/unit/transformers/test_utils.py::test___max_repeat", "tests/unit/transformers/test_utils.py::test_strings_from_regex_very_large_regex", "tests/unit/transformers/test_utils.py::test_flatten_column_list", "tests/unit/transformers/test_utils.py::test_check_nan_in_transform", "tests/unit/transformers/test_utils.py::test_try_convert_to_dtype"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "scitools__cartopy-2378_x2", "level": 2, "source": "swerebenchv2", "repo": "SciTools/cartopy", "image": "swerebenchv2/scitools-cartopy:2378-631a8db", "base_commit": "631a8db383276efa447404066d817462793024f7", "num_bugs": 2, "bugs": [{"instance_id": "scitools__cartopy-2378", "base_commit": "631a8db383276efa447404066d817462793024f7", "gold_patch": "diff --git a/lib/cartopy/crs.py b/lib/cartopy/crs.py\nindex e43a266a..a39703e8 100644\n--- a/lib/cartopy/crs.py\n+++ b/lib/cartopy/crs.py\n@@ -1790,7 +1790,7 @@ class LambertConformal(Projection):\n lons[1:-1] = np.linspace(central_longitude - 180 + 0.001,\n central_longitude + 180 - 0.001, n)\n \n- points = self.transform_points(PlateCarree(globe=globe), lons, lats)\n+ points = self.transform_points(self.as_geodetic(), lons, lats)\n \n self._boundary = sgeom.LinearRing(points)\n mins = np.min(points, axis=0)\n@@ -1866,7 +1866,7 @@ class LambertAzimuthalEqualArea(Projection):\n lon = central_longitude + 180\n sign = np.sign(central_latitude) or 1\n lat = -central_latitude + sign * 0.01\n- x, max_y = self.transform_point(lon, lat, PlateCarree(globe=globe))\n+ x, max_y = self.transform_point(lon, lat, self.as_geodetic())\n \n coords = _ellipse_boundary(a * 1.9999, max_y - false_northing,\n false_easting, false_northing, 61)\n", "test_patch": "diff --git a/lib/cartopy/tests/crs/test_lambert_conformal.py b/lib/cartopy/tests/crs/test_lambert_conformal.py\nindex 23bfea68..da754c4d 100644\n--- a/lib/cartopy/tests/crs/test_lambert_conformal.py\n+++ b/lib/cartopy/tests/crs/test_lambert_conformal.py\n@@ -3,6 +3,7 @@\n # This file is part of Cartopy and is released under the BSD 3-clause license.\n # See LICENSE in the root of the repository for full licensing details.\n \n+import numpy as np\n from numpy.testing import assert_array_almost_equal\n import pyproj\n import pytest\n@@ -38,6 +39,17 @@ def test_default_with_cutoff():\n (-49788019.81831982, 30793476.08487709))\n \n \n+def test_sphere():\n+ \"\"\"Test LambertConformal with spherical globe. (#2377)\"\"\"\n+ globe = ccrs.Globe(ellipse='sphere')\n+\n+ # This would error creating a boundary\n+ crs = ccrs.LambertConformal(globe=globe)\n+\n+ assert np.all(np.isfinite(crs.x_limits))\n+ assert np.all(np.isfinite(crs.y_limits))\n+\n+\n def test_specific_lambert():\n # This projection comes from EPSG Projection 3034 - ETRS89 / ETRS-LCC.\n crs = ccrs.LambertConformal(central_longitude=10,\n", "FAIL_TO_PASS": ["lib/cartopy/tests/crs/test_lambert_conformal.py::test_sphere"]}, {"instance_id": "scitools__cartopy-2407", "base_commit": "738bba5921a3ca72a3f6d6ec9fa804514706bad4", "gold_patch": "diff --git a/lib/cartopy/crs.py b/lib/cartopy/crs.py\nindex c2441516..bc354198 100644\n--- a/lib/cartopy/crs.py\n+++ b/lib/cartopy/crs.py\n@@ -918,10 +918,7 @@ class Projection(CRS, metaclass=ABCMeta):\n geoms = []\n for geom in geometry.geoms:\n geoms.append(self._project_point(geom, src_crs))\n- if geoms:\n- return sgeom.MultiPoint(geoms)\n- else:\n- return sgeom.MultiPoint()\n+ return sgeom.MultiPoint(geoms)\n \n def _project_multiline(self, geometry, src_crs):\n geoms = []\n@@ -929,10 +926,7 @@ class Projection(CRS, metaclass=ABCMeta):\n r = self._project_line_string(geom, src_crs)\n if r:\n geoms.extend(r.geoms)\n- if geoms:\n- return sgeom.MultiLineString(geoms)\n- else:\n- return []\n+ return sgeom.MultiLineString(geoms)\n \n def _project_multipolygon(self, geometry, src_crs):\n geoms = []\n@@ -940,11 +934,7 @@ class Projection(CRS, metaclass=ABCMeta):\n r = self._project_polygon(geom, src_crs)\n if r:\n geoms.extend(r.geoms)\n- if geoms:\n- result = sgeom.MultiPolygon(geoms)\n- else:\n- result = sgeom.MultiPolygon()\n- return result\n+ return sgeom.MultiPolygon(geoms)\n \n def _project_polygon(self, polygon, src_crs):\n \"\"\"\n", "test_patch": "diff --git a/lib/cartopy/tests/test_line_string.py b/lib/cartopy/tests/test_line_string.py\nindex a0b42ff0..926dd5b5 100644\n--- a/lib/cartopy/tests/test_line_string.py\n+++ b/lib/cartopy/tests/test_line_string.py\n@@ -8,6 +8,7 @@ import time\n \n import numpy as np\n import pytest\n+import shapely\n import shapely.geometry as sgeom\n \n import cartopy.crs as ccrs\n@@ -73,6 +74,15 @@ class TestLineString:\n tgt_proj.project_geometry(line_string, src_proj)\n assert time.time() < cutoff_time, 'Projection took too long'\n \n+ @pytest.mark.skipif(shapely.__version__ < \"2\",\n+ reason=\"Shapely <2 has an incorrect geom_type \")\n+ def test_multi_linestring_return_type(self):\n+ # Check that the return type of project_geometry is a MultiLineString\n+ # and not an empty list\n+ multi_line_string = ccrs.Mercator().project_geometry(\n+ sgeom.MultiLineString(), ccrs.PlateCarree())\n+ assert isinstance(multi_line_string, sgeom.MultiLineString)\n+\n \n class FakeProjection(ccrs.PlateCarree):\n def __init__(self, left_offset=0, right_offset=0):\n", "FAIL_TO_PASS": ["lib/cartopy/tests/test_line_string.py::TestLineString::test_multi_linestring_return_type"]}], "all_FAIL_TO_PASS": ["lib/cartopy/tests/crs/test_lambert_conformal.py::test_sphere", "lib/cartopy/tests/test_line_string.py::TestLineString::test_multi_linestring_return_type"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "alteryx__woodwork-640_x2", "level": 2, "source": "swerebenchv2", "repo": "alteryx/woodwork", "image": "swerebenchv2/alteryx-woodwork:640-7bde24e", "base_commit": "7bde24e9c9b5c5a0e228b4c62c094fced9901c3b", "num_bugs": 2, "bugs": [{"instance_id": "alteryx__woodwork-640", "base_commit": "7bde24e9c9b5c5a0e228b4c62c094fced9901c3b", "gold_patch": "diff --git a/docs/source/api_reference.rst b/docs/source/api_reference.rst\nindex d5b9119..dea1466 100644\n--- a/docs/source/api_reference.rst\n+++ b/docs/source/api_reference.rst\n@@ -12,6 +12,7 @@ WoodworkTableAccessor\n WoodworkTableAccessor\n WoodworkTableAccessor.describe\n WoodworkTableAccessor.describe_dict\n+ WoodworkTableAccessor.drop\n WoodworkTableAccessor.iloc\n WoodworkTableAccessor.init\n WoodworkTableAccessor.loc\ndiff --git a/docs/source/release_notes.rst b/docs/source/release_notes.rst\nindex eb2be94..ac2c7f9 100644\n--- a/docs/source/release_notes.rst\n+++ b/docs/source/release_notes.rst\n@@ -34,6 +34,7 @@ Release Notes\n * Add ``value_counts`` to WoodworkTableAccessor (:pr:`632`)\n * Add KoalasColumnAccessor (:pr:`634`)\n * Add ``pop`` to WoodworkTableAccessor (:pr:`636`)\n+ * Add ``drop`` to WoodworkTableAccessor (:pr:`640`)\n * Fixes\n * Create new Schema object when performing pandas operation on Accessors (:pr:`595`)\n * Changes\ndiff --git a/woodwork/table_accessor.py b/woodwork/table_accessor.py\nindex a5f9fe5..e34994b 100644\n--- a/woodwork/table_accessor.py\n+++ b/woodwork/table_accessor.py\n@@ -457,6 +457,33 @@ class WoodworkTableAccessor:\n \n return series\n \n+ def drop(self, columns):\n+ \"\"\"Drop specified columns from a DataFrame.\n+\n+ Args:\n+ columns (str or list[str]): Column name or names to drop. Must be present in the DataTable.\n+\n+ Returns:\n+ (pd.DataFrame): DataFrame with the specified columns removed, maintaining Woodwork typing information.\n+\n+ Note:\n+ This method is used for removing columns only. To remove rows with ``drop``, go through the\n+ DataFrame directly and then reinitialize Woodwork with ``DataFrame.ww.init``\n+ instead of calling ``DataFrame.ww.drop``.\n+ \"\"\"\n+ if not isinstance(columns, (list, set)):\n+ columns = [columns]\n+\n+ not_present = [col for col in columns if col not in self._dataframe.columns]\n+ if not_present:\n+ raise ValueError(f'{not_present} not found in DataFrame')\n+\n+ new_schema = self._schema._get_subset_schema([col for col in self._dataframe.columns if col not in columns])\n+ new_df = self._dataframe.drop(columns, axis=1)\n+ new_df.ww.init(schema=new_schema)\n+\n+ return new_df\n+\n def mutual_information_dict(self, num_bins=10, nrows=None):\n \"\"\"\n Calculates mutual information between all pairs of columns in the DataFrame that\n", "test_patch": "diff --git a/woodwork/tests/accessor/test_table_accessor.py b/woodwork/tests/accessor/test_table_accessor.py\nindex 7948061..f3b1df0 100644\n--- a/woodwork/tests/accessor/test_table_accessor.py\n+++ b/woodwork/tests/accessor/test_table_accessor.py\n@@ -721,13 +721,6 @@ def test_underlying_index(sample_df):\n assert schema_df.index.name is None\n assert type(schema_df.index) == specified_index\n \n- # --> add back when df.ww.drop is implemented\n- # schema_dropped = schema.drop('made_index')\n- # assert 'made_index' not in schema_dropped.columns\n- # assert 'made_index' not in schema_dropped._dataframe.columns\n- # assert type(schema_dropped._dataframe.index) == unspecified_index\n- # assert type(schema_dropped.to_dataframe().index) == unspecified_index\n-\n \n def test_accessor_already_sorted(sample_unsorted_df):\n if dd and isinstance(sample_unsorted_df, dd.DataFrame):\n@@ -813,7 +806,7 @@ def test_ordinal_with_nan_values():\n \n def test_accessor_with_falsy_column_names(falsy_names_df):\n if dd and isinstance(falsy_names_df, dd.DataFrame):\n- pytest.xfail('Dask DataTables cannot handle integer column names')\n+ pytest.xfail('Dask DataFrames cannot handle integer column names')\n xfail_dask_and_koalas(falsy_names_df)\n \n schema_df = falsy_names_df.copy()\n@@ -1448,3 +1441,71 @@ def test_pop_error(sample_df):\n \n with pytest.raises(LookupError, match=\"Column with name missing not found in DataFrame\"):\n sample_df.ww.pop(\"missing\")\n+\n+\n+def test_accessor_drop(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ schema_df = sample_df.copy()\n+ schema_df.ww.init()\n+\n+ single_input_df = schema_df.ww.drop('is_registered')\n+ assert len(single_input_df.ww.columns) == (len(schema_df.columns) - 1)\n+ assert 'is_registered' not in single_input_df.ww.columns\n+ assert to_pandas(schema_df).drop('is_registered', axis='columns').equals(to_pandas(single_input_df))\n+\n+ list_input_df = schema_df.ww.drop(['is_registered'])\n+ assert len(list_input_df.ww.columns) == (len(schema_df.columns) - 1)\n+ assert 'is_registered' not in list_input_df.ww.columns\n+ assert to_pandas(schema_df).drop('is_registered', axis='columns').equals(to_pandas(list_input_df))\n+ # should be equal to the single input example above\n+ assert single_input_df.ww.schema == list_input_df.ww.schema\n+ assert to_pandas(single_input_df).equals(to_pandas(list_input_df))\n+\n+ multiple_list_df = schema_df.ww.drop(['age', 'full_name', 'is_registered'])\n+ assert len(multiple_list_df.ww.columns) == (len(schema_df.columns) - 3)\n+ assert 'is_registered' not in multiple_list_df.ww.columns\n+ assert 'full_name' not in multiple_list_df.ww.columns\n+ assert 'age' not in multiple_list_df.ww.columns\n+\n+ assert to_pandas(schema_df).drop(['is_registered', 'age', 'full_name'], axis='columns').equals(to_pandas(multiple_list_df))\n+\n+ # Drop the same columns in a different order and confirm resulting DataFrame column order doesn't change\n+ different_order_df = schema_df.ww.drop(['is_registered', 'age', 'full_name'])\n+ assert different_order_df.ww.schema == multiple_list_df.ww.schema\n+ assert to_pandas(multiple_list_df).equals(to_pandas(different_order_df))\n+\n+\n+def test_accessor_drop_indices(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ sample_df.ww.init(index='id', time_index='signup_date')\n+ assert sample_df.ww.index == 'id'\n+ assert sample_df.ww.time_index == 'signup_date'\n+\n+ dropped_index_df = sample_df.ww.drop('id')\n+ assert 'id' not in dropped_index_df.ww.columns\n+ assert dropped_index_df.ww.index is None\n+ assert dropped_index_df.ww.time_index == 'signup_date'\n+\n+ dropped_time_index_df = sample_df.ww.drop(['signup_date'])\n+ assert 'signup_date' not in dropped_time_index_df.ww.columns\n+ assert dropped_time_index_df.ww.time_index is None\n+ assert dropped_time_index_df.ww.index == 'id'\n+\n+\n+def test_accessor_drop_errors(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ sample_df.ww.init()\n+\n+ error = re.escape(\"['not_present'] not found in DataFrame\")\n+ with pytest.raises(ValueError, match=error):\n+ sample_df.ww.drop('not_present')\n+\n+ with pytest.raises(ValueError, match=error):\n+ sample_df.ww.drop(['age', 'not_present'])\n+\n+ error = re.escape(\"['not_present1', 4] not found in DataFrame\")\n+ with pytest.raises(ValueError, match=error):\n+ sample_df.ww.drop(['not_present1', 4])\n", "FAIL_TO_PASS": ["woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]"]}, {"instance_id": "alteryx__woodwork-646", "base_commit": "a55c98ff7f71022690862d3bbaa2c9ab8d32952d", "gold_patch": "diff --git a/docs/source/release_notes.rst b/docs/source/release_notes.rst\nindex ac2c7f9..8e1ee70 100644\n--- a/docs/source/release_notes.rst\n+++ b/docs/source/release_notes.rst\n@@ -35,6 +35,7 @@ Release Notes\n * Add KoalasColumnAccessor (:pr:`634`)\n * Add ``pop`` to WoodworkTableAccessor (:pr:`636`)\n * Add ``drop`` to WoodworkTableAccessor (:pr:`640`)\n+ * Add ``rename`` to WoodworkTableAccessor (:pr:`646`)\n * Fixes\n * Create new Schema object when performing pandas operation on Accessors (:pr:`595`)\n * Changes\ndiff --git a/woodwork/exceptions.py b/woodwork/exceptions.py\nindex 2e6f887..3c6a5b3 100644\n--- a/woodwork/exceptions.py\n+++ b/woodwork/exceptions.py\n@@ -42,3 +42,7 @@ class TypeConversionError(Exception):\n \n class ParametersIgnoredWarning(UserWarning):\n pass\n+\n+\n+class ColumnNotPresentError(KeyError):\n+ pass\ndiff --git a/woodwork/schema.py b/woodwork/schema.py\nindex e9cc8a0..0eaa3b5 100644\n--- a/woodwork/schema.py\n+++ b/woodwork/schema.py\n@@ -4,6 +4,7 @@ import copy\n import pandas as pd\n \n import woodwork as ww\n+from woodwork.exceptions import ColumnNotPresentError\n from woodwork.schema_column import (\n _add_semantic_tags,\n _get_column_dict,\n@@ -327,6 +328,37 @@ class Schema(object):\n _check_time_index(self.columns.keys(), new_time_index, self.logical_types.get(new_time_index))\n self._set_time_index_tags(new_time_index)\n \n+ def rename(self, columns):\n+ \"\"\"Renames columns in a Schema\n+\n+ Args:\n+ columns (dict[str -> str]): A dictionary mapping current column names to new column names.\n+\n+ Returns:\n+ woodwork.Schema: Schema with the specified columns renamed.\n+ \"\"\"\n+ if not isinstance(columns, dict):\n+ raise TypeError('columns must be a dictionary')\n+\n+ for old_name, new_name in columns.items():\n+ if old_name not in self.columns:\n+ raise ColumnNotPresentError(f\"Column to rename must be present. {old_name} cannot be found.\")\n+ if new_name in self.columns and new_name not in columns.keys():\n+ raise ValueError(f\"The column {new_name} is already present. Please choose another name to rename {old_name} to or also rename {old_name}.\")\n+\n+ if len(columns) != len(set(columns.values())):\n+ raise ValueError('New columns names must be unique from one another.')\n+\n+ new_schema = self._get_subset_schema(list(self.columns.keys()))\n+\n+ cols_to_update = {}\n+ for old_name, new_name in columns.items():\n+ col = new_schema.columns.pop(old_name)\n+ cols_to_update[new_name] = col\n+\n+ new_schema.columns.update(cols_to_update)\n+ return new_schema\n+\n def _set_index_tags(self, index):\n '''\n Updates the semantic tags of the index by removing any standard tags\ndiff --git a/woodwork/table_accessor.py b/woodwork/table_accessor.py\nindex e34994b..349dfea 100644\n--- a/woodwork/table_accessor.py\n+++ b/woodwork/table_accessor.py\n@@ -461,7 +461,7 @@ class WoodworkTableAccessor:\n \"\"\"Drop specified columns from a DataFrame.\n \n Args:\n- columns (str or list[str]): Column name or names to drop. Must be present in the DataTable.\n+ columns (str or list[str]): Column name or names to drop. Must be present in the DataFrame.\n \n Returns:\n (pd.DataFrame): DataFrame with the specified columns removed, maintaining Woodwork typing information.\n@@ -484,6 +484,21 @@ class WoodworkTableAccessor:\n \n return new_df\n \n+ def rename(self, columns):\n+ \"\"\"Renames columns in a DataFrame, maintaining Woodwork typing information.\n+\n+ Args:\n+ columns (dict[str -> str]): A dictionary mapping current column names to new column names.\n+\n+ Returns:\n+ DataFrame: DataFrame with the specified columns renamed, maintaining Woodwork typing information.\n+ \"\"\"\n+ new_schema = self._schema.rename(columns)\n+ new_df = self._dataframe.rename(columns=columns)\n+\n+ new_df.ww.init(schema=new_schema)\n+ return new_df\n+\n def mutual_information_dict(self, num_bins=10, nrows=None):\n \"\"\"\n Calculates mutual information between all pairs of columns in the DataFrame that\n", "test_patch": "diff --git a/woodwork/tests/accessor/test_table_accessor.py b/woodwork/tests/accessor/test_table_accessor.py\nindex f3b1df0..933054a 100644\n--- a/woodwork/tests/accessor/test_table_accessor.py\n+++ b/woodwork/tests/accessor/test_table_accessor.py\n@@ -825,15 +825,17 @@ def test_accessor_with_falsy_column_names(falsy_names_df):\n assert '' not in schema_df.ww.columns\n assert schema_df.ww.time_index is None\n \n+ schema_df.ww.set_index(None)\n+ assert schema_df.ww.index is None\n+\n # --> add back in if setitem is implemented\n # dt[''] = popped_col\n # assert dt[''].name == ''\n # assert dt['']._series.name == ''\n \n- # --> add back in once rename is implemented on the accessor\n- # dt = dt.rename({'': 'col_with_name'})\n- # assert '' not in dt.columns\n- # assert 'col_with_name' in dt.columns\n+ renamed_df = schema_df.ww.rename({0: 'col_with_name'})\n+ assert 0 not in renamed_df.columns\n+ assert 'col_with_name' in renamed_df.columns\n \n \n def test_accessor_repr(sample_df, sample_column_names, sample_inferred_logical_types):\n@@ -947,11 +949,11 @@ def test_dataframe_methods_on_accessor_inplace(sample_df):\n \n pd.testing.assert_frame_equal(to_pandas(schema_df), to_pandas(df_pre_sort.sort_values(['full_name'])))\n \n- warning = \"Operation performed by rename has invalidated the Woodwork typing information:\\n \"\n+ warning = \"Operation performed by insert has invalidated the Woodwork typing information:\\n \"\n \"The following columns in the DataFrame were missing from the typing information: {'new_name'}.\\n \"\n \"Please initialize Woodwork with DataFrame.ww.init\"\n with pytest.warns(TypingInfoMismatchWarning, match=warning):\n- schema_df.ww.rename({'id': 'new_name'}, inplace=True, axis=1)\n+ schema_df.ww.insert(loc=0, column=\"new_name\", value=[1, 2, 3, 4])\n assert 'new_name' in schema_df.columns\n assert schema_df.ww.schema is None\n \n@@ -1509,3 +1511,64 @@ def test_accessor_drop_errors(sample_df):\n error = re.escape(\"['not_present1', 4] not found in DataFrame\")\n with pytest.raises(ValueError, match=error):\n sample_df.ww.drop(['not_present1', 4])\n+\n+\n+def test_accessor_rename(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ table_metadata = {'table_info': 'this is text'}\n+ id_description = 'the id of the row'\n+ sample_df.ww.init(index='id',\n+ time_index='signup_date',\n+ table_metadata=table_metadata,\n+ column_descriptions={'id': id_description},\n+ semantic_tags={'age': 'test_tag'},\n+ logical_types={'age': Double})\n+ original_df = sample_df.ww.copy()\n+\n+ new_df = sample_df.ww.rename({'age': 'birthday'})\n+\n+ assert to_pandas(sample_df.rename({'age': 'birthday'}, axis=1)).equals(to_pandas(new_df))\n+ # Confirm original dataframe hasn't changed\n+ assert to_pandas(sample_df).equals(original_df)\n+ assert sample_df.ww.schema == original_df.ww.schema\n+\n+ assert original_df.columns.get_loc('age') == new_df.columns.get_loc('birthday')\n+ pd.testing.assert_series_equal(original_df['age'], new_df['birthday'], check_names=False)\n+\n+ # confirm that metadata and descriptions are there\n+ assert new_df.ww.metadata == table_metadata\n+ assert new_df.ww.columns['id']['description'] == id_description\n+\n+ old_col = sample_df.ww.columns['age']\n+ new_col = new_df.ww.columns['birthday']\n+ assert old_col['logical_type'] == new_col['logical_type']\n+ assert old_col['semantic_tags'] == new_col['semantic_tags']\n+ assert old_col['dtype'] == new_col['dtype']\n+\n+ new_df = sample_df.ww.rename({'age': 'full_name', 'full_name': 'age'})\n+\n+ pd.testing.assert_series_equal(original_df['age'], new_df['full_name'], check_names=False)\n+ pd.testing.assert_series_equal(original_df['full_name'], new_df['age'], check_names=False)\n+\n+ assert original_df.columns.get_loc('age') == new_df.columns.get_loc('full_name')\n+ assert original_df.columns.get_loc('full_name') == new_df.columns.get_loc('age')\n+\n+\n+def test_accessor_rename_indices(sample_df):\n+ xfail_dask_and_koalas(sample_df)\n+\n+ sample_df.ww.init(\n+ index='id',\n+ time_index='signup_date')\n+\n+ renamed_df = sample_df.ww.rename({'id': 'renamed_index', 'signup_date': 'renamed_time_index'})\n+ assert 'id' not in renamed_df.columns\n+ assert 'signup_date' not in renamed_df.columns\n+ assert 'renamed_index' in renamed_df.columns\n+ assert 'renamed_time_index' in renamed_df.columns\n+\n+ assert all(renamed_df.index == renamed_df['renamed_index'])\n+\n+ assert renamed_df.ww.index == 'renamed_index'\n+ assert renamed_df.ww.time_index == 'renamed_time_index'\ndiff --git a/woodwork/tests/schema/test_schema.py b/woodwork/tests/schema/test_schema.py\nindex 3d1e408..cb60d23 100644\n--- a/woodwork/tests/schema/test_schema.py\n+++ b/woodwork/tests/schema/test_schema.py\n@@ -5,6 +5,7 @@ import pandas as pd\n import pytest\n \n from woodwork import type_system\n+from woodwork.exceptions import ColumnNotPresentError\n from woodwork.logical_types import (\n Boolean,\n Categorical,\n@@ -786,3 +787,72 @@ def test_set_index_twice(sample_column_names, sample_inferred_logical_types):\n assert schema.time_index == 'signup_date'\n assert schema.semantic_tags['signup_date'] == {'time_index'}\n assert schema == original_schema\n+\n+\n+def test_schema_rename_errors(sample_column_names, sample_inferred_logical_types):\n+ schema = Schema(sample_column_names, sample_inferred_logical_types, index='id', time_index='signup_date')\n+\n+ error = \"columns must be a dictionary\"\n+ with pytest.raises(TypeError, match=error):\n+ schema.rename(1)\n+\n+ error = 'New columns names must be unique from one another.'\n+ with pytest.raises(ValueError, match=error):\n+ schema.rename({'age': 'test', 'full_name': 'test'})\n+\n+ error = 'Column to rename must be present. not_present cannot be found.'\n+ with pytest.raises(ColumnNotPresentError, match=error):\n+ schema.rename({'not_present': 'test'})\n+\n+ error = 'The column email is already present. Please choose another name to rename age to or also rename age.'\n+ with pytest.raises(ValueError, match=error):\n+ schema.rename({'age': 'email'})\n+\n+\n+def test_schema_rename(sample_column_names, sample_inferred_logical_types):\n+\n+ table_metadata = {'table_info': 'this is text'}\n+ id_description = 'the id of the row'\n+ schema = Schema(sample_column_names, sample_inferred_logical_types,\n+ index='id',\n+ time_index='signup_date',\n+ table_metadata=table_metadata,\n+ column_descriptions={'id': id_description})\n+ original_schema = schema._get_subset_schema(list(schema.columns.keys()))\n+\n+ renamed_schema = schema.rename({'age': 'birthday'})\n+\n+ # Confirm original schema hasn't changed\n+ assert schema == original_schema\n+\n+ assert 'age' not in renamed_schema.columns\n+ assert 'birthday' in renamed_schema.columns\n+\n+ # confirm that metadata and descriptions are there\n+ assert renamed_schema.metadata == table_metadata\n+ assert schema.columns['id']['description'] == id_description\n+\n+ old_col = schema.columns['age']\n+ new_col = renamed_schema.columns['birthday']\n+ assert old_col['logical_type'] == new_col['logical_type']\n+ assert old_col['semantic_tags'] == new_col['semantic_tags']\n+ assert old_col['dtype'] == new_col['dtype']\n+\n+ swapped_schema = schema.rename({'age': 'full_name', 'full_name': 'age'})\n+ swapped_back_schema = swapped_schema.rename({'age': 'full_name', 'full_name': 'age'})\n+ assert swapped_back_schema == schema\n+\n+\n+def test_schema_rename_indices(sample_column_names, sample_inferred_logical_types):\n+ schema = Schema(sample_column_names, sample_inferred_logical_types,\n+ index='id',\n+ time_index='signup_date')\n+\n+ renamed_schema = schema.rename({'id': 'renamed_index', 'signup_date': 'renamed_time_index'})\n+ assert 'id' not in renamed_schema.columns\n+ assert 'signup_date' not in renamed_schema.columns\n+ assert 'renamed_index' in renamed_schema.columns\n+ assert 'renamed_time_index' in renamed_schema.columns\n+\n+ assert renamed_schema.index == 'renamed_index'\n+ assert renamed_schema.time_index == 'renamed_time_index'\n", "FAIL_TO_PASS": ["woodwork/tests/accessor/test_table_accessor.py::test_check_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_logical_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_time_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_unique_column_names_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_schema_property[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_separation_of_params[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_schema_parameter_warning[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_getattr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_equality_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_valid_string_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_numeric_datetime_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_numeric_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_invalid_string_time_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_string_logical_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_int_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_bool_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_str_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_float_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_datetime_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_timedelta_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_category_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_object_dtype_on_init[latlong_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_sets_string_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_boolean_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_int64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_float64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_datetime64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_invalid_dtype_casting", "woodwork/tests/accessor/test_table_accessor.py::test_underlying_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_already_sorted[sample_unsorted_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_order[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_incomplete_ranking[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_nan_values", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_falsy_column_names[falsy_names_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_repr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_invalid_schema_message[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_new_schema_object[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_inplace[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_returning_series[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_other_returns[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_subset_df_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_error[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename_indices[sample_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_physical_types", "woodwork/tests/schema/test_schema.py::test_schema_logical_types", "woodwork/tests/schema/test_schema.py::test_schema_semantic_tags", "woodwork/tests/schema/test_schema.py::test_schema_types", "woodwork/tests/schema/test_schema.py::test_schema_repr[small_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_repr_empty", "woodwork/tests/schema/test_schema.py::test_schema_equality", "woodwork/tests/schema/test_schema.py::test_schema_table_metadata", "woodwork/tests/schema/test_schema.py::test_schema_column_metadata", "woodwork/tests/schema/test_schema.py::test_get_subset_schema", "woodwork/tests/schema/test_schema.py::test_get_subset_schema_all_params", "woodwork/tests/schema/test_schema.py::test_set_logical_types", "woodwork/tests/schema/test_schema.py::test_set_logical_types_empty", "woodwork/tests/schema/test_schema.py::test_set_logical_types_invalid_data", "woodwork/tests/schema/test_schema.py::test_set_types_combined", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_add_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_all_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_invalid_column", "woodwork/tests/schema/test_schema.py::test_remove_semantic_tags", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_time_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_removes_index_via_tags", "woodwork/tests/schema/test_schema.py::test_removes_time_index_via_tags", "woodwork/tests/schema/test_schema.py::test_set_index", "woodwork/tests/schema/test_schema.py::test_set_index_errors", "woodwork/tests/schema/test_schema.py::test_set_time_index", "woodwork/tests/schema/test_schema.py::test_set_numeric_datetime_time_index", "woodwork/tests/schema/test_schema.py::test_set_time_index_errors", "woodwork/tests/schema/test_schema.py::test_set_index_twice", "woodwork/tests/schema/test_schema.py::test_schema_rename_errors", "woodwork/tests/schema/test_schema.py::test_schema_rename", "woodwork/tests/schema/test_schema.py::test_schema_rename_indices"]}], "all_FAIL_TO_PASS": ["woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_logical_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_time_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_check_unique_column_names_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_schema_property[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_separation_of_params[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_init_accessor_with_schema_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_schema_parameter_warning[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_getattr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_equality_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_valid_string_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_numeric_datetime_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_numeric_time_index[time_index_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_invalid_string_time_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_init_with_string_logical_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_int_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_bool_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_str_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_float_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_datetime_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_timedelta_dtype_inference_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_category_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_object_dtype_on_init[latlong_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_sets_string_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_boolean_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_int64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_float64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_sets_datetime64_dtype_on_init", "woodwork/tests/accessor/test_table_accessor.py::test_invalid_dtype_casting", "woodwork/tests/accessor/test_table_accessor.py::test_underlying_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_already_sorted[sample_unsorted_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_order[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_incomplete_ranking[sample_series_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_ordinal_with_nan_values", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_with_falsy_column_names[falsy_names_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_repr[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_invalid_schema_message[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_new_schema_object[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_inplace[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_returning_series[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_dataframe_methods_on_accessor_other_returns[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_get_subset_df_with_schema[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_set_index_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_set_types_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_index[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_pop_error[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_indices[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_drop_errors[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename[sample_df_pandas]", "woodwork/tests/accessor/test_table_accessor.py::test_accessor_rename_indices[sample_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_physical_types", "woodwork/tests/schema/test_schema.py::test_schema_logical_types", "woodwork/tests/schema/test_schema.py::test_schema_semantic_tags", "woodwork/tests/schema/test_schema.py::test_schema_types", "woodwork/tests/schema/test_schema.py::test_schema_repr[small_df_pandas]", "woodwork/tests/schema/test_schema.py::test_schema_repr_empty", "woodwork/tests/schema/test_schema.py::test_schema_equality", "woodwork/tests/schema/test_schema.py::test_schema_table_metadata", "woodwork/tests/schema/test_schema.py::test_schema_column_metadata", "woodwork/tests/schema/test_schema.py::test_get_subset_schema", "woodwork/tests/schema/test_schema.py::test_get_subset_schema_all_params", "woodwork/tests/schema/test_schema.py::test_set_logical_types", "woodwork/tests/schema/test_schema.py::test_set_logical_types_empty", "woodwork/tests/schema/test_schema.py::test_set_logical_types_invalid_data", "woodwork/tests/schema/test_schema.py::test_set_types_combined", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_set_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_add_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_all_semantic_tags", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_with_time_index", "woodwork/tests/schema/test_schema.py::test_reset_semantic_tags_invalid_column", "woodwork/tests/schema/test_schema.py::test_remove_semantic_tags", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_raises_error_setting_time_index_tag_directly", "woodwork/tests/schema/test_schema.py::test_removes_index_via_tags", "woodwork/tests/schema/test_schema.py::test_removes_time_index_via_tags", "woodwork/tests/schema/test_schema.py::test_set_index", "woodwork/tests/schema/test_schema.py::test_set_index_errors", "woodwork/tests/schema/test_schema.py::test_set_time_index", "woodwork/tests/schema/test_schema.py::test_set_numeric_datetime_time_index", "woodwork/tests/schema/test_schema.py::test_set_time_index_errors", "woodwork/tests/schema/test_schema.py::test_set_index_twice", "woodwork/tests/schema/test_schema.py::test_schema_rename_errors", "woodwork/tests/schema/test_schema.py::test_schema_rename", "woodwork/tests/schema/test_schema.py::test_schema_rename_indices"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "amaranth-lang__amaranth-1319_x2", "level": 2, "source": "swerebenchv2", "repo": "amaranth-lang/amaranth", "image": "swerebenchv2/amaranth-lang-amaranth:1319-49a8a94", "base_commit": "49a8a942e82bb214d10c1bb670b61a5264b82be0", "num_bugs": 2, "bugs": [{"instance_id": "amaranth-lang__amaranth-1319", "base_commit": "49a8a942e82bb214d10c1bb670b61a5264b82be0", "gold_patch": "diff --git a/amaranth/sim/_pyrtl.py b/amaranth/sim/_pyrtl.py\nindex f6c4943..5505cfb 100644\n--- a/amaranth/sim/_pyrtl.py\n+++ b/amaranth/sim/_pyrtl.py\n@@ -153,12 +153,16 @@ class _ValueCompiler(ValueVisitor, _Compiler):\n \n \n class _RHSValueCompiler(_ValueCompiler):\n- def __init__(self, state, emitter, *, mode, inputs=None):\n+ def __init__(self, state, emitter, *, mode, inputs=None, rrhs=None):\n super().__init__(state, emitter)\n assert mode in (\"curr\", \"next\")\n self.mode = mode\n # If not None, `inputs` gets populated with RHS signals.\n self.inputs = inputs\n+ # When this compiler is used to grab the \"next\" value from within _LHSValueCompiler,\n+ # we still need to use \"curr\" mode for reading part offsets etc. Allow setting a separate\n+ # _RhsValueCompiler for these contexts.\n+ self.rrhs = rrhs or self\n \n def sign(self, value):\n value_mask = (1 << len(value)) - 1\n@@ -251,7 +255,7 @@ class _RHSValueCompiler(_ValueCompiler):\n \n def on_Part(self, value):\n offset_mask = (1 << len(value.offset)) - 1\n- offset = f\"({value.stride} * ({offset_mask:#x} & {self(value.offset)}))\"\n+ offset = f\"({value.stride} * ({offset_mask:#x} & {self.rrhs(value.offset)}))\"\n return f\"({(1 << value.width) - 1} & \" \\\n f\"{self(value.value)} >> {offset})\"\n \n@@ -267,7 +271,7 @@ class _RHSValueCompiler(_ValueCompiler):\n return f\"0\"\n \n def on_SwitchValue(self, value):\n- gen_test = self.emitter.def_var(\"test\", f\"{(1 << len(value.test)) - 1:#x} & {self(value.test)}\")\n+ gen_test = self.emitter.def_var(\"test\", f\"{(1 << len(value.test)) - 1:#x} & {self.rrhs(value.test)}\")\n gen_value = self.emitter.def_var(\"rhs_switch\", \"0\")\n def case_handler(patterns, elem):\n self.emitter.append(f\"{gen_value} = {self.sign(elem)}\")\n@@ -290,7 +294,7 @@ class _LHSValueCompiler(_ValueCompiler):\n self.rrhs = rhs\n # `lrhs` is used to translate the read part of a read-modify-write cycle during partial\n # update of an lvalue.\n- self.lrhs = _RHSValueCompiler(state, emitter, mode=\"next\", inputs=None)\n+ self.lrhs = _RHSValueCompiler(state, emitter, mode=\"next\", inputs=None, rrhs=rhs)\n # If not None, `outputs` gets populated with signals on LHS.\n self.outputs = outputs\n \n", "test_patch": "diff --git a/tests/test_sim.py b/tests/test_sim.py\nindex fa4f881..6b9affd 100644\n--- a/tests/test_sim.py\n+++ b/tests/test_sim.py\n@@ -366,6 +366,16 @@ class SimulatorUnitTestCase(FHDLTestCase):\n self.assertStatement(stmt, [C(1), C(0b010)], C(0b001110101, 9))\n self.assertStatement(stmt, [C(2), C(0b100)], C(0b001001001, 9))\n \n+ def test_array_lhs_heterogenous_slice(self):\n+ l = Signal(1, init=1)\n+ m = Signal(3, init=4)\n+ n = Signal(5, init=7)\n+ array = Array([l, m, n])\n+ stmt = lambda y, a, b: [array[a].as_value()[2:].eq(b), y.eq(Cat(*array))]\n+ self.assertStatement(stmt, [C(0), C(0b000)], C(0b001111001, 9))\n+ self.assertStatement(stmt, [C(1), C(0b010)], C(0b001110001, 9))\n+ self.assertStatement(stmt, [C(2), C(0b100)], C(0b100111001, 9))\n+\n def test_array_lhs_oob(self):\n l = Signal(3)\n m = Signal(3)\n", "FAIL_TO_PASS": ["tests/test_sim.py::SimulatorUnitTestCase::test_array_lhs_heterogenous_slice"]}, {"instance_id": "amaranth-lang__amaranth-1328", "base_commit": "16f187e7fa128fe013ea347c408772206583cb63", "gold_patch": "diff --git a/amaranth/sim/_base.py b/amaranth/sim/_base.py\nindex 046f690..cf0ca61 100644\n--- a/amaranth/sim/_base.py\n+++ b/amaranth/sim/_base.py\n@@ -19,6 +19,7 @@ class BaseSignalState:\n __slots__ = ()\n \n signal = NotImplemented\n+ is_comb = NotImplemented\n \n curr = NotImplemented\n next = NotImplemented\ndiff --git a/amaranth/sim/_pyeval.py b/amaranth/sim/_pyeval.py\nindex 10ecb64..be72cc3 100644\n--- a/amaranth/sim/_pyeval.py\n+++ b/amaranth/sim/_pyeval.py\n@@ -1,5 +1,6 @@\n from amaranth.hdl._ast import *\n from amaranth.hdl._mem import MemoryData\n+from amaranth.hdl._ir import DriverConflict\n \n \n def _eval_matches(test, patterns):\n@@ -165,6 +166,8 @@ def _eval_assign_inner(sim, lhs, lhs_start, rhs, rhs_len):\n if lhs_start >= len(lhs):\n return\n slot = sim.get_signal(lhs)\n+ if sim.slots[slot].is_comb:\n+ raise DriverConflict(\"Combinationally driven signals cannot be overriden by testbenches\")\n value = sim.slots[slot].next\n mask = (1 << lhs_stop) - (1 << lhs_start)\n value &= ~mask\ndiff --git a/amaranth/sim/_pyrtl.py b/amaranth/sim/_pyrtl.py\nindex 0483dfa..bbf75ea 100644\n--- a/amaranth/sim/_pyrtl.py\n+++ b/amaranth/sim/_pyrtl.py\n@@ -479,6 +479,7 @@ class _FragmentCompiler:\n if domain_name == \"comb\":\n for signal in domain_signals:\n signal_index = self.state.get_signal(signal)\n+ self.state.slots[signal_index].is_comb = True\n emitter.append(f\"next_{signal_index} = {signal.init}\")\n \n inputs = SignalSet()\ndiff --git a/amaranth/sim/pysim.py b/amaranth/sim/pysim.py\nindex 298fe99..dc8098d 100644\n--- a/amaranth/sim/pysim.py\n+++ b/amaranth/sim/pysim.py\n@@ -303,10 +303,11 @@ class _Timeline:\n \n \n class _PySignalState(BaseSignalState):\n- __slots__ = (\"signal\", \"curr\", \"next\", \"waiters\", \"pending\")\n+ __slots__ = (\"signal\", \"is_comb\", \"curr\", \"next\", \"waiters\", \"pending\")\n \n def __init__(self, signal, pending):\n self.signal = signal\n+ self.is_comb = False\n self.pending = pending\n self.waiters = {}\n self.curr = self.next = signal.init\n", "test_patch": "diff --git a/tests/test_sim.py b/tests/test_sim.py\nindex 6e43011..8dad613 100644\n--- a/tests/test_sim.py\n+++ b/tests/test_sim.py\n@@ -1395,3 +1395,15 @@ class SimulatorRegressionTestCase(FHDLTestCase):\n self.assertEqual((yield C(0b1111, 4) ^ ~C(1, 1)), 0b1111)\n sim.add_testbench(process)\n sim.run()\n+\n+ def test_comb_assign(self):\n+ c = Signal()\n+ m = Module()\n+ m.d.comb += c.eq(1)\n+ sim = Simulator(m)\n+ def testbench():\n+ with self.assertRaisesRegex(DriverConflict,\n+ r\"^Combinationally driven signals cannot be overriden by testbenches$\"):\n+ yield c.eq(0)\n+ sim.add_testbench(testbench)\n+ sim.run()\n", "FAIL_TO_PASS": ["tests/test_sim.py::SimulatorRegressionTestCase::test_comb_assign"]}], "all_FAIL_TO_PASS": ["tests/test_sim.py::SimulatorUnitTestCase::test_array_lhs_heterogenous_slice", "tests/test_sim.py::SimulatorRegressionTestCase::test_comb_assign"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "jnothman__upsetplot-261_x2", "level": 2, "source": "swerebenchv2", "repo": "jnothman/UpSetPlot", "image": "swerebenchv2/jnothman-upsetplot:261-19e891e", "base_commit": "19e891e869a0f8dc6fbb4ba01b1949a17bc898a3", "num_bugs": 2, "bugs": [{"instance_id": "jnothman__upsetplot-261", "base_commit": "19e891e869a0f8dc6fbb4ba01b1949a17bc898a3", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 197292b..a00b4d9 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -4,6 +4,9 @@ What's new in version 0.9\n - Fixes a bug where ``show_percentages`` used the incorrect denominator if\n filtering (e.g. ``min_subset_size``) was applied. This bug was a regression\n introduced in version 0.7. (:issue:`248`)\n+- Add a ``style_categories`` method to customize category plot styles, including\n+ shading of rows in the intersection matrix, and bars in the totals plot.\n+ (:issue:`261` with thanks to :user:`Marcel Albus `).\n - Ability to disable totals plot with `totals_plot_elements=0`. (:issue:`246`)\n - Added ``max_subset_rank`` to get only n most populous subsets. (:issue:`253`)\n \ndiff --git a/examples/plot_highlight.py b/examples/plot_highlight.py\nindex 1cffbc6..bccc332 100644\n--- a/examples/plot_highlight.py\n+++ b/examples/plot_highlight.py\n@@ -62,7 +62,9 @@ plt.show()\n \n upset = UpSet(example, facecolor=\"gray\")\n upset.style_subsets(present=\"cat0\", label=\"Contains cat0\", facecolor=\"blue\")\n-upset.style_subsets(present=\"cat1\", label=\"Contains cat1\", hatch=\"xx\")\n+upset.style_subsets(\n+ present=\"cat1\", label=\"Contains cat1\", hatch=\"xx\", edgecolor=\"black\"\n+)\n upset.style_subsets(present=\"cat2\", label=\"Contains cat2\", edgecolor=\"red\")\n \n # reduce legend size:\ndiff --git a/examples/plot_highlight_categories.py b/examples/plot_highlight_categories.py\nnew file mode 100644\nindex 0000000..eae84d9\n--- /dev/null\n+++ b/examples/plot_highlight_categories.py\n@@ -0,0 +1,41 @@\n+\"\"\"\n+================================\n+Highlighting selected categories\n+================================\n+\n+Demonstrates use of the `style_categories` method to mark some\n+categories differently.\n+\"\"\"\n+\n+from matplotlib import pyplot as plt\n+\n+from upsetplot import UpSet, generate_counts\n+\n+example = generate_counts()\n+\n+\n+##########################################################################\n+# Categories can be shaded by name with the ``shading_`` parameters.\n+\n+upset = UpSet(example)\n+upset.style_categories(\"cat2\", shading_edgecolor=\"darkgreen\", shading_linewidth=1)\n+upset.style_categories(\n+ \"cat1\",\n+ shading_facecolor=\"lavender\",\n+)\n+upset.plot()\n+plt.suptitle(\"Shade or edge a category with color\")\n+plt.show()\n+\n+\n+##########################################################################\n+# Category total bars can be styled with the ``bar_`` parameters.\n+# You can also specify categories using a list of names.\n+\n+upset = UpSet(example)\n+upset.style_categories(\n+ [\"cat2\", \"cat1\"], bar_facecolor=\"aqua\", bar_hatch=\"xx\", bar_edgecolor=\"black\"\n+)\n+upset.plot()\n+plt.suptitle(\"\")\n+plt.show()\ndiff --git a/upsetplot/plotting.py b/upsetplot/plotting.py\nindex 627d846..e2f50bd 100644\n--- a/upsetplot/plotting.py\n+++ b/upsetplot/plotting.py\n@@ -266,6 +266,7 @@ class UpSet:\n \"\"\"\n \n _default_figsize = (10, 6)\n+ DPI = 100 # standard matplotlib value\n \n def __init__(\n self,\n@@ -338,6 +339,7 @@ class UpSet:\n reverse=not self._horizontal,\n include_empty_subsets=include_empty_subsets,\n )\n+ self.category_styles = {}\n self.subset_styles = [\n {\"facecolor\": facecolor} for i in range(len(self.intersections))\n ]\n@@ -924,6 +926,16 @@ class UpSet:\n )\n self._label_sizes(ax, rects, \"left\" if self._horizontal else \"top\")\n \n+ for category, rect in zip(self.totals.index.values, rects):\n+ style = {\n+ k[len(\"bar_\") :]: v\n+ for k, v in self.category_styles.get(category, {}).items()\n+ if k.startswith(\"bar_\")\n+ }\n+ style.setdefault(\"edgecolor\", style.get(\"facecolor\", self._facecolor))\n+ for attr, val in style.items():\n+ getattr(rect, \"set_\" + attr)(val)\n+\n max_total = self.totals.max()\n if self._horizontal:\n orig_ax.set_xlim(max_total, 0)\n@@ -935,15 +947,34 @@ class UpSet:\n ax.patch.set_visible(False)\n \n def plot_shading(self, ax):\n- # alternating row shading (XXX: use add_patch(Rectangle)?)\n- for i in range(0, len(self.totals), 2):\n+ # shade all rows, set every second row to zero visibility\n+ for i, category in enumerate(self.totals.index):\n+ default_shading = (\n+ self._shading_color if i % 2 == 0 else (0.0, 0.0, 0.0, 0.0)\n+ )\n+ shading_style = {\n+ k[len(\"shading_\") :]: v\n+ for k, v in self.category_styles.get(category, {}).items()\n+ if k.startswith(\"shading_\")\n+ }\n+\n+ lw = shading_style.get(\n+ \"linewidth\", 1 if shading_style.get(\"edgecolor\") else 0\n+ )\n+ lw_padding = lw / (self._default_figsize[0] * self.DPI)\n+ start_x = lw_padding\n+ end_x = 1 - lw_padding * 3\n+\n rect = plt.Rectangle(\n- self._swapaxes(0, i - 0.4),\n- *self._swapaxes(*(1, 0.8)),\n- facecolor=self._shading_color,\n- lw=0,\n+ self._swapaxes(start_x, i - 0.4),\n+ *self._swapaxes(end_x, 0.8),\n+ facecolor=shading_style.get(\"facecolor\", default_shading),\n+ edgecolor=shading_style.get(\"edgecolor\", None),\n+ ls=shading_style.get(\"linestyle\", \"-\"),\n+ lw=lw,\n zorder=0,\n )\n+\n ax.add_patch(rect)\n ax.set_frame_on(False)\n ax.tick_params(\n@@ -962,6 +993,66 @@ class UpSet:\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n \n+ def style_categories(\n+ self,\n+ categories,\n+ *,\n+ bar_facecolor=None,\n+ bar_hatch=None,\n+ bar_edgecolor=None,\n+ bar_linewidth=None,\n+ bar_linestyle=None,\n+ shading_facecolor=None,\n+ shading_edgecolor=None,\n+ shading_linewidth=None,\n+ shading_linestyle=None,\n+ ):\n+ \"\"\"Updates the style of the categories.\n+\n+ Select a category by name, and style either its total bar or its shading.\n+\n+ .. versionadded:: 0.9\n+\n+ Parameters\n+ ----------\n+ categories : str or list[str]\n+ Category names where the changed style applies.\n+ bar_facecolor : str or RGBA matplotlib color tuple, optional.\n+ Override the default facecolor in the totals plot.\n+ bar_hatch : str, optional\n+ Set a hatch for the totals plot.\n+ bar_edgecolor : str or matplotlib color, optional\n+ Set the edgecolor for total bars.\n+ bar_linewidth : int, optional\n+ Line width in points for total bar edges.\n+ bar_linestyle : str, optional\n+ Line style for edges.\n+ shading_facecolor : str or RGBA matplotlib color tuple, optional.\n+ Override the default alternating shading for specified categories.\n+ shading_edgecolor : str or matplotlib color, optional\n+ Set the edgecolor for bars, dots, and the line between dots.\n+ shading_linewidth : int, optional\n+ Line width in points for edges.\n+ shading_linestyle : str, optional\n+ Line style for edges.\n+ \"\"\"\n+ if isinstance(categories, str):\n+ categories = [categories]\n+ style = {\n+ \"bar_facecolor\": bar_facecolor,\n+ \"bar_hatch\": bar_hatch,\n+ \"bar_edgecolor\": bar_edgecolor,\n+ \"bar_linewidth\": bar_linewidth,\n+ \"bar_linestyle\": bar_linestyle,\n+ \"shading_facecolor\": shading_facecolor,\n+ \"shading_edgecolor\": shading_edgecolor,\n+ \"shading_linewidth\": shading_linewidth,\n+ \"shading_linestyle\": shading_linestyle,\n+ }\n+ style = {k: v for k, v in style.items() if v is not None}\n+ for category_name in categories:\n+ self.category_styles.setdefault(category_name, {}).update(style)\n+\n def plot(self, fig=None):\n \"\"\"Draw all parts of the plot onto fig or a new figure\n \n", "test_patch": "diff --git a/upsetplot/tests/test_upsetplot.py b/upsetplot/tests/test_upsetplot.py\nindex 80dfa76..d96b42d 100644\n--- a/upsetplot/tests/test_upsetplot.py\n+++ b/upsetplot/tests/test_upsetplot.py\n@@ -1154,6 +1154,51 @@ def test_style_subsets_artists(orientation):\n # matrix_line_collection = upset_axes[\"matrix\"].collections[1]\n \n \n+@pytest.mark.parametrize(\n+ (\n+ \"kwarg_list\",\n+ \"expected_category_styles\",\n+ ),\n+ [\n+ # Different forms of including two categories\n+ (\n+ [{\"categories\": [\"cat1\", \"cat2\"], \"shading_facecolor\": \"red\"}],\n+ {\n+ \"cat1\": {\"shading_facecolor\": \"red\"},\n+ \"cat2\": {\"shading_facecolor\": \"red\"},\n+ },\n+ ),\n+ (\n+ [\n+ {\"categories\": [\"cat1\", \"cat2\"], \"shading_facecolor\": \"red\"},\n+ {\"categories\": \"cat1\", \"shading_facecolor\": \"green\"},\n+ ],\n+ {\n+ \"cat1\": {\"shading_facecolor\": \"green\"},\n+ \"cat2\": {\"shading_facecolor\": \"red\"},\n+ },\n+ ),\n+ (\n+ [\n+ {\"categories\": [\"cat1\", \"cat2\"], \"shading_facecolor\": \"red\"},\n+ {\"categories\": \"cat1\", \"shading_edgecolor\": \"green\"},\n+ ],\n+ {\n+ \"cat1\": {\"shading_facecolor\": \"red\", \"shading_edgecolor\": \"green\"},\n+ \"cat2\": {\"shading_facecolor\": \"red\"},\n+ },\n+ ),\n+ ],\n+)\n+def test_categories(kwarg_list, expected_category_styles):\n+ data = generate_counts()\n+ upset = UpSet(data, facecolor=\"blue\")\n+ for kw in kwarg_list:\n+ upset.style_categories(**kw)\n+ actual_category_styles = upset.category_styles\n+ assert actual_category_styles == expected_category_styles\n+\n+\n def test_many_categories():\n # Tests regressions against GH#193\n n_cats = 250\n", "FAIL_TO_PASS": ["upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list0-expected_category_styles0]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list1-expected_category_styles1]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list2-expected_category_styles2]"]}, {"instance_id": "jnothman__upsetplot-264", "base_commit": "da64c81a12f5e6c8283e10a4f6cd7a42ccda1491", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex a00b4d9..37a37ef 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -8,7 +8,10 @@ What's new in version 0.9\n shading of rows in the intersection matrix, and bars in the totals plot.\n (:issue:`261` with thanks to :user:`Marcel Albus `).\n - Ability to disable totals plot with `totals_plot_elements=0`. (:issue:`246`)\n+- Ability to set totals y axis label (:issue:`243`)\n - Added ``max_subset_rank`` to get only n most populous subsets. (:issue:`253`)\n+- Added support for ``min_subset_size`` and ``max_subset_size`` specified as\n+ percentage. (:issue:`264`)\n \n What's new in version 0.8\n -------------------------\ndiff --git a/upsetplot/plotting.py b/upsetplot/plotting.py\nindex e2f50bd..3d5630f 100644\n--- a/upsetplot/plotting.py\n+++ b/upsetplot/plotting.py\n@@ -191,17 +191,27 @@ class UpSet:\n If `subset_size='sum'` or `'auto'`, then the intersection size is the\n sum of the specified field in the `data` DataFrame. If a Series, only\n None is supported and its value is summed.\n- min_subset_size : int, optional\n+ min_subset_size : int or \"number%\", optional\n Minimum size of a subset to be shown in the plot. All subsets with\n a size smaller than this threshold will be omitted from plotting.\n+ This may be specified as a percentage\n+ using a string, like \"50%\".\n Size may be a sum of values, see `subset_size`.\n \n .. versionadded:: 0.5\n- max_subset_size : int, optional\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n+ max_subset_size : int or \"number%\", optional\n Maximum size of a subset to be shown in the plot. All subsets with\n a size greater than this threshold will be omitted from plotting.\n+ This may be specified as a percentage\n+ using a string, like \"50%\".\n \n .. versionadded:: 0.5\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n max_subset_rank : int, optional\n Limit to the top N ranked subsets in descending order of size.\n All tied subsets are included.\n@@ -379,10 +389,18 @@ class UpSet:\n absent : str or list of str, optional\n Category or categories that must not be present in subsets for\n styling.\n- min_subset_size : int, optional\n+ min_subset_size : int or \"number%\", optional\n Minimum size of a subset to be styled.\n- max_subset_size : int, optional\n+ This may be specified as a percentage using a string, like \"50%\".\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n+ max_subset_size : int or \"number%\", optional\n Maximum size of a subset to be styled.\n+ This may be specified as a percentage using a string, like \"50%\".\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n max_subset_rank : int, optional\n Limit to the top N ranked subsets in descending order of size.\n All tied subsets are included.\ndiff --git a/upsetplot/reformat.py b/upsetplot/reformat.py\nindex 821a359..5853729 100644\n--- a/upsetplot/reformat.py\n+++ b/upsetplot/reformat.py\n@@ -93,6 +93,19 @@ def _scalar_to_list(val):\n return val\n \n \n+def _check_percent(value, agg):\n+ if not isinstance(value, str):\n+ return value\n+ try:\n+ if value.endswith(\"%\") and 0 <= float(value[:-1]) <= 100:\n+ return float(value[:-1]) / 100 * agg.sum()\n+ except ValueError:\n+ pass\n+ raise ValueError(\n+ f\"String value must be formatted as percentage between 0 and 100. Got {value}\"\n+ )\n+\n+\n def _get_subset_mask(\n agg,\n min_subset_size,\n@@ -104,6 +117,8 @@ def _get_subset_mask(\n absent,\n ):\n \"\"\"Get a mask over subsets based on size, degree or category presence\"\"\"\n+ min_subset_size = _check_percent(min_subset_size, agg)\n+ max_subset_size = _check_percent(max_subset_size, agg)\n subset_mask = True\n if min_subset_size is not None:\n subset_mask = np.logical_and(subset_mask, agg >= min_subset_size)\n@@ -235,13 +250,20 @@ def query(\n absent : str or list of str, optional\n Category or categories that must not be present in subsets for\n styling.\n- min_subset_size : int, optional\n+ min_subset_size : int or \"number%\", optional\n Minimum size of a subset to be reported. All subsets with\n a size smaller than this threshold will be omitted from\n- category_totals and data.\n+ category_totals and data. This may be specified as a percentage\n+ using a string, like \"50%\".\n Size may be a sum of values, see `subset_size`.\n- max_subset_size : int, optional\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n+ max_subset_size : int or \"number%\", optional\n Maximum size of a subset to be reported.\n+\n+ .. versionchanged:: 0.9\n+ Support percentages\n max_subset_rank : int, optional\n Limit to the top N ranked subsets in descending order of size.\n All tied subsets are included.\n", "test_patch": "diff --git a/upsetplot/tests/test_upsetplot.py b/upsetplot/tests/test_upsetplot.py\nindex d96b42d..3c33dea 100644\n--- a/upsetplot/tests/test_upsetplot.py\n+++ b/upsetplot/tests/test_upsetplot.py\n@@ -768,6 +768,13 @@ def test_index_must_be_bool(x):\n (True, True, True): 990,\n },\n ),\n+ (\n+ {\"min_subset_size\": \"15%\", \"max_subset_size\": \"30.1%\"},\n+ {\n+ (True, False, False): 884,\n+ (True, True, True): 990,\n+ },\n+ ),\n (\n {\"min_degree\": 2},\n {\n@@ -853,6 +860,22 @@ def test_filter_subsets_max_subset_rank_tie():\n assert cur.shape[0] == full.shape[0]\n \n \n+@pytest.mark.parametrize(\n+ \"value\",\n+ [\n+ \"1\",\n+ \"-1%\",\n+ \"1%%\",\n+ \"%1\",\n+ \"hello\",\n+ ],\n+)\n+def test_bad_percentages(value):\n+ data = generate_samples(seed=0, n_samples=5, n_categories=3)\n+ with pytest.raises(ValueError, match=\"percentage\"):\n+ UpSet(data, min_subset_size=value)\n+\n+\n @pytest.mark.parametrize(\n \"x\",\n [\n", "FAIL_TO_PASS": ["upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[-1%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1%%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[%1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[hello]"]}], "all_FAIL_TO_PASS": ["upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list0-expected_category_styles0]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list1-expected_category_styles1]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list2-expected_category_styles2]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[-1%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1%%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[%1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[hello]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "robotpy__cxxheaderparser-106_x2", "level": 2, "source": "swerebenchv2", "repo": "robotpy/cxxheaderparser", "image": "swerebenchv2/robotpy-cxxheaderparser:106-d8f8bd0", "base_commit": "d8f8bd05c7b7d1bb3408207564f7734564edd19f", "num_bugs": 2, "bugs": [{"instance_id": "robotpy__cxxheaderparser-106", "base_commit": "d8f8bd05c7b7d1bb3408207564f7734564edd19f", "gold_patch": "diff --git a/cxxheaderparser/parser.py b/cxxheaderparser/parser.py\nindex d633e2a..8a51e81 100644\n--- a/cxxheaderparser/parser.py\n+++ b/cxxheaderparser/parser.py\n@@ -1937,6 +1937,11 @@ class CxxParser:\n if self.lex.token_if(\"{\"):\n self._discard_contents(\"{\", \"}\")\n fn.has_body = True\n+ elif self.lex.token_if(\"=\"):\n+ if self.lex.token_if_val(\"delete\"):\n+ fn.deleted = True\n+ else:\n+ raise self._parse_error(None, \"expected 'delete\")\n \n def _parse_method_end(self, method: Method) -> None:\n \"\"\"\ndiff --git a/cxxheaderparser/types.py b/cxxheaderparser/types.py\nindex 59169fc..ea768b6 100644\n--- a/cxxheaderparser/types.py\n+++ b/cxxheaderparser/types.py\n@@ -696,6 +696,7 @@ class Function:\n extern: typing.Union[bool, str] = False\n static: bool = False\n inline: bool = False\n+ deleted: bool = False\n \n #: If true, the body of the function is present\n has_body: bool = False\n@@ -764,7 +765,6 @@ class Method(Function):\n constructor: bool = False\n explicit: bool = False\n default: bool = False\n- deleted: bool = False\n \n destructor: bool = False\n \n", "test_patch": "diff --git a/tests/test_fn.py b/tests/test_fn.py\nindex 4f67a41..34734d6 100644\n--- a/tests/test_fn.py\n+++ b/tests/test_fn.py\n@@ -1313,3 +1313,25 @@ def test_msvc_inline() -> None:\n ]\n )\n )\n+\n+\n+def test_deleted_function() -> None:\n+ content = \"\"\"\n+ void trim() = delete;\n+ \"\"\"\n+ data = parse_string(content, cleandoc=True)\n+\n+ assert data == ParsedData(\n+ namespace=NamespaceScope(\n+ functions=[\n+ Function(\n+ return_type=Type(\n+ typename=PQName(segments=[FundamentalSpecifier(name=\"void\")])\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"trim\")]),\n+ parameters=[],\n+ deleted=True,\n+ )\n+ ]\n+ )\n+ )\n", "FAIL_TO_PASS": ["tests/test_fn.py::test_deleted_function"]}, {"instance_id": "robotpy__cxxheaderparser-108", "base_commit": "5ed4baf63c000259f671fc86cba152f2dada98b0", "gold_patch": "diff --git a/cxxheaderparser/parser.py b/cxxheaderparser/parser.py\nindex 8a51e81..45f7fb6 100644\n--- a/cxxheaderparser/parser.py\n+++ b/cxxheaderparser/parser.py\n@@ -719,11 +719,7 @@ class CxxParser:\n args.append(TemplateArgument(dtype, param_pack))\n else:\n # special case for sizeof...(thing)\n- if (\n- param_pack\n- and len(val.tokens) == 1\n- and val.tokens[0].value == \"sizeof\"\n- ):\n+ if param_pack and val.tokens[-1].value == \"sizeof\":\n val.tokens.append(Token(\"...\", \"ELLIPSIS\"))\n tok = self._next_token_must_be(\"(\")\n raw_toks = self._consume_balanced_tokens(tok)\n", "test_patch": "diff --git a/tests/test_template.py b/tests/test_template.py\nindex cee092d..2a13b66 100644\n--- a/tests/test_template.py\n+++ b/tests/test_template.py\n@@ -2352,3 +2352,68 @@ def test_sizeof_pack() -> None:\n ]\n )\n )\n+\n+\n+def test_deduction_sizeof_pack() -> None:\n+ content = \"\"\"\n+ template \n+ SwerveDriveKinematics(ModuleTranslation, ModuleTranslations...)\n+ -> SwerveDriveKinematics<1 + sizeof...(ModuleTranslations)>;\n+ \"\"\"\n+ data = parse_string(content, cleandoc=True)\n+\n+ assert data == ParsedData(\n+ namespace=NamespaceScope(\n+ deduction_guides=[\n+ DeductionGuide(\n+ result_type=Type(\n+ typename=PQName(\n+ segments=[\n+ NameSpecifier(\n+ name=\"SwerveDriveKinematics\",\n+ specialization=TemplateSpecialization(\n+ args=[\n+ TemplateArgument(\n+ arg=Value(\n+ tokens=[\n+ Token(value=\"1\"),\n+ Token(value=\"+\"),\n+ Token(value=\"sizeof\"),\n+ Token(value=\"...\"),\n+ Token(value=\"(\"),\n+ Token(\n+ value=\"ModuleTranslations\"\n+ ),\n+ Token(value=\")\"),\n+ ]\n+ ),\n+ param_pack=True,\n+ )\n+ ]\n+ ),\n+ )\n+ ]\n+ )\n+ ),\n+ name=PQName(segments=[NameSpecifier(name=\"SwerveDriveKinematics\")]),\n+ parameters=[\n+ Parameter(\n+ type=Type(\n+ typename=PQName(\n+ segments=[NameSpecifier(name=\"ModuleTranslation\")]\n+ )\n+ )\n+ ),\n+ Parameter(\n+ type=Type(\n+ typename=PQName(\n+ segments=[NameSpecifier(name=\"ModuleTranslations\")]\n+ )\n+ ),\n+ param_pack=True,\n+ ),\n+ ],\n+ )\n+ ]\n+ )\n+ )\n", "FAIL_TO_PASS": ["tests/test_template.py::test_deduction_sizeof_pack"]}], "all_FAIL_TO_PASS": ["tests/test_fn.py::test_deleted_function", "tests/test_template.py::test_deduction_sizeof_pack"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getmoto__moto-5853_x2", "level": 2, "source": "swerebenchv2", "repo": "getmoto/moto", "image": "swerebenchv2/getmoto-moto:5853-ba78420", "base_commit": "ba784203142a4e8a4e1c3e34987a29c159e3c231", "num_bugs": 2, "bugs": [{"instance_id": "getmoto__moto-5853", "base_commit": "ba784203142a4e8a4e1c3e34987a29c159e3c231", "gold_patch": "diff --git a/moto/dynamodb/parsing/key_condition_expression.py b/moto/dynamodb/parsing/key_condition_expression.py\nindex cb9953450..3bdbaa7e1 100644\n--- a/moto/dynamodb/parsing/key_condition_expression.py\n+++ b/moto/dynamodb/parsing/key_condition_expression.py\n@@ -1,70 +1,6 @@\n from enum import Enum\n from moto.dynamodb.exceptions import MockValidationException\n-\n-\n-class KeyConditionExpressionTokenizer:\n- \"\"\"\n- Tokenizer for a KeyConditionExpression. Should be used as an iterator.\n- The final character to be returned will be an empty string, to notify the caller that we've reached the end.\n- \"\"\"\n-\n- def __init__(self, expression):\n- self.expression = expression\n- self.token_pos = 0\n-\n- def __iter__(self):\n- self.token_pos = 0\n- return self\n-\n- def is_eof(self):\n- return self.peek() == \"\"\n-\n- def peek(self):\n- \"\"\"\n- Peek the next character without changing the position\n- \"\"\"\n- try:\n- return self.expression[self.token_pos]\n- except IndexError:\n- return \"\"\n-\n- def __next__(self):\n- \"\"\"\n- Returns the next character, or an empty string if we've reached the end of the string.\n- Calling this method again will result in a StopIterator\n- \"\"\"\n- try:\n- result = self.expression[self.token_pos]\n- self.token_pos += 1\n- return result\n- except IndexError:\n- if self.token_pos == len(self.expression):\n- self.token_pos += 1\n- return \"\"\n- raise StopIteration\n-\n- def skip_characters(self, phrase, case_sensitive=False) -> None:\n- \"\"\"\n- Skip the characters in the supplied phrase.\n- If any other character is encountered instead, this will fail.\n- If we've already reached the end of the iterator, this will fail.\n- \"\"\"\n- for ch in phrase:\n- if case_sensitive:\n- assert self.expression[self.token_pos] == ch\n- else:\n- assert self.expression[self.token_pos] in [ch.lower(), ch.upper()]\n- self.token_pos += 1\n-\n- def skip_white_space(self):\n- \"\"\"\n- Skip the any whitespace characters that are coming up\n- \"\"\"\n- try:\n- while self.peek() == \" \":\n- self.token_pos += 1\n- except IndexError:\n- pass\n+from moto.utilities.tokenizer import GenericTokenizer\n \n \n class EXPRESSION_STAGES(Enum):\n@@ -100,7 +36,7 @@ def parse_expression(\n key_name = comparison = None\n key_values = []\n results = []\n- tokenizer = KeyConditionExpressionTokenizer(key_condition_expression)\n+ tokenizer = GenericTokenizer(key_condition_expression)\n for crnt_char in tokenizer:\n if crnt_char == \" \":\n if current_stage == EXPRESSION_STAGES.INITIAL_STAGE:\ndiff --git a/moto/ses/models.py b/moto/ses/models.py\nindex 7227abe12..27e1e5fef 100644\n--- a/moto/ses/models.py\n+++ b/moto/ses/models.py\n@@ -1,4 +1,3 @@\n-import re\n import json\n import email\n import datetime\n@@ -23,9 +22,9 @@ from .exceptions import (\n RuleSetNameAlreadyExists,\n RuleSetDoesNotExist,\n RuleAlreadyExists,\n- MissingRenderingAttributeException,\n ConfigurationSetAlreadyExists,\n )\n+from .template import parse_template\n from .utils import get_random_message_id, is_valid_address\n from .feedback import COMMON_MAIL, BOUNCE, COMPLAINT, DELIVERY\n \n@@ -106,17 +105,6 @@ class SESQuota(BaseModel):\n return self.sent\n \n \n-def are_all_variables_present(template, template_data):\n- subject_part = template[\"subject_part\"]\n- text_part = template[\"text_part\"]\n- html_part = template[\"html_part\"]\n-\n- for var in re.findall(\"{{(.+?)}}\", subject_part + text_part + html_part):\n- if not template_data.get(var):\n- return var, False\n- return None, True\n-\n-\n class SESBackend(BaseBackend):\n \"\"\"\n Responsible for mocking calls to SES.\n@@ -469,18 +457,13 @@ class SESBackend(BaseBackend):\n \"Template rendering data is invalid\"\n )\n \n- var, are_variables_present = are_all_variables_present(template, template_data)\n- if not are_variables_present:\n- raise MissingRenderingAttributeException(var)\n-\n subject_part = template[\"subject_part\"]\n text_part = template[\"text_part\"]\n html_part = template[\"html_part\"]\n \n- for key, value in template_data.items():\n- subject_part = str.replace(str(subject_part), \"{{\" + key + \"}}\", value)\n- text_part = str.replace(str(text_part), \"{{\" + key + \"}}\", value)\n- html_part = str.replace(str(html_part), \"{{\" + key + \"}}\", value)\n+ subject_part = parse_template(str(subject_part), template_data)\n+ text_part = parse_template(str(text_part), template_data)\n+ html_part = parse_template(str(html_part), template_data)\n \n email_obj = MIMEMultipart(\"alternative\")\n \ndiff --git a/moto/ses/template.py b/moto/ses/template.py\nnew file mode 100644\nindex 000000000..ec34cd19c\n--- /dev/null\n+++ b/moto/ses/template.py\n@@ -0,0 +1,45 @@\n+from .exceptions import MissingRenderingAttributeException\n+from moto.utilities.tokenizer import GenericTokenizer\n+\n+\n+def parse_template(template, template_data, tokenizer=None, until=None):\n+ tokenizer = tokenizer or GenericTokenizer(template)\n+ state = \"\"\n+ parsed = \"\"\n+ var_name = \"\"\n+ for char in tokenizer:\n+ if until is not None and (char + tokenizer.peek(len(until) - 1)) == until:\n+ return parsed\n+ if char == \"{\":\n+ tokenizer.skip_characters(\"{\")\n+ tokenizer.skip_white_space()\n+ if tokenizer.peek() == \"#\":\n+ state = \"LOOP\"\n+ tokenizer.skip_characters(\"#each\")\n+ tokenizer.skip_white_space()\n+ else:\n+ state = \"VAR\"\n+ continue\n+ if char == \"}\":\n+ if state in [\"LOOP\", \"VAR\"]:\n+ tokenizer.skip_characters(\"}\")\n+ if state == \"VAR\":\n+ if template_data.get(var_name) is None:\n+ raise MissingRenderingAttributeException(var_name)\n+ parsed += template_data.get(var_name)\n+ else:\n+ current_position = tokenizer.token_pos\n+ for item in template_data.get(var_name, []):\n+ tokenizer.token_pos = current_position\n+ parsed += parse_template(\n+ template, item, tokenizer, until=\"{{/each}}\"\n+ )\n+ tokenizer.skip_characters(\"{/each}}\")\n+ var_name = \"\"\n+ state = \"\"\n+ continue\n+ if state in [\"LOOP\", \"VAR\"]:\n+ var_name += char\n+ continue\n+ parsed += char\n+ return parsed\ndiff --git a/moto/utilities/tokenizer.py b/moto/utilities/tokenizer.py\nnew file mode 100644\nindex 000000000..a6e76dc7f\n--- /dev/null\n+++ b/moto/utilities/tokenizer.py\n@@ -0,0 +1,62 @@\n+class GenericTokenizer:\n+ \"\"\"\n+ Tokenizer for a KeyConditionExpression. Should be used as an iterator.\n+ The final character to be returned will be an empty string, to notify the caller that we've reached the end.\n+ \"\"\"\n+\n+ def __init__(self, expression):\n+ self.expression = expression\n+ self.token_pos = 0\n+\n+ def __iter__(self):\n+ return self\n+\n+ def is_eof(self):\n+ return self.peek() == \"\"\n+\n+ def peek(self, length=1):\n+ \"\"\"\n+ Peek the next character without changing the position\n+ \"\"\"\n+ try:\n+ return self.expression[self.token_pos : self.token_pos + length]\n+ except IndexError:\n+ return \"\"\n+\n+ def __next__(self):\n+ \"\"\"\n+ Returns the next character, or an empty string if we've reached the end of the string.\n+ Calling this method again will result in a StopIterator\n+ \"\"\"\n+ try:\n+ result = self.expression[self.token_pos]\n+ self.token_pos += 1\n+ return result\n+ except IndexError:\n+ if self.token_pos == len(self.expression):\n+ self.token_pos += 1\n+ return \"\"\n+ raise StopIteration\n+\n+ def skip_characters(self, phrase, case_sensitive=False) -> None:\n+ \"\"\"\n+ Skip the characters in the supplied phrase.\n+ If any other character is encountered instead, this will fail.\n+ If we've already reached the end of the iterator, this will fail.\n+ \"\"\"\n+ for ch in phrase:\n+ if case_sensitive:\n+ assert self.expression[self.token_pos] == ch\n+ else:\n+ assert self.expression[self.token_pos] in [ch.lower(), ch.upper()]\n+ self.token_pos += 1\n+\n+ def skip_white_space(self):\n+ \"\"\"\n+ Skip any whitespace characters that are coming up\n+ \"\"\"\n+ try:\n+ while self.peek() == \" \":\n+ self.token_pos += 1\n+ except IndexError:\n+ pass\n", "test_patch": "diff --git a/tests/test_ses/test_ses_boto3.py b/tests/test_ses/test_ses_boto3.py\nindex c2c27cdb9..0ca55c7f8 100644\n--- a/tests/test_ses/test_ses_boto3.py\n+++ b/tests/test_ses/test_ses_boto3.py\n@@ -1268,6 +1268,35 @@ def test_render_template():\n )\n \n \n+@mock_ses\n+def test_render_template__with_foreach():\n+ conn = boto3.client(\"ses\", region_name=\"us-east-1\")\n+\n+ kwargs = dict(\n+ TemplateName=\"MTT\",\n+ TemplateData=json.dumps(\n+ {\n+ \"items\": [\n+ {\"type\": \"dog\", \"name\": \"bobby\"},\n+ {\"type\": \"cat\", \"name\": \"pedro\"},\n+ ]\n+ }\n+ ),\n+ )\n+\n+ conn.create_template(\n+ Template={\n+ \"TemplateName\": \"MTT\",\n+ \"SubjectPart\": \"..\",\n+ \"TextPart\": \"..\",\n+ \"HtmlPart\": \"{{#each items}} {{name}} is a {{type}}, {{/each}}\",\n+ }\n+ )\n+ result = conn.test_render_template(**kwargs)\n+ result[\"RenderedTemplate\"].should.contain(\"bobby is a dog\")\n+ result[\"RenderedTemplate\"].should.contain(\"pedro is a cat\")\n+\n+\n @mock_ses\n def test_update_ses_template():\n conn = boto3.client(\"ses\", region_name=\"us-east-1\")\ndiff --git a/tests/test_ses/test_templating.py b/tests/test_ses/test_templating.py\nnew file mode 100644\nindex 000000000..0883013b0\n--- /dev/null\n+++ b/tests/test_ses/test_templating.py\n@@ -0,0 +1,26 @@\n+from moto.ses.template import parse_template\n+import sure # noqa # pylint: disable=unused-import\n+\n+\n+def test_template_without_args():\n+ parse_template(\"some template\", template_data={}).should.equal(\"some template\")\n+\n+\n+def test_template_with_simple_arg():\n+ t = \"Dear {{name}},\"\n+ parse_template(t, template_data={\"name\": \"John\"}).should.equal(\"Dear John,\")\n+\n+\n+def test_template_with_foreach():\n+ t = \"List:{{#each l}} - {{obj}}{{/each}} and other things\"\n+ kwargs = {\"l\": [{\"obj\": \"it1\"}, {\"obj\": \"it2\"}]}\n+ parse_template(t, kwargs).should.equal(\"List: - it1 - it2 and other things\")\n+\n+\n+def test_template_with_multiple_foreach():\n+ t = \"{{#each l}} - {{obj}}{{/each}} and list 2 {{#each l2}} {{o1}} {{o2}} {{/each}}\"\n+ kwargs = {\n+ \"l\": [{\"obj\": \"it1\"}, {\"obj\": \"it2\"}],\n+ \"l2\": [{\"o1\": \"ob1\", \"o2\": \"ob2\"}, {\"o1\": \"oc1\", \"o2\": \"oc2\"}],\n+ }\n+ parse_template(t, kwargs).should.equal(\" - it1 - it2 and list 2 ob1 ob2 oc1 oc2 \")\n", "FAIL_TO_PASS": ["tests/test_ses/test_ses_boto3.py::test_verify_email_identity", "tests/test_ses/test_ses_boto3.py::test_verify_email_identity_idempotency", "tests/test_ses/test_ses_boto3.py::test_verify_email_address", "tests/test_ses/test_ses_boto3.py::test_domain_verify", "tests/test_ses/test_ses_boto3.py::test_delete_identity", "tests/test_ses/test_ses_boto3.py::test_send_email", "tests/test_ses/test_ses_boto3.py::test_send_email_when_verify_source", "tests/test_ses/test_ses_boto3.py::test_send_unverified_email_with_chevrons", "tests/test_ses/test_ses_boto3.py::test_send_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_bulk_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_html_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_validate_domain", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source_or_from", "tests/test_ses/test_ses_boto3.py::test_send_email_notification_with_encoded_sender", "tests/test_ses/test_ses_boto3.py::test_create_configuration_set", "tests/test_ses/test_ses_boto3.py::test_describe_configuration_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set_with_rules", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule_actions", "tests/test_ses/test_ses_boto3.py::test_create_ses_template", "tests/test_ses/test_ses_boto3.py::test_render_template", "tests/test_ses/test_ses_boto3.py::test_render_template__with_foreach", "tests/test_ses/test_ses_boto3.py::test_update_ses_template", "tests/test_ses/test_ses_boto3.py::test_domains_are_case_insensitive", "tests/test_ses/test_ses_boto3.py::test_get_send_statistics", "tests/test_ses/test_ses_boto3.py::test_set_identity_mail_from_domain", "tests/test_ses/test_ses_boto3.py::test_get_identity_mail_from_domain_attributes", "tests/test_ses/test_ses_boto3.py::test_get_identity_verification_attributes", "tests/test_ses/test_templating.py::test_template_without_args", "tests/test_ses/test_templating.py::test_template_with_simple_arg", "tests/test_ses/test_templating.py::test_template_with_foreach", "tests/test_ses/test_templating.py::test_template_with_multiple_foreach"]}, {"instance_id": "getmoto__moto-5862", "base_commit": "c81bd9a1aa93f2f7da9de3bdad27e0f4173b1054", "gold_patch": "diff --git a/moto/ses/models.py b/moto/ses/models.py\nindex 27e1e5fef..dd9c94ae6 100644\n--- a/moto/ses/models.py\n+++ b/moto/ses/models.py\n@@ -115,7 +115,7 @@ class SESBackend(BaseBackend):\n \n from moto.core import DEFAULT_ACCOUNT_ID\n from moto.ses import ses_backends\n- ses_backend = ses_backends[DEFAULT_ACCOUNT_ID][\"global\"]\n+ ses_backend = ses_backends[DEFAULT_ACCOUNT_ID][region]\n messages = ses_backend.sent_messages # sent_messages is a List of Message objects\n \n Note that, as this is an internal API, the exact format may differ per versions.\n@@ -585,6 +585,4 @@ class SESBackend(BaseBackend):\n return attributes_by_identity\n \n \n-ses_backends: Mapping[str, SESBackend] = BackendDict(\n- SESBackend, \"ses\", use_boto3_regions=False, additional_regions=[\"global\"]\n-)\n+ses_backends: Mapping[str, SESBackend] = BackendDict(SESBackend, \"ses\")\ndiff --git a/moto/ses/responses.py b/moto/ses/responses.py\nindex 016ff3fc0..f36aa7601 100644\n--- a/moto/ses/responses.py\n+++ b/moto/ses/responses.py\n@@ -11,7 +11,7 @@ class EmailResponse(BaseResponse):\n \n @property\n def backend(self):\n- return ses_backends[self.current_account][\"global\"]\n+ return ses_backends[self.current_account][self.region]\n \n def verify_email_identity(self):\n address = self.querystring.get(\"EmailAddress\")[0]\n", "test_patch": "diff --git a/tests/test_ses/test_ses_boto3.py b/tests/test_ses/test_ses_boto3.py\nindex 0ca55c7f8..251c3d056 100644\n--- a/tests/test_ses/test_ses_boto3.py\n+++ b/tests/test_ses/test_ses_boto3.py\n@@ -19,6 +19,15 @@ def test_verify_email_identity():\n address.should.equal(\"test@example.com\")\n \n \n+@mock_ses\n+def test_identities_are_region_specific():\n+ us_east = boto3.client(\"ses\", region_name=\"us-east-1\")\n+ us_east.verify_email_identity(EmailAddress=\"test@example.com\")\n+\n+ us_west = boto3.client(\"ses\", region_name=\"us-west-1\")\n+ us_west.list_identities()[\"Identities\"].should.have.length_of(0)\n+\n+\n @mock_ses\n def test_verify_email_identity_idempotency():\n conn = boto3.client(\"ses\", region_name=\"us-east-1\")\n", "FAIL_TO_PASS": ["tests/test_ses/test_ses_boto3.py::test_identities_are_region_specific"]}], "all_FAIL_TO_PASS": ["tests/test_ses/test_ses_boto3.py::test_verify_email_identity", "tests/test_ses/test_ses_boto3.py::test_verify_email_identity_idempotency", "tests/test_ses/test_ses_boto3.py::test_verify_email_address", "tests/test_ses/test_ses_boto3.py::test_domain_verify", "tests/test_ses/test_ses_boto3.py::test_delete_identity", "tests/test_ses/test_ses_boto3.py::test_send_email", "tests/test_ses/test_ses_boto3.py::test_send_email_when_verify_source", "tests/test_ses/test_ses_boto3.py::test_send_unverified_email_with_chevrons", "tests/test_ses/test_ses_boto3.py::test_send_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_bulk_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email", "tests/test_ses/test_ses_boto3.py::test_send_templated_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_html_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_validate_domain", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_invalid_address", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source", "tests/test_ses/test_ses_boto3.py::test_send_raw_email_without_source_or_from", "tests/test_ses/test_ses_boto3.py::test_send_email_notification_with_encoded_sender", "tests/test_ses/test_ses_boto3.py::test_create_configuration_set", "tests/test_ses/test_ses_boto3.py::test_describe_configuration_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_create_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule_set_with_rules", "tests/test_ses/test_ses_boto3.py::test_describe_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule", "tests/test_ses/test_ses_boto3.py::test_update_receipt_rule_actions", "tests/test_ses/test_ses_boto3.py::test_create_ses_template", "tests/test_ses/test_ses_boto3.py::test_render_template", "tests/test_ses/test_ses_boto3.py::test_render_template__with_foreach", "tests/test_ses/test_ses_boto3.py::test_update_ses_template", "tests/test_ses/test_ses_boto3.py::test_domains_are_case_insensitive", "tests/test_ses/test_ses_boto3.py::test_get_send_statistics", "tests/test_ses/test_ses_boto3.py::test_set_identity_mail_from_domain", "tests/test_ses/test_ses_boto3.py::test_get_identity_mail_from_domain_attributes", "tests/test_ses/test_ses_boto3.py::test_get_identity_verification_attributes", "tests/test_ses/test_templating.py::test_template_without_args", "tests/test_ses/test_templating.py::test_template_with_simple_arg", "tests/test_ses/test_templating.py::test_template_with_foreach", "tests/test_ses/test_templating.py::test_template_with_multiple_foreach", "tests/test_ses/test_ses_boto3.py::test_identities_are_region_specific"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pycqa__pyflakes-729_x2", "level": 2, "source": "swerebenchv2", "repo": "PyCQA/pyflakes", "image": "swerebenchv2/pycqa-pyflakes:729-7d6479e", "base_commit": "7d6479e46f8f3e9607c9ef7975cc892db023d413", "num_bugs": 2, "bugs": [{"instance_id": "pycqa__pyflakes-729", "base_commit": "7d6479e46f8f3e9607c9ef7975cc892db023d413", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex ae15621..56fc3ca 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -2265,7 +2265,6 @@ class Checker:\n self.scope[node.name] = prev_definition\n \n def ANNASSIGN(self, node):\n- self.handleNode(node.target, node)\n self.handleAnnotation(node.annotation, node)\n # If the assignment has value, handle the *value* now.\n if node.value:\n@@ -2274,6 +2273,7 @@ class Checker:\n self.handleAnnotation(node.value, node)\n else:\n self.handleNode(node.value, node)\n+ self.handleNode(node.target, node)\n \n def COMPARE(self, node):\n left = node.left\n", "test_patch": "diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py\nindex 3775cd3..d881205 100644\n--- a/pyflakes/test/test_type_annotations.py\n+++ b/pyflakes/test/test_type_annotations.py\n@@ -298,6 +298,11 @@ class TestTypeAnnotations(TestCase):\n a: 'a: \"A\"'\n ''', m.ForwardAnnotationSyntaxError)\n \n+ def test_variable_annotation_references_self_name_undefined(self):\n+ self.flakes(\"\"\"\n+ x: int = x\n+ \"\"\", m.UndefinedName)\n+\n def test_TypeAlias_annotations(self):\n self.flakes(\"\"\"\n from typing_extensions import TypeAlias\n", "FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined"]}, {"instance_id": "pycqa__pyflakes-745", "base_commit": "2c64ae48e2b1984a16cf25d215c9f9d21146426d", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex b87bc88..15b4c2b 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -1068,7 +1068,7 @@ class Checker:\n )\n return handler\n \n- def handleNodeLoad(self, node):\n+ def handleNodeLoad(self, node, parent):\n name = getNodeName(node)\n if not name:\n return\n@@ -1093,7 +1093,6 @@ class Checker:\n continue\n \n if name == 'print' and isinstance(binding, Builtin):\n- parent = self.getParent(node)\n if (isinstance(parent, ast.BinOp) and\n isinstance(parent.op, ast.RShift)):\n self.report(messages.InvalidPrintSyntax, node)\n@@ -1880,7 +1879,7 @@ class Checker:\n \"\"\"\n # Locate the name in locals / function / globals scopes.\n if isinstance(node.ctx, ast.Load):\n- self.handleNodeLoad(node)\n+ self.handleNodeLoad(node, self.getParent(node))\n if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and\n isinstance(node._pyflakes_parent, ast.Call)):\n # we are doing locals() call in current scope\n@@ -2049,7 +2048,7 @@ class Checker:\n self.addBinding(node, ClassDefinition(node.name, node))\n \n def AUGASSIGN(self, node):\n- self.handleNodeLoad(node.target)\n+ self.handleNodeLoad(node.target, node)\n self.handleNode(node.value, node)\n self.handleNode(node.target, node)\n \n", "test_patch": "diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py\nindex b138cf6..ce742a5 100644\n--- a/pyflakes/test/test_other.py\n+++ b/pyflakes/test/test_other.py\n@@ -2052,6 +2052,10 @@ class TestIncompatiblePrintOperator(TestCase):\n self.assertEqual(exc.lineno, 4)\n self.assertEqual(exc.col, 0)\n \n+ def test_print_augmented_assign(self):\n+ # nonsense, but shouldn't crash pyflakes\n+ self.flakes('print += 1')\n+\n def test_print_function_assignment(self):\n \"\"\"\n A valid assignment, tested for catching false positives.\n", "FAIL_TO_PASS": ["pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_augmented_assign"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined", "pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_augmented_assign"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3519_x2", "level": 2, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3519-7a8c5cf", "base_commit": "7a8c5cf8b10e4aaced0cbea17ae1194c00d9205a", "num_bugs": 2, "bugs": [{"instance_id": "openmdao__openmdao-3519", "base_commit": "7a8c5cf8b10e4aaced0cbea17ae1194c00d9205a", "gold_patch": "diff --git a/openmdao/core/system.py b/openmdao/core/system.py\nindex 75035a5e3..cf0a71465 100644\n--- a/openmdao/core/system.py\n+++ b/openmdao/core/system.py\n@@ -25,7 +25,7 @@ from openmdao.utils.mpi import MPI, multi_proc_exception_check\n from openmdao.utils.options_dictionary import OptionsDictionary\n from openmdao.utils.record_util import create_local_meta, check_path, has_match\n from openmdao.utils.units import is_compatible, unit_conversion, simplify_unit\n-from openmdao.utils.variable_table import write_var_table, NA\n+from openmdao.utils.variable_table import write_var_table, write_options_table, NA\n from openmdao.utils.array_utils import evenly_distrib_idxs, shape_to_len, get_tol_violation, \\\n sparsity_diff_viz, get_sparsity_diff_array\n from openmdao.utils.name_maps import name2abs_name, name2abs_names\n@@ -102,6 +102,10 @@ resp_size_checks = {\n }\n resp_types = {'con': 'constraint', 'obj': 'objective'}\n \n+default_options = ['always_opt', 'default_shape', 'derivs_method', 'distributed',\n+ 'run_root_only', 'use_jit', 'assembled_jac_type',\n+ 'auto_order']\n+\n \n class _MatchType(IntEnum):\n \"\"\"\n@@ -4954,6 +4958,104 @@ class System(object, metaclass=SystemMetaclass):\n \n return var_list\n \n+ def list_options(self,\n+ include_default=True,\n+ include_solvers=True,\n+ out_stream=_DEFAULT_OUT_STREAM,\n+ return_format='list'):\n+ \"\"\"\n+ Write a list of output names and other optional information to a specified stream.\n+\n+ Parameters\n+ ----------\n+ include_default : bool\n+ When True, include the built-in openmdao system options. Default is True.\n+ include_solvers : bool\n+ When True, include options from nonlinear_solver and linear_solver.\n+ out_stream : file-like\n+ Where to send human readable output. Default is sys.stdout.\n+ Set to None to suppress.\n+ return_format : str\n+ Indicates the desired format of the return value. Can have value of 'list' or 'dict'.\n+ If 'list', the return value is a list of tuples of the form: (pathname, system options\n+ , nonlinear solver options, linear solver options)\n+ if 'dict', the return value is a dictionary with the pathname as key, and a dictionary\n+ as the value. The dictionary contains 'options', 'nonlinear_solver', and\n+ 'linear_solver' keys, each of which isa dictionary of options.\n+\n+ Returns\n+ -------\n+ list of tuple\n+ List of tuples, one for each subsystem sorted by execution order. Each tuple contains\n+ the pathname string, a dictionary of system options, a dictionary of nonlinear solver\n+ options (only if include_solvers is True) or None, and a dictionary of nonlinear solver\n+ options (only if include_solvers is True) or None.\n+ \"\"\"\n+ name = self.pathname\n+\n+ opt_list = []\n+ opts = {}\n+ nl_opts = None\n+ ln_opts = None\n+ for opt_name, opt_value in self.options.items():\n+\n+ if not include_default and opt_name in default_options:\n+ continue\n+\n+ opt_meta = self.options._dict[opt_name]\n+\n+ if opt_meta['recordable']:\n+ opts[opt_name] = opt_value\n+\n+ if include_solvers:\n+ nl = self.nonlinear_solver\n+ if nl is not None:\n+ nl_opts = {}\n+ for opt_name, opt_value in nl.options.items():\n+\n+ opt_meta = nl.options._dict[opt_name]\n+\n+ if opt_meta['recordable']:\n+ nl_opts[opt_name] = opt_value\n+\n+ ln = self.linear_solver\n+ if ln is not None:\n+ ln_opts = {}\n+ for opt_name, opt_value in ln.options.items():\n+\n+ opt_meta = ln.options._dict[opt_name]\n+\n+ if opt_meta['recordable']:\n+ ln_opts[opt_name] = opt_value\n+\n+ opt_list.append((name, opts, nl_opts, ln_opts))\n+\n+ # For components, self._subsystems_allprocs is empty.\n+ if self._subsystems_allprocs:\n+ for subsys in self.system_iter(include_self=False, recurse=True):\n+\n+ if subsys.pathname != '_auto_ivc':\n+ sub_opts = subsys.list_options(out_stream=None,\n+ include_solvers=include_solvers,\n+ include_default=include_default)\n+ opt_list.extend(sub_opts)\n+\n+ write_options_table(self.pathname, opt_list, out_stream=out_stream)\n+\n+ if return_format == 'dict':\n+ opt_dict = {}\n+ for name, opts, nl_opts, ln_opts in opt_list:\n+ opt_dict[name] = {\n+ 'options': opts,\n+ }\n+ if include_solvers:\n+ opt_dict[name]['nonlinear_solver'] = nl_opts\n+ opt_dict[name]['linear_solver'] = ln_opts\n+\n+ return opt_dict\n+\n+ return opt_list\n+\n def run_solve_nonlinear(self):\n \"\"\"\n Compute outputs.\ndiff --git a/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb b/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb\nindex 6f7eabc25..c1c31e9c6 100644\n--- a/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb\n+++ b/openmdao/docs/openmdao_book/features/core_features/options/options.ipynb\n@@ -774,6 +774,24 @@\n \"assert_near_equal(expected, c3y)\"\n ]\n },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"## Listing Options\\n\",\n+ \"\\n\",\n+ \"You can list all options in a `Group` or `Component` and their associated linear and nonlinear solvers by using the `list_options` method. This will return the options in a list of tuples of (system pathname, system dictionary of options, nonlinear_solver dictionary of options, linear_solver dictionary of options), and will also print them to stdout or any output stream that you request.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"myoptions = p.model.list_options(include_solvers=True, include_default=True)\"\n+ ]\n+ },\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\ndiff --git a/openmdao/utils/variable_table.py b/openmdao/utils/variable_table.py\nindex d7e79f505..0bd6d8925 100644\n--- a/openmdao/utils/variable_table.py\n+++ b/openmdao/utils/variable_table.py\n@@ -308,3 +308,124 @@ def _write_variable(out_stream, row, column_names, var_dict, print_arrays):\n indented_lines = [(left_column_width + indent_inc) * ' ' +\n s for s in out_str.splitlines()]\n out_stream.write('\\n'.join(indented_lines) + '\\n')\n+\n+\n+def write_options_table(pathname, opt_list, out_stream=_DEFAULT_OUT_STREAM):\n+ \"\"\"\n+ Write table of options and values for a model.\n+\n+ For non-serializable datatypes, only the type is printed.\n+\n+ Parameters\n+ ----------\n+ pathname : str\n+ Pathname to be printed. If None, defaults to 'model'.\n+ opt_list : list\n+ List of systems options dictionaries.\n+ out_stream : file-like object\n+ Where to send human readable output.\n+ \"\"\"\n+ if out_stream is None:\n+ return\n+\n+ if out_stream is _DEFAULT_OUT_STREAM:\n+ out_stream = sys.stdout\n+ elif not isinstance(out_stream, TextIOBase):\n+ raise TypeError(\"Invalid output stream specified for 'out_stream'.\")\n+\n+ count = len(opt_list)\n+\n+ # Write header\n+ pathname = pathname if pathname else 'model'\n+\n+ header = f\"Options for {count} components in '{pathname}\"\n+\n+ out_stream.write(header + '\\n')\n+\n+ if not count:\n+ out_stream.write('\\n\\n')\n+ return\n+\n+ column_names = ['option name', 'option value']\n+\n+ # Find with width of the first column in the table\n+ # Need to look through all the possible varnames to find the max width\n+ max_varname_len = len(column_names[0])\n+ for sys_name, opt_dict, nl_dict, ln_dict in opt_list:\n+ stem_size = indent_inc * len(sys_name.split('.'))\n+ max_varname_len = max(max_varname_len, stem_size)\n+ for opt_name in opt_dict:\n+ total_len = stem_size + len(opt_name)\n+ max_varname_len = max(max_varname_len, total_len)\n+\n+ if nl_dict is not None:\n+ for opt_name in nl_dict:\n+ total_len = stem_size + len(opt_name) + 2\n+ max_varname_len = max(max_varname_len, total_len)\n+ if ln_dict is not None:\n+ for opt_name in ln_dict:\n+ total_len = stem_size + len(opt_name) + 2\n+ max_varname_len = max(max_varname_len, total_len)\n+\n+ # Write out the column headers\n+ opt_val_width = 30\n+ column_header = column_names[0] + (max_varname_len - len(column_names[0])) * ' '\n+ column_dashes = max_varname_len * '-'\n+\n+ column_header += column_spacing * ' ' + column_names[1]\n+ column_dashes += column_spacing * ' ' + opt_val_width * '-'\n+\n+ out_stream.write('\\n')\n+ out_stream.write(column_header + '\\n')\n+ out_stream.write(column_dashes + '\\n')\n+\n+ core_types = (int, float, tuple, list, np.ndarray, str, bool)\n+\n+ for sys_path, opt_dict, nl_dict, ln_dict in opt_list:\n+ sys_path_list = sys_path.split('.')\n+ stem_size = indent_inc * len(sys_path_list)\n+ out_stream.write(stem_size * ' ' + sys_path_list[-1] + '\\n')\n+ stem_size += 2\n+\n+ for opt_name, opt_val in opt_dict.items():\n+\n+ if not isinstance(opt_val, core_types):\n+ opt_val = type(opt_val)\n+\n+ row = stem_size * ' ' + opt_name\n+\n+ remaining = max_varname_len - len(row) + column_spacing + 2\n+ row += remaining * ' ' + str(opt_val)\n+ out_stream.write(row + '\\n')\n+\n+ if nl_dict is not None:\n+\n+ out_stream.write(stem_size * ' ' + 'nonlinear_solver' + '\\n')\n+\n+ for opt_name, opt_val in nl_dict.items():\n+\n+ if not isinstance(opt_val, core_types):\n+ opt_val = type(opt_val)\n+\n+ row = (stem_size + 2) * ' ' + opt_name\n+\n+ remaining = max_varname_len - len(row) + column_spacing + 2\n+ row += remaining * ' ' + str(opt_val)\n+ out_stream.write(row + '\\n')\n+\n+ if ln_dict is not None:\n+\n+ out_stream.write(stem_size * ' ' + 'linear_solver' + '\\n')\n+\n+ for opt_name, opt_val in ln_dict.items():\n+\n+ if not isinstance(opt_val, core_types):\n+ opt_val = type(opt_val)\n+\n+ row = (stem_size + 2) * ' ' + opt_name\n+\n+ remaining = max_varname_len - len(row) + column_spacing + 2\n+ row += remaining * ' ' + str(opt_val)\n+ out_stream.write(row + '\\n')\n+\n+ out_stream.write('\\n\\n')\n", "test_patch": "diff --git a/openmdao/core/tests/test_system.py b/openmdao/core/tests/test_system.py\nindex ad008bd13..d152f5b3e 100644\n--- a/openmdao/core/tests/test_system.py\n+++ b/openmdao/core/tests/test_system.py\n@@ -328,6 +328,35 @@ class TestSystem(unittest.TestCase):\n self.assertEqual(sorted([name for name, _ in nonDV_indeps]),\n ['_auto_ivc.v1'])\n \n+ def test_list_options(self):\n+ from openmdao.test_suite.components.sellar_feature import SellarMDA\n+\n+ model = SellarMDA()\n+\n+ prob = Problem(model)\n+ prob.setup()\n+ prob.final_setup()\n+\n+ opt_list = prob.model.list_options(out_stream=None)\n+\n+ self.assertEqual(len(opt_list), 9)\n+ self.assertTrue(opt_list[1][0] == 'cycle')\n+ self.assertTrue(opt_list[1][2]['maxiter'] == 10)\n+ self.assertTrue(opt_list[3][1]['use_jit'] is True)\n+\n+ opt_dict = prob.model.list_options(out_stream=None, return_format='dict')\n+ self.assertTrue(opt_dict['cycle']['nonlinear_solver']['maxiter'] == 10)\n+ self.assertTrue(opt_dict['cycle']['linear_solver']['use_aitken'] is False)\n+ self.assertTrue(opt_dict['cycle']['options']['auto_order'] is False)\n+\n+ opt_list = prob.model.list_options(out_stream=None, include_solvers=False)\n+ opt_list = prob.model.list_options(out_stream=None, include_solvers=False)\n+ self.assertTrue(opt_list[1][2] is None)\n+ self.assertTrue(opt_list[1][3] is None)\n+\n+ opt_list = prob.model.list_options(out_stream=None, include_solvers=False, include_default=False)\n+ self.assertEqual(len(opt_list[1][1]), 0)\n+\n def test_setup_check_group(self):\n \n class CustomGroup(Group):\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_system.py::TestSystem::test_list_options"]}, {"instance_id": "openmdao__openmdao-3522", "base_commit": "97f89e58f032013f7fa7f6a7da45880b45059bd9", "gold_patch": "diff --git a/openmdao/core/problem.py b/openmdao/core/problem.py\nindex a3b496ba0..ad35a6a6d 100644\n--- a/openmdao/core/problem.py\n+++ b/openmdao/core/problem.py\n@@ -492,7 +492,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n \"\"\"\n return self.get_val(name, get_remote=None)\n \n- def get_val(self, name, units=None, indices=None, get_remote=False):\n+ def get_val(self, name, units=None, indices=None, get_remote=False, copy=False):\n \"\"\"\n Get an output/input variable.\n \n@@ -513,6 +513,8 @@ class Problem(object, metaclass=ProblemMetaclass):\n If False, only retrieve the value if it is on the current process, or only the part\n of the value that's on the current process for a distributed variable.\n If None and the variable is remote or distributed, a RuntimeError will be raised.\n+ copy : bool, optional\n+ If True, return a copy of the value. If False, return a reference to the value.\n \n Returns\n -------\n@@ -539,7 +541,10 @@ class Problem(object, metaclass=ProblemMetaclass):\n f\"rank {self.comm.rank}. You can retrieve values from \"\n \"other processes using `get_val(, get_remote=True)`.\")\n \n- return val\n+ if copy:\n+ return deepcopy(val)\n+ else:\n+ return val\n \n def __setitem__(self, name, value):\n \"\"\"\ndiff --git a/openmdao/core/system.py b/openmdao/core/system.py\nindex c75ec7ffa..c656dcb80 100644\n--- a/openmdao/core/system.py\n+++ b/openmdao/core/system.py\n@@ -5,6 +5,7 @@ import hashlib\n import pathlib\n import time\n import functools\n+from copy import deepcopy\n from contextlib import contextmanager\n from collections import defaultdict\n from itertools import chain\n@@ -5544,7 +5545,7 @@ class System(object, metaclass=SystemMetaclass):\n return val\n \n def get_val(self, name, units=None, indices=None, get_remote=False, rank=None,\n- vec_name='nonlinear', kind=None, flat=False, from_src=True):\n+ vec_name='nonlinear', kind=None, flat=False, from_src=True, copy=False):\n \"\"\"\n Get an output/input/residual variable.\n \n@@ -5576,6 +5577,8 @@ class System(object, metaclass=SystemMetaclass):\n If True, return the flattened version of the value.\n from_src : bool\n If True, retrieve value of an input variable from its connected source.\n+ copy : bool, optional\n+ If True, return a copy of the value. If False, return a reference to the value.\n \n Returns\n -------\n@@ -5597,9 +5600,9 @@ class System(object, metaclass=SystemMetaclass):\n else:\n # src is outside of this system so get the value from the model\n caller = self._problem_meta['model_ref']()\n- return caller._get_input_from_src(name, abs_names, conns, units=simp_units,\n- indices=indices, get_remote=get_remote, rank=rank,\n- vec_name=vec_name, flat=flat, scope_sys=self)\n+ val = caller._get_input_from_src(name, abs_names, conns, units=simp_units,\n+ indices=indices, get_remote=get_remote, rank=rank,\n+ vec_name=vec_name, flat=flat, scope_sys=self)\n else:\n val = self._abs_get_val(abs_names[0], get_remote, rank, vec_name, kind, flat)\n \n@@ -5609,7 +5612,10 @@ class System(object, metaclass=SystemMetaclass):\n if units is not None:\n val = self.convert2units(abs_names[0], val, simp_units)\n \n- return val\n+ if copy:\n+ return deepcopy(val)\n+ else:\n+ return val\n \n def _get_cached_val(self, name, abs_names, get_remote=False):\n # We have set and cached already\n", "test_patch": "diff --git a/openmdao/core/tests/test_problem.py b/openmdao/core/tests/test_problem.py\nindex 1fa86e3f6..bb5e1eeba 100644\n--- a/openmdao/core/tests/test_problem.py\n+++ b/openmdao/core/tests/test_problem.py\n@@ -31,6 +31,56 @@ except ImportError:\n \n @use_tempdirs\n class TestProblem(unittest.TestCase):\n+\n+ def test_get_val(self):\n+ class TestComp(om.ExplicitComponent):\n+ def setup(self):\n+ self.add_input('foo', shape=(3,))\n+ self.add_discrete_input('mul', val=1)\n+\n+ self.add_output('bar', shape=(3,))\n+ # add a mutable NumPy array as an output\n+ self.add_discrete_output('obj', val=np.array([1, 'm', [2, 3, 4]], dtype=object))\n+\n+ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n+ outputs['bar'] = discrete_inputs['mul']*inputs['foo']\n+\n+ p = om.Problem()\n+ p.model.add_subsystem('comp', TestComp(), promotes=['*'])\n+ p.setup()\n+\n+ p.set_val('foo', np.array([5., 5., 5.]))\n+ p.set_val('mul', 100)\n+ p.run_model()\n+\n+ foo = p.get_val('foo')\n+ mul = p.get_val('mul')\n+ bar = p.get_val('bar')\n+ obj = p.get_val('obj')\n+\n+ self.assertTrue(np.array_equal(foo, np.array([5., 5., 5.])))\n+ self.assertEqual(mul, 100)\n+ self.assertTrue(np.array_equal(bar, np.array([500., 500., 500.])))\n+\n+ foo_copy = p.get_val('foo', copy=True)\n+ mul_copy = p.get_val('mul', copy=True)\n+ bar_copy = p.get_val('bar', copy=True)\n+ obj_copy = p.get_val('obj', copy=True)\n+\n+ self.assertTrue(np.array_equal(foo_copy, np.array([5., 5., 5.])))\n+ self.assertEqual(mul_copy, 100)\n+ self.assertTrue(np.array_equal(bar_copy, np.array([500., 500., 500.])))\n+\n+ self.assertTrue(id(foo) != id(foo_copy), f\"'foo' is not a copy, {id(foo)=} {id(foo_copy)=}\")\n+ self.assertTrue(id(mul) == id(mul_copy), f\"'mul' is a copy, {id(foo)=} {id(foo_copy)=}\") # mul is a scalar\n+ self.assertTrue(id(bar) != id(bar_copy), f\"'bar' is not a copy, {id(bar)=} {id(bar_copy)=}\")\n+ self.assertTrue(id(obj) != id(obj_copy), f\"'obj' is not a copy, {id(obj)=} {id(obj_copy)=}\")\n+\n+ obj[2][0] = 10\n+ self.assertEqual(obj[2][0], 10)\n+ self.assertEqual(p.get_val('obj')[2][0], 10) # the value in the problem was modified\n+ self.assertEqual(obj_copy[2][0], 2) # the value in the copy was not modified\n+\n def test_simple_component_model_with_units(self):\n class TestComp(om.ExplicitComponent):\n def setup(self):\ndiff --git a/openmdao/core/tests/test_system.py b/openmdao/core/tests/test_system.py\nindex 4f5ad1637..f69348752 100644\n--- a/openmdao/core/tests/test_system.py\n+++ b/openmdao/core/tests/test_system.py\n@@ -13,6 +13,57 @@ from openmdao.utils.file_utils import _get_work_dir\n @use_tempdirs\n class TestSystem(unittest.TestCase):\n \n+ def test_get_val(self):\n+ import openmdao.api as om\n+\n+ class TestComp(om.ExplicitComponent):\n+ def setup(self):\n+ self.add_input('foo', shape=(3,))\n+ self.add_discrete_input('mul', val=1)\n+\n+ self.add_output('bar', shape=(3,))\n+ # add a mutable NumPy array as an output\n+ self.add_discrete_output('obj', val=np.array([1, 'm', [2, 3, 4]], dtype=object))\n+\n+ def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n+ outputs['bar'] = discrete_inputs['mul']*inputs['foo']\n+\n+ p = om.Problem()\n+ comp = p.model.add_subsystem('comp', TestComp(), promotes=['*'])\n+ p.setup()\n+\n+ p.set_val('foo', np.array([5., 5., 5.]))\n+ p.set_val('mul', 100)\n+ p.run_model()\n+\n+ foo = comp.get_val('foo')\n+ mul = comp.get_val('mul')\n+ bar = comp.get_val('bar')\n+ obj = comp.get_val('obj')\n+\n+ self.assertTrue(np.array_equal(foo, np.array([5., 5., 5.])))\n+ self.assertEqual(mul, 100)\n+ self.assertTrue(np.array_equal(bar, np.array([500., 500., 500.])))\n+\n+ foo_copy = comp.get_val('foo', copy=True)\n+ mul_copy = comp.get_val('mul', copy=True)\n+ bar_copy = comp.get_val('bar', copy=True)\n+ obj_copy = comp.get_val('obj', copy=True)\n+\n+ self.assertTrue(np.array_equal(foo_copy, np.array([5., 5., 5.])))\n+ self.assertEqual(mul_copy, 100)\n+ self.assertTrue(np.array_equal(bar_copy, np.array([500., 500., 500.])))\n+\n+ self.assertTrue(id(foo) != id(foo_copy), f\"'foo' is not a copy, {id(foo)=} {id(foo_copy)=}\")\n+ self.assertTrue(id(mul) == id(mul_copy), f\"'mul' is a copy, {id(foo)=} {id(foo_copy)=}\") # mul is a scalar\n+ self.assertTrue(id(bar) != id(bar_copy), f\"'bar' is not a copy, {id(bar)=} {id(bar_copy)=}\")\n+ self.assertTrue(id(obj) != id(obj_copy), f\"'obj' is not a copy, {id(obj)=} {id(obj_copy)=}\")\n+\n+ obj[2][0] = 10\n+ self.assertEqual(obj[2][0], 10)\n+ self.assertEqual(comp.get_val('obj')[2][0], 10) # the value in the system was modified\n+ self.assertEqual(obj_copy[2][0], 2) # the value in the copy was not modified\n+\n def test_vector_context_managers(self):\n g1 = Group()\n g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a'])\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_get_val", "openmdao/core/tests/test_system.py::TestSystem::test_get_val"]}], "all_FAIL_TO_PASS": ["openmdao/core/tests/test_system.py::TestSystem::test_list_options", "openmdao/core/tests/test_problem.py::TestProblem::test_get_val", "openmdao/core/tests/test_system.py::TestSystem::test_get_val"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "python-markdown__markdown-743_x2", "level": 2, "source": "swerebenchv2", "repo": "Python-Markdown/markdown", "image": "swerebenchv2/python-markdown-markdown:743-7c78ac3", "base_commit": "7c78ac347b5dcad2be3d8d18b37ec33c96c1eb0b", "num_bugs": 2, "bugs": [{"instance_id": "python-markdown__markdown-743", "base_commit": "7c78ac347b5dcad2be3d8d18b37ec33c96c1eb0b", "gold_patch": "diff --git a/docs/change_log/release-3.1.md b/docs/change_log/release-3.1.md\nindex c05d70f..0e8e2b1 100644\n--- a/docs/change_log/release-3.1.md\n+++ b/docs/change_log/release-3.1.md\n@@ -35,3 +35,4 @@ The following bug fixes are included in the 3.1 release:\n * Block level elements are defined per instance, not as class attributes\n (#731).\n * Double escaping of block code has been eliminated (#725).\n+* Problems with newlines in references has been fixed (#742).\ndiff --git a/markdown/inlinepatterns.py b/markdown/inlinepatterns.py\nindex 3d3e65f..dc502c2 100644\n--- a/markdown/inlinepatterns.py\n+++ b/markdown/inlinepatterns.py\n@@ -617,7 +617,7 @@ class ImageInlineProcessor(LinkInlineProcessor):\n \n class ReferenceInlineProcessor(LinkInlineProcessor):\n \"\"\" Match to a stored reference and return link element. \"\"\"\n- NEWLINE_CLEANUP_RE = re.compile(r'[ ]?\\n', re.MULTILINE)\n+ NEWLINE_CLEANUP_RE = re.compile(r'\\s+', re.MULTILINE)\n \n RE_LINK = re.compile(r'\\s?\\[([^\\]]*)\\]', re.DOTALL | re.UNICODE)\n \n", "test_patch": "diff --git a/tests/test_syntax/inline/test_links.py b/tests/test_syntax/inline/test_links.py\nindex e147c82..988e041 100644\n--- a/tests/test_syntax/inline/test_links.py\n+++ b/tests/test_syntax/inline/test_links.py\n@@ -134,3 +134,40 @@ class TestAdvancedLinks(TestCase):\n '[title](http://example.com/?a=1&b=2)',\n '

    title

    '\n )\n+\n+ def test_reference_newlines(self):\n+ \"\"\"Test reference id whitespace cleanup.\"\"\"\n+\n+ self.assertMarkdownRenders(\n+ self.dedent(\n+ \"\"\"\n+ Two things:\n+\n+ - I would like to tell you about the [code of\n+ conduct][] we are using in this project.\n+ - Only one in fact.\n+\n+ [code of conduct]: https://github.com/Python-Markdown/markdown/blob/master/CODE_OF_CONDUCT.md\n+ \"\"\"\n+ ),\n+ '

    Two things:

    \\n
      \\n
    • I would like to tell you about the '\n+ 'code of\\n'\n+ ' conduct we are using in this project.
    • \\n
    • Only one in fact.
    • \\n
    '\n+ )\n+\n+ def test_reference_across_blocks(self):\n+ \"\"\"Test references across blocks.\"\"\"\n+\n+ self.assertMarkdownRenders(\n+ self.dedent(\n+ \"\"\"\n+ I would like to tell you about the [code of\n+\n+ conduct][] we are using in this project.\n+\n+ [code of conduct]: https://github.com/Python-Markdown/markdown/blob/master/CODE_OF_CONDUCT.md\n+ \"\"\"\n+ ),\n+ '

    I would like to tell you about the [code of

    \\n'\n+ '

    conduct][] we are using in this project.

    '\n+ )\n", "FAIL_TO_PASS": ["tests/test_syntax/inline/test_links.py::TestAdvancedLinks::test_reference_newlines"]}, {"instance_id": "python-markdown__markdown-785", "base_commit": "9ec83c4c414f27bc8aa490dbac1fe30b49058ae6", "gold_patch": "diff --git a/docs/change_log/release-3.1.md b/docs/change_log/release-3.1.md\nindex 5c225cf..c5f0433 100644\n--- a/docs/change_log/release-3.1.md\n+++ b/docs/change_log/release-3.1.md\n@@ -31,6 +31,7 @@ The following new features have been included in the release:\n \n The following bug fixes are included in the 3.1 release:\n \n+* Emphasis patterns now recognize newline characters as whitespace (#783).\n * Version format had been updated to be PEP 440 compliant (#736).\n * Block level elements are defined per instance, not as class attributes\n (#731).\ndiff --git a/markdown/inlinepatterns.py b/markdown/inlinepatterns.py\nindex dc502c2..88e8ead 100644\n--- a/markdown/inlinepatterns.py\n+++ b/markdown/inlinepatterns.py\n@@ -144,7 +144,7 @@ REFERENCE_RE = LINK_RE\n IMAGE_REFERENCE_RE = IMAGE_LINK_RE\n \n # stand-alone * or _\n-NOT_STRONG_RE = r'((^| )(\\*|_)( |$))'\n+NOT_STRONG_RE = r'((^|\\s)(\\*|_)(\\s|$))'\n \n # \n AUTOLINK_RE = r'<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^>]*)>'\n", "test_patch": "diff --git a/tests/test_syntax/inline/test_emphasis.py b/tests/test_syntax/inline/test_emphasis.py\nnew file mode 100644\nindex 0000000..d96861b\n--- /dev/null\n+++ b/tests/test_syntax/inline/test_emphasis.py\n@@ -0,0 +1,86 @@\n+# -*- coding: utf-8 -*-\n+\"\"\"\n+Python Markdown\n+\n+A Python implementation of John Gruber's Markdown.\n+\n+Documentation: https://python-markdown.github.io/\n+GitHub: https://github.com/Python-Markdown/markdown/\n+PyPI: https://pypi.org/project/Markdown/\n+\n+Started by Manfred Stienstra (http://www.dwerg.net/).\n+Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).\n+Currently maintained by Waylan Limberg (https://github.com/waylan),\n+Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).\n+\n+Copyright 2007-2019 The Python Markdown Project (v. 1.7 and later)\n+Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)\n+Copyright 2004 Manfred Stienstra (the original version)\n+\n+License: BSD (see LICENSE.md for details).\n+\"\"\"\n+\n+from markdown.test_tools import TestCase\n+\n+\n+class TestNotEmphasis(TestCase):\n+\n+ def test_standalone_asterisk(self):\n+ self.assertMarkdownRenders(\n+ '*',\n+ '

    *

    '\n+ )\n+\n+ def test_standalone_understore(self):\n+ self.assertMarkdownRenders(\n+ '_',\n+ '

    _

    '\n+ )\n+\n+ def test_standalone_asterisk_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo * bar',\n+ '

    foo * bar

    '\n+ )\n+\n+ def test_standalone_understore_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo _ bar',\n+ '

    foo _ bar

    '\n+ )\n+\n+ def test_standalone_asterisks_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo * bar * baz',\n+ '

    foo * bar * baz

    '\n+ )\n+\n+ def test_standalone_understores_in_text(self):\n+ self.assertMarkdownRenders(\n+ 'foo _ bar _ baz',\n+ '

    foo _ bar _ baz

    '\n+ )\n+\n+ def test_standalone_asterisks_with_newlines(self):\n+ self.assertMarkdownRenders(\n+ 'foo\\n* bar *\\nbaz',\n+ '

    foo\\n* bar *\\nbaz

    '\n+ )\n+\n+ def test_standalone_understores_with_newlines(self):\n+ self.assertMarkdownRenders(\n+ 'foo\\n_ bar _\\nbaz',\n+ '

    foo\\n_ bar _\\nbaz

    '\n+ )\n+\n+ def test_standalone_asterisks_at_end(self):\n+ self.assertMarkdownRenders(\n+ 'foo * bar *',\n+ '

    foo * bar *

    '\n+ )\n+\n+ def test_standalone_understores_at_begin_end(self):\n+ self.assertMarkdownRenders(\n+ '_ bar _',\n+ '

    _ bar _

    '\n+ )\n", "FAIL_TO_PASS": ["tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_asterisks_with_newlines", "tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_understores_with_newlines"]}], "all_FAIL_TO_PASS": ["tests/test_syntax/inline/test_links.py::TestAdvancedLinks::test_reference_newlines", "tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_asterisks_with_newlines", "tests/test_syntax/inline/test_emphasis.py::TestNotEmphasis::test_standalone_understores_with_newlines"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tox-dev__pipdeptree-195_x2", "level": 2, "source": "swerebenchv2", "repo": "tox-dev/pipdeptree", "image": "swerebenchv2/tox-dev-pipdeptree:195-96a2341", "base_commit": "96a23415b0a86cc042a9cd80724dc6d89af09761", "num_bugs": 2, "bugs": [{"instance_id": "tox-dev__pipdeptree-195", "base_commit": "96a23415b0a86cc042a9cd80724dc6d89af09761", "gold_patch": "diff --git a/src/pipdeptree/__init__.py b/src/pipdeptree/__init__.py\nindex 7679212..e269d4c 100644\n--- a/src/pipdeptree/__init__.py\n+++ b/src/pipdeptree/__init__.py\n@@ -10,6 +10,7 @@ from collections import defaultdict, deque\n from collections.abc import Mapping\n from importlib import import_module\n from itertools import chain\n+from textwrap import dedent\n \n from pip._vendor import pkg_resources\n \n@@ -550,6 +551,44 @@ def render_json_tree(tree, indent):\n return json.dumps([aux(p) for p in nodes], indent=indent)\n \n \n+def render_mermaid(tree) -> str:\n+ \"\"\"Produce a Mermaid flowchart from the dependency graph.\n+\n+ :param dict tree: dependency graph\n+ \"\"\"\n+ # Use a sets to avoid duplicate entries.\n+ nodes: set[str] = set()\n+ edges: set[str] = set()\n+\n+ for pkg, deps in tree.items():\n+ pkg_label = f\"{pkg.project_name}\\\\n{pkg.version}\"\n+ nodes.add(f\"{pkg.key}[{pkg_label}]\")\n+ for dep in deps:\n+ edge_label = dep.version_spec or \"any\"\n+ if dep.is_missing:\n+ dep_label = f\"{dep.project_name}\\\\n(missing)\"\n+ nodes.add(f\"{dep.key}[{dep_label}]:::missing\")\n+ edges.add(f\"{pkg.key} -.-> {dep.key}\")\n+ else:\n+ edges.add(f\"{pkg.key} -- {edge_label} --> {dep.key}\")\n+\n+ # Produce the Mermaid Markdown.\n+ indent = \" \" * 4\n+ output = dedent(\n+ f\"\"\"\\\n+ flowchart TD\n+ {indent}classDef missing stroke-dasharray: 5\n+ \"\"\"\n+ )\n+ # Sort the nodes and edges to make the output deterministic.\n+ output += indent\n+ output += f\"\\n{indent}\".join(node for node in sorted(nodes))\n+ output += \"\\n\" + indent\n+ output += f\"\\n{indent}\".join(edge for edge in sorted(edges))\n+ output += \"\\n\"\n+ return output\n+\n+\n def dump_graphviz(tree, output_format=\"dot\", is_reverse=False):\n \"\"\"Output dependency graph as one of the supported GraphViz output formats.\n \n@@ -775,6 +814,12 @@ def get_parser():\n \"This option overrides all other options (except --json).\"\n ),\n )\n+ parser.add_argument(\n+ \"--mermaid\",\n+ action=\"store_true\",\n+ default=False,\n+ help=(\"Display dependency tree as a Maermaid graph. \" \"This option overrides all other options.\"),\n+ )\n parser.add_argument(\n \"--graph-output\",\n dest=\"output_format\",\n@@ -884,6 +929,8 @@ def main():\n print(render_json(tree, indent=4))\n elif args.json_tree:\n print(render_json_tree(tree, indent=4))\n+ elif args.output_format:\n+ print(render_mermaid(tree))\n elif args.output_format:\n output = dump_graphviz(tree, output_format=args.output_format, is_reverse=args.reverse)\n print_graphviz(output)\n", "test_patch": "diff --git a/tests/test_pipdeptree.py b/tests/test_pipdeptree.py\nindex 3a7aa01..ef95065 100644\n--- a/tests/test_pipdeptree.py\n+++ b/tests/test_pipdeptree.py\n@@ -306,8 +306,9 @@ def test_render_text(capsys, list_all, reverse, expected_output):\n # Tests for graph outputs\n \n \n-def test_render_dot(capsys):\n- # Extract the dependency graph from the package tree fixture and randomize it.\n+def randomized_dag_copy(t):\n+ \"\"\"Returns a copy of the package tree fixture with dependencies in randomized order.\"\"\"\n+ # Extract the dependency graph from the package tree and randomize it.\n randomized_graph = {}\n randomized_nodes = list(t._obj.keys())\n random.shuffle(randomized_nodes)\n@@ -320,10 +321,42 @@ def test_render_dot(capsys):\n # Create a randomized package tree.\n randomized_dag = p.PackageDAG(randomized_graph)\n assert len(t) == len(randomized_dag)\n+ return randomized_dag\n+\n+\n+def test_render_mermaid():\n+ # Check both the sorted and randomized package tree produces the same sorted\n+ # Mermaid output.\n+ for package_tree in (t, randomized_dag_copy(t)):\n+ output = p.render_mermaid(package_tree)\n+ assert output == dedent(\n+ \"\"\"\\\n+ flowchart TD\n+ classDef missing stroke-dasharray: 5\n+ a[a\\\\n3.4.0]\n+ b[b\\\\n2.3.1]\n+ c[c\\\\n5.10.0]\n+ d[d\\\\n2.35]\n+ e[e\\\\n0.12.1]\n+ f[f\\\\n3.1]\n+ g[g\\\\n6.8.3rc1]\n+ a -- >=2.0.0 --> b\n+ a -- >=5.7.1 --> c\n+ b -- >=2.30,<2.42 --> d\n+ c -- >=0.12.1 --> e\n+ c -- >=2.30 --> d\n+ d -- >=0.9.0 --> e\n+ f -- >=2.1.0 --> b\n+ g -- >=0.9.0 --> e\n+ g -- >=3.0.0 --> f\n+ \"\"\"\n+ )\n \n+\n+def test_render_dot(capsys):\n # Check both the sorted and randomized package tree produces the same sorted\n # graphviz output.\n- for package_tree in (t, randomized_dag):\n+ for package_tree in (t, randomized_dag_copy(t)):\n output = p.dump_graphviz(package_tree, output_format=\"dot\")\n p.print_graphviz(output)\n out, _ = capsys.readouterr()\n@@ -499,6 +532,14 @@ def test_parser_json_tree():\n assert args.output_format is None\n \n \n+def test_parser_mermaid():\n+ parser = p.get_parser()\n+ args = parser.parse_args([\"--mermaid\"])\n+ assert args.mermaid\n+ assert not args.json\n+ assert args.output_format is None\n+\n+\n def test_parser_pdf():\n parser = p.get_parser()\n args = parser.parse_args([\"--graph-output\", \"pdf\"])\n", "FAIL_TO_PASS": ["tests/test_pipdeptree.py::test_render_mermaid", "tests/test_pipdeptree.py::test_parser_mermaid"]}, {"instance_id": "tox-dev__pipdeptree-239", "base_commit": "c23f8a32aa53c6d3829dd3d3d13a8a1f8fc15713", "gold_patch": "diff --git a/src/pipdeptree/__init__.py b/src/pipdeptree/__init__.py\nindex 3c9b424..8b9fa09 100644\n--- a/src/pipdeptree/__init__.py\n+++ b/src/pipdeptree/__init__.py\n@@ -462,16 +462,90 @@ def render_text(tree, list_all=True, frozen=False):\n :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies\n :param bool frozen: show the names of the pkgs in the output that's favourable to pip --freeze\n :returns: None\n-\n \"\"\"\n tree = tree.sort()\n nodes = tree.keys()\n branch_keys = {r.key for r in chain.from_iterable(tree.values())}\n- use_bullets = not frozen\n \n if not list_all:\n nodes = [p for p in nodes if p.key not in branch_keys]\n \n+ if sys.stdout.encoding.lower() in (\"utf-8\", \"utf-16\", \"utf-32\"):\n+ _render_text_with_unicode(tree, nodes, frozen)\n+ else:\n+ _render_text_without_unicode(tree, nodes, frozen)\n+\n+\n+def _render_text_with_unicode(tree, nodes, frozen):\n+ use_bullets = not frozen\n+\n+ def aux(\n+ node,\n+ parent=None,\n+ indent=0,\n+ cur_chain=None,\n+ prefix=\"\",\n+ depth=0,\n+ has_grand_parent=False,\n+ is_last_child=False,\n+ parent_is_last_child=False,\n+ ):\n+ cur_chain = cur_chain or []\n+ node_str = node.render(parent, frozen)\n+ next_prefix = \"\"\n+ next_indent = indent + 2\n+\n+ if parent:\n+ bullet = \"\u251c\u2500\u2500 \"\n+ if is_last_child:\n+ bullet = \"\u2514\u2500\u2500 \"\n+\n+ line_char = \"\u2502\"\n+ if not use_bullets:\n+ line_char = \"\"\n+ # Add 2 spaces so direct dependencies to a project are indented\n+ bullet = \" \"\n+\n+ if has_grand_parent:\n+ next_indent -= 1\n+ if parent_is_last_child:\n+ offset = 0 if len(line_char) == 1 else 1\n+ prefix += \" \" * (indent + 1 - offset - depth)\n+ else:\n+ prefix += line_char + \" \" * (indent - depth)\n+ # Without this extra space, bullets will point to the space just before the project name\n+ prefix += \" \" if use_bullets else \"\"\n+ next_prefix = prefix\n+ node_str = prefix + bullet + node_str\n+ result = [node_str]\n+\n+ children = tree.get_children(node.key)\n+ children_strings = [\n+ aux(\n+ c,\n+ node,\n+ indent=next_indent,\n+ cur_chain=cur_chain + [c.project_name],\n+ prefix=next_prefix,\n+ depth=depth + 1,\n+ has_grand_parent=parent is not None,\n+ is_last_child=c is children[-1],\n+ parent_is_last_child=is_last_child,\n+ )\n+ for c in children\n+ if c.project_name not in cur_chain\n+ ]\n+\n+ result += list(chain.from_iterable(children_strings))\n+ return result\n+\n+ lines = chain.from_iterable([aux(p) for p in nodes])\n+ print(\"\\n\".join(lines))\n+\n+\n+def _render_text_without_unicode(tree, nodes, frozen):\n+ use_bullets = not frozen\n+\n def aux(node, parent=None, indent=0, cur_chain=None):\n cur_chain = cur_chain or []\n node_str = node.render(parent, frozen)\n", "test_patch": "diff --git a/tests/test_pipdeptree.py b/tests/test_pipdeptree.py\nindex 34fa339..473eaa3 100644\n--- a/tests/test_pipdeptree.py\n+++ b/tests/test_pipdeptree.py\n@@ -224,12 +224,139 @@ def test_req_package_as_dict():\n # Tests for render_text\n \n \n+class MockStdout:\n+ \"\"\"\n+ A wrapper to stdout that mocks the `encoding` attribute (to have `render_text()` render with unicode/non-unicode)\n+ and `write()` (so that `print()` calls can write to stdout).\n+ \"\"\"\n+\n+ def __init__(self, encoding):\n+ self.stdout = sys.stdout\n+ self.encoding = encoding\n+\n+ def encoding(self):\n+ return self.encoding\n+\n+ def write(self, text):\n+ self.stdout.write(text)\n+\n+\n @pytest.mark.parametrize(\n- (\"list_all\", \"reverse\", \"expected_output\"),\n+ (\"list_all\", \"reverse\", \"unicode\", \"expected_output\"),\n [\n (\n True,\n False,\n+ True,\n+ [\n+ \"a==3.4.0\",\n+ \"\u251c\u2500\u2500 b [required: >=2.0.0, installed: 2.3.1]\",\n+ \"\u2502 \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \"\u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 c [required: >=5.7.1, installed: 5.10.0]\",\n+ \" \u251c\u2500\u2500 d [required: >=2.30, installed: 2.35]\",\n+ \" \u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.12.1, installed: 0.12.1]\",\n+ \"b==2.3.1\",\n+ \"\u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"c==5.10.0\",\n+ \"\u251c\u2500\u2500 d [required: >=2.30, installed: 2.35]\",\n+ \"\u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 e [required: >=0.12.1, installed: 0.12.1]\",\n+ \"d==2.35\",\n+ \"\u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"e==0.12.1\",\n+ \"f==3.1\",\n+ \"\u2514\u2500\u2500 b [required: >=2.1.0, installed: 2.3.1]\",\n+ \" \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"g==6.8.3rc1\",\n+ \"\u251c\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 f [required: >=3.0.0, installed: 3.1]\",\n+ \" \u2514\u2500\u2500 b [required: >=2.1.0, installed: 2.3.1]\",\n+ \" \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ ],\n+ ),\n+ (\n+ True,\n+ True,\n+ True,\n+ [\n+ \"a==3.4.0\",\n+ \"b==2.3.1\",\n+ \"\u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \" \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"c==5.10.0\",\n+ \"\u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"d==2.35\",\n+ \"\u251c\u2500\u2500 b==2.3.1 [requires: d>=2.30,<2.42]\",\n+ \"\u2502 \u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2502 \u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \"\u2502 \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"\u2514\u2500\u2500 c==5.10.0 [requires: d>=2.30]\",\n+ \" \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"e==0.12.1\",\n+ \"\u251c\u2500\u2500 c==5.10.0 [requires: e>=0.12.1]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u251c\u2500\u2500 d==2.35 [requires: e>=0.9.0]\",\n+ \"\u2502 \u251c\u2500\u2500 b==2.3.1 [requires: d>=2.30,<2.42]\",\n+ \"\u2502 \u2502 \u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"\u2502 \u2514\u2500\u2500 c==5.10.0 [requires: d>=2.30]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u2514\u2500\u2500 g==6.8.3rc1 [requires: e>=0.9.0]\",\n+ \"f==3.1\",\n+ \"\u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"g==6.8.3rc1\",\n+ ],\n+ ),\n+ (\n+ False,\n+ False,\n+ True,\n+ [\n+ \"a==3.4.0\",\n+ \"\u251c\u2500\u2500 b [required: >=2.0.0, installed: 2.3.1]\",\n+ \"\u2502 \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \"\u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 c [required: >=5.7.1, installed: 5.10.0]\",\n+ \" \u251c\u2500\u2500 d [required: >=2.30, installed: 2.35]\",\n+ \" \u2502 \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.12.1, installed: 0.12.1]\",\n+ \"g==6.8.3rc1\",\n+ \"\u251c\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ \"\u2514\u2500\u2500 f [required: >=3.0.0, installed: 3.1]\",\n+ \" \u2514\u2500\u2500 b [required: >=2.1.0, installed: 2.3.1]\",\n+ \" \u2514\u2500\u2500 d [required: >=2.30,<2.42, installed: 2.35]\",\n+ \" \u2514\u2500\u2500 e [required: >=0.9.0, installed: 0.12.1]\",\n+ ],\n+ ),\n+ (\n+ False,\n+ True,\n+ True,\n+ [\n+ \"e==0.12.1\",\n+ \"\u251c\u2500\u2500 c==5.10.0 [requires: e>=0.12.1]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u251c\u2500\u2500 d==2.35 [requires: e>=0.9.0]\",\n+ \"\u2502 \u251c\u2500\u2500 b==2.3.1 [requires: d>=2.30,<2.42]\",\n+ \"\u2502 \u2502 \u251c\u2500\u2500 a==3.4.0 [requires: b>=2.0.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 f==3.1 [requires: b>=2.1.0]\",\n+ \"\u2502 \u2502 \u2514\u2500\u2500 g==6.8.3rc1 [requires: f>=3.0.0]\",\n+ \"\u2502 \u2514\u2500\u2500 c==5.10.0 [requires: d>=2.30]\",\n+ \"\u2502 \u2514\u2500\u2500 a==3.4.0 [requires: c>=5.7.1]\",\n+ \"\u2514\u2500\u2500 g==6.8.3rc1 [requires: e>=0.9.0]\",\n+ ],\n+ ),\n+ (\n+ True,\n+ False,\n+ False,\n [\n \"a==3.4.0\",\n \" - b [required: >=2.0.0, installed: 2.3.1]\",\n@@ -264,6 +391,7 @@ def test_req_package_as_dict():\n (\n True,\n True,\n+ False,\n [\n \"a==3.4.0\",\n \"b==2.3.1\",\n@@ -296,6 +424,7 @@ def test_req_package_as_dict():\n ],\n ),\n (\n+ False,\n False,\n False,\n [\n@@ -318,6 +447,7 @@ def test_req_package_as_dict():\n (\n False,\n True,\n+ False,\n [\n \"e==0.12.1\",\n \" - c==5.10.0 [requires: e>=0.12.1]\",\n@@ -334,11 +464,13 @@ def test_req_package_as_dict():\n ),\n ],\n )\n-def test_render_text(capsys, list_all, reverse, expected_output):\n+def test_render_text(capsys, list_all, reverse, unicode, expected_output):\n tree = t.reverse() if reverse else t\n- p.render_text(tree, list_all=list_all, frozen=False)\n- captured = capsys.readouterr()\n- assert \"\\n\".join(expected_output).strip() == captured.out.strip()\n+ encoding = \"utf-8\" if unicode else \"ascii\"\n+ with mock.patch(\"sys.stdout\", MockStdout(encoding)):\n+ p.render_text(tree, list_all=list_all, frozen=False)\n+ captured = capsys.readouterr()\n+ assert \"\\n\".join(expected_output).strip() == captured.out.strip()\n \n \n # Tests for graph outputs\n", "FAIL_TO_PASS": ["tests/test_pipdeptree.py::test_render_text[True-False-True-expected_output0]", "tests/test_pipdeptree.py::test_render_text[True-True-True-expected_output1]", "tests/test_pipdeptree.py::test_render_text[False-False-True-expected_output2]", "tests/test_pipdeptree.py::test_render_text[False-True-True-expected_output3]"]}], "all_FAIL_TO_PASS": ["tests/test_pipdeptree.py::test_render_mermaid", "tests/test_pipdeptree.py::test_parser_mermaid", "tests/test_pipdeptree.py::test_render_text[True-False-True-expected_output0]", "tests/test_pipdeptree.py::test_render_text[True-True-True-expected_output1]", "tests/test_pipdeptree.py::test_render_text[False-False-True-expected_output2]", "tests/test_pipdeptree.py::test_render_text[False-True-True-expected_output3]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "getmoto__moto-5873_x2", "level": 2, "source": "swerebenchv2", "repo": "getmoto/moto", "image": "swerebenchv2/getmoto-moto:5873-667c40e", "base_commit": "667c40e58a1dbf4a2619660464a845d2b5195cf7", "num_bugs": 2, "bugs": [{"instance_id": "getmoto__moto-5873", "base_commit": "667c40e58a1dbf4a2619660464a845d2b5195cf7", "gold_patch": "diff --git a/moto/cognitoidp/models.py b/moto/cognitoidp/models.py\nindex e8857f510..3ddb8f113 100644\n--- a/moto/cognitoidp/models.py\n+++ b/moto/cognitoidp/models.py\n@@ -1429,7 +1429,7 @@ class CognitoIdpBackend(BaseBackend):\n }\n \n return self._log_user_in(user_pool, client, username)\n- elif auth_flow is AuthFlow.REFRESH_TOKEN:\n+ elif auth_flow in (AuthFlow.REFRESH_TOKEN, AuthFlow.REFRESH_TOKEN_AUTH):\n refresh_token: str = auth_parameters.get(\"REFRESH_TOKEN\") # type: ignore[assignment]\n (\n access_token,\ndiff --git a/moto/dynamodb/models/table.py b/moto/dynamodb/models/table.py\nindex 483897246..6c95500ce 100644\n--- a/moto/dynamodb/models/table.py\n+++ b/moto/dynamodb/models/table.py\n@@ -34,6 +34,7 @@ class SecondaryIndex(BaseModel):\n self.schema = schema\n self.table_key_attrs = table_key_attrs\n self.projection = projection\n+ self.schema_key_attrs = [k[\"AttributeName\"] for k in schema]\n \n def project(self, item: Item) -> Item:\n \"\"\"\ndiff --git a/moto/dynamodb/responses.py b/moto/dynamodb/responses.py\nindex 54f3abe72..2108f4b4f 100644\n--- a/moto/dynamodb/responses.py\n+++ b/moto/dynamodb/responses.py\n@@ -79,12 +79,17 @@ def include_consumed_capacity(\n return _inner\n \n \n-def get_empty_keys_on_put(field_updates: Dict[str, Any], table: Table) -> Optional[str]:\n+def validate_put_has_empty_keys(\n+ field_updates: Dict[str, Any], table: Table, custom_error_msg: Optional[str] = None\n+) -> None:\n \"\"\"\n- Return the first key-name that has an empty value. None if all keys are filled\n+ Error if any keys have an empty value. Checks Global index attributes as well\n \"\"\"\n if table:\n key_names = table.attribute_keys\n+ gsi_key_names = list(\n+ itertools.chain(*[gsi.schema_key_attrs for gsi in table.global_indexes])\n+ )\n \n # string/binary fields with empty string as value\n empty_str_fields = [\n@@ -92,10 +97,27 @@ def get_empty_keys_on_put(field_updates: Dict[str, Any], table: Table) -> Option\n for (key, val) in field_updates.items()\n if next(iter(val.keys())) in [\"S\", \"B\"] and next(iter(val.values())) == \"\"\n ]\n- return next(\n+\n+ # First validate that all of the GSI-keys are set\n+ empty_gsi_key = next(\n+ (kn for kn in gsi_key_names if kn in empty_str_fields), None\n+ )\n+ if empty_gsi_key:\n+ gsi_name = table.global_indexes[0].name\n+ raise MockValidationException(\n+ f\"One or more parameter values are not valid. A value specified for a secondary index key is not supported. The AttributeValue for a key attribute cannot contain an empty string value. IndexName: {gsi_name}, IndexKey: {empty_gsi_key}\"\n+ )\n+\n+ # Then validate that all of the regular keys are set\n+ empty_key = next(\n (keyname for keyname in key_names if keyname in empty_str_fields), None\n )\n- return None\n+ if empty_key:\n+ msg = (\n+ custom_error_msg\n+ or \"One or more parameter values were invalid: An AttributeValue may not contain an empty string. Key: {}\"\n+ )\n+ raise MockValidationException(msg.format(empty_key))\n \n \n def put_has_empty_attrs(field_updates: Dict[str, Any], table: Table) -> bool:\n@@ -401,11 +423,7 @@ class DynamoHandler(BaseResponse):\n raise MockValidationException(\"Return values set to invalid value\")\n \n table = self.dynamodb_backend.get_table(name)\n- empty_key = get_empty_keys_on_put(item, table)\n- if empty_key:\n- raise MockValidationException(\n- f\"One or more parameter values were invalid: An AttributeValue may not contain an empty string. Key: {empty_key}\"\n- )\n+ validate_put_has_empty_keys(item, table)\n if put_has_empty_attrs(item, table):\n raise MockValidationException(\n \"One or more parameter values were invalid: An number set may not be empty\"\n@@ -462,11 +480,11 @@ class DynamoHandler(BaseResponse):\n request = list(table_request.values())[0]\n if request_type == \"PutRequest\":\n item = request[\"Item\"]\n- empty_key = get_empty_keys_on_put(item, table)\n- if empty_key:\n- raise MockValidationException(\n- f\"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: {empty_key}\"\n- )\n+ validate_put_has_empty_keys(\n+ item,\n+ table,\n+ custom_error_msg=\"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: {}\",\n+ )\n put_requests.append((table_name, item))\n elif request_type == \"DeleteRequest\":\n keys = request[\"Key\"]\n@@ -1004,6 +1022,12 @@ class DynamoHandler(BaseResponse):\n \n def transact_write_items(self) -> str:\n transact_items = self.body[\"TransactItems\"]\n+ # Validate first - we should error before we start the transaction\n+ for item in transact_items:\n+ if \"Put\" in item:\n+ item_attrs = item[\"Put\"][\"Item\"]\n+ table = self.dynamodb_backend.get_table(item[\"Put\"][\"TableName\"])\n+ validate_put_has_empty_keys(item_attrs, table)\n self.dynamodb_backend.transact_write_items(transact_items)\n response: Dict[str, Any] = {\"ConsumedCapacity\": [], \"ItemCollectionMetrics\": {}}\n return dynamo_json_dump(response)\n", "test_patch": "diff --git a/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py b/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py\nindex ebb7c13cc..4f4cc7489 100644\n--- a/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py\n+++ b/tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py\n@@ -803,6 +803,45 @@ def test_transact_write_items_multiple_operations_fail():\n )\n \n \n+@mock_dynamodb\n+def test_transact_write_items_with_empty_gsi_key():\n+ client = boto3.client(\"dynamodb\", \"us-east-2\")\n+\n+ client.create_table(\n+ TableName=\"test_table\",\n+ KeySchema=[{\"AttributeName\": \"unique_code\", \"KeyType\": \"HASH\"}],\n+ AttributeDefinitions=[\n+ {\"AttributeName\": \"unique_code\", \"AttributeType\": \"S\"},\n+ {\"AttributeName\": \"unique_id\", \"AttributeType\": \"S\"},\n+ ],\n+ GlobalSecondaryIndexes=[\n+ {\n+ \"IndexName\": \"gsi_index\",\n+ \"KeySchema\": [{\"AttributeName\": \"unique_id\", \"KeyType\": \"HASH\"}],\n+ \"Projection\": {\"ProjectionType\": \"ALL\"},\n+ }\n+ ],\n+ ProvisionedThroughput={\"ReadCapacityUnits\": 5, \"WriteCapacityUnits\": 5},\n+ )\n+\n+ transact_items = [\n+ {\n+ \"Put\": {\n+ \"Item\": {\"unique_code\": {\"S\": \"some code\"}, \"unique_id\": {\"S\": \"\"}},\n+ \"TableName\": \"test_table\",\n+ }\n+ }\n+ ]\n+\n+ with pytest.raises(ClientError) as exc:\n+ client.transact_write_items(TransactItems=transact_items)\n+ err = exc.value.response[\"Error\"]\n+ err[\"Code\"].should.equal(\"ValidationException\")\n+ err[\"Message\"].should.equal(\n+ \"One or more parameter values are not valid. A value specified for a secondary index key is not supported. The AttributeValue for a key attribute cannot contain an empty string value. IndexName: gsi_index, IndexKey: unique_id\"\n+ )\n+\n+\n @mock_dynamodb\n def test_update_primary_key_with_sortkey():\n dynamodb = boto3.resource(\"dynamodb\", region_name=\"us-east-1\")\n", "FAIL_TO_PASS": ["tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py::test_transact_write_items_with_empty_gsi_key"]}, {"instance_id": "getmoto__moto-5876", "base_commit": "6d41ad72e09b49f61e54d47880f8a65026e7c0e4", "gold_patch": "diff --git a/moto/cognitoidp/exceptions.py b/moto/cognitoidp/exceptions.py\nindex b234a5238..8271af59e 100644\n--- a/moto/cognitoidp/exceptions.py\n+++ b/moto/cognitoidp/exceptions.py\n@@ -2,6 +2,13 @@ from moto.core.exceptions import JsonRESTError\n from typing import Optional\n \n \n+class AliasExistsException(JsonRESTError):\n+ def __init__(self) -> None:\n+ super().__init__(\n+ \"AliasExistsException\", \"An account with the given email already exists.\"\n+ )\n+\n+\n class ResourceNotFoundError(JsonRESTError):\n def __init__(self, message: Optional[str]):\n super().__init__(error_type=\"ResourceNotFoundException\", message=message or \"\")\ndiff --git a/moto/cognitoidp/models.py b/moto/cognitoidp/models.py\nindex 3ddb8f113..3c6e97c62 100644\n--- a/moto/cognitoidp/models.py\n+++ b/moto/cognitoidp/models.py\n@@ -11,6 +11,7 @@ from typing import Any, Dict, List, Tuple, Optional, Set\n from moto.core import BaseBackend, BackendDict, BaseModel\n from moto.moto_api._internal import mock_random as random\n from .exceptions import (\n+ AliasExistsException,\n GroupExistsException,\n NotAuthorizedError,\n ResourceNotFoundError,\n@@ -1636,6 +1637,9 @@ class CognitoIdpBackend(BaseBackend):\n ) -> None:\n user = self.admin_get_user(user_pool_id, username)\n \n+ email = self._find_attr(\"email\", attributes)\n+ self._verify_email_is_not_used(user_pool_id, email)\n+\n user.update_attributes(attributes)\n \n def admin_delete_user_attributes(\n@@ -2031,11 +2035,32 @@ class CognitoIdpBackend(BaseBackend):\n _, username = user_pool.access_tokens[access_token]\n user = self.admin_get_user(user_pool.id, username)\n \n+ email = self._find_attr(\"email\", attributes)\n+ self._verify_email_is_not_used(user_pool.id, email)\n+\n user.update_attributes(attributes)\n return\n \n raise NotAuthorizedError(access_token)\n \n+ def _find_attr(self, name: str, attrs: List[Dict[str, str]]) -> Optional[str]:\n+ return next((a[\"Value\"] for a in attrs if a[\"Name\"] == name), None)\n+\n+ def _verify_email_is_not_used(\n+ self, user_pool_id: str, email: Optional[str]\n+ ) -> None:\n+ if not email:\n+ # We're not updating emails\n+ return\n+ user_pool = self.describe_user_pool(user_pool_id)\n+ if \"email\" not in user_pool.extended_config.get(\"UsernameAttributes\", []):\n+ # email is not used as a username - duplicate emails are allowed\n+ return\n+\n+ for user in user_pool.users.values():\n+ if user.attribute_lookup.get(\"email\", \"\") == email:\n+ raise AliasExistsException\n+\n \n class RegionAgnosticBackend:\n # Some operations are unauthenticated\n", "test_patch": "diff --git a/tests/test_cognitoidp/test_cognitoidp_exceptions.py b/tests/test_cognitoidp/test_cognitoidp_exceptions.py\nindex ec19de0a0..0cd827bdc 100644\n--- a/tests/test_cognitoidp/test_cognitoidp_exceptions.py\n+++ b/tests/test_cognitoidp/test_cognitoidp_exceptions.py\n@@ -1,6 +1,8 @@\n from unittest import TestCase\n \n import boto3\n+import pytest\n+\n from moto import mock_cognitoidp\n from botocore.exceptions import ClientError\n \n@@ -49,3 +51,47 @@ class TestCognitoUserDeleter(TestCase):\n },\n )\n exc.exception.response[\"Error\"][\"Code\"].should.equal(\"NotAuthorizedException\")\n+\n+\n+@mock_cognitoidp\n+class TestCognitoUserPoolDuplidateEmails(TestCase):\n+ def setUp(self) -> None:\n+ self.client = boto3.client(\"cognito-idp\", \"us-east-1\")\n+\n+ self.pool_id1 = self.client.create_user_pool(PoolName=\"test\")[\"UserPool\"][\"Id\"]\n+ self.pool_id2 = self.client.create_user_pool(\n+ PoolName=\"test\", UsernameAttributes=[\"email\"]\n+ )[\"UserPool\"][\"Id\"]\n+\n+ # create two users\n+ for user in [\"user1\", \"user2\"]:\n+ self.client.admin_create_user(\n+ UserPoolId=self.pool_id1,\n+ Username=user,\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": f\"{user}@test.com\"}],\n+ )\n+ self.client.admin_create_user(\n+ UserPoolId=self.pool_id2,\n+ Username=f\"{user}@test.com\",\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": f\"{user}@test.com\"}],\n+ )\n+\n+ def test_use_existing_email__when_email_is_login(self):\n+ with pytest.raises(ClientError) as exc:\n+ self.client.admin_update_user_attributes(\n+ UserPoolId=self.pool_id2,\n+ Username=\"user1@test.com\",\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": \"user2@test.com\"}],\n+ )\n+ err = exc.value.response[\"Error\"]\n+ err[\"Code\"].should.equal(\"AliasExistsException\")\n+ err[\"Message\"].should.equal(\"An account with the given email already exists.\")\n+\n+ def test_use_existing_email__when_username_is_login(self):\n+ # Because we cannot use the email as username,\n+ # multiple users can have the same email address\n+ self.client.admin_update_user_attributes(\n+ UserPoolId=self.pool_id1,\n+ Username=\"user1\",\n+ UserAttributes=[{\"Name\": \"email\", \"Value\": \"user2@test.com\"}],\n+ )\n", "FAIL_TO_PASS": ["tests/test_cognitoidp/test_cognitoidp_exceptions.py::TestCognitoUserPoolDuplidateEmails::test_use_existing_email__when_email_is_login"]}], "all_FAIL_TO_PASS": ["tests/test_dynamodb/exceptions/test_dynamodb_exceptions.py::test_transact_write_items_with_empty_gsi_key", "tests/test_cognitoidp/test_cognitoidp_exceptions.py::TestCognitoUserPoolDuplidateEmails::test_use_existing_email__when_email_is_login"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cuthbertlab__music21-1066_x2", "level": 2, "source": "swerebenchv2", "repo": "cuthbertLab/music21", "image": "swerebenchv2/cuthbertlab-music21:1066-5d566a8", "base_commit": "5d566a8089fdc50b3053d9071a24b9db157a31d4", "num_bugs": 2, "bugs": [{"instance_id": "cuthbertlab__music21-1066", "base_commit": "5d566a8089fdc50b3053d9071a24b9db157a31d4", "gold_patch": "diff --git a/music21/_version.py b/music21/_version.py\nindex 7651c8d0c..b4949ae8b 100644\n--- a/music21/_version.py\n+++ b/music21/_version.py\n@@ -42,7 +42,7 @@ When changing, update the single test case in base.py.\n Changing this number invalidates old pickles -- do it if the old pickles create a problem.\n '''\n \n-__version_info__ = (7, 0, 7, 'b1') # can be 4-tuple: (7, 0, 5, 'a2')\n+__version_info__ = (7, 0, 8) # can be 4-tuple: (7, 0, 5, 'a2')\n \n v = '.'.join(str(x) for x in __version_info__[0:3])\n if len(__version_info__) > 3 and __version_info__[3]:\ndiff --git a/music21/base.py b/music21/base.py\nindex 3330d787c..1c930b143 100644\n--- a/music21/base.py\n+++ b/music21/base.py\n@@ -28,7 +28,7 @@ available after importing `music21`.\n \n \n >>> music21.VERSION_STR\n-'7.0.7b1'\n+'7.0.8'\n \n Alternatively, after doing a complete import, these classes are available\n under the module \"base\":\ndiff --git a/music21/meter/base.py b/music21/meter/base.py\nindex 98d4d016f..ef4ac52c6 100644\n--- a/music21/meter/base.py\n+++ b/music21/meter/base.py\n@@ -1293,6 +1293,14 @@ class TimeSignature(base.Music21Object):\n >,\n >,\n >]\n+\n+ Fixed in v.7 -- incomplete final measures in 6/8:\n+\n+ >>> sixEight = meter.TimeSignature('6/8')\n+ >>> nList = [note.Note(type='quarter'), note.Note(type='eighth'), note.Note(type='eighth')]\n+ >>> beamList = sixEight.getBeams(nList)\n+ >>> print(beamList)\n+ [None, None, None]\n '''\n from music21 import stream\n if isinstance(srcList, stream.Stream):\n@@ -1352,8 +1360,11 @@ class TimeSignature(base.Music21Object):\n \n # watch for a special case where a duration completely fills\n # the archetype; this generally should not be beamed\n- if (start == archetypeSpanStart\n- and end == archetypeSpanEnd):\n+ # same if beamPrevious is None and beamNumber == 1 (quarter-eighth in 6/8)\n+ if end == archetypeSpanEnd and (\n+ start == archetypeSpanStart\n+ or (beamPrevious is None and beamNumber == 1)\n+ ):\n # increment position and continue loop\n beamsList[i] = None # replace with None!\n return\n@@ -1368,7 +1379,7 @@ class TimeSignature(base.Music21Object):\n \n elif isLast: # last is always stop\n beamType = 'stop'\n- # get a partial beam if we cannot come form a beam\n+ # get a partial beam if we cannot form a beam\n if (beamPrevious is None\n or beamNumber not in beamPrevious.getNumbers()):\n # environLocal.warn(['triggering partial left where a stop normally falls'])\ndiff --git a/music21/musicxml/xmlToM21.py b/music21/musicxml/xmlToM21.py\nindex f84960122..050e8e405 100644\n--- a/music21/musicxml/xmlToM21.py\n+++ b/music21/musicxml/xmlToM21.py\n@@ -1989,8 +1989,8 @@ class PartParser(XMLParserBase):\n Fills an empty measure with a measure of rest (bug in PDFtoMusic and\n other MusicXML writers).\n \n- sets self.lastMeasureWasShort to True or False if it is an incomplete measure\n- that is not a pickup.\n+ Sets self.lastMeasureWasShort to True or False if it is an incomplete measure\n+ that is not a pickup and sets paddingRight.\n \n >>> m = stream.Measure([meter.TimeSignature('4/4'), harmony.ChordSymbol('C7')])\n >>> m.highestTime\n@@ -2002,6 +2002,17 @@ class PartParser(XMLParserBase):\n 4.0\n >>> PP.lastMeasureWasShort\n False\n+\n+ Incomplete final measure:\n+\n+ >>> m = stream.Measure([meter.TimeSignature('6/8'), note.Note(), note.Note()])\n+ >>> m.offset = 24.0\n+ >>> PP = musicxml.xmlToM21.PartParser()\n+ >>> PP.lastMeasureOffset = 21.0\n+ >>> PP.setLastMeasureInfo(m)\n+ >>> PP.adjustTimeAttributesFromMeasure(m)\n+ >>> m.paddingRight\n+ 1.0\n '''\n # note: we cannot assume that the time signature properly\n # describes the offsets w/n this bar. need to look at\n@@ -2049,6 +2060,9 @@ class PartParser(XMLParserBase):\n # or something\n self.lastMeasureWasShort = False\n else:\n+ # Incomplete measure that is likely NOT an anacrusis, set paddingRight\n+ if m.barDurationProportion() < 1.0:\n+ m.paddingRight = m.barDuration.quarterLength - m.highestTime\n if mHighestTime < lastTimeSignatureQuarterLength:\n self.lastMeasureWasShort = True\n else:\ndiff --git a/music21/stream/makeNotation.py b/music21/stream/makeNotation.py\nindex f1a71b5e2..ab47aeca8 100644\n--- a/music21/stream/makeNotation.py\n+++ b/music21/stream/makeNotation.py\n@@ -188,6 +188,9 @@ def makeBeams(\n offset = 0.0\n if m.paddingLeft != 0.0:\n offset = opFrac(m.paddingLeft)\n+ elif m.paddingRight != 0.0:\n+ pass\n+ # Incomplete measure without any padding set: assume paddingLeft\n elif noteStream.highestTime < barQL:\n offset = barQL - noteStream.highestTime\n \n@@ -1727,9 +1730,11 @@ def setStemDirectionOneGroup(\n if not group: # pragma: no cover\n return # should not happen\n \n- up_down_stem_directions = set(n.stemDirection for n in group\n- if n.stemDirection in ('up', 'down'))\n- if len(up_down_stem_directions) < 2:\n+ stem_directions = {n.stemDirection for n in group\n+ if n.stemDirection in ('up', 'down', 'unspecified')}\n+ if 'unspecified' in stem_directions:\n+ has_consistent_stem_directions = False\n+ elif len(stem_directions) < 2:\n has_consistent_stem_directions = True\n else:\n has_consistent_stem_directions = False\n@@ -1760,8 +1765,6 @@ def setStemDirectionOneGroup(\n \n \n \n-\n-\n # -----------------------------------------------------------------------------\n \n class Test(unittest.TestCase):\n@@ -1837,6 +1840,31 @@ class Test(unittest.TestCase):\n + ['down', 'noStem', 'double', 'down']\n )\n \n+ def testSetStemDirectionConsistency(self):\n+ \"\"\"\n+ Stems that would all be up starting from scratch,\n+ but because of overrideConsistentStemDirections=False,\n+ we only change the first group with an \"unspecified\" direction\n+ \"\"\"\n+ from music21 import converter\n+ p = converter.parse('tinyNotation: 2/4 b8 f8 a8 b8')\n+ p.makeBeams(inPlace=True)\n+ self.assertEqual(\n+ [n.stemDirection for n in p.flat.notes],\n+ ['up', 'up', 'up', 'up']\n+ )\n+\n+ # make manual changes\n+ dStems = ['down', 'unspecified', 'down', 'down']\n+ for n, stemDir in zip(p.flat.notes, dStems):\n+ n.stemDirection = stemDir\n+\n+ setStemDirectionForBeamGroups(p, setNewStems=True, overrideConsistentStemDirections=False)\n+ self.assertEqual(\n+ [n.stemDirection for n in p.flat.notes],\n+ ['up', 'up', 'down', 'down']\n+ )\n+\n def testMakeBeamsWithStemDirection(self):\n from music21 import converter\n p = converter.parse(self.allaBreveBeamTest)\n", "test_patch": "diff --git a/music21/stream/tests.py b/music21/stream/tests.py\nindex 58eb22af6..5b763f437 100644\n--- a/music21/stream/tests.py\n+++ b/music21/stream/tests.py\n@@ -8303,6 +8303,33 @@ class Test(unittest.TestCase):\n self.assertEqual(beams[3], continue_beam) # fourth should be continue\n self.assertEqual(beams[4], stop_beam) # last should be stop\n \n+ def test_makeBeams__paddingRight(self):\n+ m = Measure()\n+ m.timeSignature = meter.TimeSignature('6/8')\n+ m.paddingRight = 1.0\n+ m.append(note.Note(type='quarter'))\n+ m.append(note.Note(type='eighth'))\n+ m.append(note.Note(type='eighth'))\n+\n+ m.makeBeams(inPlace=True)\n+ beams = self.get_beams_from_stream(m)\n+\n+ no_beam = beam.Beams()\n+ start_beam = beam.Beams()\n+ start_beam.append('start')\n+ stop_beam = beam.Beams()\n+ stop_beam.append('stop')\n+\n+ self.assertEqual(beams, [no_beam, no_beam, no_beam])\n+\n+ m.paddingRight = 0.5\n+ m.append(note.Note(type='eighth'))\n+\n+ m.makeBeams(inPlace=True)\n+ beams = self.get_beams_from_stream(m)\n+\n+ self.assertEqual(beams, [no_beam, no_beam, start_beam, stop_beam])\n+\n def testWrite(self):\n import os\n \n", "FAIL_TO_PASS": ["music21/stream/tests.py::Test::test_makeBeams__paddingRight"]}, {"instance_id": "cuthbertlab__music21-1138", "base_commit": "546683ad59a0368908a4325537d468f22f084acd", "gold_patch": "diff --git a/music21/meter/base.py b/music21/meter/base.py\nindex b9592f17c..ec239a2e4 100644\n--- a/music21/meter/base.py\n+++ b/music21/meter/base.py\n@@ -1178,7 +1178,10 @@ class TimeSignature(base.Music21Object):\n # create a scratch MeterSequence for structure\n tsStr = f'{self.numerator}/{self.denominator}'\n if self.beatSequence.isUniformPartition():\n- firstPartitionForm = len(self.beatSequence)\n+ if len(self.beatSequence) > 1:\n+ firstPartitionForm = len(self.beatSequence)\n+ else:\n+ firstPartitionForm = None\n cacheKey = (tsStr, firstPartitionForm, depth)\n else: # derive from meter sequence\n firstPartitionForm = self.beatSequence\n", "test_patch": "diff --git a/music21/meter/tests.py b/music21/meter/tests.py\nindex 493f6c3f4..5ee71b264 100644\n--- a/music21/meter/tests.py\n+++ b/music21/meter/tests.py\n@@ -388,6 +388,9 @@ class Test(unittest.TestCase):\n 0.5, 0.125, 0.25, 0.125, 0.25, 0.125,\n 0.5, 0.125, 0.25, 0.125, 0.25, 0.125]),\n \n+ ('3/8', [1.0, 0.125, 0.25, 0.125, 0.5, 0.125,\n+ 0.25, 0.125, 0.5, 0.125, 0.25, 0.125]),\n+\n ('11/8',\n [1.0, 0.125, 0.25, 0.125,\n 0.5, 0.125, 0.25, 0.125,\n", "FAIL_TO_PASS": ["music21/meter/tests.py::Test::testSetDefaultAccentWeights"]}], "all_FAIL_TO_PASS": ["music21/stream/tests.py::Test::test_makeBeams__paddingRight", "music21/meter/tests.py::Test::testSetDefaultAccentWeights"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pycqa__pyflakes-765_x2", "level": 2, "source": "swerebenchv2", "repo": "PyCQA/pyflakes", "image": "swerebenchv2/pycqa-pyflakes:765-e932464", "base_commit": "e9324649874a7124a08c3826d4cf78a4dc3aa32c", "num_bugs": 2, "bugs": [{"instance_id": "pycqa__pyflakes-765", "base_commit": "e9324649874a7124a08c3826d4cf78a4dc3aa32c", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex 4d778a8..e654afa 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -1068,7 +1068,7 @@ class Checker:\n \n binding = scope.get(name, None)\n if isinstance(binding, Annotation) and not self._in_postponed_annotation:\n- scope[name].used = True\n+ scope[name].used = (self.scope, node)\n continue\n \n if name == 'print' and isinstance(binding, Builtin):\n", "test_patch": "diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py\nindex f0fd3b9..396d676 100644\n--- a/pyflakes/test/test_type_annotations.py\n+++ b/pyflakes/test/test_type_annotations.py\n@@ -367,6 +367,13 @@ class TestTypeAnnotations(TestCase):\n x = 3\n ''', m.UnusedVariable)\n \n+ def test_unused_annotation_in_outer_scope_reassigned_in_local_scope(self):\n+ self.flakes('''\n+ x: int\n+ x.__dict__\n+ def f(): x = 1\n+ ''', m.UndefinedName, m.UnusedVariable)\n+\n def test_unassigned_annotation_is_undefined(self):\n self.flakes('''\n name: str\n", "FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation_in_outer_scope_reassigned_in_local_scope"]}, {"instance_id": "pycqa__pyflakes-772", "base_commit": "e19886e583637a7e2eec428cc036094b9630f2d0", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex e654afa..db4da49 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -29,8 +29,10 @@ parse_format_string = string.Formatter().parse\n def getAlternatives(n):\n if isinstance(n, ast.If):\n return [n.body]\n- if isinstance(n, ast.Try):\n+ elif isinstance(n, ast.Try):\n return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]\n+ elif sys.version_info >= (3, 10) and isinstance(n, ast.Match):\n+ return [mc.body for mc in n.cases]\n \n \n FOR_TYPES = (ast.For, ast.AsyncFor)\n", "test_patch": "diff --git a/pyflakes/test/test_match.py b/pyflakes/test/test_match.py\nindex 89826e3..b237523 100644\n--- a/pyflakes/test/test_match.py\n+++ b/pyflakes/test/test_match.py\n@@ -81,3 +81,14 @@ class TestMatch(TestCase):\n case {'foo': k1, **rest}:\n print(f'{k1=} {rest=}')\n ''')\n+\n+ def test_defined_in_different_branches(self):\n+ self.flakes('''\n+ def f(x):\n+ match x:\n+ case 1:\n+ def y(): pass\n+ case _:\n+ def y(): print(1)\n+ return y\n+ ''')\n", "FAIL_TO_PASS": ["pyflakes/test/test_match.py::TestMatch::test_defined_in_different_branches"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation_in_outer_scope_reassigned_in_local_scope", "pyflakes/test/test_match.py::TestMatch::test_defined_in_different_branches"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3455_x2", "level": 2, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3455-aacbc54", "base_commit": "aacbc54f633cacd60235e027ee16efa6af2d900e", "num_bugs": 2, "bugs": [{"instance_id": "openmdao__openmdao-3455", "base_commit": "aacbc54f633cacd60235e027ee16efa6af2d900e", "gold_patch": "diff --git a/openmdao/core/problem.py b/openmdao/core/problem.py\nindex 67eb07195..112d880f8 100644\n--- a/openmdao/core/problem.py\n+++ b/openmdao/core/problem.py\n@@ -54,7 +54,7 @@ from openmdao.utils.general_utils import pad_name, _find_dict_meta, env_truthy,\n from openmdao.utils.om_warnings import issue_warning, DerivativesWarning, warn_deprecation, \\\n OMInvalidCheckDerivativesOptionsWarning\n import openmdao.utils.coloring as coloring_mod\n-from openmdao.utils.file_utils import _get_outputs_dir, text2html, get_work_dir\n+from openmdao.utils.file_utils import _get_outputs_dir, text2html, _get_work_dir\n from openmdao.utils.testing_utils import _fix_comp_check_data\n \n try:\n@@ -264,8 +264,11 @@ class Problem(object, metaclass=ProblemMetaclass):\n \n # General options\n self.options = OptionsDictionary(parent_name=type(self).__name__)\n+ default_workdir = options['work_dir'] if 'work_dir' in options else _get_work_dir()\n+ self.options.declare('work_dir', default=default_workdir,\n+ desc='Working directory for the problem.')\n self.options.declare('coloring_dir', types=str,\n- default=os.path.join(get_work_dir(), 'coloring_files'),\n+ default=os.path.join(default_workdir, 'coloring_files'),\n desc='Directory containing coloring files (if any) for this Problem.')\n self.options.declare('group_by_pre_opt_post', types=bool,\n default=False,\n@@ -962,6 +965,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n 'name': self._name, # the name of this Problem\n 'pathname': None, # the pathname of this Problem in the current tree of Problems\n 'comm': comm,\n+ 'work_dir': pathlib.Path(self.options['work_dir']),\n 'coloring_dir': _DEFAULT_COLORING_DIR, # directory for input coloring files\n 'recording_iter': _RecIteration(comm.rank), # manager of recorder iterations\n 'local_vector_class': local_vector_class,\ndiff --git a/openmdao/devtools/iprofile.py b/openmdao/devtools/iprofile.py\nindex 53b72323e..d6e280ba5 100644\n--- a/openmdao/devtools/iprofile.py\n+++ b/openmdao/devtools/iprofile.py\n@@ -9,7 +9,7 @@ from openmdao.utils.mpi import MPI\n \n from openmdao.devtools.iprof_utils import func_group, find_qualified_name, _collect_methods, \\\n _setup_func_group, _get_methods, _Options\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n \n \n def _prof_node(fpath, parts):\n@@ -44,7 +44,7 @@ def _setup(options, finalize=True):\n if _profile_setup:\n raise RuntimeError(\"profiling is already set up.\")\n \n- _profile_prefix = os.path.join(get_work_dir(), 'iprof')\n+ _profile_prefix = os.path.join(_get_work_dir(), 'iprof')\n _profile_setup = True\n \n methods = _get_methods(options, default='openmdao')\ndiff --git a/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb b/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb\nindex b563dbba0..83a6e4f1e 100644\n--- a/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb\n+++ b/openmdao/docs/openmdao_book/features/reports/reports_system.ipynb\n@@ -103,7 +103,9 @@\n \"\\n\",\n \"1. The user has the option of setting a common output directory for ALL problems using the `OPENMDAO_WORKDIR` environment variable. Thus there is a single directory that contains all OpenMDAO output data.\\n\",\n \"\\n\",\n- \"2. The [openmdao clean](om-command-clean) or `openmdao.api.clean_outputs` function can be used to remove these directories.\\n\"\n+ \"2. The [openmdao clean](om-command-clean) or `openmdao.api.clean_outputs` function can be used to remove these directories.\\n\",\n+ \"\\n\",\n+ \"As an alternative to setting `OPENMDAO_WORKDIR` to set the top level output directory for all problems, a user can set `work_dir` as an option of Problem in order to set the top level output directory under which that problem's `'{problem_name}_out'` directory will be placed. If provided, the value of the `work_dir` option takes precedence.\\n\"\n ]\n },\n {\n@@ -351,7 +353,7 @@\n \"metadata\": {\n \"celltoolbar\": \"Tags\",\n \"kernelspec\": {\n- \"display_name\": \"Python 3\",\n+ \"display_name\": \"py311\",\n \"language\": \"python\",\n \"name\": \"python3\"\n },\ndiff --git a/openmdao/utils/file_utils.py b/openmdao/utils/file_utils.py\nindex 96959fe4f..7461e9234 100644\n--- a/openmdao/utils/file_utils.py\n+++ b/openmdao/utils/file_utils.py\n@@ -433,7 +433,7 @@ def image2html(imagefile, title='', alt=''):\n \"\"\"\n \n \n-def get_work_dir():\n+def _get_work_dir():\n \"\"\"\n Return either os.getcwd() or the value of the OPENMDAO_WORKDIR environment variable.\n \n@@ -494,7 +494,7 @@ def _get_outputs_dir(obj, *subdirs, mkdir=True):\n \n prob_pathname = prob_meta['pathname']\n \n- work_dir = pathlib.Path(get_work_dir())\n+ work_dir = prob_meta['work_dir']\n if mkdir and not work_dir.exists():\n work_dir.mkdir(exist_ok=True)\n \n", "test_patch": "diff --git a/openmdao/core/tests/test_problem.py b/openmdao/core/tests/test_problem.py\nindex 8e2b39d8d..db8dc7534 100644\n--- a/openmdao/core/tests/test_problem.py\n+++ b/openmdao/core/tests/test_problem.py\n@@ -4,6 +4,7 @@ import pathlib\n import sys\n import unittest\n import itertools\n+import tempfile\n \n from io import StringIO\n import numpy as np\n@@ -19,7 +20,7 @@ import openmdao.utils.hooks as hooks\n from openmdao.utils.units import convert_units\n from openmdao.utils.om_warnings import DerivativesWarning, OMDeprecationWarning, OpenMDAOWarning\n from openmdao.utils.testing_utils import use_tempdirs, set_env_vars\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n from openmdao.utils.tests.test_hooks import hooks_active\n \n try:\n@@ -2231,6 +2232,28 @@ class TestProblem(unittest.TestCase):\n except RuntimeError:\n self.fail(\"'setup raised RuntimeError unexpectedly\")\n \n+ def test_set_work_dir(self):\n+\n+ with tempfile.TemporaryDirectory() as temp_dir_name:\n+ prob = om.Problem(name='prob_name', work_dir=temp_dir_name)\n+ model = prob.model\n+\n+ model.add_subsystem('comp', Paraboloid())\n+\n+ model.set_input_defaults('comp.x', 3.0)\n+ model.set_input_defaults('comp.y', -4.0)\n+\n+ with self.assertRaises(RuntimeError) as e:\n+ prob.get_outputs_dir()\n+\n+ self.assertEqual('The output directory cannot be accessed before setup.',\n+ str(e.exception))\n+\n+ prob.setup()\n+\n+ d = prob.get_outputs_dir('subdir')\n+ self.assertEqual(str(pathlib.Path(temp_dir_name, 'prob_name_out', 'subdir')), str(d))\n+\n def test_get_outputs_dir(self):\n \n prob = om.Problem(name='prob_name')\n@@ -2250,7 +2273,7 @@ class TestProblem(unittest.TestCase):\n prob.setup()\n \n d = prob.get_outputs_dir('subdir')\n- self.assertEqual(str(pathlib.Path(get_work_dir(), 'prob_name_out', 'subdir')), str(d))\n+ self.assertEqual(str(pathlib.Path(_get_work_dir(), 'prob_name_out', 'subdir')), str(d))\n \n def test_duplicate_prob_name(self):\n \ndiff --git a/openmdao/core/tests/test_system.py b/openmdao/core/tests/test_system.py\nindex 4a4b2d4a4..ad008bd13 100644\n--- a/openmdao/core/tests/test_system.py\n+++ b/openmdao/core/tests/test_system.py\n@@ -7,7 +7,7 @@ import numpy as np\n from openmdao.api import Problem, Group, IndepVarComp, ExecComp, ExplicitComponent\n from openmdao.utils.assert_utils import assert_near_equal, assert_warning, assert_warnings\n from openmdao.utils.testing_utils import use_tempdirs\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n \n \n @use_tempdirs\n@@ -694,7 +694,7 @@ class TestSystem(unittest.TestCase):\n prob.setup()\n \n d = prob.get_outputs_dir('subdir')\n- self.assertEqual(str(pathlib.Path(get_work_dir(), 'test_prob_name_out', 'subdir')), str(d))\n+ self.assertEqual(str(pathlib.Path(_get_work_dir(), 'test_prob_name_out', 'subdir')), str(d))\n \n \n if __name__ == \"__main__\":\ndiff --git a/openmdao/recorders/tests/test_distrib_sqlite_recorder.py b/openmdao/recorders/tests/test_distrib_sqlite_recorder.py\nindex 9fce3adb5..f9ad9115e 100644\n--- a/openmdao/recorders/tests/test_distrib_sqlite_recorder.py\n+++ b/openmdao/recorders/tests/test_distrib_sqlite_recorder.py\n@@ -12,7 +12,7 @@ from openmdao.utils.mpi import MPI\n import openmdao.api as om\n \n from openmdao.utils.array_utils import evenly_distrib_idxs\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n from openmdao.recorders.tests.sqlite_recorder_test_utils import \\\n assertDriverIterDataRecorded, assertProblemDataRecorded\n from openmdao.recorders.tests.recorder_test_utils import run_driver\n@@ -408,7 +408,7 @@ class DistributedRecorderTest(unittest.TestCase):\n \n def run_parallel():\n # process cases.sql in parallel\n- cr = om.CaseReader(os.path.join(get_work_dir(), 'test_record_on_one_proc_out/cases.sql'))\n+ cr = om.CaseReader(os.path.join(_get_work_dir(), 'test_record_on_one_proc_out/cases.sql'))\n \n cases = cr.list_cases()\n self.assertEqual(len(cases), 9)\ndiff --git a/openmdao/utils/tests/test_file_utils.py b/openmdao/utils/tests/test_file_utils.py\nindex be3f7218f..889514edf 100644\n--- a/openmdao/utils/tests/test_file_utils.py\n+++ b/openmdao/utils/tests/test_file_utils.py\n@@ -11,7 +11,7 @@ import sys\n \n import openmdao.api as om\n from openmdao.utils.testing_utils import use_tempdirs\n-from openmdao.utils.file_utils import get_work_dir\n+from openmdao.utils.file_utils import _get_work_dir\n from openmdao.core.problem import _clear_problem_names\n from openmdao.utils.reports_system import clear_reports\n \n@@ -62,14 +62,14 @@ class TestCleanOutputs(unittest.TestCase):\n with redirect_stdout(ss):\n om.clean_outputs(p1)\n \n- self.assertEqual(len(os.listdir(get_work_dir())), 1)\n+ self.assertEqual(len(os.listdir(_get_work_dir())), 1)\n \n # Now specify p2 with the output directory.\n ss = io.StringIO()\n with redirect_stdout(ss):\n om.clean_outputs(p2)\n \n- self.assertEqual(len(os.listdir(get_work_dir())), 0)\n+ self.assertEqual(len(os.listdir(_get_work_dir())), 0)\n \n def test_specify_non_output_dir_no_prompt(self):\n \n@@ -86,7 +86,7 @@ class TestCleanOutputs(unittest.TestCase):\n # First Test that a dryrun on '.' works as expected.\n ss = io.StringIO()\n cwd = os.getcwd()\n- os.chdir(get_work_dir())\n+ os.chdir(_get_work_dir())\n try:\n with redirect_stdout(ss):\n om.clean_outputs('.', dryrun=True)\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_args", "openmdao/core/tests/test_problem.py::TestProblem::test_check_totals_user_detect", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_0_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_1_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic_return_dict", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_cleanup", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_desvar", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_response", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_promoted", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_indep_var", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_input_output", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_alias_duplicate_errors", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_ellipses_slice_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_slice_with_negative_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output_as_input_err", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_prob_name", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_problem_name", "openmdao/core/tests/test_problem.py::TestProblem::test_error_msg_set_val_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_basic_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_cs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_compact", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_manual", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_suppress", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_user_detect_forced", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_slicer", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_list_driver_vars", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_not_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_petsc_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_inputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_residuals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_run_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_get_array", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps_auto", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_input_input", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_no_promote", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_set_deriv_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_get_outputs_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_exhaustive", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_before_final_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling_bounds", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_vars_deprecated", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_w_multi_constraints", "openmdao/core/tests/test_problem.py::TestProblem::test_post_final_setup_hook", "openmdao/core/tests/test_problem.py::TestProblem::test_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_relevance", "openmdao/core/tests/test_problem.py::TestProblem::test_run_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_run_with_invalid_prefix", "openmdao/core/tests/test_problem.py::TestProblem::test_set_2d_array", "openmdao/core/tests/test_problem.py::TestProblem::test_set_checks_shape", "openmdao/core/tests/test_problem.py::TestProblem::test_set_cs_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_set_work_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_simple_component_model_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_single_string_wrt_of", "openmdao/core/tests/test_problem.py::TestProblem::test_system_setup_and_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_two_var_single_string_error", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_duplicate_inputs", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_no_auto_ivc", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance2", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance3", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance4", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance5", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance_approx", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_cs_across_nested", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob_default_naming", "openmdao/core/tests/test_problem.py::SystemInTwoProblemsTestCase::test_2problems", "openmdao/core/tests/test_system.py::TestSystem::test_get_io_metadata", "openmdao/core/tests/test_system.py::TestSystem::test_get_outputs_dir", "openmdao/core/tests/test_system.py::TestSystem::test_group_modifies_model_options", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_before_final_setup", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_output_with_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_invalid_return_format", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_is_indep_is_des_var", "openmdao/core/tests/test_system.py::TestSystem::test_missing_source", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_override", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_set_all", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_with_filter", "openmdao/core/tests/test_system.py::TestSystem::test_record_residuals_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_recording_options_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_set_checks_shape", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_component", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_group", "openmdao/core/tests/test_system.py::TestSystem::test_vector_context_managers", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_multiple_paths", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_norecurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_pattern", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_recurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_no_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_prob"]}, {"instance_id": "openmdao__openmdao-3461", "base_commit": "160303f311abb94e3b5ec147360cdb7fef3923da", "gold_patch": "diff --git a/openmdao/core/problem.py b/openmdao/core/problem.py\nindex 67eb07195..ef93e82c0 100644\n--- a/openmdao/core/problem.py\n+++ b/openmdao/core/problem.py\n@@ -6,6 +6,7 @@ import shutil\n import sys\n import pprint\n import os\n+from copy import deepcopy\n import weakref\n import pathlib\n import textwrap\n@@ -1791,7 +1792,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n desvars = self.driver._designvars\n vals = self.driver.get_design_var_values(get_remote=True, driver_scaling=driver_scaling)\n if not driver_scaling:\n- desvars = desvars.copy()\n+ desvars = deepcopy(desvars)\n for meta in desvars.values():\n scaler = meta['scaler'] if meta.get('scaler') is not None else 1.\n adder = meta['adder'] if meta.get('adder') is not None else 0.\n@@ -1819,7 +1820,7 @@ class Problem(object, metaclass=ProblemMetaclass):\n cons = self.driver._cons\n vals = self.driver.get_constraint_values(driver_scaling=driver_scaling)\n if not driver_scaling:\n- cons = cons.copy()\n+ cons = deepcopy(cons)\n for meta in cons.values():\n scaler = meta['scaler'] if meta.get('scaler') is not None else 1.\n adder = meta['adder'] if meta.get('adder') is not None else 0.\n", "test_patch": "diff --git a/openmdao/core/tests/test_problem.py b/openmdao/core/tests/test_problem.py\nindex 8e2b39d8d..1d55fc76a 100644\n--- a/openmdao/core/tests/test_problem.py\n+++ b/openmdao/core/tests/test_problem.py\n@@ -1878,6 +1878,49 @@ class TestProblem(unittest.TestCase):\n # make sure the deprecated function still returns tha data\n self.assertEqual(set(prob_vars.keys()), {'constraints', 'design_vars', 'objectives'})\n \n+ def test_list_driver_vars_bounds_bug(self):\n+\n+ model = SellarDerivatives()\n+ model.nonlinear_solver = om.NonlinearBlockGS()\n+\n+ prob = om.Problem(model)\n+ prob.driver = om.ScipyOptimizeDriver()\n+ prob.driver.options['optimizer'] = 'SLSQP'\n+ prob.driver.options['tol'] = 1e-9\n+\n+ model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), scaler=2.0)\n+ model.add_objective('obj', scaler=0.1)\n+ model.add_constraint('con1', upper=1.0, scaler=7.0)\n+\n+ prob.setup()\n+ prob.run_driver()\n+\n+ info = prob.list_driver_vars(\n+ driver_scaling=False,\n+ desvar_opts=['lower', 'upper', 'scaler', 'adder'],\n+ cons_opts=['lower', 'upper', 'scaler', 'adder'],\n+ objs_opts=['scaler', 'adder'],\n+ )\n+\n+ upper = info['design_vars'][0][1]['upper']\n+ assert_near_equal(upper, np.array([10., 10.]))\n+\n+ upper = info['constraints'][0][1]['upper']\n+ assert_near_equal(upper, 1.0)\n+\n+ info = prob.list_driver_vars(\n+ driver_scaling=False,\n+ desvar_opts=['lower', 'upper', 'scaler', 'adder'],\n+ cons_opts=['lower', 'upper', 'scaler', 'adder'],\n+ objs_opts=['scaler', 'adder'],\n+ )\n+\n+ upper = info['design_vars'][0][1]['upper']\n+ assert_near_equal(upper, np.array([10., 10.]))\n+\n+ upper = info['constraints'][0][1]['upper']\n+ assert_near_equal(upper, 1.0)\n+\n def test_list_driver_vars_before_final_setup(self):\n prob = om.Problem()\n prob.model.add_subsystem('parab', Paraboloid(), promotes_inputs=['x', 'y'])\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_bounds_bug"]}], "all_FAIL_TO_PASS": ["openmdao/core/tests/test_problem.py::TestProblem::test_args", "openmdao/core/tests/test_problem.py::TestProblem::test_check_totals_user_detect", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_0_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_jacvec_product_1_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_basic_return_dict", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_cleanup", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_desvar", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_no_response", "openmdao/core/tests/test_problem.py::TestProblem::test_compute_totals_no_args_promoted", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_indep_var", "openmdao/core/tests/test_problem.py::TestProblem::test_configure_add_input_output", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_alias_duplicate_errors", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_ellipses_slice_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_constraint_slice_with_negative_as_indices", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output", "openmdao/core/tests/test_problem.py::TestProblem::test_design_var_connected_to_output_as_input_err", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_prob_name", "openmdao/core/tests/test_problem.py::TestProblem::test_duplicate_problem_name", "openmdao/core/tests/test_problem.py::TestProblem::test_error_msg_set_val_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_basic_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_cs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_compact", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_from_driver_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_manual", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_suppress", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_check_totals_user_detect_forced", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_slicer", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_array_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_diff_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_get_set_with_units_prom_plus_explicit_err", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_list_driver_vars", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_not_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_petsc_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_inputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_promoted_sellar_set_get_outputs", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_residuals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_run_driver", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_get_array", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_set_indeps_auto", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_compute_totals_scaled", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_input_input", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_no_promote", "openmdao/core/tests/test_problem.py::TestProblem::test_feature_simple_run_once_set_deriv_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_get_outputs_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_get_set_with_units_exhaustive", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_before_final_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_driver_scaling_bounds", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_vars_deprecated", "openmdao/core/tests/test_problem.py::TestProblem::test_list_problem_w_multi_constraints", "openmdao/core/tests/test_problem.py::TestProblem::test_post_final_setup_hook", "openmdao/core/tests/test_problem.py::TestProblem::test_post_setup_solver_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_relevance", "openmdao/core/tests/test_problem.py::TestProblem::test_run_before_setup", "openmdao/core/tests/test_problem.py::TestProblem::test_run_with_invalid_prefix", "openmdao/core/tests/test_problem.py::TestProblem::test_set_2d_array", "openmdao/core/tests/test_problem.py::TestProblem::test_set_checks_shape", "openmdao/core/tests/test_problem.py::TestProblem::test_set_cs_error_messages", "openmdao/core/tests/test_problem.py::TestProblem::test_set_work_dir", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_fwd", "openmdao/core/tests/test_problem.py::TestProblem::test_setup_bad_mode_direction_rev", "openmdao/core/tests/test_problem.py::TestProblem::test_simple_component_model_with_units", "openmdao/core/tests/test_problem.py::TestProblem::test_single_string_wrt_of", "openmdao/core/tests/test_problem.py::TestProblem::test_system_setup_and_configure", "openmdao/core/tests/test_problem.py::TestProblem::test_two_var_single_string_error", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_duplicate_inputs", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_list_indep_vars_no_auto_ivc", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance2", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance3", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance4", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance5", "openmdao/core/tests/test_problem.py::RelevanceTestCase::test_relevance_approx", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_cs_across_nested", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob", "openmdao/core/tests/test_problem.py::NestedProblemTestCase::test_nested_prob_default_naming", "openmdao/core/tests/test_problem.py::SystemInTwoProblemsTestCase::test_2problems", "openmdao/core/tests/test_system.py::TestSystem::test_get_io_metadata", "openmdao/core/tests/test_system.py::TestSystem::test_get_outputs_dir", "openmdao/core/tests/test_system.py::TestSystem::test_group_modifies_model_options", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_before_final_setup", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_output_with_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_invalid_return_format", "openmdao/core/tests/test_system.py::TestSystem::test_list_inputs_outputs_is_indep_is_des_var", "openmdao/core/tests/test_system.py::TestSystem::test_missing_source", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_override", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_set_all", "openmdao/core/tests/test_system.py::TestSystem::test_model_options_with_filter", "openmdao/core/tests/test_system.py::TestSystem::test_record_residuals_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_recording_options_includes_excludes", "openmdao/core/tests/test_system.py::TestSystem::test_set_checks_shape", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_component", "openmdao/core/tests/test_system.py::TestSystem::test_setup_check_group", "openmdao/core/tests/test_system.py::TestSystem::test_vector_context_managers", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_multiple_paths", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_norecurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_pattern", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_recurse", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_no_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_non_output_dir_prompt", "openmdao/utils/tests/test_file_utils.py::TestCleanOutputs::test_specify_prob", "openmdao/core/tests/test_problem.py::TestProblem::test_list_driver_vars_bounds_bug"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "openmdao__openmdao-3098_x2", "level": 2, "source": "swerebenchv2", "repo": "OpenMDAO/OpenMDAO", "image": "swerebenchv2/openmdao-openmdao:3098-157a109", "base_commit": "157a10944aa62cd88d7cb9566435055106892f8d", "num_bugs": 2, "bugs": [{"instance_id": "openmdao__openmdao-3098", "base_commit": "157a10944aa62cd88d7cb9566435055106892f8d", "gold_patch": "diff --git a/openmdao/drivers/scipy_optimizer.py b/openmdao/drivers/scipy_optimizer.py\nindex 49b890e18..1268bfe54 100644\n--- a/openmdao/drivers/scipy_optimizer.py\n+++ b/openmdao/drivers/scipy_optimizer.py\n@@ -25,7 +25,7 @@ _gradient_optimizers = {'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP', '\n 'trust-ncg', 'trust-constr', 'basinhopping', 'shgo'}\n _hessian_optimizers = {'trust-constr', 'trust-ncg'}\n _bounds_optimizers = {'L-BFGS-B', 'TNC', 'SLSQP', 'trust-constr', 'dual_annealing', 'shgo',\n- 'differential_evolution', 'basinhopping'}\n+ 'differential_evolution', 'basinhopping', 'Nelder-Mead'}\n if Version(scipy_version) >= Version(\"1.11\"):\n # COBYLA supports bounds starting with SciPy Version 1.11\n _bounds_optimizers |= {'COBYLA'}\n", "test_patch": "diff --git a/openmdao/drivers/tests/test_scipy_optimizer.py b/openmdao/drivers/tests/test_scipy_optimizer.py\nindex 5330e3aba..a60df5f56 100644\n--- a/openmdao/drivers/tests/test_scipy_optimizer.py\n+++ b/openmdao/drivers/tests/test_scipy_optimizer.py\n@@ -2224,6 +2224,42 @@ class TestScipyOptimizeDriver(unittest.TestCase):\n assert_near_equal(p.get_val('exec.z')[0], 25)\n assert_near_equal(p.get_val('exec.z')[50], -75)\n \n+ def test_nelder_mead_bounded(self):\n+\n+ class dummy_function(om.ExplicitComponent):\n+ def setup(self):\n+ self.add_input('x', val=0.)\n+ self.add_output('y', val=0.)\n+\n+ def compute(self, inputs, outputs):\n+ x = inputs['x']\n+\n+ outputs['y'] = 2*x + 1\n+\n+ model = om.Group()\n+ model.add_subsystem('dummy_function',\n+ dummy_function(),\n+ promotes=['*'])\n+ prob = om.Problem(model=model)\n+\n+ model.add_objective('y')\n+ model.add_design_var('x', lower=0, upper=100)\n+ model.set_input_defaults('x', 25)\n+\n+ driver = prob.driver = om.ScipyOptimizeDriver()\n+ driver.options[\"optimizer\"] = 'Nelder-Mead'\n+\n+ driver.options['debug_print'] = ['desvars',\n+ 'nl_cons', 'ln_cons', 'objs', 'totals']\n+\n+ prob.setup()\n+\n+ prob.run_driver()\n+\n+ y_out = prob.get_val('y')\n+\n+ assert_near_equal(y_out, 1.0, tolerance=1.0E-3)\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["openmdao/drivers/tests/test_scipy_optimizer.py::TestScipyOptimizeDriver::test_nelder_mead_bounded"]}, {"instance_id": "openmdao__openmdao-3117", "base_commit": "e093a00f61fbda25c17d24658522f2c7a7e2dc53", "gold_patch": "diff --git a/openmdao/core/component.py b/openmdao/core/component.py\nindex bf56bbd27..8f34070dc 100644\n--- a/openmdao/core/component.py\n+++ b/openmdao/core/component.py\n@@ -386,7 +386,7 @@ class Component(System):\n \n def _get_missing_partials(self, missing):\n \"\"\"\n- Return a list of (of, wrt) tuples for which derivatives have not been declared.\n+ Provide (of, wrt) tuples for which derivatives have not been declared in the component.\n \n Parameters\n ----------\ndiff --git a/openmdao/core/driver.py b/openmdao/core/driver.py\nindex 68347a26c..f48048433 100644\n--- a/openmdao/core/driver.py\n+++ b/openmdao/core/driver.py\n@@ -8,6 +8,7 @@ import weakref\n \n import numpy as np\n \n+from openmdao.core.group import Group\n from openmdao.core.total_jac import _TotalJacInfo\n from openmdao.core.constants import INT_DTYPE, _SetupStatus\n from openmdao.recorders.recording_manager import RecordingManager\n@@ -949,6 +950,13 @@ class Driver(object):\n return\n \n problem = self._problem()\n+\n+ # Do not perform this check if any subgroup uses approximated partials.\n+ # This causes the relevance graph to be invalid.\n+ for system in problem.model.system_iter(include_self=True, recurse=True, typ=Group):\n+ if system._has_approx:\n+ return\n+\n relevant = problem.model._relevant\n fwd = problem._mode == 'fwd'\n \ndiff --git a/openmdao/core/group.py b/openmdao/core/group.py\nindex 0839e0f0e..9eea60b42 100644\n--- a/openmdao/core/group.py\n+++ b/openmdao/core/group.py\n@@ -4026,13 +4026,15 @@ class Group(System):\n \n def _get_missing_partials(self, missing):\n \"\"\"\n- Return a list of (of, wrt) tuples for which derivatives have not been declared.\n+ Provide (of, wrt) tuples for which derivatives have not been declared in the system.\n \n Parameters\n ----------\n missing : dict\n Dictionary containing list of missing derivatives keyed by system pathname.\n \"\"\"\n+ if self._has_approx:\n+ return\n for subsys in self._subsystems_myproc:\n subsys._get_missing_partials(missing)\n \ndiff --git a/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb b/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb\nindex 4e3d8c11a..bc565d584 100644\n--- a/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb\n+++ b/openmdao/docs/openmdao_book/features/core_features/working_with_derivatives/approximating_totals.ipynb\n@@ -325,6 +325,88 @@\n \"\\n\",\n \"assert_near_equal(derivs['z', 'x'], np.array([[300.]]), tolerance=1e-8)\"\n ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"id\": \"f9510c93\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"(approx_totals_relevance)=\\n\",\n+ \"## Approx-Totals and Relevance\\n\",\n+ \"\\n\",\n+ \"OpenMDAO builds a relevancy-graph that helps it be more efficient when executing complex models.\\n\",\n+ \"\\n\",\n+ \"One feature that uses this graph is the `relevance check` that is performed when a Driver begins to run.\\n\",\n+ \"The relevance check is used to verify that each constraint can be impacted by a design variable.\\n\",\n+ \"\\n\",\n+ \"However, when `approx_totals` is used, users often omit the declaration of any partials.\\n\",\n+ \"In this situation, the relevance check would normally fail, so OpenMDAO skips this check if any Group\\n\",\n+ \"in the system tree is found to use approximated derivatives.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"id\": \"bb70c742\",\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"import numpy as np\\n\",\n+ \"\\n\",\n+ \"import openmdao.api as om\\n\",\n+ \"\\n\",\n+ \"class AComp(om.ExplicitComponent):\\n\",\n+ \"\\n\",\n+ \" def setup(self):\\n\",\n+ \" self.add_input('x', val=0.0)\\n\",\n+ \" self.add_output('y', val=0.0)\\n\",\n+ \"\\n\",\n+ \" def compute(self, inputs, outputs):\\n\",\n+ \" outputs['y'] = inputs['x'] - 5.0\\n\",\n+ \"\\n\",\n+ \"class BComp(om.ExplicitComponent):\\n\",\n+ \"\\n\",\n+ \" def setup(self):\\n\",\n+ \" self.add_input('y', val=0.0)\\n\",\n+ \" self.add_output('z', val=0.0)\\n\",\n+ \"\\n\",\n+ \" def compute(self, inputs, outputs):\\n\",\n+ \" outputs['z'] = inputs['y'] ** 2\\n\",\n+ \"\\n\",\n+ \"prob = om.Problem()\\n\",\n+ \"prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP')\\n\",\n+ \"model = prob.model\\n\",\n+ \"model.set_input_defaults('x', 0.0)\\n\",\n+ \"\\n\",\n+ \"model.add_subsystem('a', AComp(), promotes=['x', 'y'])\\n\",\n+ \"model.add_subsystem('b', BComp(), promotes=['y', 'z'])\\n\",\n+ \"\\n\",\n+ \"model.add_design_var('x', lower=-100, upper=100)\\n\",\n+ \"model.add_objective('z')\\n\",\n+ \"\\n\",\n+ \"model.approx_totals(method='cs')\\n\",\n+ \"\\n\",\n+ \"prob.setup()\\n\",\n+ \"prob.run_driver()\\n\",\n+ \"\\n\",\n+ \"of = ['z']\\n\",\n+ \"wrt = ['x']\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"id\": \"d9c771d4\",\n+ \"metadata\": {\n+ \"tags\": [\n+ \"remove-input\",\n+ \"remove-output\"\n+ ]\n+ },\n+ \"outputs\": [],\n+ \"source\": [\n+ \"assert_near_equal(prob.get_val('x'), 5.0)\"\n+ ]\n }\n ],\n \"metadata\": {\n@@ -344,7 +426,7 @@\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython3\",\n- \"version\": \"3.8.10\"\n+ \"version\": \"3.11.4\"\n },\n \"orphan\": true\n },\ndiff --git a/openmdao/drivers/pyoptsparse_driver.py b/openmdao/drivers/pyoptsparse_driver.py\nindex 0f87c1f97..3a28fb306 100644\n--- a/openmdao/drivers/pyoptsparse_driver.py\n+++ b/openmdao/drivers/pyoptsparse_driver.py\n@@ -25,6 +25,7 @@ except Exception as err:\n from openmdao.core.constants import INT_DTYPE, _DEFAULT_REPORTS_DIR, _ReprClass\n from openmdao.core.analysis_error import AnalysisError\n from openmdao.core.driver import Driver, RecordingDebugging\n+from openmdao.core.group import Group\n from openmdao.utils.class_util import WeakMethodWrapper\n from openmdao.utils.mpi import FakeComm, MPI\n from openmdao.utils.om_warnings import issue_warning, warn_deprecation\n@@ -838,9 +839,13 @@ class pyOptSparseDriver(Driver):\n \n # First time through, check for zero row/col.\n if self._check_jac and self._total_jac is not None:\n- raise_error = self.options['singular_jac_behavior'] == 'error'\n- self._total_jac.check_total_jac(raise_error=raise_error,\n- tol=self.options['singular_jac_tol'])\n+ for subsys in model.system_iter(include_self=True, recurse=True, typ=Group):\n+ if subsys._has_approx:\n+ break\n+ else:\n+ raise_error = self.options['singular_jac_behavior'] == 'error'\n+ self._total_jac.check_total_jac(raise_error=raise_error,\n+ tol=self.options['singular_jac_tol'])\n self._check_jac = False\n \n # Let the optimizer try to handle the error\ndiff --git a/openmdao/drivers/scipy_optimizer.py b/openmdao/drivers/scipy_optimizer.py\nindex 1268bfe54..45f3f3bab 100644\n--- a/openmdao/drivers/scipy_optimizer.py\n+++ b/openmdao/drivers/scipy_optimizer.py\n@@ -11,6 +11,7 @@ from scipy.optimize import minimize\n \n from openmdao.core.constants import INF_BOUND\n from openmdao.core.driver import Driver, RecordingDebugging\n+from openmdao.core.group import Group\n from openmdao.utils.class_util import WeakMethodWrapper\n from openmdao.utils.mpi import MPI\n \n@@ -719,6 +720,9 @@ class ScipyOptimizeDriver(Driver):\n ndarray\n Gradient of objective with respect to input array.\n \"\"\"\n+ prob = self._problem()\n+ model = prob.model\n+\n try:\n grad = self._compute_totals(of=self._obj_and_nlcons, wrt=self._dvlist,\n return_format=self._total_jac_format)\n@@ -726,9 +730,13 @@ class ScipyOptimizeDriver(Driver):\n \n # First time through, check for zero row/col.\n if self._check_jac and self._total_jac is not None:\n- raise_error = self.options['singular_jac_behavior'] == 'error'\n- self._total_jac.check_total_jac(raise_error=raise_error,\n- tol=self.options['singular_jac_tol'])\n+ for subsys in model.system_iter(include_self=True, recurse=True, typ=Group):\n+ if subsys._has_approx:\n+ break\n+ else:\n+ raise_error = self.options['singular_jac_behavior'] == 'error'\n+ self._total_jac.check_total_jac(raise_error=raise_error,\n+ tol=self.options['singular_jac_tol'])\n self._check_jac = False\n \n except Exception as msg:\n", "test_patch": "diff --git a/openmdao/core/tests/test_semitotals.py b/openmdao/core/tests/test_semitotals.py\nindex a4508b63f..c75f46f45 100644\n--- a/openmdao/core/tests/test_semitotals.py\n+++ b/openmdao/core/tests/test_semitotals.py\n@@ -199,6 +199,7 @@ class FakeGeomComp(om.ExplicitComponent):\n \n def initialize(self):\n self.options.declare(\"n\", types=int)\n+ self.options.declare('declare_partials', types=(bool,), default=True)\n \n def setup(self):\n n = self.options[\"n\"]\n@@ -206,7 +207,8 @@ class FakeGeomComp(om.ExplicitComponent):\n self.add_input(\"feather\", val=0.0, units=\"deg\")\n self.add_output(\"x\", val=np.zeros(n), units=\"m\")\n \n- self.declare_partials(\"*\", \"*\", method=\"fd\")\n+ if self.options['declare_partials']:\n+ self.declare_partials(\"*\", \"*\", method=\"fd\")\n \n self._counter = 0\n \n@@ -222,6 +224,7 @@ class FakeAeroComp(om.ExplicitComponent):\n \n def initialize(self):\n self.options.declare(\"n\", types=int)\n+ self.options.declare('declare_partials', types=(bool,), default=True)\n \n def setup(self):\n n = self.options[\"n\"]\n@@ -232,7 +235,8 @@ class FakeAeroComp(om.ExplicitComponent):\n self.add_output(\"CT\", val=0.5)\n self.add_output(\"CP\", val=0.5)\n \n- self.declare_partials(\"*\", \"*\", method=\"fd\")\n+ if self.options['declare_partials']:\n+ self.declare_partials(\"*\", \"*\", method=\"fd\")\n \n self._counter = 0\n \n@@ -251,15 +255,19 @@ class GeometryAndAero2(om.Group):\n self.options.declare(\"n\", types=int)\n self.options.declare(\"rho\", types=float)\n self.options.declare(\"vinf\", types=float)\n+ self.options.declare('declare_partials', types=(bool,), default=True)\n \n def setup(self):\n n = self.options[\"n\"]\n+ dp = self.options['declare_partials']\n \n comp = self.add_subsystem(\"init_geom\", om.IndepVarComp(), promotes_outputs=[\"x0\"])\n comp.add_output(\"x0\", val=np.arange(n) + 1.0, units=\"m\")\n \n- self.add_subsystem(\"geom\", FakeGeomComp(n=n), promotes_inputs=[\"x0\", \"feather\"], promotes_outputs=[\"x\"])\n- self.add_subsystem(\"aero\", FakeAeroComp(n=n), promotes_inputs=[\"x\", \"omega\"], promotes_outputs=[\"CT\", \"CP\"])\n+ self.add_subsystem(\"geom\", FakeGeomComp(n=n, declare_partials=dp),\n+ promotes_inputs=[\"x0\", \"feather\"], promotes_outputs=[\"x\"])\n+ self.add_subsystem(\"aero\", FakeAeroComp(n=n, declare_partials=dp),\n+ promotes_inputs=[\"x\", \"omega\"], promotes_outputs=[\"CT\", \"CP\"])\n \n def reset_count(self):\n self.geom._counter = 0\n@@ -310,3 +318,45 @@ class TestSemiTotalsNumCalls(unittest.TestCase):\n assert_check_totals(data, atol=1e-6, rtol=1e-6)\n \n self.assertEqual(geom_and_aero.geom._counter, 4)\n+\n+ def test_check_relevance_approx_totals(self):\n+\n+ size = 10\n+ rho = 1.17573\n+ minf = 0.111078231621482\n+ speedofsound = 344.5760217432\n+ vinf = minf*speedofsound\n+\n+ prob = om.Problem()\n+ prob.driver = om.ScipyOptimizeDriver()\n+ prob.driver.options[\"optimizer\"] = \"SLSQP\"\n+\n+ omega = 7199.759242*2*np.pi/60\n+ ivc = prob.model.add_subsystem(\"ivc\", om.IndepVarComp(), promotes_outputs=[\"*\"])\n+ ivc.add_output(\"feather\", val=0.0, units=\"deg\")\n+ ivc.add_output(\"omega\", val=omega, units=\"rad/s\")\n+\n+ geom_and_aero = prob.model.add_subsystem('geom_and_aero',\n+ GeometryAndAero2(n=size, rho=rho, vinf=vinf, declare_partials=False),\n+ promotes_inputs=[\"feather\", \"omega\"],\n+ promotes_outputs=[\"CT\", \"CP\"])\n+ geom_and_aero.approx_totals(step=step, step_calc=\"abs\", method=\"fd\", form=\"forward\")\n+\n+ prob.model.add_design_var(\"feather\", lower=-5.0, upper=25.0, units=\"deg\", ref=1.0)\n+ prob.model.add_design_var(\"omega\", lower=3000*2*np.pi/60, upper=7500*2*np.pi/60, units=\"rad/s\", ref=1.0)\n+ prob.model.add_objective(\"CP\", ref=1e0)\n+ prob.model.add_constraint(\"CT\", lower=0.0)\n+\n+ prob.setup(force_alloc_complex=False)\n+\n+ omega = (6245.096992023524*2*np.pi/60) + step\n+ feather = 0.6362159381168669\n+ prob.set_val(\"omega\", omega, units=\"rad/s\")\n+ prob.set_val(\"feather\", feather, units=\"deg\")\n+ fail = prob.run_driver()\n+\n+ self.assertEqual(fail, False)\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", "FAIL_TO_PASS": ["openmdao/core/tests/test_semitotals.py::TestSemiTotalsNumCalls::test_check_relevance_approx_totals"]}], "all_FAIL_TO_PASS": ["openmdao/drivers/tests/test_scipy_optimizer.py::TestScipyOptimizeDriver::test_nelder_mead_bounded", "openmdao/core/tests/test_semitotals.py::TestSemiTotalsNumCalls::test_check_relevance_approx_totals"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cs-si__eodag-790_x2", "level": 2, "source": "swerebenchv2", "repo": "CS-SI/eodag", "image": "swerebenchv2/cs-si-eodag:790-9acf017", "base_commit": "9acf017451f71c5488011f3add086a9936cfffc8", "num_bugs": 2, "bugs": [{"instance_id": "cs-si__eodag-790", "base_commit": "9acf017451f71c5488011f3add086a9936cfffc8", "gold_patch": "diff --git a/eodag/api/core.py b/eodag/api/core.py\nindex 0d589122..9b394f4a 100644\n--- a/eodag/api/core.py\n+++ b/eodag/api/core.py\n@@ -832,6 +832,7 @@ class EODataAccessGateway(object):\n end=None,\n geom=None,\n locations=None,\n+ provider=None,\n **kwargs,\n ):\n \"\"\"Look for products matching criteria on known providers.\n@@ -877,6 +878,9 @@ class EODataAccessGateway(object):\n :type locations: dict\n :param kwargs: Some other criteria that will be used to do the search,\n using paramaters compatibles with the provider\n+ :param provider: (optional) the provider to be used, if not set, the configured\n+ default provider will be used\n+ :type provider: str\n :type kwargs: Union[int, str, bool, dict]\n :returns: A collection of EO products matching the criteria and the total\n number of results found\n@@ -888,7 +892,12 @@ class EODataAccessGateway(object):\n enforced here.\n \"\"\"\n search_kwargs = self._prepare_search(\n- start=start, end=end, geom=geom, locations=locations, **kwargs\n+ start=start,\n+ end=end,\n+ geom=geom,\n+ locations=locations,\n+ provider=provider,\n+ **kwargs,\n )\n search_plugins = search_kwargs.pop(\"search_plugins\", [])\n if search_kwargs.get(\"id\"):\n@@ -899,7 +908,9 @@ class EODataAccessGateway(object):\n )\n # remove auth from search_kwargs as a loop over providers will be performed\n search_kwargs.pop(\"auth\", None)\n- return self._search_by_id(search_kwargs.pop(\"id\"), **search_kwargs)\n+ return self._search_by_id(\n+ search_kwargs.pop(\"id\"), provider=provider, **search_kwargs\n+ )\n search_kwargs.update(\n page=page,\n items_per_page=items_per_page,\n@@ -1254,12 +1265,16 @@ class EODataAccessGateway(object):\n of EO products retrieved (0 or 1)\n :rtype: tuple(:class:`~eodag.api.search_result.SearchResult`, int)\n \"\"\"\n+ if not provider:\n+ provider = self.get_preferred_provider()[0]\n get_search_plugins_kwargs = dict(\n provider=provider, product_type=kwargs.get(\"productType\", None)\n )\n- for plugin in self._plugins_manager.get_search_plugins(\n+ search_plugins = self._plugins_manager.get_search_plugins(\n **get_search_plugins_kwargs\n- ):\n+ )\n+\n+ for plugin in search_plugins:\n logger.info(\n \"Searching product with id '%s' on provider: %s\", uid, plugin.provider\n )\n@@ -1294,7 +1309,7 @@ class EODataAccessGateway(object):\n return SearchResult([]), 0\n \n def _prepare_search(\n- self, start=None, end=None, geom=None, locations=None, **kwargs\n+ self, start=None, end=None, geom=None, locations=None, provider=None, **kwargs\n ):\n \"\"\"Internal method to prepare the search kwargs and get the search\n and auth plugins.\n@@ -1323,6 +1338,9 @@ class EODataAccessGateway(object):\n :type geom: Union[str, dict, shapely.geometry.base.BaseGeometry]\n :param locations: (optional) Location filtering by name using locations configuration\n :type locations: dict\n+ :param provider: provider to be used, if no provider is given or the product type\n+ is not available for the provider, the preferred provider is used\n+ :type provider: str\n :param kwargs: Some other criteria\n * id and/or a provider for a search by\n * search criteria to guess the product type\n@@ -1400,15 +1418,23 @@ class EODataAccessGateway(object):\n ):\n search_plugins.append(plugin)\n \n- if search_plugins[0].provider != self.get_preferred_provider()[0]:\n+ if not provider:\n+ provider = self.get_preferred_provider()[0]\n+ providers = [plugin.provider for plugin in search_plugins]\n+ if provider not in providers:\n logger.warning(\n \"Product type '%s' is not available with provider '%s'. \"\n \"Searching it on provider '%s' instead.\",\n product_type,\n- self.get_preferred_provider()[0],\n+ provider,\n search_plugins[0].provider,\n )\n else:\n+ provider_plugin = list(\n+ filter(lambda p: p.provider == provider, search_plugins)\n+ )[0]\n+ search_plugins.remove(provider_plugin)\n+ search_plugins.insert(0, provider_plugin)\n logger.info(\n \"Searching product type '%s' on provider: %s\",\n product_type,\n@@ -1440,9 +1466,6 @@ class EODataAccessGateway(object):\n # Remove the ID since this is equal to productType.\n search_plugin.config.product_type_config.pop(\"ID\", None)\n \n- logger.debug(\n- \"Using plugin class for search: %s\", search_plugin.__class__.__name__\n- )\n auth_plugin = self._plugins_manager.get_auth_plugin(search_plugin.provider)\n auth_plugins[search_plugin.provider] = auth_plugin\n \n@@ -1493,6 +1516,7 @@ class EODataAccessGateway(object):\n \n results = SearchResult([])\n total_results = 0\n+\n try:\n if \"auth\" in kwargs:\n if isinstance(kwargs[\"auth\"], dict):\n@@ -1586,6 +1610,7 @@ class EODataAccessGateway(object):\n pass\n else:\n eo_product.product_type = guesses[0]\n+\n if eo_product.search_intersection is not None:\n download_plugin = self._plugins_manager.get_download_plugin(\n eo_product\ndiff --git a/eodag/plugins/authentication/token.py b/eodag/plugins/authentication/token.py\nindex b1032426..377268c7 100644\n--- a/eodag/plugins/authentication/token.py\n+++ b/eodag/plugins/authentication/token.py\n@@ -15,19 +15,28 @@\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n+import logging\n \n import requests\n from requests import RequestException\n+from requests.adapters import HTTPAdapter\n+from urllib3 import Retry\n \n from eodag.plugins.authentication.base import Authentication\n from eodag.utils import USER_AGENT, RequestsTokenAuth\n from eodag.utils.exceptions import AuthenticationError, MisconfiguredError\n from eodag.utils.stac_reader import HTTP_REQ_TIMEOUT\n \n+logger = logging.getLogger(\"eodag.authentication.token\")\n+\n \n class TokenAuth(Authentication):\n \"\"\"TokenAuth authentication plugin\"\"\"\n \n+ def __init__(self, provider, config):\n+ super(TokenAuth, self).__init__(provider, config)\n+ self.token = \"\"\n+\n def validate_config_credentials(self):\n \"\"\"Validate configured credentials\"\"\"\n super(TokenAuth, self).validate_config_credentials()\n@@ -56,10 +65,15 @@ class TokenAuth(Authentication):\n if hasattr(self.config, \"headers\")\n else {\"headers\": USER_AGENT}\n )\n+ s = requests.Session()\n+ retries = Retry(\n+ total=3, backoff_factor=2, status_forcelist=[401, 429, 500, 502, 503, 504]\n+ )\n+ s.mount(self.config.auth_uri, HTTPAdapter(max_retries=retries))\n try:\n # First get the token\n if getattr(self.config, \"request_method\", \"POST\") == \"POST\":\n- response = requests.post(\n+ response = s.post(\n self.config.auth_uri,\n data=self.config.credentials,\n timeout=HTTP_REQ_TIMEOUT,\n@@ -67,7 +81,7 @@ class TokenAuth(Authentication):\n )\n else:\n cred = self.config.credentials\n- response = requests.get(\n+ response = s.get(\n self.config.auth_uri,\n auth=(cred[\"username\"], cred[\"password\"]),\n timeout=HTTP_REQ_TIMEOUT,\n@@ -84,11 +98,21 @@ class TokenAuth(Authentication):\n token = response.json()[self.config.token_key]\n else:\n token = response.text\n+ headers = self._get_headers(token)\n+ self.token = token\n # Return auth class set with obtained token\n- return RequestsTokenAuth(token, \"header\", headers=self._get_headers(token))\n+ return RequestsTokenAuth(token, \"header\", headers=headers)\n \n def _get_headers(self, token):\n headers = self.config.headers\n if \"Authorization\" in headers and \"$\" in headers[\"Authorization\"]:\n headers[\"Authorization\"] = headers[\"Authorization\"].replace(\"$token\", token)\n+ if (\n+ self.token\n+ and token != self.token\n+ and self.token in headers[\"Authorization\"]\n+ ):\n+ headers[\"Authorization\"] = headers[\"Authorization\"].replace(\n+ self.token, token\n+ )\n return headers\ndiff --git a/eodag/plugins/download/base.py b/eodag/plugins/download/base.py\nindex dce4db23..1e040cef 100644\n--- a/eodag/plugins/download/base.py\n+++ b/eodag/plugins/download/base.py\n@@ -373,7 +373,7 @@ class Download(PluginTopic):\n shutil.move(extraction_dir, outputs_dir)\n \n elif fs_path.endswith(\".tar.gz\"):\n- with tarfile.open(fs_path, \"r:gz\") as zfile:\n+ with tarfile.open(fs_path, \"r\") as zfile:\n progress_callback.reset(total=1)\n zfile.extractall(path=extraction_dir)\n progress_callback(1)\ndiff --git a/eodag/plugins/search/data_request_search.py b/eodag/plugins/search/data_request_search.py\nindex 1f6c586e..0bf2b043 100644\n--- a/eodag/plugins/search/data_request_search.py\n+++ b/eodag/plugins/search/data_request_search.py\n@@ -11,6 +11,7 @@ from eodag.api.product.metadata_mapping import (\n )\n from eodag.plugins.search.base import Search\n from eodag.utils import GENERIC_PRODUCT_TYPE, string_to_jsonpath\n+from eodag.utils.exceptions import RequestError\n \n logger = logging.getLogger(\"eodag.search.data_request_search\")\n \n@@ -91,10 +92,9 @@ class DataRequestSearch(Search):\n metadata = requests.get(metadata_url, headers=headers)\n metadata.raise_for_status()\n except requests.RequestException:\n- logger.error(\n- \"metadata for product_type %s could not be retrieved\", product_type\n+ raise RequestError(\n+ f\"metadata for product_type {product_type} could not be retrieved\"\n )\n- raise\n else:\n try:\n url = self.config.data_request_url\n@@ -107,11 +107,8 @@ class DataRequestSearch(Search):\n request_job = requests.post(url, json=request_body, headers=headers)\n request_job.raise_for_status()\n except requests.RequestException as e:\n- logger.error(\n- \"search job for product_type %s could not be created: %s, %s\",\n- product_type,\n- str(e),\n- request_job.text,\n+ raise RequestError(\n+ f\"search job for product_type {product_type} could not be created: {str(e)}, {request_job.text}\"\n )\n else:\n logger.info(\"search job for product_type %s created\", product_type)\n@@ -122,13 +119,11 @@ class DataRequestSearch(Search):\n status_url = self.config.status_url + data_request_id\n status_data = requests.get(status_url, headers=self.auth.headers).json()\n if \"status_code\" in status_data and status_data[\"status_code\"] == 403:\n- logger.error(\"authentication token expired during request\")\n- raise requests.RequestException\n+ raise RequestError(\"authentication token expired during request\")\n if status_data[\"status\"] == \"failed\":\n- logger.error(\n- \"data request job has failed, message: %s\", status_data[\"message\"]\n+ raise RequestError(\n+ f\"data request job has failed, message: {status_data['message']}\"\n )\n- raise requests.RequestException\n return status_data[\"status\"] == \"completed\"\n \n def _get_result_data(self, data_request_id):\ndiff --git a/eodag/rest/server.py b/eodag/rest/server.py\nindex 0c9ecbda..57cc4381 100755\n--- a/eodag/rest/server.py\n+++ b/eodag/rest/server.py\n@@ -233,12 +233,13 @@ async def handle_resource_not_found(request: Request, error):\n \n @app.exception_handler(AuthenticationError)\n async def handle_auth_error(request: Request, error):\n- \"\"\"Unauthorized [401] errors handle\"\"\"\n+ \"\"\"AuthenticationError should be sent as internal server error to the client\"\"\"\n+ logger.error(f\"{type(error).__name__}: {str(error)}\")\n return await default_exception_handler(\n request,\n HTTPException(\n- status_code=401,\n- detail=f\"{type(error).__name__}: {str(error)}\",\n+ status_code=500,\n+ detail=\"Internal server error: please contact the administrator\",\n ),\n )\n \n@@ -409,12 +410,9 @@ def stac_collections_item_download(collection_id, item_id, request: Request):\n body = {}\n arguments = dict(request.query_params, **body)\n provider = arguments.pop(\"provider\", None)\n- zipped = \"True\"\n- if \"zip\" in arguments:\n- zipped = arguments[\"zip\"]\n \n return download_stac_item_by_id_stream(\n- catalogs=[collection_id], item_id=item_id, provider=provider, zip=zipped\n+ catalogs=[collection_id], item_id=item_id, provider=provider\n )\n \n \ndiff --git a/eodag/rest/stac.py b/eodag/rest/stac.py\nindex 6e8fcbe5..afbcbce1 100644\n--- a/eodag/rest/stac.py\n+++ b/eodag/rest/stac.py\n@@ -83,9 +83,6 @@ class StacCommon(object):\n \n self.data = {}\n \n- if self.provider and self.eodag_api.get_preferred_provider() != self.provider:\n- self.eodag_api.set_preferred_provider(self.provider)\n-\n def update_data(self, data):\n \"\"\"Updates data using given input STAC dict data\n \ndiff --git a/eodag/rest/utils.py b/eodag/rest/utils.py\nindex afa872ae..8fbda850 100644\n--- a/eodag/rest/utils.py\n+++ b/eodag/rest/utils.py\n@@ -393,6 +393,10 @@ def search_products(product_type, arguments, stac_formatted=True):\n \n try:\n arg_product_type = arguments.pop(\"product_type\", None)\n+ provider = arguments.pop(\"provider\", None)\n+ if not provider:\n+ provider = eodag_api.get_preferred_provider()[0]\n+\n unserialized = arguments.pop(\"unserialized\", None)\n \n page, items_per_page = get_pagination_info(arguments)\n@@ -407,6 +411,7 @@ def search_products(product_type, arguments, stac_formatted=True):\n \"start\": dtstart,\n \"end\": dtend,\n \"geom\": geom,\n+ \"provider\": provider,\n }\n \n if stac_formatted:\n@@ -455,20 +460,24 @@ def search_products(product_type, arguments, stac_formatted=True):\n return response\n \n \n-def search_product_by_id(uid, product_type=None):\n+def search_product_by_id(uid, product_type=None, provider=None):\n \"\"\"Search a product by its id\n \n :param uid: The uid of the EO product\n :type uid: str\n :param product_type: (optional) The product type\n :type product_type: str\n+ :param provider: (optional) The provider to be used\n+ :type provider: str\n :returns: A search result\n :rtype: :class:`~eodag.api.search_result.SearchResult`\n :raises: :class:`~eodag.utils.exceptions.ValidationError`\n :raises: RuntimeError\n \"\"\"\n try:\n- products, total = eodag_api.search(id=uid, productType=product_type)\n+ products, total = eodag_api.search(\n+ id=uid, productType=product_type, provider=provider\n+ )\n return products\n except ValidationError:\n raise\n@@ -573,7 +582,7 @@ def get_stac_item_by_id(url, item_id, catalogs, root=\"/\", provider=None):\n return None\n \n \n-def download_stac_item_by_id_stream(catalogs, item_id, provider=None, zip=\"True\"):\n+def download_stac_item_by_id_stream(catalogs, item_id, provider=None):\n \"\"\"Download item\n \n :param catalogs: Catalogs list (only first is used as product_type)\n@@ -587,17 +596,16 @@ def download_stac_item_by_id_stream(catalogs, item_id, provider=None, zip=\"True\"\n :returns: a stream of the downloaded data (either as a zip or the individual assets)\n :rtype: StreamingResponse\n \"\"\"\n- if provider:\n- eodag_api.set_preferred_provider(provider)\n-\n- product = search_product_by_id(item_id, product_type=catalogs[0])[0]\n-\n+ product = search_product_by_id(\n+ item_id, product_type=catalogs[0], provider=provider\n+ )[0]\n if product.downloader is None:\n download_plugin = eodag_api._plugins_manager.get_download_plugin(product)\n auth_plugin = eodag_api._plugins_manager.get_auth_plugin(\n download_plugin.provider\n )\n product.register_downloader(download_plugin, auth_plugin)\n+\n auth = (\n product.downloader_auth.authenticate()\n if product.downloader_auth is not None\n@@ -664,7 +672,7 @@ def get_stac_catalogs(url, root=\"/\", catalogs=[], provider=None, fetch_providers\n :param fetch_providers: (optional) Whether to fetch providers for new product\n types or not\n :type fetch_providers: bool\n- :returns: Catalog dictionnary\n+ :returns: Catalog dictionary\n :rtype: dict\n \"\"\"\n return StacCatalog(\n@@ -734,10 +742,10 @@ def search_stac_items(url, arguments, root=\"/\", catalogs=[], provider=None):\n ids = [ids]\n if ids:\n search_results = SearchResult([])\n- if provider:\n- eodag_api.set_preferred_provider(provider)\n for item_id in ids:\n- found_products = search_product_by_id(item_id, product_type=collections[0])\n+ found_products = search_product_by_id(\n+ item_id, product_type=collections[0], provider=provider\n+ )\n if len(found_products) == 1:\n search_results.extend(found_products)\n search_results.properties = {\n@@ -769,7 +777,9 @@ def search_stac_items(url, arguments, root=\"/\", catalogs=[], provider=None):\n arguments.pop(\"datetime\")\n \n search_products_arguments = dict(\n- arguments, **result_catalog.search_args, **{\"unserialized\": \"true\"}\n+ arguments,\n+ **result_catalog.search_args,\n+ **{\"unserialized\": \"true\", \"provider\": provider},\n )\n \n # check if time filtering appears twice\n@@ -825,7 +835,6 @@ def search_stac_items(url, arguments, root=\"/\", catalogs=[], provider=None):\n **{\"url\": result_catalog.url, \"root\": result_catalog.root},\n ),\n )\n-\n search_results = search_products(\n product_type=result_catalog.search_args[\"product_type\"],\n arguments=search_products_arguments,\n", "test_patch": "diff --git a/tests/integration/test_core_search_results.py b/tests/integration/test_core_search_results.py\nindex 8d94a465..1fff5fe7 100644\n--- a/tests/integration/test_core_search_results.py\n+++ b/tests/integration/test_core_search_results.py\n@@ -264,3 +264,23 @@ class TestCoreSearchResults(EODagTestCase):\n for search_result in search_results:\n self.assertIsInstance(search_result.downloader, PluginTopic)\n self.assertIsInstance(search_result.downloader_auth, PluginTopic)\n+\n+ @mock.patch(\n+ \"eodag.plugins.search.qssearch.QueryStringSearch.do_search\",\n+ autospec=True,\n+ )\n+ def test_core_search_with_provider(self, mock_query):\n+ \"\"\"The core api must register search results downloaders\"\"\"\n+ self.dag.set_preferred_provider(\"creodias\")\n+ search_results_file = os.path.join(\n+ TEST_RESOURCES_PATH, \"provider_responses/peps_search.json\"\n+ )\n+ with open(search_results_file, encoding=\"utf-8\") as f:\n+ search_results_peps = json.load(f)\n+\n+ mock_query.return_value = search_results_peps[\"features\"]\n+ search_results, count = self.dag.search(\n+ productType=\"S2_MSI_L1C\", provider=\"peps\"\n+ )\n+ # use given provider and not preferred provider\n+ self.assertEqual(\"peps\", search_results[0].provider)\ndiff --git a/tests/units/test_auth_plugins.py b/tests/units/test_auth_plugins.py\nindex 93c8d71d..70cf6c2d 100644\n--- a/tests/units/test_auth_plugins.py\n+++ b/tests/units/test_auth_plugins.py\n@@ -129,7 +129,9 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n auth_plugin.config.credentials = {\"foo\": \"bar\", \"username\": \"john\"}\n auth_plugin.validate_config_credentials()\n \n- @mock.patch(\"eodag.plugins.authentication.token.requests.post\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.post\", autospec=True\n+ )\n def test_plugins_auth_tokenauth_text_token_authenticate(self, mock_requests_post):\n \"\"\"TokenAuth.authenticate must return a RequestsTokenAuth object using text token\"\"\"\n auth_plugin = self.get_auth_plugin(\"provider_text_token_header\")\n@@ -146,7 +148,7 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n \n # check token post request call arguments\n args, kwargs = mock_requests_post.call_args\n- assert args[0] == auth_plugin.config.auth_uri\n+ assert args[1] == auth_plugin.config.auth_uri\n assert kwargs[\"data\"] == auth_plugin.config.credentials\n assert kwargs[\"headers\"] == dict(auth_plugin.config.headers, **USER_AGENT)\n \n@@ -156,7 +158,9 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n assert req.headers[\"Authorization\"] == \"Bearer this_is_test_token\"\n assert req.headers[\"foo\"] == \"bar\"\n \n- @mock.patch(\"eodag.plugins.authentication.token.requests.post\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.post\", autospec=True\n+ )\n def test_plugins_auth_tokenauth_json_token_authenticate(self, mock_requests_post):\n \"\"\"TokenAuth.authenticate must return a RequestsTokenAuth object using json token\"\"\"\n auth_plugin = self.get_auth_plugin(\"provider_json_token_simple_url\")\n@@ -179,7 +183,9 @@ class TestAuthPluginTokenAuth(BaseAuthPluginTest):\n auth(req)\n assert req.headers[\"Authorization\"] == \"Bearer this_is_test_token\"\n \n- @mock.patch(\"eodag.plugins.authentication.token.requests.post\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.post\", autospec=True\n+ )\n def test_plugins_auth_tokenauth_request_error(self, mock_requests_post):\n \"\"\"TokenAuth.authenticate must raise an AuthenticationError if a request error occurs\"\"\"\n auth_plugin = self.get_auth_plugin(\"provider_json_token_simple_url\")\ndiff --git a/tests/units/test_core.py b/tests/units/test_core.py\nindex 092beac5..c3b4347e 100644\n--- a/tests/units/test_core.py\n+++ b/tests/units/test_core.py\n@@ -1292,7 +1292,7 @@ class TestCoreSearch(TestCoreBase):\n \"\"\"_prepare_search must handle a search by id\"\"\"\n base = {\"id\": \"dummy-id\", \"provider\": \"creodias\"}\n prepared_search = self.dag._prepare_search(**base)\n- expected = base\n+ expected = {\"id\": \"dummy-id\"}\n self.assertDictEqual(expected, prepared_search)\n \n def test__prepare_search_preserve_additional_kwargs(self):\ndiff --git a/tests/units/test_http_server.py b/tests/units/test_http_server.py\nindex d1a8a9aa..9a144cd8 100644\n--- a/tests/units/test_http_server.py\n+++ b/tests/units/test_http_server.py\n@@ -317,6 +317,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"search?collections={self.tested_product_type}\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -326,6 +327,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=0,43,1,44\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -344,22 +346,26 @@ class RequestTestCase(unittest.TestCase):\n side_effect=AuthenticationError(\"you are no authorized\"),\n )\n def test_auth_error(self, mock_search):\n- \"\"\"A request to eodag server raising a Authentication error must return a 401 HTTP error code\"\"\"\n- response = self.app.get(\n- f\"search?collections={self.tested_product_type}\", follow_redirects=True\n- )\n- response_content = json.loads(response.content.decode(\"utf-8\"))\n+ \"\"\"A request to eodag server raising a Authentication error must return a 500 HTTP error code\"\"\"\n \n- self.assertEqual(401, response.status_code)\n- self.assertIn(\"description\", response_content)\n- self.assertIn(\"AuthenticationError\", response_content[\"description\"])\n- self.assertIn(\"you are no authorized\", response_content[\"description\"])\n+ with self.assertLogs(level=\"ERROR\") as cm_logs:\n+ response = self.app.get(\n+ f\"search?collections={self.tested_product_type}\", follow_redirects=True\n+ )\n+ response_content = json.loads(response.content.decode(\"utf-8\"))\n+\n+ self.assertIn(\"description\", response_content)\n+ self.assertIn(\"AuthenticationError\", str(cm_logs.output))\n+ self.assertIn(\"you are no authorized\", str(cm_logs.output))\n+\n+ self.assertEqual(500, response.status_code)\n \n def test_filter(self):\n \"\"\"latestIntersect filter should only keep the latest products once search area is fully covered\"\"\"\n result1 = self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=89.65,2.65,89.7,2.7\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -371,6 +377,7 @@ class RequestTestCase(unittest.TestCase):\n result2 = self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=89.65,2.65,89.7,2.7&filter=latestIntersect\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -386,6 +393,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"search?collections={self.tested_product_type}&bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -401,6 +409,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"collections/{self.tested_product_type}/items?bbox=0,43,1,44\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -411,6 +420,7 @@ class RequestTestCase(unittest.TestCase):\n self._request_valid(\n f\"collections/{self.tested_product_type}/items?bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -426,6 +436,7 @@ class RequestTestCase(unittest.TestCase):\n results = self._request_valid(\n f\"catalogs/{self.tested_product_type}/year/2018/month/01/items?bbox=0,43,1,44\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -441,6 +452,7 @@ class RequestTestCase(unittest.TestCase):\n f\"catalogs/{self.tested_product_type}/year/2018/month/01/items\"\n \"?bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -456,6 +468,7 @@ class RequestTestCase(unittest.TestCase):\n f\"catalogs/{self.tested_product_type}/year/2018/month/01/items\"\n \"?bbox=0,43,1,44&datetime=2018-01-20/2019-01-01\",\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\n@@ -489,6 +502,7 @@ class RequestTestCase(unittest.TestCase):\n f\"catalogs/{self.tested_product_type}/items/foo\",\n expected_search_kwargs={\n \"id\": \"foo\",\n+ \"provider\": None,\n \"productType\": self.tested_product_type,\n },\n )\n@@ -499,6 +513,7 @@ class RequestTestCase(unittest.TestCase):\n f\"collections/{self.tested_product_type}/items/foo\",\n expected_search_kwargs={\n \"id\": \"foo\",\n+ \"provider\": None,\n \"productType\": self.tested_product_type,\n },\n )\n@@ -521,6 +536,7 @@ class RequestTestCase(unittest.TestCase):\n \"query\": {\"eo:cloud_cover\": {\"lte\": 10}},\n },\n expected_search_kwargs=dict(\n+ provider=\"peps\",\n productType=self.tested_product_type,\n page=1,\n items_per_page=DEFAULT_ITEMS_PER_PAGE,\ndiff --git a/tests/units/test_search_plugins.py b/tests/units/test_search_plugins.py\nindex 9e09dc6f..9d99ea9f 100644\n--- a/tests/units/test_search_plugins.py\n+++ b/tests/units/test_search_plugins.py\n@@ -22,7 +22,6 @@ import unittest\n from pathlib import Path\n from unittest import mock\n \n-import requests\n import responses\n from requests import RequestException\n \n@@ -936,10 +935,11 @@ class MockResponse:\n \n \n class TestSearchPluginDataRequestSearch(BaseSearchPluginTest):\n- @mock.patch(\"eodag.plugins.authentication.token.requests.get\", autospec=True)\n+ @mock.patch(\n+ \"eodag.plugins.authentication.token.requests.Session.get\", autospec=True\n+ )\n def setUp(self, mock_requests_get):\n \n- # One of the providers that has a BuildPostSearchResult Search plugin\n provider = \"wekeo\"\n self.search_plugin = self.get_search_plugin(self.product_type, provider)\n self.auth_plugin = self.get_auth_plugin(provider)\n@@ -973,7 +973,7 @@ class TestSearchPluginDataRequestSearch(BaseSearchPluginTest):\n mock_requests_get.return_value = MockResponse(\n {\"status\": \"failed\", \"message\": \"failed\"}, 500\n )\n- with self.assertRaises(requests.RequestException):\n+ with self.assertRaises(RequestError):\n self.search_plugin._check_request_status(\"123\")\n \n @mock.patch(\"eodag.plugins.search.data_request_search.requests.get\", autospec=True)\ndiff --git a/tests/units/test_stac_utils.py b/tests/units/test_stac_utils.py\nindex 0c8f618d..50ea9dff 100644\n--- a/tests/units/test_stac_utils.py\n+++ b/tests/units/test_stac_utils.py\n@@ -447,6 +447,7 @@ class TestStacUtils(unittest.TestCase):\n mock__request.return_value.json.return_value = (\n self.earth_search_resp_search_json\n )\n+ self.rest_utils.eodag_api.set_preferred_provider(\"peps\")\n \n response = self.rest_utils.search_stac_items(\n url=\"http://foo/search\",\n@@ -467,6 +468,8 @@ class TestStacUtils(unittest.TestCase):\n \"assets\"\n ].items():\n self.assertIn((k, v), response[\"features\"][0][\"assets\"].items())\n+ # preferred provider should not be changed\n+ self.assertEqual(\"peps\", self.rest_utils.eodag_api.get_preferred_provider()[0])\n \n @mock.patch(\n \"eodag.plugins.search.qssearch.QueryStringSearch._request\",\n", "FAIL_TO_PASS": ["tests/integration/test_core_search_results.py::TestCoreSearchResults::test_core_search_with_provider", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_json_token_authenticate", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_text_token_authenticate", "tests/units/test_core.py::TestCoreSearch::test__prepare_search_with_id", "tests/units/test_http_server.py::RequestTestCase::test_auth_error", "tests/units/test_http_server.py::RequestTestCase::test_cloud_cover_post_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_catalog_items", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_items", "tests/units/test_http_server.py::RequestTestCase::test_filter", "tests/units/test_http_server.py::RequestTestCase::test_request_params", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_catalog", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_collection", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_check_request_status", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_create_data_request", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_get_result_data", "tests/units/test_stac_utils.py::TestStacUtils::test_search_stac_items_with_stac_providers"]}, {"instance_id": "cs-si__eodag-795", "base_commit": "2eb52b8300e3859712c74412a97d15181865ce97", "gold_patch": "diff --git a/eodag/rest/server.py b/eodag/rest/server.py\nindex 57cc4381..541da3a8 100755\n--- a/eodag/rest/server.py\n+++ b/eodag/rest/server.py\n@@ -18,11 +18,12 @@\n import io\n import logging\n import os\n+import re\n import traceback\n from contextlib import asynccontextmanager\n from distutils import dist\n from json.decoder import JSONDecodeError\n-from typing import List, Union\n+from typing import List, Optional, Union\n \n import pkg_resources\n from fastapi import APIRouter as FastAPIRouter\n@@ -37,8 +38,11 @@ from starlette.exceptions import HTTPException as StarletteHTTPException\n \n from eodag.config import load_stac_api_config\n from eodag.rest.utils import (\n+ QueryableProperty,\n+ Queryables,\n download_stac_item_by_id_stream,\n eodag_api_init,\n+ fetch_collection_queryable_properties,\n get_detailled_collections_list,\n get_stac_api_version,\n get_stac_catalogs,\n@@ -61,6 +65,7 @@ from eodag.utils.exceptions import (\n )\n \n logger = logging.getLogger(\"eodag.rest.server\")\n+CAMEL_TO_SPACE_TITLED = re.compile(r\"[:_-]|(?<=[a-z])(?=[A-Z])\")\n \n \n class APIRouter(FastAPIRouter):\n@@ -595,4 +600,57 @@ async def stac_catalogs(catalogs, request: Request):\n return jsonable_encoder(response)\n \n \n+@router.get(\"/queryables\", tags=[\"Capabilities\"], response_model_exclude_none=True)\n+def list_queryables(request: Request) -> Queryables:\n+ \"\"\"Returns the list of terms available for use when writing filter expressions.\n+\n+ This endpoint provides a list of terms that can be used as filters when querying\n+ the data. These terms correspond to properties that can be filtered using comparison\n+ operators.\n+\n+ :param request: The incoming request object.\n+ :type request: fastapi.Request\n+ :returns: An object containing the list of available queryable terms.\n+ :rtype: eodag.rest.utils.Queryables\n+ \"\"\"\n+\n+ return Queryables(q_id=request.state.url)\n+\n+\n+@router.get(\n+ \"/collections/{collection_id}/queryables\",\n+ tags=[\"Capabilities\"],\n+ response_model_exclude_none=True,\n+)\n+def list_collection_queryables(\n+ request: Request, collection_id: str, provider: Optional[str] = None\n+) -> Queryables:\n+ \"\"\"Returns the list of queryable properties for a specific collection.\n+\n+ This endpoint provides a list of properties that can be used as filters when querying\n+ the specified collection. These properties correspond to characteristics of the data\n+ that can be filtered using comparison operators.\n+\n+ :param request: The incoming request object.\n+ :type request: fastapi.Request\n+ :param collection_id: The identifier of the collection for which to retrieve queryable properties.\n+ :type collection_id: str\n+ :param provider: (optional) The provider for which to retrieve additional properties.\n+ :type provider: str\n+ :returns: An object containing the list of available queryable properties for the specified collection.\n+ :rtype: eodag.rest.utils.Queryables\n+ \"\"\"\n+\n+ queryables = Queryables(q_id=request.state.url, additional_properties=False)\n+ conf_args = [collection_id, provider] if provider else [collection_id]\n+\n+ provider_properties = set(fetch_collection_queryable_properties(*conf_args))\n+\n+ for prop in provider_properties:\n+ titled_name = re.sub(CAMEL_TO_SPACE_TITLED, \" \", prop).title()\n+ queryables[prop] = QueryableProperty(description=titled_name)\n+\n+ return queryables\n+\n+\n app.include_router(router)\ndiff --git a/eodag/rest/utils.py b/eodag/rest/utils.py\nindex 8fbda850..76ab874c 100644\n--- a/eodag/rest/utils.py\n+++ b/eodag/rest/utils.py\n@@ -9,10 +9,12 @@ import os\n import re\n from collections import namedtuple\n from shutil import make_archive, rmtree\n+from typing import Dict, Optional\n \n import dateutil.parser\n from dateutil import tz\n from fastapi.responses import StreamingResponse\n+from pydantic import BaseModel, Field\n from shapely.geometry import Polygon, shape\n \n import eodag\n@@ -145,7 +147,6 @@ def search_bbox(request_bbox):\n search_bbox_keys = [\"lonmin\", \"latmin\", \"lonmax\", \"latmax\"]\n \n if request_bbox:\n-\n try:\n request_bbox_list = [float(coord) for coord in request_bbox.split(\",\")]\n except ValueError as e:\n@@ -883,6 +884,135 @@ def get_stac_extension_oseo(url):\n )\n \n \n+class QueryableProperty(BaseModel):\n+ \"\"\"A class representing a queryable property.\n+\n+ :param description: The description of the queryables property\n+ :type description: str\n+ :param ref: (optional) A reference link to the schema of the property.\n+ :type ref: str\n+ \"\"\"\n+\n+ description: str\n+ ref: Optional[str] = Field(default=None, serialization_alias=\"$ref\")\n+\n+\n+class Queryables(BaseModel):\n+ \"\"\"A class representing queryable properties for the STAC API.\n+\n+ :param json_schema: The URL of the JSON schema.\n+ :type json_schema: str\n+ :param q_id: (optional) The identifier of the queryables.\n+ :type q_id: str\n+ :param q_type: The type of the object.\n+ :type q_type: str\n+ :param title: The title of the queryables.\n+ :type title: str\n+ :param description: The description of the queryables\n+ :type description: str\n+ :param properties: A dictionary of queryable properties.\n+ :type properties: dict\n+ :param additional_properties: Whether additional properties are allowed.\n+ :type additional_properties: bool\n+ \"\"\"\n+\n+ json_schema: str = Field(\n+ default=\"https://json-schema.org/draft/2019-09/schema\",\n+ serialization_alias=\"$schema\",\n+ )\n+ q_id: Optional[str] = Field(default=None, serialization_alias=\"$id\")\n+ q_type: str = Field(default=\"object\", serialization_alias=\"type\")\n+ title: str = Field(default=\"Queryables for EODAG STAC API\")\n+ description: str = Field(\n+ default=\"Queryable names for the EODAG STAC API Item Search filter.\"\n+ )\n+ properties: Dict[str, QueryableProperty] = Field(\n+ default={\n+ \"id\": QueryableProperty(\n+ description=\"ID\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/id\",\n+ ),\n+ \"collection\": QueryableProperty(\n+ description=\"Collection\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/collection\",\n+ ),\n+ \"geometry\": QueryableProperty(\n+ description=\"Geometry\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/geometry\",\n+ ),\n+ \"bbox\": QueryableProperty(\n+ description=\"Bbox\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/bbox\",\n+ ),\n+ \"datetime\": QueryableProperty(\n+ description=\"Datetime\",\n+ ref=\"https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/datetime.json#/properties/datetime\",\n+ ),\n+ \"ids\": QueryableProperty(description=\"IDs\"),\n+ }\n+ )\n+ additional_properties: bool = Field(\n+ default=True, serialization_alias=\"additionalProperties\"\n+ )\n+\n+ def get_properties(self) -> Dict[str, QueryableProperty]:\n+ \"\"\"Get the queryable properties.\n+\n+ :returns: A dictionary containing queryable properties.\n+ :rtype: typing.Dict[str, QueryableProperty]\n+ \"\"\"\n+ return self.properties\n+\n+ def __contains__(self, name: str):\n+ return name in self.properties\n+\n+ def __setitem__(self, name: str, qprop: QueryableProperty):\n+ self.properties[name] = qprop\n+\n+\n+def rename_to_stac_standard(key: str) -> str:\n+ \"\"\"Fetch the queryable properties for a collection.\n+\n+ :param key: The camelCase key name obtained from a collection's metadata mapping.\n+ :type key: str\n+ :returns: The STAC-standardized property name if it exists, else the default camelCase queryable name\n+ :rtype: str\n+ \"\"\"\n+ # Load the stac config properties for renaming the properties\n+ # to their STAC standard\n+ stac_config_properties = stac_config[\"item\"][\"properties\"]\n+\n+ for stac_property, value in stac_config_properties.items():\n+ if str(value).endswith(key):\n+ return stac_property\n+ return key\n+\n+\n+def fetch_collection_queryable_properties(\n+ collection_id: str, provider: Optional[str] = None\n+) -> set:\n+ \"\"\"Fetch the queryable properties for a collection.\n+\n+ :param collection_id: The ID of the collection.\n+ :type collection_id: str\n+ :param provider: (optional) The provider.\n+ :type provider: str\n+ :returns queryable_properties: A set containing the STAC standardized queryable properties for a collection.\n+ :rtype queryable_properties: set\n+ \"\"\"\n+ # Fetch the metadata mapping for collection-specific queryables\n+ args = [collection_id, provider] if provider else [collection_id]\n+ search_plugin = next(eodag_api._plugins_manager.get_search_plugins(*args))\n+ mapping = dict(search_plugin.config.metadata_mapping)\n+\n+ # list of all the STAC standardized collection-specific queryables\n+ queryable_properties = set()\n+ for key, value in mapping.items():\n+ if isinstance(value, list) and \"TimeFromAscendingNode\" not in key:\n+ queryable_properties.add(rename_to_stac_standard(key))\n+ return queryable_properties\n+\n+\n def eodag_api_init():\n \"\"\"Init EODataAccessGateway server instance, pre-running all time consuming tasks\"\"\"\n eodag_api.fetch_product_types_list()\n", "test_patch": "diff --git a/tests/units/test_http_server.py b/tests/units/test_http_server.py\nindex 9a144cd8..8cfe0926 100644\n--- a/tests/units/test_http_server.py\n+++ b/tests/units/test_http_server.py\n@@ -760,3 +760,18 @@ class RequestTestCase(unittest.TestCase):\n response = self._request_valid(\"/extensions/oseo/json-schema/schema.json\")\n self.assertEqual(response[\"title\"], \"OpenSearch for Earth Observation\")\n self.assertEqual(response[\"allOf\"][0][\"$ref\"], \"#/definitions/oseo\")\n+\n+ def test_queryables(self):\n+ \"\"\"Request to /queryables should return a valid response.\"\"\"\n+ self._request_valid(\"queryables\")\n+\n+ def test_product_type_queryables(self):\n+ \"\"\"Request to /collections/{collection_id}/queryables should return a valid response.\"\"\"\n+ self._request_valid(f\"collections/{self.tested_product_type}/queryables\")\n+\n+ def test_product_type_queryables_with_provider(self):\n+ \"\"\"Request a collection-specific list of queryables for a given provider.\"\"\"\n+\n+ self._request_valid(\n+ f\"collections/{self.tested_product_type}/queryables?provider=peps\"\n+ )\n", "FAIL_TO_PASS": ["tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables", "tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables_with_provider", "tests/units/test_http_server.py::RequestTestCase::test_queryables"]}], "all_FAIL_TO_PASS": ["tests/integration/test_core_search_results.py::TestCoreSearchResults::test_core_search_with_provider", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_json_token_authenticate", "tests/units/test_auth_plugins.py::TestAuthPluginTokenAuth::test_plugins_auth_tokenauth_text_token_authenticate", "tests/units/test_core.py::TestCoreSearch::test__prepare_search_with_id", "tests/units/test_http_server.py::RequestTestCase::test_auth_error", "tests/units/test_http_server.py::RequestTestCase::test_cloud_cover_post_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_catalog_items", "tests/units/test_http_server.py::RequestTestCase::test_date_search_from_items", "tests/units/test_http_server.py::RequestTestCase::test_filter", "tests/units/test_http_server.py::RequestTestCase::test_request_params", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_catalog", "tests/units/test_http_server.py::RequestTestCase::test_search_item_id_from_collection", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_check_request_status", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_create_data_request", "tests/units/test_search_plugins.py::TestSearchPluginDataRequestSearch::test_plugins_get_result_data", "tests/units/test_stac_utils.py::TestStacUtils::test_search_stac_items_with_stac_providers", "tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables", "tests/units/test_http_server.py::RequestTestCase::test_product_type_queryables_with_provider", "tests/units/test_http_server.py::RequestTestCase::test_queryables"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "litestar-org__polyfactory-472_x2", "level": 2, "source": "swerebenchv2", "repo": "litestar-org/polyfactory", "image": "swerebenchv2/litestar-org-polyfactory:472-fb4e50a", "base_commit": "fb4e50acaa0796ed7164457c6c767c3351530a81", "num_bugs": 2, "bugs": [{"instance_id": "litestar-org__polyfactory-472", "base_commit": "fb4e50acaa0796ed7164457c6c767c3351530a81", "gold_patch": "diff --git a/docs/usage/configuration.rst b/docs/usage/configuration.rst\nindex d38d53c..2905556 100644\n--- a/docs/usage/configuration.rst\n+++ b/docs/usage/configuration.rst\n@@ -92,7 +92,7 @@ Set of fields that allow you to generate a collection with random lengths. By de\n :language: python\n \n Allow None Optionals\n-----------------------------\n+--------------------\n \n Allow `None` to be generated as a value for types marked as optional. When set to `True`, the outputted value will be randomly chosen between `None` and other allowed types. By default, this is set to `True`.\n \n@@ -113,3 +113,20 @@ Any other field definition will not be checked.\n .. literalinclude:: /examples/configuration/test_example_8.py\n :caption: Enable Check Factory Fields\n :language: python\n+\n+Use Default Values\n+------------------\n+\n+If ``__use_default__`` is set to ``True``, then the default value will be used instead of creating a random value\n+for a given field, provided there's a default value for that field.\n+\n+By default, ``__use_default__`` is set to ``False.`` If you need more fine grained control, you can override the\n+:meth:`~polyfactory.factories.base.BaseFactory.should_use_default_value` classmethod.\n+\n+.. note::\n+ Setting ``__use_default__`` has no effect for ``TypedDictFactory`` since you cannot set default values for\n+ ``TypedDict``.\n+\n+.. literalinclude:: /examples/configuration/test_example_9.py\n+ :caption: Use Default Values\n+ :language: python\ndiff --git a/polyfactory/factories/base.py b/polyfactory/factories/base.py\nindex 242b73c..3893b7b 100644\n--- a/polyfactory/factories/base.py\n+++ b/polyfactory/factories/base.py\n@@ -23,6 +23,8 @@ from os.path import realpath\n from pathlib import Path\n from random import Random\n \n+from polyfactory.field_meta import Null\n+\n try:\n from types import NoneType\n except ImportError:\n@@ -167,6 +169,10 @@ class BaseFactory(ABC, Generic[T]):\n \"\"\"\n An integer value that defines maximum length of a collection.\n \"\"\"\n+ __use_defaults__: ClassVar[bool] = False\n+ \"\"\"\n+ Flag indicating whether to use the default value on a specific field, if provided.\n+ \"\"\"\n \n # cached attributes\n _fields_metadata: list[FieldMeta]\n@@ -774,6 +780,20 @@ class BaseFactory(ABC, Generic[T]):\n and create_random_boolean(random=cls.__random__)\n )\n \n+ @classmethod\n+ def should_use_default_value(cls, field_meta: FieldMeta) -> bool:\n+ \"\"\"Determine whether to use the default value for the given field.\n+\n+ :param field_meta: FieldMeta instance.\n+\n+ :notes:\n+ - This method is distinct to allow overriding.\n+\n+ :returns: A boolean determining whether the default value should be used for the given field_meta.\n+\n+ \"\"\"\n+ return cls.__use_defaults__ and field_meta.default is not Null\n+\n @classmethod\n def should_set_field_value(cls, field_meta: FieldMeta, **kwargs: Any) -> bool:\n \"\"\"Determine whether to set a value for a given field_name.\n@@ -846,7 +866,7 @@ class BaseFactory(ABC, Generic[T]):\n \n for field_meta in cls.get_model_fields():\n field_build_parameters = cls.extract_field_build_parameters(field_meta=field_meta, build_args=kwargs)\n- if cls.should_set_field_value(field_meta, **kwargs):\n+ if cls.should_set_field_value(field_meta, **kwargs) and not cls.should_use_default_value(field_meta):\n if hasattr(cls, field_meta.name) and not hasattr(BaseFactory, field_meta.name):\n field_value = getattr(cls, field_meta.name)\n if isinstance(field_value, Ignore):\n", "test_patch": "diff --git a/docs/examples/configuration/test_example_9.py b/docs/examples/configuration/test_example_9.py\nnew file mode 100644\nindex 0000000..50371cd\n--- /dev/null\n+++ b/docs/examples/configuration/test_example_9.py\n@@ -0,0 +1,28 @@\n+from dataclasses import dataclass\n+from enum import Enum\n+\n+from polyfactory.factories import DataclassFactory\n+\n+\n+class Species(str, Enum):\n+ CAT = \"Cat\"\n+ DOG = \"Dog\"\n+\n+\n+@dataclass\n+class Pet:\n+ name: str\n+ sound: str = \"meow\"\n+ species: Species = Species.CAT\n+\n+\n+class PetFactory(DataclassFactory[Pet]):\n+ __model__ = Pet\n+ __use_defaults__ = True\n+\n+\n+def test_use_default() -> None:\n+ pet = PetFactory.build()\n+\n+ assert pet.species == Species.CAT\n+ assert pet.sound == \"meow\"\ndiff --git a/tests/test_attrs_factory.py b/tests/test_attrs_factory.py\nindex fbbae97..be5b8d6 100644\n--- a/tests/test_attrs_factory.py\n+++ b/tests/test_attrs_factory.py\n@@ -191,3 +191,31 @@ def test_with_init_false() -> None:\n __model__ = Foo\n \n assert FooFactory.build()\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ @define\n+ class Foo:\n+ default_field: int = attrs.field(default=attrs.Factory(lambda: 10, takes_self=False))\n+\n+ class FooFactory(AttrsFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ @define\n+ class Foo:\n+ default_field: int = attrs.field(default=10)\n+\n+ class FooFactory(AttrsFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\ndiff --git a/tests/test_dataclass_factory.py b/tests/test_dataclass_factory.py\nindex eb06199..6dd7e1b 100644\n--- a/tests/test_dataclass_factory.py\n+++ b/tests/test_dataclass_factory.py\n@@ -1,3 +1,4 @@\n+import dataclasses\n from dataclasses import dataclass as vanilla_dataclass\n from dataclasses import field\n from types import ModuleType\n@@ -205,3 +206,31 @@ def test_dataclass_with_init_false() -> None:\n result = MyFactory.build()\n \n assert result\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ @vanilla_dataclass\n+ class Foo:\n+ default_field: int = dataclasses.field(default_factory=lambda: 10)\n+\n+ class FooFactory(DataclassFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ @vanilla_dataclass\n+ class Foo:\n+ default_field: int = 10\n+\n+ class FooFactory(DataclassFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\ndiff --git a/tests/test_msgspec_factory.py b/tests/test_msgspec_factory.py\nindex 02ebe60..de2f981 100644\n--- a/tests/test_msgspec_factory.py\n+++ b/tests/test_msgspec_factory.py\n@@ -249,3 +249,29 @@ def test_mapping_with_constrained_item_types() -> None:\n validated_foo = msgspec.convert(structs.asdict(foo), Foo)\n \n assert validated_foo == foo\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ class Foo(Struct):\n+ default_field: int = msgspec.field(default_factory=lambda: 10)\n+\n+ class FooFactory(MsgspecFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ class Foo(Struct):\n+ default_field: int = 10\n+\n+ class FooFactory(MsgspecFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\ndiff --git a/tests/test_pydantic_factory.py b/tests/test_pydantic_factory.py\nindex b15a7d7..f04fb1f 100644\n--- a/tests/test_pydantic_factory.py\n+++ b/tests/test_pydantic_factory.py\n@@ -107,3 +107,29 @@ def test_mapping_with_annotated_item_types() -> None:\n __model__ = Foo\n \n assert FooFactory.build()\n+\n+\n+def test_use_default_with_callable_default() -> None:\n+ class Foo(BaseModel):\n+ default_field: int = Field(default_factory=lambda: 10)\n+\n+ class FooFactory(ModelFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n+\n+\n+def test_use_default_with_non_callable_default() -> None:\n+ class Foo(BaseModel):\n+ default_field: int = Field(default=10)\n+\n+ class FooFactory(ModelFactory[Foo]):\n+ __model__ = Foo\n+ __use_defaults__ = True\n+\n+ foo = FooFactory.build()\n+\n+ assert foo.default_field == 10\n", "FAIL_TO_PASS": ["docs/examples/configuration/test_example_9.py::test_use_default", "tests/test_attrs_factory.py::test_use_default_with_callable_default", "tests/test_attrs_factory.py::test_use_default_with_non_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_non_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_non_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_non_callable_default"]}, {"instance_id": "litestar-org__polyfactory-479", "base_commit": "c22633ccf76e0fa58bc53795dfedb78a6abfb807", "gold_patch": "diff --git a/polyfactory/factories/base.py b/polyfactory/factories/base.py\nindex 3893b7b..71b0407 100644\n--- a/polyfactory/factories/base.py\n+++ b/polyfactory/factories/base.py\n@@ -223,7 +223,7 @@ class BaseFactory(ABC, Generic[T]):\n if random_seed is not None:\n cls.seed_random(random_seed)\n \n- if cls.__set_as_default_factory_for_type__:\n+ if cls.__set_as_default_factory_for_type__ and hasattr(cls, \"__model__\"):\n BaseFactory._factory_type_mapping[cls.__model__] = cls\n \n @classmethod\n", "test_patch": "diff --git a/tests/test_factory_configuration.py b/tests/test_factory_configuration.py\nnew file mode 100644\nindex 0000000..aa92869\n--- /dev/null\n+++ b/tests/test_factory_configuration.py\n@@ -0,0 +1,20 @@\n+from typing import Any, Type\n+\n+from typing_extensions import TypeGuard\n+\n+from polyfactory.factories.base import BaseFactory, T\n+\n+\n+def test_setting_set_as_default_factory_for_type_on_base_factory() -> None:\n+ \"\"\"Setting the value to `True` shouldn't raise exception when initializing.\"\"\"\n+\n+ class CustomBaseFactory(BaseFactory[T]):\n+ __is_base_factory__ = True\n+ __set_as_default_factory_for_type__ = True\n+\n+ @classmethod\n+ def is_supported_type(cls, value: Any) -> TypeGuard[Type[T]]:\n+ # Set this as false since this factory will be injected into the\n+ # list of base factories, but this obviously shouldn't be ran\n+ # for any of the types.\n+ return False\n", "FAIL_TO_PASS": ["tests/test_factory_configuration.py::test_setting_set_as_default_factory_for_type_on_base_factory"]}], "all_FAIL_TO_PASS": ["docs/examples/configuration/test_example_9.py::test_use_default", "tests/test_attrs_factory.py::test_use_default_with_callable_default", "tests/test_attrs_factory.py::test_use_default_with_non_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_callable_default", "tests/test_dataclass_factory.py::test_use_default_with_non_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_callable_default", "tests/test_msgspec_factory.py::test_use_default_with_non_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_callable_default", "tests/test_pydantic_factory.py::test_use_default_with_non_callable_default", "tests/test_factory_configuration.py::test_setting_set_as_default_factory_for_type_on_base_factory"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "rigetticomputing__pyquil-156_x2", "level": 2, "source": "swerebenchv2", "repo": "rigetticomputing/pyquil", "image": "swerebenchv2/rigetticomputing-pyquil:156-b871e5d", "base_commit": "b871e5de5bac62bf5fde62c96d6e5b20078c9e35", "num_bugs": 2, "bugs": [{"instance_id": "rigetticomputing__pyquil-156", "base_commit": "b871e5de5bac62bf5fde62c96d6e5b20078c9e35", "gold_patch": "diff --git a/pyquil/quil.py b/pyquil/quil.py\nindex bc94cf9..1939d67 100644\n--- a/pyquil/quil.py\n+++ b/pyquil/quil.py\n@@ -16,14 +16,18 @@\n \"\"\"\n Module for creating and defining Quil programs.\n \"\"\"\n+from six import integer_types\n \n from .quilbase import (InstructionGroup,\n+ Instr,\n Addr,\n While,\n If,\n DefGate,\n Gate,\n Measurement,\n+ issubinstance,\n+ AbstractQubit,\n merge_resource_managers)\n \n from .gates import MEASURE, STANDARD_GATES\n@@ -75,21 +79,38 @@ class Program(InstructionGroup):\n \n def get_qubits(self):\n \"\"\"\n- :return: a set of all the qubit indices allocated in this program, synthesizing freely\n- allocated qubits if neccessary.\n+ Returns all of the qubit indices used in this program, including gate applications and\n+ allocated qubits. e.g.\n+ >>> p = Program()\n+ >>> p.inst((\"H\", 1))\n+ >>> p.get_qubits()\n+ {1}\n+ >>> q = p.alloc()\n+ >>> len(p.get_qubits())\n+ 2\n+\n+ :return: A set of all the qubit indices used in this program, synthesizing freely\n+ allocated qubits if neccessary.\n :rtype: set\n \"\"\"\n- allocated_qubits = set()\n+ qubits = set()\n self.synthesize()\n for ii, action in self:\n if isinstance(action, Gate):\n qubit_indices = {qq.index() for qq in action.arguments}\n elif isinstance(action, Measurement):\n qubit_indices = {action.arguments[0].index()}\n+ elif isinstance(action, Instr):\n+ qubit_indices = set()\n+ for arg in action.arguments:\n+ if isinstance(arg, integer_types):\n+ qubit_indices.add(arg)\n+ elif isinstance(arg, AbstractQubit):\n+ qubit_indices.add(arg.index())\n else:\n continue\n- allocated_qubits = set.union(allocated_qubits, qubit_indices)\n- return allocated_qubits\n+ qubits = set.union(qubits, qubit_indices)\n+ return qubits\n \n def defgate(self, name, matrix):\n \"\"\"\ndiff --git a/pyquil/quilbase.py b/pyquil/quilbase.py\nindex 26b09fa..239b965 100644\n--- a/pyquil/quilbase.py\n+++ b/pyquil/quilbase.py\n@@ -668,6 +668,8 @@ class Instr(AbstractInstruction):\n for arg in self.arguments:\n if issubinstance(arg, AbstractQubit):\n qubits.add(arg.index())\n+ elif isinstance(arg, int):\n+ qubits.add(arg)\n return qubits\n \n \n", "test_patch": "diff --git a/pyquil/tests/test_quil.py b/pyquil/tests/test_quil.py\nindex 2383453..e328faf 100644\n--- a/pyquil/tests/test_quil.py\n+++ b/pyquil/tests/test_quil.py\n@@ -462,3 +462,11 @@ def test_get_qubits():\n qq = pq.alloc()\n pq.inst(Y(2), X(qq))\n assert pq.get_qubits() == {0, 1, 2, 4, 5} # this synthesizes the allocation\n+\n+ qubit_index = 1\n+ p = Program((\"H\", qubit_index))\n+ assert p.get_qubits() == {qubit_index}\n+ q1 = p.alloc()\n+ q2 = p.alloc()\n+ p.inst((\"CNOT\", q1, q2))\n+ assert p.get_qubits() == {qubit_index, q1.index(), q2.index()}\n", "FAIL_TO_PASS": ["pyquil/tests/test_quil.py::test_get_qubits"]}, {"instance_id": "rigetticomputing__pyquil-166", "base_commit": "b7aee5b8476d17c6375e185f2f30ee1a9a6ca6eb", "gold_patch": "diff --git a/pyquil/quilbase.py b/pyquil/quilbase.py\nindex 82aad3c..ff40289 100644\n--- a/pyquil/quilbase.py\n+++ b/pyquil/quilbase.py\n@@ -254,6 +254,9 @@ class InstructionGroup(QuilAction):\n \n return synthesized\n \n+ def __len__(self):\n+ return len(self.synthesize())\n+\n def __str__(self):\n return self.out()\n \n", "test_patch": "diff --git a/pyquil/tests/test_quil.py b/pyquil/tests/test_quil.py\nindex 482f374..e4dfefb 100644\n--- a/pyquil/tests/test_quil.py\n+++ b/pyquil/tests/test_quil.py\n@@ -108,6 +108,23 @@ def test_program_pop():\n assert Program(instruction).out() == \"X 1\\n\"\n \n \n+def test_len_zero():\n+ prog = Program()\n+ assert len(prog) == 0\n+\n+\n+def test_len_one():\n+ prog = Program(X(0))\n+ assert len(prog) == 1\n+\n+\n+def test_len_nested():\n+ p = Program(H(0)).measure(0, 0)\n+ q = Program(H(0), CNOT(0, 1))\n+ p.if_then(0, q)\n+ assert len(p) == 8\n+\n+\n def test_plus_operator():\n p = Program()\n p += H(0)\n", "FAIL_TO_PASS": ["pyquil/tests/test_quil.py::test_len_zero", "pyquil/tests/test_quil.py::test_len_one", "pyquil/tests/test_quil.py::test_len_nested"]}], "all_FAIL_TO_PASS": ["pyquil/tests/test_quil.py::test_get_qubits", "pyquil/tests/test_quil.py::test_len_zero", "pyquil/tests/test_quil.py::test_len_one", "pyquil/tests/test_quil.py::test_len_nested"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pvlib__pvlib-python-278_x2", "level": 2, "source": "swerebenchv2", "repo": "pvlib/pvlib-python", "image": "swerebenchv2/pvlib-pvlib-python:278-6a41299", "base_commit": "6a4129905f59dd3c7173f9cdf9c0c59b46b5dcfd", "num_bugs": 2, "bugs": [{"instance_id": "pvlib__pvlib-python-278", "base_commit": "6a4129905f59dd3c7173f9cdf9c0c59b46b5dcfd", "gold_patch": "diff --git a/.gitignore b/.gitignore\nindex 658fe2d..f18eba0 100644\n--- a/.gitignore\n+++ b/.gitignore\n@@ -22,6 +22,7 @@ var/\n Drafts/\n */build/\n build/\n+venv/\n \n *.egg-info/\n .installed.cfg\n@@ -58,6 +59,8 @@ coverage.xml\n .pydevproject\n .spyderproject\n .idea/\n+*.sublime-project\n+*.sublime-workspace\n \n # Rope\n .ropeproject\ndiff --git a/docs/sphinx/source/api.rst b/docs/sphinx/source/api.rst\nindex 332b1b7..ff34b7c 100644\n--- a/docs/sphinx/source/api.rst\n+++ b/docs/sphinx/source/api.rst\n@@ -87,6 +87,10 @@ Airmass and atmospheric models\n atmosphere.alt2pres\n atmosphere.gueymard94_pw\n atmosphere.first_solar_spectral_correction\n+ atmosphere.bird_hulstrom80_aod_bb\n+ atmosphere.kasten96_lt\n+ atmosphere.angstrom_aod_at_lambda\n+ atmosphere.angstrom_alpha\n \n \n Irradiance\ndiff --git a/docs/sphinx/source/conf.py b/docs/sphinx/source/conf.py\nindex 546e61c..21d3cd5 100644\n--- a/docs/sphinx/source/conf.py\n+++ b/docs/sphinx/source/conf.py\n@@ -270,7 +270,8 @@ latex_documents = [\n extlinks = {'issue': ('https://github.com/pvlib/pvlib-python/issues/%s',\n 'GH'),\n 'wiki': ('https://github.com/pvlib/pvlib-python/wiki/%s',\n- 'wiki ')}\n+ 'wiki '),\n+ 'doi': ('http://dx.doi.org/%s', 'DOI: ')}\n \n # -- Options for manual page output ---------------------------------------\n \ndiff --git a/docs/sphinx/source/whatsnew/v0.4.4.txt b/docs/sphinx/source/whatsnew/v0.4.4.txt\nindex 48ff7da..e2be6a7 100644\n--- a/docs/sphinx/source/whatsnew/v0.4.4.txt\n+++ b/docs/sphinx/source/whatsnew/v0.4.4.txt\n@@ -6,6 +6,9 @@ v0.4.4 (January xx, 2017)\n Enhancements\n ~~~~~~~~~~~~\n \n+* Added Kasten pyrheliometric formula to calculate Linke turbidity factors with\n+ improvements by Ineichen and Perez to extend range of air mass (:issue:`278`)\n+\n \n Documentation\n ~~~~~~~~~~~~~\n@@ -19,3 +22,4 @@ Contributors\n ~~~~~~~~~~~~\n \n * Will Holmgren\n+* Mark Mikofski\ndiff --git a/pvlib/atmosphere.py b/pvlib/atmosphere.py\nindex 7ea4b5e..0b90094 100644\n--- a/pvlib/atmosphere.py\n+++ b/pvlib/atmosphere.py\n@@ -292,7 +292,7 @@ def gueymard94_pw(temp_air, relative_humidity):\n ----------\n .. [1] W. M. Keogh and A. W. Blakers, Accurate Measurement, Using Natural\n Sunlight, of Silicon Solar Cells, Prog. in Photovoltaics: Res.\n- and Appl. 2004, vol 12, pp. 1-19 (DOI: 10.1002/pip.517)\n+ and Appl. 2004, vol 12, pp. 1-19 (:doi:`10.1002/pip.517`)\n \n .. [2] C. Gueymard, Analysis of Monthly Average Atmospheric Precipitable\n Water and Turbidity in Canada and Northern United States,\n@@ -467,3 +467,193 @@ def first_solar_spectral_correction(pw, airmass_absolute, module_type=None,\n coeff[4]*np.sqrt(pw) + coeff[5]*ama/np.sqrt(pw))\n \n return modifier\n+\n+\n+def bird_hulstrom80_aod_bb(aod380, aod500):\n+ \"\"\"\n+ Approximate broadband aerosol optical depth.\n+\n+ Bird and Hulstrom developed a correlation for broadband aerosol optical\n+ depth (AOD) using two wavelengths, 380 nm and 500 nm.\n+\n+ Parameters\n+ ----------\n+ aod380 : numeric\n+ AOD measured at 380 nm\n+ aod500 : numeric\n+ AOD measured at 500 nm\n+\n+ Returns\n+ -------\n+ aod_bb : numeric\n+ broadband AOD\n+\n+ See also\n+ --------\n+ kasten96_lt\n+\n+ References\n+ ----------\n+ [1] Bird and Hulstrom, \"Direct Insolation Models\" (1980)\n+ `SERI/TR-335-344 `_\n+\n+ [2] R. E. Bird and R. L. Hulstrom, \"Review, Evaluation, and Improvement of\n+ Direct Irradiance Models\", Journal of Solar Energy Engineering 103(3),\n+ pp. 182-192 (1981)\n+ :doi:`10.1115/1.3266239`\n+ \"\"\"\n+ # approximate broadband AOD using (Bird-Hulstrom 1980)\n+ return 0.27583 * aod380 + 0.35 * aod500\n+\n+\n+def kasten96_lt(airmass_absolute, precipitable_water, aod_bb):\n+ \"\"\"\n+ Calculate Linke turbidity factor using Kasten pyrheliometric formula.\n+\n+ Note that broadband aerosol optical depth (AOD) can be approximated by AOD\n+ measured at 700 nm according to Molineaux [4] . Bird and Hulstrom offer an\n+ alternate approximation using AOD measured at 380 nm and 500 nm.\n+\n+ Based on original implementation by Armel Oumbe.\n+\n+ .. warning::\n+ These calculations are only valid for air mass less than 5 atm and\n+ precipitable water less than 5 cm.\n+\n+ Parameters\n+ ----------\n+ airmass_absolute : numeric\n+ airmass, pressure corrected in atmospheres\n+ precipitable_water : numeric\n+ precipitable water or total column water vapor in centimeters\n+ aod_bb : numeric\n+ broadband AOD\n+\n+ Returns\n+ -------\n+ lt : numeric\n+ Linke turbidity\n+\n+ See also\n+ --------\n+ bird_hulstrom80_aod_bb\n+ angstrom_aod_at_lambda\n+\n+ References\n+ ----------\n+ [1] F. Linke, \"Transmissions-Koeffizient und Trubungsfaktor\", Beitrage\n+ zur Physik der Atmosphare, Vol 10, pp. 91-103 (1922)\n+\n+ [2] F. Kasten, \"A simple parameterization of the pyrheliometric formula for\n+ determining the Linke turbidity factor\", Meteorologische Rundschau 33,\n+ pp. 124-127 (1980)\n+\n+ [3] Kasten, \"The Linke turbidity factor based on improved values of the\n+ integral Rayleigh optical thickness\", Solar Energy, Vol. 56, No. 3,\n+ pp. 239-244 (1996)\n+ :doi:`10.1016/0038-092X(95)00114-7`\n+\n+ [4] B. Molineaux, P. Ineichen, N. O'Neill, \"Equivalence of pyrheliometric\n+ and monochromatic aerosol optical depths at a single key wavelength\",\n+ Applied Optics Vol. 37, issue 10, 7008-7018 (1998)\n+ :doi:`10.1364/AO.37.007008`\n+\n+ [5] P. Ineichen, \"Conversion function between the Linke turbidity and the\n+ atmospheric water vapor and aerosol content\", Solar Energy 82,\n+ pp. 1095-1097 (2008)\n+ :doi:`10.1016/j.solener.2008.04.010`\n+\n+ [6] P. Ineichen and R. Perez, \"A new airmass independent formulation for\n+ the Linke Turbidity coefficient\", Solar Energy, Vol. 73, no. 3, pp. 151-157\n+ (2002)\n+ :doi:`10.1016/S0038-092X(02)00045-2`\n+ \"\"\"\n+ # \"From numerically integrated spectral simulations done with Modtran\n+ # (Berk, 1989), Molineaux (1998) obtained for the broadband optical depth\n+ # of a clean and dry atmospshere (fictitious atmosphere that comprises only\n+ # the effects of Rayleigh scattering and absorption by the atmosphere gases\n+ # other than the water vapor) the following expression\"\n+ # - P. Ineichen (2008)\n+ delta_cda = -0.101 + 0.235 * airmass_absolute ** (-0.16)\n+ # \"and the broadband water vapor optical depth where pwat is the integrated\n+ # precipitable water vapor content of the atmosphere expressed in cm and am\n+ # the optical air mass. The precision of these fits is better than 1% when\n+ # compared with Modtran simulations in the range 1 < am < 5 and\n+ # 0 < pwat < 5 cm at sea level\" - P. Ineichen (2008)\n+ delta_w = 0.112 * airmass_absolute ** (-0.55) * precipitable_water ** 0.34\n+ # broadband AOD\n+ delta_a = aod_bb\n+ # \"Then using the Kasten pyrheliometric formula (1980, 1996), the Linke\n+ # turbidity at am = 2 can be written. The extension of the Linke turbidity\n+ # coefficient to other values of air mass was published by Ineichen and\n+ # Perez (2002)\" - P. Ineichen (2008)\n+ lt = -(9.4 + 0.9 * airmass_absolute) * np.log(\n+ np.exp(-airmass_absolute * (delta_cda + delta_w + delta_a))\n+ ) / airmass_absolute\n+ # filter out of extrapolated values\n+ return lt\n+\n+\n+def angstrom_aod_at_lambda(aod0, lambda0, alpha, lambda1=700.0):\n+ r\"\"\"\n+ Get AOD at specified wavelength using Angstrom turbidity model.\n+\n+ Parameters\n+ ----------\n+ aod0 : numeric\n+ aerosol optical depth (AOD) measured at known wavelength\n+ lambda0 : numeric\n+ wavelength in nanometers corresponding to ``aod0``\n+ alpha : numeric\n+ Angstrom :math:`\\alpha` exponent corresponding to ``aod0``\n+ lambda1 : numeric\n+ desired wavelength in nanometers, defaults to 700 nm\n+\n+ Returns\n+ -------\n+ aod1 : numeric\n+ AOD at desired wavelength, ``lambda1``\n+\n+ See also\n+ --------\n+ angstrom_alpha\n+\n+ References\n+ ----------\n+ [1] Anders Angstrom, \"On the Atmospheric Transmission of Sun Radiation and\n+ On Dust in the Air\", Geografiska Annaler Vol. 11, pp. 156-166 (1929) JSTOR\n+ :doi:`10.2307/519399`\n+\n+ [2] Anders Angstrom, \"Techniques of Determining the Turbidity of the\n+ Atmosphere\", Tellus 13:2, pp. 214-223 (1961) Taylor & Francis\n+ :doi:`10.3402/tellusa.v13i2.9493` and Co-Action Publishing\n+ :doi:`10.1111/j.2153-3490.1961.tb00078.x`\n+ \"\"\"\n+ return aod0 * ((lambda1 / lambda0) ** (-alpha))\n+\n+\n+def angstrom_alpha(aod1, lambda1, aod2, lambda2):\n+ r\"\"\"\n+ Calculate Angstrom alpha exponent.\n+\n+ Parameters\n+ ----------\n+ aod1 : numeric\n+ first aerosol optical depth\n+ lambda1 : numeric\n+ wavelength in nanometers corresponding to ``aod1``\n+ aod2 : numeric\n+ second aerosol optical depth\n+ lambda2 : numeric\n+ wavelength in nanometers corresponding to ``aod2``\n+\n+ Returns\n+ -------\n+ alpha : numeric\n+ Angstrom :math:`\\alpha` exponent for AOD in ``(lambda1, lambda2)``\n+\n+ See also\n+ --------\n+ angstrom_aod_at_lambda\n+ \"\"\"\n+ return - np.log(aod1 / aod2) / np.log(lambda1 / lambda2)\n", "test_patch": "diff --git a/pvlib/test/test_atmosphere.py b/pvlib/test/test_atmosphere.py\nindex 5522fa3..40e58c7 100644\n--- a/pvlib/test/test_atmosphere.py\n+++ b/pvlib/test/test_atmosphere.py\n@@ -1,4 +1,3 @@\n-import datetime\n import itertools\n \n import numpy as np\n@@ -7,10 +6,8 @@ import pandas as pd\n import pytest\n from numpy.testing import assert_allclose\n \n-from pvlib.location import Location\n-from pvlib import solarposition\n from pvlib import atmosphere\n-\n+from pvlib import solarposition\n \n latitude, longitude, tz, altitude = 32.2, -111, 'US/Arizona', 700\n \n@@ -113,3 +110,43 @@ def test_first_solar_spectral_correction_supplied():\n def test_first_solar_spectral_correction_ambiguous():\n with pytest.raises(TypeError):\n atmosphere.first_solar_spectral_correction(1, 1)\n+\n+\n+def test_kasten96_lt():\n+ \"\"\"Test Linke turbidity factor calculated from AOD, Pwat and AM\"\"\"\n+ amp = np.array([1, 3, 5])\n+ pwat = np.array([0, 2.5, 5])\n+ aod_bb = np.array([0, 0.1, 1])\n+ lt_expected = np.array(\n+ [[[1.3802, 2.4102, 11.6802],\n+ [1.16303976, 2.37303976, 13.26303976],\n+ [1.12101907, 2.51101907, 15.02101907]],\n+\n+ [[2.95546945, 3.98546945, 13.25546945],\n+ [2.17435443, 3.38435443, 14.27435443],\n+ [1.99821967, 3.38821967, 15.89821967]],\n+\n+ [[3.37410769, 4.40410769, 13.67410769],\n+ [2.44311797, 3.65311797, 14.54311797],\n+ [2.23134152, 3.62134152, 16.13134152]]]\n+ )\n+ lt = atmosphere.kasten96_lt(*np.meshgrid(amp, pwat, aod_bb))\n+ assert np.allclose(lt, lt_expected, 1e-3)\n+ return lt\n+\n+\n+def test_angstrom_aod():\n+ \"\"\"Test Angstrom turbidity model functions.\"\"\"\n+ aod550 = 0.15\n+ aod1240 = 0.05\n+ alpha = atmosphere.angstrom_alpha(aod550, 550, aod1240, 1240)\n+ assert np.isclose(alpha, 1.3513924317859232)\n+ aod700 = atmosphere.angstrom_aod_at_lambda(aod550, 550, alpha)\n+ assert np.isclose(aod700, 0.10828110997681031)\n+\n+\n+def test_bird_hulstrom80_aod_bb():\n+ \"\"\"Test Bird_Hulstrom broadband AOD.\"\"\"\n+ aod380, aod500 = 0.22072480948195175, 0.1614279181106312\n+ bird_hulstrom = atmosphere.bird_hulstrom80_aod_bb(aod380, aod500)\n+ assert np.isclose(0.11738229553812768, bird_hulstrom)\n", "FAIL_TO_PASS": ["pvlib/test/test_atmosphere.py::test_kasten96_lt", "pvlib/test/test_atmosphere.py::test_angstrom_aod", "pvlib/test/test_atmosphere.py::test_bird_hulstrom80_aod_bb"]}, {"instance_id": "pvlib__pvlib-python-304", "base_commit": "be65117d9cc14f8afc9b2c0a629fe54573771062", "gold_patch": "diff --git a/.gitattributes b/.gitattributes\nindex 4488f4c..81490a9 100644\n--- a/.gitattributes\n+++ b/.gitattributes\n@@ -1,1 +1,4 @@\n pvlib/version.py export-subst\n+\n+# reduce the number of merge conflicts\n+docs/sphinx/source/whatsnew/v*.txt merge=union\ndiff --git a/docs/sphinx/source/whatsnew/v0.4.4.txt b/docs/sphinx/source/whatsnew/v0.4.4.txt\nindex 4356814..b0aff39 100644\n--- a/docs/sphinx/source/whatsnew/v0.4.4.txt\n+++ b/docs/sphinx/source/whatsnew/v0.4.4.txt\n@@ -10,6 +10,14 @@ Enhancements\n improvements by Ineichen and Perez to extend range of air mass (:issue:`278`)\n \n \n+API Changes\n+~~~~~~~~~~~\n+\n+* Change PVSystem default module_parameters and inverter_parameters to\n+ empty dict. Code that relied on these attributes being None or raising\n+ a TypeError will need to be updated. (issue:`294`)\n+\n+\n Documentation\n ~~~~~~~~~~~~~\n \ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\nindex ba64fc2..ce5947e 100644\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -133,13 +133,19 @@ class PVSystem(object):\n \n # could tie these together with @property\n self.module = module\n- self.module_parameters = module_parameters\n+ if module_parameters is None:\n+ self.module_parameters = {}\n+ else:\n+ self.module_parameters = module_parameters\n \n self.modules_per_string = modules_per_string\n self.strings_per_inverter = strings_per_inverter\n \n self.inverter = inverter\n- self.inverter_parameters = inverter_parameters\n+ if inverter_parameters is None:\n+ self.inverter_parameters = {}\n+ else:\n+ self.inverter_parameters = inverter_parameters\n \n self.racking_model = racking_model\n \n", "test_patch": "diff --git a/pvlib/test/test_pvsystem.py b/pvlib/test/test_pvsystem.py\nindex ba9372f..4fbc9b1 100644\n--- a/pvlib/test/test_pvsystem.py\n+++ b/pvlib/test/test_pvsystem.py\n@@ -615,6 +615,9 @@ def test_snlinverter_Pnt_micro(sam_data):\n \n def test_PVSystem_creation():\n pv_system = pvsystem.PVSystem(module='blah', inverter='blarg')\n+ # ensure that parameter attributes are dict-like. GH 294\n+ pv_system.module_parameters['pdc0'] = 1\n+ pv_system.inverter_parameters['Paco'] = 1\n \n \n def test_PVSystem_get_aoi():\n", "FAIL_TO_PASS": ["pvlib/test/test_pvsystem.py::test_PVSystem_creation"]}], "all_FAIL_TO_PASS": ["pvlib/test/test_atmosphere.py::test_kasten96_lt", "pvlib/test/test_atmosphere.py::test_angstrom_aod", "pvlib/test/test_atmosphere.py::test_bird_hulstrom80_aod_bb", "pvlib/test/test_pvsystem.py::test_PVSystem_creation"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "sdv-dev__rdt-610_x2", "level": 2, "source": "swerebenchv2", "repo": "sdv-dev/RDT", "image": "swerebenchv2/sdv-dev-rdt:610-a8aacd1", "base_commit": "a8aacd1df1d1c9598e913f96cb022197eca0948a", "num_bugs": 2, "bugs": [{"instance_id": "sdv-dev__rdt-610", "base_commit": "a8aacd1df1d1c9598e913f96cb022197eca0948a", "gold_patch": "diff --git a/rdt/performance/datasets/categorical.py b/rdt/performance/datasets/categorical.py\nindex d747211..13b43d8 100644\n--- a/rdt/performance/datasets/categorical.py\n+++ b/rdt/performance/datasets/categorical.py\n@@ -331,7 +331,7 @@ class UniqueIntegerGenerator(CategoricalGenerator):\n 'memory': 2000.0\n },\n 'transform': {\n- 'time': 0.0003,\n+ 'time': 0.0004,\n 'memory': 500000.0\n },\n 'reverse_transform': {\n@@ -358,11 +358,11 @@ class UniqueIntegerNaNsGenerator(CategoricalGenerator):\n 'memory': 1000.0\n },\n 'transform': {\n- 'time': 0.0002,\n+ 'time': 0.0004,\n 'memory': 1000000.0\n },\n 'reverse_transform': {\n- 'time': 0.0002,\n+ 'time': 0.0004,\n 'memory': 1000000.0,\n }\n }\n@@ -385,7 +385,7 @@ class UniqueStringGenerator(CategoricalGenerator):\n 'memory': 2000.0\n },\n 'transform': {\n- 'time': 0.0002,\n+ 'time': 0.0004,\n 'memory': 500000.0\n },\n 'reverse_transform': {\n@@ -416,7 +416,7 @@ class UniqueStringNaNsGenerator(CategoricalGenerator):\n 'memory': 1000000.0\n },\n 'reverse_transform': {\n- 'time': 0.0002,\n+ 'time': 0.0005,\n 'memory': 1000000.0,\n }\n }\ndiff --git a/rdt/transformers/base.py b/rdt/transformers/base.py\nindex 137dff7..a534c6e 100644\n--- a/rdt/transformers/base.py\n+++ b/rdt/transformers/base.py\n@@ -100,6 +100,8 @@ class BaseTransformer:\n \n def reset_randomization(self):\n \"\"\"Reset the random state for ``reverse_transform``.\"\"\"\n+ self.set_random_state(self.INITIAL_FIT_STATE, 'fit')\n+ self.set_random_state(self.INITIAL_TRANSFORM_STATE, 'transform')\n self.set_random_state(self.INITIAL_REVERSE_TRANSFORM_STATE, 'reverse_transform')\n \n def _set_missing_value_replacement(self, default, missing_value_replacement):\ndiff --git a/rdt/transformers/categorical.py b/rdt/transformers/categorical.py\nindex edbb759..ec6e7e5 100644\n--- a/rdt/transformers/categorical.py\n+++ b/rdt/transformers/categorical.py\n@@ -566,6 +566,22 @@ class CustomLabelEncoder(LabelEncoder):\n self.order = pd.Series(order).fillna(np.nan)\n super().__init__(add_noise=add_noise)\n \n+ def __repr__(self):\n+ \"\"\"Represent initialization of transformer as text.\n+\n+ Returns:\n+ str:\n+ The name of the transformer followed by any non-default parameters.\n+ \"\"\"\n+ class_name = self.__class__.get_name()\n+ custom_args = []\n+ custom_args.append('order=')\n+ if self.add_noise:\n+ custom_args.append(f'add_noise={self.add_noise}')\n+\n+ args_string = ', '.join(custom_args)\n+ return f'{class_name}({args_string})'\n+\n def _fit(self, data):\n \"\"\"Fit the transformer to the data.\n \n", "test_patch": "diff --git a/tests/unit/transformers/test_base.py b/tests/unit/transformers/test_base.py\nindex 7d35c10..633d7c5 100644\n--- a/tests/unit/transformers/test_base.py\n+++ b/tests/unit/transformers/test_base.py\n@@ -117,14 +117,20 @@ class TestBaseTransformer:\n \"\"\"Test that the random seed for ``reverse_transform`` is reset.\"\"\"\n # Setup\n transformer = BaseTransformer()\n+ transformer.random_states['fit'] = 0\n+ transformer.random_states['transform'] = 2\n transformer.random_states['reverse_transform'] = None\n \n # Run\n transformer.reset_randomization()\n \n # Assert\n- expected_state = transformer.INITIAL_REVERSE_TRANSFORM_STATE\n- assert transformer.random_states['reverse_transform'] == expected_state\n+ fit_state = transformer.INITIAL_FIT_STATE\n+ transform_state = transformer.INITIAL_TRANSFORM_STATE\n+ reverse_transform_state = transformer.INITIAL_REVERSE_TRANSFORM_STATE\n+ assert transformer.random_states['fit'] == fit_state\n+ assert transformer.random_states['transform'] == transform_state\n+ assert transformer.random_states['reverse_transform'] == reverse_transform_state\n \n def test_get_subclasses(self):\n \"\"\"Test the ``get_subclasses`` method.\ndiff --git a/tests/unit/transformers/test_categorical.py b/tests/unit/transformers/test_categorical.py\nindex cffafad..800f9a2 100644\n--- a/tests/unit/transformers/test_categorical.py\n+++ b/tests/unit/transformers/test_categorical.py\n@@ -1808,6 +1808,35 @@ class TestCustomLabelEncoder:\n assert transformer.add_noise == 'add_noise_value'\n pd.testing.assert_series_equal(transformer.order, pd.Series(['b', 'c', 'a', np.nan]))\n \n+ def test___repr___default(self):\n+ \"\"\"Test that the ``__repr__`` method prints the custom order.\n+\n+ The order should be printed as instead of the actual order.\n+ \"\"\"\n+ # Setup\n+ transformer = CustomLabelEncoder(order=['VISA', 'AMEX', 'DISCOVER', None])\n+\n+ # Run\n+ stringified_transformer = transformer.__repr__()\n+\n+ # Assert\n+ assert stringified_transformer == 'CustomLabelEncoder(order=)'\n+\n+ def test___repr___add_noise_true(self):\n+ \"\"\"Test that the ``__repr__`` method prints the custom order with ``add_noise``.\n+\n+ The order should be printed as instead of the actual order. If ``add_noise``\n+ is provided, it should be printed too.\n+ \"\"\"\n+ # Setup\n+ transformer = CustomLabelEncoder(order=['VISA', 'AMEX', 'DISCOVER', None], add_noise=True)\n+\n+ # Run\n+ stringified_transformer = transformer.__repr__()\n+\n+ # Assert\n+ assert stringified_transformer == 'CustomLabelEncoder(order=, add_noise=True)'\n+\n def test__fit(self):\n \"\"\"Test the ``_fit`` method.\n \n", "FAIL_TO_PASS": ["tests/unit/transformers/test_base.py::TestBaseTransformer::test_reset_randomization", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___add_noise_true"]}, {"instance_id": "sdv-dev__rdt-622", "base_commit": "d4c0affce11bf4515855a6f70f9793a3e7e38497", "gold_patch": "diff --git a/rdt/transformers/categorical.py b/rdt/transformers/categorical.py\nindex ec6e7e5..5b3c638 100644\n--- a/rdt/transformers/categorical.py\n+++ b/rdt/transformers/categorical.py\n@@ -147,7 +147,7 @@ class FrequencyEncoder(BaseTransformer):\n if category is np.nan:\n mask = data.isna()\n else:\n- mask = (data.to_numpy() == category)\n+ mask = data.to_numpy() == category\n \n if self.add_noise:\n result[mask] = norm.rvs(\n@@ -227,7 +227,7 @@ class FrequencyEncoder(BaseTransformer):\n # loop over categories\n for category, values in self.intervals.items():\n start = values[0]\n- mask = (start <= data.to_numpy())\n+ mask = start <= data.to_numpy()\n result[mask] = category\n \n return pd.Series(result, index=data.index, dtype=self.dtype)\ndiff --git a/rdt/transformers/pii/anonymizer.py b/rdt/transformers/pii/anonymizer.py\nindex 58056a6..e6fc434 100644\n--- a/rdt/transformers/pii/anonymizer.py\n+++ b/rdt/transformers/pii/anonymizer.py\n@@ -1,5 +1,6 @@\n \"\"\"Personal Identifiable Information Anonymizer.\"\"\"\n \n+import hashlib\n import importlib\n import inspect\n import warnings\n@@ -38,7 +39,6 @@ class AnonymizedFaker(BaseTransformer):\n \n IS_GENERATOR = True\n INPUT_SDTYPE = 'pii'\n- INITIAL_SEED = 30\n \n @staticmethod\n def check_provider_function(provider_name, function_name):\n@@ -100,9 +100,9 @@ class AnonymizedFaker(BaseTransformer):\n self.check_provider_function(self.provider_name, self.function_name)\n self.output_properties = {None: {'next_transformer': None}}\n \n+ self._faker_random_seed = None\n self.locales = locales\n self.faker = faker.Faker(self.locales)\n- self.faker.seed_instance(self.INITIAL_SEED)\n if self.locales:\n self._check_locales()\n \n@@ -110,7 +110,7 @@ class AnonymizedFaker(BaseTransformer):\n \"\"\"Create a new ``Faker`` instance.\"\"\"\n super().reset_randomization()\n self.faker = faker.Faker(self.locales)\n- self.faker.seed_instance(self.INITIAL_SEED)\n+ self.faker.seed_instance(self._faker_random_seed)\n \n def _function(self):\n \"\"\"Return a callable ``faker`` function.\"\"\"\n@@ -119,6 +119,15 @@ class AnonymizedFaker(BaseTransformer):\n \n return getattr(self.faker, self.function_name)(**self.function_kwargs)\n \n+ def _set_seed(self, data):\n+ hash_value = self.get_input_column()\n+ for value in data.head(5):\n+ hash_value += str(value)\n+\n+ hash_value = int(hashlib.sha256(hash_value.encode('utf-8')).hexdigest(), 16)\n+ self._faker_random_seed = hash_value % ((2 ** 32) - 1) # maximum value for a seed\n+ self.faker.seed_instance(self._faker_random_seed)\n+\n def _fit(self, data):\n \"\"\"Fit the transformer to the data.\n \n@@ -126,6 +135,7 @@ class AnonymizedFaker(BaseTransformer):\n data (pandas.Series):\n Data to fit to.\n \"\"\"\n+ self._set_seed(data)\n self.data_length = len(data)\n \n def _transform(self, _data):\n@@ -244,6 +254,7 @@ class PseudoAnonymizedFaker(AnonymizedFaker):\n data (pandas.Series):\n Data to fit the transformer to.\n \"\"\"\n+ self._set_seed(columns_data)\n unique_values = columns_data[columns_data.notna()].unique()\n unique_data_length = len(unique_values)\n try:\n", "test_patch": "diff --git a/tests/integration/test_hyper_transformer.py b/tests/integration/test_hyper_transformer.py\nindex 593e0da..9e67821 100644\n--- a/tests/integration/test_hyper_transformer.py\n+++ b/tests/integration/test_hyper_transformer.py\n@@ -12,6 +12,7 @@ from rdt.transformers import (\n AnonymizedFaker, BaseTransformer, BinaryEncoder, ClusterBasedNormalizer, FloatFormatter,\n FrequencyEncoder, LabelEncoder, OneHotEncoder, RegexGenerator, UnixTimestampEncoder,\n get_default_transformer, get_default_transformers)\n+from rdt.transformers.pii.anonymizer import PseudoAnonymizedFaker\n \n \n class DummyTransformerNumerical(BaseTransformer):\n@@ -1098,11 +1099,11 @@ def test_hyper_transformer_reset_randomization():\n # test reverse transforming multiple times with different tranformers\n expected_first_reverse = pd.DataFrame({\n 'credit_card': [\n- '180090934066211',\n- '30083012986584',\n- '2290394691481974',\n- '4444812351068428276',\n- '4875851017747494'\n+ '3564483245479407',\n+ '4863061245886958069',\n+ '4039466324278480',\n+ '4217004814656859',\n+ '4343691397776091'\n ],\n 'age': [18, 25, 54, 60, 31],\n 'name': ['AAAAA', 'AAAAB', 'AAAAC', 'AAAAD', 'AAAAE'],\n@@ -1112,11 +1113,11 @@ def test_hyper_transformer_reset_randomization():\n })\n expected_second_reverse = pd.DataFrame({\n 'credit_card': [\n- '4228463375694866475',\n- '378224850315805',\n- '3568070297954787',\n- '4681503697026160',\n- '4490550771579'\n+ '4208002654643',\n+ '3547584322792794',\n+ '30187802217181',\n+ '4138954513622487900',\n+ '346502559595986'\n ],\n 'age': [18, 25, 54, 60, 31],\n 'name': ['AAAAF', 'AAAAG', 'AAAAH', 'AAAAI', 'AAAAJ'],\n@@ -1127,7 +1128,6 @@ def test_hyper_transformer_reset_randomization():\n first_reverse1 = ht1.reverse_transform(first_transformed1)\n first_reverse2 = ht2.reverse_transform(first_transformed1)\n second_reverse1 = ht1.reverse_transform(first_transformed1)\n-\n pd.testing.assert_frame_equal(first_reverse1, expected_first_reverse)\n pd.testing.assert_frame_equal(first_reverse2, expected_first_reverse)\n pd.testing.assert_frame_equal(expected_second_reverse, second_reverse1)\n@@ -1167,3 +1167,141 @@ def test_hyper_transformer_cluster_based_normalizer_randomization():\n ht2.fit(data)\n \n pd.testing.assert_frame_equal(transformed1, ht2.transform(data))\n+\n+\n+def test_hypertransformer_anonymized_faker():\n+ \"\"\"Test ``AnonymizedFaker`` generates different random values for different columns.\n+\n+ Issue: https://github.com/sdv-dev/RDT/issues/619.\n+ \"\"\"\n+ # Setup\n+ data = pd.DataFrame({\n+ 'id1': ['a', 'b', 'c'],\n+ 'id2': ['d', 'e', 'f'],\n+ })\n+ ht = HyperTransformer()\n+\n+ # Run - simple run\n+ ht.detect_initial_config(data)\n+ ht.update_sdtypes({\n+ 'id1': 'pii',\n+ 'id2': 'pii'\n+ })\n+ ht.update_transformers({\n+ 'id1': AnonymizedFaker(),\n+ 'id2': AnonymizedFaker()\n+ })\n+ ht.fit(data)\n+ transformed = ht.transform(data)\n+ reverse_transformed1 = ht.reverse_transform(transformed)\n+\n+ # Assert\n+ assert reverse_transformed1['id1'].tolist() != reverse_transformed1['id2'].tolist()\n+\n+ # Run - make sure transforming again returns different values than the original transform\n+ transformed = ht.transform(data)\n+ reverse_transformed2 = ht.reverse_transform(transformed)\n+\n+ # Assert\n+ assert reverse_transformed2['id1'].tolist() != reverse_transformed2['id2'].tolist()\n+ assert reverse_transformed1['id1'].tolist() != reverse_transformed2['id1'].tolist()\n+ assert reverse_transformed1['id2'].tolist() != reverse_transformed2['id2'].tolist()\n+\n+ # Run - make sure resetting randomization works\n+ ht.reset_randomization()\n+ transformed = ht.transform(data)\n+ reverse_transformed3 = ht.reverse_transform(transformed)\n+\n+ # Assert\n+ pd.testing.assert_frame_equal(reverse_transformed1, reverse_transformed3)\n+\n+\n+def test_hypertransformer_pseudo_anonymized_faker():\n+ \"\"\"Test ``PseudoAnonymizedFaker`` generates different random values for different columns.\"\"\"\n+ # Setup\n+ data = pd.DataFrame({\n+ 'id1': ['a', 'b', 'c'],\n+ 'id2': ['a', 'b', 'c'],\n+ })\n+ ht = HyperTransformer()\n+\n+ # Run\n+ ht.detect_initial_config(data)\n+ ht.update_sdtypes({\n+ 'id1': 'pii',\n+ 'id2': 'pii'\n+ })\n+ ht.update_transformers({\n+ 'id1': PseudoAnonymizedFaker(),\n+ 'id2': PseudoAnonymizedFaker()\n+ })\n+ ht.fit(data)\n+ transformed = ht.transform(data)\n+ reverse_transformed1 = ht.reverse_transform(transformed)\n+\n+ # Assert\n+ assert reverse_transformed1['id1'].tolist() != reverse_transformed1['id2'].tolist()\n+\n+ # Run - run it again on the exact same data\n+ ht = HyperTransformer()\n+ ht.detect_initial_config(data)\n+ ht.update_sdtypes({\n+ 'id1': 'pii',\n+ 'id2': 'pii'\n+ })\n+ ht.update_transformers({\n+ 'id1': PseudoAnonymizedFaker(),\n+ 'id2': PseudoAnonymizedFaker()\n+ })\n+ ht.fit(data)\n+ transformed = ht.transform(data)\n+ reverse_transformed2 = ht.reverse_transform(transformed)\n+\n+ # Assert - different instances of the same transformer should return the same result\n+ assert reverse_transformed1['id1'].tolist() == reverse_transformed2['id1'].tolist()\n+\n+\n+def test_hypertransformer_anonymized_faker_multi_table():\n+ \"\"\"Test ``AnonymizedFaker`` generates different values for columns with same name.\"\"\"\n+ # Setup\n+ data1 = pd.DataFrame({\n+ 'id1': ['a', 'b', 'c'],\n+ 'id2': ['a', 'b', 'c'],\n+ })\n+ data2 = pd.DataFrame({\n+ 'id1': ['d', 'e', 'f'],\n+ 'id2': ['d', 'e', 'f'],\n+ })\n+ ht = HyperTransformer()\n+\n+ # Run on data1\n+ ht.detect_initial_config(data1)\n+ ht.update_sdtypes({\n+ 'id1': 'pii',\n+ 'id2': 'pii'\n+ })\n+ ht.update_transformers({\n+ 'id1': AnonymizedFaker(),\n+ 'id2': PseudoAnonymizedFaker()\n+ })\n+ ht.fit(data1)\n+ transformed = ht.transform(data1)\n+ reverse_transformed1 = ht.reverse_transform(transformed)\n+\n+ # Run on data2\n+ ht.detect_initial_config(data2)\n+ ht.update_sdtypes({\n+ 'id1': 'pii',\n+ 'id2': 'pii'\n+ })\n+ ht.update_transformers({\n+ 'id1': AnonymizedFaker(),\n+ 'id2': PseudoAnonymizedFaker()\n+ })\n+ ht.fit(data2)\n+ transformed = ht.transform(data2)\n+ reverse_transformed2 = ht.reverse_transform(transformed)\n+\n+ # Assert\n+ assert reverse_transformed1['id1'].tolist() != reverse_transformed2['id1'].tolist()\n+ assert reverse_transformed1['id2'].tolist() != reverse_transformed2['id2'].tolist()\ndiff --git a/tests/unit/transformers/pii/test_anonymizer.py b/tests/unit/transformers/pii/test_anonymizer.py\nindex c93147a..162c902 100644\n--- a/tests/unit/transformers/pii/test_anonymizer.py\n+++ b/tests/unit/transformers/pii/test_anonymizer.py\n@@ -308,6 +308,7 @@ class TestAnonymizedFaker:\n # Setup\n transformer = AnonymizedFaker()\n columns_data = pd.Series(['1', '2', '3'])\n+ transformer.columns = ['col']\n \n # Run\n transformer._fit(columns_data)\n@@ -612,6 +613,7 @@ class TestPseudoAnonymizedFaker:\n instance = PseudoAnonymizedFaker()\n instance._function = Mock()\n instance._function.side_effect = [1, 2, 3]\n+ instance.columns = ['col']\n data = pd.Series(['a', 'b', 'c'])\n \n # Run\n@@ -648,6 +650,7 @@ class TestPseudoAnonymizedFaker:\n \"\"\"\n # Setup\n instance = PseudoAnonymizedFaker('misc', 'boolean')\n+ instance.columns = ['col']\n data = pd.Series(['a', 'b', 'c', 'd'])\n \n # Run / Assert\ndiff --git a/tests/unit/transformers/test_base.py b/tests/unit/transformers/test_base.py\nindex 633d7c5..5eb5622 100644\n--- a/tests/unit/transformers/test_base.py\n+++ b/tests/unit/transformers/test_base.py\n@@ -935,7 +935,7 @@ class TestBaseTransformer:\n 'b': [4, 5, 6],\n 'c': [7, 8, 9]\n })\n- column = 'a'\n+ column = ['a']\n \n class Dummy(BaseTransformer):\n def __init__(self):\ndiff --git a/tests/unit/transformers/test_text.py b/tests/unit/transformers/test_text.py\nindex 4a9f405..ac16b37 100644\n--- a/tests/unit/transformers/test_text.py\n+++ b/tests/unit/transformers/test_text.py\n@@ -54,7 +54,7 @@ class TestRegexGenerator:\n 'generator_size': 380204032,\n 'output_properties': {None: {'next_transformer': None}},\n 'regex_format': '[A-Za-z]{5}',\n- 'random_states': mock_random_sates\n+ 'random_states': mock_random_sates,\n }\n \n @patch('rdt.transformers.text.strings_from_regex')\n", "FAIL_TO_PASS": ["tests/integration/test_hyper_transformer.py::test_hyper_transformer_reset_randomization", "tests/integration/test_hyper_transformer.py::test_hypertransformer_anonymized_faker", "tests/integration/test_hyper_transformer.py::test_hypertransformer_pseudo_anonymized_faker", "tests/integration/test_hyper_transformer.py::test_hypertransformer_anonymized_faker_multi_table"]}], "all_FAIL_TO_PASS": ["tests/unit/transformers/test_base.py::TestBaseTransformer::test_reset_randomization", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___default", "tests/unit/transformers/test_categorical.py::TestCustomLabelEncoder::test___repr___add_noise_true", "tests/integration/test_hyper_transformer.py::test_hyper_transformer_reset_randomization", "tests/integration/test_hyper_transformer.py::test_hypertransformer_anonymized_faker", "tests/integration/test_hyper_transformer.py::test_hypertransformer_pseudo_anonymized_faker", "tests/integration/test_hyper_transformer.py::test_hypertransformer_anonymized_faker_multi_table"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pyccel__pyccel-2072_x2", "level": 2, "source": "swerebenchv2", "repo": "pyccel/pyccel", "image": "swerebenchv2/pyccel-pyccel:2072-0341065", "base_commit": "03410656a3336afa229ff4c604d497e0999c5750", "num_bugs": 2, "bugs": [{"instance_id": "pyccel__pyccel-2072", "base_commit": "03410656a3336afa229ff4c604d497e0999c5750", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex ca6291ca..bcf2cb4f 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -44,6 +44,7 @@ All notable changes to this project will be documented in this file.\n - #1918 : Add support for set method `clear()`.\n - #1918 : Add support for set method `copy()`.\n - #1753 : Add support for set method `union()`.\n+- #1744 : Add Python support for set method `intersection()`.\n - #1884 : Add support for dict method `items()`.\n - #1936 : Add missing C output for inline decorator example in documentation\n - #1937 : Optimise `pyccel.ast.basic.PyccelAstNode.substitute` method.\ndiff --git a/docs/builtin-functions.md b/docs/builtin-functions.md\nindex cc613789..b7ca91c6 100644\n--- a/docs/builtin-functions.md\n+++ b/docs/builtin-functions.md\n@@ -102,7 +102,7 @@ Python contains a limited number of builtin functions defined [here](https://doc\n | `difference` | No |\n | `difference_update` | No |\n | `discard` | Python-only |\n-| `intersection` | No |\n+| `intersection` | Python-only |\n | `intersection_update` | No |\n | `isdisjoint` | No |\n | `issubset` | No |\ndiff --git a/pyccel/ast/builtin_methods/set_methods.py b/pyccel/ast/builtin_methods/set_methods.py\nindex 782fee7d..85630e80 100644\n--- a/pyccel/ast/builtin_methods/set_methods.py\n+++ b/pyccel/ast/builtin_methods/set_methods.py\n@@ -18,6 +18,7 @@ __all__ = (\n 'SetClear',\n 'SetCopy',\n 'SetDiscard',\n+ 'SetIntersection',\n 'SetMethod',\n 'SetPop',\n 'SetUnion',\n@@ -232,3 +233,32 @@ class SetUnion(SetMethod):\n raise TypeError(f\"Argument of type {o.class_type} cannot be used to build set of type {self._class_type}\")\n self._shape = (None,)*self._class_type.rank\n super().__init__(set_obj, *others)\n+\n+#==============================================================================\n+\n+class SetIntersection(SetMethod):\n+ \"\"\"\n+ Represents a call to the set method .intersection.\n+\n+ Represents a call to the set method .intersection. This method builds a new set\n+ by including all elements which appear in \"both\" of the iterables\n+ (the set object and the arguments).\n+\n+ Parameters\n+ ----------\n+ set_obj : TypedAstNode\n+ The set object which the method is called from.\n+ *others : TypedAstNode\n+ The iterables which will be combined (common elements) with this set.\n+ \"\"\"\n+ __slots__ = ('_other','_class_type', '_shape')\n+ name = 'intersection'\n+\n+ def __init__(self, set_obj, *others):\n+ self._class_type = set_obj.class_type\n+ element_type = self._class_type.element_type\n+ for o in others:\n+ if element_type != o.class_type.element_type:\n+ raise TypeError(f\"Argument fo type {o.type_class} cannot be used to build set of type {self._class_type}\")\n+ self._shape = (None,)*self.rank\n+ super().__init__(set_obj, *others)\ndiff --git a/pyccel/ast/class_defs.py b/pyccel/ast/class_defs.py\nindex da4bee0b..9ecdc16d 100644\n--- a/pyccel/ast/class_defs.py\n+++ b/pyccel/ast/class_defs.py\n@@ -7,7 +7,7 @@ This module contains all types which define a python class which is automaticall\n \"\"\"\n \n from pyccel.ast.builtin_methods.set_methods import (SetAdd, SetClear, SetCopy, SetPop,\n- SetDiscard, SetUpdate, SetUnion)\n+ SetDiscard, SetUpdate, SetUnion, SetIntersection)\n from pyccel.ast.builtin_methods.list_methods import (ListAppend, ListInsert, ListPop,\n ListClear, ListExtend, ListRemove,\n ListCopy, ListSort)\n@@ -166,8 +166,10 @@ SetClass = ClassDef('set',\n PyccelFunctionDef('pop', func_class = SetPop),\n PyccelFunctionDef('remove', func_class = SetDiscard),\n PyccelFunctionDef('union', func_class = SetUnion),\n+ PyccelFunctionDef('intersection', func_class = SetIntersection),\n PyccelFunctionDef('update', func_class = SetUpdate),\n PyccelFunctionDef('__or__', func_class = SetUnion),\n+ PyccelFunctionDef('__and__', func_class = SetIntersection),\n PyccelFunctionDef('__ior__', func_class = SetUpdate),\n ])\n \ndiff --git a/pyccel/parser/syntactic.py b/pyccel/parser/syntactic.py\nindex 8e32cd9f..8546eb35 100644\n--- a/pyccel/parser/syntactic.py\n+++ b/pyccel/parser/syntactic.py\n@@ -442,6 +442,8 @@ class SyntaxParser(BasicParser):\n return AugAssign(lhs, '%', rhs)\n elif isinstance(stmt.op, ast.BitOr):\n return AugAssign(lhs, '|', rhs)\n+ elif isinstance(stmt.op, ast.BitAnd):\n+ return AugAssign(lhs, '&', rhs)\n else:\n return errors.report(PYCCEL_RESTRICTION_TODO, symbol = stmt,\n severity='error')\n", "test_patch": "diff --git a/tests/epyccel/test_epyccel_sets.py b/tests/epyccel/test_epyccel_sets.py\nindex e54f45ff..acb045b2 100644\n--- a/tests/epyccel/test_epyccel_sets.py\n+++ b/tests/epyccel/test_epyccel_sets.py\n@@ -425,6 +425,46 @@ def test_set_union_2_args(language):\n assert python_result[0] == pyccel_result[0]\n assert set(python_result[1:]) == set(pyccel_result[1:])\n \n+def test_set_intersection_int(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3}\n+ b = {2,3,4}\n+ c = a.intersection(b)\n+ return len(c), c.pop(), c.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_no_args(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4}\n+ c = a.intersection()\n+ a.add(5)\n+ return len(c), c.pop(), c.pop(), c.pop(), c.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_2_args(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4}\n+ b = {5,6,7,2,1,3}\n+ c = {7,6,10,4,2,3,1}\n+ d = a.intersection(b, c)\n+ return len(d), d.pop(), d.pop(), d.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n @pytest.mark.parametrize( 'language', (\n pytest.param(\"fortran\", marks = pytest.mark.fortran),\n pytest.param(\"c\", marks = [\n@@ -485,6 +525,57 @@ def test_set_union_operator(language):\n assert python_result[0] == pyccel_result[0]\n assert set(python_result[1:]) == set(pyccel_result[1:])\n \n+def test_temporary_set_intersection(python_only_language):\n+ def intersection_int():\n+ a = {1,2}\n+ b = {2}\n+ d = a.intersection(b).pop()\n+ return d\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result == pyccel_result\n+\n+def test_set_intersection_list(python_only_language):\n+ def intersection_list():\n+ a = {1.2, 2.3, 5.0}\n+ b = [1.2, 5.0, 4.0]\n+ d = a.intersection(b)\n+ return len(d), d.pop(), d.pop()\n+\n+ epyccel_func = epyccel(intersection_list, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_list()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_tuple(python_only_language):\n+ def intersection_tuple():\n+ a = {True}\n+ b = (False, True)\n+ d = a.intersection(b)\n+ return len(d), d.pop()\n+\n+ epyccel_func = epyccel(intersection_tuple, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_tuple()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n+def test_set_intersection_operator(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4,8}\n+ b = {5,2,3,7,8}\n+ c = a & b\n+ return len(c), c.pop(), c.pop(), c.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n @pytest.mark.parametrize( 'language', (\n pytest.param(\"fortran\", marks = [\n pytest.mark.xfail(reason=\"Update not fully implemented yet. See #2022\"),\n@@ -521,6 +612,19 @@ def test_set_contains(language):\n python_result = union_int()\n assert python_result == pyccel_result\n \n+def test_set_intersection_augoperator(python_only_language):\n+ def intersection_int():\n+ a = {1,2,3,4}\n+ b = {2,3,4}\n+ a &= b\n+ return len(a), a.pop(), a.pop(), a.pop()\n+\n+ epyccel_func = epyccel(intersection_int, language = python_only_language)\n+ pyccel_result = epyccel_func()\n+ python_result = intersection_int()\n+ assert python_result[0] == pyccel_result[0]\n+ assert set(python_result[1:]) == set(pyccel_result[1:])\n+\n def test_set_ptr(language):\n def set_ptr():\n a = {1,2,3,4,5,6,7,8}\n", "FAIL_TO_PASS": ["tests/epyccel/test_epyccel_sets.py::test_set_intersection_int[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_no_args[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_2_args[python]", "tests/epyccel/test_epyccel_sets.py::test_temporary_set_intersection[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_list[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_tuple[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_operator[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_augoperator[python]"]}, {"instance_id": "pyccel__pyccel-2082", "base_commit": "9327f8d3d0f0b1bd5337cfc398a811bb5cc9e70b", "gold_patch": "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex bcf2cb4f..34098d0d 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -86,6 +86,7 @@ All notable changes to this project will be documented in this file.\n - #2013 : Stop limiting the length of strings to 128 characters.\n - #2078 : Fix translation of classes containing comments.\n - #2041 : Include all type extension methods by default.\n+- #2082 : Allow the use of a list comprehension to initialise an array.\n \n ### Changed\n \ndiff --git a/ci_tools/check_pylint_commands.py b/ci_tools/check_pylint_commands.py\nindex bce7bada..86176a06 100644\n--- a/ci_tools/check_pylint_commands.py\n+++ b/ci_tools/check_pylint_commands.py\n@@ -23,6 +23,7 @@ accepted_pylint_commands = {re.compile('.*/IMPORTING_EXISTING_IDENTIFIED3.py'):[\n re.compile('tests/pyccel/project_class_imports/.*'):['relative-beyond-top-level'], # ignore Codacy bad pylint call\n re.compile('tests/errors/syntax_errors/import_star.py'):['wildcard-import'],\n re.compile('tests/stc_containers/leaks_check.py'):['unused-variable'],\n+ re.compile('tests/epyccel/modules/arrays.py'):['reimported'], # Repeat NumPy imports due to functions being translated individually\n }\n \n def run_pylint(file, flag, messages):\ndiff --git a/pyccel/ast/functionalexpr.py b/pyccel/ast/functionalexpr.py\nindex e685fe5e..4b55e3d8 100644\n--- a/pyccel/ast/functionalexpr.py\n+++ b/pyccel/ast/functionalexpr.py\n@@ -53,9 +53,12 @@ class FunctionalFor(TypedAstNode):\n Dummy_0 += 1\n ```\n Index is `Dummy_0`.\n+ target_type : PyccelSymbol, optional\n+ The type of the result of the functional for. This is useful at\n+ the syntactic stage to pass along the final type of the lhs (list/set/array/etc).\n \"\"\"\n __slots__ = ('_loops','_expr', '_lhs', '_indices','_index',\n- '_shape','_class_type')\n+ '_shape','_class_type', '_target_type')\n _attribute_nodes = ('_loops','_expr', '_lhs', '_indices','_index')\n \n def __init__(\n@@ -64,13 +67,15 @@ class FunctionalFor(TypedAstNode):\n expr=None,\n lhs=None,\n indices=None,\n- index=None\n+ index=None,\n+ target_type=None\n ):\n self._loops = loops\n self._expr = expr\n self._lhs = lhs\n self._indices = indices\n self._index = index\n+ self._target_type = target_type\n super().__init__()\n \n if pyccel_stage != 'syntactic':\n@@ -97,6 +102,16 @@ class FunctionalFor(TypedAstNode):\n def index(self):\n return self._index\n \n+ @property\n+ def target_type(self):\n+ \"\"\"\n+ The type of the result of the functional for.\n+\n+ The type of the result of the functional for. This is useful at\n+ the syntactic stage to pass along the final type of the lhs (list/set/array/etc).\n+ \"\"\"\n+ return self._target_type\n+\n #==============================================================================\n class GeneratorComprehension(FunctionalFor):\n \"\"\" Super class for all functions which reduce generator expressions to scalars\ndiff --git a/pyccel/parser/semantic.py b/pyccel/parser/semantic.py\nindex ab3ef5b4..13f2e3d5 100644\n--- a/pyccel/parser/semantic.py\n+++ b/pyccel/parser/semantic.py\n@@ -150,6 +150,7 @@ type_container = {\n PythonTupleFunction : HomogeneousTupleType,\n PythonListFunction : HomogeneousListType,\n PythonSetFunction : HomogeneousSetType,\n+ NumpyArray : NumpyNDArrayType,\n }\n \n #==============================================================================\n@@ -3796,7 +3797,7 @@ class SemanticParser(BasicParser):\n dim = sympy_to_pyccel(dim, idx_subs)\n except TypeError:\n errors.report(PYCCEL_RESTRICTION_LIST_COMPREHENSION_SIZE + f'\\n Deduced size : {dim}',\n- bounding_box=(self.current_ast_node.lineno, self.current_ast_node.col_offset),\n+ symbol=expr,\n severity='fatal')\n \n # TODO find a faster way to calculate dim\n@@ -3816,7 +3817,35 @@ class SemanticParser(BasicParser):\n severity='fatal')\n \n d_var['memory_handling'] = 'heap'\n- class_type = HomogeneousListType(class_type)\n+ target_type_name = expr.target_type\n+ if isinstance(target_type_name, DottedName):\n+ lhs = target_type_name.name[0] if len(target_type_name.name) == 2 \\\n+ else DottedName(*target_type_name.name[:-1])\n+ first = self._visit(lhs)\n+ if isinstance(first, Module):\n+ conversion_func = first[target_type_name.name[-1]]\n+ else:\n+ conversion_func = None\n+ else:\n+ conversion_func = self.scope.find(target_type_name, 'functions')\n+ if conversion_func is None:\n+ if target_type_name in builtin_functions_dict:\n+ conversion_func = PyccelFunctionDef(target_type_name,\n+ builtin_functions_dict[target_type_name])\n+ if conversion_func is None:\n+ errors.report(\"Unrecognised output type from functional for.\\n\"+PYCCEL_RESTRICTION_TODO,\n+ symbol=expr,\n+ severity='fatal')\n+\n+ try:\n+ class_type = type_container[conversion_func.cls_name](class_type)\n+ except TypeError:\n+ if class_type.rank > 0:\n+ errors.report(\"ND comprehension expressions cannot be saved directly to an array yet.\\n\"+PYCCEL_RESTRICTION_TODO,\n+ symbol=expr,\n+ severity='fatal')\n+\n+ class_type = type_container[conversion_func.cls_name](numpy_process_dtype(class_type), rank=1, order=None)\n d_var['class_type'] = class_type\n shape = [dim]\n if d_var['shape']:\ndiff --git a/pyccel/parser/syntactic.py b/pyccel/parser/syntactic.py\nindex 9739ce2a..0c9d4dab 100644\n--- a/pyccel/parser/syntactic.py\n+++ b/pyccel/parser/syntactic.py\n@@ -1099,7 +1099,7 @@ class SyntaxParser(BasicParser):\n if len(args) == 0:\n args = ()\n \n- if len(args) == 1 and isinstance(args[0].value, GeneratorComprehension):\n+ if len(args) == 1 and isinstance(args[0].value, (GeneratorComprehension, FunctionalFor)):\n return args[0].value\n \n func = self._visit(stmt.func)\n@@ -1165,18 +1165,30 @@ class SyntaxParser(BasicParser):\n \n generators = list(self._visit(stmt.generators))\n \n- if not isinstance(self._context[-2],ast.Assign):\n+ success = isinstance(self._context[-2],ast.Assign)\n+ if not success and len(self._context) > 2:\n+ success = isinstance(self._context[-3],ast.Assign) and isinstance(self._context[-2],ast.Call)\n+\n+ assignment = next((c for c in reversed(self._context) if isinstance(c, ast.Assign)), None)\n+\n+ if not success:\n errors.report(PYCCEL_RESTRICTION_LIST_COMPREHENSION_ASSIGN,\n symbol = stmt,\n severity='error')\n lhs = PyccelSymbol('_', is_temp=True)\n else:\n- lhs = self._visit(self._context[-2].targets)\n+ lhs = self._visit(assignment.targets)\n if len(lhs)==1:\n lhs = lhs[0]\n else:\n raise NotImplementedError(\"A list comprehension cannot be unpacked\")\n \n+ parent = self._context[-2]\n+ if isinstance(parent, ast.Call):\n+ output_type = self._visit(parent.func)\n+ else:\n+ output_type = 'list'\n+\n index = PyccelSymbol('_', is_temp=True)\n \n args = [index]\n@@ -1198,7 +1210,7 @@ class SyntaxParser(BasicParser):\n indices = indices[::-1]\n \n return FunctionalFor([assign1, generators[-1]],target.rhs, target.lhs,\n- indices, index)\n+ indices, index, target_type = output_type)\n \n def _visit_GeneratorExp(self, stmt):\n \n", "test_patch": "diff --git a/tests/epyccel/modules/arrays.py b/tests/epyccel/modules/arrays.py\nindex 24008b0b..cdad8597 100644\n--- a/tests/epyccel/modules/arrays.py\n+++ b/tests/epyccel/modules/arrays.py\n@@ -1,4 +1,4 @@\n-# pylint: disable=missing-function-docstring, missing-module-docstring\n+# pylint: disable=missing-function-docstring, missing-module-docstring, reimported\n import numpy as np\n \n from pyccel.decorators import template, stack_array, allow_negative_index\n@@ -71,6 +71,11 @@ def array_int_1d_initialization_3():\n b = np.array(a)\n return np.sum(b), b[0], b[-1]\n \n+def array_int_1d_initialization_4():\n+ import numpy as np\n+ b = np.array([i*2 for i in range(10)])\n+ return b\n+\n #==============================================================================\n # 2D ARRAYS OF INT-32 WITH C ORDERING\n #==============================================================================\ndiff --git a/tests/epyccel/test_arrays.py b/tests/epyccel/test_arrays.py\nindex 2c03b938..34e814be 100644\n--- a/tests/epyccel/test_arrays.py\n+++ b/tests/epyccel/test_arrays.py\n@@ -346,6 +346,13 @@ def test_array_int_1d_initialization_3(language):\n \n assert f1() == f2()\n \n+def test_array_int_1d_initialization_4(language):\n+\n+ f1 = arrays.array_int_1d_initialization_4\n+ f2 = epyccel( f1 , language = language)\n+\n+ check_array_equal(f1(), f2())\n+\n #==============================================================================\n # TEST: 2D ARRAYS OF INT-32 WITH C ORDERING\n #==============================================================================\n", "FAIL_TO_PASS": ["tests/epyccel/test_arrays.py::test_array_int_1d_initialization_4[fortran]", "tests/epyccel/test_arrays.py::test_array_int_1d_initialization_4[c]", "tests/epyccel/test_arrays.py::test_array_int_1d_initialization_4[python]"]}], "all_FAIL_TO_PASS": ["tests/epyccel/test_epyccel_sets.py::test_set_intersection_int[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_no_args[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_2_args[python]", "tests/epyccel/test_epyccel_sets.py::test_temporary_set_intersection[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_list[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_tuple[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_operator[python]", "tests/epyccel/test_epyccel_sets.py::test_set_intersection_augoperator[python]", "tests/epyccel/test_arrays.py::test_array_int_1d_initialization_4[fortran]", "tests/epyccel/test_arrays.py::test_array_int_1d_initialization_4[c]", "tests/epyccel/test_arrays.py::test_array_int_1d_initialization_4[python]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "delgan__loguru-1303_x2", "level": 2, "source": "swerebenchv2", "repo": "Delgan/loguru", "image": "swerebenchv2/delgan-loguru:1303-7b6f6e3", "base_commit": "7b6f6e3741eea7b56273e072a008dc2564592496", "num_bugs": 2, "bugs": [{"instance_id": "delgan__loguru-1303", "base_commit": "7b6f6e3741eea7b56273e072a008dc2564592496", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 5e0e34d..1f575b8 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -7,6 +7,8 @@\n - Update the default log format to include the timezone offset since it produces less ambiguous logs (`#856 `_, thanks `@tim-x-y-z `_).\n - Honor the ``NO_COLOR`` environment variable to disable color output by default if ``colorize`` is not provided (`#1178 `_).\n - Add requirement for ``TERM`` environment variable not to be ``\"dumb\"`` to enable colorization (`#1287 `_, thanks `@snosov1 `_).\n+- Make ``logger.catch()`` compatible with asynchronous generators (`#1302 `_).\n+\n \n `0.7.3`_ (2024-12-06)\n =====================\ndiff --git a/loguru/_logger.py b/loguru/_logger.py\nindex 911dd60..5c2ba54 100644\n--- a/loguru/_logger.py\n+++ b/loguru/_logger.py\n@@ -114,10 +114,16 @@ from ._recattrs import RecordException, RecordFile, RecordLevel, RecordProcess,\n from ._simple_sinks import AsyncSink, CallableSink, StandardSink, StreamSink\n \n if sys.version_info >= (3, 6):\n+ from collections.abc import AsyncGenerator\n+ from inspect import isasyncgenfunction\n from os import PathLike\n+\n else:\n from pathlib import PurePath as PathLike\n \n+ def isasyncgenfunction(func):\n+ return False\n+\n \n Level = namedtuple(\"Level\", [\"name\", \"no\", \"color\", \"icon\"]) # noqa: PYI024\n \n@@ -1293,6 +1299,30 @@ class Logger:\n return (yield from function(*args, **kwargs))\n return default\n \n+ elif isasyncgenfunction(function):\n+\n+ class AsyncGenCatchWrapper(AsyncGenerator):\n+\n+ def __init__(self, gen):\n+ self._gen = gen\n+\n+ async def asend(self, value):\n+ with catcher:\n+ try:\n+ return await self._gen.asend(value)\n+ except StopAsyncIteration:\n+ pass\n+ except:\n+ raise\n+ raise StopAsyncIteration\n+\n+ async def athrow(self, *args, **kwargs):\n+ return await self._gen.athrow(*args, **kwargs)\n+\n+ def catch_wrapper(*args, **kwargs):\n+ gen = function(*args, **kwargs)\n+ return AsyncGenCatchWrapper(gen)\n+\n else:\n \n def catch_wrapper(*args, **kwargs):\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 269b914..c689c01 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -133,6 +133,9 @@ convention = \"numpy\"\n [tool.typos.default]\n extend-ignore-re = [\"(?Rm)^.*# spellchecker: disable-line$\"]\n \n+[tool.typos.default.extend-identifiers]\n+asend = \"asend\"\n+\n [tool.typos.files]\n extend-exclude = [\n \"tests/exceptions/output/**\", # False positive due to ansi sequences.\n", "test_patch": "diff --git a/tests/exceptions/output/modern/decorate_async_generator.txt b/tests/exceptions/output/modern/decorate_async_generator.txt\nnew file mode 100644\nindex 0000000..a965a70\n--- /dev/null\n+++ b/tests/exceptions/output/modern/decorate_async_generator.txt\n@@ -0,0 +1,1 @@\n+Done\ndiff --git a/tests/exceptions/output/modern/exception_formatting_async_generator.txt b/tests/exceptions/output/modern/exception_formatting_async_generator.txt\nnew file mode 100644\nindex 0000000..c5fdfab\n--- /dev/null\n+++ b/tests/exceptions/output/modern/exception_formatting_async_generator.txt\n@@ -0,0 +1,42 @@\n+\n+Traceback (most recent call last):\n+ File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 20, in \n+ f.send(None)\n+ File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 14, in foo\n+ yield a / b\n+ZeroDivisionError: division by zero\n+\n+Traceback (most recent call last):\n+\n+ File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 20, in \n+ f.send(None)\n+ \u2502 \u2514 \n+ \u2514 .Catcher.__call__..AsyncGenCatchWrapper.asend at 0xDEADBEEF>\n+\n+ File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 14, in foo\n+ yield a / b\n+ \u2502 \u2514 0\n+ \u2514 1\n+\n+ZeroDivisionError: division by zero\n+\n+Traceback (most recent call last):\n+> File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 20, in \n+ f.send(None)\n+ File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 14, in foo\n+ yield a / b\n+ZeroDivisionError: division by zero\n+\n+Traceback (most recent call last):\n+\n+> File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 20, in \n+ f.send(None)\n+ \u2502 \u2514 \n+ \u2514 .Catcher.__call__..AsyncGenCatchWrapper.asend at 0xDEADBEEF>\n+\n+ File \"tests/exceptions/source/modern/exception_formatting_async_generator.py\", line 14, in foo\n+ yield a / b\n+ \u2502 \u2514 0\n+ \u2514 1\n+\n+ZeroDivisionError: division by zero\ndiff --git a/tests/exceptions/source/modern/decorate_async_generator.py b/tests/exceptions/source/modern/decorate_async_generator.py\nnew file mode 100644\nindex 0000000..b1dffed\n--- /dev/null\n+++ b/tests/exceptions/source/modern/decorate_async_generator.py\n@@ -0,0 +1,111 @@\n+from loguru import logger\n+import asyncio\n+import sys\n+\n+logger.remove()\n+\n+# We're truly only testing whether the tests succeed, we do not care about the formatting.\n+# These should be regular Pytest test cases, but that is not possible because the syntax is not valid in Python 3.5.\n+logger.add(lambda m: None, format=\"\", diagnose=True, backtrace=True, colorize=True)\n+\n+def test_decorate_async_generator():\n+ @logger.catch(reraise=True)\n+ async def generator(x, y):\n+ yield x\n+ yield y\n+\n+ async def coro():\n+ out = []\n+ async for val in generator(1, 2):\n+ out.append(val)\n+ return out\n+\n+ res = asyncio.run(coro())\n+ assert res == [1, 2]\n+\n+\n+def test_decorate_async_generator_with_error():\n+ @logger.catch(reraise=False)\n+ async def generator(x, y):\n+ yield x\n+ yield y\n+ raise ValueError\n+\n+ async def coro():\n+ out = []\n+ async for val in generator(1, 2):\n+ out.append(val)\n+ return out\n+\n+ res = asyncio.run(coro())\n+ assert res == [1, 2]\n+\n+def test_decorate_async_generator_with_error_reraised():\n+ @logger.catch(reraise=True)\n+ async def generator(x, y):\n+ yield x\n+ yield y\n+ raise ValueError\n+\n+ async def coro():\n+ out = []\n+ try:\n+ async for val in generator(1, 2):\n+ out.append(val)\n+ except ValueError:\n+ pass\n+ else:\n+ raise AssertionError(\"ValueError not raised\")\n+ return out\n+\n+ res = asyncio.run(coro())\n+ assert res == [1, 2]\n+\n+\n+def test_decorate_async_generator_then_async_send():\n+ @logger.catch\n+ async def generator(x, y):\n+ yield x\n+ yield y\n+\n+ async def coro():\n+ gen = generator(1, 2)\n+ await gen.asend(None)\n+ await gen.asend(None)\n+ try:\n+ await gen.asend(None)\n+ except StopAsyncIteration:\n+ pass\n+ else:\n+ raise AssertionError(\"StopAsyncIteration not raised\")\n+\n+ asyncio.run(coro())\n+\n+\n+def test_decorate_async_generator_then_async_throw():\n+ @logger.catch\n+ async def generator(x, y):\n+ yield x\n+ yield y\n+\n+ async def coro():\n+ gen = generator(1, 2)\n+ await gen.asend(None)\n+ try:\n+ await gen.athrow(ValueError)\n+ except ValueError:\n+ pass\n+ else:\n+ raise AssertionError(\"ValueError not raised\")\n+\n+ asyncio.run(coro())\n+\n+\n+test_decorate_async_generator()\n+test_decorate_async_generator_with_error()\n+test_decorate_async_generator_with_error_reraised()\n+test_decorate_async_generator_then_async_send()\n+test_decorate_async_generator_then_async_throw()\n+\n+logger.add(sys.stderr, format=\"{message}\")\n+logger.info(\"Done\")\ndiff --git a/tests/exceptions/source/modern/exception_formatting_async_generator.py b/tests/exceptions/source/modern/exception_formatting_async_generator.py\nnew file mode 100644\nindex 0000000..120bc4c\n--- /dev/null\n+++ b/tests/exceptions/source/modern/exception_formatting_async_generator.py\n@@ -0,0 +1,22 @@\n+import sys\n+\n+from loguru import logger\n+\n+logger.remove()\n+logger.add(sys.stderr, format=\"\", diagnose=False, backtrace=False, colorize=False)\n+logger.add(sys.stderr, format=\"\", diagnose=True, backtrace=False, colorize=False)\n+logger.add(sys.stderr, format=\"\", diagnose=False, backtrace=True, colorize=False)\n+logger.add(sys.stderr, format=\"\", diagnose=True, backtrace=True, colorize=False)\n+\n+\n+@logger.catch\n+async def foo(a, b):\n+ yield a / b\n+\n+\n+f = foo(1, 0).asend(None)\n+\n+try:\n+ f.send(None)\n+except StopAsyncIteration:\n+ pass\ndiff --git a/tests/test_exceptions_catch.py b/tests/test_exceptions_catch.py\nindex 1e7aea9..71ebc29 100644\n--- a/tests/test_exceptions_catch.py\n+++ b/tests/test_exceptions_catch.py\n@@ -407,9 +407,9 @@ def test_decorate_generator(writer):\n def test_decorate_generator_with_error():\n @logger.catch\n def foo():\n- for i in range(3):\n- 1 / (2 - i)\n- yield i\n+ yield 0\n+ yield 1\n+ raise ValueError\n \n assert list(foo()) == [0, 1]\n \ndiff --git a/tests/test_exceptions_formatting.py b/tests/test_exceptions_formatting.py\nindex 47e05cf..58b6646 100644\n--- a/tests/test_exceptions_formatting.py\n+++ b/tests/test_exceptions_formatting.py\n@@ -23,16 +23,21 @@ def normalize(exception):\n \n def fix_filepath(match):\n filepath = match.group(1)\n+\n+ # Pattern to check if the filepath contains ANSI escape codes.\n pattern = (\n r'((?:\\x1b\\[[0-9]*m)+)([^\"]+?)((?:\\x1b\\[[0-9]*m)+)([^\"]+?)((?:\\x1b\\[[0-9]*m)+)'\n )\n+\n match = re.match(pattern, filepath)\n start_directory = os.path.dirname(os.path.dirname(__file__))\n if match:\n+ # Simplify the path while preserving the color highlighting of the file basename.\n groups = list(match.groups())\n groups[1] = os.path.relpath(os.path.abspath(groups[1]), start_directory) + \"/\"\n relpath = \"\".join(groups)\n else:\n+ # We can straightforwardly convert from absolute to relative path.\n relpath = os.path.relpath(os.path.abspath(filepath), start_directory)\n return 'File \"%s\"' % relpath.replace(\"\\\\\", \"/\")\n \n@@ -241,6 +246,8 @@ def test_exception_others(filename):\n (\"filename\", \"minimum_python_version\"),\n [\n (\"type_hints\", (3, 6)),\n+ (\"exception_formatting_async_generator\", (3, 6)),\n+ (\"decorate_async_generator\", (3, 7)),\n (\"positional_only_argument\", (3, 8)),\n (\"walrus_operator\", (3, 8)),\n (\"match_statement\", (3, 10)),\n", "FAIL_TO_PASS": ["tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_with_error", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_with_error_reraised", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_then_async_send", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_then_async_throw", "tests/test_exceptions_catch.py::test_caret_not_masked[False]", "tests/test_exceptions_catch.py::test_caret_not_masked[True]", "tests/test_exceptions_catch.py::test_no_caret_if_no_backtrace[False]", "tests/test_exceptions_catch.py::test_no_caret_if_no_backtrace[True]", "tests/test_exceptions_catch.py::test_sink_encoding[ascii]", "tests/test_exceptions_catch.py::test_sink_encoding[UTF8]", "tests/test_exceptions_catch.py::test_sink_encoding[None]", "tests/test_exceptions_catch.py::test_sink_encoding[unknown-encoding]", "tests/test_exceptions_catch.py::test_sink_encoding[]", "tests/test_exceptions_catch.py::test_sink_encoding[encoding5]", "tests/test_exceptions_catch.py::test_file_sink_ascii_encoding", "tests/test_exceptions_catch.py::test_file_sink_utf8_encoding", "tests/test_exceptions_catch.py::test_has_sys_real_prefix", "tests/test_exceptions_catch.py::test_no_sys_real_prefix", "tests/test_exceptions_catch.py::test_has_site_getsitepackages", "tests/test_exceptions_catch.py::test_no_site_getsitepackages", "tests/test_exceptions_catch.py::test_user_site_is_path", "tests/test_exceptions_catch.py::test_user_site_is_none", "tests/test_exceptions_catch.py::test_sysconfig_get_path_return_path", "tests/test_exceptions_catch.py::test_sysconfig_get_path_return_none", "tests/test_exceptions_catch.py::test_no_exception", "tests/test_exceptions_catch.py::test_exception_is_none", "tests/test_exceptions_catch.py::test_exception_is_tuple", "tests/test_exceptions_catch.py::test_exception_not_raising[ZeroDivisionError]", "tests/test_exceptions_catch.py::test_exception_not_raising[ArithmeticError]", "tests/test_exceptions_catch.py::test_exception_not_raising[exception2]", "tests/test_exceptions_catch.py::test_exception_raising[ValueError]", "tests/test_exceptions_catch.py::test_exception_raising[exception1]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[BaseException-ZeroDivisionError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[BaseException-ArithmeticError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[BaseException-exclude2]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[ZeroDivisionError-ZeroDivisionError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[ZeroDivisionError-ArithmeticError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[ZeroDivisionError-exclude2]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[BaseException-ValueError]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[BaseException-exclude1]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[ZeroDivisionError-ValueError]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[ZeroDivisionError-exclude1]", "tests/test_exceptions_catch.py::test_reraise", "tests/test_exceptions_catch.py::test_onerror", "tests/test_exceptions_catch.py::test_onerror_with_reraise", "tests/test_exceptions_catch.py::test_decorate_function", "tests/test_exceptions_catch.py::test_decorate_coroutine", "tests/test_exceptions_catch.py::test_decorate_generator", "tests/test_exceptions_catch.py::test_decorate_generator_with_error", "tests/test_exceptions_catch.py::test_default_with_function", "tests/test_exceptions_catch.py::test_default_with_generator", "tests/test_exceptions_catch.py::test_default_with_coroutine", "tests/test_exceptions_catch.py::test_error_when_decorating_class_without_parentheses", "tests/test_exceptions_catch.py::test_error_when_decorating_class_with_parentheses", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_without_reraise", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_multiple_sinks", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_with_enqueue", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_twice", "tests/test_exceptions_catch.py::test_unprintable_with_catch_context_manager", "tests/test_exceptions_catch.py::test_unprintable_with_catch_context_manager_reused", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_multiple_threads", "tests/test_exceptions_formatting.py::test_backtrace[chained_expression_direct]", "tests/test_exceptions_formatting.py::test_backtrace[chained_expression_indirect]", "tests/test_exceptions_formatting.py::test_backtrace[chaining_first]", "tests/test_exceptions_formatting.py::test_backtrace[chaining_second]", "tests/test_exceptions_formatting.py::test_backtrace[chaining_third]", "tests/test_exceptions_formatting.py::test_backtrace[enqueue]", "tests/test_exceptions_formatting.py::test_backtrace[enqueue_with_others_handlers]", "tests/test_exceptions_formatting.py::test_backtrace[frame_values_backward]", "tests/test_exceptions_formatting.py::test_backtrace[frame_values_forward]", "tests/test_exceptions_formatting.py::test_backtrace[function]", "tests/test_exceptions_formatting.py::test_backtrace[head_recursion]", "tests/test_exceptions_formatting.py::test_backtrace[missing_attributes_traceback_objects]", "tests/test_exceptions_formatting.py::test_backtrace[nested]", "tests/test_exceptions_formatting.py::test_backtrace[nested_chained_catch_up]", "tests/test_exceptions_formatting.py::test_backtrace[nested_decorator_catch_up]", "tests/test_exceptions_formatting.py::test_backtrace[nested_explicit_catch_up]", "tests/test_exceptions_formatting.py::test_backtrace[nested_wrapping]", "tests/test_exceptions_formatting.py::test_backtrace[no_tb]", "tests/test_exceptions_formatting.py::test_backtrace[not_enough_arguments]", "tests/test_exceptions_formatting.py::test_backtrace[raising_recursion]", "tests/test_exceptions_formatting.py::test_backtrace[suppressed_expression_direct]", "tests/test_exceptions_formatting.py::test_backtrace[suppressed_expression_indirect]", "tests/test_exceptions_formatting.py::test_backtrace[tail_recursion]", "tests/test_exceptions_formatting.py::test_backtrace[too_many_arguments]", "tests/test_exceptions_formatting.py::test_diagnose[assertion_error]", "tests/test_exceptions_formatting.py::test_diagnose[assertion_error_custom]", "tests/test_exceptions_formatting.py::test_diagnose[assertion_error_in_string]", "tests/test_exceptions_formatting.py::test_diagnose[attributes]", "tests/test_exceptions_formatting.py::test_diagnose[chained_both]", "tests/test_exceptions_formatting.py::test_diagnose[encoding]", "tests/test_exceptions_formatting.py::test_diagnose[global_variable]", "tests/test_exceptions_formatting.py::test_diagnose[indentation_error]", "tests/test_exceptions_formatting.py::test_diagnose[keyword_argument]", "tests/test_exceptions_formatting.py::test_diagnose[multilines_repr]", "tests/test_exceptions_formatting.py::test_diagnose[no_error_message]", "tests/test_exceptions_formatting.py::test_diagnose[parenthesis]", "tests/test_exceptions_formatting.py::test_diagnose[source_multilines]", "tests/test_exceptions_formatting.py::test_diagnose[source_strings]", "tests/test_exceptions_formatting.py::test_diagnose[syntax_error]", "tests/test_exceptions_formatting.py::test_diagnose[syntax_highlighting]", "tests/test_exceptions_formatting.py::test_diagnose[truncating]", "tests/test_exceptions_formatting.py::test_diagnose[unprintable_object]", "tests/test_exceptions_formatting.py::test_exception_ownership[assertion_from_lib]", "tests/test_exceptions_formatting.py::test_exception_ownership[assertion_from_local]", "tests/test_exceptions_formatting.py::test_exception_ownership[callback]", "tests/test_exceptions_formatting.py::test_exception_ownership[catch_decorator]", "tests/test_exceptions_formatting.py::test_exception_ownership[catch_decorator_from_lib]", "tests/test_exceptions_formatting.py::test_exception_ownership[decorated_callback]", "tests/test_exceptions_formatting.py::test_exception_ownership[direct]", "tests/test_exceptions_formatting.py::test_exception_ownership[indirect]", "tests/test_exceptions_formatting.py::test_exception_ownership[string_lib]", "tests/test_exceptions_formatting.py::test_exception_ownership[string_source]", "tests/test_exceptions_formatting.py::test_exception_ownership[syntaxerror]", "tests/test_exceptions_formatting.py::test_exception_others[assertionerror_without_traceback]", "tests/test_exceptions_formatting.py::test_exception_others[broken_but_decorated_repr]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_context_manager]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_decorator_with_parentheses]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_decorator_without_parentheses]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_function]", "tests/test_exceptions_formatting.py::test_exception_others[catch_message]", "tests/test_exceptions_formatting.py::test_exception_others[exception_formatting_coroutine]", "tests/test_exceptions_formatting.py::test_exception_others[exception_formatting_function]", "tests/test_exceptions_formatting.py::test_exception_others[exception_formatting_generator]", "tests/test_exceptions_formatting.py::test_exception_others[exception_in_property]", "tests/test_exceptions_formatting.py::test_exception_others[handler_formatting_with_context_manager]", "tests/test_exceptions_formatting.py::test_exception_others[handler_formatting_with_decorator]", "tests/test_exceptions_formatting.py::test_exception_others[level_name]", "tests/test_exceptions_formatting.py::test_exception_others[level_number]", "tests/test_exceptions_formatting.py::test_exception_others[message_formatting_with_context_manager]", "tests/test_exceptions_formatting.py::test_exception_others[message_formatting_with_decorator]", "tests/test_exceptions_formatting.py::test_exception_others[nested_with_reraise]", "tests/test_exceptions_formatting.py::test_exception_others[one_liner_recursion]", "tests/test_exceptions_formatting.py::test_exception_others[recursion_error]", "tests/test_exceptions_formatting.py::test_exception_others[repeated_lines]", "tests/test_exceptions_formatting.py::test_exception_others[syntaxerror_without_traceback]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit_negative]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit_none]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit_unset]", "tests/test_exceptions_formatting.py::test_exception_others[zerodivisionerror_without_traceback]", "tests/test_exceptions_formatting.py::test_exception_modern[type_hints-minimum_python_version0]", "tests/test_exceptions_formatting.py::test_exception_modern[exception_formatting_async_generator-minimum_python_version1]", "tests/test_exceptions_formatting.py::test_exception_modern[decorate_async_generator-minimum_python_version2]", "tests/test_exceptions_formatting.py::test_exception_modern[positional_only_argument-minimum_python_version3]", "tests/test_exceptions_formatting.py::test_exception_modern[walrus_operator-minimum_python_version4]", "tests/test_exceptions_formatting.py::test_exception_modern[match_statement-minimum_python_version5]", "tests/test_exceptions_formatting.py::test_group_exception_using_backport", "tests/test_exceptions_formatting.py::test_invalid_format_exception_only_no_output", "tests/test_exceptions_formatting.py::test_invalid_format_exception_only_indented_error_message"]}, {"instance_id": "delgan__loguru-1304", "base_commit": "7748b6cde69880101a5cfb5dcc653ad7cf23402d", "gold_patch": "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 1f575b8..1d48efc 100644\n--- a/CHANGELOG.rst\n+++ b/CHANGELOG.rst\n@@ -7,6 +7,7 @@\n - Update the default log format to include the timezone offset since it produces less ambiguous logs (`#856 `_, thanks `@tim-x-y-z `_).\n - Honor the ``NO_COLOR`` environment variable to disable color output by default if ``colorize`` is not provided (`#1178 `_).\n - Add requirement for ``TERM`` environment variable not to be ``\"dumb\"`` to enable colorization (`#1287 `_, thanks `@snosov1 `_).\n+- Make ``logger.catch()`` usable as an asynchronous context manager (`#1084 `_).\n - Make ``logger.catch()`` compatible with asynchronous generators (`#1302 `_).\n \n \ndiff --git a/loguru/_logger.py b/loguru/_logger.py\nindex 5c2ba54..7f17f1a 100644\n--- a/loguru/_logger.py\n+++ b/loguru/_logger.py\n@@ -1333,6 +1333,12 @@ class Logger:\n functools.update_wrapper(catch_wrapper, function)\n return catch_wrapper\n \n+ async def __aenter__(self):\n+ return self.__enter__()\n+\n+ async def __aexit__(self, type_, value, traceback_):\n+ return self.__exit__(type_, value, traceback_)\n+\n return Catcher(False)\n \n def opt(\n", "test_patch": "diff --git a/tests/test_exceptions_catch.py b/tests/test_exceptions_catch.py\nindex 71ebc29..f06b831 100644\n--- a/tests/test_exceptions_catch.py\n+++ b/tests/test_exceptions_catch.py\n@@ -439,6 +439,15 @@ def test_default_with_coroutine():\n assert asyncio.run(foo()) == 42\n \n \n+def test_async_context_manager():\n+ async def coro():\n+ async with logger.catch():\n+ return 1 / 0\n+ return 1\n+\n+ assert asyncio.run(coro()) == 1\n+\n+\n def test_error_when_decorating_class_without_parentheses():\n with pytest.raises(TypeError):\n \n", "FAIL_TO_PASS": ["tests/test_exceptions_catch.py::test_async_context_manager"]}], "all_FAIL_TO_PASS": ["tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_with_error", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_with_error_reraised", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_then_async_send", "tests/exceptions/source/modern/decorate_async_generator.py::test_decorate_async_generator_then_async_throw", "tests/test_exceptions_catch.py::test_caret_not_masked[False]", "tests/test_exceptions_catch.py::test_caret_not_masked[True]", "tests/test_exceptions_catch.py::test_no_caret_if_no_backtrace[False]", "tests/test_exceptions_catch.py::test_no_caret_if_no_backtrace[True]", "tests/test_exceptions_catch.py::test_sink_encoding[ascii]", "tests/test_exceptions_catch.py::test_sink_encoding[UTF8]", "tests/test_exceptions_catch.py::test_sink_encoding[None]", "tests/test_exceptions_catch.py::test_sink_encoding[unknown-encoding]", "tests/test_exceptions_catch.py::test_sink_encoding[]", "tests/test_exceptions_catch.py::test_sink_encoding[encoding5]", "tests/test_exceptions_catch.py::test_file_sink_ascii_encoding", "tests/test_exceptions_catch.py::test_file_sink_utf8_encoding", "tests/test_exceptions_catch.py::test_has_sys_real_prefix", "tests/test_exceptions_catch.py::test_no_sys_real_prefix", "tests/test_exceptions_catch.py::test_has_site_getsitepackages", "tests/test_exceptions_catch.py::test_no_site_getsitepackages", "tests/test_exceptions_catch.py::test_user_site_is_path", "tests/test_exceptions_catch.py::test_user_site_is_none", "tests/test_exceptions_catch.py::test_sysconfig_get_path_return_path", "tests/test_exceptions_catch.py::test_sysconfig_get_path_return_none", "tests/test_exceptions_catch.py::test_no_exception", "tests/test_exceptions_catch.py::test_exception_is_none", "tests/test_exceptions_catch.py::test_exception_is_tuple", "tests/test_exceptions_catch.py::test_exception_not_raising[ZeroDivisionError]", "tests/test_exceptions_catch.py::test_exception_not_raising[ArithmeticError]", "tests/test_exceptions_catch.py::test_exception_not_raising[exception2]", "tests/test_exceptions_catch.py::test_exception_raising[ValueError]", "tests/test_exceptions_catch.py::test_exception_raising[exception1]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[BaseException-ZeroDivisionError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[BaseException-ArithmeticError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[BaseException-exclude2]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[ZeroDivisionError-ZeroDivisionError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[ZeroDivisionError-ArithmeticError]", "tests/test_exceptions_catch.py::test_exclude_exception_raising[ZeroDivisionError-exclude2]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[BaseException-ValueError]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[BaseException-exclude1]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[ZeroDivisionError-ValueError]", "tests/test_exceptions_catch.py::test_exclude_exception_not_raising[ZeroDivisionError-exclude1]", "tests/test_exceptions_catch.py::test_reraise", "tests/test_exceptions_catch.py::test_onerror", "tests/test_exceptions_catch.py::test_onerror_with_reraise", "tests/test_exceptions_catch.py::test_decorate_function", "tests/test_exceptions_catch.py::test_decorate_coroutine", "tests/test_exceptions_catch.py::test_decorate_generator", "tests/test_exceptions_catch.py::test_decorate_generator_with_error", "tests/test_exceptions_catch.py::test_default_with_function", "tests/test_exceptions_catch.py::test_default_with_generator", "tests/test_exceptions_catch.py::test_default_with_coroutine", "tests/test_exceptions_catch.py::test_error_when_decorating_class_without_parentheses", "tests/test_exceptions_catch.py::test_error_when_decorating_class_with_parentheses", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_without_reraise", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_multiple_sinks", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_with_enqueue", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_twice", "tests/test_exceptions_catch.py::test_unprintable_with_catch_context_manager", "tests/test_exceptions_catch.py::test_unprintable_with_catch_context_manager_reused", "tests/test_exceptions_catch.py::test_unprintable_but_decorated_repr_multiple_threads", "tests/test_exceptions_formatting.py::test_backtrace[chained_expression_direct]", "tests/test_exceptions_formatting.py::test_backtrace[chained_expression_indirect]", "tests/test_exceptions_formatting.py::test_backtrace[chaining_first]", "tests/test_exceptions_formatting.py::test_backtrace[chaining_second]", "tests/test_exceptions_formatting.py::test_backtrace[chaining_third]", "tests/test_exceptions_formatting.py::test_backtrace[enqueue]", "tests/test_exceptions_formatting.py::test_backtrace[enqueue_with_others_handlers]", "tests/test_exceptions_formatting.py::test_backtrace[frame_values_backward]", "tests/test_exceptions_formatting.py::test_backtrace[frame_values_forward]", "tests/test_exceptions_formatting.py::test_backtrace[function]", "tests/test_exceptions_formatting.py::test_backtrace[head_recursion]", "tests/test_exceptions_formatting.py::test_backtrace[missing_attributes_traceback_objects]", "tests/test_exceptions_formatting.py::test_backtrace[nested]", "tests/test_exceptions_formatting.py::test_backtrace[nested_chained_catch_up]", "tests/test_exceptions_formatting.py::test_backtrace[nested_decorator_catch_up]", "tests/test_exceptions_formatting.py::test_backtrace[nested_explicit_catch_up]", "tests/test_exceptions_formatting.py::test_backtrace[nested_wrapping]", "tests/test_exceptions_formatting.py::test_backtrace[no_tb]", "tests/test_exceptions_formatting.py::test_backtrace[not_enough_arguments]", "tests/test_exceptions_formatting.py::test_backtrace[raising_recursion]", "tests/test_exceptions_formatting.py::test_backtrace[suppressed_expression_direct]", "tests/test_exceptions_formatting.py::test_backtrace[suppressed_expression_indirect]", "tests/test_exceptions_formatting.py::test_backtrace[tail_recursion]", "tests/test_exceptions_formatting.py::test_backtrace[too_many_arguments]", "tests/test_exceptions_formatting.py::test_diagnose[assertion_error]", "tests/test_exceptions_formatting.py::test_diagnose[assertion_error_custom]", "tests/test_exceptions_formatting.py::test_diagnose[assertion_error_in_string]", "tests/test_exceptions_formatting.py::test_diagnose[attributes]", "tests/test_exceptions_formatting.py::test_diagnose[chained_both]", "tests/test_exceptions_formatting.py::test_diagnose[encoding]", "tests/test_exceptions_formatting.py::test_diagnose[global_variable]", "tests/test_exceptions_formatting.py::test_diagnose[indentation_error]", "tests/test_exceptions_formatting.py::test_diagnose[keyword_argument]", "tests/test_exceptions_formatting.py::test_diagnose[multilines_repr]", "tests/test_exceptions_formatting.py::test_diagnose[no_error_message]", "tests/test_exceptions_formatting.py::test_diagnose[parenthesis]", "tests/test_exceptions_formatting.py::test_diagnose[source_multilines]", "tests/test_exceptions_formatting.py::test_diagnose[source_strings]", "tests/test_exceptions_formatting.py::test_diagnose[syntax_error]", "tests/test_exceptions_formatting.py::test_diagnose[syntax_highlighting]", "tests/test_exceptions_formatting.py::test_diagnose[truncating]", "tests/test_exceptions_formatting.py::test_diagnose[unprintable_object]", "tests/test_exceptions_formatting.py::test_exception_ownership[assertion_from_lib]", "tests/test_exceptions_formatting.py::test_exception_ownership[assertion_from_local]", "tests/test_exceptions_formatting.py::test_exception_ownership[callback]", "tests/test_exceptions_formatting.py::test_exception_ownership[catch_decorator]", "tests/test_exceptions_formatting.py::test_exception_ownership[catch_decorator_from_lib]", "tests/test_exceptions_formatting.py::test_exception_ownership[decorated_callback]", "tests/test_exceptions_formatting.py::test_exception_ownership[direct]", "tests/test_exceptions_formatting.py::test_exception_ownership[indirect]", "tests/test_exceptions_formatting.py::test_exception_ownership[string_lib]", "tests/test_exceptions_formatting.py::test_exception_ownership[string_source]", "tests/test_exceptions_formatting.py::test_exception_ownership[syntaxerror]", "tests/test_exceptions_formatting.py::test_exception_others[assertionerror_without_traceback]", "tests/test_exceptions_formatting.py::test_exception_others[broken_but_decorated_repr]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_context_manager]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_decorator_with_parentheses]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_decorator_without_parentheses]", "tests/test_exceptions_formatting.py::test_exception_others[catch_as_function]", "tests/test_exceptions_formatting.py::test_exception_others[catch_message]", "tests/test_exceptions_formatting.py::test_exception_others[exception_formatting_coroutine]", "tests/test_exceptions_formatting.py::test_exception_others[exception_formatting_function]", "tests/test_exceptions_formatting.py::test_exception_others[exception_formatting_generator]", "tests/test_exceptions_formatting.py::test_exception_others[exception_in_property]", "tests/test_exceptions_formatting.py::test_exception_others[handler_formatting_with_context_manager]", "tests/test_exceptions_formatting.py::test_exception_others[handler_formatting_with_decorator]", "tests/test_exceptions_formatting.py::test_exception_others[level_name]", "tests/test_exceptions_formatting.py::test_exception_others[level_number]", "tests/test_exceptions_formatting.py::test_exception_others[message_formatting_with_context_manager]", "tests/test_exceptions_formatting.py::test_exception_others[message_formatting_with_decorator]", "tests/test_exceptions_formatting.py::test_exception_others[nested_with_reraise]", "tests/test_exceptions_formatting.py::test_exception_others[one_liner_recursion]", "tests/test_exceptions_formatting.py::test_exception_others[recursion_error]", "tests/test_exceptions_formatting.py::test_exception_others[repeated_lines]", "tests/test_exceptions_formatting.py::test_exception_others[syntaxerror_without_traceback]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit_negative]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit_none]", "tests/test_exceptions_formatting.py::test_exception_others[sys_tracebacklimit_unset]", "tests/test_exceptions_formatting.py::test_exception_others[zerodivisionerror_without_traceback]", "tests/test_exceptions_formatting.py::test_exception_modern[type_hints-minimum_python_version0]", "tests/test_exceptions_formatting.py::test_exception_modern[exception_formatting_async_generator-minimum_python_version1]", "tests/test_exceptions_formatting.py::test_exception_modern[decorate_async_generator-minimum_python_version2]", "tests/test_exceptions_formatting.py::test_exception_modern[positional_only_argument-minimum_python_version3]", "tests/test_exceptions_formatting.py::test_exception_modern[walrus_operator-minimum_python_version4]", "tests/test_exceptions_formatting.py::test_exception_modern[match_statement-minimum_python_version5]", "tests/test_exceptions_formatting.py::test_group_exception_using_backport", "tests/test_exceptions_formatting.py::test_invalid_format_exception_only_no_output", "tests/test_exceptions_formatting.py::test_invalid_format_exception_only_indented_error_message", "tests/test_exceptions_catch.py::test_async_context_manager"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "modin-project__modin-6785_x2", "level": 2, "source": "swerebenchv2", "repo": "modin-project/modin", "image": "swerebenchv2/modin-project-modin:6785-76d741b", "base_commit": "76d741bec279305b041ba5689947438884893dad", "num_bugs": 2, "bugs": [{"instance_id": "modin-project__modin-6785", "base_commit": "76d741bec279305b041ba5689947438884893dad", "gold_patch": "diff --git a/modin/pandas/dataframe.py b/modin/pandas/dataframe.py\nindex 2484b393..acba48aa 100644\n--- a/modin/pandas/dataframe.py\n+++ b/modin/pandas/dataframe.py\n@@ -60,6 +60,7 @@ from .iterator import PartitionIterator\n from .series import Series\n from .utils import (\n SET_DATAFRAME_ATTRIBUTE_WARNING,\n+ _doc_binary_op,\n cast_function_modin2pandas,\n from_non_pandas,\n from_pandas,\n@@ -2720,6 +2721,23 @@ class DataFrame(BasePandasDataset):\n raise KeyError(key)\n self._update_inplace(new_query_compiler=self._query_compiler.delitem(key))\n \n+ @_doc_binary_op(\n+ operation=\"integer division and modulo\",\n+ bin_op=\"divmod\",\n+ returns=\"tuple of two DataFrames\",\n+ )\n+ def __divmod__(self, right):\n+ return self._default_to_pandas(pandas.DataFrame.__divmod__, right)\n+\n+ @_doc_binary_op(\n+ operation=\"integer division and modulo\",\n+ bin_op=\"divmod\",\n+ right=\"left\",\n+ returns=\"tuple of two DataFrames\",\n+ )\n+ def __rdivmod__(self, left):\n+ return self._default_to_pandas(pandas.DataFrame.__rdivmod__, left)\n+\n __add__ = add\n __iadd__ = add # pragma: no cover\n __radd__ = radd\ndiff --git a/modin/pandas/indexing.py b/modin/pandas/indexing.py\nindex f492278e..fc36b84d 100644\n--- a/modin/pandas/indexing.py\n+++ b/modin/pandas/indexing.py\n@@ -568,6 +568,9 @@ class _LocationIndexerBase(ClassLogger):\n masked_df = self.df.__constructor__(\n query_compiler=self.qc.getitem_array(row_loc._query_compiler)\n )\n+ if isinstance(masked_df, Series):\n+ assert col_loc == slice(None)\n+ return masked_df\n # Passing `slice(None)` as a row indexer since we've just applied it\n return type(self)(masked_df)[(slice(None), col_loc)]\n \n", "test_patch": "diff --git a/modin/pandas/test/dataframe/test_binary.py b/modin/pandas/test/dataframe/test_binary.py\nindex 62a20d5f..32799189 100644\n--- a/modin/pandas/test/dataframe/test_binary.py\n+++ b/modin/pandas/test/dataframe/test_binary.py\n@@ -90,6 +90,17 @@ def test_math_functions(other, axis, op):\n )\n \n \n+@pytest.mark.parametrize(\"other\", [lambda df: 2, lambda df: df])\n+def test___divmod__(other):\n+ data = test_data[\"float_nan_data\"]\n+ eval_general(*create_test_dfs(data), lambda df: divmod(df, other(df)))\n+\n+\n+def test___rdivmod__():\n+ data = test_data[\"float_nan_data\"]\n+ eval_general(*create_test_dfs(data), lambda df: divmod(2, df))\n+\n+\n @pytest.mark.parametrize(\n \"other\",\n [lambda df: df[: -(2**4)], lambda df: df[df.columns[0]].reset_index(drop=True)],\ndiff --git a/modin/pandas/test/test_series.py b/modin/pandas/test/test_series.py\nindex e64e1371..8945a356 100644\n--- a/modin/pandas/test/test_series.py\n+++ b/modin/pandas/test/test_series.py\n@@ -2363,6 +2363,14 @@ def test_loc(data):\n df_equals(modin_result, pandas_result)\n \n \n+def test_loc_with_boolean_series():\n+ modin_series, pandas_series = create_test_series([1, 2, 3])\n+ modin_mask, pandas_mask = create_test_series([True, False, False])\n+ modin_result = modin_series.loc[modin_mask]\n+ pandas_result = pandas_series.loc[pandas_mask]\n+ df_equals(modin_result, pandas_result)\n+\n+\n # This tests the bug from https://github.com/modin-project/modin/issues/3736\n def test_loc_setting_categorical_series():\n modin_series = pd.Series([\"a\", \"b\", \"c\"], dtype=\"category\")\n", "FAIL_TO_PASS": ["modin/pandas/test/dataframe/test_binary.py::test___divmod__[0]", "modin/pandas/test/dataframe/test_binary.py::test___divmod__[1]", "modin/pandas/test/dataframe/test_binary.py::test___rdivmod__", "modin/pandas/test/test_series.py::test_loc_with_boolean_series"]}, {"instance_id": "modin-project__modin-6787", "base_commit": "2fee14409bfda6661b8fcccbb33f3c93ae17204f", "gold_patch": "diff --git a/modin/pandas/dataframe.py b/modin/pandas/dataframe.py\nindex acba48aa..97df23e9 100644\n--- a/modin/pandas/dataframe.py\n+++ b/modin/pandas/dataframe.py\n@@ -1163,7 +1163,7 @@ class DataFrame(BasePandasDataset):\n if other.name is None:\n raise ValueError(\"Other Series must have a name\")\n other = self.__constructor__(other)\n- if on is not None:\n+ if on is not None or how == \"cross\":\n return self.__constructor__(\n query_compiler=self._query_compiler.join(\n other._query_compiler,\n", "test_patch": "diff --git a/modin/pandas/test/dataframe/test_join_sort.py b/modin/pandas/test/dataframe/test_join_sort.py\nindex 0d4ab89f..232eba8a 100644\n--- a/modin/pandas/test/dataframe/test_join_sort.py\n+++ b/modin/pandas/test/dataframe/test_join_sort.py\n@@ -167,6 +167,19 @@ def test_join(test_data, test_data2):\n df_equals(modin_join, pandas_join)\n \n \n+def test_join_cross_6786():\n+ data = [[7, 8, 9], [10, 11, 12]]\n+ modin_df, pandas_df = create_test_dfs(data, columns=[\"x\", \"y\", \"z\"])\n+\n+ modin_join = modin_df.join(\n+ modin_df[[\"x\"]].set_axis([\"p\", \"q\"], axis=0), how=\"cross\", lsuffix=\"p\"\n+ )\n+ pandas_join = pandas_df.join(\n+ pandas_df[[\"x\"]].set_axis([\"p\", \"q\"], axis=0), how=\"cross\", lsuffix=\"p\"\n+ )\n+ df_equals(modin_join, pandas_join)\n+\n+\n def test_join_5203():\n data = np.ones([2, 4])\n kwargs = {\"columns\": [\"a\", \"b\", \"c\", \"d\"]}\n", "FAIL_TO_PASS": ["modin/pandas/test/dataframe/test_join_sort.py::test_join_cross_6786"]}], "all_FAIL_TO_PASS": ["modin/pandas/test/dataframe/test_binary.py::test___divmod__[0]", "modin/pandas/test/dataframe/test_binary.py::test___divmod__[1]", "modin/pandas/test/dataframe/test_binary.py::test___rdivmod__", "modin/pandas/test/test_series.py::test_loc_with_boolean_series", "modin/pandas/test/dataframe/test_join_sort.py::test_join_cross_6786"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "narwhals-dev__narwhals-1803_x2", "level": 2, "source": "swerebenchv2", "repo": "narwhals-dev/narwhals", "image": "swerebenchv2/narwhals-dev-narwhals:1803-4be5c20", "base_commit": "4be5c203a5ba60fb2dbeed8d0ef043b2f68318f5", "num_bugs": 2, "bugs": [{"instance_id": "narwhals-dev__narwhals-1803", "base_commit": "4be5c203a5ba60fb2dbeed8d0ef043b2f68318f5", "gold_patch": "diff --git a/docs/api-reference/dataframe.md b/docs/api-reference/dataframe.md\nindex d937bf28..9e12c389 100644\n--- a/docs/api-reference/dataframe.md\n+++ b/docs/api-reference/dataframe.md\n@@ -44,6 +44,7 @@\n - to_native\n - to_numpy\n - to_pandas\n+ - to_polars\n - unique\n - unpivot\n - with_columns\ndiff --git a/docs/api-reference/series.md b/docs/api-reference/series.md\nindex 0aea494f..d3bbd62f 100644\n--- a/docs/api-reference/series.md\n+++ b/docs/api-reference/series.md\n@@ -77,6 +77,7 @@\n - to_list\n - to_numpy\n - to_pandas\n+ - to_polars\n - to_native\n - unique\n - value_counts\ndiff --git a/docs/installation.md b/docs/installation.md\nindex 8857b802..59a884ef 100644\n--- a/docs/installation.md\n+++ b/docs/installation.md\n@@ -30,7 +30,7 @@ To verify the installation, start the Python REPL and execute:\n ```python\n >>> import narwhals\n >>> narwhals.__version__\n-'1.21.1'\n+'1.22.0'\n ```\n \n If you see the version number, then the installation was successful!\ndiff --git a/narwhals/__init__.py b/narwhals/__init__.py\nindex fedc35b3..a7078355 100644\n--- a/narwhals/__init__.py\n+++ b/narwhals/__init__.py\n@@ -79,7 +79,7 @@ from narwhals.utils import maybe_get_index\n from narwhals.utils import maybe_reset_index\n from narwhals.utils import maybe_set_index\n \n-__version__ = \"1.21.1\"\n+__version__ = \"1.22.0\"\n \n __all__ = [\n \"Array\",\ndiff --git a/narwhals/_arrow/dataframe.py b/narwhals/_arrow/dataframe.py\nindex 61688795..ed738647 100644\n--- a/narwhals/_arrow/dataframe.py\n+++ b/narwhals/_arrow/dataframe.py\n@@ -30,6 +30,7 @@ if TYPE_CHECKING:\n \n import numpy as np\n import pandas as pd\n+ import polars as pl\n import pyarrow as pa\n from typing_extensions import Self\n \n@@ -427,6 +428,11 @@ class ArrowDataFrame(CompliantDataFrame, CompliantLazyFrame):\n def to_pandas(self: Self) -> pd.DataFrame:\n return self._native_frame.to_pandas()\n \n+ def to_polars(self: Self) -> pl.DataFrame:\n+ import polars as pl # ignore-banned-import\n+\n+ return pl.from_arrow(self._native_frame) # type: ignore[return-value]\n+\n def to_numpy(self: Self) -> np.ndarray:\n import numpy as np # ignore-banned-import\n \ndiff --git a/narwhals/_arrow/series.py b/narwhals/_arrow/series.py\nindex 656a802c..873b2997 100644\n--- a/narwhals/_arrow/series.py\n+++ b/narwhals/_arrow/series.py\n@@ -29,6 +29,7 @@ if TYPE_CHECKING:\n \n import numpy as np\n import pandas as pd\n+ import polars as pl\n import pyarrow as pa\n from typing_extensions import Self\n \n@@ -733,6 +734,11 @@ class ArrowSeries(CompliantSeries):\n \n return pd.Series(self._native_series, name=self.name)\n \n+ def to_polars(self: Self) -> pl.Series:\n+ import polars as pl # ignore-banned-import\n+\n+ return pl.from_arrow(self._native_series) # type: ignore[return-value]\n+\n def is_duplicated(self: Self) -> ArrowSeries:\n return self.to_frame().is_duplicated().alias(self.name)\n \ndiff --git a/narwhals/_pandas_like/dataframe.py b/narwhals/_pandas_like/dataframe.py\nindex 0cff4cb3..47c43a69 100644\n--- a/narwhals/_pandas_like/dataframe.py\n+++ b/narwhals/_pandas_like/dataframe.py\n@@ -35,6 +35,7 @@ if TYPE_CHECKING:\n \n import numpy as np\n import pandas as pd\n+ import polars as pl\n from typing_extensions import Self\n \n from narwhals._pandas_like.group_by import PandasLikeGroupBy\n@@ -763,12 +764,27 @@ class PandasLikeDataFrame:\n )\n return df.to_numpy(copy=copy)\n \n- def to_pandas(self) -> Any:\n+ def to_pandas(self: Self) -> pd.DataFrame:\n if self._implementation is Implementation.PANDAS:\n return self._native_frame\n- if self._implementation is Implementation.MODIN:\n+ elif self._implementation is Implementation.CUDF: # pragma: no cover\n+ return self._native_frame.to_pandas()\n+ elif self._implementation is Implementation.MODIN:\n return self._native_frame._to_pandas()\n- return self._native_frame.to_pandas() # pragma: no cover\n+ msg = f\"Unknown implementation: {self._implementation}\" # pragma: no cover\n+ raise AssertionError(msg)\n+\n+ def to_polars(self: Self) -> pl.DataFrame:\n+ import polars as pl # ignore-banned-import\n+\n+ if self._implementation is Implementation.PANDAS:\n+ return pl.from_pandas(self._native_frame)\n+ elif self._implementation is Implementation.CUDF: # pragma: no cover\n+ return pl.from_pandas(self._native_frame.to_pandas())\n+ elif self._implementation is Implementation.MODIN:\n+ return pl.from_pandas(self._native_frame._to_pandas())\n+ msg = f\"Unknown implementation: {self._implementation}\" # pragma: no cover\n+ raise AssertionError(msg)\n \n def write_parquet(self, file: Any) -> Any:\n self._native_frame.to_parquet(file)\ndiff --git a/narwhals/_pandas_like/series.py b/narwhals/_pandas_like/series.py\nindex 139c9a3b..358041db 100644\n--- a/narwhals/_pandas_like/series.py\n+++ b/narwhals/_pandas_like/series.py\n@@ -29,6 +29,8 @@ from narwhals.utils import validate_backend_version\n if TYPE_CHECKING:\n from types import ModuleType\n \n+ import pandas as pd\n+ import polars as pl\n from typing_extensions import Self\n \n from narwhals._pandas_like.dataframe import PandasLikeDataFrame\n@@ -303,13 +305,13 @@ class PandasLikeSeries(CompliantSeries):\n def arg_min(self) -> int:\n ser = self._native_series\n if self._implementation is Implementation.PANDAS and self._backend_version < (1,):\n- return ser.values.argmin() # type: ignore[no-any-return]\n+ return ser.to_numpy().argmin() # type: ignore[no-any-return]\n return ser.argmin() # type: ignore[no-any-return]\n \n def arg_max(self) -> int:\n ser = self._native_series\n if self._implementation is Implementation.PANDAS and self._backend_version < (1,):\n- return ser.values.argmax() # type: ignore[no-any-return]\n+ return ser.to_numpy().argmax() # type: ignore[no-any-return]\n return ser.argmax() # type: ignore[no-any-return]\n \n # Binary comparisons\n@@ -837,16 +839,28 @@ class PandasLikeSeries(CompliantSeries):\n )\n return s.to_numpy(dtype=dtype, copy=copy)\n \n- def to_pandas(self) -> Any:\n+ def to_pandas(self: Self) -> pd.Series:\n if self._implementation is Implementation.PANDAS:\n return self._native_series\n- elif self._implementation is Implementation.CUDF:\n+ elif self._implementation is Implementation.CUDF: # pragma: no cover\n return self._native_series.to_pandas()\n elif self._implementation is Implementation.MODIN:\n return self._native_series._to_pandas()\n msg = f\"Unknown implementation: {self._implementation}\" # pragma: no cover\n raise AssertionError(msg)\n \n+ def to_polars(self: Self) -> pl.DataFrame:\n+ import polars as pl # ignore-banned-import\n+\n+ if self._implementation is Implementation.PANDAS:\n+ return pl.from_pandas(self._native_series)\n+ elif self._implementation is Implementation.CUDF: # pragma: no cover\n+ return pl.from_pandas(self._native_series.to_pandas())\n+ elif self._implementation is Implementation.MODIN:\n+ return pl.from_pandas(self._native_series._to_pandas())\n+ msg = f\"Unknown implementation: {self._implementation}\" # pragma: no cover\n+ raise AssertionError(msg)\n+\n # --- descriptive ---\n def is_duplicated(self: Self) -> Self:\n res = self._native_series.duplicated(keep=False)\ndiff --git a/narwhals/_polars/dataframe.py b/narwhals/_polars/dataframe.py\nindex d5e11528..763a0981 100644\n--- a/narwhals/_polars/dataframe.py\n+++ b/narwhals/_polars/dataframe.py\n@@ -332,6 +332,9 @@ class PolarsDataFrame:\n )\n return self._from_native_object(result)\n \n+ def to_polars(self: Self) -> pl.DataFrame:\n+ return self._native_frame\n+\n \n class PolarsLazyFrame:\n def __init__(\ndiff --git a/narwhals/_polars/series.py b/narwhals/_polars/series.py\nindex 33572db7..32289632 100644\n--- a/narwhals/_polars/series.py\n+++ b/narwhals/_polars/series.py\n@@ -417,6 +417,9 @@ class PolarsSeries:\n msg = f\"Unable to compare other of type {type(other)} with series of type {self.dtype}.\"\n raise InvalidOperationError(msg) from exc\n \n+ def to_polars(self: Self) -> pl.Series:\n+ return self._native_series\n+\n @property\n def dt(self: Self) -> PolarsSeriesDateTimeNamespace:\n return PolarsSeriesDateTimeNamespace(self)\ndiff --git a/narwhals/_spark_like/namespace.py b/narwhals/_spark_like/namespace.py\nindex f53f66f7..a8c778b8 100644\n--- a/narwhals/_spark_like/namespace.py\n+++ b/narwhals/_spark_like/namespace.py\n@@ -3,10 +3,12 @@ from __future__ import annotations\n import operator\n from functools import reduce\n from typing import TYPE_CHECKING\n+from typing import Any\n from typing import Iterable\n from typing import Literal\n \n from narwhals._expression_parsing import combine_root_names\n+from narwhals._expression_parsing import parse_into_expr\n from narwhals._expression_parsing import parse_into_exprs\n from narwhals._expression_parsing import reduce_output_names\n from narwhals._spark_like.dataframe import SparkLikeLazyFrame\n@@ -334,3 +336,103 @@ class SparkLikeNamespace(CompliantNamespace[\"Column\"]):\n \"ignore_nulls\": ignore_nulls,\n },\n )\n+\n+ def when(self, *predicates: IntoSparkLikeExpr) -> SparkLikeWhen:\n+ plx = self.__class__(backend_version=self._backend_version, version=self._version)\n+ condition = plx.all_horizontal(*predicates)\n+ return SparkLikeWhen(\n+ condition, self._backend_version, returns_scalar=False, version=self._version\n+ )\n+\n+\n+class SparkLikeWhen:\n+ def __init__(\n+ self,\n+ condition: SparkLikeExpr,\n+ backend_version: tuple[int, ...],\n+ then_value: Any | None = None,\n+ otherwise_value: Any | None = None,\n+ *,\n+ returns_scalar: bool,\n+ version: Version,\n+ ) -> None:\n+ self._backend_version = backend_version\n+ self._condition = condition\n+ self._then_value = then_value\n+ self._otherwise_value = otherwise_value\n+ self._returns_scalar = returns_scalar\n+ self._version = version\n+\n+ def __call__(self, df: SparkLikeLazyFrame) -> list[Column]:\n+ from pyspark.sql import functions as F # noqa: N812\n+\n+ plx = df.__narwhals_namespace__()\n+ condition = parse_into_expr(self._condition, namespace=plx)(df)[0]\n+\n+ try:\n+ value_ = parse_into_expr(self._then_value, namespace=plx)(df)[0]\n+ col_name = get_column_name(df, value_)\n+ except TypeError:\n+ # `self._then_value` is a scalar and can't be converted to an expression\n+ value_ = F.lit(self._then_value)\n+ col_name = \"literal\"\n+\n+ try:\n+ other_ = parse_into_expr(self._otherwise_value, namespace=plx)(df)[0]\n+ except TypeError:\n+ # `self._otherwise_value` is a scalar and can't be converted to an expression\n+ other_ = F.lit(self._otherwise_value)\n+\n+ return [\n+ F.when(condition=condition, value=value_)\n+ .otherwise(value=other_)\n+ .alias(col_name)\n+ ]\n+\n+ def then(self, value: SparkLikeExpr | Any) -> SparkLikeThen:\n+ self._then_value = value\n+\n+ return SparkLikeThen( # type: ignore[abstract]\n+ self,\n+ depth=0,\n+ function_name=\"whenthen\",\n+ root_names=None,\n+ output_names=None,\n+ returns_scalar=self._returns_scalar,\n+ backend_version=self._backend_version,\n+ version=self._version,\n+ kwargs={\"value\": value},\n+ )\n+\n+\n+class SparkLikeThen(SparkLikeExpr):\n+ def __init__(\n+ self,\n+ call: SparkLikeWhen,\n+ *,\n+ depth: int,\n+ function_name: str,\n+ root_names: list[str] | None,\n+ output_names: list[str] | None,\n+ returns_scalar: bool,\n+ backend_version: tuple[int, ...],\n+ version: Version,\n+ kwargs: dict[str, Any],\n+ ) -> None:\n+ self._backend_version = backend_version\n+ self._version = version\n+ self._call = call\n+ self._depth = depth\n+ self._function_name = function_name\n+ self._root_names = root_names\n+ self._output_names = output_names\n+ self._returns_scalar = returns_scalar\n+ self._kwargs = kwargs\n+\n+ def otherwise(self, value: SparkLikeExpr | Any) -> SparkLikeExpr:\n+ # type ignore because we are setting the `_call` attribute to a\n+ # callable object of type `SparkLikeWhen`, base class has the attribute as\n+ # only a `Callable`\n+ self._call._otherwise_value = value # type: ignore[attr-defined]\n+ self._function_name = \"whenotherwise\"\n+ return self\ndiff --git a/narwhals/dataframe.py b/narwhals/dataframe.py\nindex dd786ef3..1ae43028 100644\n--- a/narwhals/dataframe.py\n+++ b/narwhals/dataframe.py\n@@ -30,6 +30,7 @@ if TYPE_CHECKING:\n \n import numpy as np\n import pandas as pd\n+ import polars as pl\n import pyarrow as pa\n from typing_extensions import Self\n \n@@ -581,6 +582,72 @@ class DataFrame(BaseFrame[DataFrameT]):\n \"\"\"\n return self._compliant_frame.to_pandas()\n \n+ def to_polars(self) -> pl.DataFrame:\n+ \"\"\"Convert this DataFrame to a polars DataFrame.\n+\n+ Returns:\n+ A polars DataFrame.\n+\n+ Examples:\n+ Construct pandas, Polars (eager) and PyArrow DataFrames:\n+\n+ >>> import pandas as pd\n+ >>> import polars as pl\n+ >>> import pyarrow as pa\n+ >>> import narwhals as nw\n+ >>> from narwhals.typing import IntoDataFrame\n+ >>> data = {\"foo\": [1, 2, 3], \"bar\": [6.0, 7.0, 8.0], \"ham\": [\"a\", \"b\", \"c\"]}\n+ >>> df_pd = pd.DataFrame(data)\n+ >>> df_pl = pl.DataFrame(data)\n+ >>> df_pa = pa.table(data)\n+\n+ We define a library agnostic function:\n+\n+ >>> def agnostic_to_polars(df_native: IntoDataFrame) -> pl.DataFrame:\n+ ... df = nw.from_native(df_native)\n+ ... return df.to_polars()\n+\n+ We can then pass any supported library such as pandas, Polars (eager), or\n+ PyArrow to `agnostic_to_polars`:\n+\n+ >>> agnostic_to_polars(df_pd)\n+ shape: (3, 3)\n+ \u250c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2510\n+ \u2502 foo \u2506 bar \u2506 ham \u2502\n+ \u2502 --- \u2506 --- \u2506 --- \u2502\n+ \u2502 i64 \u2506 f64 \u2506 str \u2502\n+ \u255e\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2561\n+ \u2502 1 \u2506 6.0 \u2506 a \u2502\n+ \u2502 2 \u2506 7.0 \u2506 b \u2502\n+ \u2502 3 \u2506 8.0 \u2506 c \u2502\n+ \u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2518\n+\n+ >>> agnostic_to_polars(df_pl)\n+ shape: (3, 3)\n+ \u250c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2510\n+ \u2502 foo \u2506 bar \u2506 ham \u2502\n+ \u2502 --- \u2506 --- \u2506 --- \u2502\n+ \u2502 i64 \u2506 f64 \u2506 str \u2502\n+ \u255e\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2561\n+ \u2502 1 \u2506 6.0 \u2506 a \u2502\n+ \u2502 2 \u2506 7.0 \u2506 b \u2502\n+ \u2502 3 \u2506 8.0 \u2506 c \u2502\n+ \u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2518\n+\n+ >>> agnostic_to_polars(df_pa)\n+ shape: (3, 3)\n+ \u250c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2510\n+ \u2502 foo \u2506 bar \u2506 ham \u2502\n+ \u2502 --- \u2506 --- \u2506 --- \u2502\n+ \u2502 i64 \u2506 f64 \u2506 str \u2502\n+ \u255e\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2561\n+ \u2502 1 \u2506 6.0 \u2506 a \u2502\n+ \u2502 2 \u2506 7.0 \u2506 b \u2502\n+ \u2502 3 \u2506 8.0 \u2506 c \u2502\n+ \u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2518\n+ \"\"\"\n+ return self._compliant_frame.to_polars() # type: ignore[no-any-return]\n+\n @overload\n def write_csv(self, file: None = None) -> str: ...\n \ndiff --git a/narwhals/series.py b/narwhals/series.py\nindex 46ed53ab..dc80056c 100644\n--- a/narwhals/series.py\n+++ b/narwhals/series.py\n@@ -26,6 +26,7 @@ if TYPE_CHECKING:\n \n import numpy as np\n import pandas as pd\n+ import polars as pl\n import pyarrow as pa\n from typing_extensions import Self\n \n@@ -2764,8 +2765,8 @@ class Series(Generic[IntoSeriesT]):\n \"\"\"\n return self._compliant_series.to_numpy()\n \n- def to_pandas(self) -> pd.Series:\n- \"\"\"Convert to pandas.\n+ def to_pandas(self: Self) -> pd.Series:\n+ \"\"\"Convert to pandas Series.\n \n Returns:\n A pandas Series containing the data from this Series.\n@@ -2811,6 +2812,62 @@ class Series(Generic[IntoSeriesT]):\n \"\"\"\n return self._compliant_series.to_pandas()\n \n+ def to_polars(self: Self) -> pl.Series:\n+ \"\"\"Convert to polars Series.\n+\n+ Returns:\n+ A polars Series containing the data from this Series.\n+\n+ Examples:\n+ >>> import pandas as pd\n+ >>> import polars as pl\n+ >>> import pyarrow as pa\n+ >>> import narwhals as nw\n+ >>> from narwhals.typing import IntoSeries\n+\n+ >>> data = [1, 2, 3]\n+ >>> s_pd = pd.Series(data, name=\"a\")\n+ >>> s_pl = pl.Series(\"a\", data)\n+ >>> s_pa = pa.chunked_array([data])\n+\n+ We define a library agnostic function:\n+\n+ >>> def agnostic_to_polars(s_native: IntoSeries) -> pd.Series:\n+ ... s = nw.from_native(s_native, series_only=True)\n+ ... return s.to_polars()\n+\n+ We can then pass any supported library such as pandas, Polars, or\n+ PyArrow to `agnostic_to_polars`:\n+\n+ >>> agnostic_to_polars(s_pd) # doctest: +NORMALIZE_WHITESPACE\n+ shape: (3,)\n+ Series: 'a' [i64]\n+ [\n+ 1\n+ 2\n+ 3\n+ ]\n+\n+ >>> agnostic_to_polars(s_pl) # doctest: +NORMALIZE_WHITESPACE\n+ shape: (3,)\n+ Series: 'a' [i64]\n+ [\n+ 1\n+ 2\n+ 3\n+ ]\n+\n+ >>> agnostic_to_polars(s_pa) # doctest: +NORMALIZE_WHITESPACE\n+ shape: (3,)\n+ Series: '' [i64]\n+ [\n+ 1\n+ 2\n+ 3\n+ ]\n+ \"\"\"\n+ return self._compliant_series.to_polars() # type: ignore[no-any-return]\n+\n def __add__(self, other: object) -> Self:\n return self._from_compliant_series(\n self._compliant_series.__add__(self._extract_native(other))\ndiff --git a/pyproject.toml b/pyproject.toml\nindex 37dd3696..c461d703 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -5,7 +5,7 @@ build-backend = \"hatchling.build\"\n \n [project]\n name = \"narwhals\"\n-version = \"1.21.1\"\n+version = \"1.22.0\"\n dependencies = []\n requires-python = \">=3.8\"\n authors = [\ndiff --git a/utils/check_api_reference.py b/utils/check_api_reference.py\nindex 2b85a2dc..1b186774 100644\n--- a/utils/check_api_reference.py\n+++ b/utils/check_api_reference.py\n@@ -30,6 +30,7 @@ SERIES_ONLY_METHODS = {\n \"to_native\",\n \"to_numpy\",\n \"to_pandas\",\n+ \"to_polars\",\n \"value_counts\",\n \"zip_with\",\n \"__iter__\",\n", "test_patch": "diff --git a/tests/expr_and_series/when_test.py b/tests/expr_and_series/when_test.py\nindex 0faf5917..94e37aaa 100644\n--- a/tests/expr_and_series/when_test.py\n+++ b/tests/expr_and_series/when_test.py\n@@ -17,9 +17,7 @@ data = {\n }\n \n \n-def test_when(constructor: Constructor, request: pytest.FixtureRequest) -> None:\n- if \"pyspark\" in str(constructor):\n- request.applymarker(pytest.mark.xfail)\n+def test_when(constructor: Constructor) -> None:\n df = nw.from_native(constructor(data))\n result = df.select(nw.when(nw.col(\"a\") == 1).then(value=3).alias(\"a_when\"))\n expected = {\n@@ -28,9 +26,7 @@ def test_when(constructor: Constructor, request: pytest.FixtureRequest) -> None:\n assert_equal_data(result, expected)\n \n \n-def test_when_otherwise(constructor: Constructor, request: pytest.FixtureRequest) -> None:\n- if \"pyspark\" in str(constructor):\n- request.applymarker(pytest.mark.xfail)\n+def test_when_otherwise(constructor: Constructor) -> None:\n df = nw.from_native(constructor(data))\n result = df.select(nw.when(nw.col(\"a\") == 1).then(3).otherwise(6).alias(\"a_when\"))\n expected = {\n@@ -39,11 +35,7 @@ def test_when_otherwise(constructor: Constructor, request: pytest.FixtureRequest\n assert_equal_data(result, expected)\n \n \n-def test_multiple_conditions(\n- constructor: Constructor, request: pytest.FixtureRequest\n-) -> None:\n- if \"pyspark\" in str(constructor):\n- request.applymarker(pytest.mark.xfail)\n+def test_multiple_conditions(constructor: Constructor) -> None:\n df = nw.from_native(constructor(data))\n result = df.select(\n nw.when(nw.col(\"a\") < 3, nw.col(\"c\") < 5.0).then(3).alias(\"a_when\")\n@@ -85,11 +77,7 @@ def test_value_series(constructor_eager: ConstructorEager) -> None:\n assert_equal_data(result, expected)\n \n \n-def test_value_expression(\n- constructor: Constructor, request: pytest.FixtureRequest\n-) -> None:\n- if \"pyspark\" in str(constructor):\n- request.applymarker(pytest.mark.xfail)\n+def test_value_expression(constructor: Constructor) -> None:\n df = nw.from_native(constructor(data))\n result = df.select(nw.when(nw.col(\"a\") == 1).then(nw.col(\"a\") + 9).alias(\"a_when\"))\n expected = {\n@@ -122,11 +110,7 @@ def test_otherwise_series(constructor_eager: ConstructorEager) -> None:\n assert_equal_data(result, expected)\n \n \n-def test_otherwise_expression(\n- constructor: Constructor, request: pytest.FixtureRequest\n-) -> None:\n- if \"pyspark\" in str(constructor):\n- request.applymarker(pytest.mark.xfail)\n+def test_otherwise_expression(constructor: Constructor) -> None:\n df = nw.from_native(constructor(data))\n result = df.select(\n nw.when(nw.col(\"a\") == 1).then(-1).otherwise(nw.col(\"a\") + 7).alias(\"a_when\")\n@@ -140,7 +124,7 @@ def test_otherwise_expression(\n def test_when_then_otherwise_into_expr(\n constructor: Constructor, request: pytest.FixtureRequest\n ) -> None:\n- if (\"pyspark\" in str(constructor)) or \"duckdb\" in str(constructor):\n+ if \"duckdb\" in str(constructor):\n request.applymarker(pytest.mark.xfail)\n df = nw.from_native(constructor(data))\n result = df.select(nw.when(nw.col(\"a\") > 1).then(\"c\").otherwise(\"e\"))\n@@ -151,7 +135,7 @@ def test_when_then_otherwise_into_expr(\n def test_when_then_otherwise_lit_str(\n constructor: Constructor, request: pytest.FixtureRequest\n ) -> None:\n- if (\"pyspark\" in str(constructor)) or \"duckdb\" in str(constructor):\n+ if \"duckdb\" in str(constructor):\n request.applymarker(pytest.mark.xfail)\n df = nw.from_native(constructor(data))\n result = df.select(nw.when(nw.col(\"a\") > 1).then(nw.col(\"b\")).otherwise(nw.lit(\"z\")))\ndiff --git a/tests/frame/to_polars_test.py b/tests/frame/to_polars_test.py\nnew file mode 100644\nindex 00000000..d8683cbd\n--- /dev/null\n+++ b/tests/frame/to_polars_test.py\n@@ -0,0 +1,23 @@\n+from __future__ import annotations\n+\n+from typing import TYPE_CHECKING\n+\n+import polars as pl\n+import pytest\n+from polars.testing import assert_frame_equal\n+\n+import narwhals.stable.v1 as nw\n+\n+if TYPE_CHECKING:\n+ from tests.utils import ConstructorEager\n+\n+\n+@pytest.mark.filterwarnings(\"ignore:.*Passing a BlockManager.*:DeprecationWarning\")\n+def test_convert_polars(constructor_eager: ConstructorEager) -> None:\n+ data = {\"a\": [1, 3, 2], \"b\": [4, 4, 6], \"z\": [7.1, 8, 9]}\n+ df_raw = constructor_eager(data)\n+ result = nw.from_native(df_raw).to_polars() # type: ignore[union-attr]\n+\n+ expected = pl.DataFrame(data)\n+\n+ assert_frame_equal(result, expected)\ndiff --git a/tests/series_only/to_polars_test.py b/tests/series_only/to_polars_test.py\nnew file mode 100644\nindex 00000000..b5e66ea8\n--- /dev/null\n+++ b/tests/series_only/to_polars_test.py\n@@ -0,0 +1,24 @@\n+from __future__ import annotations\n+\n+from typing import TYPE_CHECKING\n+\n+import polars as pl\n+from polars.testing import assert_series_equal\n+\n+import narwhals.stable.v1 as nw\n+\n+if TYPE_CHECKING:\n+ from tests.utils import ConstructorEager\n+\n+data = [1, 3, 2]\n+\n+\n+def test_series_to_polars(constructor_eager: ConstructorEager) -> None:\n+ result = (\n+ nw.from_native(constructor_eager({\"a\": data}), eager_only=True)[\"a\"]\n+ .alias(\"a\")\n+ .to_polars()\n+ )\n+\n+ expected = pl.Series(\"a\", data)\n+ assert_series_equal(result, expected)\n", "FAIL_TO_PASS": ["tests/series_only/to_polars_test.py::test_series_to_polars[pandas[pyarrow]]", "tests/series_only/to_polars_test.py::test_series_to_polars[pyarrow]", "tests/series_only/to_polars_test.py::test_series_to_polars[pandas[nullable]]", "tests/series_only/to_polars_test.py::test_series_to_polars[pandas]", "tests/series_only/to_polars_test.py::test_series_to_polars[polars[eager]]", "tests/frame/to_polars_test.py::test_convert_polars[pandas[pyarrow]]", "tests/frame/to_polars_test.py::test_convert_polars[pandas]", "tests/frame/to_polars_test.py::test_convert_polars[pyarrow]", "tests/frame/to_polars_test.py::test_convert_polars[pandas[nullable]]", "tests/frame/to_polars_test.py::test_convert_polars[polars[eager]]"]}, {"instance_id": "narwhals-dev__narwhals-1810", "base_commit": "0b75d8502a19ad4ccfa8ddccab6f327adebf87d6", "gold_patch": "diff --git a/narwhals/_arrow/dataframe.py b/narwhals/_arrow/dataframe.py\nindex ed738647..96a8ef71 100644\n--- a/narwhals/_arrow/dataframe.py\n+++ b/narwhals/_arrow/dataframe.py\n@@ -395,10 +395,9 @@ class ArrowDataFrame(CompliantDataFrame, CompliantLazyFrame):\n )\n return self._from_native_frame(self._native_frame.drop(to_drop))\n \n- def drop_nulls(self: Self, subset: str | list[str] | None) -> Self:\n+ def drop_nulls(self: Self, subset: list[str] | None) -> Self:\n if subset is None:\n return self._from_native_frame(self._native_frame.drop_null())\n- subset = [subset] if isinstance(subset, str) else subset\n plx = self.__narwhals_namespace__()\n return self.filter(~plx.any_horizontal(plx.col(*subset).is_null()))\n \ndiff --git a/narwhals/_arrow/namespace.py b/narwhals/_arrow/namespace.py\nindex b02ad32e..70d372a5 100644\n--- a/narwhals/_arrow/namespace.py\n+++ b/narwhals/_arrow/namespace.py\n@@ -435,19 +435,18 @@ class ArrowWhen:\n \n plx = df.__narwhals_namespace__()\n condition = parse_into_expr(self._condition, namespace=plx)(df)[0]\n+\n try:\n value_series = parse_into_expr(self._then_value, namespace=plx)(df)[0]\n except TypeError:\n- # `self._otherwise_value` is a scalar and can't be converted to an expression\n- value_series = condition.__class__._from_iterable(\n- pa.repeat(pa.scalar(self._then_value), len(condition)),\n- name=\"literal\",\n- backend_version=self._backend_version,\n- version=self._version,\n+ # `self._then_value` is a scalar and can't be converted to an expression\n+ value_series = plx._create_series_from_scalar(\n+ self._then_value, reference_series=condition\n )\n \n- value_series_native = value_series._native_series\n- condition_native = condition._native_series\n+ condition_native, value_series_native = broadcast_series(\n+ [condition, value_series]\n+ )\n \n if self._otherwise_value is None:\n otherwise_native = pa.repeat(\n@@ -472,9 +471,7 @@ class ArrowWhen:\n ]\n else:\n otherwise_series = otherwise_expr(df)[0]\n- condition_native, otherwise_native = broadcast_series(\n- [condition, otherwise_series]\n- )\n+ _, otherwise_native = broadcast_series([condition, otherwise_series])\n return [\n value_series._from_native_series(\n pc.if_else(condition_native, value_series_native, otherwise_native)\ndiff --git a/narwhals/_dask/dataframe.py b/narwhals/_dask/dataframe.py\nindex 89e1bc48..1a8efc44 100644\n--- a/narwhals/_dask/dataframe.py\n+++ b/narwhals/_dask/dataframe.py\n@@ -149,10 +149,9 @@ class DaskLazyFrame(CompliantLazyFrame):\n )\n return self._from_native_frame(df)\n \n- def drop_nulls(self: Self, subset: str | list[str] | None) -> Self:\n+ def drop_nulls(self: Self, subset: list[str] | None) -> Self:\n if subset is None:\n return self._from_native_frame(self._native_frame.dropna())\n- subset = [subset] if isinstance(subset, str) else subset\n plx = self.__narwhals_namespace__()\n return self.filter(~plx.any_horizontal(plx.col(*subset).is_null()))\n \ndiff --git a/narwhals/_dask/namespace.py b/narwhals/_dask/namespace.py\nindex 23805afd..936b9abb 100644\n--- a/narwhals/_dask/namespace.py\n+++ b/narwhals/_dask/namespace.py\n@@ -398,13 +398,24 @@ class DaskWhen:\n plx = df.__narwhals_namespace__()\n condition = parse_into_expr(self._condition, namespace=plx)(df)[0]\n condition = cast(\"dx.Series\", condition)\n+\n try:\n- value_series = parse_into_expr(self._then_value, namespace=plx)(df)[0]\n+ then_expr = parse_into_expr(self._then_value, namespace=plx)\n except TypeError:\n- # `self._otherwise_value` is a scalar and can't be converted to an expression\n+ # `self._then_value` is a scalar and can't be converted to an expression\n+ value_sequence: Sequence[Any] = [self._then_value]\n+ is_scalar = True\n+ else:\n+ is_scalar = then_expr._returns_scalar # type: ignore[attr-defined]\n+ value_sequence = then_expr(df)[0]\n+\n+ if is_scalar:\n _df = condition.to_frame(\"a\")\n- _df[\"tmp\"] = self._then_value\n+ _df[\"tmp\"] = value_sequence[0]\n value_series = _df[\"tmp\"]\n+ else:\n+ value_series = value_sequence\n+\n value_series = cast(\"dx.Series\", value_series)\n validate_comparand(condition, value_series)\n \ndiff --git a/narwhals/_duckdb/dataframe.py b/narwhals/_duckdb/dataframe.py\nindex 98eca0bd..a3c2798b 100644\n--- a/narwhals/_duckdb/dataframe.py\n+++ b/narwhals/_duckdb/dataframe.py\n@@ -321,3 +321,12 @@ class DuckDBLazyFrame:\n )\n )\n return self._from_native_frame(result)\n+\n+ def drop_nulls(self: Self, subset: list[str] | None) -> Self:\n+ import duckdb\n+\n+ rel = self._native_frame\n+ subset_ = subset if subset is not None else rel.columns\n+ keep_condition = \" and \".join(f'\"{col}\" is not null' for col in subset_)\n+ query = f\"select * from rel where {keep_condition}\" # noqa: S608\n+ return self._from_native_frame(duckdb.sql(query))\ndiff --git a/narwhals/_pandas_like/dataframe.py b/narwhals/_pandas_like/dataframe.py\nindex 47c43a69..fdd53b4a 100644\n--- a/narwhals/_pandas_like/dataframe.py\n+++ b/narwhals/_pandas_like/dataframe.py\n@@ -371,10 +371,9 @@ class PandasLikeDataFrame:\n )\n return self._from_native_frame(df)\n \n- def drop_nulls(self, subset: str | list[str] | None) -> Self:\n+ def drop_nulls(self, subset: list[str] | None) -> Self:\n if subset is None:\n return self._from_native_frame(self._native_frame.dropna(axis=0))\n- subset = [subset] if isinstance(subset, str) else subset\n plx = self.__narwhals_namespace__()\n return self.filter(~plx.any_horizontal(plx.col(*subset).is_null()))\n \ndiff --git a/narwhals/_pandas_like/namespace.py b/narwhals/_pandas_like/namespace.py\nindex 52e56d34..4265a340 100644\n--- a/narwhals/_pandas_like/namespace.py\n+++ b/narwhals/_pandas_like/namespace.py\n@@ -461,20 +461,17 @@ class PandasWhen:\n \n plx = df.__narwhals_namespace__()\n condition = parse_into_expr(self._condition, namespace=plx)(df)[0]\n+\n try:\n value_series = parse_into_expr(self._then_value, namespace=plx)(df)[0]\n except TypeError:\n- # `self._otherwise_value` is a scalar and can't be converted to an expression\n- value_series = condition.__class__._from_iterable(\n- [self._then_value] * len(condition),\n- name=\"literal\",\n- index=condition._native_series.index,\n- implementation=self._implementation,\n- backend_version=self._backend_version,\n- version=self._version,\n+ # `self._then_value` is a scalar and can't be converted to an expression\n+ value_series = plx._create_series_from_scalar(\n+ self._then_value, reference_series=condition\n )\n- value_series_native, condition_native = broadcast_align_and_extract_native(\n- value_series, condition\n+\n+ condition_native, value_series_native = broadcast_align_and_extract_native(\n+ condition, value_series\n )\n \n if self._otherwise_value is None:\n@@ -494,7 +491,14 @@ class PandasWhen:\n ]\n else:\n otherwise_series = otherwise_expr(df)[0]\n- return [value_series.zip_with(condition, otherwise_series)]\n+ _, otherwise_native = broadcast_align_and_extract_native(\n+ condition, otherwise_series\n+ )\n+ return [\n+ value_series._from_native_series(\n+ value_series_native.where(condition_native, otherwise_native)\n+ )\n+ ]\n \n def then(self, value: PandasLikeExpr | PandasLikeSeries | Any) -> PandasThen:\n self._then_value = value\ndiff --git a/narwhals/_spark_like/dataframe.py b/narwhals/_spark_like/dataframe.py\nindex 7e7f41dd..34da43fd 100644\n--- a/narwhals/_spark_like/dataframe.py\n+++ b/narwhals/_spark_like/dataframe.py\n@@ -183,7 +183,7 @@ class SparkLikeLazyFrame:\n sort_cols = [sort_f(col) for col, sort_f in zip(flat_by, sort_funcs)]\n return self._from_native_frame(self._native_frame.sort(*sort_cols))\n \n- def drop_nulls(self: Self, subset: str | list[str] | None) -> Self:\n+ def drop_nulls(self: Self, subset: list[str] | None) -> Self:\n return self._from_native_frame(self._native_frame.dropna(subset=subset))\n \n def rename(self: Self, mapping: dict[str, str]) -> Self:\ndiff --git a/narwhals/dataframe.py b/narwhals/dataframe.py\nindex 1ae43028..e4504167 100644\n--- a/narwhals/dataframe.py\n+++ b/narwhals/dataframe.py\n@@ -107,7 +107,8 @@ class BaseFrame(Generic[FrameT]):\n self._compliant_frame.with_row_index(name),\n )\n \n- def drop_nulls(self: Self, subset: str | list[str] | None = None) -> Self:\n+ def drop_nulls(self: Self, subset: str | list[str] | None) -> Self:\n+ subset = [subset] if isinstance(subset, str) else subset\n return self._from_compliant_dataframe(\n self._compliant_frame.drop_nulls(subset=subset),\n )\n", "test_patch": "diff --git a/tests/expr_and_series/when_test.py b/tests/expr_and_series/when_test.py\nindex 94e37aaa..4f768db0 100644\n--- a/tests/expr_and_series/when_test.py\n+++ b/tests/expr_and_series/when_test.py\n@@ -141,3 +141,13 @@ def test_when_then_otherwise_lit_str(\n result = df.select(nw.when(nw.col(\"a\") > 1).then(nw.col(\"b\")).otherwise(nw.lit(\"z\")))\n expected = {\"b\": [\"z\", \"b\", \"c\"]}\n assert_equal_data(result, expected)\n+\n+\n+def test_when_then_otherwise_both_lit(constructor: Constructor) -> None:\n+ df = nw.from_native(constructor(data))\n+ result = df.select(\n+ x1=nw.when(nw.col(\"a\") > 1).then(nw.lit(42)).otherwise(nw.lit(-1)),\n+ x2=nw.when(nw.col(\"a\") > 2).then(nw.lit(42)).otherwise(nw.lit(-1)),\n+ )\n+ expected = {\"x1\": [-1, 42, 42], \"x2\": [-1, -1, 42]}\n+ assert_equal_data(result, expected)\ndiff --git a/tests/frame/drop_nulls_test.py b/tests/frame/drop_nulls_test.py\nindex 368ad6ba..c49b1712 100644\n--- a/tests/frame/drop_nulls_test.py\n+++ b/tests/frame/drop_nulls_test.py\n@@ -7,18 +7,16 @@ from tests.utils import Constructor\n from tests.utils import assert_equal_data\n \n data = {\n- \"a\": [1.0, 2.0, None, 4.0],\n- \"b\": [None, 3.0, None, 5.0],\n+ \"alpha\": [1.0, 2.0, None, 4.0],\n+ \"beta gamma\": [None, 3.0, None, 5.0],\n }\n \n \n-def test_drop_nulls(constructor: Constructor, request: pytest.FixtureRequest) -> None:\n- if \"duckdb\" in str(constructor):\n- request.applymarker(pytest.mark.xfail)\n+def test_drop_nulls(constructor: Constructor) -> None:\n result = nw.from_native(constructor(data)).drop_nulls()\n expected = {\n- \"a\": [2.0, 4.0],\n- \"b\": [3.0, 5.0],\n+ \"alpha\": [2.0, 4.0],\n+ \"beta gamma\": [3.0, 5.0],\n }\n assert_equal_data(result, expected)\n \n@@ -26,18 +24,15 @@ def test_drop_nulls(constructor: Constructor, request: pytest.FixtureRequest) ->\n @pytest.mark.parametrize(\n (\"subset\", \"expected\"),\n [\n- (\"a\", {\"a\": [1, 2.0, 4.0], \"b\": [None, 3.0, 5.0]}),\n- ([\"a\"], {\"a\": [1, 2.0, 4.0], \"b\": [None, 3.0, 5.0]}),\n- ([\"a\", \"b\"], {\"a\": [2.0, 4.0], \"b\": [3.0, 5.0]}),\n+ (\"alpha\", {\"alpha\": [1, 2.0, 4.0], \"beta gamma\": [None, 3.0, 5.0]}),\n+ ([\"alpha\"], {\"alpha\": [1, 2.0, 4.0], \"beta gamma\": [None, 3.0, 5.0]}),\n+ ([\"alpha\", \"beta gamma\"], {\"alpha\": [2.0, 4.0], \"beta gamma\": [3.0, 5.0]}),\n ],\n )\n def test_drop_nulls_subset(\n constructor: Constructor,\n subset: str | list[str],\n expected: dict[str, float],\n- request: pytest.FixtureRequest,\n ) -> None:\n- if \"duckdb\" in str(constructor):\n- request.applymarker(pytest.mark.xfail)\n result = nw.from_native(constructor(data)).drop_nulls(subset=subset)\n assert_equal_data(result, expected)\n", "FAIL_TO_PASS": ["tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pandas[pyarrow]]", "tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pyarrow]", "tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pandas]", "tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pandas[nullable]]"]}], "all_FAIL_TO_PASS": ["tests/series_only/to_polars_test.py::test_series_to_polars[pandas[pyarrow]]", "tests/series_only/to_polars_test.py::test_series_to_polars[pyarrow]", "tests/series_only/to_polars_test.py::test_series_to_polars[pandas[nullable]]", "tests/series_only/to_polars_test.py::test_series_to_polars[pandas]", "tests/series_only/to_polars_test.py::test_series_to_polars[polars[eager]]", "tests/frame/to_polars_test.py::test_convert_polars[pandas[pyarrow]]", "tests/frame/to_polars_test.py::test_convert_polars[pandas]", "tests/frame/to_polars_test.py::test_convert_polars[pyarrow]", "tests/frame/to_polars_test.py::test_convert_polars[pandas[nullable]]", "tests/frame/to_polars_test.py::test_convert_polars[polars[eager]]", "tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pandas[pyarrow]]", "tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pyarrow]", "tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pandas]", "tests/expr_and_series/when_test.py::test_when_then_otherwise_both_lit[pandas[nullable]]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "researchobject__ro-crate-py-149_x2", "level": 2, "source": "swerebenchv2", "repo": "ResearchObject/ro-crate-py", "image": "swerebenchv2/researchobject-ro-crate-py:149-1e4687a", "base_commit": "1e4687a0fb07a56e426a0cb876300de38e54e09c", "num_bugs": 2, "bugs": [{"instance_id": "researchobject__ro-crate-py-149", "base_commit": "1e4687a0fb07a56e426a0cb876300de38e54e09c", "gold_patch": "diff --git a/CITATION.cff b/CITATION.cff\nindex b255f9b..6599788 100644\n--- a/CITATION.cff\n+++ b/CITATION.cff\n@@ -16,6 +16,9 @@ authors:\n - family-names: Huber\n given-names: Sebastiaan\n orcid: https://orcid.org/0000-0001-5845-8880\n+ - family-names: Kinoshita\n+ given-names: Bruno\n+ orcid: https://orcid.org/0000-0001-8250-4074\n - family-names: Leo\n given-names: Simone\n orcid: https://orcid.org/0000-0001-8271-5429\ndiff --git a/README.md b/README.md\nindex 67b650e..8fe5702 100644\n--- a/README.md\n+++ b/README.md\n@@ -171,6 +171,60 @@ Note that entities can have multiple types, e.g.:\n \"@type\" = [\"File\", \"SoftwareSourceCode\"]\n ```\n \n+#### Modifying the crate from JSON-LD dictionaries\n+\n+The `add_jsonld` method allows to add a contextual entity directly from a\n+JSON-LD dictionary containing at least the `@id` and `@type` keys:\n+\n+```python\n+crate.add_jsonld({\n+ \"@id\": \"https://orcid.org/0000-0000-0000-0000\",\n+ \"@type\": \"Person\",\n+ \"name\": \"Alice Doe\"\n+})\n+```\n+\n+Existing entities can be updated from JSON-LD dictionaries via `update_jsonld`:\n+\n+```python\n+crate.update_jsonld({\n+ \"@id\": \"https://orcid.org/0000-0000-0000-0000\",\n+ \"name\": \"Alice K. Doe\"\n+})\n+```\n+\n+There is also an `add_or_update_jsonld` method that adds the entity if it's\n+not already in the crate and updates it if it already exists (note that, when\n+updating, the `@type` key is ignored). This allows to \"patch\" an RO-Crate from\n+a JSON-LD file. For instance, suppose you have the following `patch.json` file:\n+\n+```json\n+{\n+ \"@graph\": [\n+ {\n+ \"@id\": \"./\",\n+ \"author\": {\"@id\": \"https://orcid.org/0000-0000-0000-0001\"}\n+ },\n+ {\n+ \"@id\": \"https://orcid.org/0000-0000-0000-0001\",\n+ \"@type\": \"Person\",\n+ \"name\": \"Bob Doe\"\n+ }\n+ ]\n+}\n+```\n+\n+Then the following sets Bob as the author of the crate according to the above\n+file:\n+\n+```python\n+crate = ROCrate(\"temp-crate\")\n+with open(\"patch.json\") as f:\n+ json_data = json.load(f)\n+for d in json_data.get(\"@graph\", []):\n+ crate.add_or_update_jsonld(d)\n+```\n+\n ### Consuming an RO-Crate\n \n An existing RO-Crate package can be loaded from a directory or zip file:\n@@ -278,7 +332,7 @@ Note that data entities (e.g., workflows) must already be present in the directo\n cd test/test-data/ro-crate-galaxy-sortchangecase\n ```\n \n-This directory is already an ro-crate. Delete the metadata file to get a plain directory tree:\n+This directory is already an RO-Crate. Delete the metadata file to get a plain directory tree:\n \n ```bash\n rm ro-crate-metadata.json\n@@ -315,7 +369,6 @@ rocrate add test-instance test1 http://example.com -r jobs -i test1_1\n rocrate add test-definition test1 test/test1/sort-and-change-case-test.yml -e planemo -v '>=0.70'\n ```\n \n-\n ## License\n \n * Copyright 2019-2022 The University of Manchester, UK\ndiff --git a/rocrate/__init__.py b/rocrate/__init__.py\nindex 2ff3ad1..e19cc6d 100644\n--- a/rocrate/__init__.py\n+++ b/rocrate/__init__.py\n@@ -33,6 +33,7 @@ __author__ = \", \".join((\n 'Ignacio Eguinoa',\n 'Alban Gaignard',\n 'Sebastiaan Huber',\n+ 'Bruno Kinoshita',\n 'Simone Leo',\n 'Luca Pireddu',\n 'Laura Rodr\u00edguez-Navas',\ndiff --git a/rocrate/model/entity.py b/rocrate/model/entity.py\nindex ede44d2..6a64501 100644\n--- a/rocrate/model/entity.py\n+++ b/rocrate/model/entity.py\n@@ -32,7 +32,7 @@ class Entity(MutableMapping):\n if identifier:\n self.id = self.format_id(identifier)\n else:\n- self.id = \"#%s\" % uuid.uuid4()\n+ self.id = f\"#{uuid.uuid4()}\"\n if properties:\n empty = self._empty()\n empty.update(properties)\n@@ -46,7 +46,7 @@ class Entity(MutableMapping):\n return str(identifier)\n \n def __repr__(self):\n- return \"<%s %s>\" % (self.id, self.type)\n+ return f\"<{self.id} {self.type}>\"\n \n def properties(self):\n return self._jsonld\ndiff --git a/rocrate/rocrate.py b/rocrate/rocrate.py\nindex 264e894..d50a768 100644\n--- a/rocrate/rocrate.py\n+++ b/rocrate/rocrate.py\n@@ -513,6 +513,76 @@ class ROCrate():\n self.metadata.extra_terms.update(TESTING_EXTRA_TERMS)\n return definition\n \n+ def add_jsonld(self, jsonld):\n+ \"\"\"Add a JSON-LD dictionary as a contextual entity to the RO-Crate.\n+\n+ The `@id` and `@type` keys must be present in the JSON-LD dictionary.\n+\n+ Args:\n+ jsonld: A JSON-LD dictionary containing at least `@id` and `@type`.\n+ Return:\n+ The entity added to the RO-Crate.\n+ Raises:\n+ ValueError: if the jsonld object is empty or None or if the\n+ entity already exists (found via @id).\n+ \"\"\"\n+ required_keys = {\"@id\", \"@type\"}\n+ if not jsonld or not required_keys.issubset(jsonld):\n+ raise ValueError(\"you must provide a non-empty JSON-LD dictionary with @id and @type set\")\n+ entity_id = jsonld.pop(\"@id\")\n+ if self.get(entity_id):\n+ raise ValueError(f\"entity {entity_id} already exists in the RO-Crate\")\n+ return self.add(ContextEntity(\n+ self,\n+ entity_id,\n+ properties=jsonld\n+ ))\n+\n+ def update_jsonld(self, jsonld):\n+ \"\"\"Update an entity in the RO-Crate from a JSON-LD dictionary.\n+\n+ An `@id` must be present in the JSON-LD dictionary. Any other keys\n+ in the JSON-LD dictionary that start with `@` will be removed.\n+\n+ Args:\n+ jsonld: A JSON-LD dictionary.\n+ Return:\n+ The updated entity.\n+ Raises:\n+ ValueError: if the jsonld object is empty or None, if @id was not\n+ provided, or if the entity was not found.\n+ \"\"\"\n+ if not jsonld or \"@id\" not in jsonld:\n+ raise ValueError(\"you must provide a non-empty JSON-LD dictionary\")\n+ entity_id = jsonld.pop(\"@id\")\n+ entity: Entity = self.get(entity_id)\n+ if not entity:\n+ raise ValueError(f\"entity {entity_id} does not exist in the RO-Crate\")\n+ jsonld = {k: v for k, v in jsonld.items() if not k.startswith('@')}\n+ entity._jsonld.update(jsonld)\n+ return entity\n+\n+ def add_or_update_jsonld(self, jsonld):\n+ \"\"\"Add or update an entity from a JSON-LD dictionary.\n+\n+ An `@id` must be present in the JSON-LD dictionary.\n+\n+ Args:\n+ jsonld: A JSON-LD dictionary.\n+ Return:\n+ The added or updated entity.\n+ Raises:\n+ ValueError: if the jsonld object is empty or None or if @id was not\n+ provided.\n+ \"\"\"\n+ if not jsonld or \"@id\" not in jsonld:\n+ raise ValueError(\"you must provide a non-empty JSON-LD dictionary\")\n+ entity_id = jsonld.get(\"@id\")\n+ entity: Entity = self.get(entity_id)\n+ if not entity:\n+ return self.add_jsonld(jsonld)\n+ return self.update_jsonld(jsonld)\n+\n def __validate_suite(self, suite):\n if isinstance(suite, TestSuite):\n assert suite.crate is self\ndiff --git a/setup.py b/setup.py\nindex 5775239..30a2001 100755\n--- a/setup.py\n+++ b/setup.py\n@@ -61,6 +61,7 @@ setup(\n 'Ignacio Eguinoa',\n 'Alban Gaignard',\n 'Sebastiaan Huber',\n+ 'Bruno Kinoshita',\n 'Simone Leo',\n 'Luca Pireddu',\n 'Laura Rodr\u00edguez-Navas',\n", "test_patch": "diff --git a/test/test_jsonld.py b/test/test_jsonld.py\nnew file mode 100644\nindex 0000000..8e29535\n--- /dev/null\n+++ b/test/test_jsonld.py\n@@ -0,0 +1,227 @@\n+# Copyright 2019-2022 The University of Manchester, UK\n+# Copyright 2020-2022 Vlaams Instituut voor Biotechnologie (VIB), BE\n+# Copyright 2020-2022 Barcelona Supercomputing Center (BSC), ES\n+# Copyright 2020-2022 Center for Advanced Studies, Research and Development in Sardinia (CRS4), IT\n+# Copyright 2022 \u00c9cole Polytechnique F\u00e9d\u00e9rale de Lausanne, CH\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\"\"\"Tests for the JSON-LD methods of the ROCrate object.\"\"\"\n+\n+from uuid import uuid4\n+\n+import pytest\n+\n+from rocrate.rocrate import ROCrate\n+\n+\n+# --- add\n+\n+\n+def test_add_jsonld_raises_json_is_none():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.add_jsonld(None)\n+\n+\n+def test_add_jsonld_raises_json_is_empty():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.add_jsonld({})\n+\n+\n+def test_add_jsonld_raises_json_missing_id():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.add_jsonld({\n+ '@type': 'CreativeWork'\n+ })\n+\n+\n+def test_add_jsonld_raises_json_missing_type(test_data_dir):\n+ crate_dir = test_data_dir / 'read_crate'\n+ crate = ROCrate(crate_dir)\n+\n+ with pytest.raises(ValueError, match='.*@type.*'):\n+ crate.add_jsonld({\n+ '@id': './',\n+ 'license': 'NA'\n+ })\n+\n+\n+def test_add_jsonld_raises_json_duplicate_id(test_data_dir):\n+ crate_dir = test_data_dir / 'read_crate'\n+ crate = ROCrate(crate_dir)\n+\n+ with pytest.raises(ValueError, match='.*already exists.*'):\n+ crate.add_jsonld({\n+ '@id': './',\n+ '@type': 'Dataset',\n+ 'license': 'NA'\n+ })\n+\n+\n+def test_add_jsonld(test_data_dir):\n+ crate_dir = test_data_dir / 'read_crate'\n+ crate = ROCrate(crate_dir)\n+\n+ new_entity_id = f'#{uuid4()}'\n+\n+ crate.add_jsonld({\n+ '@id': new_entity_id,\n+ '@type': 'CreativeWork',\n+ 'name': 'A test entity'\n+ })\n+ new_entity = crate.get(new_entity_id)\n+ assert new_entity.type == 'CreativeWork'\n+ assert new_entity[\"name\"] == 'A test entity'\n+\n+\n+# --- update\n+\n+\n+def test_update_jsonld_raises_json_is_none():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.update_jsonld(None)\n+\n+\n+def test_update_jsonld_raises_json_is_empty():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.update_jsonld({})\n+\n+\n+def test_update_jsonld_raises_json_missing_id():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.update_jsonld({\n+ '@type': 'CreativeWork'\n+ })\n+\n+\n+def test_update_jsonld_raises_id_not_found(test_data_dir):\n+ crate_dir = test_data_dir / 'read_crate'\n+ crate = ROCrate(crate_dir)\n+\n+ missing_entity_id = f'#{uuid4()}'\n+\n+ with pytest.raises(ValueError, match='.*does not exist.*'):\n+ crate.update_jsonld({\n+ '@id': missing_entity_id,\n+ '@type': 'CreativeWork',\n+ 'name': 'This entity does not exist in the RO-Crate'\n+ })\n+\n+\n+def test_update_jsonld(test_data_dir):\n+ crate_dir = test_data_dir / 'read_crate'\n+ crate = ROCrate(crate_dir)\n+\n+ new_entity_id = f'#{uuid4()}'\n+\n+ crate.add_jsonld({\n+ '@id': new_entity_id,\n+ '@type': 'CreativeWork',\n+ 'name': 'A test entity'\n+ })\n+\n+ entity_added = crate.get(new_entity_id)\n+ assert entity_added.type == 'CreativeWork'\n+ assert entity_added['name'] == 'A test entity'\n+\n+ entity_added['name'] = 'No potatoes today'\n+ # N.B.: Properties that start with @ are ignored when updating.\n+ update_dict = entity_added._jsonld.copy()\n+ update_dict['@type'] = 'Dataset'\n+ crate.update_jsonld(update_dict)\n+\n+ updated_entity = crate.get(new_entity_id)\n+ assert entity_added.id == updated_entity.id\n+ assert updated_entity.type == 'CreativeWork'\n+ assert updated_entity['name'] == 'No potatoes today'\n+\n+ assert '@type' in update_dict\n+\n+\n+# --- add or update\n+\n+\n+def test_add_or_update_jsonld_raises_json_is_none():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.add_or_update_jsonld(None)\n+\n+\n+def test_add_or_update_jsonld_raises_json_is_empty():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.add_or_update_jsonld({})\n+\n+\n+def test_add_or_update_jsonld_raises_json_missing_id():\n+ crate = ROCrate()\n+\n+ with pytest.raises(ValueError, match='.*non-empty JSON-LD.*'):\n+ crate.add_or_update_jsonld({\n+ '@type': 'CreativeWork'\n+ })\n+\n+\n+def test_add_or_update_add_jsonld(test_data_dir):\n+ crate_dir = test_data_dir / 'read_crate'\n+ crate = ROCrate(crate_dir)\n+\n+ new_entity_id = f'#{uuid4()}'\n+\n+ crate.add_or_update_jsonld({\n+ '@id': new_entity_id,\n+ '@type': 'CreativeWork',\n+ 'name': 'A test entity'\n+ })\n+ new_entity = crate.get(new_entity_id)\n+ assert new_entity.type == 'CreativeWork'\n+ assert new_entity[\"name\"] == 'A test entity'\n+\n+\n+def test_add_or_update_update_jsonld(test_data_dir):\n+ crate_dir = test_data_dir / 'read_crate'\n+ crate = ROCrate(crate_dir)\n+\n+ new_entity_id = f'#{uuid4()}'\n+\n+ crate.add_jsonld({\n+ '@id': new_entity_id,\n+ '@type': 'CreativeWork',\n+ 'name': 'A test entity'\n+ })\n+\n+ entity_added = crate.get(new_entity_id)\n+ assert entity_added.type == 'CreativeWork'\n+ assert entity_added['name'] == 'A test entity'\n+\n+ entity_added['name'] = 'No potatoes today'\n+ crate.add_or_update_jsonld(entity_added._jsonld.copy())\n+\n+ updated_entity = crate.get(new_entity_id)\n+ assert entity_added.id == updated_entity.id\n+ assert entity_added.type == updated_entity.type\n+ assert updated_entity['name'] == 'No potatoes today'\ndiff --git a/test/test_model.py b/test/test_model.py\nindex 49561ec..fbfa8fd 100644\n--- a/test/test_model.py\n+++ b/test/test_model.py\n@@ -18,6 +18,7 @@\n \n import datetime\n import json\n+import os\n import tempfile\n import timeit\n import uuid\n@@ -95,6 +96,7 @@ def test_data_entities(test_data_dir):\n assert set(_.id for _ in (file_, dataset, data_entity)) <= part_ids\n \n \n+@pytest.mark.skipif(os.name != \"posix\", reason=\"CI sometimes fails on macOS\")\n def test_data_entities_perf():\n \"\"\"\\\n Test that adding a data entity happens in constant time.\n", "FAIL_TO_PASS": ["test/test_jsonld.py::test_add_jsonld_raises_json_is_none", "test/test_jsonld.py::test_add_jsonld_raises_json_is_empty", "test/test_jsonld.py::test_add_jsonld_raises_json_missing_id", "test/test_jsonld.py::test_add_jsonld_raises_json_missing_type", "test/test_jsonld.py::test_add_jsonld_raises_json_duplicate_id", "test/test_jsonld.py::test_add_jsonld", "test/test_jsonld.py::test_update_jsonld_raises_json_is_none", "test/test_jsonld.py::test_update_jsonld_raises_json_is_empty", "test/test_jsonld.py::test_update_jsonld_raises_json_missing_id", "test/test_jsonld.py::test_update_jsonld_raises_id_not_found", "test/test_jsonld.py::test_update_jsonld", "test/test_jsonld.py::test_add_or_update_jsonld_raises_json_is_none", "test/test_jsonld.py::test_add_or_update_jsonld_raises_json_is_empty", "test/test_jsonld.py::test_add_or_update_jsonld_raises_json_missing_id", "test/test_jsonld.py::test_add_or_update_add_jsonld", "test/test_jsonld.py::test_add_or_update_update_jsonld"]}, {"instance_id": "researchobject__ro-crate-py-152", "base_commit": "f5281c1c583b1b66bcd8e05e0953635519ba5b2f", "gold_patch": "diff --git a/rocrate/model/softwareapplication.py b/rocrate/model/softwareapplication.py\nindex c7bc8a5..29d8b2b 100644\n--- a/rocrate/model/softwareapplication.py\n+++ b/rocrate/model/softwareapplication.py\n@@ -54,7 +54,6 @@ class SoftwareApplication(ContextEntity, CreativeWork):\n \n \n PLANEMO_ID = \"https://w3id.org/ro/terms/test#PlanemoEngine\"\n-PLANEMO_DEFAULT_VERSION = \"0.74\"\n \n \n def planemo(crate):\ndiff --git a/rocrate/rocrate.py b/rocrate/rocrate.py\nindex 76f9105..02c57f8 100644\n--- a/rocrate/rocrate.py\n+++ b/rocrate/rocrate.py\n@@ -42,7 +42,7 @@ from .model.computationalworkflow import ComputationalWorkflow, WorkflowDescript\n from .model.computerlanguage import ComputerLanguage, get_lang\n from .model.testinstance import TestInstance\n from .model.testservice import TestService, get_service\n-from .model.softwareapplication import SoftwareApplication, get_app, PLANEMO_DEFAULT_VERSION\n+from .model.softwareapplication import SoftwareApplication, get_app\n from .model.testsuite import TestSuite\n \n from .utils import is_url, subclasses, get_norm_value, walk\n@@ -509,9 +509,6 @@ class ROCrate():\n self, suite, source=None, dest_path=None, fetch_remote=False, validate_url=False, properties=None,\n engine=\"planemo\", engine_version=None\n ):\n- if engine_version is None:\n- # FIXME: this should be engine-specific\n- engine_version = PLANEMO_DEFAULT_VERSION\n suite = self.__validate_suite(suite)\n definition = self.add(\n TestDefinition(self, source=source, dest_path=dest_path, fetch_remote=fetch_remote,\n@@ -523,7 +520,8 @@ class ROCrate():\n engine = get_app(self, engine)\n self.add(engine)\n definition.engine = engine\n- definition.engineVersion = engine_version\n+ if engine_version is not None:\n+ definition.engineVersion = engine_version\n suite.definition = definition\n self.metadata.extra_terms.update(TESTING_EXTRA_TERMS)\n return definition\n", "test_patch": "diff --git a/test/test_test_metadata.py b/test/test_test_metadata.py\nindex 219baa4..6ba584d 100644\n--- a/test/test_test_metadata.py\n+++ b/test/test_test_metadata.py\n@@ -243,6 +243,8 @@ def test_add_test_definition(test_data_dir, engine, engine_version):\n assert crate.dereference(PLANEMO) is d.engine\n if engine_version:\n assert d.engineVersion == engine_version\n+ else:\n+ assert \"engineVersion\" not in d\n \n \n def test_test_suites_prop(test_data_dir):\n", "FAIL_TO_PASS": ["test/test_test_metadata.py::test_add_test_definition[None-None]", "test/test_test_metadata.py::test_add_test_definition[planemo-None]"]}], "all_FAIL_TO_PASS": ["test/test_jsonld.py::test_add_jsonld_raises_json_is_none", "test/test_jsonld.py::test_add_jsonld_raises_json_is_empty", "test/test_jsonld.py::test_add_jsonld_raises_json_missing_id", "test/test_jsonld.py::test_add_jsonld_raises_json_missing_type", "test/test_jsonld.py::test_add_jsonld_raises_json_duplicate_id", "test/test_jsonld.py::test_add_jsonld", "test/test_jsonld.py::test_update_jsonld_raises_json_is_none", "test/test_jsonld.py::test_update_jsonld_raises_json_is_empty", "test/test_jsonld.py::test_update_jsonld_raises_json_missing_id", "test/test_jsonld.py::test_update_jsonld_raises_id_not_found", "test/test_jsonld.py::test_update_jsonld", "test/test_jsonld.py::test_add_or_update_jsonld_raises_json_is_none", "test/test_jsonld.py::test_add_or_update_jsonld_raises_json_is_empty", "test/test_jsonld.py::test_add_or_update_jsonld_raises_json_missing_id", "test/test_jsonld.py::test_add_or_update_add_jsonld", "test/test_jsonld.py::test_add_or_update_update_jsonld", "test/test_test_metadata.py::test_add_test_definition[None-None]", "test/test_test_metadata.py::test_add_test_definition[planemo-None]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "sdispater__tomlkit-82_x2", "level": 2, "source": "swerebenchv2", "repo": "sdispater/tomlkit", "image": "swerebenchv2/sdispater-tomlkit:82-6bdaadc", "base_commit": "6bdaadcd9c786d63643792dfc6de21d95372a87d", "num_bugs": 2, "bugs": [{"instance_id": "sdispater__tomlkit-82", "base_commit": "6bdaadcd9c786d63643792dfc6de21d95372a87d", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex 0d36421..a9e245c 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -25,7 +25,6 @@ after_success:\n jobs:\n include:\n - python: \"2.7\"\n- - python: \"3.4\"\n - python: \"3.5\"\n - python: \"3.6\"\n - python: \"3.7\"\ndiff --git a/tomlkit/container.py b/tomlkit/container.py\nindex b8197ba..a7d4fe9 100644\n--- a/tomlkit/container.py\n+++ b/tomlkit/container.py\n@@ -23,6 +23,9 @@ from .items import Whitespace\n from .items import item as _item\n \n \n+_NOT_SET = object()\n+\n+\n class Container(dict):\n \"\"\"\n A container for items within a TOMLDocument.\n@@ -501,6 +504,19 @@ class Container(dict):\n \n return self[key]\n \n+ def pop(self, key, default=_NOT_SET):\n+ try:\n+ value = self[key]\n+ except KeyError:\n+ if default is _NOT_SET:\n+ raise\n+\n+ return default\n+\n+ del self[key]\n+\n+ return value\n+\n def setdefault(\n self, key, default=None\n ): # type: (Union[Key, str], Any) -> Union[Item, Container]\n@@ -698,6 +714,23 @@ class OutOfOrderTableProxy(dict):\n def values(self):\n return self._internal_container.values()\n \n+ def items(self): # type: () -> Generator[Item]\n+ return self._internal_container.items()\n+\n+ def update(self, other): # type: (Dict) -> None\n+ self._internal_container.update(other)\n+\n+ def get(self, key, default=None): # type: (Any, Optional[Any]) -> Any\n+ return self._internal_container.get(key, default=default)\n+\n+ def pop(self, key, default=_NOT_SET):\n+ return self._internal_container.pop(key, default=default)\n+\n+ def setdefault(\n+ self, key, default=None\n+ ): # type: (Union[Key, str], Any) -> Union[Item, Container]\n+ return self._internal_container.setdefault(key, default=default)\n+\n def __contains__(self, key):\n return key in self._internal_container\n \n", "test_patch": "diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py\nindex b625e79..8c741ff 100644\n--- a/tests/test_toml_document.py\n+++ b/tests/test_toml_document.py\n@@ -551,5 +551,21 @@ key = \"value\"\n assert isinstance(doc[\"a\"], dict)\n assert isinstance(doc[\"a\"][\"a\"], dict)\n \n- assert \"key\" in doc[\"a\"][\"a\"]\n- assert \"c\" in doc[\"a\"][\"a\"]\n+ table = doc[\"a\"][\"a\"]\n+ assert \"key\" in table\n+ assert \"c\" in table\n+ assert \"value\" == table.get(\"key\")\n+ assert {} == table.get(\"c\")\n+ assert table.get(\"d\") is None\n+ assert \"foo\" == table.get(\"d\", \"foo\")\n+\n+ assert \"bar\" == table.setdefault(\"d\", \"bar\")\n+ assert \"bar\" == table[\"d\"]\n+\n+ assert \"value\" == table.pop(\"key\")\n+ assert \"key\" not in table\n+\n+ assert \"baz\" == table.pop(\"missing\", default=\"baz\")\n+\n+ with pytest.raises(KeyError):\n+ table.pop(\"missing\")\n", "FAIL_TO_PASS": ["tests/test_toml_document.py::test_out_of_order_tables_are_still_dicts"]}, {"instance_id": "sdispater__tomlkit-103", "base_commit": "3e6a2a719df1dbf6d3a44e6932736fa3a842aac6", "gold_patch": "diff --git a/tomlkit/_compat.py b/tomlkit/_compat.py\nindex d5cb1f8..8d3b0ae 100644\n--- a/tomlkit/_compat.py\n+++ b/tomlkit/_compat.py\n@@ -150,6 +150,12 @@ else:\n long = int\n \n \n+if PY36:\n+ OrderedDict = dict\n+else:\n+ from collections import OrderedDict\n+\n+\n def decode(string, encodings=None):\n if not PY2 and not isinstance(string, bytes):\n return string\ndiff --git a/tomlkit/api.py b/tomlkit/api.py\nindex 3f47526..3de4121 100644\n--- a/tomlkit/api.py\n+++ b/tomlkit/api.py\n@@ -34,12 +34,12 @@ def loads(string): # type: (str) -> _TOMLDocument\n return parse(string)\n \n \n-def dumps(data): # type: (_TOMLDocument) -> str\n+def dumps(data, sort_keys=False): # type: (_TOMLDocument, bool) -> str\n \"\"\"\n Dumps a TOMLDocument into a string.\n \"\"\"\n if not isinstance(data, _TOMLDocument) and isinstance(data, dict):\n- data = item(data)\n+ data = item(data, _sort_keys=sort_keys)\n \n return data.as_string()\n \ndiff --git a/tomlkit/items.py b/tomlkit/items.py\nindex 8218f9c..184ffe7 100644\n--- a/tomlkit/items.py\n+++ b/tomlkit/items.py\n@@ -28,7 +28,7 @@ else:\n from functools import lru_cache\n \n \n-def item(value, _parent=None):\n+def item(value, _parent=None, _sort_keys=False):\n from .container import Container\n \n if isinstance(value, Item):\n@@ -42,8 +42,11 @@ def item(value, _parent=None):\n return Float(value, Trivia(), str(value))\n elif isinstance(value, dict):\n val = Table(Container(), Trivia(), False)\n- for k, v in sorted(value.items(), key=lambda i: (isinstance(i[1], dict), i[0])):\n- val[k] = item(v, _parent=val)\n+ for k, v in sorted(\n+ value.items(),\n+ key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),\n+ ):\n+ val[k] = item(v, _parent=val, _sort_keys=_sort_keys)\n \n return val\n elif isinstance(value, list):\n@@ -57,13 +60,14 @@ def item(value, _parent=None):\n table = Table(Container(), Trivia(), True)\n \n for k, _v in sorted(\n- v.items(), key=lambda i: (isinstance(i[1], dict), i[0])\n+ v.items(),\n+ key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),\n ):\n- i = item(_v)\n+ i = item(_v, _sort_keys=_sort_keys)\n if isinstance(table, InlineTable):\n i.trivia.trail = \"\"\n \n- table[k] = item(i)\n+ table[k] = item(i, _sort_keys=_sort_keys)\n \n v = table\n \n", "test_patch": "diff --git a/tests/test_items.py b/tests/test_items.py\nindex c4b074c..5fc30de 100644\n--- a/tests/test_items.py\n+++ b/tests/test_items.py\n@@ -14,6 +14,7 @@ import pytest\n from tomlkit import inline_table\n from tomlkit import parse\n from tomlkit._compat import PY2\n+from tomlkit._compat import OrderedDict\n from tomlkit.exceptions import NonExistentKey\n from tomlkit.items import Bool\n from tomlkit.items import InlineTable\n@@ -208,8 +209,56 @@ bar = \"baz\"\n )\n \n \n-def test_dicts_are_converted_to_tables_and_sorted():\n- t = item({\"foo\": {\"bar\": \"baz\", \"abc\": 123, \"baz\": [{\"c\": 3, \"b\": 2, \"a\": 1}]}})\n+def test_dicts_are_converted_to_tables_and_keep_order():\n+ t = item(\n+ OrderedDict(\n+ [\n+ (\n+ \"foo\",\n+ OrderedDict(\n+ [\n+ (\"bar\", \"baz\"),\n+ (\"abc\", 123),\n+ (\"baz\", [OrderedDict([(\"c\", 3), (\"b\", 2), (\"a\", 1)])]),\n+ ]\n+ ),\n+ )\n+ ]\n+ )\n+ )\n+\n+ assert (\n+ t.as_string()\n+ == \"\"\"[foo]\n+bar = \"baz\"\n+abc = 123\n+\n+[[foo.baz]]\n+c = 3\n+b = 2\n+a = 1\n+\"\"\"\n+ )\n+\n+\n+def test_dicts_are_converted_to_tables_and_are_sorted_if_requested():\n+ t = item(\n+ OrderedDict(\n+ [\n+ (\n+ \"foo\",\n+ OrderedDict(\n+ [\n+ (\"bar\", \"baz\"),\n+ (\"abc\", 123),\n+ (\"baz\", [OrderedDict([(\"c\", 3), (\"b\", 2), (\"a\", 1)])]),\n+ ]\n+ ),\n+ )\n+ ]\n+ ),\n+ _sort_keys=True,\n+ )\n \n assert (\n t.as_string()\n@@ -226,7 +275,9 @@ c = 3\n \n \n def test_dicts_with_sub_dicts_are_properly_converted():\n- t = item({\"foo\": {\"bar\": {\"string\": \"baz\"}, \"int\": 34, \"float\": 3.14}})\n+ t = item(\n+ {\"foo\": {\"bar\": {\"string\": \"baz\"}, \"int\": 34, \"float\": 3.14}}, _sort_keys=True\n+ )\n \n assert (\n t.as_string()\n", "FAIL_TO_PASS": ["tests/test_items.py::test_key_comparison", "tests/test_items.py::test_items_can_be_appended_to_and_removed_from_a_table", "tests/test_items.py::test_items_can_be_appended_to_and_removed_from_an_inline_table", "tests/test_items.py::test_inf_and_nan_are_supported", "tests/test_items.py::test_hex_octal_and_bin_integers_are_supported", "tests/test_items.py::test_key_automatically_sets_proper_string_type_if_not_bare", "tests/test_items.py::test_array_behaves_like_a_list", "tests/test_items.py::test_array_multiline", "tests/test_items.py::test_dicts_are_converted_to_tables", "tests/test_items.py::test_dicts_are_converted_to_tables_and_keep_order", "tests/test_items.py::test_dicts_are_converted_to_tables_and_are_sorted_if_requested", "tests/test_items.py::test_dicts_with_sub_dicts_are_properly_converted", "tests/test_items.py::test_item_array_of_dicts_converted_to_aot", "tests/test_items.py::test_integers_behave_like_ints", "tests/test_items.py::test_floats_behave_like_floats", "tests/test_items.py::test_datetimes_behave_like_datetimes", "tests/test_items.py::test_dates_behave_like_dates", "tests/test_items.py::test_times_behave_like_times", "tests/test_items.py::test_strings_behave_like_strs", "tests/test_items.py::test_tables_behave_like_dicts", "tests/test_items.py::test_items_are_pickable", "tests/test_items.py::test_trim_comments_when_building_inline_table", "tests/test_items.py::test_deleting_inline_table_elemeent_does_not_leave_trailing_separator", "tests/test_items.py::test_booleans_comparison"]}], "all_FAIL_TO_PASS": ["tests/test_toml_document.py::test_out_of_order_tables_are_still_dicts", "tests/test_items.py::test_key_comparison", "tests/test_items.py::test_items_can_be_appended_to_and_removed_from_a_table", "tests/test_items.py::test_items_can_be_appended_to_and_removed_from_an_inline_table", "tests/test_items.py::test_inf_and_nan_are_supported", "tests/test_items.py::test_hex_octal_and_bin_integers_are_supported", "tests/test_items.py::test_key_automatically_sets_proper_string_type_if_not_bare", "tests/test_items.py::test_array_behaves_like_a_list", "tests/test_items.py::test_array_multiline", "tests/test_items.py::test_dicts_are_converted_to_tables", "tests/test_items.py::test_dicts_are_converted_to_tables_and_keep_order", "tests/test_items.py::test_dicts_are_converted_to_tables_and_are_sorted_if_requested", "tests/test_items.py::test_dicts_with_sub_dicts_are_properly_converted", "tests/test_items.py::test_item_array_of_dicts_converted_to_aot", "tests/test_items.py::test_integers_behave_like_ints", "tests/test_items.py::test_floats_behave_like_floats", "tests/test_items.py::test_datetimes_behave_like_datetimes", "tests/test_items.py::test_dates_behave_like_dates", "tests/test_items.py::test_times_behave_like_times", "tests/test_items.py::test_strings_behave_like_strs", "tests/test_items.py::test_tables_behave_like_dicts", "tests/test_items.py::test_items_are_pickable", "tests/test_items.py::test_trim_comments_when_building_inline_table", "tests/test_items.py::test_deleting_inline_table_elemeent_does_not_leave_trailing_separator", "tests/test_items.py::test_booleans_comparison"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "joke2k__faker-1887_x2", "level": 2, "source": "swerebenchv2", "repo": "joke2k/faker", "image": "swerebenchv2/joke2k-faker:1887-597e80a", "base_commit": "597e80a347faa6cefe06098870c64b040498794a", "num_bugs": 2, "bugs": [{"instance_id": "joke2k__faker-1887", "base_commit": "597e80a347faa6cefe06098870c64b040498794a", "gold_patch": "diff --git a/.bumpversion.cfg b/.bumpversion.cfg\nindex a392635f..f3fed20b 100644\n--- a/.bumpversion.cfg\n+++ b/.bumpversion.cfg\n@@ -1,5 +1,5 @@\n [bumpversion]\n-current_version = 18.11.2\n+current_version = 18.13.0\n files = VERSION faker/__init__.py docs/conf.py\n commit = True\n tag = True\ndiff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 81411978..ac2a557b 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -1,5 +1,13 @@\n ## Changelog\n \n+### [v18.13.0 - 2023-07-07](https://github.com/joke2k/faker/compare/v18.12.0...v18.13.0)\n+\n+* Add `.optional` proxy that may or may not return a fake value. Thanks @ligne.\n+\n+### [v18.12.0 - 2023-07-07](https://github.com/joke2k/faker/compare/v18.11.2...v18.12.0)\n+\n+* Add fake automotive `vin` number function. Thanks @cyanghsieh.\n+\n ### [v18.11.2 - 2023-06-27](https://github.com/joke2k/faker/compare/v18.11.1...v18.11.2)\n \n * Fix area codes for `fr_FR` mobile phone numbers. Thanks @QuentinFchx.\ndiff --git a/VERSION b/VERSION\nindex 0ec67166..d939939b 100644\n--- a/VERSION\n+++ b/VERSION\n@@ -1,1 +1,1 @@\n-18.11.2\n+18.13.0\ndiff --git a/docs/conf.py b/docs/conf.py\nindex de2064d9..7587165a 100644\n--- a/docs/conf.py\n+++ b/docs/conf.py\n@@ -51,9 +51,9 @@ copyright = \"2014, Daniele Faraglia\"\n # built documents.\n #\n # The short X.Y version.\n-version = \"18.11.2\"\n+version = \"18.13.0\"\n # The full version, including alpha/beta/rc tags.\n-release = \"18.11.2\"\n+release = \"18.13.0\"\n \n # The language for content autogenerated by Sphinx. Refer to documentation\n # for a list of supported languages.\ndiff --git a/faker/__init__.py b/faker/__init__.py\nindex cfbf27ff..d46861c1 100644\n--- a/faker/__init__.py\n+++ b/faker/__init__.py\n@@ -2,6 +2,6 @@ from faker.factory import Factory\n from faker.generator import Generator\n from faker.proxy import Faker\n \n-VERSION = \"18.11.2\"\n+VERSION = \"18.13.0\"\n \n __all__ = (\"Factory\", \"Generator\", \"Faker\")\ndiff --git a/faker/providers/automotive/__init__.py b/faker/providers/automotive/__init__.py\nindex 4a3156e3..1f89d37c 100644\n--- a/faker/providers/automotive/__init__.py\n+++ b/faker/providers/automotive/__init__.py\n@@ -7,6 +7,36 @@ from .. import BaseProvider, ElementsType\n localized = True\n \n \n+def calculate_vin_str_weight(s: str, weight_factor: list) -> int:\n+ \"\"\"\n+ multiply s(str) by weight_factor char by char\n+ e.g.\n+ input: s=\"ABCDE\", weight_factor=[1, 2, 3, 4, 5]\n+ return: A*1 + B*2 + C*3 + D*4 + E*5\n+\n+ will multiply 0 when len(weight_factor) less than len(s)\n+ \"\"\"\n+\n+ def _get_char_weight(c: str) -> int:\n+ \"\"\"A=1, B=2, ...., I=9,\n+ J=1, K=2, ..., R=9,\n+ S=2, T=3, ..., Z=9\n+ \"\"\"\n+ if ord(c) <= 64: # 0-9\n+ return int(c)\n+ if ord(c) <= 73: # A-I\n+ return ord(c) - 64\n+ if ord(c) <= 82: # J-R\n+ return ord(c) - 73\n+ # S-Z\n+ return ord(c) - 81\n+\n+ res = 0\n+ for i, c in enumerate(s):\n+ res += _get_char_weight(c) * weight_factor[i] if i < len(weight_factor) else 0\n+ return res\n+\n+\n class Provider(BaseProvider):\n \"\"\"Implement default automotive provider for Faker.\"\"\"\n \n@@ -20,3 +50,14 @@ class Provider(BaseProvider):\n self.random_element(self.license_formats),\n )\n return self.numerify(temp)\n+\n+ def vin(self) -> str:\n+ \"\"\"Generate vin number.\"\"\"\n+ vin_chars = \"1234567890ABCDEFGHJKLMNPRSTUVWXYZ\" # I, O, Q are restricted\n+ front_part = self.bothify(\"????????\", letters=vin_chars)\n+ rear_part = self.bothify(\"????????\", letters=vin_chars)\n+ front_part_weight = calculate_vin_str_weight(front_part, [8, 7, 6, 5, 4, 3, 2, 10])\n+ rear_part_weight = calculate_vin_str_weight(rear_part, [9, 8, 7, 6, 5, 4, 3, 2])\n+ checksum = (front_part_weight + rear_part_weight) % 11\n+ checksum_char = \"X\" if checksum == 10 else str(checksum)\n+ return front_part + checksum_char + rear_part\ndiff --git a/faker/providers/automotive/en_PH/__init__.py b/faker/providers/automotive/en_PH/__init__.py\nindex f78c0f9f..71f05d3e 100644\n--- a/faker/providers/automotive/en_PH/__init__.py\n+++ b/faker/providers/automotive/en_PH/__init__.py\n@@ -1,10 +1,10 @@\n from string import ascii_uppercase\n from typing import List\n \n-from ... import BaseProvider\n+from .. import Provider as AutomotiveProvider\n \n \n-class Provider(BaseProvider):\n+class Provider(AutomotiveProvider):\n \"\"\"Implement automotive provider for ``en_PH`` locale.\n \n Vehicle registration in the Philippines has many controversies and is full\ndiff --git a/faker/providers/ssn/es_MX/__init__.py b/faker/providers/ssn/es_MX/__init__.py\nindex 7207c3db..c91e18ba 100644\n--- a/faker/providers/ssn/es_MX/__init__.py\n+++ b/faker/providers/ssn/es_MX/__init__.py\n@@ -7,9 +7,16 @@ Registry Code (CURP) and Federal Taxpayer Registry ID (RFC).\n \n import random\n import string\n+from typing import Optional\n \n from .. import Provider as BaseProvider\n \n+try:\n+ from typing import Literal # type: ignore\n+except ImportError:\n+ from typing_extensions import Literal # type: ignore\n+\n+\n ALPHABET = string.ascii_uppercase\n ALPHANUMERIC = string.digits + ALPHABET\n VOWELS = \"AEIOU\"\n@@ -224,3 +231,30 @@ class Provider(BaseProvider):\n random_rfc = name_initials + birth_date + disambiguation_code\n \n return random_rfc\n+\n+ def elector_code(self, gender: Literal[\"H\", \"M\"] = None) -> str:\n+ \"\"\"\n+ Unique elector code issued by INE (Instituto Nacional Electoral) in Mexico.\n+\n+ :param gender: Gender for which to generate the code. Will be randomly\n+ selected if not provided.\n+ :type gender: str\n+ :return: a random INE elector code\n+\n+ :sample:\n+ :sample: gender='M'\n+ \"\"\"\n+ if gender and gender not in (\"H\", \"M\"):\n+ raise ValueError(\"Gender must be 'H' or 'M'\")\n+\n+ gender = gender or random.choice(\"HM\")\n+\n+ consonants = \"\".join(random.choices(CONSONANTS, k=6))\n+\n+ birthday = self.generator.date_of_birth()\n+ birth_date = birthday.strftime(\"%y%m%d\")\n+\n+ entity = random.randint(1, 33)\n+ disambiguation_code = \"\".join(random.choices(string.digits, k=3))\n+\n+ return f\"{consonants}{birth_date}{entity:02d}{gender}{disambiguation_code}\"\ndiff --git a/faker/proxy.py b/faker/proxy.py\nindex 78f159bc..653a5943 100644\n--- a/faker/proxy.py\n+++ b/faker/proxy.py\n@@ -4,7 +4,7 @@ import re\n \n from collections import OrderedDict\n from random import Random\n-from typing import Any, Callable, Dict, List, Optional, Pattern, Sequence, Tuple, Union\n+from typing import Any, Callable, Dict, List, Optional, Pattern, Sequence, Tuple, TypeVar, Union\n \n from .config import DEFAULT_LOCALE\n from .exceptions import UniquenessException\n@@ -15,6 +15,8 @@ from .utils.distribution import choices_distribution\n \n _UNIQUE_ATTEMPTS = 1000\n \n+RetType = TypeVar(\"RetType\")\n+\n \n class Faker:\n \"\"\"Proxy class capable of supporting multiple locales\"\"\"\n@@ -36,6 +38,7 @@ class Faker:\n self._factory_map = OrderedDict()\n self._weights = None\n self._unique_proxy = UniqueProxy(self)\n+ self._optional_proxy = OptionalProxy(self)\n \n if isinstance(locale, str):\n locales = [locale.replace(\"-\", \"_\")]\n@@ -137,6 +140,10 @@ class Faker:\n def unique(self) -> \"UniqueProxy\":\n return self._unique_proxy\n \n+ @property\n+ def optional(self) -> \"OptionalProxy\":\n+ return self._optional_proxy\n+\n def _select_factory(self, method_name: str) -> Factory:\n \"\"\"\n Returns a random factory that supports the provider method\n@@ -322,3 +329,38 @@ class UniqueProxy:\n return retval\n \n return wrapper\n+\n+\n+class OptionalProxy:\n+ \"\"\"\n+ Return either a fake value or None, with a customizable probability.\n+ \"\"\"\n+\n+ def __init__(self, proxy: Faker):\n+ self._proxy = proxy\n+\n+ def __getattr__(self, name: str) -> Any:\n+ obj = getattr(self._proxy, name)\n+ if callable(obj):\n+ return self._wrap(name, obj)\n+ else:\n+ raise TypeError(\"Accessing non-functions through .optional is not supported.\")\n+\n+ def __getstate__(self):\n+ # Copy the object's state from self.__dict__ which contains\n+ # all our instance attributes. Always use the dict.copy()\n+ # method to avoid modifying the original state.\n+ state = self.__dict__.copy()\n+ return state\n+\n+ def __setstate__(self, state):\n+ self.__dict__.update(state)\n+\n+ def _wrap(self, name: str, function: Callable[..., RetType]) -> Callable[..., Optional[RetType]]:\n+ @functools.wraps(function)\n+ def wrapper(*args: Any, prob: float = 0.5, **kwargs: Any) -> Optional[RetType]:\n+ if not 0 < prob <= 1.0:\n+ raise ValueError(\"prob must be between 0 and 1\")\n+ return function(*args, **kwargs) if self._proxy.boolean(chance_of_getting_true=int(prob * 100)) else None\n+\n+ return wrapper\n", "test_patch": "diff --git a/tests/providers/test_automotive.py b/tests/providers/test_automotive.py\nindex 62f725b0..ad193bc1 100644\n--- a/tests/providers/test_automotive.py\n+++ b/tests/providers/test_automotive.py\n@@ -2,6 +2,7 @@ import re\n \n from typing import Pattern\n \n+from faker.providers.automotive import calculate_vin_str_weight\n from faker.providers.automotive.de_DE import Provider as DeDeAutomotiveProvider\n from faker.providers.automotive.es_ES import Provider as EsEsAutomotiveProvider\n from faker.providers.automotive.ro_RO import Provider as RoRoAutomotiveProvider\n@@ -23,6 +24,19 @@ class _SimpleAutomotiveTestMixin:\n assert match is not None\n self.perform_extra_checks(license_plate, match)\n \n+ def test_vin(self, faker, num_samples):\n+ for _ in range(num_samples):\n+ vin_number = faker.vin()\n+ # length check: 17\n+ assert len(vin_number) == 17\n+\n+ # verify checksum: vin_number[8]\n+ front_part_weight = calculate_vin_str_weight(vin_number[:8], [8, 7, 6, 5, 4, 3, 2, 10])\n+ rear_part_weight = calculate_vin_str_weight(vin_number[9:], [9, 8, 7, 6, 5, 4, 3, 2])\n+ checksum = (front_part_weight + rear_part_weight) % 11\n+ checksum_str = \"X\" if checksum == 10 else str(checksum)\n+ assert vin_number[8] == checksum_str\n+\n \n class TestArBh(_SimpleAutomotiveTestMixin):\n \"\"\"Test ar_BH automotive provider methods\"\"\"\ndiff --git a/tests/providers/test_ssn.py b/tests/providers/test_ssn.py\nindex 0b2b83d4..6765f54c 100644\n--- a/tests/providers/test_ssn.py\n+++ b/tests/providers/test_ssn.py\n@@ -630,8 +630,8 @@ class TestEsCA(TestEsES):\n Faker.seed(0)\n \n \n-class TestEsMX(unittest.TestCase):\n- def setUp(self):\n+class TestEsMX:\n+ def setup_method(self):\n self.fake = Faker(\"es_MX\")\n Faker.seed(0)\n \n@@ -665,6 +665,26 @@ class TestEsMX(unittest.TestCase):\n assert len(rfc) == 12\n assert re.search(r\"^[A-Z]{3}\\d{6}[0-9A-Z]{3}$\", rfc)\n \n+ @pytest.mark.parametrize(\n+ \"gender,pattern\",\n+ [\n+ (\"M\", r\"^[A-Z]{6}\\d{8}M\\d{3}$\"),\n+ (\"H\", r\"^[A-Z]{6}\\d{8}H\\d{3}$\"),\n+ (None, r\"^[A-Z]{6}\\d{8}[HM]\\d{3}$\"),\n+ ],\n+ ids=[\"woman\", \"man\", \"any\"],\n+ )\n+ def test_elector_code(self, gender, pattern):\n+ for _ in range(100):\n+ elector_code = self.fake.elector_code(gender=gender)\n+\n+ assert len(elector_code) == 18\n+ assert re.search(pattern, elector_code)\n+\n+ def test_elector_code_unsupported_gender(self):\n+ with pytest.raises(ValueError, match=\"Gender must be\"):\n+ self.fake.elector_code(\"Z\")\n+\n \n class TestEsCL(unittest.TestCase):\n def setUp(self):\ndiff --git a/tests/test_optional.py b/tests/test_optional.py\nnew file mode 100644\nindex 00000000..f84bcdb3\n--- /dev/null\n+++ b/tests/test_optional.py\n@@ -0,0 +1,44 @@\n+import pytest\n+\n+from faker import Faker\n+\n+\n+class TestOptionalClass:\n+ def test_optional(self) -> None:\n+ fake = Faker()\n+\n+ assert {fake.optional.boolean() for _ in range(10)} == {True, False, None}\n+\n+ def test_optional_probability(self) -> None:\n+ \"\"\"The probability is configurable.\"\"\"\n+ fake = Faker()\n+\n+ fake.optional.name(prob=0.1)\n+\n+ def test_optional_arguments(self) -> None:\n+ \"\"\"Other arguments are passed through to the function.\"\"\"\n+ fake = Faker()\n+\n+ fake.optional.pyint(1, 2, prob=0.4)\n+\n+ def test_optional_valid_range(self) -> None:\n+ \"\"\"Only probabilities in the range (0, 1].\"\"\"\n+ fake = Faker()\n+\n+ with pytest.raises(ValueError, match=\"\"):\n+ fake.optional.name(prob=0)\n+\n+ with pytest.raises(ValueError, match=\"\"):\n+ fake.optional.name(prob=1.1)\n+\n+ with pytest.raises(ValueError, match=\"\"):\n+ fake.optional.name(prob=-3)\n+\n+ def test_functions_only(self):\n+ \"\"\"Accessing non-functions through the `.optional` attribute\n+ will throw a TypeError.\"\"\"\n+\n+ fake = Faker()\n+\n+ with pytest.raises(TypeError, match=\"Accessing non-functions through .optional is not supported.\"):\n+ fake.optional.locales\ndiff --git a/tests/test_proxy.py b/tests/test_proxy.py\nindex 5a7e8dbd..322bc396 100644\n--- a/tests/test_proxy.py\n+++ b/tests/test_proxy.py\n@@ -428,6 +428,7 @@ class TestFakerProxyClass:\n \"_factory_map\",\n \"_weights\",\n \"_unique_proxy\",\n+ \"_optional_proxy\",\n ]\n )\n for factory in fake.factories:\n", "FAIL_TO_PASS": ["tests/providers/test_automotive.py::TestArBh::test_license_plate", "tests/providers/test_automotive.py::TestArBh::test_vin", "tests/providers/test_automotive.py::TestAzAz::test_license_plate", "tests/providers/test_automotive.py::TestAzAz::test_vin", "tests/providers/test_automotive.py::TestSkSk::test_license_plate", "tests/providers/test_automotive.py::TestSkSk::test_vin", "tests/providers/test_automotive.py::TestPtBr::test_license_plate", "tests/providers/test_automotive.py::TestPtBr::test_vin", "tests/providers/test_automotive.py::TestPtPt::test_license_plate", "tests/providers/test_automotive.py::TestPtPt::test_vin", "tests/providers/test_automotive.py::TestHeIl::test_license_plate", "tests/providers/test_automotive.py::TestHeIl::test_vin", "tests/providers/test_automotive.py::TestHuHu::test_license_plate", "tests/providers/test_automotive.py::TestHuHu::test_vin", "tests/providers/test_automotive.py::TestDeDe::test_license_plate", "tests/providers/test_automotive.py::TestDeDe::test_vin", "tests/providers/test_automotive.py::TestSvSe::test_license_plate", "tests/providers/test_automotive.py::TestSvSe::test_vin", "tests/providers/test_automotive.py::TestPlPl::test_License_plate", "tests/providers/test_automotive.py::TestEnPh::test_license_plate", "tests/providers/test_automotive.py::TestEnPh::test_vin", "tests/providers/test_automotive.py::TestEnPh::test_motorcycle_plate", "tests/providers/test_automotive.py::TestEnPh::test_automobile_plate", "tests/providers/test_automotive.py::TestEnPh::test_protocol_plate", "tests/providers/test_automotive.py::TestFilPh::test_license_plate", "tests/providers/test_automotive.py::TestFilPh::test_vin", "tests/providers/test_automotive.py::TestFilPh::test_motorcycle_plate", "tests/providers/test_automotive.py::TestFilPh::test_automobile_plate", "tests/providers/test_automotive.py::TestFilPh::test_protocol_plate", "tests/providers/test_automotive.py::TestTlPh::test_license_plate", "tests/providers/test_automotive.py::TestTlPh::test_vin", "tests/providers/test_automotive.py::TestTlPh::test_motorcycle_plate", "tests/providers/test_automotive.py::TestTlPh::test_automobile_plate", "tests/providers/test_automotive.py::TestTlPh::test_protocol_plate", "tests/providers/test_automotive.py::TestRuRu::test_license_plate", "tests/providers/test_automotive.py::TestRuRu::test_vin", "tests/providers/test_automotive.py::TestRuRu::test_vehicle_category", "tests/providers/test_automotive.py::TestFrFr::test_license_plate", "tests/providers/test_automotive.py::TestFrFr::test_vin", "tests/providers/test_automotive.py::TestItIt::test_license_plate", "tests/providers/test_automotive.py::TestItIt::test_vin", "tests/providers/test_automotive.py::TestNoNo::test_license_plate", "tests/providers/test_automotive.py::TestNoNo::test_vin", "tests/providers/test_automotive.py::TestEsCo::test_license_plate", "tests/providers/test_automotive.py::TestEsCo::test_vin", "tests/providers/test_automotive.py::TestEsEs::test_plate_new_format", "tests/providers/test_automotive.py::TestEsEs::test_plate_old_format", "tests/providers/test_automotive.py::TestEsEs::test_plate_old_format_explicit_province_prefix", "tests/providers/test_automotive.py::TestEsEs::test_plate_format", "tests/providers/test_automotive.py::TestThTh::test_license_plate", "tests/providers/test_automotive.py::TestThTh::test_vin", "tests/providers/test_automotive.py::TestTrTr::test_license_plate", "tests/providers/test_automotive.py::TestTrTr::test_vin", "tests/providers/test_automotive.py::TestRoRo::test_license_plate", "tests/providers/test_automotive.py::TestRoRo::test_vin", "tests/providers/test_automotive.py::TestElGr::test_license_plate", "tests/providers/test_automotive.py::TestElGr::test_vin", "tests/providers/test_automotive.py::TestNlNl::test_license_plate", "tests/providers/test_automotive.py::TestNlNl::test_vin", "tests/providers/test_automotive.py::TestNlNl::test_plate_car", "tests/providers/test_automotive.py::TestNlNl::test_plate_motorbike", "tests/providers/test_automotive.py::TestViVn::test_license_plate", "tests/providers/test_automotive.py::TestViVn::test_vin", "tests/providers/test_automotive.py::TestFiFi::test_license_plate", "tests/providers/test_automotive.py::TestFiFi::test_vin", "tests/providers/test_automotive.py::TestSqAl::test_license_plate", "tests/providers/test_automotive.py::TestSqAl::test_vin", "tests/providers/test_automotive.py::TestDeCh::test_license_plate", "tests/providers/test_automotive.py::TestDeCh::test_vin", "tests/providers/test_automotive.py::TestNlBe::test_license_plate", "tests/providers/test_automotive.py::TestNlBe::test_vin", "tests/providers/test_automotive.py::TestZhCn::test_license_plate", "tests/providers/test_automotive.py::TestZhCn::test_vin", "tests/providers/test_automotive.py::TestZhTw::test_license_plate", "tests/providers/test_automotive.py::TestZhTw::test_vin", "tests/providers/test_ssn.py::TestSvSE::test_org_and_vat_id", "tests/providers/test_ssn.py::TestSvSE::test_org_id_long_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_org_id_long_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_org_id_short_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_org_id_short_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_long_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_long_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_short_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_short_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_vat_id", "tests/providers/test_ssn.py::TestBgBG::test_vat_id", "tests/providers/test_ssn.py::TestCsCZ::test_birth_number", "tests/providers/test_ssn.py::TestCsCZ::test_vat_id", "tests/providers/test_ssn.py::TestSkSK::test_birth_number", "tests/providers/test_ssn.py::TestSkSK::test_vat_id", "tests/providers/test_ssn.py::TestDeAT::test_vat_id", "tests/providers/test_ssn.py::TestElCY::test_vat_id", "tests/providers/test_ssn.py::TestElGr::test_police_id", "tests/providers/test_ssn.py::TestElGr::test_ssn", "tests/providers/test_ssn.py::TestElGr::test_tin", "tests/providers/test_ssn.py::TestElGr::test_vat_id", "tests/providers/test_ssn.py::TestEnCA::test_ssn", "tests/providers/test_ssn.py::TestEnUS::test_bad_tin_type", "tests/providers/test_ssn.py::TestEnUS::test_ein", "tests/providers/test_ssn.py::TestEnUS::test_invalid_ssn", "tests/providers/test_ssn.py::TestEnUS::test_itin", "tests/providers/test_ssn.py::TestEnUS::test_prohibited_ssn_value", "tests/providers/test_ssn.py::TestEnUS::test_ssn", "tests/providers/test_ssn.py::TestEnUS::test_wrong_tin_type_case", "tests/providers/test_ssn.py::TestEsCO::test_legal_person_nit", "tests/providers/test_ssn.py::TestEsCO::test_legal_person_nit_with_check_digit", "tests/providers/test_ssn.py::TestEsCO::test_natural_person_nit_with_check_digit", "tests/providers/test_ssn.py::TestEsCO::test_nit_check_digit", "tests/providers/test_ssn.py::TestEsCO::test_nuip", "tests/providers/test_ssn.py::TestEsES::test_cif", "tests/providers/test_ssn.py::TestEsES::test_doi", "tests/providers/test_ssn.py::TestEsES::test_nie", "tests/providers/test_ssn.py::TestEsES::test_nif", "tests/providers/test_ssn.py::TestEsES::test_vat_id", "tests/providers/test_ssn.py::TestEsCA::test_cif", "tests/providers/test_ssn.py::TestEsCA::test_doi", "tests/providers/test_ssn.py::TestEsCA::test_nie", "tests/providers/test_ssn.py::TestEsCA::test_nif", "tests/providers/test_ssn.py::TestEsCA::test_vat_id", "tests/providers/test_ssn.py::TestEsMX::test_ssn", "tests/providers/test_ssn.py::TestEsMX::test_curp", "tests/providers/test_ssn.py::TestEsMX::test_rfc_natural", "tests/providers/test_ssn.py::TestEsMX::test_rfc_legal", "tests/providers/test_ssn.py::TestEsMX::test_elector_code[woman]", "tests/providers/test_ssn.py::TestEsMX::test_elector_code[man]", "tests/providers/test_ssn.py::TestEsMX::test_elector_code[any]", "tests/providers/test_ssn.py::TestEsMX::test_elector_code_unsupported_gender", "tests/providers/test_ssn.py::TestEsCL::test_rut", "tests/providers/test_ssn.py::TestEtEE::test_ssn", "tests/providers/test_ssn.py::TestEtEE::test_ssn_2000", "tests/providers/test_ssn.py::TestEtEE::test_ssn_2100", "tests/providers/test_ssn.py::TestEtEE::test_ssn_checksum", "tests/providers/test_ssn.py::TestEtEE::test_vat_id", "tests/providers/test_ssn.py::TestFiFI::test_artifical_ssn", "tests/providers/test_ssn.py::TestFiFI::test_century_code", "tests/providers/test_ssn.py::TestFiFI::test_ssn_sanity", "tests/providers/test_ssn.py::TestFiFI::test_valid_ssn", "tests/providers/test_ssn.py::TestFiFI::test_vat_id", "tests/providers/test_ssn.py::TestFrFR::test_checksum", "tests/providers/test_ssn.py::TestFrFR::test_ssn", "tests/providers/test_ssn.py::TestFrFR::test_vat_id", "tests/providers/test_ssn.py::TestFrCH::test_checksum[checksum_remainder_11]", "tests/providers/test_ssn.py::TestFrCH::test_checksum[checksum_remainder_10]", "tests/providers/test_ssn.py::TestFrCH::test_checksum[checksum_remainder_other]", "tests/providers/test_ssn.py::TestEnGB::test_vat_id", "tests/providers/test_ssn.py::TestHrHR::test_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn_checksum", "tests/providers/test_ssn.py::TestHrHR::test_vat_id", "tests/providers/test_ssn.py::TestHuHU::test_ssn", "tests/providers/test_ssn.py::TestHuHU::test_vat_id", "tests/providers/test_ssn.py::TestItIT::test_checksum", "tests/providers/test_ssn.py::TestItIT::test_ssn", "tests/providers/test_ssn.py::TestItIT::test_ssn_with_latin_chars", "tests/providers/test_ssn.py::TestItIT::test_vat_id", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_cpf", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_rg", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn_checksum", "tests/providers/test_ssn.py::TestNlBE::test_ssn", "tests/providers/test_ssn.py::TestNlNL::test_vat_id", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_gender_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_gender_passed", "tests/providers/test_ssn.py::TestPlPL::test_calculate_month", "tests/providers/test_ssn.py::TestPlPL::test_ssn", "tests/providers/test_ssn.py::TestPlPL::test_ssn_checksum", "tests/providers/test_ssn.py::TestPlPL::test_vat_id", "tests/providers/test_ssn.py::TestEnPh::test_PH_gsis", "tests/providers/test_ssn.py::TestEnPh::test_PH_pagibig", "tests/providers/test_ssn.py::TestEnPh::test_PH_philhealth", "tests/providers/test_ssn.py::TestEnPh::test_PH_sss", "tests/providers/test_ssn.py::TestEnPh::test_PH_umid", "tests/providers/test_ssn.py::TestFilPh::test_PH_gsis", "tests/providers/test_ssn.py::TestFilPh::test_PH_pagibig", "tests/providers/test_ssn.py::TestFilPh::test_PH_philhealth", "tests/providers/test_ssn.py::TestFilPh::test_PH_sss", "tests/providers/test_ssn.py::TestFilPh::test_PH_umid", "tests/providers/test_ssn.py::TestThTH::test_ssn", "tests/providers/test_ssn.py::TestThTH::test_vat_id", "tests/providers/test_ssn.py::TestTlPh::test_PH_gsis", "tests/providers/test_ssn.py::TestTlPh::test_PH_pagibig", "tests/providers/test_ssn.py::TestTlPh::test_PH_philhealth", "tests/providers/test_ssn.py::TestTlPh::test_PH_sss", "tests/providers/test_ssn.py::TestTlPh::test_PH_umid", "tests/providers/test_ssn.py::TestEnIn::test_first_digit_non_zero", "tests/providers/test_ssn.py::TestEnIn::test_length", "tests/providers/test_ssn.py::TestEnIn::test_valid_luhn", "tests/providers/test_ssn.py::TestZhCN::test_zh_CN_ssn", "tests/providers/test_ssn.py::TestZhCN::test_zh_CN_ssn_gender_passed", "tests/providers/test_ssn.py::TestZhCN::test_zh_CN_ssn_invalid_gender_passed", "tests/providers/test_ssn.py::TestRoRO::test_ssn", "tests/providers/test_ssn.py::TestRoRO::test_ssn_checksum", "tests/providers/test_ssn.py::TestRoRO::test_vat_checksum", "tests/providers/test_ssn.py::TestRoRO::test_vat_id", "tests/providers/test_ssn.py::TestLvLV::test_century_code", "tests/providers/test_ssn.py::TestLvLV::test_ssn_sanity", "tests/providers/test_ssn.py::TestLvLV::test_vat_id", "tests/providers/test_ssn.py::TestZhTW::test_checksum", "tests/providers/test_ssn.py::TestZhTW::test_gender", "tests/providers/test_ssn.py::TestZhTW::test_length", "tests/test_optional.py::TestOptionalClass::test_optional", "tests/test_optional.py::TestOptionalClass::test_optional_probability", "tests/test_optional.py::TestOptionalClass::test_optional_arguments", "tests/test_optional.py::TestOptionalClass::test_optional_valid_range", "tests/test_optional.py::TestOptionalClass::test_functions_only", "tests/test_proxy.py::TestFakerProxyClass::test_unspecified_locale", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_string", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_list", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_list_invalid_value_type", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_ordereddict", "tests/test_proxy.py::TestFakerProxyClass::test_invalid_locale", "tests/test_proxy.py::TestFakerProxyClass::test_items", "tests/test_proxy.py::TestFakerProxyClass::test_dunder_getitem", "tests/test_proxy.py::TestFakerProxyClass::test_seed_classmethod", "tests/test_proxy.py::TestFakerProxyClass::test_seed_class_locales", "tests/test_proxy.py::TestFakerProxyClass::test_seed_instance", "tests/test_proxy.py::TestFakerProxyClass::test_seed_locale", "tests/test_proxy.py::TestFakerProxyClass::test_single_locale_proxy_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_proxy_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_caching_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_no_weights", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_with_weights", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_single_provider", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_shared_providers", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_unsupported_method", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_single_choice", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_with_locales", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_multiple_locales", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_multiple_choices", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_enabled_multiple_choices", "tests/test_proxy.py::TestFakerProxyClass::test_dir_include_all_providers_attribute_in_list", "tests/test_proxy.py::TestFakerProxyClass::test_copy", "tests/test_proxy.py::TestFakerProxyClass::test_pickle"]}, {"instance_id": "joke2k__faker-1946", "base_commit": "6e258eefb8cfed8ad796e2712f708e5fb08ba439", "gold_patch": "diff --git a/faker/providers/date_time/__init__.py b/faker/providers/date_time/__init__.py\nindex 17b9debd..b3a2197f 100644\n--- a/faker/providers/date_time/__init__.py\n+++ b/faker/providers/date_time/__init__.py\n@@ -1,3 +1,4 @@\n+import platform\n import re\n \n from calendar import timegm\n@@ -73,6 +74,21 @@ for name, sym in [\n \n \n class Provider(BaseProvider):\n+ # NOTE: Windows only guarantee second precision, in order to emulate that\n+ # we need to inspect the platform to determine which function is most\n+ # appropriate to generate random seconds with.\n+ if platform.system() == \"Windows\":\n+\n+ @property\n+ def _rand_seconds(self):\n+ return self.generator.random.randint\n+\n+ else:\n+\n+ @property\n+ def _rand_seconds(self):\n+ return self.generator.random.uniform\n+\n centuries: ElementsType[str] = [\n \"I\",\n \"II\",\n@@ -1814,7 +1830,7 @@ class Provider(BaseProvider):\n \"\"\"\n start_datetime = self._parse_start_datetime(start_datetime)\n end_datetime = self._parse_end_datetime(end_datetime)\n- return self.generator.random.randint(start_datetime, end_datetime)\n+ return self._rand_seconds(start_datetime, end_datetime)\n \n def time_delta(self, end_datetime: Optional[DateParseType] = None) -> timedelta:\n \"\"\"\n@@ -1824,7 +1840,7 @@ class Provider(BaseProvider):\n end_datetime = self._parse_end_datetime(end_datetime)\n seconds = end_datetime - start_datetime\n \n- ts = self.generator.random.randint(*sorted([0, seconds]))\n+ ts = self._rand_seconds(*sorted([0, seconds]))\n return timedelta(seconds=ts)\n \n def date_time(\n@@ -1867,7 +1883,7 @@ class Provider(BaseProvider):\n start_time = -62135596800 if start_datetime is None else self._parse_start_datetime(start_datetime)\n end_datetime = self._parse_end_datetime(end_datetime)\n \n- ts = self.generator.random.randint(start_time, end_datetime)\n+ ts = self._rand_seconds(start_time, end_datetime)\n # NOTE: using datetime.fromtimestamp(ts) directly will raise\n # a \"ValueError: timestamp out of range for platform time_t\"\n # on some platforms due to system C functions;\n@@ -2033,7 +2049,7 @@ class Provider(BaseProvider):\n if end_date - start_date <= 1:\n ts = start_date + self.generator.random.random()\n else:\n- ts = self.generator.random.randint(start_date, end_date)\n+ ts = self._rand_seconds(start_date, end_date)\n if tzinfo is None:\n return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts)\n else:\n@@ -2132,7 +2148,7 @@ class Provider(BaseProvider):\n datetime_to_timestamp(datetime.now(tzinfo)) if datetime_end is None else self._parse_date_time(datetime_end)\n )\n \n- timestamp = self.generator.random.randint(datetime_start_, datetime_end_)\n+ timestamp = self._rand_seconds(datetime_start_, datetime_end_)\n try:\n if tzinfo is None:\n pick = convert_timestamp_to_datetime(timestamp, tzlocal())\n", "test_patch": "diff --git a/tests/providers/test_date_time.py b/tests/providers/test_date_time.py\nindex 492b3ec3..bb8cb69a 100644\n--- a/tests/providers/test_date_time.py\n+++ b/tests/providers/test_date_time.py\n@@ -183,7 +183,6 @@ class TestDateTime(unittest.TestCase):\n assert not self.fake.iso8601().endswith(\"+00:00\")\n assert self.fake.iso8601(utc).endswith(\"+00:00\")\n assert self.fake.iso8601()[10] == \"T\"\n- assert len(self.fake.iso8601()) == 19\n assert len(self.fake.iso8601(timespec=\"hours\")) == 13\n assert len(self.fake.iso8601(timespec=\"minutes\")) == 16\n assert len(self.fake.iso8601(timespec=\"seconds\")) == 19\n@@ -194,6 +193,14 @@ class TestDateTime(unittest.TestCase):\n assert self.fake.iso8601(tzinfo=utc, sep=\" \")[10] == \" \"\n assert self.fake.iso8601(tzinfo=utc, sep=\"_\")[10] == \"_\"\n \n+ @pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"windows does not support sub second precision\")\n+ def test_iso8601_fractional_seconds_win(self):\n+ assert len(self.fake.iso8601()) == 19\n+\n+ @pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"non windows does support sub second precision\")\n+ def test_iso8601_fractional_seconds_non_win(self):\n+ assert len(self.fake.iso8601()) == 26\n+\n def test_date_object(self):\n assert isinstance(self.fake.date_object(), date)\n \n@@ -493,7 +500,7 @@ class TestDateTime(unittest.TestCase):\n \n constrained_unix_time = self.fake.unix_time(end_datetime=end_datetime, start_datetime=start_datetime)\n \n- self.assertIsInstance(constrained_unix_time, int)\n+ self.assertIsInstance(constrained_unix_time, (int, float))\n self.assertBetween(\n constrained_unix_time,\n datetime_to_timestamp(start_datetime),\n@@ -505,7 +512,7 @@ class TestDateTime(unittest.TestCase):\n \n recent_unix_time = self.fake.unix_time(start_datetime=one_day_ago)\n \n- self.assertIsInstance(recent_unix_time, int)\n+ self.assertIsInstance(recent_unix_time, (int, float))\n self.assertBetween(\n recent_unix_time,\n datetime_to_timestamp(one_day_ago),\n@@ -517,7 +524,7 @@ class TestDateTime(unittest.TestCase):\n \n distant_unix_time = self.fake.unix_time(end_datetime=one_day_after_epoch_start)\n \n- self.assertIsInstance(distant_unix_time, int)\n+ self.assertIsInstance(distant_unix_time, (int, float))\n self.assertBetween(\n distant_unix_time,\n datetime_to_timestamp(epoch_start),\n@@ -527,7 +534,7 @@ class TestDateTime(unittest.TestCase):\n # Ensure wide-open unix_times are generated correctly\n self.fake.unix_time()\n \n- self.assertIsInstance(constrained_unix_time, int)\n+ self.assertIsInstance(constrained_unix_time, (int, float))\n self.assertBetween(constrained_unix_time, 0, datetime_to_timestamp(now))\n \n # Ensure it does not throw error with startdate='now' for machines with negative offset\n@@ -538,6 +545,16 @@ class TestDateTime(unittest.TestCase):\n if platform.system() != \"Windows\":\n del os.environ[\"TZ\"]\n \n+ @pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"windows does not support sub second precision\")\n+ def test_unix_time_win(self):\n+ unix_time = self.fake.unix_time()\n+ assert isinstance(unix_time, int)\n+\n+ @pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"non windows does support sub second precision\")\n+ def test_unix_time_non_win(self):\n+ unix_time = self.fake.unix_time()\n+ assert isinstance(unix_time, float)\n+\n def test_change_year(self):\n _2020_06_01 = datetime.strptime(\"2020-06-01\", \"%Y-%m-%d\")\n _20_years_ago = change_year(_2020_06_01, -20)\n", "FAIL_TO_PASS": ["tests/providers/test_date_time.py::TestDateTime::test_iso8601_fractional_seconds_non_win", "tests/providers/test_date_time.py::TestDateTime::test_unix_time_non_win"]}], "all_FAIL_TO_PASS": ["tests/providers/test_automotive.py::TestArBh::test_license_plate", "tests/providers/test_automotive.py::TestArBh::test_vin", "tests/providers/test_automotive.py::TestAzAz::test_license_plate", "tests/providers/test_automotive.py::TestAzAz::test_vin", "tests/providers/test_automotive.py::TestSkSk::test_license_plate", "tests/providers/test_automotive.py::TestSkSk::test_vin", "tests/providers/test_automotive.py::TestPtBr::test_license_plate", "tests/providers/test_automotive.py::TestPtBr::test_vin", "tests/providers/test_automotive.py::TestPtPt::test_license_plate", "tests/providers/test_automotive.py::TestPtPt::test_vin", "tests/providers/test_automotive.py::TestHeIl::test_license_plate", "tests/providers/test_automotive.py::TestHeIl::test_vin", "tests/providers/test_automotive.py::TestHuHu::test_license_plate", "tests/providers/test_automotive.py::TestHuHu::test_vin", "tests/providers/test_automotive.py::TestDeDe::test_license_plate", "tests/providers/test_automotive.py::TestDeDe::test_vin", "tests/providers/test_automotive.py::TestSvSe::test_license_plate", "tests/providers/test_automotive.py::TestSvSe::test_vin", "tests/providers/test_automotive.py::TestPlPl::test_License_plate", "tests/providers/test_automotive.py::TestEnPh::test_license_plate", "tests/providers/test_automotive.py::TestEnPh::test_vin", "tests/providers/test_automotive.py::TestEnPh::test_motorcycle_plate", "tests/providers/test_automotive.py::TestEnPh::test_automobile_plate", "tests/providers/test_automotive.py::TestEnPh::test_protocol_plate", "tests/providers/test_automotive.py::TestFilPh::test_license_plate", "tests/providers/test_automotive.py::TestFilPh::test_vin", "tests/providers/test_automotive.py::TestFilPh::test_motorcycle_plate", "tests/providers/test_automotive.py::TestFilPh::test_automobile_plate", "tests/providers/test_automotive.py::TestFilPh::test_protocol_plate", "tests/providers/test_automotive.py::TestTlPh::test_license_plate", "tests/providers/test_automotive.py::TestTlPh::test_vin", "tests/providers/test_automotive.py::TestTlPh::test_motorcycle_plate", "tests/providers/test_automotive.py::TestTlPh::test_automobile_plate", "tests/providers/test_automotive.py::TestTlPh::test_protocol_plate", "tests/providers/test_automotive.py::TestRuRu::test_license_plate", "tests/providers/test_automotive.py::TestRuRu::test_vin", "tests/providers/test_automotive.py::TestRuRu::test_vehicle_category", "tests/providers/test_automotive.py::TestFrFr::test_license_plate", "tests/providers/test_automotive.py::TestFrFr::test_vin", "tests/providers/test_automotive.py::TestItIt::test_license_plate", "tests/providers/test_automotive.py::TestItIt::test_vin", "tests/providers/test_automotive.py::TestNoNo::test_license_plate", "tests/providers/test_automotive.py::TestNoNo::test_vin", "tests/providers/test_automotive.py::TestEsCo::test_license_plate", "tests/providers/test_automotive.py::TestEsCo::test_vin", "tests/providers/test_automotive.py::TestEsEs::test_plate_new_format", "tests/providers/test_automotive.py::TestEsEs::test_plate_old_format", "tests/providers/test_automotive.py::TestEsEs::test_plate_old_format_explicit_province_prefix", "tests/providers/test_automotive.py::TestEsEs::test_plate_format", "tests/providers/test_automotive.py::TestThTh::test_license_plate", "tests/providers/test_automotive.py::TestThTh::test_vin", "tests/providers/test_automotive.py::TestTrTr::test_license_plate", "tests/providers/test_automotive.py::TestTrTr::test_vin", "tests/providers/test_automotive.py::TestRoRo::test_license_plate", "tests/providers/test_automotive.py::TestRoRo::test_vin", "tests/providers/test_automotive.py::TestElGr::test_license_plate", "tests/providers/test_automotive.py::TestElGr::test_vin", "tests/providers/test_automotive.py::TestNlNl::test_license_plate", "tests/providers/test_automotive.py::TestNlNl::test_vin", "tests/providers/test_automotive.py::TestNlNl::test_plate_car", "tests/providers/test_automotive.py::TestNlNl::test_plate_motorbike", "tests/providers/test_automotive.py::TestViVn::test_license_plate", "tests/providers/test_automotive.py::TestViVn::test_vin", "tests/providers/test_automotive.py::TestFiFi::test_license_plate", "tests/providers/test_automotive.py::TestFiFi::test_vin", "tests/providers/test_automotive.py::TestSqAl::test_license_plate", "tests/providers/test_automotive.py::TestSqAl::test_vin", "tests/providers/test_automotive.py::TestDeCh::test_license_plate", "tests/providers/test_automotive.py::TestDeCh::test_vin", "tests/providers/test_automotive.py::TestNlBe::test_license_plate", "tests/providers/test_automotive.py::TestNlBe::test_vin", "tests/providers/test_automotive.py::TestZhCn::test_license_plate", "tests/providers/test_automotive.py::TestZhCn::test_vin", "tests/providers/test_automotive.py::TestZhTw::test_license_plate", "tests/providers/test_automotive.py::TestZhTw::test_vin", "tests/providers/test_ssn.py::TestSvSE::test_org_and_vat_id", "tests/providers/test_ssn.py::TestSvSE::test_org_id_long_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_org_id_long_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_org_id_short_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_org_id_short_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_long_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_long_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_short_no_dash", "tests/providers/test_ssn.py::TestSvSE::test_pers_id_short_with_dash", "tests/providers/test_ssn.py::TestSvSE::test_vat_id", "tests/providers/test_ssn.py::TestBgBG::test_vat_id", "tests/providers/test_ssn.py::TestCsCZ::test_birth_number", "tests/providers/test_ssn.py::TestCsCZ::test_vat_id", "tests/providers/test_ssn.py::TestSkSK::test_birth_number", "tests/providers/test_ssn.py::TestSkSK::test_vat_id", "tests/providers/test_ssn.py::TestDeAT::test_vat_id", "tests/providers/test_ssn.py::TestElCY::test_vat_id", "tests/providers/test_ssn.py::TestElGr::test_police_id", "tests/providers/test_ssn.py::TestElGr::test_ssn", "tests/providers/test_ssn.py::TestElGr::test_tin", "tests/providers/test_ssn.py::TestElGr::test_vat_id", "tests/providers/test_ssn.py::TestEnCA::test_ssn", "tests/providers/test_ssn.py::TestEnUS::test_bad_tin_type", "tests/providers/test_ssn.py::TestEnUS::test_ein", "tests/providers/test_ssn.py::TestEnUS::test_invalid_ssn", "tests/providers/test_ssn.py::TestEnUS::test_itin", "tests/providers/test_ssn.py::TestEnUS::test_prohibited_ssn_value", "tests/providers/test_ssn.py::TestEnUS::test_ssn", "tests/providers/test_ssn.py::TestEnUS::test_wrong_tin_type_case", "tests/providers/test_ssn.py::TestEsCO::test_legal_person_nit", "tests/providers/test_ssn.py::TestEsCO::test_legal_person_nit_with_check_digit", "tests/providers/test_ssn.py::TestEsCO::test_natural_person_nit_with_check_digit", "tests/providers/test_ssn.py::TestEsCO::test_nit_check_digit", "tests/providers/test_ssn.py::TestEsCO::test_nuip", "tests/providers/test_ssn.py::TestEsES::test_cif", "tests/providers/test_ssn.py::TestEsES::test_doi", "tests/providers/test_ssn.py::TestEsES::test_nie", "tests/providers/test_ssn.py::TestEsES::test_nif", "tests/providers/test_ssn.py::TestEsES::test_vat_id", "tests/providers/test_ssn.py::TestEsCA::test_cif", "tests/providers/test_ssn.py::TestEsCA::test_doi", "tests/providers/test_ssn.py::TestEsCA::test_nie", "tests/providers/test_ssn.py::TestEsCA::test_nif", "tests/providers/test_ssn.py::TestEsCA::test_vat_id", "tests/providers/test_ssn.py::TestEsMX::test_ssn", "tests/providers/test_ssn.py::TestEsMX::test_curp", "tests/providers/test_ssn.py::TestEsMX::test_rfc_natural", "tests/providers/test_ssn.py::TestEsMX::test_rfc_legal", "tests/providers/test_ssn.py::TestEsMX::test_elector_code[woman]", "tests/providers/test_ssn.py::TestEsMX::test_elector_code[man]", "tests/providers/test_ssn.py::TestEsMX::test_elector_code[any]", "tests/providers/test_ssn.py::TestEsMX::test_elector_code_unsupported_gender", "tests/providers/test_ssn.py::TestEsCL::test_rut", "tests/providers/test_ssn.py::TestEtEE::test_ssn", "tests/providers/test_ssn.py::TestEtEE::test_ssn_2000", "tests/providers/test_ssn.py::TestEtEE::test_ssn_2100", "tests/providers/test_ssn.py::TestEtEE::test_ssn_checksum", "tests/providers/test_ssn.py::TestEtEE::test_vat_id", "tests/providers/test_ssn.py::TestFiFI::test_artifical_ssn", "tests/providers/test_ssn.py::TestFiFI::test_century_code", "tests/providers/test_ssn.py::TestFiFI::test_ssn_sanity", "tests/providers/test_ssn.py::TestFiFI::test_valid_ssn", "tests/providers/test_ssn.py::TestFiFI::test_vat_id", "tests/providers/test_ssn.py::TestFrFR::test_checksum", "tests/providers/test_ssn.py::TestFrFR::test_ssn", "tests/providers/test_ssn.py::TestFrFR::test_vat_id", "tests/providers/test_ssn.py::TestFrCH::test_checksum[checksum_remainder_11]", "tests/providers/test_ssn.py::TestFrCH::test_checksum[checksum_remainder_10]", "tests/providers/test_ssn.py::TestFrCH::test_checksum[checksum_remainder_other]", "tests/providers/test_ssn.py::TestEnGB::test_vat_id", "tests/providers/test_ssn.py::TestHrHR::test_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn_checksum", "tests/providers/test_ssn.py::TestHrHR::test_vat_id", "tests/providers/test_ssn.py::TestHuHU::test_ssn", "tests/providers/test_ssn.py::TestHuHU::test_vat_id", "tests/providers/test_ssn.py::TestItIT::test_checksum", "tests/providers/test_ssn.py::TestItIT::test_ssn", "tests/providers/test_ssn.py::TestItIT::test_ssn_with_latin_chars", "tests/providers/test_ssn.py::TestItIT::test_vat_id", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_cpf", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_rg", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn_checksum", "tests/providers/test_ssn.py::TestNlBE::test_ssn", "tests/providers/test_ssn.py::TestNlNL::test_vat_id", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_gender_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_gender_passed", "tests/providers/test_ssn.py::TestPlPL::test_calculate_month", "tests/providers/test_ssn.py::TestPlPL::test_ssn", "tests/providers/test_ssn.py::TestPlPL::test_ssn_checksum", "tests/providers/test_ssn.py::TestPlPL::test_vat_id", "tests/providers/test_ssn.py::TestEnPh::test_PH_gsis", "tests/providers/test_ssn.py::TestEnPh::test_PH_pagibig", "tests/providers/test_ssn.py::TestEnPh::test_PH_philhealth", "tests/providers/test_ssn.py::TestEnPh::test_PH_sss", "tests/providers/test_ssn.py::TestEnPh::test_PH_umid", "tests/providers/test_ssn.py::TestFilPh::test_PH_gsis", "tests/providers/test_ssn.py::TestFilPh::test_PH_pagibig", "tests/providers/test_ssn.py::TestFilPh::test_PH_philhealth", "tests/providers/test_ssn.py::TestFilPh::test_PH_sss", "tests/providers/test_ssn.py::TestFilPh::test_PH_umid", "tests/providers/test_ssn.py::TestThTH::test_ssn", "tests/providers/test_ssn.py::TestThTH::test_vat_id", "tests/providers/test_ssn.py::TestTlPh::test_PH_gsis", "tests/providers/test_ssn.py::TestTlPh::test_PH_pagibig", "tests/providers/test_ssn.py::TestTlPh::test_PH_philhealth", "tests/providers/test_ssn.py::TestTlPh::test_PH_sss", "tests/providers/test_ssn.py::TestTlPh::test_PH_umid", "tests/providers/test_ssn.py::TestEnIn::test_first_digit_non_zero", "tests/providers/test_ssn.py::TestEnIn::test_length", "tests/providers/test_ssn.py::TestEnIn::test_valid_luhn", "tests/providers/test_ssn.py::TestZhCN::test_zh_CN_ssn", "tests/providers/test_ssn.py::TestZhCN::test_zh_CN_ssn_gender_passed", "tests/providers/test_ssn.py::TestZhCN::test_zh_CN_ssn_invalid_gender_passed", "tests/providers/test_ssn.py::TestRoRO::test_ssn", "tests/providers/test_ssn.py::TestRoRO::test_ssn_checksum", "tests/providers/test_ssn.py::TestRoRO::test_vat_checksum", "tests/providers/test_ssn.py::TestRoRO::test_vat_id", "tests/providers/test_ssn.py::TestLvLV::test_century_code", "tests/providers/test_ssn.py::TestLvLV::test_ssn_sanity", "tests/providers/test_ssn.py::TestLvLV::test_vat_id", "tests/providers/test_ssn.py::TestZhTW::test_checksum", "tests/providers/test_ssn.py::TestZhTW::test_gender", "tests/providers/test_ssn.py::TestZhTW::test_length", "tests/test_optional.py::TestOptionalClass::test_optional", "tests/test_optional.py::TestOptionalClass::test_optional_probability", "tests/test_optional.py::TestOptionalClass::test_optional_arguments", "tests/test_optional.py::TestOptionalClass::test_optional_valid_range", "tests/test_optional.py::TestOptionalClass::test_functions_only", "tests/test_proxy.py::TestFakerProxyClass::test_unspecified_locale", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_string", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_list", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_list_invalid_value_type", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_ordereddict", "tests/test_proxy.py::TestFakerProxyClass::test_invalid_locale", "tests/test_proxy.py::TestFakerProxyClass::test_items", "tests/test_proxy.py::TestFakerProxyClass::test_dunder_getitem", "tests/test_proxy.py::TestFakerProxyClass::test_seed_classmethod", "tests/test_proxy.py::TestFakerProxyClass::test_seed_class_locales", "tests/test_proxy.py::TestFakerProxyClass::test_seed_instance", "tests/test_proxy.py::TestFakerProxyClass::test_seed_locale", "tests/test_proxy.py::TestFakerProxyClass::test_single_locale_proxy_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_proxy_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_caching_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_no_weights", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_with_weights", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_single_provider", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_shared_providers", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_unsupported_method", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_single_choice", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_with_locales", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_multiple_locales", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_multiple_choices", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_enabled_multiple_choices", "tests/test_proxy.py::TestFakerProxyClass::test_dir_include_all_providers_attribute_in_list", "tests/test_proxy.py::TestFakerProxyClass::test_copy", "tests/test_proxy.py::TestFakerProxyClass::test_pickle", "tests/providers/test_date_time.py::TestDateTime::test_iso8601_fractional_seconds_non_win", "tests/providers/test_date_time.py::TestDateTime::test_unix_time_non_win"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "nchammas__flintrock-180_x2", "level": 2, "source": "swerebenchv2", "repo": "nchammas/flintrock", "image": "swerebenchv2/nchammas-flintrock:180-f9091b3", "base_commit": "f9091b3ce508c814fd97ab3936ae77335feafff8", "num_bugs": 2, "bugs": [{"instance_id": "nchammas__flintrock-180", "base_commit": "f9091b3ce508c814fd97ab3936ae77335feafff8", "gold_patch": "diff --git a/.travis.yml b/.travis.yml\nindex c7d3638..72a7864 100644\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -8,6 +8,7 @@ install:\n script:\n - \"py.test ./tests/test_static.py\"\n - \"py.test ./tests/test_flintrock.py\"\n+ - \"py.test ./tests/test_core.py\"\n - \"pip install -r requirements/maintainer.pip\"\n - \"py.test ./tests/test_pyinstaller_packaging.py\"\n addons:\ndiff --git a/README.md b/README.md\nindex cfb41ed..abf3393 100644\n--- a/README.md\n+++ b/README.md\n@@ -18,10 +18,10 @@ Here's a quick way to launch a cluster on EC2, assuming you already have an [AWS\n ```sh\n flintrock launch test-cluster \\\n --num-slaves 1 \\\n- --spark-version 2.0.2 \\\n+ --spark-version 2.1.0 \\\n --ec2-key-name key_name \\\n --ec2-identity-file /path/to/key.pem \\\n- --ec2-ami ami-b73b63a0 \\\n+ --ec2-ami ami-9be6f38c \\\n --ec2-user ec2-user\n ```\n \n@@ -57,6 +57,30 @@ flintrock --help\n \n That's not all. Flintrock has a few more [features](#features) that you may find interesting.\n \n+### Accessing data on S3\n+\n+We recommend you access data on S3 from your Flintrock cluster by following\n+these steps:\n+\n+1. Setup an [IAM Role](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html)\n+ that grants access to S3 as desired. Reference this role when you launch\n+ your cluster using the `--ec2-instance-profile-name` option (or its\n+ equivalent in your `config.yaml` file).\n+2. Reference S3 paths in your Spark code using the `s3a://` prefix. `s3a://` is\n+ backwards compatible with `s3n://` and replaces both `s3n://` and `s3://`.\n+ The Hadoop project [recommends using `s3a://`](https://hadoop.apache.org/docs/current/hadoop-aws/tools/hadoop-aws/index.html#S3A)\n+ since it is actively developed, supports larger files, and offers\n+ better performance.\n+3. Make sure Flintrock is configured to use Hadoop/HDFS 2.7+. Earlier\n+ versions of Hadoop do not have solid implementations of `s3a://`.\n+ Flintrock's default is Hadoop 2.7.3, so you don't need to do anything\n+ here if you're using a vanilla configuration.\n+\n+With this approach you don't need to copy around your AWS credentials\n+or pass them into your Spark programs. As long as the assigned IAM role\n+allows it, Spark will be able to read and write data to S3 simply by\n+referencing the appropriate path (e.g. `s3a://bucket/path/to/file`).\n+\n \n ## Installation\n \n@@ -196,7 +220,7 @@ provider: ec2\n \n services:\n spark:\n- version: 2.0.2\n+ version: 2.1.0\n \n launch:\n num-slaves: 1\n@@ -207,7 +231,7 @@ providers:\n identity-file: /path/to/.ssh/key.pem\n instance-type: m3.medium\n region: us-east-1\n- ami: ami-b73b63a0\n+ ami: ami-9be6f38c\n user: ec2-user\n ```\n \ndiff --git a/flintrock/config.yaml.template b/flintrock/config.yaml.template\nindex 1767c40..29edbe6 100644\n--- a/flintrock/config.yaml.template\n+++ b/flintrock/config.yaml.template\n@@ -1,6 +1,6 @@\n services:\n spark:\n- version: 2.0.2\n+ version: 2.1.0\n # git-commit: latest # if not 'latest', provide a full commit SHA; e.g. d6dc12ef0146ae409834c78737c116050961f350\n # git-repository: # optional; defaults to https://github.com/apache/spark\n # optional; defaults to download from from the official Spark S3 bucket\n@@ -24,7 +24,7 @@ providers:\n instance-type: m3.medium\n region: us-east-1\n # availability-zone: \n- ami: ami-b73b63a0 # Amazon Linux, us-east-1\n+ ami: ami-9be6f38c # Amazon Linux, us-east-1\n user: ec2-user\n # ami: ami-61bbf104 # CentOS 7, us-east-1\n # user: centos\ndiff --git a/flintrock/core.py b/flintrock/core.py\nindex 19e8ccf..20dc79b 100644\n--- a/flintrock/core.py\n+++ b/flintrock/core.py\n@@ -423,30 +423,65 @@ class FlintrockCluster:\n user=user,\n identity_file=identity_file)\n \n- def generate_template_mapping(self, *, service: str) -> dict:\n- \"\"\"\n- Generate a template mapping from a FlintrockCluster instance that we can use\n- to fill in template parameters.\n- \"\"\"\n- root_dir = posixpath.join(self.storage_dirs.root, service)\n- ephemeral_dirs = ','.join(posixpath.join(path, service) for path in self.storage_dirs.ephemeral)\n-\n- template_mapping = {\n- 'master_ip': self.master_ip,\n- 'master_host': self.master_host,\n- 'slave_ips': '\\n'.join(self.slave_ips),\n- 'slave_hosts': '\\n'.join(self.slave_hosts),\n- 'root_dir': root_dir,\n- 'ephemeral_dirs': ephemeral_dirs,\n-\n- # If ephemeral storage is available, it replaces the root volume, which is\n- # typically persistent. We don't want to mix persistent and ephemeral\n- # storage since that causes problems after cluster stop/start; some volumes\n- # have leftover data, whereas others start fresh.\n- 'root_ephemeral_dirs': ephemeral_dirs if ephemeral_dirs else root_dir,\n- }\n \n- return template_mapping\n+def generate_template_mapping(\n+ *,\n+ cluster: FlintrockCluster,\n+ # If we add additional services later on we may want to refactor\n+ # this to take a list of services and dynamically pull the service\n+ # name.\n+ hadoop_version: str,\n+ spark_version: str\n+) -> dict:\n+ \"\"\"\n+ Generate a template mapping from a FlintrockCluster instance that we can use\n+ to fill in template parameters.\n+ \"\"\"\n+ hadoop_root_dir = posixpath.join(cluster.storage_dirs.root, 'hadoop')\n+ hadoop_ephemeral_dirs = ','.join(\n+ posixpath.join(path, 'hadoop')\n+ for path in cluster.storage_dirs.ephemeral\n+ )\n+ spark_root_dir = posixpath.join(cluster.storage_dirs.root, 'spark')\n+ spark_ephemeral_dirs = ','.join(\n+ posixpath.join(path, 'spark')\n+ for path in cluster.storage_dirs.ephemeral\n+ )\n+\n+ template_mapping = {\n+ 'master_ip': cluster.master_ip,\n+ 'master_host': cluster.master_host,\n+ 'slave_ips': '\\n'.join(cluster.slave_ips),\n+ 'slave_hosts': '\\n'.join(cluster.slave_hosts),\n+\n+ 'hadoop_version': hadoop_version,\n+ 'hadoop_short_version': '.'.join(hadoop_version.split('.')[:2]),\n+ 'spark_version': spark_version,\n+ 'spark_short_version': '.'.join(spark_version.split('.')[:2]),\n+\n+ 'hadoop_root_dir': hadoop_root_dir,\n+ 'hadoop_ephemeral_dirs': hadoop_ephemeral_dirs,\n+ 'spark_root_dir': spark_root_dir,\n+ 'spark_ephemeral_dirs': spark_ephemeral_dirs,\n+\n+ # If ephemeral storage is available, it replaces the root volume, which is\n+ # typically persistent. We don't want to mix persistent and ephemeral\n+ # storage since that causes problems after cluster stop/start; some volumes\n+ # have leftover data, whereas others start fresh.\n+ 'hadoop_root_ephemeral_dirs': hadoop_ephemeral_dirs if hadoop_ephemeral_dirs else hadoop_root_dir,\n+ 'spark_root_ephemeral_dirs': spark_ephemeral_dirs if spark_ephemeral_dirs else spark_root_dir,\n+ }\n+\n+ return template_mapping\n+\n+\n+# TODO: Cache these files. (?) They are being read potentially tens or\n+# hundreds of times. Maybe it doesn't matter because the files\n+# are so small.\n+def get_formatted_template(*, path: str, mapping: dict) -> str:\n+ with open(path) as f:\n+ formatted = f.read().format(**mapping)\n+ return formatted\n \n \n def run_against_hosts(*, partial_func: functools.partial, hosts: list):\ndiff --git a/flintrock/flintrock.py b/flintrock/flintrock.py\nindex aece38e..58cb9d6 100644\n--- a/flintrock/flintrock.py\n+++ b/flintrock/flintrock.py\n@@ -187,13 +187,14 @@ def cli(cli_context, config, provider):\n @click.argument('cluster-name')\n @click.option('--num-slaves', type=click.IntRange(min=1), required=True)\n @click.option('--install-hdfs/--no-install-hdfs', default=False)\n-@click.option('--hdfs-version')\n+@click.option('--hdfs-version', default='2.7.3')\n @click.option('--hdfs-download-source',\n help=\"URL to download Hadoop from.\",\n default='http://www.apache.org/dyn/closer.lua/hadoop/common/hadoop-{v}/hadoop-{v}.tar.gz?as_json',\n show_default=True)\n @click.option('--install-spark/--no-install-spark', default=True)\n @click.option('--spark-version',\n+ default='2.1.0',\n help=\"Spark release version to install.\")\n @click.option('--spark-download-source',\n help=\"URL to download a release of Spark from.\",\n@@ -314,7 +315,11 @@ def launch(\n services += [hdfs]\n if install_spark:\n if spark_version:\n- spark = Spark(version=spark_version, download_source=spark_download_source)\n+ spark = Spark(\n+ version=spark_version,\n+ hadoop_version=hdfs_version,\n+ download_source=spark_download_source,\n+ )\n elif spark_git_commit:\n print(\n \"Warning: Building Spark takes a long time. \"\n@@ -324,7 +329,9 @@ def launch(\n print(\"Building Spark at latest commit: {c}\".format(c=spark_git_commit))\n spark = Spark(\n git_commit=spark_git_commit,\n- git_repository=spark_git_repository)\n+ git_repository=spark_git_repository,\n+ hadoop_version=hdfs_version,\n+ )\n services += [spark]\n \n if provider == 'ec2':\ndiff --git a/flintrock/services.py b/flintrock/services.py\nindex 5e13608..f850d3e 100644\n--- a/flintrock/services.py\n+++ b/flintrock/services.py\n@@ -9,7 +9,11 @@ import urllib.request\n import paramiko\n \n # Flintrock modules\n-from .core import FlintrockCluster\n+from .core import (\n+ FlintrockCluster,\n+ generate_template_mapping,\n+ get_formatted_template,\n+)\n from .ssh import ssh_check_output\n \n FROZEN = getattr(sys, 'frozen', False)\n@@ -22,15 +26,6 @@ else:\n SCRIPTS_DIR = os.path.join(THIS_DIR, 'scripts')\n \n \n-# TODO: Cache these files. (?) They are being read potentially tens or\n-# hundreds of times. Maybe it doesn't matter because the files\n-# are so small.\n-def get_formatted_template(path: str, mapping: dict) -> str:\n- with open(path) as f:\n- formatted = f.read().format(**mapping)\n- return formatted\n-\n-\n class FlintrockService:\n \"\"\"\n This is an abstract class. Implementations of this class capture all the logic\n@@ -108,7 +103,7 @@ class FlintrockService:\n \n \n class HDFS(FlintrockService):\n- def __init__(self, version, download_source):\n+ def __init__(self, *, version, download_source):\n self.version = version\n self.download_source = download_source\n self.manifest = {'version': version, 'download_source': download_source}\n@@ -154,7 +149,8 @@ class HDFS(FlintrockService):\n 'hadoop/conf/slaves',\n 'hadoop/conf/hadoop-env.sh',\n 'hadoop/conf/core-site.xml',\n- 'hadoop/conf/hdfs-site.xml']\n+ 'hadoop/conf/hdfs-site.xml',\n+ ]\n \n for template_path in template_paths:\n ssh_check_output(\n@@ -165,7 +161,13 @@ class HDFS(FlintrockService):\n f=shlex.quote(\n get_formatted_template(\n path=os.path.join(THIS_DIR, \"templates\", template_path),\n- mapping=cluster.generate_template_mapping(service='hdfs'))),\n+ mapping=generate_template_mapping(\n+ cluster=cluster,\n+ hadoop_version=self.version,\n+ # Hadoop doesn't need to know what\n+ # Spark version we're using.\n+ spark_version='',\n+ ))),\n p=shlex.quote(template_path)))\n \n # TODO: Convert this into start_master() and split master- or slave-specific\n@@ -203,8 +205,15 @@ class HDFS(FlintrockService):\n \n \n class Spark(FlintrockService):\n- def __init__(self, version: str=None, download_source: str=None,\n- git_commit: str=None, git_repository: str=None):\n+ def __init__(\n+ self,\n+ *,\n+ version: str=None,\n+ hadoop_version: str,\n+ download_source: str=None,\n+ git_commit: str=None,\n+ git_repository: str=None\n+ ):\n # TODO: Convert these checks into something that throws a proper exception.\n # Perhaps reuse logic from CLI.\n assert bool(version) ^ bool(git_commit)\n@@ -212,12 +221,14 @@ class Spark(FlintrockService):\n assert git_repository\n \n self.version = version\n+ self.hadoop_version = hadoop_version\n self.download_source = download_source\n self.git_commit = git_commit\n self.git_repository = git_repository\n \n self.manifest = {\n 'version': version,\n+ 'hadoop_version': hadoop_version,\n 'download_source': download_source,\n 'git_commit': git_commit,\n 'git_repository': git_repository}\n@@ -261,13 +272,15 @@ class Spark(FlintrockService):\n cd spark\n git reset --hard {commit}\n if [ -e \"make-distribution.sh\" ]; then\n- ./make-distribution.sh -Phadoop-2.6\n+ ./make-distribution.sh -Phadoop-{hadoop_short_version}\n else\n- ./dev/make-distribution.sh -Phadoop-2.6\n+ ./dev/make-distribution.sh -Phadoop-{hadoop_short_version}\n fi\n \"\"\".format(\n repo=shlex.quote(self.git_repository),\n- commit=shlex.quote(self.git_commit)))\n+ commit=shlex.quote(self.git_commit),\n+ hadoop_short_version='.'.join(self.hadoop_version.split('.')[:2]),\n+ ))\n ssh_check_output(\n client=ssh_client,\n command=\"\"\"\n@@ -289,7 +302,9 @@ class Spark(FlintrockService):\n cluster: FlintrockCluster):\n template_paths = [\n 'spark/conf/spark-env.sh',\n- 'spark/conf/slaves']\n+ 'spark/conf/slaves',\n+ 'spark/conf/spark-defaults.conf',\n+ ]\n for template_path in template_paths:\n ssh_check_output(\n client=ssh_client,\n@@ -299,7 +314,11 @@ class Spark(FlintrockService):\n f=shlex.quote(\n get_formatted_template(\n path=os.path.join(THIS_DIR, \"templates\", template_path),\n- mapping=cluster.generate_template_mapping(service='spark'))),\n+ mapping=generate_template_mapping(\n+ cluster=cluster,\n+ hadoop_version=self.hadoop_version,\n+ spark_version=self.version,\n+ ))),\n p=shlex.quote(template_path)))\n \n # TODO: Convert this into start_master() and split master- or slave-specific\ndiff --git a/flintrock/templates/hadoop/conf/core-site.xml b/flintrock/templates/hadoop/conf/core-site.xml\nindex d53ffbd..b4bebb4 100644\n--- a/flintrock/templates/hadoop/conf/core-site.xml\n+++ b/flintrock/templates/hadoop/conf/core-site.xml\n@@ -4,7 +4,7 @@\n \n \n hadoop.tmp.dir\n- {root_ephemeral_dirs}\n+ {hadoop_root_ephemeral_dirs}\n \n \n \ndiff --git a/flintrock/templates/hadoop/conf/hdfs-site.xml b/flintrock/templates/hadoop/conf/hdfs-site.xml\nindex 94e34eb..c2c117c 100644\n--- a/flintrock/templates/hadoop/conf/hdfs-site.xml\n+++ b/flintrock/templates/hadoop/conf/hdfs-site.xml\n@@ -9,6 +9,6 @@\n \n \n dfs.datanode.data.dir\n- {root_ephemeral_dirs}\n+ {hadoop_root_ephemeral_dirs}\n \n \ndiff --git a/flintrock/templates/spark/conf/spark-defaults.conf b/flintrock/templates/spark/conf/spark-defaults.conf\nnew file mode 100644\nindex 0000000..b4ed251\n--- /dev/null\n+++ b/flintrock/templates/spark/conf/spark-defaults.conf\n@@ -0,0 +1,1 @@\n+spark.jars.packages org.apache.hadoop:hadoop-aws:{hadoop_version}\ndiff --git a/flintrock/templates/spark/conf/spark-env.sh b/flintrock/templates/spark/conf/spark-env.sh\nindex d849910..77bd7f8 100644\n--- a/flintrock/templates/spark/conf/spark-env.sh\n+++ b/flintrock/templates/spark/conf/spark-env.sh\n@@ -1,6 +1,6 @@\n #!/usr/bin/env bash\n \n-export SPARK_LOCAL_DIRS=\"{root_ephemeral_dirs}\"\n+export SPARK_LOCAL_DIRS=\"{spark_root_ephemeral_dirs}\"\n \n # Standalone cluster options\n export SPARK_EXECUTOR_INSTANCES=\"1\"\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 92bfaa9..36fa8a5 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -4,14 +4,40 @@ import tempfile\n import uuid\n from collections import OrderedDict\n \n-# External modules\n+# Flintrock\n+from flintrock.core import FlintrockCluster, StorageDirs\n+\n+# External\n import pytest\n \n HADOOP_VERSION = '2.7.3'\n-SPARK_VERSION = '2.0.2'\n+SPARK_VERSION = '2.1.0'\n SPARK_GIT_COMMIT = '584354eaac02531c9584188b143367ba694b0c34' # 2.0.2\n \n \n+class Dummy():\n+ pass\n+\n+\n+@pytest.fixture(scope='session')\n+def dummy_cluster():\n+ storage_dirs = StorageDirs(\n+ root='/media/root',\n+ ephemeral=['/media/eph1', '/media/eph2'],\n+ persistent=None,\n+ )\n+\n+ cluster = Dummy()\n+ cluster.name = 'test'\n+ cluster.storage_dirs = storage_dirs\n+ cluster.master_ip = '10.0.0.1'\n+ cluster.master_host = 'master.hostname'\n+ cluster.slave_ips = ['10.0.0.2']\n+ cluster.slave_hosts = ['slave1.hostname']\n+\n+ return cluster\n+\n+\n def random_string():\n return str(uuid.uuid4())[:8]\n \ndiff --git a/tests/test_core.py b/tests/test_core.py\nnew file mode 100644\nindex 0000000..56e58ed\n--- /dev/null\n+++ b/tests/test_core.py\n@@ -0,0 +1,29 @@\n+import os\n+\n+# Flintrock\n+from flintrock.core import (\n+ generate_template_mapping,\n+ get_formatted_template,\n+)\n+\n+FLINTROCK_ROOT_DIR = (\n+ os.path.dirname(\n+ os.path.dirname(\n+ os.path.realpath(__file__))))\n+\n+\n+def test_templates(dummy_cluster):\n+ template_dir = os.path.join(FLINTROCK_ROOT_DIR, 'flintrock', 'templates')\n+ for (dirpath, dirnames, filenames) in os.walk(template_dir):\n+ if filenames:\n+ for filename in filenames:\n+ template_path = os.path.join(dirpath, filename)\n+ mapping = generate_template_mapping(\n+ cluster=dummy_cluster,\n+ hadoop_version='',\n+ spark_version='',\n+ )\n+ get_formatted_template(\n+ path=template_path,\n+ mapping=mapping,\n+ )\n", "FAIL_TO_PASS": ["tests/test_core.py::test_templates"]}, {"instance_id": "nchammas__flintrock-186", "base_commit": "be4c3fd5e67eb8d6255b84b153ae9d1916d1e889", "gold_patch": "diff --git a/CHANGES.md b/CHANGES.md\nindex cc7b8d7..52f6b0c 100644\n--- a/CHANGES.md\n+++ b/CHANGES.md\n@@ -2,10 +2,44 @@\n \n ## [Unreleased]\n \n-[Unreleased]: https://github.com/nchammas/flintrock/compare/v0.7.0...master\n+[Unreleased]: https://github.com/nchammas/flintrock/compare/v0.8.0...master\n \n Nothing notable yet.\n \n+## [0.8.0] - 2017-02-11\n+\n+[0.8.0]: https://github.com/nchammas/flintrock/compare/v0.7.0...v0.8.0\n+\n+### Added\n+\n+* [#180]: Accessing data on S3 from your Flintrock cluster is now much\n+ easier! Just configure Flintrock to use Hadoop 2.7+ (which is the\n+ default) and an appropriate IAM role, and you'll be able to access\n+ paths on S3 using the new `s3a://` prefix. [Check the README] for\n+ more information.\n+* [#176], [#187]: Flintrock now supports users with non-standard home\n+ directories.\n+\n+[#180]: https://github.com/nchammas/flintrock/pull/180\n+[#176]: https://github.com/nchammas/flintrock/pull/176\n+[#187]: https://github.com/nchammas/flintrock/pull/187\n+[Check the README]: https://github.com/nchammas/flintrock/tree/v0.8.0#accessing-data-on-s3\n+\n+### Changed\n+\n+* [#168]: Flintrock now does a better job of cleaning up after\n+ interrupted operations.\n+* [#179], [#184]: Flintrock can now clean up malformed Flintrock\n+ clusters.\n+* [`6b426ae`]: We fixed an issue affecting some users of Flintrock's\n+ standalone package that caused Flintrock to intermittently throw\n+ `ImportError`s.\n+\n+[#168]: https://github.com/nchammas/flintrock/pull/168\n+[#179]: https://github.com/nchammas/flintrock/pull/179\n+[#184]: https://github.com/nchammas/flintrock/pull/184\n+[`6b426ae`]: https://github.com/nchammas/flintrock/commit/6b426aedc7e92b434021cc09c6e7eb181fca7eef\n+\n ## [0.7.0] - 2016-11-15\n \n [0.7.0]: https://github.com/nchammas/flintrock/compare/v0.6.0...v0.7.0\ndiff --git a/README.md b/README.md\nindex abf3393..2d67e24 100644\n--- a/README.md\n+++ b/README.md\n@@ -21,7 +21,7 @@ flintrock launch test-cluster \\\n --spark-version 2.1.0 \\\n --ec2-key-name key_name \\\n --ec2-identity-file /path/to/key.pem \\\n- --ec2-ami ami-9be6f38c \\\n+ --ec2-ami ami-0b33d91d \\\n --ec2-user ec2-user\n ```\n \n@@ -125,7 +125,7 @@ unzip it to a location of your choice, and run the `flintrock` executable inside\n For example:\n \n ```sh\n-flintrock_version=\"0.7.0\"\n+flintrock_version=\"0.8.0\"\n \n curl --location --remote-name \"https://github.com/nchammas/flintrock/releases/download/v$flintrock_version/Flintrock-$flintrock_version-standalone-OSX-x86_64.zip\"\n unzip -q -d flintrock \"Flintrock-$flintrock_version-standalone-OSX-x86_64.zip\"\n@@ -231,7 +231,7 @@ providers:\n identity-file: /path/to/.ssh/key.pem\n instance-type: m3.medium\n region: us-east-1\n- ami: ami-9be6f38c\n+ ami: ami-0b33d91d\n user: ec2-user\n ```\n \ndiff --git a/flintrock/__init__.py b/flintrock/__init__.py\nindex 11c50e6..071b765 100644\n--- a/flintrock/__init__.py\n+++ b/flintrock/__init__.py\n@@ -1,2 +1,2 @@\n # See: https://packaging.python.org/en/latest/distributing/#standards-compliance-for-interoperability\n-__version__ = '0.8.0.dev0'\n+__version__ = '0.9.0.dev0'\ndiff --git a/flintrock/config.yaml.template b/flintrock/config.yaml.template\nindex 29edbe6..ccaa062 100644\n--- a/flintrock/config.yaml.template\n+++ b/flintrock/config.yaml.template\n@@ -24,7 +24,7 @@ providers:\n instance-type: m3.medium\n region: us-east-1\n # availability-zone: \n- ami: ami-9be6f38c # Amazon Linux, us-east-1\n+ ami: ami-0b33d91d # Amazon Linux, us-east-1\n user: ec2-user\n # ami: ami-61bbf104 # CentOS 7, us-east-1\n # user: centos\n@@ -36,6 +36,10 @@ providers:\n # - group-name1\n # - group-name2\n # instance-profile-name:\n+ # tags:\n+ # - key1,value1\n+ # - key2, value2 # leading/trailing spaces are trimmed\n+ # - key3, # value will be empty\n tenancy: default # default | dedicated\n ebs-optimized: no # yes | no\n instance-initiated-shutdown-behavior: terminate # terminate | stop\ndiff --git a/flintrock/core.py b/flintrock/core.py\nindex 20dc79b..594695f 100644\n--- a/flintrock/core.py\n+++ b/flintrock/core.py\n@@ -140,8 +140,8 @@ class FlintrockCluster:\n manifest_raw = ssh_check_output(\n client=master_ssh_client,\n command=\"\"\"\n- cat /home/{u}/.flintrock-manifest.json\n- \"\"\".format(u=shlex.quote(user)))\n+ cat \"$HOME/.flintrock-manifest.json\"\n+ \"\"\")\n # TODO: Would it be better if storage (ephemeral and otherwise) was\n # implemented as a Flintrock service and tracked in the manifest?\n ephemeral_dirs_raw = ssh_check_output(\n@@ -570,10 +570,10 @@ def setup_node(\n command=\"\"\"\n set -e\n \n- echo {private_key} > ~/.ssh/id_rsa\n- echo {public_key} >> ~/.ssh/authorized_keys\n+ echo {private_key} > \"$HOME/.ssh/id_rsa\"\n+ echo {public_key} >> \"$HOME/.ssh/authorized_keys\"\n \n- chmod 400 ~/.ssh/id_rsa\n+ chmod 400 \"$HOME/.ssh/id_rsa\"\n \"\"\".format(\n private_key=shlex.quote(cluster.ssh_key_pair.private),\n public_key=shlex.quote(cluster.ssh_key_pair.public)))\n@@ -644,11 +644,11 @@ def provision_cluster(\n ssh_check_output(\n client=master_ssh_client,\n command=\"\"\"\n- echo {m} > /home/{u}/.flintrock-manifest.json\n- chmod go-rw /home/{u}/.flintrock-manifest.json\n+ echo {m} > \"$HOME/.flintrock-manifest.json\"\n+ chmod go-rw \"$HOME/.flintrock-manifest.json\"\n \"\"\".format(\n- m=shlex.quote(json.dumps(manifest, indent=4, sort_keys=True)),\n- u=shlex.quote(user)))\n+ m=shlex.quote(json.dumps(manifest, indent=4, sort_keys=True))\n+ ))\n \n for service in services:\n service.configure_master(\n@@ -861,4 +861,4 @@ def copy_file_node(\n # core.py and services.py. I've thought about how to remove this circular dependency,\n # but for now this seems like what we need to go with.\n # Flintrock modules\n-from .services import HDFS, Spark # Used by start_cluster()\n+from .services import HDFS, Spark # Used by start_cluster() # noqa\ndiff --git a/flintrock/ec2.py b/flintrock/ec2.py\nindex 6be0deb..7a2a61a 100644\n--- a/flintrock/ec2.py\n+++ b/flintrock/ec2.py\n@@ -4,7 +4,6 @@ import sys\n import time\n import urllib.request\n import base64\n-import os\n from collections import namedtuple\n from datetime import datetime\n \n@@ -234,6 +233,7 @@ class EC2Cluster(FlintrockCluster):\n identity_file: str,\n num_slaves: int,\n spot_price: float,\n+ tags: list,\n assume_yes: bool):\n security_group_ids = [\n group['GroupId']\n@@ -287,15 +287,17 @@ class EC2Cluster(FlintrockCluster):\n instance_initiated_shutdown_behavior=instance_initiated_shutdown_behavior,\n user_data=user_data)\n \n+ slave_tags = [\n+ {'Key': 'flintrock-role', 'Value': 'slave'},\n+ {'Key': 'Name', 'Value': '{c}-slave'.format(c=self.name)}]\n+ slave_tags += tags\n+\n (ec2.instances\n .filter(\n Filters=[\n {'Name': 'instance-id', 'Values': [i.id for i in new_slave_instances]}\n ])\n- .create_tags(\n- Tags=[\n- {'Key': 'flintrock-role', 'Value': 'slave'},\n- {'Key': 'Name', 'Value': '{c}-slave'.format(c=self.name)}]))\n+ .create_tags(Tags=slave_tags))\n \n existing_slaves = {i.public_ip_address for i in self.slave_instances}\n \n@@ -817,7 +819,8 @@ def launch(\n tenancy='default',\n ebs_optimized=False,\n instance_initiated_shutdown_behavior='stop',\n- user_data):\n+ user_data,\n+ tags):\n \"\"\"\n Launch a cluster.\n \"\"\"\n@@ -898,24 +901,29 @@ def launch(\n master_instance = cluster_instances[0]\n slave_instances = cluster_instances[1:]\n \n+ master_tags = [\n+ {'Key': 'flintrock-role', 'Value': 'master'},\n+ {'Key': 'Name', 'Value': '{c}-master'.format(c=cluster_name)}]\n+ master_tags += tags\n+\n (ec2.instances\n .filter(\n Filters=[\n {'Name': 'instance-id', 'Values': [master_instance.id]}\n ])\n- .create_tags(\n- Tags=[\n- {'Key': 'flintrock-role', 'Value': 'master'},\n- {'Key': 'Name', 'Value': '{c}-master'.format(c=cluster_name)}]))\n+ .create_tags(Tags=master_tags))\n+\n+ slave_tags = [\n+ {'Key': 'flintrock-role', 'Value': 'slave'},\n+ {'Key': 'Name', 'Value': '{c}-slave'.format(c=cluster_name)}]\n+ slave_tags += tags\n+\n (ec2.instances\n .filter(\n Filters=[\n {'Name': 'instance-id', 'Values': [i.id for i in slave_instances]}\n ])\n- .create_tags(\n- Tags=[\n- {'Key': 'flintrock-role', 'Value': 'slave'},\n- {'Key': 'Name', 'Value': '{c}-slave'.format(c=cluster_name)}]))\n+ .create_tags(Tags=slave_tags))\n \n cluster = EC2Cluster(\n name=cluster_name,\n@@ -1005,6 +1013,30 @@ def get_clusters(*, cluster_names: list=[], region: str, vpc_id: str) -> list:\n return clusters\n \n \n+def cli_validate_tags(ctx, param, value):\n+ return validate_tags(value)\n+\n+\n+def validate_tags(value):\n+ \"\"\"\n+ Validate and parse optional EC2 tags.\n+ \"\"\"\n+ err_msg = (\"Tags need to be specified as 'Key,Value' pairs \"\n+ \"separated by a single comma. Key cannot be empty \"\n+ \"or be made up entirely of whitespace.\")\n+ tags = value\n+ result = []\n+ for tag in tags:\n+ if tag.count(',') != 1:\n+ raise click.BadParameter(err_msg)\n+ key, value = [word.strip() for word in tag.split(',', maxsplit=1)]\n+ if not key:\n+ raise click.BadParameter(err_msg)\n+ result.append({'Key': key, 'Value': value})\n+\n+ return result\n+\n+\n def _get_cluster_name(instance: 'boto3.resources.factory.ec2.Instance') -> str:\n \"\"\"\n Given an EC2 instance, get the name of the Flintrock cluster it belongs to.\ndiff --git a/flintrock/flintrock.py b/flintrock/flintrock.py\nindex 58cb9d6..25721d6 100644\n--- a/flintrock/flintrock.py\n+++ b/flintrock/flintrock.py\n@@ -236,6 +236,11 @@ def cli(cli_context, config, provider):\n @click.option('--ec2-user-data',\n type=click.File(mode='r', encoding='utf-8'),\n help=\"Path to EC2 user data script that will run on instance launch.\")\n+@click.option('--ec2-tag', 'ec2_tags',\n+ callback=ec2.cli_validate_tags,\n+ multiple=True,\n+ help=\"Additional tags (e.g. 'Key,Value') to assign to the instances. \"\n+ \"You can specify this option multiple times.\")\n @click.pass_context\n def launch(\n cli_context,\n@@ -266,7 +271,8 @@ def launch(\n ec2_tenancy,\n ec2_ebs_optimized,\n ec2_instance_initiated_shutdown_behavior,\n- ec2_user_data):\n+ ec2_user_data,\n+ ec2_tags):\n \"\"\"\n Launch a new cluster.\n \"\"\"\n@@ -356,7 +362,8 @@ def launch(\n tenancy=ec2_tenancy,\n ebs_optimized=ec2_ebs_optimized,\n instance_initiated_shutdown_behavior=ec2_instance_initiated_shutdown_behavior,\n- user_data=ec2_user_data)\n+ user_data=ec2_user_data,\n+ tags=ec2_tags)\n else:\n raise UnsupportedProviderError(provider)\n \n@@ -619,6 +626,11 @@ def stop(cli_context, cluster_name, ec2_region, ec2_vpc_id, assume_yes):\n @click.option('--ec2-user')\n @click.option('--ec2-spot-price', type=float)\n @click.option('--assume-yes/--no-assume-yes', default=False)\n+@click.option('--ec2-tag', 'ec2_tags',\n+ callback=ec2.cli_validate_tags,\n+ multiple=True,\n+ help=\"Additional tags (e.g. 'Key,Value') to assign to the instances. \"\n+ \"You can specify this option multiple times.\")\n @click.pass_context\n def add_slaves(\n cli_context,\n@@ -629,6 +641,7 @@ def add_slaves(\n ec2_identity_file,\n ec2_user,\n ec2_spot_price,\n+ ec2_tags,\n assume_yes):\n \"\"\"\n Add slaves to an existing cluster.\n@@ -656,6 +669,7 @@ def add_slaves(\n identity_file = ec2_identity_file\n provider_options = {\n 'spot_price': ec2_spot_price,\n+ 'tags': ec2_tags\n }\n else:\n raise UnsupportedProviderError(provider)\ndiff --git a/flintrock/scripts/setup-ephemeral-storage.py b/flintrock/scripts/setup-ephemeral-storage.py\nindex b246c1c..dcb8876 100644\n--- a/flintrock/scripts/setup-ephemeral-storage.py\n+++ b/flintrock/scripts/setup-ephemeral-storage.py\n@@ -12,6 +12,7 @@ The resulting structure we create is as follows:\n /root: The instance's root volume.\n /ephemeral[0-N]: Instance store volumes.\n /persistent[0-N]: EBS volumes.\n+ /tmp: A temporary directory with lots of space.\n \n WARNING: Be conscious about what this script prints to stdout, as that\n output is parsed by Flintrock.\n@@ -97,7 +98,7 @@ def format_devices(devices):\n \n for p in format_processes:\n stdout_raw, stderr_raw = p.communicate()\n- stdout, stderr = stdout_raw.decode('utf-8'), stderr_raw.decode('utf-8')\n+ stdout, stderr = stdout_raw.decode('utf-8'), stderr_raw.decode('utf-8') # noqa\n return_code = p.returncode\n if return_code != 0:\n raise Exception(\n@@ -131,7 +132,7 @@ def mount_devices(devices):\n device.name,\n device.mount_point,\n 'ext4',\n- 'defaults,users,noatime,nodiratime',\n+ 'defaults,users,noatime',\n '0',\n '0'])),\n shell=True)\n@@ -159,6 +160,19 @@ def create_root_dir():\n return path\n \n \n+def create_tmp_dir(target):\n+ \"\"\"\n+ Create a folder that services can use as a temporary directory for big files.\n+ \"\"\"\n+ path = '/media/tmp'\n+ subprocess.check_output([\n+ 'sudo', 'ln', '-s', target, path])\n+ subprocess.check_output(\n+ 'sudo chown \"$(logname):$(logname)\" {p}'.format(p=path),\n+ shell=True)\n+ return path\n+\n+\n if __name__ == '__main__':\n if sys.version_info < (2, 7) or ((3, 0) <= sys.version_info < (3, 4)):\n raise Exception(\n@@ -182,6 +196,11 @@ if __name__ == '__main__':\n mount_devices(ephemeral_devices)\n \n root_dir = create_root_dir()\n+ if ephemeral_devices:\n+ tmp_dir = ephemeral_devices[0].mount_point\n+ else:\n+ tmp_dir = '/tmp'\n+ create_tmp_dir(tmp_dir)\n \n print(json.dumps(\n {\ndiff --git a/flintrock/services.py b/flintrock/services.py\nindex f850d3e..48f36a5 100644\n--- a/flintrock/services.py\n+++ b/flintrock/services.py\n@@ -192,7 +192,7 @@ class HDFS(FlintrockService):\n hdfs_master_ui = 'http://{m}:50070/webhdfs/v1/?op=GETCONTENTSUMMARY'.format(m=master_host)\n \n try:\n- hdfs_ui_info = json.loads(\n+ hdfs_ui_info = json.loads( # noqa\n urllib.request.urlopen(hdfs_master_ui).read().decode('utf-8'))\n except Exception as e:\n # TODO: Catch a more specific problem.\ndiff --git a/flintrock/ssh.py b/flintrock/ssh.py\nindex ba0469e..ad0049c 100644\n--- a/flintrock/ssh.py\n+++ b/flintrock/ssh.py\n@@ -129,7 +129,7 @@ def ssh(*, user: str, host: str, identity_file: str):\n \"\"\"\n SSH into a host for interactive use.\n \"\"\"\n- ret = subprocess.call(\n+ subprocess.call(\n [\n 'ssh',\n '-o', 'StrictHostKeyChecking=no',\ndiff --git a/flintrock/templates/hadoop/conf/hadoop-env.sh b/flintrock/templates/hadoop/conf/hadoop-env.sh\nindex 39805ba..e872b48 100644\n--- a/flintrock/templates/hadoop/conf/hadoop-env.sh\n+++ b/flintrock/templates/hadoop/conf/hadoop-env.sh\n@@ -1,2 +1,2 @@\n-export HADOOP_HOME=\"/home/$(logname)/hadoop\"\n+export HADOOP_HOME=\"$HOME/hadoop\"\n export HADOOP_SSH_OPTS=\"-o StrictHostKeyChecking=no -o ConnectTimeout=5\"\ndiff --git a/flintrock/templates/spark/conf/spark-env.sh b/flintrock/templates/spark/conf/spark-env.sh\nindex 77bd7f8..968e659 100644\n--- a/flintrock/templates/spark/conf/spark-env.sh\n+++ b/flintrock/templates/spark/conf/spark-env.sh\n@@ -9,7 +9,7 @@ export SPARK_WORKER_CORES=\"$(nproc)\"\n export SPARK_MASTER_HOST=\"{master_host}\"\n \n # TODO: Make this dependent on HDFS install.\n-export HADOOP_CONF_DIR=\"/home/$(logname)/hadoop/conf\"\n+export HADOOP_CONF_DIR=\"$HOME/hadoop/conf\"\n \n # TODO: Make this non-EC2-specific.\n # Bind Spark's web UIs to this machine's public EC2 hostname\ndiff --git a/generate-standalone-package.py b/generate-standalone-package.py\nindex c142035..0e33d25 100644\n--- a/generate-standalone-package.py\n+++ b/generate-standalone-package.py\n@@ -13,7 +13,8 @@ if __name__ == '__main__':\n operating_system = 'OSX'\n machine_type = platform.machine()\n \n- subprocess.run([\n+ subprocess.run(\n+ [\n 'pyinstaller',\n '--noconfirm',\n '--clean',\n@@ -23,7 +24,8 @@ if __name__ == '__main__':\n # We won't need this when this issue is resolved:\n # https://github.com/pyinstaller/pyinstaller/issues/1844\n '--hidden-import', 'html.parser',\n- 'standalone.py'],\n+ 'standalone.py'\n+ ],\n check=True)\n \n shutil.make_archive(\ndiff --git a/hook-flintrock.py b/hook-flintrock.py\nindex 5478cf8..38b8908 100644\n--- a/hook-flintrock.py\n+++ b/hook-flintrock.py\n@@ -1,4 +1,4 @@\n-datas=[\n+datas = [\n ('flintrock/scripts', './scripts'),\n ('flintrock/templates', './templates'),\n ('flintrock/config.yaml.template', './'),\ndiff --git a/make-release.sh b/make-release.sh\nindex 7419b5b..ae51d0b 100644\n--- a/make-release.sh\n+++ b/make-release.sh\n@@ -5,6 +5,7 @@\n # - Default Amazon Linux AMI\n # Update CHANGES\n # - Check: https://github.com/nchammas/flintrock/pulls?q=is%3Apr+is%3Aclosed+label%3A%22needs+changelog%22\n+# - Update \"Unreleased\" section. \"Nothing notable yet.\"\n # Tag release on GitHub\n \n trash dist/ build/ Flintrock.egg-info/\ndiff --git a/requirements/developer.pip b/requirements/developer.pip\nindex ef0a99c..2ec3050 100644\n--- a/requirements/developer.pip\n+++ b/requirements/developer.pip\n@@ -1,5 +1,5 @@\n -r user.pip\n-pycodestyle == 2.2.0\n-pytest >= 3.0.4\n+pytest >= 3.0.6\n pytest-cov >= 2.4.0\n+flake8 == 3.3.0\n # PyYAML # requirement already covered by setup.py\ndiff --git a/setup.cfg b/setup.cfg\nnew file mode 100644\nindex 0000000..9f5236f\n--- /dev/null\n+++ b/setup.cfg\n@@ -0,0 +1,8 @@\n+[tool:pytest]\n+norecursedirs = venv\n+addopts = --verbose --cov flintrock --cov-report html\n+\n+[flake8]\n+max-line-length = 100\n+exclude = venv, build, dist\n+ignore = E501\ndiff --git a/setup.py b/setup.py\nindex c045bd7..3ccead7 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -49,10 +49,10 @@ setuptools.setup(\n # totally break Flintrock.\n # For example: https://github.com/paramiko/paramiko/issues/615\n install_requires=[\n- 'boto3 == 1.4.3',\n- 'botocore == 1.4.91',\n- 'click == 6.6',\n- 'paramiko == 2.0.2',\n+ 'boto3 == 1.4.4',\n+ 'botocore == 1.5.10',\n+ 'click == 6.7',\n+ 'paramiko == 2.1.1',\n 'PyYAML == 3.12',\n # This is to ensure that PyInstaller works. dateutil is an\n # indirect dependency of Flintrock, and PyInstaller chokes on\n@@ -63,7 +63,7 @@ setuptools.setup(\n # of Flintrock intermittently fail due to an out-of-date version\n # of Cryptography being used.\n # See: https://github.com/nchammas/flintrock/issues/169\n- 'cryptography >= 1.7.1',\n+ 'cryptography >= 1.7.2',\n ],\n \n entry_points={\ndiff --git a/tox.ini b/tox.ini\ndeleted file mode 100644\nindex 3bb4d36..0000000\n--- a/tox.ini\n+++ /dev/null\n@@ -1,7 +0,0 @@\n-[pycodestyle]\n-max-line-length=100\n-ignore=E501,E402\n-\n-[pytest]\n-norecursedirs=venv\n-addopts=--verbose --cov flintrock --cov-report html\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 36fa8a5..48298f8 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -5,7 +5,7 @@ import uuid\n from collections import OrderedDict\n \n # Flintrock\n-from flintrock.core import FlintrockCluster, StorageDirs\n+from flintrock.core import StorageDirs\n \n # External\n import pytest\ndiff --git a/tests/test_ec2.py b/tests/test_ec2.py\nnew file mode 100644\nindex 0000000..fd60eb7\n--- /dev/null\n+++ b/tests/test_ec2.py\n@@ -0,0 +1,32 @@\n+import pytest\n+import click\n+from flintrock.ec2 import validate_tags\n+\n+\n+def test_validate_tags():\n+ # List of test cases; each test case is a tuple, with first element\n+ # the input and the second element the expected output\n+ positive_test_cases = [\n+ # basic case\n+ (['k1,v1'], [{'Key': 'k1', 'Value': 'v1'}]),\n+ # strips whitespace?\n+ (['k2, v2 '], [{'Key': 'k2', 'Value': 'v2'}]),\n+ # empty Value\n+ (['k3,'], [{'Key': 'k3', 'Value': ''}]),\n+ # multiple tags\n+ (['k4,v4', 'k5,v5'],\n+ [{'Key': 'k4', 'Value': 'v4'}, {'Key': 'k5', 'Value': 'v5'}])]\n+\n+ for test_case in positive_test_cases:\n+ ec2_tags = validate_tags(test_case[0])\n+ assert(isinstance(ec2_tags, list))\n+ for i, ec2_tag in enumerate(ec2_tags):\n+ expected_dict = test_case[1][i]\n+ for k in expected_dict:\n+ assert k in ec2_tag\n+ assert ec2_tag[k] == expected_dict[k]\n+\n+ negative_test_cases = [[\"k1\"], [\"k2,v2,\"], [\"k3,,v3\"], [\",v4\"]]\n+ for test_case in negative_test_cases:\n+ with pytest.raises(click.BadParameter):\n+ validate_tags(test_case)\ndiff --git a/tests/test_static.py b/tests/test_static.py\nindex e5024b6..fde3cff 100644\n--- a/tests/test_static.py\n+++ b/tests/test_static.py\n@@ -1,8 +1,8 @@\n import compileall\n import os\n+import subprocess\n \n # External modules\n-import pycodestyle\n import yaml\n \n FLINTROCK_ROOT_DIR = (\n@@ -31,11 +31,9 @@ def test_code_compiles():\n assert result == 1\n \n \n-def test_style():\n- style = pycodestyle.StyleGuide(\n- config_file=os.path.join(FLINTROCK_ROOT_DIR, 'tox.ini'))\n- result = style.check_files(TEST_PATHS)\n- assert result.total_errors == 0\n+def test_flake8():\n+ ret = subprocess.call(['flake8'], cwd=FLINTROCK_ROOT_DIR)\n+ assert ret == 0\n \n \n def test_config_template_is_valid():\n", "FAIL_TO_PASS": ["tests/test_ec2.py::test_validate_tags", "tests/test_static.py::test_code_compiles", "tests/test_static.py::test_config_template_is_valid"]}], "all_FAIL_TO_PASS": ["tests/test_core.py::test_templates", "tests/test_ec2.py::test_validate_tags", "tests/test_static.py::test_code_compiles", "tests/test_static.py::test_config_template_is_valid"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "cs-si__eodag-566_x2", "level": 2, "source": "swerebenchv2", "repo": "CS-SI/eodag", "image": "swerebenchv2/cs-si-eodag:566-9af6855", "base_commit": "9af685574aa465456bca01f245b830b324db2c5c", "num_bugs": 2, "bugs": [{"instance_id": "cs-si__eodag-566", "base_commit": "9af685574aa465456bca01f245b830b324db2c5c", "gold_patch": "diff --git a/eodag/plugins/download/http.py b/eodag/plugins/download/http.py\nindex 58fe8a89..9b9b66ba 100644\n--- a/eodag/plugins/download/http.py\n+++ b/eodag/plugins/download/http.py\n@@ -252,6 +252,9 @@ class HTTPDownload(Download):\n assets_urls = [\n a[\"href\"] for a in getattr(product, \"assets\", {}).values() if \"href\" in a\n ]\n+ assets_values = [\n+ a for a in getattr(product, \"assets\", {}).values() if \"href\" in a\n+ ]\n \n if not assets_urls:\n raise NotAvailableError(\"No assets available for %s\" % product)\n@@ -271,55 +274,77 @@ class HTTPDownload(Download):\n \"flatten_top_dirs\", getattr(self.config, \"flatten_top_dirs\", False)\n )\n \n- total_size = sum(\n- [\n- # get total size using header[Content-length] of each asset\n- int(\n- requests.head(\n- asset_url, auth=auth, timeout=HTTP_REQ_TIMEOUT\n- ).headers.get(\"Content-length\", 0)\n- )\n- or int( # alternative: get total size using header[content-disposition][size] of each asset\n- parse_header(\n- requests.head(\n- asset_url, auth=auth, timeout=HTTP_REQ_TIMEOUT\n- ).headers.get(\"content-disposition\", \"\")\n- )[-1].get(\"size\", 0)\n- )\n- for asset_url in assets_urls\n- if not asset_url.startswith(\"file:\")\n- ]\n+ # get extra parameters to pass to the query\n+ params = kwargs.pop(\"dl_url_params\", None) or getattr(\n+ self.config, \"dl_url_params\", {}\n )\n+\n+ total_size = 0\n+ # loop for assets size & filename\n+ for asset in assets_values:\n+ if not asset[\"href\"].startswith(\"file:\"):\n+ # HEAD request for size & filename\n+ asset_headers = requests.head(\n+ asset[\"href\"], auth=auth, timeout=HTTP_REQ_TIMEOUT\n+ ).headers\n+ header_content_disposition_dict = {}\n+\n+ if not asset.get(\"size\", 0):\n+ # size from HEAD header / Content-length\n+ asset[\"size\"] = int(asset_headers.get(\"Content-length\", 0))\n+\n+ if not asset.get(\"size\", 0) or not asset.get(\"filename\", 0):\n+ # header content-disposition\n+ header_content_disposition_dict = parse_header(\n+ asset_headers.get(\"content-disposition\", \"\")\n+ )[-1]\n+ if not asset.get(\"size\", 0):\n+ # size from HEAD header / content-disposition / size\n+ asset[\"size\"] = int(header_content_disposition_dict.get(\"size\", 0))\n+ if not asset.get(\"filename\", 0):\n+ # filename from HEAD header / content-disposition / size\n+ asset[\"filename\"] = header_content_disposition_dict.get(\n+ \"filename\", None\n+ )\n+\n+ if not asset.get(\"size\", 0):\n+ # GET request for size\n+ with requests.get(\n+ asset[\"href\"],\n+ stream=True,\n+ auth=auth,\n+ params=params,\n+ timeout=DEFAULT_STREAM_REQUESTS_TIMEOUT,\n+ ) as stream:\n+ # size from GET header / Content-length\n+ asset[\"size\"] = int(stream.headers.get(\"Content-length\", 0))\n+ if not asset.get(\"size\", 0):\n+ # size from GET header / content-disposition / size\n+ asset[\"size\"] = int(\n+ parse_header(\n+ stream.headers.get(\"content-disposition\", \"\")\n+ )[-1].get(\"size\", 0)\n+ )\n+\n+ total_size += asset[\"size\"]\n+\n progress_callback.reset(total=total_size)\n error_messages = set()\n \n local_assets_count = 0\n \n- for asset_url in assets_urls:\n+ # loop for assets download\n+ for asset in assets_values:\n \n- if asset_url.startswith(\"file:\"):\n- logger.info(f\"Local asset detected. Download skipped for {asset_url}\")\n+ if asset[\"href\"].startswith(\"file:\"):\n+ logger.info(\n+ f\"Local asset detected. Download skipped for {asset['href']}\"\n+ )\n local_assets_count += 1\n continue\n \n- # get asset filename from header\n- asset_content_disposition = requests.head(\n- asset_url, auth=auth, timeout=HTTP_REQ_TIMEOUT\n- ).headers.get(\"content-disposition\", None)\n- if asset_content_disposition:\n- asset_filename = parse_header(asset_content_disposition)[-1].get(\n- \"filename\", None\n- )\n- else:\n- asset_filename = None\n-\n- # get extra parameters to pass to the query\n- params = kwargs.pop(\"dl_url_params\", None) or getattr(\n- self.config, \"dl_url_params\", {}\n- )\n-\n with requests.get(\n- asset_url,\n+ asset[\"href\"],\n stream=True,\n auth=auth,\n params=params,\n@@ -343,28 +368,28 @@ class HTTPDownload(Download):\n )\n else:\n logger.warning(\"Unexpected error: %s\" % e)\n- logger.warning(\"Skipping %s\" % asset_url)\n+ logger.warning(\"Skipping %s\" % asset[\"href\"])\n error_messages.add(str(e))\n else:\n- asset_rel_path = urlparse(asset_url).path.strip(\"/\")\n+ asset_rel_path = urlparse(asset[\"href\"]).path.strip(\"/\")\n asset_rel_dir = os.path.dirname(asset_rel_path)\n \n- if asset_filename is None:\n- # try getting content-disposition header from GET if not in HEAD result\n- asset_content_disposition = stream.headers.get(\n+ if not asset.get(\"filename\", None):\n+ # try getting filename in GET header if was not found in HEAD result\n+ asset_content_disposition_dict = stream.headers.get(\n \"content-disposition\", None\n )\n- if asset_content_disposition:\n- asset_filename = parse_header(asset_content_disposition)[\n- -1\n- ].get(\"filename\", None)\n+ if asset_content_disposition_dict:\n+ asset[\"filename\"] = parse_header(\n+ asset_content_disposition_dict\n+ )[-1].get(\"filename\", None)\n \n- if asset_filename is None:\n+ if not asset.get(\"filename\", None):\n # default filename extracted from path\n- asset_filename = os.path.basename(asset_rel_path)\n+ asset[\"filename\"] = os.path.basename(asset_rel_path)\n \n asset_abs_path = os.path.join(\n- fs_dir_path, asset_rel_dir, asset_filename\n+ fs_dir_path, asset_rel_dir, asset[\"filename\"]\n )\n asset_abs_path_dir = os.path.dirname(asset_abs_path)\n if not os.path.isdir(asset_abs_path_dir):\n", "test_patch": "diff --git a/tests/units/test_download_plugins.py b/tests/units/test_download_plugins.py\nindex d31a976b..f37a1b01 100644\n--- a/tests/units/test_download_plugins.py\n+++ b/tests/units/test_download_plugins.py\n@@ -239,6 +239,73 @@ class TestDownloadPluginHttp(BaseDownloadPluginTest):\n )\n )\n \n+ @mock.patch(\"eodag.utils.ProgressCallback.reset\", autospec=True)\n+ @mock.patch(\"eodag.plugins.download.http.requests.head\", autospec=True)\n+ @mock.patch(\"eodag.plugins.download.http.requests.get\", autospec=True)\n+ def test_plugins_download_http_assets_size(\n+ self, mock_requests_get, mock_requests_head, mock_progress_callback_reset\n+ ):\n+ \"\"\"HTTPDownload.download() must get assets sizes\"\"\"\n+\n+ plugin = self.get_download_plugin(self.product)\n+ self.product.location = self.product.remote_location = \"http://somewhere\"\n+ self.product.assets = {\n+ \"foo\": {\"href\": \"http://somewhere/a\"},\n+ \"bar\": {\"href\": \"http://somewhere/b\"},\n+ }\n+\n+ mock_requests_head.return_value.headers = {\n+ \"Content-length\": \"1\",\n+ \"content-disposition\": '; size = \"2\"',\n+ }\n+ mock_requests_get.return_value.__enter__.return_value.headers = {\n+ \"Content-length\": \"3\",\n+ \"content-disposition\": '; size = \"4\"',\n+ }\n+\n+ # size from HEAD / Content-length\n+ with TemporaryDirectory() as temp_dir:\n+ plugin.download(self.product, outputs_prefix=temp_dir)\n+ mock_progress_callback_reset.assert_called_once_with(mock.ANY, total=1 + 1)\n+\n+ # size from HEAD / content-disposition\n+ mock_requests_head.return_value.headers.pop(\"Content-length\")\n+ mock_progress_callback_reset.reset_mock()\n+ self.product.location = \"http://somewhere\"\n+ self.product.assets = {\n+ \"foo\": {\"href\": \"http://somewhere/a\"},\n+ \"bar\": {\"href\": \"http://somewhere/b\"},\n+ }\n+ with TemporaryDirectory() as temp_dir:\n+ plugin.download(self.product, outputs_prefix=temp_dir)\n+ mock_progress_callback_reset.assert_called_once_with(mock.ANY, total=2 + 2)\n+\n+ # size from GET / Content-length\n+ mock_requests_head.return_value.headers.pop(\"content-disposition\")\n+ mock_progress_callback_reset.reset_mock()\n+ self.product.location = \"http://somewhere\"\n+ self.product.assets = {\n+ \"foo\": {\"href\": \"http://somewhere/a\"},\n+ \"bar\": {\"href\": \"http://somewhere/b\"},\n+ }\n+ with TemporaryDirectory() as temp_dir:\n+ plugin.download(self.product, outputs_prefix=temp_dir)\n+ mock_progress_callback_reset.assert_called_once_with(mock.ANY, total=3 + 3)\n+\n+ # size from GET / content-disposition\n+ mock_requests_get.return_value.__enter__.return_value.headers.pop(\n+ \"Content-length\"\n+ )\n+ mock_progress_callback_reset.reset_mock()\n+ self.product.location = \"http://somewhere\"\n+ self.product.assets = {\n+ \"foo\": {\"href\": \"http://somewhere/a\"},\n+ \"bar\": {\"href\": \"http://somewhere/b\"},\n+ }\n+ with TemporaryDirectory() as temp_dir:\n+ plugin.download(self.product, outputs_prefix=temp_dir)\n+ mock_progress_callback_reset.assert_called_once_with(mock.ANY, total=4 + 4)\n+\n def test_plugins_download_http_one_local_asset(\n self,\n ):\n", "FAIL_TO_PASS": ["tests/units/test_download_plugins.py::TestDownloadPluginHttp::test_plugins_download_http_assets_size"]}, {"instance_id": "cs-si__eodag-576", "base_commit": "73e95cb6407329faf860cb775e1dd61838e6a2c4", "gold_patch": "diff --git a/eodag/plugins/download/aws.py b/eodag/plugins/download/aws.py\nindex e5d9d2a9..8c28dcce 100644\n--- a/eodag/plugins/download/aws.py\n+++ b/eodag/plugins/download/aws.py\n@@ -19,7 +19,6 @@\n import logging\n import os\n import re\n-import shutil\n from pathlib import Path\n \n import boto3\n@@ -36,6 +35,7 @@ from eodag.api.product.metadata_mapping import (\n from eodag.plugins.download.base import Download\n from eodag.utils import (\n ProgressCallback,\n+ flatten_top_directories,\n get_bucket_name_and_prefix,\n path_to_uri,\n rename_subfolder,\n@@ -421,13 +421,7 @@ class AwsDownload(Download):\n self.finalize_s2_safe_product(product_local_path)\n # flatten directory structure\n elif flatten_top_dirs:\n- tmp_product_local_path = \"%s-tmp\" % product_local_path\n- for d, dirs, files in os.walk(product_local_path):\n- if len(files) != 0:\n- shutil.copytree(d, tmp_product_local_path)\n- shutil.rmtree(product_local_path)\n- os.rename(tmp_product_local_path, product_local_path)\n- break\n+ flatten_top_directories(product_local_path, common_prefix)\n \n if build_safe:\n self.check_manifest_file_list(product_local_path)\ndiff --git a/eodag/plugins/download/http.py b/eodag/plugins/download/http.py\nindex 9b9b66ba..e7061532 100644\n--- a/eodag/plugins/download/http.py\n+++ b/eodag/plugins/download/http.py\n@@ -33,7 +33,12 @@ from eodag.plugins.download.base import (\n DEFAULT_STREAM_REQUESTS_TIMEOUT,\n Download,\n )\n-from eodag.utils import ProgressCallback, path_to_uri, uri_to_path\n+from eodag.utils import (\n+ ProgressCallback,\n+ flatten_top_directories,\n+ path_to_uri,\n+ uri_to_path,\n+)\n from eodag.utils.exceptions import (\n AuthenticationError,\n MisconfiguredError,\n@@ -421,13 +426,7 @@ class HTTPDownload(Download):\n \n # flatten directory structure\n if flatten_top_dirs:\n- tmp_product_local_path = \"%s-tmp\" % fs_dir_path\n- for d, dirs, files in os.walk(fs_dir_path):\n- if len(files) != 0:\n- shutil.copytree(d, tmp_product_local_path)\n- shutil.rmtree(fs_dir_path)\n- os.rename(tmp_product_local_path, fs_dir_path)\n- break\n+ flatten_top_directories(fs_dir_path)\n \n # save hash/record file\n with open(record_filename, \"w\") as fh:\ndiff --git a/eodag/utils/__init__.py b/eodag/utils/__init__.py\nindex 40234376..b51b5f1e 100644\n--- a/eodag/utils/__init__.py\n+++ b/eodag/utils/__init__.py\n@@ -31,6 +31,7 @@ import json\n import logging as py_logging\n import os\n import re\n+import shutil\n import string\n import types\n import unicodedata\n@@ -39,6 +40,7 @@ from collections import defaultdict\n from glob import glob\n from itertools import repeat, starmap\n from pathlib import Path\n+from tempfile import mkdtemp\n \n # All modules using these should import them from utils package\n from urllib.parse import ( # noqa; noqa\n@@ -1058,3 +1060,25 @@ def get_bucket_name_and_prefix(url=None, bucket_path_level=None):\n )\n \n return bucket, prefix\n+\n+\n+def flatten_top_directories(nested_dir_root, common_subdirs_path=None):\n+ \"\"\"Flatten directory structure, removing common empty sub-directories\n+\n+ :param nested_dir_root: Absolute path of the directory structure to flatten\n+ :type nested_dir_root: str\n+ :param common_subdirs_path: (optional) Absolute path of the desired subdirectory to remove\n+ :type common_subdirs_path: str\n+ \"\"\"\n+ if not common_subdirs_path:\n+ subpaths_list = [p for p in Path(nested_dir_root).glob(\"**/*\") if p.is_file()]\n+ common_subdirs_path = os.path.commonpath(subpaths_list)\n+\n+ if nested_dir_root != common_subdirs_path:\n+ logger.debug(f\"Flatten {common_subdirs_path} to {nested_dir_root}\")\n+ tmp_path = mkdtemp()\n+ # need to delete tmp_path to prevent FileExistsError with copytree. Use dirs_exist_ok with py > 3.7\n+ shutil.rmtree(tmp_path)\n+ shutil.copytree(common_subdirs_path, tmp_path)\n+ shutil.rmtree(nested_dir_root)\n+ shutil.move(tmp_path, nested_dir_root)\n", "test_patch": "diff --git a/tests/context.py b/tests/context.py\nindex dd8a54a7..dec2c197 100644\n--- a/tests/context.py\n+++ b/tests/context.py\n@@ -73,6 +73,7 @@ from eodag.utils import (\n parse_qsl,\n urlsplit,\n GENERIC_PRODUCT_TYPE,\n+ flatten_top_directories,\n )\n from eodag.utils.exceptions import (\n AddressNotFound,\ndiff --git a/tests/units/test_utils.py b/tests/units/test_utils.py\nindex 8616d6c2..04b4ad9b 100644\n--- a/tests/units/test_utils.py\n+++ b/tests/units/test_utils.py\n@@ -16,15 +16,19 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n+import os\n import sys\n import unittest\n from contextlib import closing\n from datetime import datetime\n from io import StringIO\n+from pathlib import Path\n+from tempfile import TemporaryDirectory\n \n from tests.context import (\n DownloadedCallback,\n ProgressCallback,\n+ flatten_top_directories,\n get_bucket_name_and_prefix,\n get_timestamp,\n merge_mappings,\n@@ -215,3 +219,46 @@ class TestUtils(unittest.TestCase):\n ),\n (\"bucket\", \"path/to/product\"),\n )\n+\n+ def test_flatten_top_dirs(self):\n+ \"\"\"flatten_top_dirs must flatten directory structure\"\"\"\n+ with TemporaryDirectory() as nested_dir_root:\n+ os.makedirs(os.path.join(nested_dir_root, \"a\", \"b\", \"c1\"))\n+ os.makedirs(os.path.join(nested_dir_root, \"a\", \"b\", \"c2\"))\n+ # create empty files\n+ open(os.path.join(nested_dir_root, \"a\", \"b\", \"c1\", \"foo\"), \"a\").close()\n+ open(os.path.join(nested_dir_root, \"a\", \"b\", \"c2\", \"bar\"), \"a\").close()\n+ open(os.path.join(nested_dir_root, \"a\", \"b\", \"c2\", \"baz\"), \"a\").close()\n+\n+ flatten_top_directories(nested_dir_root)\n+\n+ dir_content = list(Path(nested_dir_root).glob(\"**/*\"))\n+\n+ self.assertEqual(len(dir_content), 5)\n+ self.assertIn(Path(nested_dir_root) / \"c1\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"c1\" / \"foo\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"c2\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"c2\" / \"bar\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"c2\" / \"baz\", dir_content)\n+\n+ def test_flatten_top_dirs_given_subdir(self):\n+ \"\"\"flatten_top_dirs must flatten directory structure using given subdirectory\"\"\"\n+ with TemporaryDirectory() as nested_dir_root:\n+ os.makedirs(os.path.join(nested_dir_root, \"a\", \"b\", \"c1\"))\n+ os.makedirs(os.path.join(nested_dir_root, \"a\", \"b\", \"c2\"))\n+ # create empty files\n+ open(os.path.join(nested_dir_root, \"a\", \"b\", \"c1\", \"foo\"), \"a\").close()\n+ open(os.path.join(nested_dir_root, \"a\", \"b\", \"c2\", \"bar\"), \"a\").close()\n+ open(os.path.join(nested_dir_root, \"a\", \"b\", \"c2\", \"baz\"), \"a\").close()\n+\n+ flatten_top_directories(nested_dir_root, os.path.join(nested_dir_root, \"a\"))\n+\n+ dir_content = list(Path(nested_dir_root).glob(\"**/*\"))\n+\n+ self.assertEqual(len(dir_content), 6)\n+ self.assertIn(Path(nested_dir_root) / \"b\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"b\" / \"c1\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"b\" / \"c1\" / \"foo\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"b\" / \"c2\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"b\" / \"c2\" / \"bar\", dir_content)\n+ self.assertIn(Path(nested_dir_root) / \"b\" / \"c2\" / \"baz\", dir_content)\n", "FAIL_TO_PASS": ["tests/units/test_utils.py::TestUtils::test_downloaded_callback", "tests/units/test_utils.py::TestUtils::test_flatten_top_dirs", "tests/units/test_utils.py::TestUtils::test_flatten_top_dirs_given_subdir", "tests/units/test_utils.py::TestUtils::test_get_bucket_name_and_prefix", "tests/units/test_utils.py::TestUtils::test_merge_mappings", "tests/units/test_utils.py::TestUtils::test_path_to_uri", "tests/units/test_utils.py::TestUtils::test_progresscallback_copy", "tests/units/test_utils.py::TestUtils::test_progresscallback_disable", "tests/units/test_utils.py::TestUtils::test_progresscallback_init", "tests/units/test_utils.py::TestUtils::test_progresscallback_init_customize", "tests/units/test_utils.py::TestUtils::test_uri_to_path", "tests/units/test_utils.py::TestUtils::test_utils_get_timestamp"]}], "all_FAIL_TO_PASS": ["tests/units/test_download_plugins.py::TestDownloadPluginHttp::test_plugins_download_http_assets_size", "tests/units/test_utils.py::TestUtils::test_downloaded_callback", "tests/units/test_utils.py::TestUtils::test_flatten_top_dirs", "tests/units/test_utils.py::TestUtils::test_flatten_top_dirs_given_subdir", "tests/units/test_utils.py::TestUtils::test_get_bucket_name_and_prefix", "tests/units/test_utils.py::TestUtils::test_merge_mappings", "tests/units/test_utils.py::TestUtils::test_path_to_uri", "tests/units/test_utils.py::TestUtils::test_progresscallback_copy", "tests/units/test_utils.py::TestUtils::test_progresscallback_disable", "tests/units/test_utils.py::TestUtils::test_progresscallback_init", "tests/units/test_utils.py::TestUtils::test_progresscallback_init_customize", "tests/units/test_utils.py::TestUtils::test_uri_to_path", "tests/units/test_utils.py::TestUtils::test_utils_get_timestamp"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "zalando__patroni-2304_x2", "level": 2, "source": "swerebenchv2", "repo": "zalando/patroni", "image": "swerebenchv2/zalando-patroni:2304-96b75fa", "base_commit": "96b75fa7cbf43f185642cf7d5e5b6b57ecf231bc", "num_bugs": 2, "bugs": [{"instance_id": "zalando__patroni-2304", "base_commit": "96b75fa7cbf43f185642cf7d5e5b6b57ecf231bc", "gold_patch": "diff --git a/patroni/ha.py b/patroni/ha.py\nindex 0bd2747a..9f84613f 100644\n--- a/patroni/ha.py\n+++ b/patroni/ha.py\n@@ -307,7 +307,8 @@ class Ha(object):\n \n if self._rewind.can_rewind:\n # rewind is required, but postgres wasn't shut down cleanly.\n- if self.state_handler.controldata().get('Database cluster state') == 'in archive recovery':\n+ if not self.state_handler.is_running() and \\\n+ self.state_handler.controldata().get('Database cluster state') == 'in archive recovery':\n msg = self._handle_crash_recovery()\n if msg:\n return msg\n@@ -315,8 +316,7 @@ class Ha(object):\n msg = 'running pg_rewind from ' + leader.name\n return self._async_executor.try_run_async(msg, self._rewind.execute, args=(leader,)) or msg\n \n- # remove_data_directory_on_diverged_timelines is set\n- if not self.is_standby_cluster():\n+ if self._rewind.should_remove_data_directory_on_diverged_timelines and not self.is_standby_cluster():\n msg = 'reinitializing due to diverged timelines'\n return self._async_executor.try_run_async(msg, self._do_reinitialize, args=(self.cluster,)) or msg\n \ndiff --git a/patroni/postgresql/rewind.py b/patroni/postgresql/rewind.py\nindex 5a2e4a39..db7055df 100644\n--- a/patroni/postgresql/rewind.py\n+++ b/patroni/postgresql/rewind.py\n@@ -46,9 +46,13 @@ class Rewind(object):\n return False\n return self.configuration_allows_rewind(self._postgresql.controldata())\n \n+ @property\n+ def should_remove_data_directory_on_diverged_timelines(self):\n+ return self._postgresql.config.get('remove_data_directory_on_diverged_timelines')\n+\n @property\n def can_rewind_or_reinitialize_allowed(self):\n- return self._postgresql.config.get('remove_data_directory_on_diverged_timelines') or self.can_rewind\n+ return self.should_remove_data_directory_on_diverged_timelines or self.can_rewind\n \n def trigger_check_diverged_lsn(self):\n if self.can_rewind_or_reinitialize_allowed and self._state != REWIND_STATUS.NEED:\n@@ -374,19 +378,22 @@ class Rewind(object):\n \n if self.pg_rewind(r):\n self._state = REWIND_STATUS.SUCCESS\n- elif not self.check_leader_is_not_in_recovery(r):\n- logger.warning('Failed to rewind because master %s become unreachable', leader.name)\n else:\n- logger.error('Failed to rewind from healty master: %s', leader.name)\n-\n- for name in ('remove_data_directory_on_rewind_failure', 'remove_data_directory_on_diverged_timelines'):\n- if self._postgresql.config.get(name):\n- logger.warning('%s is set. removing...', name)\n- self._postgresql.remove_data_directory()\n- self._state = REWIND_STATUS.INITIAL\n- break\n+ if not self.check_leader_is_not_in_recovery(r):\n+ logger.warning('Failed to rewind because master %s become unreachable', leader.name)\n+ if not self.can_rewind: # It is possible that the previous attempt damaged pg_control file!\n+ self._state = REWIND_STATUS.FAILED\n else:\n+ logger.error('Failed to rewind from healty master: %s', leader.name)\n self._state = REWIND_STATUS.FAILED\n+\n+ if self.failed:\n+ for name in ('remove_data_directory_on_rewind_failure', 'remove_data_directory_on_diverged_timelines'):\n+ if self._postgresql.config.get(name):\n+ logger.warning('%s is set. removing...', name)\n+ self._postgresql.remove_data_directory()\n+ self._state = REWIND_STATUS.INITIAL\n+ break\n return False\n \n def reset_state(self):\n", "test_patch": "diff --git a/tests/test_ha.py b/tests/test_ha.py\nindex 56277f97..5ed4503d 100644\n--- a/tests/test_ha.py\n+++ b/tests/test_ha.py\n@@ -314,6 +314,7 @@ class TestHa(PostgresInit):\n self.assertEqual(self.ha.run_cycle(), 'fake')\n \n @patch.object(Rewind, 'rewind_or_reinitialize_needed_and_possible', Mock(return_value=True))\n+ @patch.object(Rewind, 'should_remove_data_directory_on_diverged_timelines', PropertyMock(return_value=True))\n @patch.object(Bootstrap, 'create_replica', Mock(return_value=1))\n def test_recover_with_reinitialize(self):\n self.p.is_running = false\n", "FAIL_TO_PASS": ["tests/test_ha.py::TestHa::test_recover_with_reinitialize"]}, {"instance_id": "zalando__patroni-2308", "base_commit": "ef3401c17fb1520e2c169fc740606f602528656f", "gold_patch": "diff --git a/docs/SETTINGS.rst b/docs/SETTINGS.rst\nindex 63e7f1c5..4e9103ec 100644\n--- a/docs/SETTINGS.rst\n+++ b/docs/SETTINGS.rst\n@@ -314,7 +314,7 @@ PostgreSQL\n - **pg\\_ctl\\_timeout**: How long should pg_ctl wait when doing ``start``, ``stop`` or ``restart``. Default value is 60 seconds.\n - **use\\_pg\\_rewind**: try to use pg\\_rewind on the former leader when it joins cluster as a replica.\n - **remove\\_data\\_directory\\_on\\_rewind\\_failure**: If this option is enabled, Patroni will remove the PostgreSQL data directory and recreate the replica. Otherwise it will try to follow the new leader. Default value is **false**.\n- - **remove\\_data\\_directory\\_on\\_diverged\\_timelines**: Patroni will remove the PostgreSQL data directory and recreate the replica if it notices that timelines are diverging and the former master can not start streaming from the new master. This option is useful when ``pg_rewind`` can not be used. Default value is **false**.\n+ - **remove\\_data\\_directory\\_on\\_diverged\\_timelines**: Patroni will remove the PostgreSQL data directory and recreate the replica if it notices that timelines are diverging and the former master can not start streaming from the new master. This option is useful when ``pg_rewind`` can not be used. While performing timelines divergence check on PostgreSQL v10 and older Patroni will try to connect with replication credential to the \"postgres\" database. Hence, such access should be allowed in the pg_hba.conf. Default value is **false**.\n - **replica\\_method**: for each create_replica_methods other than basebackup, you would add a configuration section of the same name. At a minimum, this should include \"command\" with a full path to the actual script to be executed. Other configuration parameters will be passed along to the script in the form \"parameter=value\".\n - **pre\\_promote**: a fencing script that executes during a failover after acquiring the leader lock but before promoting the replica. If the script exits with a non-zero code, Patroni does not promote the replica and removes the leader key from DCS.\n \ndiff --git a/features/environment.py b/features/environment.py\nindex 955e2a39..f07e4729 100644\n--- a/features/environment.py\n+++ b/features/environment.py\n@@ -186,7 +186,7 @@ class PatroniController(AbstractController):\n config['postgresql']['parameters'].update({\n 'logging_collector': 'on', 'log_destination': 'csvlog', 'log_directory': self._output_dir,\n 'log_filename': name + '.log', 'log_statement': 'all', 'log_min_messages': 'debug1',\n- 'unix_socket_directories': self._data_dir})\n+ 'unix_socket_directories': tempfile.gettempdir()})\n \n if 'bootstrap' in config:\n config['bootstrap']['post_bootstrap'] = 'psql -w -c \"SELECT 1\"'\ndiff --git a/patroni/dcs/kubernetes.py b/patroni/dcs/kubernetes.py\nindex 059bd369..3f1c1e51 100644\n--- a/patroni/dcs/kubernetes.py\n+++ b/patroni/dcs/kubernetes.py\n@@ -518,6 +518,8 @@ class ObjectCache(Thread):\n self._condition = condition\n self._name = name # name of this pod\n self._is_ready = False\n+ self._response = None # needs to be accessible from the `kill_stream()` method\n+ self._response_lock = Lock() # protect the `self._response` from concurrent access\n self._object_cache = {}\n self._object_cache_lock = Lock()\n self._annotations_map = {self._dcs.leader_path: self._dcs._LEADER, self._dcs.config_path: self._dcs._CONFIG}\n@@ -558,63 +560,99 @@ class ObjectCache(Thread):\n with self._object_cache_lock:\n return self._object_cache.get(name)\n \n+ def _process_event(self, event):\n+ ev_type = event['type']\n+ obj = event['object']\n+ name = obj['metadata']['name']\n+\n+ if ev_type in ('ADDED', 'MODIFIED'):\n+ obj = K8sObject(obj)\n+ success, old_value = self.set(name, obj)\n+ if success:\n+ new_value = (obj.metadata.annotations or {}).get(self._annotations_map.get(name))\n+ elif ev_type == 'DELETED':\n+ success, old_value = self.delete(name, obj['metadata']['resourceVersion'])\n+ new_value = None\n+ else:\n+ return logger.warning('Unexpected event type: %s', ev_type)\n+\n+ if success and obj.get('kind') != 'Pod':\n+ if old_value:\n+ old_value = (old_value.metadata.annotations or {}).get(self._annotations_map.get(name))\n+\n+ value_changed = old_value != new_value and \\\n+ (name != self._dcs.config_path or old_value is not None and new_value is not None)\n+\n+ if value_changed:\n+ logger.debug('%s changed from %s to %s', name, old_value, new_value)\n+\n+ # Do not wake up HA loop if we run as leader and received leader object update event\n+ if value_changed or name == self._dcs.leader_path and self._name != new_value:\n+ self._dcs.event.set()\n+\n+ @staticmethod\n+ def _finish_response(response):\n+ try:\n+ response.close()\n+ finally:\n+ response.release_conn()\n+\n+ def _do_watch(self, resource_version):\n+ with self._response_lock:\n+ self._response = None\n+ response = self._watch(resource_version)\n+ with self._response_lock:\n+ if self._response is None:\n+ self._response = response\n+\n+ if not self._response:\n+ return self._finish_response(response)\n+\n+ for event in iter_response_objects(response):\n+ if event['object'].get('code') == 410:\n+ break\n+ self._process_event(event)\n+\n def _build_cache(self):\n objects = self._list()\n- return_type = 'V1' + objects.kind[:-4]\n with self._object_cache_lock:\n self._object_cache = {item.metadata.name: item for item in objects.items}\n with self._condition:\n self._is_ready = True\n self._condition.notify()\n \n- response = self._watch(objects.metadata.resource_version)\n try:\n- for event in iter_response_objects(response):\n- obj = event['object']\n- if obj.get('code') == 410:\n- break\n-\n- ev_type = event['type']\n- name = obj['metadata']['name']\n-\n- if ev_type in ('ADDED', 'MODIFIED'):\n- obj = K8sObject(obj)\n- success, old_value = self.set(name, obj)\n- if success:\n- new_value = (obj.metadata.annotations or {}).get(self._annotations_map.get(name))\n- elif ev_type == 'DELETED':\n- success, old_value = self.delete(name, obj['metadata']['resourceVersion'])\n- new_value = None\n- else:\n- logger.warning('Unexpected event type: %s', ev_type)\n- continue\n-\n- if success and return_type != 'V1Pod':\n- if old_value:\n- old_value = (old_value.metadata.annotations or {}).get(self._annotations_map.get(name))\n-\n- value_changed = old_value != new_value and \\\n- (name != self._dcs.config_path or old_value is not None and new_value is not None)\n-\n- if value_changed:\n- logger.debug('%s changed from %s to %s', name, old_value, new_value)\n-\n- # Do not wake up HA loop if we run as leader and received leader object update event\n- if value_changed or name == self._dcs.leader_path and self._name != new_value:\n- self._dcs.event.set()\n+ self._do_watch(objects.metadata.resource_version)\n finally:\n with self._condition:\n self._is_ready = False\n- response.close()\n- response.release_conn()\n+ with self._response_lock:\n+ response, self._response = self._response, None\n+ if response:\n+ self._finish_response(response)\n+\n+ def kill_stream(self):\n+ sock = None\n+ with self._response_lock:\n+ if self._response:\n+ try:\n+ sock = self._response.connection.sock\n+ except Exception:\n+ sock = None\n+ else:\n+ self._response = False\n+ if sock:\n+ try:\n+ sock.shutdown(socket.SHUT_RDWR)\n+ sock.close()\n+ except Exception as e:\n+ logger.debug('Error on socket.shutdown: %r', e)\n \n def run(self):\n while True:\n try:\n self._build_cache()\n except Exception as e:\n- with self._condition:\n- self._is_ready = False\n logger.error('ObjectCache.run %r', e)\n \n def is_ready(self):\n@@ -889,7 +927,14 @@ class Kubernetes(AbstractDCS):\n def patch_or_create(self, name, annotations, resource_version=None, patch=False, retry=True, ips=None):\n if retry is True:\n retry = self.retry\n- return self._patch_or_create(name, annotations, resource_version, patch, retry, ips)\n+ try:\n+ return self._patch_or_create(name, annotations, resource_version, patch, retry, ips)\n+ except k8s_client.rest.ApiException as e:\n+ if e.status == 409 and resource_version: # Conflict in resource_version\n+ # Terminate watchers, it could be a sign that K8s API is in a failed state\n+ self._kinds.kill_stream()\n+ self._pods.kill_stream()\n+ raise e\n \n def patch_or_create_config(self, annotations, resource_version=None, patch=False, retry=True):\n # SCOPE-config endpoint requires corresponding service otherwise it might be \"cleaned\" by k8s master\ndiff --git a/patroni/postgresql/rewind.py b/patroni/postgresql/rewind.py\nindex db7055df..481f0b7a 100644\n--- a/patroni/postgresql/rewind.py\n+++ b/patroni/postgresql/rewind.py\n@@ -28,13 +28,17 @@ class Rewind(object):\n def configuration_allows_rewind(data):\n return data.get('wal_log_hints setting', 'off') == 'on' or data.get('Data page checksum version', '0') != '0'\n \n+ @property\n+ def enabled(self):\n+ return self._postgresql.config.get('use_pg_rewind')\n+\n @property\n def can_rewind(self):\n \"\"\" check if pg_rewind executable is there and that pg_controldata indicates\n we have either wal_log_hints or checksums turned on\n \"\"\"\n # low-hanging fruit: check if pg_rewind configuration is there\n- if not self._postgresql.config.get('use_pg_rewind'):\n+ if not self.enabled:\n return False\n \n cmd = [self._postgresql.pgcommand('pg_rewind'), '--help']\n@@ -186,8 +190,14 @@ class Rewind(object):\n if isinstance(leader, Leader) and leader.member.data.get('role') != 'master':\n return\n \n- if not self.check_leader_is_not_in_recovery(\n- self._conn_kwargs(leader, self._postgresql.config.replication)):\n+ # We want to use replication credentials when connecting to the \"postgres\" database in case if\n+ # `use_pg_rewind` isn't enabled and only `remove_data_directory_on_diverged_timelines` is set\n+ # for Postgresql older than v11 (where Patroni can't use a dedicated user for rewind).\n+ # In all other cases we will use rewind or superuser credentials.\n+ check_credentials = self._postgresql.config.replication if not self.enabled and\\\n+ self.should_remove_data_directory_on_diverged_timelines and\\\n+ self._postgresql.major_version < 110000 else self._postgresql.config.rewind_credentials\n+ if not self.check_leader_is_not_in_recovery(self._conn_kwargs(leader, check_credentials)):\n return\n \n history = need_rewind = None\n@@ -315,15 +325,18 @@ class Rewind(object):\n restore_command = self._postgresql.config.get('recovery_conf', {}).get('restore_command') \\\n if self._postgresql.major_version < 120000 else self._postgresql.get_guc_value('restore_command')\n \n- # currently, pg_rewind expects postgresql.conf to be inside $PGDATA, which is not the case on e.g. Debian\n- # Fix this logic if e.g. PG15 receives an update for pg_rewind:\n- pg_rewind_can_restore = self._postgresql.major_version >= 130000 \\\n- and restore_command \\\n- and self._postgresql.config._config_dir == self._postgresql.data_dir\n+ # Until v15 pg_rewind expected postgresql.conf to be inside $PGDATA, which is not the case on e.g. Debian\n+ pg_rewind_can_restore = restore_command and (self._postgresql.major_version >= 150000 or\n+ (self._postgresql.major_version >= 130000 and\n+ self._postgresql.config._config_dir == self._postgresql.data_dir))\n \n cmd = [self._postgresql.pgcommand('pg_rewind')]\n if pg_rewind_can_restore:\n cmd.append('--restore-target-wal')\n+ if self._postgresql.major_version >= 150000 and\\\n+ self._postgresql.config._config_dir != self._postgresql.data_dir:\n+ cmd.append('--config-file={0}'.format(self._postgresql.config.postgresql_conf))\n+\n cmd.extend(['-D', self._postgresql.data_dir, '--source-server', dsn])\n \n while True:\ndiff --git a/patroni/postgresql/validator.py b/patroni/postgresql/validator.py\nindex f6fd3d6e..8922bb85 100644\n--- a/patroni/postgresql/validator.py\n+++ b/patroni/postgresql/validator.py\n@@ -99,9 +99,11 @@ class String(namedtuple('String', 'version_from,version_till')):\n # key - parameter name\n # value - tuple or multiple tuples if something was changing in GUC across postgres versions\n parameters = CaseInsensitiveDict({\n+ 'allow_in_place_tablespaces': Bool(150000, None),\n 'allow_system_table_mods': Bool(90300, None),\n 'application_name': String(90300, None),\n 'archive_command': String(90300, None),\n+ 'archive_library': String(150000, None),\n 'archive_mode': (\n Bool(90300, 90500),\n EnumBool(90500, None, ('always',))\n@@ -158,7 +160,10 @@ parameters = CaseInsensitiveDict({\n 'cluster_name': String(90500, None),\n 'commit_delay': Integer(90300, None, 0, 100000, None),\n 'commit_siblings': Integer(90300, None, 0, 1000, None),\n- 'compute_query_id': EnumBool(140000, None, ('auto',)),\n+ 'compute_query_id': (\n+ EnumBool(140000, 150000, ('auto',)),\n+ EnumBool(150000, None, ('auto', 'regress'))\n+ ),\n 'config_file': String(90300, None),\n 'constraint_exclusion': EnumBool(90300, None, ('partition',)),\n 'cpu_index_tuple_cost': Real(90300, None, 0, 1.79769e+308, None),\n@@ -170,6 +175,7 @@ parameters = CaseInsensitiveDict({\n 'DateStyle': String(90300, None),\n 'db_user_namespace': Bool(90300, None),\n 'deadlock_timeout': Integer(90300, None, 1, 2147483647, 'ms'),\n+ 'debug_discard_caches': Integer(150000, None, 0, 0, None),\n 'debug_pretty_print': Bool(90300, None),\n 'debug_print_parse': Bool(90300, None),\n 'debug_print_plan': Bool(90300, None),\n@@ -194,12 +200,14 @@ parameters = CaseInsensitiveDict({\n 'enable_async_append': Bool(140000, None),\n 'enable_bitmapscan': Bool(90300, None),\n 'enable_gathermerge': Bool(100000, None),\n+ 'enable_group_by_reordering': Bool(150000, None),\n 'enable_hashagg': Bool(90300, None),\n 'enable_hashjoin': Bool(90300, None),\n 'enable_incremental_sort': Bool(130000, None),\n 'enable_indexonlyscan': Bool(90300, None),\n 'enable_indexscan': Bool(90300, None),\n 'enable_material': Bool(90300, None),\n+ 'enable_memoize': Bool(150000, None),\n 'enable_mergejoin': Bool(90300, None),\n 'enable_nestloop': Bool(90300, None),\n 'enable_parallel_append': Bool(110000, None),\n@@ -294,6 +302,7 @@ parameters = CaseInsensitiveDict({\n 'log_replication_commands': Bool(90500, None),\n 'log_rotation_age': Integer(90300, None, 0, 35791394, 'min'),\n 'log_rotation_size': Integer(90300, None, 0, 2097151, 'kB'),\n+ 'log_startup_progress_interval': Integer(150000, None, 0, 2147483647, 'ms'),\n 'log_statement': Enum(90300, None, ('none', 'ddl', 'mod', 'all')),\n 'log_statement_sample_rate': Real(130000, None, 0, 1, None),\n 'log_statement_stats': Bool(90300, None),\n@@ -368,6 +377,8 @@ parameters = CaseInsensitiveDict({\n 'quote_all_identifiers': Bool(90300, None),\n 'random_page_cost': Real(90300, None, 0, 1.79769e+308, None),\n 'recovery_init_sync_method': Enum(140000, None, ('fsync', 'syncfs')),\n+ 'recovery_prefetch': EnumBool(150000, None, ('try',)),\n+ 'recursive_worktable_factor': Real(150000, None, 0.001, 1e+06, None),\n 'remove_temp_files_after_crash': Bool(140000, None),\n 'replacement_sort_tuples': Integer(90600, 110000, 0, 2147483647, None),\n 'restart_after_crash': Bool(90300, None),\n@@ -397,7 +408,8 @@ parameters = CaseInsensitiveDict({\n 'ssl_renegotiation_limit': Integer(90300, 90500, 0, 2147483647, 'kB'),\n 'standard_conforming_strings': Bool(90300, None),\n 'statement_timeout': Integer(90300, None, 0, 2147483647, 'ms'),\n- 'stats_temp_directory': String(90300, None),\n+ 'stats_fetch_consistency': Enum(150000, None, ('none', 'cache', 'snapshot')),\n+ 'stats_temp_directory': String(90300, 150000),\n 'superuser_reserved_connections': (\n Integer(90300, 90600, 0, 8388607, None),\n Integer(90600, None, 0, 262143, None)\n@@ -463,8 +475,12 @@ parameters = CaseInsensitiveDict({\n 'vacuum_multixact_freeze_min_age': Integer(90300, None, 0, 1000000000, None),\n 'vacuum_multixact_freeze_table_age': Integer(90300, None, 0, 2000000000, None),\n 'wal_buffers': Integer(90300, None, -1, 262143, '8kB'),\n- 'wal_compression': Bool(90500, None),\n+ 'wal_compression': (\n+ Bool(90500, 150000),\n+ EnumBool(150000, None, ('pglz', 'lz4', 'zstd'))\n+ ),\n 'wal_consistency_checking': String(100000, None),\n+ 'wal_decode_buffer_size': Integer(150000, None, 65536, 1073741823, 'B'),\n 'wal_init_zero': Bool(120000, None),\n 'wal_keep_segments': Integer(90300, 130000, 0, 2147483647, None),\n 'wal_keep_size': Integer(130000, None, 0, 2147483647, 'MB'),\ndiff --git a/patroni/utils.py b/patroni/utils.py\nindex 1cfad919..01953d05 100644\n--- a/patroni/utils.py\n+++ b/patroni/utils.py\n@@ -362,7 +362,7 @@ def polling_loop(timeout, interval=1):\n def split_host_port(value, default_port):\n t = value.rsplit(':', 1)\n if ':' in t[0]:\n- t[0] = t[0].strip('[]')\n+ t[0] = ','.join([h.strip().strip('[]') for h in t[0].split(',')])\n t.append(default_port)\n return t[0], int(t[1])\n \ndiff --git a/postgres0.yml b/postgres0.yml\nindex 4a958ac8..33ead029 100644\n--- a/postgres0.yml\n+++ b/postgres0.yml\n@@ -119,7 +119,7 @@ postgresql:\n # Fully qualified kerberos ticket file for the running user\n # same as KRB5CCNAME used by the GSS\n # krb_server_keyfile: /var/spool/keytabs/postgres\n- unix_socket_directories: '.'\n+ unix_socket_directories: '..' # parent directory of data_dir\n # Additional fencing script executed after acquiring the leader lock but before promoting the replica\n #pre_promote: /path/to/pre_promote.sh\n \ndiff --git a/postgres1.yml b/postgres1.yml\nindex 17ccfdc2..6721a745 100644\n--- a/postgres1.yml\n+++ b/postgres1.yml\n@@ -113,7 +113,7 @@ postgresql:\n # Fully qualified kerberos ticket file for the running user\n # same as KRB5CCNAME used by the GSS\n # krb_server_keyfile: /var/spool/keytabs/postgres\n- unix_socket_directories: '.'\n+ unix_socket_directories: '..' # parent directory of data_dir\n basebackup:\n - verbose\n - max-rate: 100M\ndiff --git a/postgres2.yml b/postgres2.yml\nindex c17dd7d0..824afd75 100644\n--- a/postgres2.yml\n+++ b/postgres2.yml\n@@ -110,7 +110,7 @@ postgresql:\n # Fully qualified kerberos ticket file for the running user\n # same as KRB5CCNAME used by the GSS\n # krb_server_keyfile: /var/spool/keytabs/postgres\n- unix_socket_directories: '.'\n+ unix_socket_directories: '..' # parent directory of data_dir\n tags:\n nofailover: false\n noloadbalance: false\n", "test_patch": "diff --git a/tests/test_kubernetes.py b/tests/test_kubernetes.py\nindex 982edb5d..fbdd9b67 100644\n--- a/tests/test_kubernetes.py\n+++ b/tests/test_kubernetes.py\n@@ -4,7 +4,7 @@ import socket\n import time\n import unittest\n \n-from mock import Mock, mock_open, patch\n+from mock import Mock, PropertyMock, mock_open, patch\n from patroni.dcs.kubernetes import k8s_client, k8s_config, K8sConfig, K8sConnectionFailed,\\\n K8sException, K8sObject, Kubernetes, KubernetesError, KubernetesRetriableException,\\\n Retry, RetryFailedError, SERVICE_HOST_ENV_NAME, SERVICE_PORT_ENV_NAME\n@@ -235,7 +235,9 @@ class TestKubernetesConfigMaps(BaseTestKubernetes):\n self.k.manual_failover('foo', 'bar')\n \n def test_set_config_value(self):\n- self.k.set_config_value('{}')\n+ with patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map',\n+ Mock(side_effect=k8s_client.rest.ApiException(409, '')), create=True):\n+ self.k.set_config_value('{}', 1)\n \n @patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod', create=True)\n def test_touch_member(self, mock_patch_namespaced_pod):\n@@ -345,3 +347,18 @@ class TestCacheBuilder(BaseTestKubernetes):\n def test__list(self):\n self.k._pods._func = Mock(side_effect=Exception)\n self.assertRaises(Exception, self.k._pods._list)\n+\n+ @patch('patroni.dcs.kubernetes.ObjectCache._watch', Mock(return_value=None))\n+ def test__do_watch(self):\n+ self.assertRaises(AttributeError, self.k._kinds._do_watch, '1')\n+\n+ @patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map, create=True)\n+ @patch('patroni.dcs.kubernetes.ObjectCache._watch')\n+ def test_kill_stream(self, mock_watch):\n+ self.k._kinds.kill_stream()\n+ mock_watch.return_value.read_chunked.return_value = []\n+ mock_watch.return_value.connection.sock.close.side_effect = Exception\n+ self.k._kinds._do_watch('1')\n+ self.k._kinds.kill_stream()\n+ type(mock_watch.return_value).connection = PropertyMock(side_effect=Exception)\n+ self.k._kinds.kill_stream()\ndiff --git a/tests/test_rewind.py b/tests/test_rewind.py\nindex 33b8149e..2d510b33 100644\n--- a/tests/test_rewind.py\n+++ b/tests/test_rewind.py\n@@ -66,7 +66,7 @@ class TestRewind(BaseTestPostgresql):\n \n def test_pg_rewind(self):\n r = {'user': '', 'host': '', 'port': '', 'database': '', 'password': ''}\n- with patch.object(Postgresql, 'major_version', PropertyMock(return_value=130000)),\\\n+ with patch.object(Postgresql, 'major_version', PropertyMock(return_value=150000)),\\\n patch.object(CancellableSubprocess, 'call', Mock(return_value=None)):\n with patch('subprocess.check_output', Mock(return_value=b'boo')):\n self.assertFalse(self.r.pg_rewind(r))\n", "FAIL_TO_PASS": ["tests/test_kubernetes.py::TestCacheBuilder::test__do_watch", "tests/test_kubernetes.py::TestCacheBuilder::test_kill_stream"]}], "all_FAIL_TO_PASS": ["tests/test_ha.py::TestHa::test_recover_with_reinitialize", "tests/test_kubernetes.py::TestCacheBuilder::test__do_watch", "tests/test_kubernetes.py::TestCacheBuilder::test_kill_stream"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "tornadoweb__tornado-3477_x2", "level": 2, "source": "swerebenchv2", "repo": "tornadoweb/tornado", "image": "swerebenchv2/tornadoweb-tornado:3477-0b7e700", "base_commit": "0b7e700c1fe90f387602ad3305598b23833c30f9", "num_bugs": 2, "bugs": [{"instance_id": "tornadoweb__tornado-3477", "base_commit": "0b7e700c1fe90f387602ad3305598b23833c30f9", "gold_patch": "diff --git a/tornado/httputil.py b/tornado/httputil.py\nindex 2f1a9ba8..b2b93463 100644\n--- a/tornado/httputil.py\n+++ b/tornado/httputil.py\n@@ -207,18 +207,39 @@ class HTTPHeaders(StrMutableMapping):\n yield (name, value)\n \n def parse_line(self, line: str) -> None:\n- \"\"\"Updates the dictionary with a single header line.\n+ r\"\"\"Updates the dictionary with a single header line.\n \n >>> h = HTTPHeaders()\n >>> h.parse_line(\"Content-Type: text/html\")\n >>> h.get('content-type')\n 'text/html'\n+ >>> h.parse_line(\"Content-Length: 42\\r\\n\")\n+ >>> h.get('content-type')\n+ 'text/html'\n+\n+ .. versionchanged:: 6.5\n+ Now supports lines with or without the trailing CRLF, making it possible\n+ to pass lines from AsyncHTTPClient's header_callback directly to this method.\n+\n+ .. deprecated:: 6.5\n+ In Tornado 7.0, certain deprecated features of HTTP will become errors.\n+ Specifically, line folding and the use of LF (with CR) as a line separator\n+ will be removed.\n \"\"\"\n+ if m := re.search(r\"\\r?\\n$\", line):\n+ # RFC 9112 section 2.2: a recipient MAY recognize a single LF as a line\n+ # terminator and ignore any preceding CR.\n+ # TODO(7.0): Remove this support for LF-only line endings.\n+ line = line[: m.start()]\n+ if not line:\n+ # Empty line, or the final CRLF of a header block.\n+ return\n if line[0].isspace():\n # continuation of a multi-line header\n+ # TODO(7.0): Remove support for line folding.\n if self._last_key is None:\n raise HTTPInputError(\"first header line cannot start with whitespace\")\n- new_part = \" \" + line.lstrip(HTTP_WHITESPACE)\n+ new_part = \" \" + line.strip(HTTP_WHITESPACE)\n self._as_list[self._last_key][-1] += new_part\n self._dict[self._last_key] += new_part\n else:\n@@ -243,13 +264,16 @@ class HTTPHeaders(StrMutableMapping):\n \n \"\"\"\n h = cls()\n- # RFC 7230 section 3.5: a recipient MAY recognize a single LF as a line\n- # terminator and ignore any preceding CR.\n- for line in headers.split(\"\\n\"):\n- if line.endswith(\"\\r\"):\n- line = line[:-1]\n- if line:\n- h.parse_line(line)\n+\n+ start = 0\n+ while True:\n+ lf = headers.find(\"\\n\", start)\n+ if lf == -1:\n+ h.parse_line(headers[start:])\n+ break\n+ line = headers[start : lf + 1]\n+ start = lf + 1\n+ h.parse_line(line)\n return h\n \n # MutableMapping abstract method implementations.\n", "test_patch": "diff --git a/tornado/test/httpclient_test.py b/tornado/test/httpclient_test.py\nindex f6e7dbbe..08c809a2 100644\n--- a/tornado/test/httpclient_test.py\n+++ b/tornado/test/httpclient_test.py\n@@ -482,6 +482,23 @@ Transfer-Encoding: chunked\n self.assertRegex(first_line[0], \"HTTP/[0-9]\\\\.[0-9] 200.*\\r\\n\")\n self.assertEqual(chunks, [b\"asdf\", b\"qwer\"])\n \n+ def test_header_callback_to_parse_line(self):\n+ # Make a request with header_callback and feed the headers to HTTPHeaders.parse_line.\n+ # (Instead of HTTPHeaders.parse which is used in normal cases). Ensure that the resulting\n+ # headers are as expected, and in particular do not have trailing whitespace added\n+ # due to the final CRLF line.\n+ headers = HTTPHeaders()\n+\n+ def header_callback(line):\n+ if line.startswith(\"HTTP/\"):\n+ # Ignore the first status line\n+ return\n+ headers.parse_line(line)\n+\n+ self.fetch(\"/hello\", header_callback=header_callback)\n+ for k, v in headers.get_all():\n+ self.assertTrue(v == v.strip(), (k, v))\n+\n @gen_test\n def test_configure_defaults(self):\n defaults = dict(user_agent=\"TestDefaultUserAgent\", allow_ipv6=False)\n", "FAIL_TO_PASS": ["tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_callback_to_parse_line"]}, {"instance_id": "tornadoweb__tornado-3488", "base_commit": "1a8c15283af6bfc5b5944a3f2c6df4ff067e56a7", "gold_patch": "diff --git a/tornado/httputil.py b/tornado/httputil.py\nindex 0f443cdd..5d05cacb 100644\n--- a/tornado/httputil.py\n+++ b/tornado/httputil.py\n@@ -248,7 +248,7 @@ class HTTPHeaders(StrMutableMapping):\n if not line:\n # Empty line, or the final CRLF of a header block.\n return\n- if line[0].isspace():\n+ if line[0] in HTTP_WHITESPACE:\n # continuation of a multi-line header\n # TODO(7.0): Remove support for line folding.\n if self._last_key is None:\n", "test_patch": "diff --git a/tornado/test/httputil_test.py b/tornado/test/httputil_test.py\nindex 53ae4607..221c1dcb 100644\n--- a/tornado/test/httputil_test.py\n+++ b/tornado/test/httputil_test.py\n@@ -287,13 +287,22 @@ Foo: even\n [(\"Asdf\", \"qwer zxcv\"), (\"Foo\", \"bar baz\"), (\"Foo\", \"even more lines\")],\n )\n \n- def test_malformed_continuation(self):\n+ def test_continuation(self):\n+ data = \"Foo: bar\\r\\n\\tasdf\"\n+ headers = HTTPHeaders.parse(data)\n+ self.assertEqual(headers[\"Foo\"], \"bar asdf\")\n+\n # If the first line starts with whitespace, it's a\n # continuation line with nothing to continue, so reject it\n # (with a proper error).\n data = \" Foo: bar\"\n self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n \n+ # \\f (formfeed) is whitespace according to str.isspace, but\n+ # not according to the HTTP spec.\n+ data = \"Foo: bar\\r\\n\\fasdf\"\n+ self.assertRaises(HTTPInputError, HTTPHeaders.parse, data)\n+\n def test_unicode_newlines(self):\n # Ensure that only \\r\\n is recognized as a header separator, and not\n # the other newline-like unicode characters.\n", "FAIL_TO_PASS": ["tornado/test/httputil_test.py::HTTPHeadersTest::test_continuation"]}], "all_FAIL_TO_PASS": ["tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_callback_to_parse_line", "tornado/test/httputil_test.py::HTTPHeadersTest::test_continuation"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pycqa__pyflakes-619_x2", "level": 2, "source": "swerebenchv2", "repo": "PyCQA/pyflakes", "image": "swerebenchv2/pycqa-pyflakes:619-40e6dc2", "base_commit": "40e6dc23a8fc48f814e0c81fdcd936321ab9c023", "num_bugs": 2, "bugs": [{"instance_id": "pycqa__pyflakes-619", "base_commit": "40e6dc23a8fc48f814e0c81fdcd936321ab9c023", "gold_patch": "diff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex 01bcf50..48d3841 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -548,6 +548,10 @@ class Annotation(Binding):\n annotation.\n \"\"\"\n \n+ def redefines(self, other):\n+ \"\"\"An Annotation doesn't define any name, so it cannot redefine one.\"\"\"\n+ return False\n+\n \n class FunctionDefinition(Definition):\n pass\ndiff --git a/tox.ini b/tox.ini\nindex 37f2b86..c88831a 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -8,7 +8,7 @@ deps = flake8==3.6.0\n setenv = PYFLAKES_ERROR_UNKNOWN=1\n commands =\n python --version --version\n- python -m unittest discover pyflakes\n+ python -m unittest discover pyflakes {posargs}\n flake8 pyflakes setup.py\n \n [flake8]\n", "test_patch": "diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py\nindex 9e7ca14..f131034 100644\n--- a/pyflakes/test/test_type_annotations.py\n+++ b/pyflakes/test/test_type_annotations.py\n@@ -283,6 +283,14 @@ class TestTypeAnnotations(TestCase):\n a: 'a: \"A\"'\n ''', m.ForwardAnnotationSyntaxError)\n \n+ @skipIf(version_info < (3, 6), 'new in Python 3.6')\n+ def test_annotating_an_import(self):\n+ self.flakes('''\n+ from a import b, c\n+ b: c\n+ print(b)\n+ ''')\n+\n @skipIf(version_info < (3, 6), 'new in Python 3.6')\n def test_unused_annotation(self):\n # Unused annotations are fine in module and class scope\n", "FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotating_an_import"]}, {"instance_id": "pycqa__pyflakes-632", "base_commit": "95fe313ba5ca384041472cd171ea60fad910c207", "gold_patch": "diff --git a/README.rst b/README.rst\nindex c456d25..47ea7ed 100644\n--- a/README.rst\n+++ b/README.rst\n@@ -39,8 +39,7 @@ Design Principles\n Pyflakes makes a simple promise: it will never complain about style,\n and it will try very, very hard to never emit false positives.\n \n-Pyflakes is also faster than Pylint_\n-or Pychecker_. This is\n+Pyflakes is also faster than Pylint_. This is\n largely because Pyflakes only examines the syntax tree of each file\n individually. As a consequence, Pyflakes is more limited in the\n types of things it can check.\n@@ -79,7 +78,6 @@ All changes should include tests and pass flake8_.\n .. _Pylint: https://www.pylint.org/\n .. _flake8: https://pypi.org/project/flake8/\n .. _`PEP 8`: https://www.python.org/dev/peps/pep-0008/\n-.. _Pychecker: http://pychecker.sourceforge.net/\n .. _`rebase your changes`: https://git-scm.com/book/en/v2/Git-Branching-Rebasing\n .. _`GitHub pull request`: https://github.com/PyCQA/pyflakes/pulls\n \ndiff --git a/pyflakes/checker.py b/pyflakes/checker.py\nindex 48d3841..45c7a4a 100644\n--- a/pyflakes/checker.py\n+++ b/pyflakes/checker.py\n@@ -275,7 +275,8 @@ def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()):\n yield field\n elif isinstance(field, list):\n for item in field:\n- yield item\n+ if isinstance(item, ast.AST):\n+ yield item\n \n \n def convert_to_value(item):\n@@ -691,6 +692,8 @@ def getNodeName(node):\n return node.id\n if hasattr(node, 'name'): # an ExceptHandler node\n return node.name\n+ if hasattr(node, 'rest'): # a MatchMapping node\n+ return node.rest\n \n \n TYPING_MODULES = frozenset(('typing', 'typing_extensions'))\n@@ -717,6 +720,16 @@ def _is_typing_helper(node, is_name_match_fn, scope_stack):\n \n return False\n \n+ def _module_scope_is_typing(name):\n+ for scope in reversed(scope_stack):\n+ if name in scope:\n+ return (\n+ isinstance(scope[name], Importation) and\n+ scope[name].fullName in TYPING_MODULES\n+ )\n+\n+ return False\n+\n return (\n (\n isinstance(node, ast.Name) and\n@@ -724,7 +737,7 @@ def _is_typing_helper(node, is_name_match_fn, scope_stack):\n ) or (\n isinstance(node, ast.Attribute) and\n isinstance(node.value, ast.Name) and\n- node.value.id in TYPING_MODULES and\n+ _module_scope_is_typing(node.value.id) and\n is_name_match_fn(node.attr)\n )\n )\n@@ -868,7 +881,6 @@ class Checker(object):\n \n nodeDepth = 0\n offset = None\n- traceTree = False\n _in_annotation = AnnotationState.NONE\n _in_deferred = False\n \n@@ -1393,8 +1405,6 @@ class Checker(object):\n if self.offset and getattr(node, 'lineno', None) is not None:\n node.lineno += self.offset[0]\n node.col_offset += self.offset[1]\n- if self.traceTree:\n- print(' ' * self.nodeDepth + node.__class__.__name__)\n if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or\n self.isDocstring(node)):\n self.futuresAllowed = False\n@@ -1406,8 +1416,6 @@ class Checker(object):\n handler(node)\n finally:\n self.nodeDepth -= 1\n- if self.traceTree:\n- print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)\n \n _getDoctestExamples = doctest.DocTestParser().get_examples\n \n@@ -2383,3 +2391,12 @@ class Checker(object):\n left = right\n \n self.handleChildren(node)\n+\n+ MATCH = MATCH_CASE = MATCHCLASS = MATCHOR = MATCHSEQUENCE = handleChildren\n+ MATCHSINGLETON = MATCHVALUE = handleChildren\n+\n+ def _match_target(self, node):\n+ self.handleNodeStore(node)\n+ self.handleChildren(node)\n+\n+ MATCHAS = MATCHMAPPING = MATCHSTAR = _match_target\ndiff --git a/tox.ini b/tox.ini\nindex c88831a..0396f02 100644\n--- a/tox.ini\n+++ b/tox.ini\n@@ -1,7 +1,7 @@\n [tox]\n skip_missing_interpreters = True\n envlist =\n- py27,py34,py35,py36,py37,py38,pypy,pypy3\n+ py27,py35,py36,py37,py38,py39,py310,pypy,pypy3\n \n [testenv]\n deps = flake8==3.6.0\n", "test_patch": "diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml\nindex 39ba139..8c078ae 100644\n--- a/.github/workflows/test.yml\n+++ b/.github/workflows/test.yml\n@@ -8,7 +8,7 @@ jobs:\n strategy:\n fail-fast: false\n matrix:\n- python-version: [\"2.7\", \"3.5\", \"3.6\", \"3.7\", \"3.8\", \"3.9\", \"pypy2\", \"pypy3\"]\n+ python-version: [\"2.7\", \"3.5\", \"3.6\", \"3.7\", \"3.8\", \"3.9\", \"3.10-dev\", \"pypy2\", \"pypy3\"]\n os: [ubuntu-latest]\n # Include py2 + minimum py3 + maximum py3 + pypy + pypy3 on Windows\n include:\ndiff --git a/pyflakes/test/test_api.py b/pyflakes/test/test_api.py\nindex d379b3b..2c1cf19 100644\n--- a/pyflakes/test/test_api.py\n+++ b/pyflakes/test/test_api.py\n@@ -441,7 +441,7 @@ def baz():\n evaluate(source)\n except SyntaxError:\n e = sys.exc_info()[1]\n- if not PYPY:\n+ if not PYPY and sys.version_info < (3, 10):\n self.assertTrue(e.text.count('\\n') > 1)\n else:\n self.fail()\n@@ -449,10 +449,17 @@ def baz():\n with self.makeTempFile(source) as sourcePath:\n if PYPY:\n message = 'end of file (EOF) while scanning triple-quoted string literal'\n+ elif sys.version_info >= (3, 10):\n+ message = 'unterminated triple-quoted string literal (detected at line 8)' # noqa: E501\n else:\n message = 'invalid syntax'\n \n- column = 8 if sys.version_info >= (3, 8) else 11\n+ if sys.version_info >= (3, 10):\n+ column = 12\n+ elif sys.version_info >= (3, 8):\n+ column = 8\n+ else:\n+ column = 11\n self.assertHasErrors(\n sourcePath,\n [\"\"\"\\\n@@ -468,21 +475,25 @@ def baz():\n \"\"\"\n with self.makeTempFile(\"def foo(\") as sourcePath:\n if PYPY:\n- result = \"\"\"\\\n-%s:1:7: parenthesis is never closed\n-def foo(\n- ^\n-\"\"\" % (sourcePath,)\n+ msg = 'parenthesis is never closed'\n+ elif sys.version_info >= (3, 10):\n+ msg = \"'(' was never closed\"\n else:\n- result = \"\"\"\\\n-%s:1:9: unexpected EOF while parsing\n-def foo(\n- ^\n-\"\"\" % (sourcePath,)\n+ msg = 'unexpected EOF while parsing'\n \n- self.assertHasErrors(\n- sourcePath,\n- [result])\n+ if PYPY:\n+ column = 7\n+ elif sys.version_info >= (3, 10):\n+ column = 8\n+ else:\n+ column = 9\n+\n+ spaces = ' ' * (column - 1)\n+ expected = '{}:1:{}: {}\\ndef foo(\\n{}^\\n'.format(\n+ sourcePath, column, msg, spaces\n+ )\n+\n+ self.assertHasErrors(sourcePath, [expected])\n \n def test_eofSyntaxErrorWithTab(self):\n \"\"\"\n@@ -515,6 +526,8 @@ def foo(bar=baz, bax):\n if ERROR_HAS_LAST_LINE:\n if PYPY:\n column = 7\n+ elif sys.version_info >= (3, 10):\n+ column = 18\n elif sys.version_info >= (3, 9):\n column = 21\n elif sys.version_info >= (3, 8):\ndiff --git a/pyflakes/test/test_match.py b/pyflakes/test/test_match.py\nnew file mode 100644\nindex 0000000..89826e3\n--- /dev/null\n+++ b/pyflakes/test/test_match.py\n@@ -0,0 +1,83 @@\n+from sys import version_info\n+\n+from pyflakes.test.harness import TestCase, skipIf\n+\n+\n+@skipIf(version_info < (3, 10), \"Python >= 3.10 only\")\n+class TestMatch(TestCase):\n+ def test_match_bindings(self):\n+ self.flakes('''\n+ def f():\n+ x = 1\n+ match x:\n+ case 1 as y:\n+ print(f'matched as {y}')\n+ ''')\n+ self.flakes('''\n+ def f():\n+ x = [1, 2, 3]\n+ match x:\n+ case [1, y, 3]:\n+ print(f'matched {y}')\n+ ''')\n+ self.flakes('''\n+ def f():\n+ x = {'foo': 1}\n+ match x:\n+ case {'foo': y}:\n+ print(f'matched {y}')\n+ ''')\n+\n+ def test_match_pattern_matched_class(self):\n+ self.flakes('''\n+ from a import B\n+\n+ match 1:\n+ case B(x=1) as y:\n+ print(f'matched {y}')\n+ ''')\n+ self.flakes('''\n+ from a import B\n+\n+ match 1:\n+ case B(a, x=z) as y:\n+ print(f'matched {y} {a} {z}')\n+ ''')\n+\n+ def test_match_placeholder(self):\n+ self.flakes('''\n+ def f():\n+ match 1:\n+ case _:\n+ print('catchall!')\n+ ''')\n+\n+ def test_match_singleton(self):\n+ self.flakes('''\n+ match 1:\n+ case True:\n+ print('true')\n+ ''')\n+\n+ def test_match_or_pattern(self):\n+ self.flakes('''\n+ match 1:\n+ case 1 | 2:\n+ print('one or two')\n+ ''')\n+\n+ def test_match_star(self):\n+ self.flakes('''\n+ x = [1, 2, 3]\n+ match x:\n+ case [1, *y]:\n+ print(f'captured: {y}')\n+ ''')\n+\n+ def test_match_double_star(self):\n+ self.flakes('''\n+ x = {'foo': 'bar', 'baz': 'womp'}\n+ match x:\n+ case {'foo': k1, **rest}:\n+ print(f'{k1=} {rest=}')\n+ ''')\ndiff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py\nindex f131034..f3b6c24 100644\n--- a/pyflakes/test/test_type_annotations.py\n+++ b/pyflakes/test/test_type_annotations.py\n@@ -121,6 +121,23 @@ class TestTypeAnnotations(TestCase):\n def f(self, x): return x\n \"\"\")\n \n+ def test_aliased_import(self):\n+ \"\"\"Detect when typing is imported as another name\"\"\"\n+ self.flakes(\"\"\"\n+ import typing as t\n+\n+ @t.overload\n+ def f(s): # type: (None) -> None\n+ pass\n+\n+ @t.overload\n+ def f(s): # type: (int) -> int\n+ pass\n+\n+ def f(s):\n+ return s\n+ \"\"\")\n+\n def test_not_a_typing_overload(self):\n \"\"\"regression test for @typing.overload detection bug in 2.1.0\"\"\"\n self.flakes(\"\"\"\n@@ -531,7 +548,7 @@ class TestTypeAnnotations(TestCase):\n def test_type_cast_literal_str_to_str(self):\n # Checks that our handling of quoted type annotations in the first\n # argument to `cast` doesn't cause issues when (only) the _second_\n- # argument is a literal str which looks a bit like a type annoation.\n+ # argument is a literal str which looks a bit like a type annotation.\n self.flakes(\"\"\"\n from typing import cast\n \n", "FAIL_TO_PASS": ["pyflakes/test/test_match.py::TestMatch::test_match_bindings", "pyflakes/test/test_match.py::TestMatch::test_match_double_star", "pyflakes/test/test_match.py::TestMatch::test_match_pattern_matched_class", "pyflakes/test/test_match.py::TestMatch::test_match_star", "pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_aliased_import"]}], "all_FAIL_TO_PASS": ["pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotating_an_import", "pyflakes/test/test_match.py::TestMatch::test_match_bindings", "pyflakes/test/test_match.py::TestMatch::test_match_double_star", "pyflakes/test/test_match.py::TestMatch::test_match_pattern_matched_class", "pyflakes/test/test_match.py::TestMatch::test_match_star", "pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_aliased_import"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "googlecloudplatform__cloud-sql-python-connector-475_x2", "level": 2, "source": "swerebenchv2", "repo": "GoogleCloudPlatform/cloud-sql-python-connector", "image": "swerebenchv2/googlecloudplatform-cloud-sql-python-connector:475-528852a", "base_commit": "528852a6ec3ecf7a55749697c1245624cc226208", "num_bugs": 2, "bugs": [{"instance_id": "googlecloudplatform__cloud-sql-python-connector-475", "base_commit": "528852a6ec3ecf7a55749697c1245624cc226208", "gold_patch": "diff --git a/google/cloud/sql/connector/connector.py b/google/cloud/sql/connector/connector.py\nindex ed4afb1..e4ff716 100755\n--- a/google/cloud/sql/connector/connector.py\n+++ b/google/cloud/sql/connector/connector.py\n@@ -76,6 +76,12 @@ class Connector:\n :param loop\n Event loop to run asyncio tasks, if not specified, defaults to\n creating new event loop on background thread.\n+\n+ :type sqladmin_api_endpoint: str\n+ :param sqladmin_api_endpoint:\n+ Base URL to use when calling the Cloud SQL Admin API endpoint.\n+ Defaults to \"https://sqladmin.googleapis.com\", this argument should\n+ only be used in development.\n \"\"\"\n \n def __init__(\n@@ -86,6 +92,7 @@ class Connector:\n credentials: Optional[Credentials] = None,\n loop: asyncio.AbstractEventLoop = None,\n quota_project: Optional[str] = None,\n+ sqladmin_api_endpoint: str = \"https://sqladmin.googleapis.com\",\n ) -> None:\n # if event loop is given, use for background tasks\n if loop:\n@@ -108,6 +115,7 @@ class Connector:\n self._enable_iam_auth = enable_iam_auth\n self._ip_type = ip_type\n self._quota_project = quota_project\n+ self._sqladmin_api_endpoint = sqladmin_api_endpoint\n self._credentials = credentials\n \n def connect(\n@@ -204,6 +212,7 @@ class Connector:\n self._credentials,\n enable_iam_auth,\n self._quota_project,\n+ self._sqladmin_api_endpoint,\n )\n self._instances[instance_connection_string] = instance\n \ndiff --git a/google/cloud/sql/connector/instance.py b/google/cloud/sql/connector/instance.py\nindex 0f55fbf..31f5eed 100644\n--- a/google/cloud/sql/connector/instance.py\n+++ b/google/cloud/sql/connector/instance.py\n@@ -195,6 +195,12 @@ class Instance:\n The Project ID for an existing Google Cloud project. The project specified\n is used for quota and billing purposes. If not specified, defaults to\n project sourced from environment.\n+\n+ :type sqladmin_api_endpoint: str\n+ :param sqladmin_api_endpoint:\n+ Base URL to use when calling the Cloud SQL Admin API endpoint.\n+ Defaults to \"https://sqladmin.googleapis.com\", this argument should\n+ only be used in development.\n \"\"\"\n \n # asyncio.AbstractEventLoop is used because the default loop,\n@@ -227,6 +233,7 @@ class Instance:\n \n _instance_connection_string: str\n _user_agent_string: str\n+ _sqladmin_api_endpoint: str\n _instance: str\n _project: str\n _region: str\n@@ -245,6 +252,7 @@ class Instance:\n credentials: Optional[Credentials] = None,\n enable_iam_auth: bool = False,\n quota_project: str = None,\n+ sqladmin_api_endpoint: str = \"https://sqladmin.googleapis.com\",\n ) -> None:\n # Validate connection string\n connection_string_split = instance_connection_string.split(\":\")\n@@ -265,6 +273,7 @@ class Instance:\n \n self._user_agent_string = f\"{APPLICATION_NAME}/{version}+{driver_name}\"\n self._quota_project = quota_project\n+ self._sqladmin_api_endpoint = sqladmin_api_endpoint\n self._loop = loop\n self._keys = keys\n # validate credentials type\n@@ -339,6 +348,7 @@ class Instance:\n metadata_task = self._loop.create_task(\n _get_metadata(\n self._client_session,\n+ self._sqladmin_api_endpoint,\n self._credentials,\n self._project,\n self._instance,\n@@ -348,6 +358,7 @@ class Instance:\n ephemeral_task = self._loop.create_task(\n _get_ephemeral(\n self._client_session,\n+ self._sqladmin_api_endpoint,\n self._credentials,\n self._project,\n self._instance,\ndiff --git a/google/cloud/sql/connector/refresh_utils.py b/google/cloud/sql/connector/refresh_utils.py\nindex 2b55e2e..6f4b237 100644\n--- a/google/cloud/sql/connector/refresh_utils.py\n+++ b/google/cloud/sql/connector/refresh_utils.py\n@@ -42,6 +42,7 @@ _iam_auth_refresh_buffer: int = 55 # seconds\n \n async def _get_metadata(\n client_session: aiohttp.ClientSession,\n+ sqladmin_api_endpoint: str,\n credentials: Credentials,\n project: str,\n instance: str,\n@@ -50,6 +51,10 @@ async def _get_metadata(\n and returns a dictionary containing the IP addresses and certificate\n authority of the Cloud SQL Instance.\n \n+ :type sqladmin_api_endpoint: str\n+ :param sqladmin_api_endpoint:\n+ Base URL to use when calling the Cloud SQL Admin API endpoint.\n+\n :type credentials: google.auth.credentials.Credentials\n :param credentials:\n A credentials object created from the google-auth Python library.\n@@ -89,8 +94,8 @@ async def _get_metadata(\n \"Authorization\": \"Bearer {}\".format(credentials.token),\n }\n \n- url = \"https://sqladmin.googleapis.com/sql/{}/projects/{}/instances/{}/connectSettings\".format(\n- _sql_api_version, project, instance\n+ url = \"{}/sql/{}/projects/{}/instances/{}/connectSettings\".format(\n+ sqladmin_api_endpoint, _sql_api_version, project, instance\n )\n \n logger.debug(f\"['{instance}']: Requesting metadata\")\n@@ -108,6 +113,7 @@ async def _get_metadata(\n \n async def _get_ephemeral(\n client_session: aiohttp.ClientSession,\n+ sqladmin_api_endpoint: str,\n credentials: Credentials,\n project: str,\n instance: str,\n@@ -116,6 +122,10 @@ async def _get_ephemeral(\n ) -> str:\n \"\"\"Asynchronously requests an ephemeral certificate from the Cloud SQL Instance.\n \n+ :type sqladmin_api_endpoint: str\n+ :param sqladmin_api_endpoint:\n+ Base URL to use when calling the Cloud SQL Admin API endpoint.\n+\n :type credentials: google.auth.credentials.Credentials\n :param credentials: A credentials object\n created from the google-auth library. Must be\n@@ -164,8 +174,8 @@ async def _get_ephemeral(\n \"Authorization\": f\"Bearer {credentials.token}\",\n }\n \n- url = \"https://sqladmin.googleapis.com/sql/{}/projects/{}/instances/{}:generateEphemeralCert\".format(\n- _sql_api_version, project, instance\n+ url = \"{}/sql/{}/projects/{}/instances/{}:generateEphemeralCert\".format(\n+ sqladmin_api_endpoint, _sql_api_version, project, instance\n )\n \n data = {\"public_key\": pub_key}\n", "test_patch": "diff --git a/tests/unit/test_refresh_utils.py b/tests/unit/test_refresh_utils.py\nindex e05bce6..010c059 100644\n--- a/tests/unit/test_refresh_utils.py\n+++ b/tests/unit/test_refresh_utils.py\n@@ -66,7 +66,12 @@ async def test_get_ephemeral(\n )\n async with aiohttp.ClientSession() as client_session:\n result: Any = await _get_ephemeral(\n- client_session, credentials, project, instance, pub_key\n+ client_session,\n+ \"https://sqladmin.googleapis.com\",\n+ credentials,\n+ project,\n+ instance,\n+ pub_key,\n )\n result = result.strip() # remove any trailing whitespace\n result = result.split(\"\\n\")\n@@ -93,6 +98,7 @@ async def test_get_ephemeral_TypeError(credentials: Credentials) -> None:\n with pytest.raises(TypeError):\n await _get_ephemeral(\n client_session=client_session,\n+ sqladmin_api_endpoint=\"https://sqladmin.googleapis.com\",\n credentials=\"bad-credentials\",\n project=project,\n instance=instance,\n@@ -102,6 +108,7 @@ async def test_get_ephemeral_TypeError(credentials: Credentials) -> None:\n with pytest.raises(TypeError):\n await _get_ephemeral(\n client_session=client_session,\n+ sqladmin_api_endpoint=\"https://sqladmin.googleapis.com\",\n credentials=credentials,\n project=12345,\n instance=instance,\n@@ -111,6 +118,7 @@ async def test_get_ephemeral_TypeError(credentials: Credentials) -> None:\n with pytest.raises(TypeError):\n await _get_ephemeral(\n client_session=client_session,\n+ sqladmin_api_endpoint=\"https://sqladmin.googleapis.com\",\n credentials=credentials,\n project=project,\n instance=12345,\n@@ -120,6 +128,7 @@ async def test_get_ephemeral_TypeError(credentials: Credentials) -> None:\n with pytest.raises(TypeError):\n await _get_ephemeral(\n client_session=client_session,\n+ sqladmin_api_endpoint=\"https://sqladmin.googleapis.com\",\n credentials=credentials,\n project=project,\n instance=instance,\n@@ -147,7 +156,13 @@ async def test_get_metadata(\n )\n \n async with aiohttp.ClientSession() as client_session:\n- result = await _get_metadata(client_session, credentials, project, instance)\n+ result = await _get_metadata(\n+ client_session,\n+ \"https://sqladmin.googleapis.com\",\n+ credentials,\n+ project,\n+ instance,\n+ )\n \n assert result[\"ip_addresses\"] is not None and isinstance(\n result[\"server_ca_cert\"], str\n@@ -169,6 +184,7 @@ async def test_get_metadata_TypeError(credentials: Credentials) -> None:\n with pytest.raises(TypeError):\n await _get_metadata(\n client_session=client_session,\n+ sqladmin_api_endpoint=\"https://sqladmin.googleapis.com\",\n credentials=\"bad-credentials\",\n project=project,\n instance=instance,\n@@ -177,6 +193,7 @@ async def test_get_metadata_TypeError(credentials: Credentials) -> None:\n with pytest.raises(TypeError):\n await _get_metadata(\n client_session=client_session,\n+ sqladmin_api_endpoint=\"https://sqladmin.googleapis.com\",\n credentials=credentials,\n project=12345,\n instance=instance,\n@@ -185,6 +202,7 @@ async def test_get_metadata_TypeError(credentials: Credentials) -> None:\n with pytest.raises(TypeError):\n await _get_metadata(\n client_session=client_session,\n+ sqladmin_api_endpoint=\"https://sqladmin.googleapis.com\",\n credentials=credentials,\n project=project,\n instance=12345,\n", "FAIL_TO_PASS": ["tests/unit/test_refresh_utils.py::test_get_ephemeral", "tests/unit/test_refresh_utils.py::test_get_metadata"]}, {"instance_id": "googlecloudplatform__cloud-sql-python-connector-476", "base_commit": "c4788c2ee9650a1282bc553f2c27ae78bebb20c2", "gold_patch": "diff --git a/google/cloud/sql/connector/instance.py b/google/cloud/sql/connector/instance.py\nindex 31f5eed..5bb420e 100644\n--- a/google/cloud/sql/connector/instance.py\n+++ b/google/cloud/sql/connector/instance.py\n@@ -100,6 +100,15 @@ class ExpiredInstanceMetadata(Exception):\n super(ExpiredInstanceMetadata, self).__init__(self, *args)\n \n \n+class AutoIAMAuthNotSupported(Exception):\n+ \"\"\"\n+ Exception to be raised when Automatic IAM Authentication is not\n+ supported with database engine version.\n+ \"\"\"\n+\n+ pass\n+\n+\n class InstanceMetadata:\n ip_addrs: Dict[str, Any]\n context: ssl.SSLContext\n@@ -115,7 +124,6 @@ class InstanceMetadata:\n enable_iam_auth: bool,\n ) -> None:\n self.ip_addrs = ip_addrs\n-\n self.context = ssl.SSLContext(ssl.PROTOCOL_TLS)\n \n # verify OpenSSL version supports TLSv1.3\n@@ -366,10 +374,21 @@ class Instance:\n self._enable_iam_auth,\n )\n )\n-\n- metadata, ephemeral_cert = await asyncio.gather(\n- metadata_task, ephemeral_task\n- )\n+ try:\n+ metadata = await metadata_task\n+ # check if automatic IAM database authn is supported for database engine\n+ if self._enable_iam_auth and not metadata[\n+ \"database_version\"\n+ ].startswith(\"POSTGRES\"):\n+ raise AutoIAMAuthNotSupported(\n+ f\"'{metadata['database_version']}' does not support automatic IAM authentication. It is only supported with Cloud SQL Postgres instances.\"\n+ )\n+ except Exception:\n+ # cancel ephemeral cert task if exception occurs before it is awaited\n+ ephemeral_task.cancel()\n+ raise\n+\n+ ephemeral_cert = await ephemeral_task\n \n x509 = load_pem_x509_certificate(\n ephemeral_cert.encode(\"UTF-8\"), default_backend()\ndiff --git a/google/cloud/sql/connector/refresh_utils.py b/google/cloud/sql/connector/refresh_utils.py\nindex d009621..abb70fc 100644\n--- a/google/cloud/sql/connector/refresh_utils.py\n+++ b/google/cloud/sql/connector/refresh_utils.py\n@@ -105,6 +105,7 @@ async def _get_metadata(\n metadata = {\n \"ip_addresses\": {ip[\"type\"]: ip[\"ipAddress\"] for ip in ret_dict[\"ipAddresses\"]},\n \"server_ca_cert\": ret_dict[\"serverCaCert\"][\"cert\"],\n+ \"database_version\": ret_dict[\"databaseVersion\"],\n }\n \n return metadata\n", "test_patch": "diff --git a/tests/conftest.py b/tests/conftest.py\nindex 11813b8..b2ca048 100644\n--- a/tests/conftest.py\n+++ b/tests/conftest.py\n@@ -162,20 +162,23 @@ async def instance(\n # mock Cloud SQL Admin API calls\n with aioresponses() as mocked:\n mocked.get(\n- \"https://sqladmin.googleapis.com/sql/v1beta4/projects/my-project/instances/my-instance/connectSettings\",\n+ f\"https://sqladmin.googleapis.com/sql/v1beta4/projects/{mock_instance.project}/instances/{mock_instance.name}/connectSettings\",\n status=200,\n body=mock_instance.connect_settings(),\n repeat=True,\n )\n mocked.post(\n- \"https://sqladmin.googleapis.com/sql/v1beta4/projects/my-project/instances/my-instance:generateEphemeralCert\",\n+ f\"https://sqladmin.googleapis.com/sql/v1beta4/projects/{mock_instance.project}/instances/{mock_instance.name}:generateEphemeralCert\",\n status=200,\n body=mock_instance.generate_ephemeral(client_key),\n repeat=True,\n )\n \n instance = Instance(\n- \"my-project:my-region:my-instance\", \"pg8000\", keys, event_loop\n+ f\"{mock_instance.project}:{mock_instance.region}:{mock_instance.name}\",\n+ \"pg8000\",\n+ keys,\n+ event_loop,\n )\n \n yield instance\ndiff --git a/tests/system/test_connector_object.py b/tests/system/test_connector_object.py\nindex 909aa9c..91ab10d 100644\n--- a/tests/system/test_connector_object.py\n+++ b/tests/system/test_connector_object.py\n@@ -15,11 +15,13 @@ limitations under the License.\n \"\"\"\n import asyncio\n import os\n+import pytest\n import pymysql\n import sqlalchemy\n import logging\n import google.auth\n from google.cloud.sql.connector import Connector\n+from google.cloud.sql.connector.instance import AutoIAMAuthNotSupported\n import datetime\n import concurrent.futures\n from threading import Thread\n@@ -141,3 +143,34 @@ def test_connector_with_custom_loop() -> None:\n assert result[0] == 1\n # assert that Connector does not start its own thread\n assert connector._thread is None\n+\n+\n+def test_connector_mysql_iam_auth_error() -> None:\n+ \"\"\"\n+ Test that connecting with enable_iam_auth set to True\n+ for MySQL raises exception.\n+ \"\"\"\n+ with pytest.raises(AutoIAMAuthNotSupported):\n+ with Connector(enable_iam_auth=True) as connector:\n+ connector.connect(\n+ os.environ[\"MYSQL_CONNECTION_NAME\"],\n+ \"pymysql\",\n+ user=\"my-user\",\n+ db=\"my-db\",\n+ )\n+\n+\n+def test_connector_sqlserver_iam_auth_error() -> None:\n+ \"\"\"\n+ Test that connecting with enable_iam_auth set to True\n+ for SQL Server raises exception.\n+ \"\"\"\n+ with pytest.raises(AutoIAMAuthNotSupported):\n+ with Connector(enable_iam_auth=True) as connector:\n+ connector.connect(\n+ os.environ[\"SQLSERVER_CONNECTION_NAME\"],\n+ \"pytds\",\n+ user=\"my-user\",\n+ password=\"my-pass\",\n+ db=\"my-db\",\n+ )\ndiff --git a/tests/unit/mocks.py b/tests/unit/mocks.py\nindex 9e53e50..84b66fa 100644\n--- a/tests/unit/mocks.py\n+++ b/tests/unit/mocks.py\n@@ -178,11 +178,17 @@ async def create_ssl_context() -> ssl.SSLContext:\n \n \n class FakeCSQLInstance:\n- def __init__(self, project: str, region: str, name: str) -> None:\n+ def __init__(\n+ self,\n+ project: str = \"my-project\",\n+ region: str = \"my-region\",\n+ name: str = \"my-instance\",\n+ db_version: str = \"POSTGRES_14\",\n+ ) -> None:\n self.project = project\n self.region = region\n self.name = name\n- self.db_version = \"POSTGRES_14\" # arbitrary value\n+ self.db_version = db_version\n self.ip_addrs = {\"PRIMARY\": \"0.0.0.0\", \"PRIVATE\": \"1.1.1.1\"}\n self.backend_type = \"SECOND_GEN\"\n \ndiff --git a/tests/unit/test_instance.py b/tests/unit/test_instance.py\nindex 63cb6b0..fb31c18 100644\n--- a/tests/unit/test_instance.py\n+++ b/tests/unit/test_instance.py\n@@ -20,6 +20,7 @@ import datetime\n from google.cloud.sql.connector.rate_limiter import AsyncRateLimiter\n from google.auth.credentials import Credentials\n from google.cloud.sql.connector.instance import (\n+ AutoIAMAuthNotSupported,\n IPTypes,\n Instance,\n CredentialsTypeError,\n@@ -402,3 +403,21 @@ async def test_ClientResponseError(\n )\n finally:\n await instance.close()\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\n+ \"mock_instance\",\n+ [\n+ mocks.FakeCSQLInstance(db_version=\"SQLSERVER_2019_STANDARD\"),\n+ mocks.FakeCSQLInstance(db_version=\"MYSQL_8_0\"),\n+ ],\n+)\n+async def test_AutoIAMAuthNotSupportedError(instance: Instance) -> None:\n+ \"\"\"\n+ Test that AutoIAMAuthNotSupported exception is raised\n+ for SQL Server and MySQL instances.\n+ \"\"\"\n+ instance._enable_iam_auth = True\n+ with pytest.raises(AutoIAMAuthNotSupported):\n+ await instance._current\ndiff --git a/tests/unit/test_refresh_utils.py b/tests/unit/test_refresh_utils.py\nindex 010c059..dd84830 100644\n--- a/tests/unit/test_refresh_utils.py\n+++ b/tests/unit/test_refresh_utils.py\n@@ -164,8 +164,10 @@ async def test_get_metadata(\n instance,\n )\n \n- assert result[\"ip_addresses\"] is not None and isinstance(\n- result[\"server_ca_cert\"], str\n+ assert (\n+ result[\"ip_addresses\"] is not None\n+ and result[\"database_version\"] == \"POSTGRES_14\"\n+ and isinstance(result[\"server_ca_cert\"], str)\n )\n \n \n", "FAIL_TO_PASS": ["tests/unit/test_instance.py::test_Instance_init", "tests/unit/test_instance.py::test_Instance_init_bad_credentials", "tests/unit/test_instance.py::test_schedule_refresh_replaces_result", "tests/unit/test_instance.py::test_schedule_refresh_wont_replace_valid_result_with_invalid", "tests/unit/test_instance.py::test_schedule_refresh_replaces_invalid_result", "tests/unit/test_instance.py::test_force_refresh_cancels_pending_refresh", "tests/unit/test_instance.py::test_auth_init_with_credentials_object", "tests/unit/test_instance.py::test_auth_init_with_default_credentials", "tests/unit/test_instance.py::test_Instance_close", "tests/unit/test_instance.py::test_perform_refresh", "tests/unit/test_instance.py::test_perform_refresh_expiration", "tests/unit/test_instance.py::test_connect_info", "tests/unit/test_instance.py::test_get_preferred_ip", "tests/unit/test_instance.py::test_get_preferred_ip_CloudSQLIPTypeError", "tests/unit/test_instance.py::test_ClientResponseError", "tests/unit/test_instance.py::test_AutoIAMAuthNotSupportedError[mock_instance0]", "tests/unit/test_instance.py::test_AutoIAMAuthNotSupportedError[mock_instance1]", "tests/unit/test_refresh_utils.py::test_get_ephemeral", "tests/unit/test_refresh_utils.py::test_get_ephemeral_TypeError", "tests/unit/test_refresh_utils.py::test_get_metadata", "tests/unit/test_refresh_utils.py::test_get_metadata_TypeError", "tests/unit/test_refresh_utils.py::test_is_valid_with_valid_metadata", "tests/unit/test_refresh_utils.py::test_is_valid_with_expired_metadata"]}], "all_FAIL_TO_PASS": ["tests/unit/test_refresh_utils.py::test_get_ephemeral", "tests/unit/test_refresh_utils.py::test_get_metadata", "tests/unit/test_instance.py::test_Instance_init", "tests/unit/test_instance.py::test_Instance_init_bad_credentials", "tests/unit/test_instance.py::test_schedule_refresh_replaces_result", "tests/unit/test_instance.py::test_schedule_refresh_wont_replace_valid_result_with_invalid", "tests/unit/test_instance.py::test_schedule_refresh_replaces_invalid_result", "tests/unit/test_instance.py::test_force_refresh_cancels_pending_refresh", "tests/unit/test_instance.py::test_auth_init_with_credentials_object", "tests/unit/test_instance.py::test_auth_init_with_default_credentials", "tests/unit/test_instance.py::test_Instance_close", "tests/unit/test_instance.py::test_perform_refresh", "tests/unit/test_instance.py::test_perform_refresh_expiration", "tests/unit/test_instance.py::test_connect_info", "tests/unit/test_instance.py::test_get_preferred_ip", "tests/unit/test_instance.py::test_get_preferred_ip_CloudSQLIPTypeError", "tests/unit/test_instance.py::test_ClientResponseError", "tests/unit/test_instance.py::test_AutoIAMAuthNotSupportedError[mock_instance0]", "tests/unit/test_instance.py::test_AutoIAMAuthNotSupportedError[mock_instance1]", "tests/unit/test_refresh_utils.py::test_get_ephemeral", "tests/unit/test_refresh_utils.py::test_get_ephemeral_TypeError", "tests/unit/test_refresh_utils.py::test_get_metadata", "tests/unit/test_refresh_utils.py::test_get_metadata_TypeError", "tests/unit/test_refresh_utils.py::test_is_valid_with_valid_metadata", "tests/unit/test_refresh_utils.py::test_is_valid_with_expired_metadata"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "qiskit__qiskit-terra-7952_x2", "level": 2, "source": "swerebenchv2", "repo": "Qiskit/qiskit-terra", "image": "swerebenchv2/qiskit-qiskit-terra:7952-5012ee1", "base_commit": "5012ee196495a183ac934cbcc697c2b374ad42cb", "num_bugs": 2, "bugs": [{"instance_id": "qiskit__qiskit-terra-7952", "base_commit": "5012ee196495a183ac934cbcc697c2b374ad42cb", "gold_patch": "diff --git a/qiskit/transpiler/passes/routing/sabre_swap.py b/qiskit/transpiler/passes/routing/sabre_swap.py\nindex 3690c763f..5e44b29e5 100644\n--- a/qiskit/transpiler/passes/routing/sabre_swap.py\n+++ b/qiskit/transpiler/passes/routing/sabre_swap.py\n@@ -18,7 +18,6 @@ from copy import copy, deepcopy\n import numpy as np\n \n from qiskit.circuit.library.standard_gates import SwapGate\n-from qiskit.circuit.quantumregister import Qubit\n from qiskit.transpiler.basepasses import TransformationPass\n from qiskit.transpiler.exceptions import TranspilerError\n from qiskit.transpiler.layout import Layout\n@@ -276,15 +275,18 @@ class SabreSwap(TransformationPass):\n self.qubits_decay = {k: 1 for k in self.qubits_decay.keys()}\n \n def _successors(self, node, dag):\n- for _, successor, edge_data in dag.edges(node):\n- if not isinstance(successor, DAGOpNode):\n- continue\n- if isinstance(edge_data, Qubit):\n+ \"\"\"Return an iterable of the successors along each wire from the given node.\n+\n+ This yields the same successor multiple times if there are parallel wires (e.g. two adjacent\n+ operations that have one clbit and qubit in common), which is important in the swapping\n+ algorithm for detecting if each wire has been accounted for.\"\"\"\n+ for _, successor, _ in dag.edges(node):\n+ if isinstance(successor, DAGOpNode):\n yield successor\n \n def _is_resolved(self, node):\n \"\"\"Return True if all of a node's predecessors in dag are applied.\"\"\"\n- return self.applied_predecessors[node] == len(node.qargs)\n+ return self.applied_predecessors[node] == len(node.qargs) + len(node.cargs)\n \n def _obtain_extended_set(self, dag, front_layer):\n \"\"\"Populate extended_set by looking ahead a fixed number of gates.\ndiff --git a/releasenotes/notes/fix-sabreswap-clbits-428eb5f3a46063da.yaml b/releasenotes/notes/fix-sabreswap-clbits-428eb5f3a46063da.yaml\nnew file mode 100644\nindex 000000000..0401e5a36\n--- /dev/null\n+++ b/releasenotes/notes/fix-sabreswap-clbits-428eb5f3a46063da.yaml\n@@ -0,0 +1,9 @@\n+---\n+fixes:\n+ - |\n+ Fixed :class:`.SabreSwap`, and by extension :func:`.transpile` with\n+ ``optimization_level=3``, occasionally re-ordering measurements invalidly.\n+ Previously, if two measurements wrote to the same classical bit,\n+ :class:`.SabreSwap` could (depending on the coupling map) re-order them to\n+ produce a non-equivalent circuit. This behaviour was stochastic, so may\n+ not have appeared reliably.\n", "test_patch": "diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py\nindex a19f574a3..509225f65 100644\n--- a/test/python/transpiler/test_sabre_swap.py\n+++ b/test/python/transpiler/test_sabre_swap.py\n@@ -13,6 +13,7 @@\n \"\"\"Test the Sabre Swap pass\"\"\"\n \n import unittest\n+from qiskit.circuit.library import CCXGate, HGate, Measure\n from qiskit.transpiler.passes import SabreSwap\n from qiskit.transpiler import CouplingMap, PassManager\n from qiskit import QuantumRegister, QuantumCircuit\n@@ -95,6 +96,34 @@ class TestSabreSwap(QiskitTestCase):\n \n self.assertEqual(set(cm_edges), set(coupling.get_edges()))\n \n+ def test_do_not_reorder_measurements(self):\n+ \"\"\"Test that SabreSwap doesn't reorder measurements to the same classical bit.\n+\n+ With the particular coupling map used in this test and the 3q ccx gate, the routing would\n+ invariably the measurements if the classical successors are not accurately tracked.\n+ Regression test of gh-7950.\"\"\"\n+ coupling = CouplingMap([(0, 2), (2, 0), (1, 2), (2, 1)])\n+ qc = QuantumCircuit(3, 1)\n+ qc.compose(CCXGate().definition, [0, 1, 2], []) # Unroll CCX to 2q operations.\n+ qc.h(0)\n+ qc.barrier()\n+ qc.measure(0, 0) # This measure is 50/50 between the Z states.\n+ qc.measure(1, 0) # This measure always overwrites with 0.\n+ passmanager = PassManager(SabreSwap(coupling))\n+ transpiled = passmanager.run(qc)\n+\n+ last_h, h_qubits, _ = transpiled.data[-4]\n+ self.assertIsInstance(last_h, HGate)\n+ first_measure, first_measure_qubits, _ = transpiled.data[-2]\n+ second_measure, second_measure_qubits, _ = transpiled.data[-1]\n+ self.assertIsInstance(first_measure, Measure)\n+ self.assertIsInstance(second_measure, Measure)\n+ # Assert that the first measure is on the same qubit that the HGate was applied to, and the\n+ # second measurement is on a different qubit (though we don't care which exactly - that\n+ # depends a little on the randomisation of the pass).\n+ self.assertEqual(h_qubits, first_measure_qubits)\n+ self.assertNotEqual(h_qubits, second_measure_qubits)\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["test/python/transpiler/test_sabre_swap.py::TestSabreSwap::test_do_not_reorder_measurements"]}, {"instance_id": "qiskit__qiskit-terra-7970", "base_commit": "dde6126e8d8ad550801e9a29adc21c83faf17748", "gold_patch": "diff --git a/qiskit/transpiler/passes/routing/sabre_swap.py b/qiskit/transpiler/passes/routing/sabre_swap.py\nindex 5e44b29e5..c6555b069 100644\n--- a/qiskit/transpiler/passes/routing/sabre_swap.py\n+++ b/qiskit/transpiler/passes/routing/sabre_swap.py\n@@ -15,7 +15,9 @@\n import logging\n from collections import defaultdict\n from copy import copy, deepcopy\n+\n import numpy as np\n+import retworkx\n \n from qiskit.circuit.library.standard_gates import SwapGate\n from qiskit.transpiler.basepasses import TransformationPass\n@@ -64,7 +66,13 @@ class SabreSwap(TransformationPass):\n `arXiv:1809.02573 `_\n \"\"\"\n \n- def __init__(self, coupling_map, heuristic=\"basic\", seed=None, fake_run=False):\n+ def __init__(\n+ self,\n+ coupling_map,\n+ heuristic=\"basic\",\n+ seed=None,\n+ fake_run=False,\n+ ):\n r\"\"\"SabreSwap initializer.\n \n Args:\n@@ -153,6 +161,14 @@ class SabreSwap(TransformationPass):\n if len(dag.qubits) > self.coupling_map.size():\n raise TranspilerError(\"More virtual qubits exist than physical.\")\n \n+ max_iterations_without_progress = 10 * len(dag.qubits) # Arbitrary.\n+ ops_since_progress = []\n+ extended_set = None\n+\n+ # Normally this isn't necessary, but here we want to log some objects that have some\n+ # non-trivial cost to create.\n+ do_expensive_logging = logger.isEnabledFor(logging.DEBUG)\n+\n self.dist_matrix = self.coupling_map.distance_matrix\n \n rng = np.random.default_rng(self.seed)\n@@ -169,7 +185,7 @@ class SabreSwap(TransformationPass):\n \n # A decay factor for each qubit used to heuristically penalize recently\n # used qubits (to encourage parallelism).\n- self.qubits_decay = {qubit: 1 for qubit in dag.qubits}\n+ self.qubits_decay = dict.fromkeys(dag.qubits, 1)\n \n # Start algorithm from the front layer and iterate until all gates done.\n num_search_steps = 0\n@@ -178,10 +194,12 @@ class SabreSwap(TransformationPass):\n for _, input_node in dag.input_map.items():\n for successor in self._successors(input_node, dag):\n self.applied_predecessors[successor] += 1\n+\n while front_layer:\n execute_gate_list = []\n \n # Remove as many immediately applicable gates as possible\n+ new_front_layer = []\n for node in front_layer:\n if len(node.qargs) == 2:\n v0, v1 = node.qargs\n@@ -191,13 +209,24 @@ class SabreSwap(TransformationPass):\n current_layout._v2p[v0], current_layout._v2p[v1]\n ):\n execute_gate_list.append(node)\n+ else:\n+ new_front_layer.append(node)\n else: # Single-qubit gates as well as barriers are free\n execute_gate_list.append(node)\n+ front_layer = new_front_layer\n+\n+ if not execute_gate_list and len(ops_since_progress) > max_iterations_without_progress:\n+ # Backtrack to the last time we made progress, then greedily insert swaps to route\n+ # the gate with the smallest distance between its arguments. This is a release\n+ # valve for the algorithm to avoid infinite loops only, and should generally not\n+ # come into play for most circuits.\n+ self._undo_operations(ops_since_progress, mapped_dag, current_layout)\n+ self._add_greedy_swaps(front_layer, mapped_dag, current_layout, canonical_register)\n+ continue\n \n if execute_gate_list:\n for node in execute_gate_list:\n self._apply_gate(mapped_dag, node, current_layout, canonical_register)\n- front_layer.remove(node)\n for successor in self._successors(node, dag):\n self.applied_predecessors[successor] += 1\n if self._is_resolved(successor):\n@@ -207,27 +236,33 @@ class SabreSwap(TransformationPass):\n self._reset_qubits_decay()\n \n # Diagnostics\n- logger.debug(\n- \"free! %s\",\n- [\n- (n.name if isinstance(n, DAGOpNode) else None, n.qargs)\n- for n in execute_gate_list\n- ],\n- )\n- logger.debug(\n- \"front_layer: %s\",\n- [(n.name if isinstance(n, DAGOpNode) else None, n.qargs) for n in front_layer],\n- )\n-\n+ if do_expensive_logging:\n+ logger.debug(\n+ \"free! %s\",\n+ [\n+ (n.name if isinstance(n, DAGOpNode) else None, n.qargs)\n+ for n in execute_gate_list\n+ ],\n+ )\n+ logger.debug(\n+ \"front_layer: %s\",\n+ [\n+ (n.name if isinstance(n, DAGOpNode) else None, n.qargs)\n+ for n in front_layer\n+ ],\n+ )\n+\n+ ops_since_progress = []\n+ extended_set = None\n continue\n \n # After all free gates are exhausted, heuristically find\n # the best swap and insert it. When two or more swaps tie\n # for best score, pick one randomly.\n- extended_set = self._obtain_extended_set(dag, front_layer)\n- swap_candidates = self._obtain_swaps(front_layer, current_layout)\n- swap_scores = dict.fromkeys(swap_candidates, 0)\n- for swap_qubits in swap_scores:\n+ if extended_set is None:\n+ extended_set = self._obtain_extended_set(dag, front_layer)\n+ swap_scores = {}\n+ for swap_qubits in self._obtain_swaps(front_layer, current_layout):\n trial_layout = current_layout.copy()\n trial_layout.swap(*swap_qubits)\n score = self._score_heuristic(\n@@ -238,9 +273,14 @@ class SabreSwap(TransformationPass):\n best_swaps = [k for k, v in swap_scores.items() if v == min_score]\n best_swaps.sort(key=lambda x: (self._bit_indices[x[0]], self._bit_indices[x[1]]))\n best_swap = rng.choice(best_swaps)\n- swap_node = DAGOpNode(op=SwapGate(), qargs=best_swap)\n- self._apply_gate(mapped_dag, swap_node, current_layout, canonical_register)\n+ swap_node = self._apply_gate(\n+ mapped_dag,\n+ DAGOpNode(op=SwapGate(), qargs=best_swap),\n+ current_layout,\n+ canonical_register,\n+ )\n current_layout.swap(*best_swap)\n+ ops_since_progress.append(swap_node)\n \n num_search_steps += 1\n if num_search_steps % DECAY_RESET_INTERVAL == 0:\n@@ -250,23 +290,23 @@ class SabreSwap(TransformationPass):\n self.qubits_decay[best_swap[1]] += DECAY_RATE\n \n # Diagnostics\n- logger.debug(\"SWAP Selection...\")\n- logger.debug(\"extended_set: %s\", [(n.name, n.qargs) for n in extended_set])\n- logger.debug(\"swap scores: %s\", swap_scores)\n- logger.debug(\"best swap: %s\", best_swap)\n- logger.debug(\"qubits decay: %s\", self.qubits_decay)\n+ if do_expensive_logging:\n+ logger.debug(\"SWAP Selection...\")\n+ logger.debug(\"extended_set: %s\", [(n.name, n.qargs) for n in extended_set])\n+ logger.debug(\"swap scores: %s\", swap_scores)\n+ logger.debug(\"best swap: %s\", best_swap)\n+ logger.debug(\"qubits decay: %s\", self.qubits_decay)\n \n self.property_set[\"final_layout\"] = current_layout\n-\n if not self.fake_run:\n return mapped_dag\n return dag\n \n def _apply_gate(self, mapped_dag, node, current_layout, canonical_register):\n- if self.fake_run:\n- return\n new_node = _transform_gate_for_layout(node, current_layout, canonical_register)\n- mapped_dag.apply_operation_back(new_node.op, new_node.qargs, new_node.cargs)\n+ if self.fake_run:\n+ return new_node\n+ return mapped_dag.apply_operation_back(new_node.op, new_node.qargs, new_node.cargs)\n \n def _reset_qubits_decay(self):\n \"\"\"Reset all qubit decay factors to 1 upon request (to forget about\n@@ -332,9 +372,20 @@ class SabreSwap(TransformationPass):\n virtual_neighbor = current_layout[neighbor]\n swap = sorted([virtual, virtual_neighbor], key=lambda q: self._bit_indices[q])\n candidate_swaps.add(tuple(swap))\n-\n return candidate_swaps\n \n+ def _add_greedy_swaps(self, front_layer, dag, layout, qubits):\n+ \"\"\"Mutate ``dag`` and ``layout`` by applying greedy swaps to ensure that at least one gate\n+ can be routed.\"\"\"\n+ layout_map = layout._v2p\n+ target_node = min(\n+ front_layer,\n+ key=lambda node: self.dist_matrix[layout_map[node.qargs[0]], layout_map[node.qargs[1]]],\n+ )\n+ for pair in _shortest_swap_path(tuple(target_node.qargs), self.coupling_map, layout):\n+ self._apply_gate(dag, DAGOpNode(op=SwapGate(), qargs=pair), layout, qubits)\n+ layout.swap(*pair)\n+\n def _compute_cost(self, layer, layout):\n cost = 0\n layout_map = layout._v2p\n@@ -369,13 +420,38 @@ class SabreSwap(TransformationPass):\n \n raise TranspilerError(\"Heuristic %s not recognized.\" % heuristic)\n \n+ def _undo_operations(self, operations, dag, layout):\n+ \"\"\"Mutate ``dag`` and ``layout`` by undoing the swap gates listed in ``operations``.\"\"\"\n+ if dag is None:\n+ for operation in reversed(operations):\n+ layout.swap(*operation.qargs)\n+ else:\n+ for operation in reversed(operations):\n+ dag.remove_op_node(operation)\n+ p0 = self._bit_indices[operation.qargs[0]]\n+ p1 = self._bit_indices[operation.qargs[1]]\n+ layout.swap(p0, p1)\n+\n \n def _transform_gate_for_layout(op_node, layout, device_qreg):\n \"\"\"Return node implementing a virtual op on given layout.\"\"\"\n mapped_op_node = copy(op_node)\n+ mapped_op_node.qargs = [device_qreg[layout._v2p[x]] for x in op_node.qargs]\n+ return mapped_op_node\n \n- premap_qargs = op_node.qargs\n- mapped_qargs = map(lambda x: device_qreg[layout._v2p[x]], premap_qargs)\n- mapped_op_node.qargs = list(mapped_qargs)\n \n- return mapped_op_node\n+def _shortest_swap_path(target_qubits, coupling_map, layout):\n+ \"\"\"Return an iterator that yields the swaps between virtual qubits needed to bring the two\n+ virtual qubits in ``target_qubits`` together in the coupling map.\"\"\"\n+ v_start, v_goal = target_qubits\n+ start, goal = layout._v2p[v_start], layout._v2p[v_goal]\n+ # TODO: remove the list call once using retworkx 0.12, as the return value can be sliced.\n+ path = list(retworkx.dijkstra_shortest_paths(coupling_map.graph, start, target=goal)[goal])\n+ # Swap both qubits towards the \"centre\" (as opposed to applying the same swaps to one) to\n+ # parallelise and reduce depth.\n+ split = len(path) // 2\n+ forwards, backwards = path[1:split], reversed(path[split:-1])\n+ for swap in forwards:\n+ yield v_start, layout._p2v[swap]\n+ for swap in backwards:\n+ yield v_goal, layout._p2v[swap]\ndiff --git a/releasenotes/notes/sabreswap-loop-230ef99e61358105.yaml b/releasenotes/notes/sabreswap-loop-230ef99e61358105.yaml\nnew file mode 100644\nindex 000000000..f004d411b\n--- /dev/null\n+++ b/releasenotes/notes/sabreswap-loop-230ef99e61358105.yaml\n@@ -0,0 +1,11 @@\n+---\n+fixes:\n+ - |\n+ The :class:`.SabreSwap` transpiler pass, and by extension\n+ :class:`.SabreLayout` and :func:`.transpile` at ``optimization_level=3``,\n+ now has an escape mechanism to guarantee that it can never get stuck in an\n+ infinite loop. Certain inputs previously could, with a great amount of bad\n+ luck, get stuck in a stable local minimum of the search space and the pass\n+ would never make further progress. It will now force a series of swaps that\n+ allow the routing to continue if it detects it has not made progress\n+ recently. Fixed `#7707 `__.\n", "test_patch": "diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py\nindex 509225f65..f7a9e96cf 100644\n--- a/test/python/transpiler/test_sabre_swap.py\n+++ b/test/python/transpiler/test_sabre_swap.py\n@@ -13,13 +13,79 @@\n \"\"\"Test the Sabre Swap pass\"\"\"\n \n import unittest\n-from qiskit.circuit.library import CCXGate, HGate, Measure\n+\n+import ddt\n+\n+from qiskit.circuit.library import CCXGate, HGate, Measure, SwapGate\n from qiskit.transpiler.passes import SabreSwap\n from qiskit.transpiler import CouplingMap, PassManager\n from qiskit import QuantumRegister, QuantumCircuit\n from qiskit.test import QiskitTestCase\n-\n-\n+from qiskit.utils import optionals\n+\n+\n+def looping_circuit(uphill_swaps=1, additional_local_minimum_gates=0):\n+ \"\"\"A circuit that causes SabreSwap to loop infinitely.\n+\n+ This looks like (using cz gates to show the symmetry, though we actually output cx for testing\n+ purposes):\n+\n+ .. parsed-literal::\n+\n+ q_0: \u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+ \u2502\n+ q_1: \u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+ \u2502 \u2502\n+ q_2: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+ \u2502 \u2502 \u2502\n+ q_3: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+ \u2502 \u2502 \u2502 \u2502\n+ q_4: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\n+ \u2502 \u2502 \u2502 \u2502 \u2502\n+ q_5: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u25a0\u2500\n+ \u2502 \u2502 \u2502 \u2502 \u2502\n+ q_6: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\n+ \u2502 \u2502 \u2502 \u2502 \u2502\n+ q_7: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u25a0\u2500\n+ \u2502 \u2502 \u2502 \u2502 \u2502\n+ q_8: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\n+ \u2502 \u2502 \u2502 \u2502\n+ q_9: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+ \u2502 \u2502 \u2502\n+ q_10: \u2500\u253c\u2500\u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+ \u2502 \u2502\n+ q_11: \u2500\u253c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+ \u2502\n+ q_12: \u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n+\n+ where `uphill_swaps` is the number of qubits separating the inner-most gate (representing how\n+ many swaps need to be made that all increase the heuristics), and\n+ `additional_local_minimum_gates` is how many extra gates to add on the outside (these increase\n+ the size of the region of stability).\n+ \"\"\"\n+ outers = 4 + additional_local_minimum_gates\n+ n_qubits = 2 * outers + 4 + uphill_swaps\n+ # This is (most of) the front layer, which is a bunch of outer qubits in the\n+ # coupling map.\n+ outer_pairs = [(i, n_qubits - i - 1) for i in range(outers)]\n+ inner_heuristic_peak = [\n+ # This gate is completely \"inside\" all the others in the front layer in\n+ # terms of the coupling map, so it's the only one that we can in theory\n+ # make progress towards without making the others worse.\n+ (outers + 1, outers + 2 + uphill_swaps),\n+ # These are the only two gates in the extended set, and they both get\n+ # further apart if you make a swap to bring the above gate closer\n+ # together, which is the trick that creates the \"heuristic hill\".\n+ (outers, outers + 1),\n+ (outers + 2 + uphill_swaps, outers + 3 + uphill_swaps),\n+ ]\n+ qc = QuantumCircuit(n_qubits)\n+ for pair in outer_pairs + inner_heuristic_peak:\n+ qc.cx(*pair)\n+ return qc\n+\n+\n+@ddt.ddt\n class TestSabreSwap(QiskitTestCase):\n \"\"\"Tests the SabreSwap pass.\"\"\"\n \n@@ -124,6 +190,53 @@ class TestSabreSwap(QiskitTestCase):\n self.assertEqual(h_qubits, first_measure_qubits)\n self.assertNotEqual(h_qubits, second_measure_qubits)\n \n+ # The 'basic' method can't get stuck in the same way.\n+ @ddt.data(\"lookahead\", \"decay\")\n+ def test_no_infinite_loop(self, method):\n+ \"\"\"Test that the 'release value' mechanisms allow SabreSwap to make progress even on\n+ circuits that get stuck in a stable local minimum of the lookahead parameters.\"\"\"\n+ qc = looping_circuit(3, 1)\n+ qc.measure_all()\n+ coupling_map = CouplingMap.from_line(qc.num_qubits)\n+ routing_pass = PassManager(SabreSwap(coupling_map, method))\n+\n+ n_swap_gates = 0\n+\n+ def leak_number_of_swaps(cls, *args, **kwargs):\n+ nonlocal n_swap_gates\n+ n_swap_gates += 1\n+ if n_swap_gates > 1_000:\n+ raise Exception(\"SabreSwap seems to be stuck in a loop\")\n+ # pylint: disable=bad-super-call\n+ return super(SwapGate, cls).__new__(cls, *args, **kwargs)\n+\n+ with unittest.mock.patch.object(SwapGate, \"__new__\", leak_number_of_swaps):\n+ routed = routing_pass.run(qc)\n+\n+ routed_ops = routed.count_ops()\n+ del routed_ops[\"swap\"]\n+ self.assertEqual(routed_ops, qc.count_ops())\n+ couplings = {\n+ tuple(routed.find_bit(bit).index for bit in qargs)\n+ for _, qargs, _ in routed.data\n+ if len(qargs) == 2\n+ }\n+ # Asserting equality to the empty set gives better errors on failure than asserting that\n+ # `couplings <= coupling_map`.\n+ self.assertEqual(couplings - set(coupling_map.get_edges()), set())\n+\n+ # Assert that the same keys are produced by a simulation - this is a test that the inserted\n+ # swaps route the qubits correctly.\n+ if not optionals.HAS_AER:\n+ return\n+\n+ from qiskit import Aer\n+\n+ sim = Aer.get_backend(\"aer_simulator\")\n+ in_results = sim.run(qc, shots=4096).result().get_counts()\n+ out_results = sim.run(routed, shots=4096).result().get_counts()\n+ self.assertEqual(set(in_results), set(out_results))\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "FAIL_TO_PASS": ["test/python/transpiler/test_sabre_swap.py::TestSabreSwap::test_no_infinite_loop_1_lookahead", "test/python/transpiler/test_sabre_swap.py::TestSabreSwap::test_no_infinite_loop_2_decay"]}], "all_FAIL_TO_PASS": ["test/python/transpiler/test_sabre_swap.py::TestSabreSwap::test_do_not_reorder_measurements", "test/python/transpiler/test_sabre_swap.py::TestSabreSwap::test_no_infinite_loop_1_lookahead", "test/python/transpiler/test_sabre_swap.py::TestSabreSwap::test_no_infinite_loop_2_decay"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "copier-org__copier-2032_x2", "level": 2, "source": "swerebenchv2", "repo": "copier-org/copier", "image": "swerebenchv2/copier-org-copier:2032-1b4bbb7", "base_commit": "1b4bbb714885a03baa2b9338e8c19d07b7acdbee", "num_bugs": 2, "bugs": [{"instance_id": "copier-org__copier-2032", "base_commit": "1b4bbb714885a03baa2b9338e8c19d07b7acdbee", "gold_patch": "diff --git a/copier/errors.py b/copier/errors.py\nindex 01e6f1a..48a87fc 100644\n--- a/copier/errors.py\n+++ b/copier/errors.py\n@@ -147,3 +147,10 @@ class MissingSettingsWarning(UserWarning, CopierWarning):\n \n class MissingFileWarning(UserWarning, CopierWarning):\n \"\"\"I still couldn't find what I'm looking for.\"\"\"\n+\n+\n+class InteractiveSessionError(UserMessageError):\n+ \"\"\"An interactive session is required to run this program.\"\"\"\n+\n+ def __init__(self, message: str) -> None:\n+ super().__init__(f\"Interactive session required: {message}\")\ndiff --git a/copier/main.py b/copier/main.py\nindex 382b017..ce462f0 100644\n--- a/copier/main.py\n+++ b/copier/main.py\n@@ -32,16 +32,16 @@ from unicodedata import normalize\n from jinja2.loaders import FileSystemLoader\n from pathspec import PathSpec\n from plumbum import ProcessExecutionError, colors\n-from plumbum.cli.terminal import ask\n from plumbum.machines import local\n from pydantic import ConfigDict, PositiveInt\n from pydantic.dataclasses import dataclass\n from pydantic_core import to_jsonable_python\n-from questionary import unsafe_prompt\n+from questionary import confirm, unsafe_prompt\n \n from .errors import (\n CopierAnswersInterrupt,\n ExtensionNotFoundError,\n+ InteractiveSessionError,\n UnsafeTemplateError,\n UserMessageError,\n YieldTagInFileError,\n@@ -466,7 +466,11 @@ class Worker:\n file_=sys.stderr,\n )\n return True\n- return bool(ask(f\" Overwrite {dst_relpath}?\", default=True))\n+ try:\n+ answer = confirm(f\" Overwrite {dst_relpath}?\", default=True).unsafe_ask()\n+ except EOFError as err:\n+ raise InteractiveSessionError(\"Consider using `--overwrite`\") from err\n+ return bool(answer)\n \n def _render_allowed(\n self,\n@@ -587,10 +591,15 @@ class Worker:\n if new_answer is MISSING:\n raise ValueError(f'Question \"{var_name}\" is required')\n else:\n- new_answer = unsafe_prompt(\n- [question.get_questionary_structure()],\n- answers={question.var_name: question.get_default()},\n- )[question.var_name]\n+ try:\n+ new_answer = unsafe_prompt(\n+ [question.get_questionary_structure()],\n+ answers={question.var_name: question.get_default()},\n+ )[question.var_name]\n+ except EOFError as err:\n+ raise InteractiveSessionError(\n+ \"Use `--defaults` and/or `--data`/`--data-file`\"\n+ ) from err\n except KeyboardInterrupt as err:\n raise CopierAnswersInterrupt(\n self.answers, question, self.template\n", "test_patch": "diff --git a/tests/test_prompt.py b/tests/test_prompt.py\nindex 492f806..086f9fe 100644\n--- a/tests/test_prompt.py\n+++ b/tests/test_prompt.py\n@@ -1,5 +1,7 @@\n from __future__ import annotations\n \n+import platform\n+import subprocess\n import sys\n from pathlib import Path\n from typing import Any, Dict, List, Mapping, Protocol, Union\n@@ -997,3 +999,53 @@ def test_secret_validator(\n tui.sendline(default)\n tui.expect_exact(\"******\")\n tui.expect_exact(pexpect.EOF)\n+\n+\n+# Related to https://github.com/prompt-toolkit/python-prompt-toolkit/issues/1243#issuecomment-706668723)\n+@pytest.mark.xfail(\n+ platform.system() == \"Windows\",\n+ reason=\"prompt-toolkit in subprocess call fails on Windows\",\n+)\n+def test_interactive_session_required_for_question_prompt(\n+ question_tree: QuestionTreeFixture,\n+) -> None:\n+ \"\"\"Answering a question prompt requires an interactive session.\"\"\"\n+ src, dst = question_tree(type=\"str\")\n+ process = subprocess.run(\n+ (*COPIER_PATH, \"copy\", str(src), str(dst)),\n+ stdin=subprocess.PIPE, # Prevents interactive input\n+ capture_output=True,\n+ timeout=10,\n+ )\n+ assert process.returncode == 1\n+ assert (\n+ b\"Interactive session required: Use `--defaults` and/or `--data`/`--data-file`\"\n+ ) in process.stderr\n+\n+\n+# Related to https://github.com/prompt-toolkit/python-prompt-toolkit/issues/1243#issuecomment-706668723)\n+@pytest.mark.xfail(\n+ platform.system() == \"Windows\",\n+ reason=\"prompt-toolkit in subprocess call fails on Windows\",\n+)\n+def test_interactive_session_required_for_overwrite_prompt(\n+ tmp_path_factory: pytest.TempPathFactory,\n+) -> None:\n+ \"\"\"Overwriting a file without `--overwrite` flag requires an interactive session.\"\"\"\n+ src, dst = map(tmp_path_factory.mktemp, (\"src\", \"dst\"))\n+ build_file_tree(\n+ {\n+ (src / \"foo.txt.jinja\"): \"bar\",\n+ (dst / \"foo.txt\"): \"baz\",\n+ }\n+ )\n+ process = subprocess.run(\n+ (*COPIER_PATH, \"copy\", str(src), str(dst)),\n+ stdin=subprocess.PIPE, # Prevents interactive input\n+ capture_output=True,\n+ timeout=10,\n+ )\n+ assert process.returncode == 1\n+ assert (\n+ b\"Interactive session required: Consider using `--overwrite`\" in process.stderr\n+ )\n", "FAIL_TO_PASS": ["tests/test_prompt.py::test_interactive_session_required_for_overwrite_prompt", "tests/test_prompt.py::test_interactive_session_required_for_question_prompt"]}, {"instance_id": "copier-org__copier-2067", "base_commit": "ef0037522109182ed8f187ef4f094848bf94b42b", "gold_patch": "diff --git a/copier/main.py b/copier/main.py\nindex ce462f0..69c6f15 100644\n--- a/copier/main.py\n+++ b/copier/main.py\n@@ -563,6 +563,10 @@ class Worker:\n if not question.get_when():\n # Omit its answer from the answers file.\n self.answers.hide(var_name)\n+ # Delete last answers to re-compute the answer from the default\n+ # value (if it exists).\n+ if var_name in self.answers.last:\n+ del self.answers.last[var_name]\n # Skip immediately to the next question when it has no default\n # value.\n if question.default is MISSING:\n", "test_patch": "diff --git a/tests/test_recopy.py b/tests/test_recopy.py\nindex 20bcedb..09dd2a5 100644\n--- a/tests/test_recopy.py\n+++ b/tests/test_recopy.py\n@@ -130,3 +130,50 @@ def test_recopy_dont_validate_computed_value(\n run_recopy(dst, overwrite=True)\n answers = load_answersfile_data(dst)\n assert \"computed\" not in answers\n+\n+\n+def test_conditional_computed_value(tmp_path_factory: pytest.TempPathFactory) -> None:\n+ src, dst = map(tmp_path_factory.mktemp, (\"src\", \"dst\"))\n+\n+ build_file_tree(\n+ {\n+ src / \"copier.yml\": (\n+ \"\"\"\\\n+ first:\n+ type: bool\n+\n+ second:\n+ type: bool\n+ default: \"{{ first }}\"\n+ when: \"{{ first }}\"\n+ \"\"\"\n+ ),\n+ src / \"{{ _copier_conf.answers_file }}.jinja\": (\n+ \"{{ _copier_answers|to_nice_yaml }}\"\n+ ),\n+ src / \"log.txt.jinja\": \"{{ first }} {{ second }}\",\n+ }\n+ )\n+ git_save(src)\n+\n+ run_copy(str(src), dst, data={\"first\": True}, defaults=True)\n+ answers = load_answersfile_data(dst)\n+ assert answers[\"first\"] is True\n+ assert answers[\"second\"] is True\n+ assert (dst / \"log.txt\").read_text() == \"True True\"\n+\n+ git_save(dst, \"v1\")\n+\n+ run_recopy(dst, data={\"first\": False}, overwrite=True)\n+ answers = load_answersfile_data(dst)\n+ assert answers[\"first\"] is False\n+ assert \"second\" not in answers\n+ assert (dst / \"log.txt\").read_text() == \"False False\"\n+\n+ git_save(dst, \"v2\")\n+\n+ run_recopy(dst, data={\"first\": True}, defaults=True, overwrite=True)\n+ answers = load_answersfile_data(dst)\n+ assert answers[\"first\"] is True\n+ assert answers[\"second\"] is True\n+ assert (dst / \"log.txt\").read_text() == \"True True\"\ndiff --git a/tests/test_updatediff.py b/tests/test_updatediff.py\nindex 07f42c3..b4f5f0d 100644\n--- a/tests/test_updatediff.py\n+++ b/tests/test_updatediff.py\n@@ -1869,3 +1869,55 @@ def test_conflict_on_update_with_unicode_in_content(\n zzz\ud83d\udc0d\n \"\"\"\n )\n+\n+\n+def test_conditional_computed_value(tmp_path_factory: pytest.TempPathFactory) -> None:\n+ src, dst = map(tmp_path_factory.mktemp, (\"src\", \"dst\"))\n+\n+ build_file_tree(\n+ {\n+ src / \"copier.yml\": (\n+ \"\"\"\\\n+ first:\n+ type: bool\n+\n+ second:\n+ type: bool\n+ default: \"{{ first }}\"\n+ when: \"{{ first }}\"\n+ \"\"\"\n+ ),\n+ src / \"{{ _copier_conf.answers_file }}.jinja\": (\n+ \"{{ _copier_answers|to_nice_yaml }}\"\n+ ),\n+ src / \"log.txt.jinja\": \"{{ first }} {{ second }}\",\n+ }\n+ )\n+ with local.cwd(src):\n+ git_init(\"v1\")\n+ git(\"tag\", \"v1\")\n+\n+ run_copy(str(src), dst, data={\"first\": True}, defaults=True)\n+ answers = load_answersfile_data(dst)\n+ assert answers[\"first\"] is True\n+ assert answers[\"second\"] is True\n+ assert (dst / \"log.txt\").read_text() == \"True True\"\n+\n+ with local.cwd(dst):\n+ git_init(\"v1\")\n+\n+ run_update(dst, data={\"first\": False}, overwrite=True)\n+ answers = load_answersfile_data(dst)\n+ assert answers[\"first\"] is False\n+ assert \"second\" not in answers\n+ assert (dst / \"log.txt\").read_text() == \"False False\"\n+\n+ with local.cwd(dst):\n+ git(\"add\", \".\")\n+ git(\"commit\", \"-m\", \"v2\")\n+\n+ run_update(dst, data={\"first\": True}, defaults=True, overwrite=True)\n+ answers = load_answersfile_data(dst)\n+ assert answers[\"first\"] is True\n+ assert answers[\"second\"] is True\n+ assert (dst / \"log.txt\").read_text() == \"True True\"\n", "FAIL_TO_PASS": ["tests/test_recopy.py::test_conditional_computed_value", "tests/test_updatediff.py::test_conditional_computed_value"]}], "all_FAIL_TO_PASS": ["tests/test_prompt.py::test_interactive_session_required_for_overwrite_prompt", "tests/test_prompt.py::test_interactive_session_required_for_question_prompt", "tests/test_recopy.py::test_conditional_computed_value", "tests/test_updatediff.py::test_conditional_computed_value"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "s-knibbs__dataclasses-jsonschema-101_x2", "level": 2, "source": "swerebenchv2", "repo": "s-knibbs/dataclasses-jsonschema", "image": "swerebenchv2/s-knibbs-dataclasses-jsonschema:101-2fd41a0", "base_commit": "2fd41a0b35591cf02016ba32787bd3dcf837c0d1", "num_bugs": 2, "bugs": [{"instance_id": "s-knibbs__dataclasses-jsonschema-101", "base_commit": "2fd41a0b35591cf02016ba32787bd3dcf837c0d1", "gold_patch": "diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py\nindex 8b79677..8d3e789 100644\n--- a/dataclasses_jsonschema/__init__.py\n+++ b/dataclasses_jsonschema/__init__.py\n@@ -532,7 +532,7 @@ class JsonSchemaMixin:\n \n @classmethod\n def _get_field_schema(cls, field: Union[Field, Type], schema_type: SchemaType) -> Tuple[JsonDict, bool]:\n- field_schema: JsonDict = {'type': 'object'}\n+ field_schema: JsonDict = {}\n required = True\n \n if isinstance(field, Field):\n", "test_patch": "diff --git a/tests/test_core.py b/tests/test_core.py\nindex dc7041b..45b3532 100644\n--- a/tests/test_core.py\n+++ b/tests/test_core.py\n@@ -4,7 +4,7 @@ from enum import Enum\n \n from dataclasses import dataclass, field\n from ipaddress import IPv4Address, IPv6Address\n-from typing import List, NewType, Optional, Union, Set\n+from typing import List, NewType, Optional, Union, Set, Any\n from typing_extensions import Final, Literal\n from uuid import UUID\n \n@@ -747,3 +747,22 @@ def test_set_decode_encode():\n assert isinstance(expected_blog.to_dict()[\"tags\"], list)\n assert len(expected_blog.to_dict()[\"tags\"]) == 2\n assert BlogArticle.from_dict(expected_blog_dict) == expected_blog\n+\n+\n+def test_any_type_schema():\n+ @dataclass\n+ class GraphNode(JsonSchemaMixin):\n+ \"\"\"A graph node\"\"\"\n+ id: int\n+ data: Any\n+\n+ expected_schema = compose_schema({\n+ \"type\": \"object\",\n+ \"description\": \"A graph node\",\n+ \"properties\": {\n+ \"id\": {\"type\": \"integer\"},\n+ \"data\": {}\n+ },\n+ \"required\": [\"id\", \"data\"]\n+ })\n+ assert GraphNode.json_schema() == expected_schema\n", "FAIL_TO_PASS": ["tests/test_core.py::test_any_type_schema"]}, {"instance_id": "s-knibbs__dataclasses-jsonschema-104", "base_commit": "734fc59969ffabd870d196448162aa3389ac42ff", "gold_patch": "diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py\nindex 8d3e789..77b392f 100644\n--- a/dataclasses_jsonschema/__init__.py\n+++ b/dataclasses_jsonschema/__init__.py\n@@ -188,12 +188,13 @@ class JsonSchemaMixin:\n __discriminator_name: Optional[str]\n # True if __discriminator_name is inherited from the base class\n __discriminator_inherited: bool\n+ __allow_additional_props: bool\n \n @classmethod\n def _discriminator(cls) -> Optional[str]:\n return cls.__discriminator_name\n \n- def __init_subclass__(cls, discriminator: Optional[Union[str, bool]] = None):\n+ def __init_subclass__(cls, discriminator: Optional[Union[str, bool]] = None, allow_additional_props: bool = True):\n # Initialise caches\n cls.__schema = {}\n cls.__compiled_schema = {}\n@@ -219,6 +220,7 @@ class JsonSchemaMixin:\n cls.__discriminator_inherited = True\n else:\n cls.__discriminator_name = None\n+ cls.__allow_additional_props = allow_additional_props\n \n @classmethod\n def field_mapping(cls) -> Dict[str, str]:\n@@ -693,6 +695,9 @@ class JsonSchemaMixin:\n 'properties': properties\n }\n \n+ if not cls.__allow_additional_props:\n+ schema[\"additionalProperties\"] = False\n+\n if cls.__discriminator_name is not None and \\\n schema_type == SchemaType.OPENAPI_3 and \\\n not cls.__discriminator_inherited:\n", "test_patch": "diff --git a/tests/test_core.py b/tests/test_core.py\nindex 45b3532..b956692 100644\n--- a/tests/test_core.py\n+++ b/tests/test_core.py\n@@ -766,3 +766,23 @@ def test_any_type_schema():\n \"required\": [\"id\", \"data\"]\n })\n assert GraphNode.json_schema() == expected_schema\n+\n+\n+def test_additional_properties_allowed():\n+ @dataclass\n+ class Scorpion(JsonSchemaMixin, allow_additional_props=False):\n+ \"\"\"A scorpion\"\"\"\n+ species: str\n+ venom_rating: int\n+\n+ expected_schema = compose_schema({\n+ \"type\": \"object\",\n+ \"description\": \"A scorpion\",\n+ \"properties\": {\n+ \"species\": {\"type\": \"string\"},\n+ \"venom_rating\": {\"type\": \"integer\"},\n+ },\n+ \"required\": [\"species\", \"venom_rating\"],\n+ \"additionalProperties\": False,\n+ })\n+ assert Scorpion.json_schema() == expected_schema\n", "FAIL_TO_PASS": ["tests/test_core.py::test_additional_properties_allowed"]}], "all_FAIL_TO_PASS": ["tests/test_core.py::test_any_type_schema", "tests/test_core.py::test_additional_properties_allowed"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "virtuslab__git-machete-487_x2", "level": 2, "source": "swerebenchv2", "repo": "VirtusLab/git-machete", "image": "swerebenchv2/virtuslab-git-machete:487-9f95ea7", "base_commit": "9f95ea7ab1edb936180b9af6b98d883079889dee", "num_bugs": 2, "bugs": [{"instance_id": "virtuslab__git-machete-487", "base_commit": "9f95ea7ab1edb936180b9af6b98d883079889dee", "gold_patch": "diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md\nindex 195ad76..64c9190 100644\n--- a/RELEASE_NOTES.md\n+++ b/RELEASE_NOTES.md\n@@ -2,7 +2,8 @@\n \n ## New in git-machete 3.10.0\n \n-- added: boolean git config key `machete.status.extraSpaceBeforeBranchName` that enables configurable rendering of `status` command\n+- added: boolean git config key `machete.status.extraSpaceBeforeBranchName` that enable configurable rendering of `status` command\n+- added: 3 git config keys `machete.github.{remote,organization,repository}` that enable `git machete github *` subcommands to work with custom GitHub URLs\n \n ## New in git-machete 3.9.1\n \ndiff --git a/docs/source/cli_help/anno.rst b/docs/source/cli_help/anno.rst\nindex aaa85c4..57f775a 100644\n--- a/docs/source/cli_help/anno.rst\n+++ b/docs/source/cli_help/anno.rst\n@@ -23,6 +23,7 @@ If invoked with ``-H`` or ``--sync-github-prs``, annotates the branches based on\n Any existing annotations are overwritten for the branches that have an opened PR; annotations for the other branches remain untouched.\n \n .. include:: github_api_access.rst\n+.. include:: github_config_keys.rst\n \n In any other case, sets the annotation for the given/current branch to the given .\n If multiple 's are passed to the command, they are concatenated with a single space.\ndiff --git a/docs/source/cli_help/clean.rst b/docs/source/cli_help/clean.rst\nindex c77c182..063df51 100644\n--- a/docs/source/cli_help/clean.rst\n+++ b/docs/source/cli_help/clean.rst\n@@ -17,6 +17,7 @@ No branch will be deleted unless explicitly confirmed by the user (or unless ``-\n Equivalent of ``git machete github sync`` if invoked with ``-H`` or ``--checkout-my-github-prs``.\n \n .. include:: github_api_access.rst\n+.. include:: github_config_keys.rst\n \n **Options:**\n \ndiff --git a/docs/source/cli_help/github.rst b/docs/source/cli_help/github.rst\nindex 10efed2..31fafa3 100644\n--- a/docs/source/cli_help/github.rst\n+++ b/docs/source/cli_help/github.rst\n@@ -13,6 +13,7 @@ where ```` is one of: ``anno-prs``, ``checkout-prs``, ``create-pr``,\n Creates, checks out and manages GitHub PRs while keeping them reflected in branch definition file.\n \n .. include:: github_api_access.rst\n+.. include:: github_config_keys.rst\n \n ``anno-prs``:\n \n@@ -20,6 +21,7 @@ Creates, checks out and manages GitHub PRs while keeping them reflected in branc\n Any existing annotations are overwritten for the branches that have an opened PR; annotations for the other branches remain untouched.\n Equivalent to ``git machete anno --sync-github-prs``.\n \n+\n ``checkout-prs [--all | --by= | --mine | ... ]``:\n \n Check out the head branch of the given pull requests (specified by numbers or by a flag),\ndiff --git a/docs/source/conf.py b/docs/source/conf.py\nindex 4bf76a9..340151c 100644\n--- a/docs/source/conf.py\n+++ b/docs/source/conf.py\n@@ -47,7 +47,8 @@ exclude_patterns = [\n 'completion.rst',\n 'description.rst',\n 'learning_materials.rst',\n- 'github_api_access.rst'\n+ 'github_api_access.rst',\n+ 'github_config_keys.rst'\n ]\n \n \ndiff --git a/docs/source/github_config_keys.rst b/docs/source/github_config_keys.rst\nnew file mode 100644\nindex 0000000..4558d64\n--- /dev/null\n+++ b/docs/source/github_config_keys.rst\n@@ -0,0 +1,23 @@\n+.. _github_config_keys:\n+\n+ .. note::\n+\n+ GitHub API server URL will be inferred from ``git remote``.\n+ You can override this by setting the following git config keys:\n+ Remote name\n+ E.g. ``machete.github.remote`` = ``origin``\n+\n+ Organization name\n+ E.g. ``machete.github.organization`` = ``VirtusLab``\n+\n+ Repository name\n+ E.g. ``machete.github.repository`` = ``git-machete``\n+\n+ To do this, run ``git config --local --edit`` and add the following section:\n+\n+ .. code-block:: ini\n+\n+ [machete \"github\"]\n+ organization = \n+ repository = \n+ remote = \ndiff --git a/git_machete/client.py b/git_machete/client.py\nindex 3405137..57f8cac 100644\n--- a/git_machete/client.py\n+++ b/git_machete/client.py\n@@ -20,7 +20,7 @@ from git_machete.github import (\n add_assignees_to_pull_request, add_reviewers_to_pull_request,\n create_pull_request, checkout_pr_refs, derive_pull_request_by_head, derive_pull_requests,\n get_github_token_possible_providers, get_parsed_github_remote_url, get_pull_request_by_number_or_none, GitHubPullRequest,\n- is_github_remote_url, set_base_of_pull_request, set_milestone_of_pull_request)\n+ is_github_remote_url, RemoteAndOrganizationAndRepository, set_base_of_pull_request, set_milestone_of_pull_request)\n from git_machete.utils import (\n get_pretty_choices, flat_map, excluding, fmt, tupled, warn, debug, bold,\n colored, underline, dim, get_second, AnsiEscapeCodes)\n@@ -1386,33 +1386,7 @@ class MacheteClient:\n return result\n \n def sync_annotations_to_github_prs(self) -> None:\n-\n- url_for_remote: Dict[str, str] = {remote: self.__git.get_url_of_remote(remote) for remote in\n- self.__git.get_remotes()}\n- if not url_for_remote:\n- raise MacheteException(fmt('No remotes defined for this repository (see `git remote`)'))\n-\n- optional_org_name_for_github_remote: Dict[str, Optional[Tuple[str, str]]] = {\n- remote: get_parsed_github_remote_url(url) for remote, url in url_for_remote.items()}\n- org_name_for_github_remote: Dict[str, Tuple[str, str]] = {remote: org_name for remote, org_name in\n- optional_org_name_for_github_remote.items() if\n- org_name}\n- if not org_name_for_github_remote:\n- raise MacheteException(\n- fmt('Remotes are defined for this repository, but none of them '\n- 'corresponds to GitHub (see `git remote -v` for details)'))\n-\n- org: str = ''\n- repo: str = ''\n- if len(org_name_for_github_remote) == 1:\n- org, repo = list(org_name_for_github_remote.values())[0]\n- elif len(org_name_for_github_remote) > 1:\n- if 'origin' in org_name_for_github_remote:\n- org, repo = org_name_for_github_remote['origin']\n- else:\n- raise MacheteException(\n- f'Multiple non-origin remotes correspond to GitHub in this repository: '\n- f'{\", \".join(org_name_for_github_remote.keys())}, aborting')\n+ remote, org, repo = self.__derive_remote_and_github_org_and_repo()\n current_user: Optional[str] = git_machete.github.derive_current_user_login()\n debug('Current GitHub user is ' + (current_user or ''))\n pr: GitHubPullRequest\n@@ -1880,7 +1854,7 @@ class MacheteClient:\n org: str\n repo: str\n remote: str\n- remote, (org, repo) = self.__derive_remote_and_github_org_and_repo()\n+ remote, org, repo = self.__derive_remote_and_github_org_and_repo()\n current_user: Optional[str] = git_machete.github.derive_current_user_login()\n if not current_user and my_opened_prs:\n msg = (\"Could not determine current user name, please check that the GitHub API token provided by one of the: \"\n@@ -2030,14 +2004,14 @@ class MacheteClient:\n for remote, url in url_for_remote.items():\n url = url if url.endswith('.git') else url + '.git'\n remote_url = remote_url if remote_url.endswith('.git') else remote_url + '.git'\n- if is_github_remote_url(url) and get_parsed_github_remote_url(url) == get_parsed_github_remote_url(remote_url):\n+ if is_github_remote_url(url) and get_parsed_github_remote_url(url, remote) == get_parsed_github_remote_url(remote_url, remote):\n return remote\n return None\n \n def retarget_github_pr(self, head: LocalBranchShortName) -> None:\n org: str\n repo: str\n- _, (org, repo) = self.__derive_remote_and_github_org_and_repo()\n+ _, org, repo = self.__derive_remote_and_github_org_and_repo()\n \n debug(f'organization is {org}, repository is {repo}')\n \n@@ -2060,30 +2034,44 @@ class MacheteClient:\n else:\n print(fmt(f'The base branch of PR #{pr.number} is already `{new_base}`'))\n \n- def __derive_remote_and_github_org_and_repo(self) -> Tuple[str, Tuple[str, str]]:\n+ def __derive_remote_and_github_org_and_repo(self) -> RemoteAndOrganizationAndRepository:\n+ remote_and_organization_and_repository_for_custom_url = self.__get_remote_and_organization_and_repository_name_for_custom_url()\n+ if all(remote_and_organization_and_repository_for_custom_url):\n+ return remote_and_organization_and_repository_for_custom_url\n+\n url_for_remote: Dict[str, str] = {\n remote: self.__git.get_url_of_remote(remote) for remote in self.__git.get_remotes()\n }\n if not url_for_remote:\n raise MacheteException(fmt('No remotes defined for this repository (see `git remote`)'))\n \n- org_and_repo_for_github_remote: Dict[str, Tuple[str, str]] = {\n- remote: get_parsed_github_remote_url(url) for remote, url in url_for_remote.items() if is_github_remote_url(url)\n+ remote_and_github_org_and_repo: Dict[str, RemoteAndOrganizationAndRepository] = {\n+ remote: get_parsed_github_remote_url(url, remote) for remote, url in url_for_remote.items() if is_github_remote_url(url)\n }\n- if not org_and_repo_for_github_remote:\n+ if not remote_and_github_org_and_repo:\n raise MacheteException(\n fmt('Remotes are defined for this repository, but none of them '\n- 'corresponds to GitHub (see `git remote -v` for details)\\n'))\n+ 'corresponds to GitHub (see `git remote -v` for details). \\n'\n+ 'It is possible that you are using custom GitHub URL.\\n'\n+ 'If that is the case, you can provide repository information explicitly, via these 3 git config keys: '\n+ '`machete.github.{remote,organization,repository}`\\n'))\n \n- if len(org_and_repo_for_github_remote) == 1:\n- return list(org_and_repo_for_github_remote.items())[0]\n+ if len(remote_and_github_org_and_repo) == 1:\n+ return remote_and_github_org_and_repo[list(remote_and_github_org_and_repo.keys())[0]]\n \n- if 'origin' in org_and_repo_for_github_remote:\n- return 'origin', org_and_repo_for_github_remote['origin']\n+ if 'origin' in remote_and_github_org_and_repo:\n+ return remote_and_github_org_and_repo['origin']\n \n raise MacheteException(\n f'Multiple non-origin remotes correspond to GitHub in this repository: '\n- f'{\", \".join(org_and_repo_for_github_remote.keys())}, aborting')\n+ f'{\", \".join(remote_and_github_org_and_repo.keys())}, aborting. \\n'\n+ f'You can also select the repository by providing 3 git config keys: '\n+ '`machete.github.{remote,organization,repository}`\\n')\n+\n+ def __get_remote_and_organization_and_repository_name_for_custom_url(self) -> RemoteAndOrganizationAndRepository:\n+ return RemoteAndOrganizationAndRepository(remote=self.__git.get_config_attr_or_none(\"machete.github.remote\"),\n+ organization=self.__git.get_config_attr_or_none(\"machete.github.organization\"),\n+ repository=self.__git.get_config_attr_or_none(\"machete.github.repository\"))\n \n def create_github_pr(\n self, *, head: LocalBranchShortName, opt_draft: bool, opt_onto: Optional[LocalBranchShortName]) -> None:\n@@ -2096,7 +2084,7 @@ class MacheteClient:\n raise MacheteException(f'Could not determine base branch for PR. Branch `{head}` is a root branch.')\n org: str\n repo: str\n- remote, (org, repo) = self.__derive_remote_and_github_org_and_repo()\n+ remote, org, repo = self.__derive_remote_and_github_org_and_repo()\n print(f\"Fetching {remote}...\")\n self.__git.fetch_remote(remote)\n if '/'.join([remote, base]) not in self.__git.get_remote_branches():\ndiff --git a/git_machete/docs.py b/git_machete/docs.py\nindex d520d7b..ab16b25 100644\n--- a/git_machete/docs.py\n+++ b/git_machete/docs.py\n@@ -1,3 +1,4 @@\n+import textwrap\n from typing import Dict\n from git_machete.constants import DISCOVER_DEFAULT_FRESH_BRANCH_COUNT\n \n@@ -30,6 +31,29 @@ short_docs: Dict[str, str] = {\n \"version\": \"Display the version and exit\"\n }\n \n+github_api_access = '''To allow GitHub API access for private repositories (and also to perform side-effecting actions like opening a PR,\n+even in case of public repositories), a GitHub API token with `repo` scope is required, see https://github.com/settings/tokens.\n+This will be resolved from the first of:\n+ 1. `GITHUB_TOKEN` env var,\n+ 2. content of the `.github-token` file in the home directory (`~`),\n+ 3. current auth token from the `gh` GitHub CLI,\n+ 4. current auth token from the `hub` GitHub CLI.'''\n+\n+github_config_keys = '''GitHub API server URL will be inferred from `git remote`.\n+You can override this by setting the following git config keys:\n+ Remote name\n+ E.g. `machete.github.remote` = `origin`\n+ Organization name\n+ E.g. `machete.github.organization` = `VirtusLab`\n+ Repository name\n+ E.g. `machete.github.repository` = `git-machete`\n+\n+To do this, run `git config --local --edit` and add the following section:\n+ [machete \"github\"]\n+ organization = \n+ repository = \n+ remote = '''\n+\n long_docs: Dict[str, str] = {\n \"add\": \"\"\"\n Usage: git machete add [-o|--onto=] [-R|--as-root] [-y|--yes] []\n@@ -112,7 +136,7 @@ long_docs: Dict[str, str] = {\n -y, --yes Don't ask for confirmation whether to fast-forward the current branch or whether to slide-out the downstream.\n Fails if the current branch has more than one green-edge downstream branch.\n \"\"\",\n- \"anno\": \"\"\"\n+ \"anno\": f\"\"\"\n Usage:\n git machete anno [-b|--branch=] []\n git machete anno -H|--sync-github-prs\n@@ -126,12 +150,9 @@ long_docs: Dict[str, str] = {\n If invoked with `-H` or `--sync-github-prs`, annotates the branches based on their corresponding GitHub PR numbers and authors.\n Any existing annotations are overwritten for the branches that have an opened PR; annotations for the other branches remain untouched.\n \n- To allow GitHub API access for private repositories (and also to perform side-effecting actions like opening a PR, even in case of public repositories),\n- a GitHub API token with `repo` scope is required, see `https://github.com/settings/tokens`. This will be resolved from the first of:\n- 1. `GITHUB_TOKEN` env var,\n- 2. content of the `.github-token` file in the home directory (`~`),\n- 3. current auth token from the `gh` GitHub CLI,\n- 4. current auth token from the `hub` GitHub CLI.\n+{textwrap.indent(github_api_access, \" \")}\n+\n+{textwrap.indent(github_config_keys, \" \")}\n \n In any other case, sets the annotation for the given/current branch to the given argument.\n If multiple arguments are passed to the command, they are concatenated with a single space.\n@@ -142,9 +163,8 @@ long_docs: Dict[str, str] = {\n -b, --branch= Branch to set the annotation for.\n -H, --sync-github-prs Annotate with GitHub PR numbers and authors where applicable.\n \"\"\",\n- \"clean\": \"\"\"\n- Usage:\n- git machete clean [-c|--checkout-my-github-prs] [-y|--yes]\n+ \"clean\": f\"\"\"\n+ Usage: git machete clean [-c|--checkout-my-github-prs] [-y|--yes]\n \n Synchronizes with the remote repository:\n 1. if invoked with `-H` or `--checkout-my-github-prs`, checks out open PRs for the current user associated with the GitHub token and also traverses the chain of pull requests upwards, adding branches one by one to git-machete and checks them out locally as well,\n@@ -154,13 +174,9 @@ long_docs: Dict[str, str] = {\n No branch will be deleted unless explicitly confirmed by the user (or unless `-y/--yes` option is passed).\n Equivalent of `git machete github sync` if invoked with `-H` or `--checkout-my-github-prs`.\n \n- To allow GitHub API access for private repositories (and also to perform side-effecting actions like opening a PR, even in case of public repositories),\n- a GitHub API token with `repo` scope is required, see https://github.com/settings/tokens. This will be resolved from the first of:\n+{textwrap.indent(github_api_access, \" \")}\n \n- 1. `GITHUB_TOKEN` env var,\n- 2. content of the `.github-token` file in the home directory (`~`),\n- 3. current auth token from the `gh` GitHub CLI,\n- 4. current auth token from the `hub` GitHub CLI.\n+{textwrap.indent(github_config_keys, \" \")}\n \n **Options:**\n --c, --checkout-my-github-prs Checkout your open PRs into local branches.\n@@ -327,18 +343,16 @@ long_docs: Dict[str, str] = {\n Tabs or any number of spaces can be used as indentation.\n It's only important to be consistent wrt. the sequence of characters used for indentation between all lines.\n \"\"\",\n- \"github\": \"\"\"\n+ \"github\": f\"\"\"\n Usage: git machete github \n where is one of: `anno-prs`, `checkout-prs`, `create-pr`, `retarget-pr`, `sync`.\n \n Creates, checks out and manages GitHub PRs while keeping them reflected in branch definition file.\n \n- To allow GitHub API access for private repositories (and also to perform side-effecting actions like opening a PR, even in case of public repositories),\n- a GitHub API token with `repo` scope is required, see `https://github.com/settings/tokens`. This will be resolved from the first of:\n- 1. `GITHUB_TOKEN` env var,\n- 2. content of the .github-token file in the home directory (`~`),\n- 3. current auth token from the `gh` GitHub CLI,\n- 4. current auth token from the `hub` GitHub CLI.\n+{textwrap.indent(github_api_access, \" \")}\n+\n+{textwrap.indent(github_config_keys, \" \")}\n+\n \n `anno-prs`:\n \ndiff --git a/git_machete/git_operations.py b/git_machete/git_operations.py\nindex 546dd42..10a43a1 100644\n--- a/git_machete/git_operations.py\n+++ b/git_machete/git_operations.py\n@@ -339,7 +339,7 @@ class GitContext:\n return self.__remotes_cached\n \n def get_url_of_remote(self, remote: str) -> str:\n- return self._popen_git(\"config\", \"--get\", f\"remote.{remote}.url\").strip() # 'git remote get-url' method has only been added in git v2.5.1\n+ return self.get_config_attr_or_none(f\"remote.{remote}.url\").strip() # 'git remote get-url' method has only been added in git v2.5.1\n \n def fetch_remote(self, remote: str) -> None:\n if remote not in self.__fetch_done_for:\ndiff --git a/git_machete/github.py b/git_machete/github.py\nindex 72af595..139bd83 100644\n--- a/git_machete/github.py\n+++ b/git_machete/github.py\n@@ -7,7 +7,7 @@ import re\n import shutil\n import subprocess\n from pathlib import Path\n-from typing import Any, Dict, List, Optional, Tuple\n+from typing import Any, Dict, List, NamedTuple, Optional\n import urllib.request\n import urllib.error\n \n@@ -15,7 +15,6 @@ from git_machete.utils import debug, fmt\n from git_machete.exceptions import MacheteException, UnprocessableEntityHTTPError\n from git_machete.git_operations import GitContext, LocalBranchShortName\n \n-\n GITHUB_TOKEN_ENV_VAR = 'GITHUB_TOKEN'\n # GitHub Enterprise deployments use alternate domains.\n # The logic in this module will need to be expanded to detect\n@@ -42,6 +41,12 @@ class GitHubPullRequest(object):\n return f\"PR #{self.number} by {self.user}: {self.head} -> {self.base}\"\n \n \n+class RemoteAndOrganizationAndRepository(NamedTuple):\n+ remote: str\n+ organization: str\n+ repository: str\n+\n+\n def __parse_pr_json(pr_json: Any) -> GitHubPullRequest:\n return GitHubPullRequest(number=int(pr_json['number']),\n user=pr_json['user']['login'],\n@@ -254,12 +259,14 @@ def is_github_remote_url(url: str) -> bool:\n return any((re.match(pattern, url) for pattern in GITHUB_REMOTE_PATTERNS))\n \n \n-def get_parsed_github_remote_url(url: str) -> Optional[Tuple[str, str]]:\n+def get_parsed_github_remote_url(url: str, remote: str) -> Optional[RemoteAndOrganizationAndRepository]:\n \n for pattern in GITHUB_REMOTE_PATTERNS:\n match = re.match(pattern, url)\n if match:\n- return match.group(1), match.group(2)\n+ return RemoteAndOrganizationAndRepository(remote=remote,\n+ organization=match.group(1),\n+ repository=match.group(2))\n return None\n \n \n", "test_patch": "diff --git a/tests/mockers.py b/tests/mockers.py\nindex f7cad10..7e76788 100644\n--- a/tests/mockers.py\n+++ b/tests/mockers.py\n@@ -103,6 +103,10 @@ class GitRepositorySandbox:\n self.execute(f'git remote add {remote} {url}')\n return self\n \n+ def remove_remote(self, remote: str) -> \"GitRepositorySandbox\":\n+ self.execute(f'git remote remove {remote}')\n+ return self\n+\n def add_git_config_key(self, key: str, value: str) -> \"GitRepositorySandbox\":\n self.execute(f'git config {key} {value}')\n return self\ndiff --git a/tests/test_github.py b/tests/test_github.py\nindex a3621fd..3af713a 100644\n--- a/tests/test_github.py\n+++ b/tests/test_github.py\n@@ -202,6 +202,38 @@ class TestGithub:\n \"\"\",\n )\n \n+ # Test anno-prs using custom remote URL provided by git config keys\n+ (\n+ self.repo_sandbox\n+ .remove_remote('new_origin')\n+ .add_git_config_key('machete.github.remote', 'custom_origin')\n+ .add_git_config_key('machete.github.organization', 'custom_user')\n+ .add_git_config_key('machete.github.repository', 'custom_repo')\n+ )\n+\n+ launch_command(\"discover\", \"-y\")\n+ launch_command('github', 'anno-prs')\n+ assert_command(\n+ [\"status\"],\n+ \"\"\"\n+ master\n+ |\n+ o-hotfix/add-trigger (diverged from origin)\n+ |\n+ o-ignore-trailing * PR #3 (github_user) (diverged from & older than origin)\n+\n+ develop\n+ |\n+ x-allow-ownership-link PR #7 (github_user) (ahead of origin)\n+ | |\n+ | x-build-chain (untracked)\n+ |\n+ o-call-ws PR #31 (github_user) (ahead of origin)\n+ |\n+ x-drop-constraint (untracked)\n+ \"\"\",\n+ )\n+\n git_api_state_for_test_create_pr = MockGitHubAPIState(\n [\n {\n@@ -705,7 +737,7 @@ class TestGithub:\n # check against wrong pr number\n repo: str\n org: str\n- (org, repo) = get_parsed_github_remote_url(self.repo_sandbox.remote_path)\n+ _, org, repo = get_parsed_github_remote_url(self.repo_sandbox.remote_path, remote='origin')\n expected_error_message = f\"PR #100 is not found in repository `{org}/{repo}`\"\n with pytest.raises(MacheteException) as e:\n launch_command('github', 'checkout-prs', '100')\n", "FAIL_TO_PASS": ["tests/test_github.py::TestGithub::test_github_anno_prs", "tests/test_github.py::TestGithub::test_github_checkout_prs"]}, {"instance_id": "virtuslab__git-machete-525", "base_commit": "91fc20b6976a4bb63d3b72095667e1c9ff1799b1", "gold_patch": "diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md\nindex 64c9190..415d7be 100644\n--- a/RELEASE_NOTES.md\n+++ b/RELEASE_NOTES.md\n@@ -1,5 +1,10 @@\n # Release notes\n \n+## New in git-machete 3.10.1\n+\n+- fixed: `git machete diff` doesn't crash when supplied with the short branch name (`develop`)\n+- fixed: `git machete {log, add, anno, fork-point, is-managed, show}` doesn't crash when supplied with the full branch name (`refs/heads/develop`)\n+\n ## New in git-machete 3.10.0\n \n - added: boolean git config key `machete.status.extraSpaceBeforeBranchName` that enable configurable rendering of `status` command\ndiff --git a/git_machete/__init__.py b/git_machete/__init__.py\nindex 3f3750c..e88098e 100644\n--- a/git_machete/__init__.py\n+++ b/git_machete/__init__.py\n@@ -1,1 +1,1 @@\n-__version__ = '3.10.0'\n+__version__ = '3.10.1'\ndiff --git a/git_machete/cli.py b/git_machete/cli.py\nindex 2bb1fee..fbfcb46 100644\n--- a/git_machete/cli.py\n+++ b/git_machete/cli.py\n@@ -13,7 +13,7 @@ from git_machete import utils\n from git_machete.client import MacheteClient\n from git_machete.docs import short_docs, long_docs\n from git_machete.exceptions import MacheteException, StopInteraction\n-from git_machete.git_operations import AnyRevision, GitContext, LocalBranchShortName, RemoteBranchShortName\n+from git_machete.git_operations import AnyBranchName, AnyRevision, GitContext, LocalBranchShortName, RemoteBranchShortName\n from git_machete.utils import fmt, underline, excluding, warn, AnsiEscapeCodes\n \n T = TypeVar('T')\n@@ -378,7 +378,7 @@ def update_cli_opts_using_parsed_args(\n \n for opt, arg in vars(parsed_args).items():\n if opt == \"branch\":\n- cli_opts.opt_branch = LocalBranchShortName.of(arg)\n+ cli_opts.opt_branch = AnyBranchName.of(arg)\n elif opt == \"checked_out_since\":\n cli_opts.opt_checked_out_since = arg\n elif opt == \"color\":\n@@ -475,9 +475,9 @@ def set_utils_global_variables(\n utils.verbose_mode = cli_opts.opt_verbose\n \n \n-def get_branch_arg_or_current_branch(\n- cli_opts: git_machete.options.CommandLineOptions, git_context: GitContext) -> LocalBranchShortName:\n- return cli_opts.opt_branch or git_context.get_current_branch()\n+def get_local_branch_short_name_from_arg_or_current_branch(\n+ branch_from_arg: Optional[AnyBranchName], git_context: GitContext) -> LocalBranchShortName:\n+ return LocalBranchShortName.of(branch_from_arg.replace('refs/heads/', '')) if branch_from_arg else git_context.get_current_branch()\n \n \n def exit_script(status_code: Optional[int] = None, error: Optional[BaseException] = None) -> None:\n@@ -540,7 +540,7 @@ def launch(orig_args: List[str]) -> None:\n should_perform_interactive_slide_out = MacheteClient.should_perform_interactive_slide_out(cmd)\n if cmd == \"add\":\n machete_client.read_definition_file(perform_interactive_slide_out=should_perform_interactive_slide_out)\n- branch = get_branch_arg_or_current_branch(cli_opts, git)\n+ branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)\n machete_client.add(\n branch=branch,\n opt_onto=cli_opts.opt_onto,\n@@ -560,7 +560,7 @@ def launch(orig_args: List[str]) -> None:\n if cli_opts.opt_sync_github_prs:\n machete_client.sync_annotations_to_github_prs()\n else:\n- branch = cli_opts.opt_branch or git.get_current_branch()\n+ branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)\n machete_client.expect_in_managed_branches(branch)\n if parsed_cli.annotation_text:\n machete_client.annotate(branch, parsed_cli.annotation_text)\n@@ -578,7 +578,8 @@ def launch(orig_args: List[str]) -> None:\n machete_client.delete_unmanaged(opt_yes=cli_opts.opt_yes)\n elif cmd in {\"diff\", alias_by_command[\"diff\"]}:\n machete_client.read_definition_file(perform_interactive_slide_out=should_perform_interactive_slide_out)\n- machete_client.diff(branch=parsed_cli.branch, opt_stat=cli_opts.opt_stat) # passing None if not specified\n+ machete_client.diff(branch=get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git),\n+ opt_stat=cli_opts.opt_stat) # passing None if not specified\n elif cmd == \"discover\":\n # No need to read definition file.\n machete_client.discover_tree(\n@@ -594,7 +595,7 @@ def launch(orig_args: List[str]) -> None:\n print(os.path.abspath(machete_client.definition_file_path))\n elif cmd == \"fork-point\":\n machete_client.read_definition_file(perform_interactive_slide_out=should_perform_interactive_slide_out)\n- branch = get_branch_arg_or_current_branch(cli_opts, git)\n+ branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)\n if cli_opts.opt_inferred:\n print(machete_client.fork_point(\n branch=branch,\n@@ -670,7 +671,7 @@ def launch(orig_args: List[str]) -> None:\n machete_client.delete_untracked(opt_yes=cli_opts.opt_yes)\n elif cmd == \"is-managed\":\n machete_client.read_definition_file(perform_interactive_slide_out=should_perform_interactive_slide_out)\n- branch = get_branch_arg_or_current_branch(cli_opts, git)\n+ branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)\n if branch is None or branch not in machete_client.managed_branches:\n exit_script(1)\n elif cmd == \"list\":\n@@ -714,7 +715,7 @@ def launch(orig_args: List[str]) -> None:\n print(\"\\n\".join(res))\n elif cmd in {\"log\", alias_by_command[\"log\"]}:\n machete_client.read_definition_file(perform_interactive_slide_out=should_perform_interactive_slide_out)\n- branch = get_branch_arg_or_current_branch(cli_opts, git)\n+ branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)\n machete_client.log(branch)\n elif cmd == \"reapply\":\n machete_client.read_definition_file(perform_interactive_slide_out=should_perform_interactive_slide_out)\n@@ -732,7 +733,7 @@ def launch(orig_args: List[str]) -> None:\n cli_opts.opt_no_interactive_rebase)\n elif cmd == \"show\":\n direction = parsed_cli.direction\n- branch = get_branch_arg_or_current_branch(cli_opts, git)\n+ branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)\n if direction == \"current\":\n if 'branch' in parsed_cli:\n raise MacheteException(\ndiff --git a/git_machete/options.py b/git_machete/options.py\nindex e8f854f..6d60661 100644\n--- a/git_machete/options.py\n+++ b/git_machete/options.py\n@@ -1,14 +1,14 @@\n from typing import Optional, List\n \n from git_machete.exceptions import MacheteException\n-from git_machete.git_operations import AnyRevision, LocalBranchShortName\n+from git_machete.git_operations import AnyBranchName, AnyRevision, LocalBranchShortName\n \n \n class CommandLineOptions:\n \n def __init__(self) -> None:\n self.opt_as_root: bool = False\n- self.opt_branch: Optional[LocalBranchShortName] = None\n+ self.opt_branch: Optional[AnyBranchName] = None\n self.opt_checked_out_since: Optional[str] = None\n self.opt_color: str = \"auto\"\n self.opt_debug: bool = False\n", "test_patch": "diff --git a/tests/mockers.py b/tests/mockers.py\nindex 7e76788..d4199cb 100644\n--- a/tests/mockers.py\n+++ b/tests/mockers.py\n@@ -27,21 +27,6 @@ def popen(command: str) -> str:\n return process.read().strip()\n \n \n-def get_current_commit_hash() -> FullCommitHash:\n- \"\"\"Returns hash of a commit of the current branch head.\"\"\"\n- return FullCommitHash.of(popen(\"git rev-parse HEAD\"))\n-\n-\n-def mock_run_cmd(cmd: str, *args: str, **kwargs: Any) -> int:\n- completed_process: subprocess.CompletedProcess[bytes] = subprocess.run(\n- [cmd] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)\n- exit_code: int = completed_process.returncode\n-\n- if exit_code != 0:\n- print(dim(f\"\\n\"), file=sys.stderr)\n- return completed_process.returncode\n-\n-\n class GitRepositorySandbox:\n second_remote_path = mkdtemp()\n \n@@ -78,6 +63,12 @@ class GitRepositorySandbox:\n self.execute(f'git commit -m \"{message}\"')\n return self\n \n+ def add_file_with_content_and_commit(self, file_name: str = 'file_name.txt', file_content: str = 'Some file content\\n', message: str = \"Some commit message.\") -> \"GitRepositorySandbox\":\n+ self.write_to_file(file_name=file_name, file_content=file_content)\n+ self.execute(f\"git add {file_name}\")\n+ self.execute(f'git commit -m \"{message}\"')\n+ return self\n+\n def commit_amend(self, message: str) -> \"GitRepositorySandbox\":\n self.execute(f'git commit --amend -m \"{message}\"')\n return self\n@@ -111,6 +102,11 @@ class GitRepositorySandbox:\n self.execute(f'git config {key} {value}')\n return self\n \n+ def write_to_file(self, file_name: str, file_content: str) -> \"GitRepositorySandbox\":\n+ with open(file_name, 'w') as f:\n+ f.write(file_content)\n+ return self\n+\n \n class MockGitHubAPIState:\n def __init__(self, pulls: List[Dict[str, Any]], issues: List[Dict[str, Any]] = None) -> None:\n@@ -341,6 +337,21 @@ def rewrite_definition_file(new_body: str) -> None:\n def_file.writelines(new_body)\n \n \n+def get_current_commit_hash() -> FullCommitHash:\n+ \"\"\"Returns hash of a commit of the current branch head.\"\"\"\n+ return FullCommitHash.of(popen(\"git rev-parse HEAD\"))\n+\n+\n+def mock_run_cmd(cmd: str, *args: str, **kwargs: Any) -> int:\n+ completed_process: subprocess.CompletedProcess[bytes] = subprocess.run(\n+ [cmd] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)\n+ exit_code: int = completed_process.returncode\n+\n+ if exit_code != 0:\n+ print(dim(f\"\\n\"), file=sys.stderr)\n+ return completed_process.returncode\n+\n+\n def mock_run_cmd_and_forward_stdout(cmd: str, *args: str, **kwargs: Any) -> int:\n completed_process: subprocess.CompletedProcess[bytes] = subprocess.run(\n [cmd] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, ** kwargs)\ndiff --git a/tests/test_add.py b/tests/test_add.py\nindex 1045e71..0a35cf1 100644\n--- a/tests/test_add.py\n+++ b/tests/test_add.py\n@@ -1,7 +1,6 @@\n from typing import Any\n \n-from .mockers import (GitRepositorySandbox, assert_command, launch_command,\n- mock_run_cmd)\n+from .mockers import (GitRepositorySandbox, assert_command, launch_command, mock_run_cmd)\n \n \n class TestAdd:\n@@ -40,13 +39,32 @@ class TestAdd:\n \n self.repo_sandbox.new_branch(\"bugfix/feature_fail\")\n \n+ # Test `git machete add` without providing the branch name\n assert_command(\n- ['add', '-y', 'bugfix/feature_fail'],\n+ ['add', '-y'],\n 'Adding `bugfix/feature_fail` onto the inferred upstream (parent) branch `develop`\\n'\n 'Added branch `bugfix/feature_fail` onto `develop`\\n',\n strip_indentation=False\n )\n \n+ self.repo_sandbox.check_out('develop')\n+ self.repo_sandbox.new_branch(\"bugfix/some_feature\")\n+ assert_command(\n+ ['add', '-y', 'bugfix/some_feature'],\n+ 'Adding `bugfix/some_feature` onto the inferred upstream (parent) branch `develop`\\n'\n+ 'Added branch `bugfix/some_feature` onto `develop`\\n',\n+ strip_indentation=False\n+ )\n+\n+ self.repo_sandbox.check_out('develop')\n+ self.repo_sandbox.new_branch(\"bugfix/another_feature\")\n+ assert_command(\n+ ['add', '-y', 'refs/heads/bugfix/another_feature'],\n+ 'Adding `bugfix/another_feature` onto the inferred upstream (parent) branch `develop`\\n'\n+ 'Added branch `bugfix/another_feature` onto `develop`\\n',\n+ strip_indentation=False\n+ )\n+\n # test with --onto option\n self.repo_sandbox.new_branch(\"chore/remove_indentation\")\n \ndiff --git a/tests/test_anno.py b/tests/test_anno.py\nnew file mode 100644\nindex 0000000..f912764\n--- /dev/null\n+++ b/tests/test_anno.py\n@@ -0,0 +1,72 @@\n+from .mockers import (GitRepositorySandbox, assert_command, launch_command)\n+\n+\n+class TestAnno:\n+\n+ def setup_method(self) -> None:\n+\n+ self.repo_sandbox = GitRepositorySandbox()\n+\n+ (\n+ self.repo_sandbox\n+ # Create the remote and sandbox repos, chdir into sandbox repo\n+ .new_repo(self.repo_sandbox.remote_path, \"--bare\")\n+ .new_repo(self.repo_sandbox.local_path)\n+ .execute(f\"git remote add origin {self.repo_sandbox.remote_path}\")\n+ .execute('git config user.email \"tester@test.com\"')\n+ .execute('git config user.name \"Tester Test\"')\n+ )\n+\n+ def test_anno(self) -> None:\n+ \"\"\"\n+ Verify behaviour of a 'git machete anno' command.\n+ \"\"\"\n+\n+ (\n+ self.repo_sandbox.new_branch(\"master\")\n+ .commit(\"master commit.\")\n+ .new_branch(\"develop\")\n+ .commit(\"develop commit.\")\n+ .new_branch(\"feature\")\n+ .commit(\"feature commit.\")\n+ .check_out(\"develop\")\n+ .commit(\"New commit on develop\")\n+ )\n+ launch_command('discover', '-y')\n+\n+ # Test `git machete anno` without providing the branch name\n+ launch_command('anno', 'Custom annotation for `develop` branch')\n+ assert_command(\n+ [\"status\"],\n+ \"\"\"\n+ master (untracked)\n+\n+ develop * Custom annotation for `develop` branch (untracked)\n+ |\n+ x-feature (untracked)\n+ \"\"\",\n+ )\n+\n+ launch_command('anno', '-b=feature', 'Custom annotation for `feature` branch')\n+ assert_command(\n+ [\"status\"],\n+ \"\"\"\n+ master (untracked)\n+\n+ develop * Custom annotation for `develop` branch (untracked)\n+ |\n+ x-feature Custom annotation for `feature` branch (untracked)\n+ \"\"\",\n+ )\n+\n+ launch_command('anno', '-b=refs/heads/feature', 'Custom annotation for `feature` branch')\n+ assert_command(\n+ [\"status\"],\n+ \"\"\"\n+ master (untracked)\n+\n+ develop * Custom annotation for `develop` branch (untracked)\n+ |\n+ x-feature Custom annotation for `feature` branch (untracked)\n+ \"\"\",\n+ )\ndiff --git a/tests/test_diff.py b/tests/test_diff.py\nnew file mode 100644\nindex 0000000..72d9c1a\n--- /dev/null\n+++ b/tests/test_diff.py\n@@ -0,0 +1,52 @@\n+from typing import Any\n+\n+from .mockers import (GitRepositorySandbox, assert_command, mock_run_cmd_and_forward_stdout)\n+\n+\n+class TestDiff:\n+\n+ def setup_method(self) -> None:\n+\n+ self.repo_sandbox = GitRepositorySandbox()\n+\n+ (\n+ self.repo_sandbox\n+ # Create the remote and sandbox repos, chdir into sandbox repo\n+ .new_repo(self.repo_sandbox.remote_path, \"--bare\")\n+ .new_repo(self.repo_sandbox.local_path)\n+ .execute(f\"git remote add origin {self.repo_sandbox.remote_path}\")\n+ .execute('git config user.email \"tester@test.com\"')\n+ .execute('git config user.name \"Tester Test\"')\n+ )\n+\n+ def test_diff(self, mocker: Any) -> None:\n+ \"\"\"\n+ Verify behaviour of a 'git machete diff' command.\n+ \"\"\"\n+ mocker.patch('git_machete.utils.run_cmd', mock_run_cmd_and_forward_stdout) # to hide git outputs in tests\n+ (\n+ self.repo_sandbox.new_branch(\"master\")\n+ .add_file_with_content_and_commit(message='master commit1')\n+ .push()\n+ .new_branch(\"develop\")\n+ .add_file_with_content_and_commit(file_name='develop_file_name.txt', file_content='Develop content\\n', message='develop commit')\n+ .push()\n+ )\n+\n+ expected_status_output = (\n+\"\"\"diff --git a/develop_file_name.txt b/develop_file_name.txt\n+new file mode 100644\n+index 0000000..a3bd4e5\n+--- /dev/null\n++++ b/develop_file_name.txt\n+@@ -0,0 +1 @@\n++Develop content\n+\n+\"\"\" # noqa: E122\n+ )\n+ # Test `git machete diff` without providing the branch name\n+ assert_command([\"diff\"], expected_status_output, strip_indentation=False)\n+\n+ assert_command([\"diff\", \"develop\"], expected_status_output, strip_indentation=False)\n+\n+ assert_command([\"diff\", \"refs/heads/develop\"], expected_status_output, strip_indentation=False)\ndiff --git a/tests/test_fork_point.py b/tests/test_fork_point.py\nnew file mode 100644\nindex 0000000..404bb40\n--- /dev/null\n+++ b/tests/test_fork_point.py\n@@ -0,0 +1,52 @@\n+from .mockers import (GitRepositorySandbox, assert_command, launch_command)\n+\n+import os\n+\n+\n+class TestForkPoint:\n+\n+ def setup_method(self) -> None:\n+\n+ self.repo_sandbox = GitRepositorySandbox()\n+\n+ (\n+ self.repo_sandbox\n+ # Create the remote and sandbox repos, chdir into sandbox repo\n+ .new_repo(self.repo_sandbox.remote_path, \"--bare\")\n+ .new_repo(self.repo_sandbox.local_path)\n+ .execute(f\"git remote add origin {self.repo_sandbox.remote_path}\")\n+ .execute('git config user.email \"tester@test.com\"')\n+ .execute('git config user.name \"Tester Test\"')\n+ )\n+\n+ def test_fork_point(self) -> None:\n+ \"\"\"\n+ Verify behaviour of a 'git machete fork-point' command.\n+ \"\"\"\n+ fixed_committer_and_author_date = 'Mon 20 Aug 2018 20:19:19 +0200'\n+ os.environ['GIT_COMMITTER_DATE'] = fixed_committer_and_author_date\n+ os.environ['GIT_AUTHOR_DATE'] = fixed_committer_and_author_date\n+ try:\n+ (\n+ self.repo_sandbox.new_branch(\"master\")\n+ .add_file_with_content_and_commit(message=\"master commit.\")\n+ .new_branch(\"develop\")\n+ .add_file_with_content_and_commit(file_content='develop content', message=\"develop commit.\")\n+ .new_branch(\"feature\")\n+ .commit('feature commit.')\n+ )\n+ finally:\n+ # Clean-up environment variables\n+ os.environ.pop('GIT_COMMITTER_DATE', None)\n+ os.environ.pop('GIT_AUTHOR_DATE', None)\n+\n+ launch_command('discover', '-y')\n+\n+ # Test `git machete fork-point` without providing the branch name\n+ # hash 67007ed30def3b9b658380b895a9f62b525286e0 corresponds to the commit on develop branch\n+ assert_command([\"fork-point\"], \"67007ed30def3b9b658380b895a9f62b525286e0\\n\", strip_indentation=False)\n+\n+ # hash 515319fa0ab47f372f6159bcc8ac27b43ee8a0ed corresponds to the commit on master branch\n+ assert_command([\"fork-point\", 'develop'], \"515319fa0ab47f372f6159bcc8ac27b43ee8a0ed\\n\", strip_indentation=False)\n+\n+ assert_command([\"fork-point\", 'refs/heads/develop'], \"515319fa0ab47f372f6159bcc8ac27b43ee8a0ed\\n\", strip_indentation=False)\ndiff --git a/tests/test_github.py b/tests/test_github.py\nindex 3af713a..90fe555 100644\n--- a/tests/test_github.py\n+++ b/tests/test_github.py\n@@ -199,7 +199,7 @@ class TestGithub:\n o-call-ws PR #31 (github_user) (ahead of origin)\n |\n x-drop-constraint (untracked)\n- \"\"\",\n+ \"\"\"\n )\n \n # Test anno-prs using custom remote URL provided by git config keys\ndiff --git a/tests/test_is_managed.py b/tests/test_is_managed.py\nnew file mode 100644\nindex 0000000..9fa7de4\n--- /dev/null\n+++ b/tests/test_is_managed.py\n@@ -0,0 +1,46 @@\n+import pytest\n+\n+from .mockers import (GitRepositorySandbox, launch_command)\n+\n+\n+class TestIsManaged:\n+\n+ def setup_method(self) -> None:\n+\n+ self.repo_sandbox = GitRepositorySandbox()\n+\n+ (\n+ self.repo_sandbox\n+ # Create the remote and sandbox repos, chdir into sandbox repo\n+ .new_repo(self.repo_sandbox.remote_path, \"--bare\")\n+ .new_repo(self.repo_sandbox.local_path)\n+ .execute(f\"git remote add origin {self.repo_sandbox.remote_path}\")\n+ .execute('git config user.email \"tester@test.com\"')\n+ .execute('git config user.name \"Tester Test\"')\n+ )\n+\n+ def test_is_managed(self) -> None:\n+ \"\"\"\n+ Verify behaviour of a 'git machete is-managed' command.\n+ \"\"\"\n+ (\n+ self.repo_sandbox.new_branch(\"master\")\n+ .commit(\"master commit.\")\n+ .new_branch(\"develop\")\n+ .commit(\"develop commit.\")\n+ .new_branch(\"feature\")\n+ .commit(\"feature commit.\")\n+ .check_out(\"develop\")\n+ .commit(\"New commit on develop\")\n+ )\n+ launch_command(\"discover\", \"-y\")\n+\n+ # Test `git machete is-managed` without providing the branch name\n+ launch_command('is-managed')\n+\n+ launch_command('is-managed', 'develop')\n+\n+ launch_command('is-managed', 'refs/heads/develop')\n+\n+ with pytest.raises(SystemExit):\n+ launch_command('is-managed', 'random_branch_name')\ndiff --git a/tests/test_log.py b/tests/test_log.py\nindex 706f4c5..263e78b 100644\n--- a/tests/test_log.py\n+++ b/tests/test_log.py\n@@ -1,7 +1,6 @@\n from typing import Any\n \n-from .mockers import (GitRepositorySandbox, get_current_commit_hash,\n- launch_command, mock_run_cmd_and_forward_stdout)\n+from .mockers import (GitRepositorySandbox, get_current_commit_hash, launch_command, mock_run_cmd_and_forward_stdout)\n \n \n class TestLog:\n@@ -34,17 +33,17 @@ class TestLog:\n self.repo_sandbox.commit()\n childs_second_commit_hash = get_current_commit_hash()\n \n- log_content = launch_command('log')\n+ log_contents = [launch_command('log'), launch_command('log', 'child'), launch_command('log', 'refs/heads/child')]\n \n- assert childs_first_commit_hash in log_content, \\\n+ assert all(childs_first_commit_hash in log_content for log_content in log_contents), \\\n (\"Verify that oldest commit from current branch is visible when \"\n \"executing `git machete log`.\"\n )\n- assert childs_second_commit_hash in log_content, \\\n+ assert all(childs_second_commit_hash in log_content for log_content in log_contents), \\\n (\"Verify that youngest commit from current branch is visible when \"\n \"executing `git machete log`.\"\n )\n- assert roots_only_commit_hash not in log_content, \\\n+ assert all(roots_only_commit_hash not in log_content for log_content in log_contents), \\\n (\"Verify that commits from parent branch are not visible when \"\n \"executing `git machete log`.\"\n )\ndiff --git a/tests/test_show.py b/tests/test_show.py\nindex 49378e3..3ece362 100644\n--- a/tests/test_show.py\n+++ b/tests/test_show.py\n@@ -1,7 +1,6 @@\n from typing import Any\n \n-from .mockers import (GitRepositorySandbox, assert_command, launch_command,\n- mock_run_cmd)\n+from .mockers import (GitRepositorySandbox, assert_command, launch_command, mock_run_cmd)\n \n \n class TestShow:\n@@ -80,7 +79,7 @@ class TestShow:\n o-hotfix/add-trigger (diverged from origin)\n |\n o-ignore-trailing * (diverged from & older than origin)\n- \"\"\",\n+ \"\"\"\n )\n \n def test_show(self, mocker: Any) -> None:\n@@ -90,6 +89,7 @@ class TestShow:\n \n assert launch_command(\"show\", \"up\").strip() == \"hotfix/add-trigger\"\n assert launch_command(\"show\", \"up\", \"call-ws\").strip() == \"develop\"\n+ assert launch_command(\"show\", \"up\", \"refs/heads/call-ws\").strip() == \"develop\"\n assert launch_command(\"show\", \"current\").strip() == \"ignore-trailing\"\n \n def test_show_up(self, mocker: Any) -> None:\ndiff --git a/tests/test_traverse.py b/tests/test_traverse.py\nindex 9d5efe2..9906333 100644\n--- a/tests/test_traverse.py\n+++ b/tests/test_traverse.py\n@@ -80,7 +80,7 @@ class TestTraverse:\n o-hotfix/add-trigger (diverged from origin)\n |\n o-ignore-trailing * (diverged from & older than origin)\n- \"\"\",\n+ \"\"\"\n )\n \n def test_traverse_no_push(self, mocker: Any) -> None:\n", "FAIL_TO_PASS": ["tests/test_anno.py::TestAnno::test_anno", "tests/test_fork_point.py::TestForkPoint::test_fork_point", "tests/test_is_managed.py::TestIsManaged::test_is_managed"]}], "all_FAIL_TO_PASS": ["tests/test_github.py::TestGithub::test_github_anno_prs", "tests/test_github.py::TestGithub::test_github_checkout_prs", "tests/test_anno.py::TestAnno::test_anno", "tests/test_fork_point.py::TestForkPoint::test_fork_point", "tests/test_is_managed.py::TestIsManaged::test_is_managed"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "crossgl__crosstl-202_x2", "level": 2, "source": "swerebenchv2", "repo": "CrossGL/crosstl", "image": "swerebenchv2/crossgl-crosstl:202-a4da57d", "base_commit": "a4da57d8408a35c00f0146a2e1ef08989301fb56", "num_bugs": 2, "bugs": [{"instance_id": "crossgl__crosstl-202", "base_commit": "a4da57d8408a35c00f0146a2e1ef08989301fb56", "gold_patch": "diff --git a/crosstl/src/backend/DirectX/DirectxAst.py b/crosstl/src/backend/DirectX/DirectxAst.py\nindex b314f05..2484e0a 100644\n--- a/crosstl/src/backend/DirectX/DirectxAst.py\n+++ b/crosstl/src/backend/DirectX/DirectxAst.py\n@@ -86,6 +86,15 @@ class ForNode(ASTNode):\n return f\"ForNode(init={self.init}, condition={self.condition}, update={self.update}, body={self.body})\"\n \n \n+class WhileNode(ASTNode):\n+ def __init__(self, condition, body):\n+ self.condition = condition\n+ self.body = body\n+\n+ def __repr__(self):\n+ return f\"WhileNode(condition={self.condition}, body={self.body})\"\n+\n+\n class ReturnNode(ASTNode):\n def __init__(self, value):\n self.value = value\ndiff --git a/crosstl/src/backend/DirectX/DirectxCrossGLCodeGen.py b/crosstl/src/backend/DirectX/DirectxCrossGLCodeGen.py\nindex 92f02b5..57f34de 100644\n--- a/crosstl/src/backend/DirectX/DirectxCrossGLCodeGen.py\n+++ b/crosstl/src/backend/DirectX/DirectxCrossGLCodeGen.py\n@@ -140,6 +140,8 @@ class HLSLToCrossGLConverter:\n code += f\"return {self.generate_expression(stmt.value, is_main)};\\n\"\n elif isinstance(stmt, ForNode):\n code += self.generate_for_loop(stmt, indent, is_main)\n+ elif isinstance(stmt, WhileNode):\n+ code += self.generate_while_loop(stmt, indent, is_main)\n elif isinstance(stmt, IfNode):\n code += self.generate_if_statement(stmt, indent, is_main)\n return code\n@@ -154,6 +156,14 @@ class HLSLToCrossGLConverter:\n code += \" \" * indent + \"}\\n\"\n return code\n \n+ def generate_while_loop(self, node, indent, is_main):\n+ condition = self.generate_expression(node.condition, is_main)\n+\n+ code = f\"while ({condition}) {{\\n\"\n+ code += self.generate_function_body(node.body, indent + 1, is_main)\n+ code += \" \" * indent + \"}\\n\"\n+ return code\n+\n def generate_if_statement(self, node, indent, is_main):\n condition = self.generate_expression(node.condition, is_main)\n \ndiff --git a/crosstl/src/backend/DirectX/DirectxLexer.py b/crosstl/src/backend/DirectX/DirectxLexer.py\nindex c42565b..c5a1574 100644\n--- a/crosstl/src/backend/DirectX/DirectxLexer.py\n+++ b/crosstl/src/backend/DirectX/DirectxLexer.py\n@@ -19,6 +19,7 @@ TOKENS = [\n (\"ELSE_IF\", r\"\\belse\\sif\\b\"),\n (\"ELSE\", r\"\\belse\\b\"),\n (\"FOR\", r\"\\bfor\\b\"),\n+ (\"WHILE\", r\"\\b\\while\\b\"),\n (\"REGISTER\", r\"\\bregister\\b\"),\n (\"IDENTIFIER\", r\"[a-zA-Z_][a-zA-Z0-9_]*\"),\n (\"NUMBER\", r\"\\d+(\\.\\d+)?\"),\n@@ -72,6 +73,7 @@ KEYWORDS = {\n \"if\": \"IF\",\n \"else\": \"ELSE\",\n \"for\": \"FOR\",\n+ \"while\": \"WHILE\",\n \"register\": \"REGISTER\",\n }\n \ndiff --git a/crosstl/src/backend/DirectX/DirectxParser.py b/crosstl/src/backend/DirectX/DirectxParser.py\nindex 61fd544..3dd6014 100644\n--- a/crosstl/src/backend/DirectX/DirectxParser.py\n+++ b/crosstl/src/backend/DirectX/DirectxParser.py\n@@ -2,6 +2,7 @@ from .DirectxAst import (\n AssignmentNode,\n BinaryOpNode,\n ForNode,\n+ WhileNode,\n FunctionCallNode,\n FunctionNode,\n IfNode,\n@@ -195,6 +196,8 @@ class HLSLParser:\n return self.parse_for_statement()\n elif self.current_token[0] == \"RETURN\":\n return self.parse_return_statement()\n+ elif self.current_token[0] == \"WHILE\":\n+ return self.parse_while_statement()\n else:\n return self.parse_expression_statement()\n \n@@ -340,6 +343,19 @@ class HLSLParser:\n \n return ForNode(init, condition, update, body)\n \n+ def parse_while_statement(self):\n+ self.eat(\"WHILE\")\n+ self.eat(\"LPAREN\")\n+\n+ # Parse condition\n+ condition = self.parse_expression()\n+ self.eat(\"RPAREN\")\n+\n+ # Parse body\n+ body = self.parse_block()\n+\n+ return WhileNode(condition, body)\n+\n def parse_return_statement(self):\n self.eat(\"RETURN\")\n value = self.parse_expression()\ndiff --git a/crosstl/src/translator/codegen/directx_codegen.py b/crosstl/src/translator/codegen/directx_codegen.py\nindex c013e40..e9de6f9 100644\n--- a/crosstl/src/translator/codegen/directx_codegen.py\n+++ b/crosstl/src/translator/codegen/directx_codegen.py\n@@ -258,6 +258,7 @@ class HLSLCodeGen:\n \"MULTIPLY\": \"*\",\n \"DIVIDE\": \"/\",\n \"BITWISE_XOR\": \"^\",\n+ \"BITWISE_AND\": \"&\",\n \"LESS_THAN\": \"<\",\n \"GREATER_THAN\": \">\",\n \"ASSIGN_ADD\": \"+=\",\ndiff --git a/crosstl/src/translator/codegen/metal_codegen.py b/crosstl/src/translator/codegen/metal_codegen.py\nindex 50cc592..11b5949 100644\n--- a/crosstl/src/translator/codegen/metal_codegen.py\n+++ b/crosstl/src/translator/codegen/metal_codegen.py\n@@ -343,6 +343,7 @@ class MetalCodeGen:\n \"MULTIPLY\": \"*\",\n \"DIVIDE\": \"/\",\n \"BITWISE_XOR\": \"^\",\n+ \"BITWISE_AND\": \"&\",\n \"LESS_THAN\": \"<\",\n \"GREATER_THAN\": \">\",\n \"ASSIGN_ADD\": \"+=\",\ndiff --git a/crosstl/src/translator/parser.py b/crosstl/src/translator/parser.py\nindex 4e4fb1c..e4e148e 100644\n--- a/crosstl/src/translator/parser.py\n+++ b/crosstl/src/translator/parser.py\n@@ -439,6 +439,7 @@ class Parser:\n \"BITWISE_SHIFT_RIGHT\",\n \"BITWISE_SHIFT_LEFT\",\n \"BITWISE_XOR\",\n+ \"BITWISE_AND\",\n \"ASSIGN_SHIFT_LEFT\",\n \"ASSIGN_SHIFT_RIGHT\",\n ]:\n@@ -507,6 +508,7 @@ class Parser:\n \"BITWISE_SHIFT_RIGHT\",\n \"BITWISE_SHIFT_LEFT\",\n \"BITWISE_XOR\",\n+ \"BITWISE_AND\",\n \"ASSIGN_SHIFT_LEFT\" \"ASSIGN_SHIFT_RIGHT\",\n ]:\n op = self.current_token[1]\n@@ -538,6 +540,7 @@ class Parser:\n \"BITWISE_SHIFT_RIGHT\",\n \"BITWISE_SHIFT_LEFT\",\n \"BITWISE_XOR\",\n+ \"BITWISE_AND\",\n \"EQUAL\",\n \"ASSIGN_AND\",\n \"ASSIGN_OR\",\n@@ -599,6 +602,7 @@ class Parser:\n \"BITWISE_SHIFT_RIGHT\",\n \"BITWISE_SHIFT_LEFT\",\n \"BITWISE_XOR\",\n+ \"BITWISE_AND\",\n \"ASSIGN_SHIFT_RIGHT\",\n \"ASSIGN_SHIFT_LEFT\",\n ]:\n@@ -790,6 +794,7 @@ class Parser:\n \"BITWISE_SHIFT_RIGHT\",\n \"BITWISE_SHIFT_LEFT\",\n \"BITWISE_XOR\",\n+ \"BITWISE_AND\",\n \"ASSIGN_SHIFT_RIGHT\",\n \"ASSIGN_SHIFT_LEFT\",\n ]:\n", "test_patch": "diff --git a/tests/test_backend/test_directx/test_codegen.py b/tests/test_backend/test_directx/test_codegen.py\nindex a7ca79d..ed7112b 100644\n--- a/tests/test_backend/test_directx/test_codegen.py\n+++ b/tests/test_backend/test_directx/test_codegen.py\n@@ -160,6 +160,56 @@ def test_for_codegen():\n pytest.fail(\"For loop parsing or code generation not implemented.\")\n \n \n+def test_while_codegen():\n+ code = \"\"\"\n+ struct VSInput {\n+ float4 position : POSITION;\n+ float4 color : TEXCOORD0;\n+ };\n+\n+ struct VSOutput {\n+ float4 out_position : TEXCOORD0;\n+ };\n+\n+ VSOutput VSMain(VSInput input) {\n+ VSOutput output;\n+ output.out_position = input.position;\n+ int i = 0;\n+ while (i < 10) {\n+ output.out_position = input.color;\n+ i = i + 1; // Increment the loop variable\n+ }\n+ return output;\n+ }\n+\n+ struct PSInput {\n+ float4 in_position : TEXCOORD0;\n+ };\n+\n+ struct PSOutput {\n+ float4 out_color : SV_TARGET0;\n+ };\n+\n+ PSOutput PSMain(PSInput input) {\n+ PSOutput output;\n+ output.out_color = input.in_position;\n+ int i = 0;\n+ while (i < 10) {\n+ output.out_color = float4(1.0, 1.0, 1.0, 1.0);\n+ i = i + 1; // Increment the loop variable\n+ }\n+ return output;\n+ }\n+ \"\"\"\n+ try:\n+ tokens = tokenize_code(code)\n+ ast = parse_code(tokens)\n+ generated_code = generate_code(ast)\n+ print(generated_code)\n+ except SyntaxError:\n+ pytest.fail(\"While loop parsing or code generation not implemented.\")\n+\n+\n def test_else_codegen():\n code = \"\"\"\n struct VSInput {\ndiff --git a/tests/test_backend/test_directx/test_parser.py b/tests/test_backend/test_directx/test_parser.py\nindex eed91e9..7d3cc2d 100644\n--- a/tests/test_backend/test_directx/test_parser.py\n+++ b/tests/test_backend/test_directx/test_parser.py\n@@ -75,6 +75,25 @@ def test_for_parsing():\n pytest.fail(\"for parsing not implemented.\")\n \n \n+def test_while_parsing():\n+ code = \"\"\"\n+ VSOutput VSMain(VSInput input) {\n+ VSOutput output;\n+ int i = 0;\n+ while (i < 10) {\n+ output.out_position = input.position;\n+ i = i + 1;\n+ }\n+ return output;\n+ }\n+ \"\"\"\n+ try:\n+ tokens = tokenize_code(code)\n+ parse_code(tokens)\n+ except SyntaxError:\n+ pytest.fail(\"while parsing not implemented\")\n+\n+\n def test_else_parsing():\n code = \"\"\"\n PSOutput PSMain(PSInput input) {\ndiff --git a/tests/test_translator/test_codegen/test_directx_codegen.py b/tests/test_translator/test_codegen/test_directx_codegen.py\nindex 686dbf4..ca816a2 100644\n--- a/tests/test_translator/test_codegen/test_directx_codegen.py\n+++ b/tests/test_translator/test_codegen/test_directx_codegen.py\n@@ -559,5 +559,42 @@ def test_bitwise_operators():\n pytest.fail(\"Bitwise Shift codegen not implemented\")\n \n \n+def test_bitwise_and_operator():\n+ code = \"\"\"\n+ shader main {\n+ struct VSInput {\n+ vec2 texCoord @ TEXCOORD0;\n+ };\n+ struct VSOutput {\n+ vec4 color @ COLOR;\n+ };\n+ sampler2D iChannel0;\n+ vertex {\n+ VSOutput main(VSInput input) {\n+ VSOutput output;\n+ // Use bitwise AND on texture coordinates (for testing purposes)\n+ output.color = vec4(float(int(input.texCoord.x * 100.0) & 15), \n+ float(int(input.texCoord.y * 100.0) & 15), \n+ 0.0, 1.0);\n+ return output;\n+ }\n+ }\n+ fragment {\n+ vec4 main(VSOutput input) @ gl_FragColor {\n+ // Simple fragment shader to display the result of the AND operation\n+ return vec4(input.color.rgb, 1.0);\n+ }\n+ }\n+}\n+ \"\"\"\n+ try:\n+ tokens = tokenize_code(code)\n+ ast = parse_code(tokens)\n+ generated_code = generate_code(ast)\n+ print(generated_code)\n+ except SyntaxError:\n+ pytest.fail(\"Bitwise AND codegen not implemented\")\n+\n+\n if __name__ == \"__main__\":\n pytest.main()\ndiff --git a/tests/test_translator/test_parser.py b/tests/test_translator/test_parser.py\nindex 2bcd5c7..737e1d6 100644\n--- a/tests/test_translator/test_parser.py\n+++ b/tests/test_translator/test_parser.py\n@@ -551,5 +551,40 @@ def test_xor_operator():\n pytest.fail(\"Bitwise XOR not working\")\n \n \n+def test_and_operator():\n+ code = \"\"\"\n+ shader main {\n+ struct VSInput {\n+ vec2 texCoord @ TEXCOORD0;\n+ };\n+ struct VSOutput {\n+ vec4 color @ COLOR;\n+ };\n+ sampler2D iChannel0;\n+ vertex {\n+ VSOutput main(VSInput input) {\n+ VSOutput output;\n+ // Use bitwise AND on texture coordinates (for testing purposes)\n+ output.color = vec4(float(int(input.texCoord.x * 100.0) & 15), \n+ float(int(input.texCoord.y * 100.0) & 15), \n+ 0.0, 1.0);\n+ return output;\n+ }\n+ }\n+ fragment {\n+ vec4 main(VSOutput input) @ gl_FragColor {\n+ // Simple fragment shader to display the result of the AND operation\n+ return vec4(input.color.rgb, 1.0);\n+ }\n+ }\n+}\n+ \"\"\"\n+ try:\n+ tokens = tokenize_code(code)\n+ parse_code(tokens)\n+ except SyntaxError:\n+ pytest.fail(\"Bitwise AND not working\")\n+\n+\n if __name__ == \"__main__\":\n pytest.main()\n", "FAIL_TO_PASS": ["tests/test_backend/test_directx/test_codegen.py::test_while_codegen", "tests/test_backend/test_directx/test_parser.py::test_while_parsing"]}, {"instance_id": "crossgl__crosstl-207", "base_commit": "e2f2c2452273935cbb394848c9bb79903ee0a545", "gold_patch": "diff --git a/crosstl/src/backend/DirectX/DirectxLexer.py b/crosstl/src/backend/DirectX/DirectxLexer.py\nindex c5a1574..d6632a3 100644\n--- a/crosstl/src/backend/DirectX/DirectxLexer.py\n+++ b/crosstl/src/backend/DirectX/DirectxLexer.py\n@@ -45,6 +45,7 @@ TOKENS = [\n (\"DIVIDE_EQUALS\", r\"/=\"),\n (\"ASSIGN_XOR\", r\"\\^=\"),\n (\"ASSIGN_OR\", r\"\\|=\"),\n+ (\"ASSIGN_AND\", r\"\\&=\"),\n (\"AND\", r\"&&\"),\n (\"OR\", r\"\\|\\|\"),\n (\"DOT\", r\"\\.\"),\ndiff --git a/crosstl/src/backend/DirectX/DirectxParser.py b/crosstl/src/backend/DirectX/DirectxParser.py\nindex 3dd6014..2764649 100644\n--- a/crosstl/src/backend/DirectX/DirectxParser.py\n+++ b/crosstl/src/backend/DirectX/DirectxParser.py\n@@ -234,6 +234,7 @@ class HLSLParser:\n \"DIVIDE_EQUALS\",\n \"ASSIGN_XOR\",\n \"ASSIGN_OR\",\n+ \"ASSIGN_AND\",\n ]:\n # Handle assignment operators (e.g., =, +=, -=, ^=, etc.)\n op = self.current_token[1]\n@@ -250,6 +251,7 @@ class HLSLParser:\n \"DIVIDE_EQUALS\",\n \"ASSIGN_XOR\",\n \"ASSIGN_OR\",\n+ \"ASSIGN_AND\",\n ]:\n # Handle assignment operators (e.g., =, +=, -=, ^=, etc.)\n op = self.current_token[1]\n@@ -269,6 +271,7 @@ class HLSLParser:\n \"DIVIDE_EQUALS\",\n \"ASSIGN_XOR\",\n \"ASSIGN_OR\",\n+ \"ASSIGN_AND\",\n ]:\n op = self.current_token[1]\n self.eat(self.current_token[0])\n@@ -380,6 +383,7 @@ class HLSLParser:\n \"DIVIDE_EQUALS\",\n \"ASSIGN_XOR\",\n \"ASSIGN_OR\",\n+ \"ASSIGN_AND\",\n ]:\n op = self.current_token[1]\n self.eat(self.current_token[0])\n", "test_patch": "diff --git a/tests/test_backend/test_directx/test_codegen.py b/tests/test_backend/test_directx/test_codegen.py\nindex ed7112b..55ed1be 100644\n--- a/tests/test_backend/test_directx/test_codegen.py\n+++ b/tests/test_backend/test_directx/test_codegen.py\n@@ -386,7 +386,10 @@ def test_assignment_ops_parsing():\n output.redValue ^= 0x1;\n output.out_color.r = asfloat(redValue);\n \n- outpu.redValue |= 0x2;\n+ output.redValue |= 0x2;\n+\n+ output.redValue &= 0x3;\n+\n }\n \n return output;\ndiff --git a/tests/test_backend/test_directx/test_lexer.py b/tests/test_backend/test_directx/test_lexer.py\nindex 4cb364d..76ba0bc 100644\n--- a/tests/test_backend/test_directx/test_lexer.py\n+++ b/tests/test_backend/test_directx/test_lexer.py\n@@ -137,6 +137,10 @@ def test_assignment_ops_tokenization():\n uint redValue = asuint(output.out_color.r);\n redValue ^= 0x1;\n output.out_color.r = asfloat(redValue);\n+\n+ redValue |= 0x2;\n+\n+ redValue &= 0x3;\n }\n \n return output;\ndiff --git a/tests/test_backend/test_directx/test_parser.py b/tests/test_backend/test_directx/test_parser.py\nindex 7d3cc2d..5b1b702 100644\n--- a/tests/test_backend/test_directx/test_parser.py\n+++ b/tests/test_backend/test_directx/test_parser.py\n@@ -177,6 +177,8 @@ def test_assignment_ops_parsing():\n output.out_color.r = asfloat(redValue);\n \n output.redValue |= 0x2;\n+\n+ output.redValue &= 0x3;\n }\n \n return output;\n", "FAIL_TO_PASS": ["tests/test_backend/test_directx/test_codegen.py::test_assignment_ops_parsing", "tests/test_backend/test_directx/test_lexer.py::test_assignment_ops_tokenization", "tests/test_backend/test_directx/test_parser.py::test_assignment_ops_parsing"]}], "all_FAIL_TO_PASS": ["tests/test_backend/test_directx/test_codegen.py::test_while_codegen", "tests/test_backend/test_directx/test_parser.py::test_while_parsing", "tests/test_backend/test_directx/test_codegen.py::test_assignment_ops_parsing", "tests/test_backend/test_directx/test_lexer.py::test_assignment_ops_tokenization", "tests/test_backend/test_directx/test_parser.py::test_assignment_ops_parsing"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "python-attrs__attrs-500_x2", "level": 2, "source": "swerebenchv2", "repo": "python-attrs/attrs", "image": "swerebenchv2/python-attrs-attrs:500-a35d8fb", "base_commit": "a35d8fb4c4c057cc6778879f2d01ac7b9ac4b6ad", "num_bugs": 2, "bugs": [{"instance_id": "python-attrs__attrs-500", "base_commit": "a35d8fb4c4c057cc6778879f2d01ac7b9ac4b6ad", "gold_patch": "diff --git a/changelog.d/500.change.rst b/changelog.d/500.change.rst\nnew file mode 100644\nindex 0000000..c1a6402\n--- /dev/null\n+++ b/changelog.d/500.change.rst\n@@ -0,0 +1,3 @@\n+``attrs`` now has first class support for defining exception classes.\n+\n+If you define a class using ``@attr.s(auto_exc=True)`` and subclass an exception, the class will behave like a well-behaved exception class including an appropriate ``__str__`` method, and all attributes additionally available in an ``args`` attribute.\ndiff --git a/docs/api.rst b/docs/api.rst\nindex 3cd01a1..98ea845 100644\n--- a/docs/api.rst\n+++ b/docs/api.rst\n@@ -18,7 +18,7 @@ What follows is the API explanation, if you'd like a more hands-on introduction,\n Core\n ----\n \n-.. autofunction:: attr.s(these=None, repr_ns=None, repr=True, cmp=True, hash=None, init=True, slots=False, frozen=False, weakref_slot=True, str=False, auto_attribs=False, kw_only=False, cache_hash=False)\n+.. autofunction:: attr.s(these=None, repr_ns=None, repr=True, cmp=True, hash=None, init=True, slots=False, frozen=False, weakref_slot=True, str=False, auto_attribs=False, kw_only=False, cache_hash=False, auto_exc=False)\n \n .. note::\n \n@@ -42,6 +42,20 @@ Core\n >>> D = attr.s(these={\"x\": attr.ib()}, init=False)(D)\n >>> D(1)\n D(x=1)\n+ >>> @attr.s(auto_exc=True)\n+ ... class Error(Exception):\n+ ... x = attr.ib()\n+ ... y = attr.ib(default=42, init=False)\n+ >>> Error(\"foo\")\n+ Error(x='foo', y=42)\n+ >>> raise Error(\"foo\")\n+ Traceback (most recent call last):\n+ ...\n+ Error: ('foo', 42)\n+ >>> raise ValueError(\"foo\", 42) # for comparison\n+ Traceback (most recent call last):\n+ ...\n+ ValueError: ('foo', 42)\n \n \n .. autofunction:: attr.ib\ndiff --git a/src/attr/__init__.pyi b/src/attr/__init__.pyi\nindex ea788ea..fcb93b1 100644\n--- a/src/attr/__init__.pyi\n+++ b/src/attr/__init__.pyi\n@@ -167,6 +167,7 @@ def attrs(\n auto_attribs: bool = ...,\n kw_only: bool = ...,\n cache_hash: bool = ...,\n+ auto_exc: bool = ...,\n ) -> _C: ...\n @overload\n def attrs(\n@@ -184,6 +185,7 @@ def attrs(\n auto_attribs: bool = ...,\n kw_only: bool = ...,\n cache_hash: bool = ...,\n+ auto_exc: bool = ...,\n ) -> Callable[[_C], _C]: ...\n \n # TODO: add support for returning NamedTuple from the mypy plugin\n@@ -212,6 +214,7 @@ def make_class(\n auto_attribs: bool = ...,\n kw_only: bool = ...,\n cache_hash: bool = ...,\n+ auto_exc: bool = ...,\n ) -> type: ...\n \n # _funcs --\ndiff --git a/src/attr/_make.py b/src/attr/_make.py\nindex 843c76b..043edef 100644\n--- a/src/attr/_make.py\n+++ b/src/attr/_make.py\n@@ -453,6 +453,7 @@ class _ClassBuilder(object):\n \"_has_post_init\",\n \"_delete_attribs\",\n \"_base_attr_map\",\n+ \"_is_exc\",\n )\n \n def __init__(\n@@ -465,6 +466,7 @@ class _ClassBuilder(object):\n auto_attribs,\n kw_only,\n cache_hash,\n+ is_exc,\n ):\n attrs, base_attrs, base_map = _transform_attrs(\n cls, these, auto_attribs, kw_only\n@@ -482,6 +484,7 @@ class _ClassBuilder(object):\n self._cache_hash = cache_hash\n self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n self._delete_attribs = not bool(these)\n+ self._is_exc = is_exc\n \n self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n \n@@ -688,6 +691,7 @@ class _ClassBuilder(object):\n self._slots,\n self._cache_hash,\n self._base_attr_map,\n+ self._is_exc,\n )\n )\n \n@@ -738,6 +742,7 @@ def attrs(\n auto_attribs=False,\n kw_only=False,\n cache_hash=False,\n+ auto_exc=False,\n ):\n r\"\"\"\n A class decorator that adds `dunder\n@@ -847,6 +852,19 @@ def attrs(\n fields involved in hash code computation or mutations of the objects\n those fields point to after object creation. If such changes occur,\n the behavior of the object's hash code is undefined.\n+ :param bool auto_exc: If the class subclasses :class:`BaseException`\n+ (which implicitly includes any subclass of any exception), the\n+ following happens to behave like a well-behaved Python exceptions\n+ class:\n+\n+ - the values for *cmp* and *hash* are ignored and the instances compare\n+ and hash by the instance's ids (N.B. ``attrs`` will *not* remove\n+ existing implementations of ``__hash__`` or the equality methods. It\n+ just won't add own ones.),\n+ - all attributes that are either passed into ``__init__`` or have a\n+ default value are additionally available as a tuple in the ``args``\n+ attribute,\n+ - the value of *str* is ignored leaving ``__str__`` to base classes.\n \n .. versionadded:: 16.0.0 *slots*\n .. versionadded:: 16.1.0 *frozen*\n@@ -866,12 +884,16 @@ def attrs(\n to each other.\n .. versionadded:: 18.2.0 *kw_only*\n .. versionadded:: 18.2.0 *cache_hash*\n+ .. versionadded:: 19.1.0 *auto_exc*\n \"\"\"\n \n def wrap(cls):\n+\n if getattr(cls, \"__class__\", None) is None:\n raise TypeError(\"attrs only works with new-style classes.\")\n \n+ is_exc = auto_exc is True and issubclass(cls, BaseException)\n+\n builder = _ClassBuilder(\n cls,\n these,\n@@ -881,13 +903,14 @@ def attrs(\n auto_attribs,\n kw_only,\n cache_hash,\n+ is_exc,\n )\n \n if repr is True:\n builder.add_repr(repr_ns)\n if str is True:\n builder.add_str()\n- if cmp is True:\n+ if cmp is True and not is_exc:\n builder.add_cmp()\n \n if hash is not True and hash is not False and hash is not None:\n@@ -902,7 +925,11 @@ def attrs(\n \" hashing must be either explicitly or implicitly \"\n \"enabled.\"\n )\n- elif hash is True or (hash is None and cmp is True and frozen is True):\n+ elif (\n+ hash is True\n+ or (hash is None and cmp is True and frozen is True)\n+ and is_exc is False\n+ ):\n builder.add_hash()\n else:\n if cache_hash:\n@@ -1241,7 +1268,9 @@ def _add_repr(cls, ns=None, attrs=None):\n return cls\n \n \n-def _make_init(attrs, post_init, frozen, slots, cache_hash, base_attr_map):\n+def _make_init(\n+ attrs, post_init, frozen, slots, cache_hash, base_attr_map, is_exc\n+):\n attrs = [a for a in attrs if a.init or a.default is not NOTHING]\n \n # We cache the generated init methods for the same kinds of attributes.\n@@ -1250,16 +1279,18 @@ def _make_init(attrs, post_init, frozen, slots, cache_hash, base_attr_map):\n unique_filename = \"\".format(sha1.hexdigest())\n \n script, globs, annotations = _attrs_to_init_script(\n- attrs, frozen, slots, post_init, cache_hash, base_attr_map\n+ attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc\n )\n locs = {}\n bytecode = compile(script, unique_filename, \"exec\")\n attr_dict = dict((a.name, a) for a in attrs)\n globs.update({\"NOTHING\": NOTHING, \"attr_dict\": attr_dict})\n+\n if frozen is True:\n # Save the lookup overhead in __init__ if we need to circumvent\n # immutability.\n globs[\"_cached_setattr\"] = _obj_setattr\n+\n eval(bytecode, globs, locs)\n \n # In order of debuggers like PDB being able to step through the code,\n@@ -1273,6 +1304,7 @@ def _make_init(attrs, post_init, frozen, slots, cache_hash, base_attr_map):\n \n __init__ = locs[\"__init__\"]\n __init__.__annotations__ = annotations\n+\n return __init__\n \n \n@@ -1287,6 +1319,7 @@ def _add_init(cls, frozen):\n _is_slot_cls(cls),\n cache_hash=False,\n base_attr_map={},\n+ is_exc=False,\n )\n return cls\n \n@@ -1376,7 +1409,7 @@ def _is_slot_attr(a_name, base_attr_map):\n \n \n def _attrs_to_init_script(\n- attrs, frozen, slots, post_init, cache_hash, base_attr_map\n+ attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc\n ):\n \"\"\"\n Return a script of an initializer for *attrs* and a dict of globals.\n@@ -1625,6 +1658,13 @@ def _attrs_to_init_script(\n init_hash_cache = \"self.%s = %s\"\n lines.append(init_hash_cache % (_hash_cache_field, \"None\"))\n \n+ # For exceptions we rely on BaseException.__init__ for proper\n+ # initialization.\n+ if is_exc:\n+ vals = \",\".join(\"self.\" + a.name for a in attrs if a.init)\n+\n+ lines.append(\"BaseException.__init__(self, %s)\" % (vals,))\n+\n args = \", \".join(args)\n if kw_only_args:\n if PY2:\n", "test_patch": "diff --git a/tests/test_dark_magic.py b/tests/test_dark_magic.py\nindex e40fe93..bac2a01 100644\n--- a/tests/test_dark_magic.py\n+++ b/tests/test_dark_magic.py\n@@ -6,6 +6,8 @@ from __future__ import absolute_import, division, print_function\n \n import pickle\n \n+from copy import deepcopy\n+\n import pytest\n import six\n \n@@ -508,3 +510,68 @@ class TestDarkMagic(object):\n assert \"property\" == attr.fields(C).property.name\n assert \"itemgetter\" == attr.fields(C).itemgetter.name\n assert \"x\" == attr.fields(C).x.name\n+\n+ @pytest.mark.parametrize(\"slots\", [True, False])\n+ @pytest.mark.parametrize(\"frozen\", [True, False])\n+ def test_auto_exc(self, slots, frozen):\n+ \"\"\"\n+ Classes with auto_exc=True have a Exception-style __str__, are neither\n+ comparable nor hashable, and store the fields additionally in\n+ self.args.\n+ \"\"\"\n+\n+ @attr.s(auto_exc=True, slots=slots, frozen=frozen)\n+ class FooError(Exception):\n+ x = attr.ib()\n+ y = attr.ib(init=False, default=42)\n+ z = attr.ib(init=False)\n+ a = attr.ib()\n+\n+ FooErrorMade = attr.make_class(\n+ \"FooErrorMade\",\n+ bases=(Exception,),\n+ attrs={\n+ \"x\": attr.ib(),\n+ \"y\": attr.ib(init=False, default=42),\n+ \"z\": attr.ib(init=False),\n+ \"a\": attr.ib(),\n+ },\n+ auto_exc=True,\n+ slots=slots,\n+ frozen=frozen,\n+ )\n+\n+ assert FooError(1, \"foo\") != FooError(1, \"foo\")\n+ assert FooErrorMade(1, \"foo\") != FooErrorMade(1, \"foo\")\n+\n+ for cls in (FooError, FooErrorMade):\n+ with pytest.raises(cls) as ei:\n+ raise cls(1, \"foo\")\n+\n+ e = ei.value\n+\n+ assert e is e\n+ assert e == e\n+ assert \"(1, 'foo')\" == str(e)\n+ assert (1, \"foo\") == e.args\n+\n+ with pytest.raises(TypeError):\n+ hash(e)\n+\n+ if not frozen:\n+ deepcopy(e)\n+\n+ @pytest.mark.parametrize(\"slots\", [True, False])\n+ @pytest.mark.parametrize(\"frozen\", [True, False])\n+ def test_auto_exc_one_attrib(self, slots, frozen):\n+ \"\"\"\n+ Having one attribute works with auto_exc=True.\n+\n+ Easy to get wrong with tuple literals.\n+ \"\"\"\n+\n+ @attr.s(auto_exc=True, slots=slots, frozen=frozen)\n+ class FooError(Exception):\n+ x = attr.ib()\n+\n+ FooError(1)\ndiff --git a/tests/test_make.py b/tests/test_make.py\nindex a0597f1..61b4f63 100644\n--- a/tests/test_make.py\n+++ b/tests/test_make.py\n@@ -1425,7 +1425,9 @@ class TestClassBuilder(object):\n class C(object):\n pass\n \n- b = _ClassBuilder(C, None, True, True, False, False, False, False)\n+ b = _ClassBuilder(\n+ C, None, True, True, False, False, False, False, False\n+ )\n \n assert \"<_ClassBuilder(cls=C)>\" == repr(b)\n \n@@ -1437,7 +1439,9 @@ class TestClassBuilder(object):\n class C(object):\n x = attr.ib()\n \n- b = _ClassBuilder(C, None, True, True, False, False, False, False)\n+ b = _ClassBuilder(\n+ C, None, True, True, False, False, False, False, False\n+ )\n \n cls = (\n b.add_cmp()\n@@ -1500,6 +1504,7 @@ class TestClassBuilder(object):\n frozen=False,\n weakref_slot=True,\n auto_attribs=False,\n+ is_exc=False,\n kw_only=False,\n cache_hash=False,\n )\ndiff --git a/tests/typing_example.py b/tests/typing_example.py\nindex 527216f..b68ce6e 100644\n--- a/tests/typing_example.py\n+++ b/tests/typing_example.py\n@@ -80,6 +80,20 @@ HH(x=[1], y=[], z=1.1)\n c == cc\n \n \n+# Exceptions\n+@attr.s(auto_exc=True)\n+class Error(Exception):\n+ x = attr.ib()\n+\n+\n+try:\n+ raise Error(1)\n+except Error as e:\n+ e.x\n+ e.args\n+ str(e)\n+\n+\n # Converters\n # XXX: Currently converters can only be functions so none of this works\n # although the stubs should be correct.\n", "FAIL_TO_PASS": ["tests/test_dark_magic.py::TestDarkMagic::test_fields[C2]", "tests/test_dark_magic.py::TestDarkMagic::test_fields[C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_asdict[C1]", "tests/test_dark_magic.py::TestDarkMagic::test_asdict[C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_validator[C1]", "tests/test_dark_magic.py::TestDarkMagic::test_validator[C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_renaming", "tests/test_dark_magic.py::TestDarkMagic::test_programmatic", "tests/test_dark_magic.py::TestDarkMagic::test_subclassing_with_extra_attrs[Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_subclassing_with_extra_attrs[SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_subclass_without_extra_attrs[Base]", "tests/test_dark_magic.py::TestDarkMagic::test_subclass_without_extra_attrs[BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_instance[Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_instance[FrozenToo]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_subclassing_frozen_gives_frozen", "tests/test_dark_magic.py::TestDarkMagic::test_metaclass_preserved[WithMeta]", "tests/test_dark_magic.py::TestDarkMagic::test_metaclass_preserved[WithMetaSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_default_decorator", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_dict_patch_class", "tests/test_dark_magic.py::TestDarkMagic::test_hash_by_id", "tests/test_dark_magic.py::TestDarkMagic::test_handles_different_defaults", "tests/test_dark_magic.py::TestDarkMagic::test_hash_false_cmp_false[True]", "tests/test_dark_magic.py::TestDarkMagic::test_hash_false_cmp_false[False]", "tests/test_dark_magic.py::TestDarkMagic::test_overwrite_base", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_tuple_class_aliasing", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[False-False]", "tests/test_make.py::TestCountingAttr::test_returns_Attr", "tests/test_make.py::TestCountingAttr::test_validators_lists_to_wrapped_tuples", "tests/test_make.py::TestCountingAttr::test_validator_decorator_single", "tests/test_make.py::TestCountingAttr::test_validator_decorator[0]", "tests/test_make.py::TestCountingAttr::test_validator_decorator[1]", "tests/test_make.py::TestCountingAttr::test_validator_decorator[2]", "tests/test_make.py::TestCountingAttr::test_default_decorator_already_set", "tests/test_make.py::TestCountingAttr::test_default_decorator_sets", "tests/test_make.py::TestAttribute::test_deprecated_convert_argument", "tests/test_make.py::TestAttribute::test_deprecated_convert_attribute", "tests/test_make.py::TestAttribute::test_convert_converter", "tests/test_make.py::TestTransformAttrs::test_no_modifications", "tests/test_make.py::TestTransformAttrs::test_normal", "tests/test_make.py::TestTransformAttrs::test_empty", "tests/test_make.py::TestTransformAttrs::test_transforms_to_attribute", "tests/test_make.py::TestTransformAttrs::test_conflicting_defaults", "tests/test_make.py::TestTransformAttrs::test_kw_only", "tests/test_make.py::TestTransformAttrs::test_these", "tests/test_make.py::TestTransformAttrs::test_these_leave_body", "tests/test_make.py::TestTransformAttrs::test_these_ordered", "tests/test_make.py::TestTransformAttrs::test_multiple_inheritance", "tests/test_make.py::TestAttributes::test_sets_attrs", "tests/test_make.py::TestAttributes::test_empty", "tests/test_make.py::TestAttributes::test_immutable", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__repr__]", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__eq__]", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__hash__]", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__init__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[repr-__repr__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[cmp-__eq__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[hash-__hash__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[init-__init__]", "tests/test_make.py::TestAttributes::test_repr_qualname", "tests/test_make.py::TestAttributes::test_repr_fake_qualname", "tests/test_make.py::TestAttributes::test_name_not_overridden", "tests/test_make.py::TestAttributes::test_post_init", "tests/test_make.py::TestAttributes::test_types", "tests/test_make.py::TestAttributes::test_clean_class[True]", "tests/test_make.py::TestAttributes::test_clean_class[False]", "tests/test_make.py::TestAttributes::test_factory_sugar", "tests/test_make.py::TestAttributes::test_sugar_factory_mutex", "tests/test_make.py::TestAttributes::test_sugar_callable", "tests/test_make.py::TestKeywordOnlyAttributes::test_adds_keyword_only_arguments", "tests/test_make.py::TestKeywordOnlyAttributes::test_ignores_kw_only_when_init_is_false", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_attributes_presence", "tests/test_make.py::TestKeywordOnlyAttributes::test_conflicting_keyword_only_attributes", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_attributes_allow_subclassing", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_class_level", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_class_level_subclassing", "tests/test_make.py::TestKeywordOnlyAttributes::test_init_false_attribute_after_keyword_attribute", "tests/test_make.py::TestKeywordOnlyAttributes::test_init_false_attribute_after_keyword_attribute_with_inheritance", "tests/test_make.py::TestMakeClass::test_simple[list]", "tests/test_make.py::TestMakeClass::test_simple[tuple]", "tests/test_make.py::TestMakeClass::test_dict", "tests/test_make.py::TestMakeClass::test_attr_args", "tests/test_make.py::TestMakeClass::test_catches_wrong_attrs_type", "tests/test_make.py::TestMakeClass::test_bases", "tests/test_make.py::TestMakeClass::test_clean_class[True]", "tests/test_make.py::TestMakeClass::test_clean_class[False]", "tests/test_make.py::TestMakeClass::test_missing_sys_getframe", "tests/test_make.py::TestMakeClass::test_make_class_ordered", "tests/test_make.py::TestFields::test_instance", "tests/test_make.py::TestFields::test_handler_non_attrs_class", "tests/test_make.py::TestFields::test_fields", "tests/test_make.py::TestFields::test_fields_properties", "tests/test_make.py::TestFieldsDict::test_instance", "tests/test_make.py::TestFieldsDict::test_handler_non_attrs_class", "tests/test_make.py::TestFieldsDict::test_fields_dict", "tests/test_make.py::TestConverter::test_convert", "tests/test_make.py::TestConverter::test_convert_property", "tests/test_make.py::TestConverter::test_convert_factory_property", "tests/test_make.py::TestConverter::test_factory_takes_self", "tests/test_make.py::TestConverter::test_factory_hashable", "tests/test_make.py::TestConverter::test_convert_before_validate", "tests/test_make.py::TestConverter::test_frozen", "tests/test_make.py::TestConverter::test_deprecated_convert", "tests/test_make.py::TestConverter::test_convert_converter", "tests/test_make.py::TestValidate::test_success", "tests/test_make.py::TestValidate::test_propagates", "tests/test_make.py::TestValidate::test_run_validators", "tests/test_make.py::TestValidate::test_multiple_validators", "tests/test_make.py::TestValidate::test_multiple_empty", "tests/test_make.py::TestMetadata::test_metadata_present", "tests/test_make.py::TestMetadata::test_metadata_immutability", "tests/test_make.py::TestMetadata::test_empty_metadata_singleton", "tests/test_make.py::TestMetadata::test_empty_countingattr_metadata_independent", "tests/test_make.py::TestMetadata::test_not_none_metadata", "tests/test_make.py::TestMetadata::test_metadata", "tests/test_make.py::TestClassBuilder::test_repr_str", "tests/test_make.py::TestClassBuilder::test_repr", "tests/test_make.py::TestClassBuilder::test_returns_self", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__init__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__hash__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__repr__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__str__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__eq__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__ne__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__lt__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__le__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__gt__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__ge__]", "tests/test_make.py::TestClassBuilder::test_handles_missing_meta_on_class", "tests/test_make.py::TestClassBuilder::test_weakref_setstate", "tests/test_make.py::TestClassBuilder::test_no_references_to_original", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__lt__]", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__le__]", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__gt__]", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__ge__]"]}, {"instance_id": "python-attrs__attrs-556", "base_commit": "4a1b3a1436c375c72f80866c6ca145ff0e69086f", "gold_patch": "diff --git a/changelog.d/523.change.rst b/changelog.d/523.change.rst\nnew file mode 100644\nindex 0000000..86bf8cd\n--- /dev/null\n+++ b/changelog.d/523.change.rst\n@@ -0,0 +1,1 @@\n+When collecting attributes using ``@attr.s(auto_attribs=True)``, attributes with a default of ``None`` are now deleted too.\ndiff --git a/changelog.d/556.change.rst b/changelog.d/556.change.rst\nnew file mode 100644\nindex 0000000..86bf8cd\n--- /dev/null\n+++ b/changelog.d/556.change.rst\n@@ -0,0 +1,1 @@\n+When collecting attributes using ``@attr.s(auto_attribs=True)``, attributes with a default of ``None`` are now deleted too.\ndiff --git a/src/attr/_make.py b/src/attr/_make.py\nindex 2e96542..283aec6 100644\n--- a/src/attr/_make.py\n+++ b/src/attr/_make.py\n@@ -42,6 +42,9 @@ _hash_cache_field = \"_attrs_cached_hash\"\n \n _empty_metadata_singleton = metadata_proxy({})\n \n+# Unique object for unequivocal getattr() defaults.\n+_sentinel = object()\n+\n \n class _Nothing(object):\n \"\"\"\n@@ -504,7 +507,7 @@ class _ClassBuilder(object):\n for name in self._attr_names:\n if (\n name not in base_names\n- and getattr(cls, name, None) is not None\n+ and getattr(cls, name, _sentinel) != _sentinel\n ):\n try:\n delattr(cls, name)\n", "test_patch": "diff --git a/tests/test_annotations.py b/tests/test_annotations.py\nindex cbf5bd0..1f23f1d 100644\n--- a/tests/test_annotations.py\n+++ b/tests/test_annotations.py\n@@ -265,3 +265,20 @@ class TestAnnotations:\n x: int\n \n assert 1 == C(1).x\n+\n+ def test_removes_none_too(self):\n+ \"\"\"\n+ Regression test for #523: make sure defaults that are set to None are\n+ removed too.\n+ \"\"\"\n+\n+ @attr.s(auto_attribs=True)\n+ class C:\n+ x: int = 42\n+ y: typing.Any = None\n+\n+ with pytest.raises(AttributeError):\n+ C.x\n+\n+ with pytest.raises(AttributeError):\n+ C.y\n", "FAIL_TO_PASS": ["tests/test_annotations.py::TestAnnotations::test_removes_none_too"]}], "all_FAIL_TO_PASS": ["tests/test_dark_magic.py::TestDarkMagic::test_fields[C2]", "tests/test_dark_magic.py::TestDarkMagic::test_fields[C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_asdict[C1]", "tests/test_dark_magic.py::TestDarkMagic::test_asdict[C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_validator[C1]", "tests/test_dark_magic.py::TestDarkMagic::test_validator[C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_renaming", "tests/test_dark_magic.py::TestDarkMagic::test_programmatic", "tests/test_dark_magic.py::TestDarkMagic::test_subclassing_with_extra_attrs[Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_subclassing_with_extra_attrs[SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_subclass_without_extra_attrs[Base]", "tests/test_dark_magic.py::TestDarkMagic::test_subclass_without_extra_attrs[BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_instance[Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_instance[FrozenToo]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[2-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[3-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_attributes[4-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[2-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[3-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C1]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C1Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C2]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-C2Slots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-Base]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-BaseSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-Sub]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-SubSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-Frozen]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-FrozenNoSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_pickle_object[4-FromMakeClass]", "tests/test_dark_magic.py::TestDarkMagic::test_subclassing_frozen_gives_frozen", "tests/test_dark_magic.py::TestDarkMagic::test_metaclass_preserved[WithMeta]", "tests/test_dark_magic.py::TestDarkMagic::test_metaclass_preserved[WithMetaSlots]", "tests/test_dark_magic.py::TestDarkMagic::test_default_decorator", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_attrib_overwrite[False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_dict_patch_class", "tests/test_dark_magic.py::TestDarkMagic::test_hash_by_id", "tests/test_dark_magic.py::TestDarkMagic::test_handles_different_defaults", "tests/test_dark_magic.py::TestDarkMagic::test_hash_false_cmp_false[True]", "tests/test_dark_magic.py::TestDarkMagic::test_hash_false_cmp_false[False]", "tests/test_dark_magic.py::TestDarkMagic::test_overwrite_base", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-True-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[True-False-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-True-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-True-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-True-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-True-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-True-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_frozen_slots_combo[False-False-False-False-False-False-False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_tuple_class_aliasing", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc[False-False]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[True-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[True-False]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[False-True]", "tests/test_dark_magic.py::TestDarkMagic::test_auto_exc_one_attrib[False-False]", "tests/test_make.py::TestCountingAttr::test_returns_Attr", "tests/test_make.py::TestCountingAttr::test_validators_lists_to_wrapped_tuples", "tests/test_make.py::TestCountingAttr::test_validator_decorator_single", "tests/test_make.py::TestCountingAttr::test_validator_decorator[0]", "tests/test_make.py::TestCountingAttr::test_validator_decorator[1]", "tests/test_make.py::TestCountingAttr::test_validator_decorator[2]", "tests/test_make.py::TestCountingAttr::test_default_decorator_already_set", "tests/test_make.py::TestCountingAttr::test_default_decorator_sets", "tests/test_make.py::TestAttribute::test_deprecated_convert_argument", "tests/test_make.py::TestAttribute::test_deprecated_convert_attribute", "tests/test_make.py::TestAttribute::test_convert_converter", "tests/test_make.py::TestTransformAttrs::test_no_modifications", "tests/test_make.py::TestTransformAttrs::test_normal", "tests/test_make.py::TestTransformAttrs::test_empty", "tests/test_make.py::TestTransformAttrs::test_transforms_to_attribute", "tests/test_make.py::TestTransformAttrs::test_conflicting_defaults", "tests/test_make.py::TestTransformAttrs::test_kw_only", "tests/test_make.py::TestTransformAttrs::test_these", "tests/test_make.py::TestTransformAttrs::test_these_leave_body", "tests/test_make.py::TestTransformAttrs::test_these_ordered", "tests/test_make.py::TestTransformAttrs::test_multiple_inheritance", "tests/test_make.py::TestAttributes::test_sets_attrs", "tests/test_make.py::TestAttributes::test_empty", "tests/test_make.py::TestAttributes::test_immutable", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__repr__]", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__eq__]", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__hash__]", "tests/test_make.py::TestAttributes::test_adds_all_by_default[__init__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[repr-__repr__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[cmp-__eq__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[hash-__hash__]", "tests/test_make.py::TestAttributes::test_respects_add_arguments[init-__init__]", "tests/test_make.py::TestAttributes::test_repr_qualname", "tests/test_make.py::TestAttributes::test_repr_fake_qualname", "tests/test_make.py::TestAttributes::test_name_not_overridden", "tests/test_make.py::TestAttributes::test_post_init", "tests/test_make.py::TestAttributes::test_types", "tests/test_make.py::TestAttributes::test_clean_class[True]", "tests/test_make.py::TestAttributes::test_clean_class[False]", "tests/test_make.py::TestAttributes::test_factory_sugar", "tests/test_make.py::TestAttributes::test_sugar_factory_mutex", "tests/test_make.py::TestAttributes::test_sugar_callable", "tests/test_make.py::TestKeywordOnlyAttributes::test_adds_keyword_only_arguments", "tests/test_make.py::TestKeywordOnlyAttributes::test_ignores_kw_only_when_init_is_false", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_attributes_presence", "tests/test_make.py::TestKeywordOnlyAttributes::test_conflicting_keyword_only_attributes", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_attributes_allow_subclassing", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_class_level", "tests/test_make.py::TestKeywordOnlyAttributes::test_keyword_only_class_level_subclassing", "tests/test_make.py::TestKeywordOnlyAttributes::test_init_false_attribute_after_keyword_attribute", "tests/test_make.py::TestKeywordOnlyAttributes::test_init_false_attribute_after_keyword_attribute_with_inheritance", "tests/test_make.py::TestMakeClass::test_simple[list]", "tests/test_make.py::TestMakeClass::test_simple[tuple]", "tests/test_make.py::TestMakeClass::test_dict", "tests/test_make.py::TestMakeClass::test_attr_args", "tests/test_make.py::TestMakeClass::test_catches_wrong_attrs_type", "tests/test_make.py::TestMakeClass::test_bases", "tests/test_make.py::TestMakeClass::test_clean_class[True]", "tests/test_make.py::TestMakeClass::test_clean_class[False]", "tests/test_make.py::TestMakeClass::test_missing_sys_getframe", "tests/test_make.py::TestMakeClass::test_make_class_ordered", "tests/test_make.py::TestFields::test_instance", "tests/test_make.py::TestFields::test_handler_non_attrs_class", "tests/test_make.py::TestFields::test_fields", "tests/test_make.py::TestFields::test_fields_properties", "tests/test_make.py::TestFieldsDict::test_instance", "tests/test_make.py::TestFieldsDict::test_handler_non_attrs_class", "tests/test_make.py::TestFieldsDict::test_fields_dict", "tests/test_make.py::TestConverter::test_convert", "tests/test_make.py::TestConverter::test_convert_property", "tests/test_make.py::TestConverter::test_convert_factory_property", "tests/test_make.py::TestConverter::test_factory_takes_self", "tests/test_make.py::TestConverter::test_factory_hashable", "tests/test_make.py::TestConverter::test_convert_before_validate", "tests/test_make.py::TestConverter::test_frozen", "tests/test_make.py::TestConverter::test_deprecated_convert", "tests/test_make.py::TestConverter::test_convert_converter", "tests/test_make.py::TestValidate::test_success", "tests/test_make.py::TestValidate::test_propagates", "tests/test_make.py::TestValidate::test_run_validators", "tests/test_make.py::TestValidate::test_multiple_validators", "tests/test_make.py::TestValidate::test_multiple_empty", "tests/test_make.py::TestMetadata::test_metadata_present", "tests/test_make.py::TestMetadata::test_metadata_immutability", "tests/test_make.py::TestMetadata::test_empty_metadata_singleton", "tests/test_make.py::TestMetadata::test_empty_countingattr_metadata_independent", "tests/test_make.py::TestMetadata::test_not_none_metadata", "tests/test_make.py::TestMetadata::test_metadata", "tests/test_make.py::TestClassBuilder::test_repr_str", "tests/test_make.py::TestClassBuilder::test_repr", "tests/test_make.py::TestClassBuilder::test_returns_self", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__init__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__hash__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__repr__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__str__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__eq__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__ne__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__lt__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__le__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__gt__]", "tests/test_make.py::TestClassBuilder::test_attaches_meta_dunders[__ge__]", "tests/test_make.py::TestClassBuilder::test_handles_missing_meta_on_class", "tests/test_make.py::TestClassBuilder::test_weakref_setstate", "tests/test_make.py::TestClassBuilder::test_no_references_to_original", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__lt__]", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__le__]", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__gt__]", "tests/test_make.py::TestMakeCmp::test_subclasses_deprecated[__ge__]", "tests/test_annotations.py::TestAnnotations::test_removes_none_too"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "pylons__pyramid-3576_x2", "level": 2, "source": "swerebenchv2", "repo": "Pylons/pyramid", "image": "swerebenchv2/pylons-pyramid:3576-1722cbb", "base_commit": "1722cbb7bf40ce9d3793faf38f63e9f00d577613", "num_bugs": 2, "bugs": [{"instance_id": "pylons__pyramid-3576", "base_commit": "1722cbb7bf40ce9d3793faf38f63e9f00d577613", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 67256db8d..3bd14705d 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -4,6 +4,10 @@ unreleased\n Features\n --------\n \n+- It is now possible to pass multiple values to the ``header`` predicate\n+ for route and view configuration.\n+ See https://github.com/Pylons/pyramid/pull/3576\n+\n - Add support for Python 3.8.\n See https://github.com/Pylons/pyramid/pull/3547\n \ndiff --git a/docs/narr/viewconfig.rst b/docs/narr/viewconfig.rst\nindex 891d294d7..b43ebb93e 100644\n--- a/docs/narr/viewconfig.rst\n+++ b/docs/narr/viewconfig.rst\n@@ -391,7 +391,7 @@ configured view.\n the ``REQUEST_METHOD`` of the :term:`WSGI` environment.\n \n ``request_param``\n- This value can be any string or a sequence of strings. A view declaration\n+ This argument can be any string or a sequence of strings. A view declaration\n with this argument ensures that the view will only be called when the\n :term:`request` has a key in the ``request.params`` dictionary (an HTTP\n ``GET`` or ``POST`` variable) that has a name which matches the supplied\n@@ -406,7 +406,7 @@ configured view.\n consideration of keys and values in the ``request.params`` dictionary.\n \n ``match_param``\n- This param may be either a single string of the format \"key=value\" or a tuple\n+ This argument may be either a single string of the format \"key=value\" or a tuple\n containing one or more of these strings.\n \n This argument ensures that the view will only be called when the\n@@ -448,24 +448,23 @@ configured view.\n associated view callable.\n \n ``header``\n- This value represents an HTTP header name or a header name/value pair.\n-\n- If ``header`` is specified, it must be a header name or a\n- ``headername:headervalue`` pair.\n-\n- If ``header`` is specified without a value (a bare header name only, e.g.,\n- ``If-Modified-Since``), the view will only be invoked if the HTTP header\n- exists with any value in the request.\n-\n- If ``header`` is specified, and possesses a name/value pair (e.g.,\n- ``User-Agent:Mozilla/.*``), the view will only be invoked if the HTTP header\n- exists *and* the HTTP header matches the value requested. When the\n- ``headervalue`` contains a ``:`` (colon), it will be considered a name/value\n- pair (e.g., ``User-Agent:Mozilla/.*`` or ``Host:localhost``). The value\n- portion should be a regular expression.\n-\n- Whether or not the value represents a header name or a header name/value\n- pair, the case of the header name is not significant.\n+ This param matches one or more HTTP header names or header name/value pairs.\n+ If specified, this param must be a string or a sequence of strings,\n+ each string being a header name or a ``headername:headervalue`` pair.\n+\n+ - Each string specified as a bare header name without a value (for example\n+ ``If-Modified-Since``) will match a request if it contains an HTTP header\n+ with that same name. The case of the name is not significant, and the\n+ header may have any value in the request.\n+\n+ - Each string specified as a name/value pair (that is, if it contains a ``:``\n+ (colon), like ``User-Agent:Mozilla/.*``) will match a request only if it\n+ contains an HTTP header with the requested name (ignoring case, so\n+ ``User-Agent`` or ``user-agent`` would both match), *and* the value of the\n+ HTTP header matches the value requested (``Mozilla/.*`` in our example).\n+ The value portion is interpreted as a regular expression.\n+\n+ The view will only be invoked if all strings are matching.\n \n If ``header`` is not specified, the composition, presence, or absence of HTTP\n headers is not taken into consideration when deciding whether or not to\ndiff --git a/src/pyramid/config/routes.py b/src/pyramid/config/routes.py\nindex 9452a05ab..a12e18fa8 100644\n--- a/src/pyramid/config/routes.py\n+++ b/src/pyramid/config/routes.py\n@@ -211,31 +211,32 @@ class RoutesConfiguratorMixin:\n dictionary (an HTTP ``GET`` or ``POST`` variable) that has a\n name which matches the supplied value. If the value\n supplied as the argument has a ``=`` sign in it,\n- e.g. ``request_param=\"foo=123\"``, then the key\n- (``foo``) must both exist in the ``request.params`` dictionary, and\n+ e.g. ``request_param=\"foo=123\"``, then both the key\n+ (``foo``) must exist in the ``request.params`` dictionary, and\n the value must match the right hand side of the expression (``123``)\n for the route to \"match\" the current request. If this predicate\n returns ``False``, route matching continues.\n \n header\n \n- This argument represents an HTTP header name or a header\n- name/value pair. If the argument contains a ``:`` (colon),\n- it will be considered a name/value pair\n- (e.g. ``User-Agent:Mozilla/.*`` or ``Host:localhost``). If\n- the value contains a colon, the value portion should be a\n- regular expression. If the value does not contain a colon,\n- the entire value will be considered to be the header name\n- (e.g. ``If-Modified-Since``). If the value evaluates to a\n- header name only without a value, the header specified by\n- the name must be present in the request for this predicate\n- to be true. If the value evaluates to a header name/value\n- pair, the header specified by the name must be present in\n- the request *and* the regular expression specified as the\n- value must match the header value. Whether or not the value\n- represents a header name or a header name/value pair, the\n- case of the header name is not significant. If this\n- predicate returns ``False``, route matching continues.\n+ This argument can be a string or an iterable of strings for HTTP\n+ headers. The matching is determined as follow:\n+\n+ - If a string does not contain a ``:`` (colon), it will be\n+ considered to be the header name (example ``If-Modified-Since``).\n+ In this case, the header specified by the name must be present\n+ in the request for this string to match. Case is not significant.\n+\n+ - If a string contains a colon, it will be considered a\n+ name/value pair (for example ``User-Agent:Mozilla/.*`` or\n+ ``Host:localhost``), where the value part is a regular\n+ expression. The header specified by the name must be present\n+ in the request *and* the regular expression specified as the\n+ value part must match the value of the request header. Case is\n+ not significant for the header name, but it is for the value.\n+\n+ All strings must be matched for this predicate to return ``True``.\n+ If this predicate returns ``False``, route matching continues.\n \n accept\n \ndiff --git a/src/pyramid/config/views.py b/src/pyramid/config/views.py\nindex 6faa29d20..a064ebd05 100644\n--- a/src/pyramid/config/views.py\n+++ b/src/pyramid/config/views.py\n@@ -670,22 +670,24 @@ class ViewsConfiguratorMixin:\n \n header\n \n- This value represents an HTTP header name or a header\n- name/value pair. If the value contains a ``:`` (colon), it\n- will be considered a name/value pair\n- (e.g. ``User-Agent:Mozilla/.*`` or ``Host:localhost``). The\n- value portion should be a regular expression. If the value\n- does not contain a colon, the entire value will be\n- considered to be the header name\n- (e.g. ``If-Modified-Since``). If the value evaluates to a\n- header name only without a value, the header specified by\n- the name must be present in the request for this predicate\n- to be true. If the value evaluates to a header name/value\n- pair, the header specified by the name must be present in\n- the request *and* the regular expression specified as the\n- value must match the header value. Whether or not the value\n- represents a header name or a header name/value pair, the\n- case of the header name is not significant.\n+ This argument can be a string or an iterable of strings for HTTP\n+ headers. The matching is determined as follow:\n+\n+ - If a string does not contain a ``:`` (colon), it will be\n+ considered to be a header name (example ``If-Modified-Since``).\n+ In this case, the header specified by the name must be present\n+ in the request for this string to match. Case is not significant.\n+\n+ - If a string contains a colon, it will be considered a\n+ name/value pair (for example ``User-Agent:Mozilla/.*`` or\n+ ``Host:localhost``), where the value part is a regular\n+ expression. The header specified by the name must be present\n+ in the request *and* the regular expression specified as the\n+ value part must match the value of the request header. Case is\n+ not significant for the header name, but it is for the value.\n+\n+ All strings must be matched for this predicate to return ``True``.\n+ If this predicate returns ``False``, view matching continues.\n \n path_info\n \ndiff --git a/src/pyramid/predicates.py b/src/pyramid/predicates.py\nindex 8b443e79b..576bbbce6 100644\n--- a/src/pyramid/predicates.py\n+++ b/src/pyramid/predicates.py\n@@ -98,33 +98,43 @@ class RequestParamPredicate:\n \n class HeaderPredicate:\n def __init__(self, val, config):\n- name = val\n- v = None\n- if ':' in name:\n- name, val_str = name.split(':', 1)\n- try:\n- v = re.compile(val_str)\n- except re.error as why:\n- raise ConfigurationError(why.args[0])\n- if v is None:\n- self._text = 'header %s' % (name,)\n- else:\n- self._text = 'header %s=%s' % (name, val_str)\n- self.name = name\n- self.val = v\n+ values = []\n+\n+ val = as_sorted_tuple(val)\n+ for name in val:\n+ v, val_str = None, None\n+ if ':' in name:\n+ name, val_str = name.split(':', 1)\n+ try:\n+ v = re.compile(val_str)\n+ except re.error as why:\n+ raise ConfigurationError(why.args[0])\n+\n+ values.append((name, v, val_str))\n+\n+ self.val = values\n \n def text(self):\n- return self._text\n+ return 'header %s' % ', '.join(\n+ '%s=%s' % (name, val_str) if val_str else name\n+ for name, _, val_str in self.val\n+ )\n \n phash = text\n \n def __call__(self, context, request):\n- if self.val is None:\n- return self.name in request.headers\n- val = request.headers.get(self.name)\n- if val is None:\n- return False\n- return self.val.match(val) is not None\n+ for name, val, _ in self.val:\n+ if val is None:\n+ if name not in request.headers:\n+ return False\n+ else:\n+ value = request.headers.get(name)\n+ if value is None:\n+ return False\n+ if val.match(value) is None:\n+ return False\n+\n+ return True\n \n \n class AcceptPredicate:\n", "test_patch": "diff --git a/tests/test_config/test_predicates.py b/tests/test_config/test_predicates.py\nindex d1562947e..8017fc898 100644\n--- a/tests/test_config/test_predicates.py\n+++ b/tests/test_config/test_predicates.py\n@@ -312,6 +312,20 @@ class TestPredicateList(unittest.TestCase):\n self.assertEqual(predicates[10].text(), 'classmethod predicate')\n self.assertTrue(predicates[11].text().startswith('custom predicate'))\n \n+ def test_predicate_text_is_correct_when_multiple(self):\n+ _, predicates, _ = self._callFUT(\n+ request_method=('one', 'two'),\n+ request_param=('par2=on', 'par1'),\n+ header=('header2', 'header1:val.*'),\n+ accept=('accept1', 'accept2'),\n+ match_param=('foo=bar', 'baz=bim'),\n+ )\n+ self.assertEqual(predicates[0].text(), \"request_method = one,two\")\n+ self.assertEqual(predicates[1].text(), 'request_param par1,par2=on')\n+ self.assertEqual(predicates[2].text(), 'header header1=val.*, header2')\n+ self.assertEqual(predicates[3].text(), 'accept = accept1, accept2')\n+ self.assertEqual(predicates[4].text(), \"match_param baz=bim,foo=bar\")\n+\n def test_match_param_from_string(self):\n _, predicates, _ = self._callFUT(match_param='foo=bar')\n request = DummyRequest()\n@@ -354,6 +368,72 @@ class TestPredicateList(unittest.TestCase):\n hash2, _, __ = self._callFUT(request_method='GET')\n self.assertEqual(hash1, hash2)\n \n+ def test_header_simple(self):\n+ _, predicates, _ = self._callFUT(header='foo')\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'baz': 'foo'}\n+ self.assertTrue(predicates[0](Dummy(), request))\n+\n+ def test_header_simple_fails(self):\n+ _, predicates, _ = self._callFUT(header='content-length')\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'baz': 'foo'}\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n+ def test_header_with_value(self):\n+ _, predicates, _ = self._callFUT(header='foo:bar')\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'baz': 'foo'}\n+ self.assertTrue(predicates[0](Dummy(), request))\n+\n+ def test_header_with_value_fails(self):\n+ _, predicates, _ = self._callFUT(header='foo:bar')\n+ request = DummyRequest()\n+ request.headers = {'foo': 'nobar', 'baz': 'foo'}\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n+ def test_header_with_value_fails_case(self):\n+ _, predicates, _ = self._callFUT(header='foo:bar')\n+ request = DummyRequest()\n+ request.headers = {'foo': 'BAR'}\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n+ def test_header_multiple(self):\n+ _, predicates, _ = self._callFUT(header=('foo', 'content-length'))\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'content-length': '42'}\n+ self.assertTrue(predicates[0](Dummy(), request))\n+\n+ def test_header_multiple_fails(self):\n+ _, predicates, _ = self._callFUT(header=('foo', 'content-encoding'))\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'content-length': '42'}\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n+ def test_header_multiple_with_values(self):\n+ _, predicates, _ = self._callFUT(header=('foo:bar', 'spam:egg'))\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'spam': 'eggs'}\n+ self.assertTrue(predicates[0](Dummy(), request))\n+\n+ def test_header_multiple_with_values_fails(self):\n+ _, predicates, _ = self._callFUT(header=('foo:bar', 'spam:egg$'))\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'spam': 'eggs'}\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n+ def test_header_multiple_mixed(self):\n+ _, predicates, _ = self._callFUT(header=('foo:bar', 'spam'))\n+ request = DummyRequest()\n+ request.headers = {'foo': 'bars', 'spam': 'ham'}\n+ self.assertTrue(predicates[0](Dummy(), request))\n+\n+ def test_header_multiple_mixed_fails(self):\n+ _, predicates, _ = self._callFUT(header=('foo:bar', 'spam'))\n+ request = DummyRequest()\n+ request.headers = {'foo': 'nobar', 'spamme': 'ham'}\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n def test_unknown_predicate(self):\n from pyramid.exceptions import ConfigurationError\n \n@@ -472,6 +552,7 @@ class DummyRequest:\n environ = {}\n self.environ = environ\n self.params = {}\n+ self.headers = {}\n self.cookies = {}\n \n \n", "FAIL_TO_PASS": ["tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_mixed", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_with_values", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_text_is_correct_when_multiple"]}, {"instance_id": "pylons__pyramid-3598", "base_commit": "48a04855ad4f1f1ae6af934090f35a4ad035ed67", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 6b6e1ebbb..753997bf4 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -22,10 +22,13 @@ Features\n - ``pyramid.config.Configurator.set_security_policy``.\n - ``pyramid.interfaces.ISecurityPolicy``\n - ``pyramid.request.Request.authenticated_identity``.\n+ - ``pyramid.request.Request.is_authenticated``\n - ``pyramid.authentication.SessionAuthenticationHelper``\n - ``pyramid.authorization.ACLHelper``\n+ - ``is_authenticated=True/False`` predicate for route and view configs\n \n- See https://github.com/Pylons/pyramid/pull/3465\n+ See https://github.com/Pylons/pyramid/pull/3465 and\n+ https://github.com/Pylons/pyramid/pull/3598\n \n - Changed the default ``serializer`` on\n ``pyramid.session.SignedCookieSessionFactory`` to use\ndiff --git a/docs/narr/advanced-features.rst b/docs/narr/advanced-features.rst\nindex 6e819ff5b..6f3b4e11b 100644\n--- a/docs/narr/advanced-features.rst\n+++ b/docs/narr/advanced-features.rst\n@@ -34,7 +34,7 @@ For our example above, you can do this instead:\n .. code-block:: python\n :linenos:\n \n- @view_config(route_name=\"items\", effective_principals=pyramid.authorization.Authenticated)\n+ @view_config(route_name=\"items\", is_authenticated=True)\n def auth_view(request):\n # do one thing\n \ndiff --git a/docs/narr/viewconfig.rst b/docs/narr/viewconfig.rst\nindex b43ebb93e..de82fc075 100644\n--- a/docs/narr/viewconfig.rst\n+++ b/docs/narr/viewconfig.rst\n@@ -494,6 +494,15 @@ configured view.\n \n .. versionadded:: 1.4a3\n \n+``is_authenticated``\n+ This value, if specified, must be either ``True`` or ``False``.\n+ If it is specified and ``True``, only a request from an authenticated user, as\n+ determined by the :term:`security policy` in use, will satisfy the predicate.\n+ If it is specified and ``False``, only a request from a user who is not\n+ authenticated will satisfy the predicate.\n+\n+ .. versionadded:: 2.0\n+\n ``effective_principals``\n If specified, this value should be a :term:`principal` identifier or a\n sequence of principal identifiers. If the\n@@ -505,6 +514,9 @@ configured view.\n \n .. versionadded:: 1.4a4\n \n+ .. deprecated:: 2.0\n+ Use ``is_authenticated`` or a custom predicate.\n+\n ``custom_predicates``\n If ``custom_predicates`` is specified, it must be a sequence of references to\n custom predicate callables. Custom predicates can be combined with\ndiff --git a/src/pyramid/config/routes.py b/src/pyramid/config/routes.py\nindex a12e18fa8..4f3440c40 100644\n--- a/src/pyramid/config/routes.py\n+++ b/src/pyramid/config/routes.py\n@@ -268,6 +268,17 @@ class RoutesConfiguratorMixin:\n \n Removed support for media ranges.\n \n+ is_authenticated\n+\n+ This value, if specified, must be either ``True`` or ``False``.\n+ If it is specified and ``True``, only a request from an authenticated\n+ user, as determined by the :term:`security policy` in use, will\n+ satisfy the predicate.\n+ If it is specified and ``False``, only a request from a user who is\n+ not authenticated will satisfy the predicate.\n+\n+ .. versionadded:: 2.0\n+\n effective_principals\n \n If specified, this value should be a :term:`principal` identifier or\n@@ -282,6 +293,7 @@ class RoutesConfiguratorMixin:\n .. versionadded:: 1.4a4\n \n .. deprecated:: 2.0\n+ Use ``is_authenticated`` or a custom predicate.\n \n custom_predicates\n \n@@ -537,6 +549,7 @@ class RoutesConfiguratorMixin:\n ('request_param', p.RequestParamPredicate),\n ('header', p.HeaderPredicate),\n ('accept', p.AcceptPredicate),\n+ ('is_authenticated', p.IsAuthenticatedPredicate),\n ('effective_principals', p.EffectivePrincipalsPredicate),\n ('custom', p.CustomPredicate),\n ('traverse', p.TraversePredicate),\ndiff --git a/src/pyramid/config/views.py b/src/pyramid/config/views.py\nindex a064ebd05..26b69beb9 100644\n--- a/src/pyramid/config/views.py\n+++ b/src/pyramid/config/views.py\n@@ -712,6 +712,17 @@ class ViewsConfiguratorMixin:\n \n .. versionadded:: 1.4a3\n \n+ is_authenticated\n+\n+ This value, if specified, must be either ``True`` or ``False``.\n+ If it is specified and ``True``, only a request from an authenticated\n+ user, as determined by the :term:`security policy` in use, will\n+ satisfy the predicate.\n+ If it is specified and ``False``, only a request from a user who is\n+ not authenticated will satisfy the predicate.\n+\n+ .. versionadded:: 2.0\n+\n effective_principals\n \n If specified, this value should be a :term:`principal` identifier or\n@@ -726,6 +737,7 @@ class ViewsConfiguratorMixin:\n .. versionadded:: 1.4a4\n \n .. deprecated:: 2.0\n+ Use ``is_authenticated`` or a custom predicate.\n \n custom_predicates\n \n@@ -1205,6 +1217,7 @@ class ViewsConfiguratorMixin:\n ('request_type', p.RequestTypePredicate),\n ('match_param', p.MatchParamPredicate),\n ('physical_path', p.PhysicalPathPredicate),\n+ ('is_authenticated', p.IsAuthenticatedPredicate),\n ('effective_principals', p.EffectivePrincipalsPredicate),\n ('custom', p.CustomPredicate),\n ):\ndiff --git a/src/pyramid/interfaces.py b/src/pyramid/interfaces.py\nindex e92662f11..b8c8d06a9 100644\n--- a/src/pyramid/interfaces.py\n+++ b/src/pyramid/interfaces.py\n@@ -113,6 +113,16 @@ class IResponse(Interface):\n \"\"\" Return a new app_iter built from the response app_iter that\n serves up only the given start:stop range. \"\"\"\n \n+ authenticated_identity = Attribute(\n+ \"\"\"An object representing the authenticated user, as determined by\n+ the security policy in use, or ``None`` for unauthenticated requests.\n+ The object's class and meaning is defined by the security policy.\"\"\"\n+ )\n+\n+ authenticated_userid = Attribute(\n+ \"\"\"A string to identify the authenticated user or ``None``.\"\"\"\n+ )\n+\n body = Attribute(\n \"\"\"The body of the response, as a str. This will read in the entire\n app_iter if necessary.\"\"\"\n@@ -233,6 +243,11 @@ class IResponse(Interface):\n \n headers = Attribute(\"\"\" The headers in a dictionary-like object \"\"\")\n \n+ is_authenticated = Attribute(\n+ \"\"\"A boolean indicating whether the request has an authenticated\n+ user, as determined by the security policy in use.\"\"\"\n+ )\n+\n last_modified = Attribute(\n \"\"\" Gets and sets and deletes the Last-Modified header. For more\n information on Last-Modified see RFC 2616 section 14.29. Converts\ndiff --git a/src/pyramid/predicates.py b/src/pyramid/predicates.py\nindex 576bbbce6..fe8bc228c 100644\n--- a/src/pyramid/predicates.py\n+++ b/src/pyramid/predicates.py\n@@ -276,6 +276,19 @@ class PhysicalPathPredicate:\n return False\n \n \n+class IsAuthenticatedPredicate:\n+ def __init__(self, val, config):\n+ self.val = val\n+\n+ def text(self):\n+ return \"is_authenticated = %r\" % (self.val,)\n+\n+ phash = text\n+\n+ def __call__(self, context, request):\n+ return request.is_authenticated == self.val\n+\n+\n class EffectivePrincipalsPredicate:\n def __init__(self, val, config):\n if is_nonstr_iter(val):\ndiff --git a/src/pyramid/security.py b/src/pyramid/security.py\nindex 58bc72116..2a1ef24bd 100644\n--- a/src/pyramid/security.py\n+++ b/src/pyramid/security.py\n@@ -244,6 +244,11 @@ class SecurityAPIMixin:\n return None\n return policy.authenticated_userid(self)\n \n+ @property\n+ def is_authenticated(self):\n+ \"\"\"Return ``True`` if a user is authenticated for this request.\"\"\"\n+ return self.authenticated_identity is not None\n+\n def has_permission(self, permission, context=None):\n \"\"\" Given a permission and an optional context, returns an instance of\n :data:`pyramid.security.Allowed` if the permission is granted to this\n", "test_patch": "diff --git a/tests/test_config/test_predicates.py b/tests/test_config/test_predicates.py\nindex 8017fc898..7e2f32786 100644\n--- a/tests/test_config/test_predicates.py\n+++ b/tests/test_config/test_predicates.py\n@@ -19,6 +19,7 @@ class TestPredicateList(unittest.TestCase):\n ('containment', predicates.ContainmentPredicate),\n ('request_type', predicates.RequestTypePredicate),\n ('match_param', predicates.MatchParamPredicate),\n+ ('is_authenticated', predicates.IsAuthenticatedPredicate),\n ('custom', predicates.CustomPredicate),\n ('traverse', predicates.TraversePredicate),\n ):\n@@ -38,6 +39,19 @@ class TestPredicateList(unittest.TestCase):\n def test_ordering_number_of_predicates(self):\n from pyramid.config.predicates import predvalseq\n \n+ order0, _, _ = self._callFUT(\n+ xhr='xhr',\n+ request_method='request_method',\n+ path_info='path_info',\n+ request_param='param',\n+ match_param='foo=bar',\n+ header='header',\n+ accept='accept',\n+ is_authenticated=True,\n+ containment='containment',\n+ request_type='request_type',\n+ custom=predvalseq([DummyCustomPredicate()]),\n+ )\n order1, _, _ = self._callFUT(\n xhr='xhr',\n request_method='request_method',\n@@ -121,6 +135,7 @@ class TestPredicateList(unittest.TestCase):\n )\n order11, _, _ = self._callFUT(xhr='xhr')\n order12, _, _ = self._callFUT()\n+ self.assertTrue(order1 > order0)\n self.assertEqual(order1, order2)\n self.assertTrue(order3 > order2)\n self.assertTrue(order4 > order3)\n@@ -131,7 +146,7 @@ class TestPredicateList(unittest.TestCase):\n self.assertTrue(order9 > order8)\n self.assertTrue(order10 > order9)\n self.assertTrue(order11 > order10)\n- self.assertTrue(order12 > order10)\n+ self.assertTrue(order12 > order11)\n \n def test_ordering_importance_of_predicates(self):\n from pyramid.config.predicates import predvalseq\n@@ -145,7 +160,8 @@ class TestPredicateList(unittest.TestCase):\n order7, _, _ = self._callFUT(containment='containment')\n order8, _, _ = self._callFUT(request_type='request_type')\n order9, _, _ = self._callFUT(match_param='foo=bar')\n- order10, _, _ = self._callFUT(\n+ order10, _, _ = self._callFUT(is_authenticated=True)\n+ order11, _, _ = self._callFUT(\n custom=predvalseq([DummyCustomPredicate()])\n )\n self.assertTrue(order1 > order2)\n@@ -157,6 +173,7 @@ class TestPredicateList(unittest.TestCase):\n self.assertTrue(order7 > order8)\n self.assertTrue(order8 > order9)\n self.assertTrue(order9 > order10)\n+ self.assertTrue(order10 > order11)\n \n def test_ordering_importance_and_number(self):\n from pyramid.config.predicates import predvalseq\n@@ -296,6 +313,7 @@ class TestPredicateList(unittest.TestCase):\n ]\n ),\n match_param='foo=bar',\n+ is_authenticated=False,\n )\n self.assertEqual(predicates[0].text(), 'xhr = True')\n self.assertEqual(\n@@ -308,9 +326,10 @@ class TestPredicateList(unittest.TestCase):\n self.assertEqual(predicates[6].text(), 'containment = containment')\n self.assertEqual(predicates[7].text(), 'request_type = request_type')\n self.assertEqual(predicates[8].text(), \"match_param foo=bar\")\n- self.assertEqual(predicates[9].text(), 'custom predicate')\n- self.assertEqual(predicates[10].text(), 'classmethod predicate')\n- self.assertTrue(predicates[11].text().startswith('custom predicate'))\n+ self.assertEqual(predicates[9].text(), \"is_authenticated = False\")\n+ self.assertEqual(predicates[10].text(), 'custom predicate')\n+ self.assertEqual(predicates[11].text(), 'classmethod predicate')\n+ self.assertTrue(predicates[12].text().startswith('custom predicate'))\n \n def test_predicate_text_is_correct_when_multiple(self):\n _, predicates, _ = self._callFUT(\n@@ -434,6 +453,30 @@ class TestPredicateList(unittest.TestCase):\n request.headers = {'foo': 'nobar', 'spamme': 'ham'}\n self.assertFalse(predicates[0](Dummy(), request))\n \n+ def test_is_authenticated_true_matches(self):\n+ _, predicates, _ = self._callFUT(is_authenticated=True)\n+ request = DummyRequest()\n+ request.is_authenticated = True\n+ self.assertTrue(predicates[0](Dummy(), request))\n+\n+ def test_is_authenticated_true_fails(self):\n+ _, predicates, _ = self._callFUT(is_authenticated=True)\n+ request = DummyRequest()\n+ request.is_authenticated = False\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n+ def test_is_authenticated_false_matches(self):\n+ _, predicates, _ = self._callFUT(is_authenticated=False)\n+ request = DummyRequest()\n+ request.is_authenticated = False\n+ self.assertTrue(predicates[0](Dummy(), request))\n+\n+ def test_is_authenticated_false_fails(self):\n+ _, predicates, _ = self._callFUT(is_authenticated=False)\n+ request = DummyRequest()\n+ request.is_authenticated = True\n+ self.assertFalse(predicates[0](Dummy(), request))\n+\n def test_unknown_predicate(self):\n from pyramid.exceptions import ConfigurationError\n \ndiff --git a/tests/test_config/test_routes.py b/tests/test_config/test_routes.py\nindex 8227784ec..605f61857 100644\n--- a/tests/test_config/test_routes.py\n+++ b/tests/test_config/test_routes.py\n@@ -184,6 +184,18 @@ class RoutesConfiguratorMixinTests(unittest.TestCase):\n request.params = {}\n self.assertEqual(predicate(None, request), False)\n \n+ def test_add_route_with_is_authenticated(self):\n+ config = self._makeOne(autocommit=True)\n+ config.add_route('name', 'path', is_authenticated=True)\n+ route = self._assertRoute(config, 'name', 'path', 1)\n+ predicate = route.predicates[0]\n+ request = self._makeRequest(config)\n+ request.is_authenticated = True\n+ self.assertEqual(predicate(None, request), True)\n+ request = self._makeRequest(config)\n+ request.is_authenticated = False\n+ self.assertEqual(predicate(None, request), False)\n+\n def test_add_route_with_custom_predicates(self):\n import warnings\n \ndiff --git a/tests/test_config/test_views.py b/tests/test_config/test_views.py\nindex 2a55ad45d..09714d82e 100644\n--- a/tests/test_config/test_views.py\n+++ b/tests/test_config/test_views.py\n@@ -1742,6 +1742,46 @@ class TestViewsConfigurationMixin(unittest.TestCase):\n request.is_xhr = False\n self._assertNotFound(wrapper, None, request)\n \n+ def test_add_view_with_is_authenticated_true_matches(self):\n+ from pyramid.renderers import null_renderer as nr\n+\n+ view = lambda *arg: 'OK'\n+ config = self._makeOne(autocommit=True)\n+ config.add_view(view=view, is_authenticated=True, renderer=nr)\n+ wrapper = self._getViewCallable(config)\n+ request = self._makeRequest(config)\n+ request.is_authenticated = True\n+ self.assertEqual(wrapper(None, request), 'OK')\n+\n+ def test_add_view_with_is_authenticated_true_no_match(self):\n+ view = lambda *arg: 'OK'\n+ config = self._makeOne(autocommit=True)\n+ config.add_view(view=view, is_authenticated=True)\n+ wrapper = self._getViewCallable(config)\n+ request = self._makeRequest(config)\n+ request.is_authenticated = False\n+ self._assertNotFound(wrapper, None, request)\n+\n+ def test_add_view_with_is_authenticated_false_matches(self):\n+ from pyramid.renderers import null_renderer as nr\n+\n+ view = lambda *arg: 'OK'\n+ config = self._makeOne(autocommit=True)\n+ config.add_view(view=view, is_authenticated=False, renderer=nr)\n+ wrapper = self._getViewCallable(config)\n+ request = self._makeRequest(config)\n+ request.is_authenticated = False\n+ self.assertEqual(wrapper(None, request), 'OK')\n+\n+ def test_add_view_with_is_authenticated_false_no_match(self):\n+ view = lambda *arg: 'OK'\n+ config = self._makeOne(autocommit=True)\n+ config.add_view(view=view, is_authenticated=False)\n+ wrapper = self._getViewCallable(config)\n+ request = self._makeRequest(config)\n+ request.is_authenticated = True\n+ self._assertNotFound(wrapper, None, request)\n+\n def test_add_view_with_header_badregex(self):\n view = lambda *arg: 'OK'\n config = self._makeOne()\ndiff --git a/tests/test_security.py b/tests/test_security.py\nindex bf2908100..72598f570 100644\n--- a/tests/test_security.py\n+++ b/tests/test_security.py\n@@ -393,6 +393,29 @@ class TestUnAuthenticatedUserId(unittest.TestCase):\n self.assertEqual(request.unauthenticated_userid, 'wat')\n \n \n+class TestIsAuthenticated(unittest.TestCase):\n+ def setUp(self):\n+ testing.setUp()\n+\n+ def tearDown(self):\n+ testing.tearDown()\n+\n+ def test_no_security_policy(self):\n+ request = _makeRequest()\n+ self.assertIs(request.is_authenticated, False)\n+\n+ def test_with_security_policy(self):\n+ request = _makeRequest()\n+ _registerSecurityPolicy(request.registry, '123')\n+ self.assertIs(request.is_authenticated, True)\n+\n+ def test_with_legacy_security_policy(self):\n+ request = _makeRequest()\n+ _registerAuthenticationPolicy(request.registry, 'yo')\n+ _registerLegacySecurityPolicy(request.registry)\n+ self.assertEqual(request.authenticated_userid, 'yo')\n+\n+\n class TestEffectivePrincipals(unittest.TestCase):\n def setUp(self):\n testing.setUp()\n", "FAIL_TO_PASS": ["tests/test_config/test_predicates.py::TestPredicateList::test_custom_predicates_can_affect_traversal", "tests/test_config/test_predicates.py::TestPredicateList::test_different_custom_predicates_with_same_hash", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_mixed", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_mixed_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_with_values", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_with_values_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_simple", "tests/test_config/test_predicates.py::TestPredicateList::test_header_simple_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_with_value", "tests/test_config/test_predicates.py::TestPredicateList::test_header_with_value_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_with_value_fails_case", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_false_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_false_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_true_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_true_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_dict", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_dict_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_string", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_string_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_notted", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_importance_and_number", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_importance_of_predicates", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_number_of_predicates", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_xhr_and_request_method_trump_only_containment", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_close_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_text_is_correct", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_text_is_correct_when_multiple", "tests/test_config/test_predicates.py::TestPredicateList::test_request_method_ordering_hashes_same", "tests/test_config/test_predicates.py::TestPredicateList::test_request_method_sequence", "tests/test_config/test_predicates.py::TestPredicateList::test_traverse_has_remainder_already", "tests/test_config/test_predicates.py::TestPredicateList::test_traverse_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_traverse_matches_with_highorder_chars", "tests/test_config/test_predicates.py::TestPredicateList::test_unknown_predicate", "tests/test_config/test_routes.py::RoutesConfiguratorMixinTests::test_add_route_with_is_authenticated", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_false_matches", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_false_no_match", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_true_matches", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_true_no_match", "tests/test_security.py::TestIsAuthenticated::test_no_security_policy", "tests/test_security.py::TestIsAuthenticated::test_with_security_policy"]}], "all_FAIL_TO_PASS": ["tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_mixed", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_with_values", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_text_is_correct_when_multiple", "tests/test_config/test_predicates.py::TestPredicateList::test_custom_predicates_can_affect_traversal", "tests/test_config/test_predicates.py::TestPredicateList::test_different_custom_predicates_with_same_hash", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_mixed", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_mixed_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_with_values", "tests/test_config/test_predicates.py::TestPredicateList::test_header_multiple_with_values_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_simple", "tests/test_config/test_predicates.py::TestPredicateList::test_header_simple_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_with_value", "tests/test_config/test_predicates.py::TestPredicateList::test_header_with_value_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_header_with_value_fails_case", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_false_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_false_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_true_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_is_authenticated_true_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_dict", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_dict_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_string", "tests/test_config/test_predicates.py::TestPredicateList::test_match_param_from_string_fails", "tests/test_config/test_predicates.py::TestPredicateList::test_notted", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_importance_and_number", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_importance_of_predicates", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_number_of_predicates", "tests/test_config/test_predicates.py::TestPredicateList::test_ordering_xhr_and_request_method_trump_only_containment", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_close_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_text_is_correct", "tests/test_config/test_predicates.py::TestPredicateList::test_predicate_text_is_correct_when_multiple", "tests/test_config/test_predicates.py::TestPredicateList::test_request_method_ordering_hashes_same", "tests/test_config/test_predicates.py::TestPredicateList::test_request_method_sequence", "tests/test_config/test_predicates.py::TestPredicateList::test_traverse_has_remainder_already", "tests/test_config/test_predicates.py::TestPredicateList::test_traverse_matches", "tests/test_config/test_predicates.py::TestPredicateList::test_traverse_matches_with_highorder_chars", "tests/test_config/test_predicates.py::TestPredicateList::test_unknown_predicate", "tests/test_config/test_routes.py::RoutesConfiguratorMixinTests::test_add_route_with_is_authenticated", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_false_matches", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_false_no_match", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_true_matches", "tests/test_config/test_views.py::TestViewsConfigurationMixin::test_add_view_with_is_authenticated_true_no_match", "tests/test_security.py::TestIsAuthenticated::test_no_security_policy", "tests/test_security.py::TestIsAuthenticated::test_with_security_policy"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "ipython__traitlets-629_x2", "level": 2, "source": "swerebenchv2", "repo": "ipython/traitlets", "image": "swerebenchv2/ipython-traitlets:629-2942197", "base_commit": "294219773e453cd7d05b7906923197ceb8dd8731", "num_bugs": 2, "bugs": [{"instance_id": "ipython__traitlets-629", "base_commit": "294219773e453cd7d05b7906923197ceb8dd8731", "gold_patch": "diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst\nindex 691a73d..5511e81 100644\n--- a/docs/source/changelog.rst\n+++ b/docs/source/changelog.rst\n@@ -4,6 +4,12 @@ Changes in Traitlets\n Traitlets 5.0\n -------------\n \n+5.0.5\n+*****\n+\n+- Support deprecated literals for sets, tuples on the command-line: ``nbconvert --TagRemovePreprocessor.remove_cell_tags='{\"tag\"}'``\n+- Fix ``from_string_list`` for Tuples in general\n+\n 5.0.4\n *****\n \ndiff --git a/traitlets/traitlets.py b/traitlets/traitlets.py\nindex 8bc4e1f..b1894a4 100644\n--- a/traitlets/traitlets.py\n+++ b/traitlets/traitlets.py\n@@ -2412,6 +2412,8 @@ class Container(Instance):\n _valid_defaults = SequenceTypes\n _trait = None\n \n+ _literal_from_string_pairs = (\"[]\", \"()\")\n+\n def __init__(self, trait=None, default_value=None, **kwargs):\n \"\"\"Create a container trait type from a list, set, or tuple.\n \n@@ -2517,20 +2519,34 @@ class Container(Instance):\n r = s_list[0]\n if r == \"None\" and self.allow_none:\n return None\n- if (\n- (r[0] == '[' and r[-1] == ']') or\n- (r[0] == '(' and r[-1] == ')')\n+ if len(r) >= 2 and any(\n+ r.startswith(start) and r.endswith(end)\n+ for start, end in self._literal_from_string_pairs\n ):\n+ if self.this_class:\n+ clsname = self.this_class.__name__ + \".\"\n+ else:\n+ clsname = \"\"\n+\n warn(\n \"--{0}={1} for containers is deprecated in traitlets 5.0. \"\n- \"You can pass --{0} item ... multiple times to add items to a list.\".format(\n- self.name, r),\n- FutureWarning\n+ \"You can pass `--{0} item` ... multiple times to add items to a list.\".format(\n+ clsname + self.name, r\n+ ),\n+ FutureWarning,\n )\n return self.klass(literal_eval(r))\n- return self.klass([self.item_from_string(s) for s in s_list])\n+ sig = inspect.signature(self.item_from_string)\n+ if \"index\" in sig.parameters:\n+ item_from_string = self.item_from_string\n+ else:\n+ # backward-compat: allow item_from_string to ignore index arg\n+ item_from_string = lambda s, index=None: self.item_from_string(s)\n+ return self.klass(\n+ [item_from_string(s, index=idx) for idx, s in enumerate(s_list)]\n+ )\n \n- def item_from_string(self, s):\n+ def item_from_string(self, s, index=None):\n \"\"\"Cast a single item from a string\n \n Evaluated when parsing CLI configuration from a string\n@@ -2596,6 +2612,8 @@ class Set(List):\n klass = set\n _cast_types = (tuple, list)\n \n+ _literal_from_string_pairs = (\"[]\", \"()\", \"{}\")\n+\n # Redefine __init__ just to make the docstring more accurate.\n def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize,\n **kwargs):\n@@ -2687,13 +2705,24 @@ class Tuple(Container):\n warn(\"Traits should be given as instances, not types (for example, `Int()`, not `Int`)\"\n \" Passing types is deprecated in traitlets 4.1.\",\n DeprecationWarning, stacklevel=2)\n- t = trait() if isinstance(trait, type) else trait\n- self._traits.append(t)\n+ trait = trait()\n+ self._traits.append(trait)\n \n if self._traits and default_value is None:\n # don't allow default to be an empty container if length is specified\n args = None\n- super(Container,self).__init__(klass=self.klass, args=args, **kwargs)\n+ super(Container, self).__init__(klass=self.klass, args=args, **kwargs)\n+\n+ def item_from_string(self, s, index):\n+ \"\"\"Cast a single item from a string\n+\n+ Evaluated when parsing CLI configuration from a string\n+ \"\"\"\n+ if not self._traits or index >= len(self._traits):\n+ # return s instead of raising index error\n+ # length errors will be raised later on validation\n+ return s\n+ return self._traits[index].from_string(s)\n \n def validate_elements(self, obj, value):\n if not self._traits:\n", "test_patch": "diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py\nindex e4f456b..a5cdb2a 100644\n--- a/traitlets/tests/test_traitlets.py\n+++ b/traitlets/tests/test_traitlets.py\n@@ -45,6 +45,7 @@ from traitlets import (\n Instance,\n TCPAddress,\n List,\n+ Set,\n Tuple,\n ObjectName,\n DottedObjectName,\n@@ -2787,12 +2788,69 @@ def test_list_from_string(s, expected):\n ([\"x\"], ValueError, Integer()),\n ([\"1\", \"x\"], [\"1\", \"x\"], Unicode()),\n ([\"None\"], [None], Unicode(allow_none=True)),\n+ ([\"None\"], [\"None\"], Unicode(allow_none=False)),\n ],\n )\n def test_list_items_from_string(s, expected, value_trait):\n _from_string_test(List(value_trait), s, expected)\n \n \n+@pytest.mark.parametrize(\n+ \"s, expected\",\n+ [\n+ (\"[]\", set()),\n+ ('[1, 2, \"x\"]', {1, 2, \"x\"}),\n+ ('{1, 2, \"x\"}', {1, 2, \"x\"}),\n+ ([\"1\", \"x\"], {\"1\", \"x\"}),\n+ ([\"None\"], None),\n+ ],\n+)\n+def test_set_from_string(s, expected):\n+ _from_string_test(Set, s, expected)\n+\n+\n+@pytest.mark.parametrize(\n+ \"s, expected, value_trait\",\n+ [\n+ ([\"1\", \"2\", \"3\"], {1, 2, 3}, Integer()),\n+ ([\"x\"], ValueError, Integer()),\n+ ([\"1\", \"x\"], {\"1\", \"x\"}, Unicode()),\n+ ([\"None\"], {None}, Unicode(allow_none=True)),\n+ ],\n+)\n+def test_set_items_from_string(s, expected, value_trait):\n+ _from_string_test(Set(value_trait), s, expected)\n+\n+\n+@pytest.mark.parametrize(\n+ \"s, expected\",\n+ [\n+ (\"[]\", ()),\n+ (\"()\", ()),\n+ ('[1, 2, \"x\"]', (1, 2, \"x\")),\n+ ('(1, 2, \"x\")', (1, 2, \"x\")),\n+ ([\"1\", \"x\"], (\"1\", \"x\")),\n+ ([\"None\"], None),\n+ ],\n+)\n+def test_tuple_from_string(s, expected):\n+ _from_string_test(Tuple, s, expected)\n+\n+\n+@pytest.mark.parametrize(\n+ \"s, expected, value_traits\",\n+ [\n+ ([\"1\", \"2\", \"3\"], (1, 2, 3), [Integer(), Integer(), Integer()]),\n+ ([\"x\"], ValueError, [Integer()]),\n+ ([\"1\", \"x\"], (\"1\", \"x\"), [Unicode()]),\n+ ([\"None\"], (\"None\",), [Unicode(allow_none=False)]),\n+ ([\"None\"], (None,), [Unicode(allow_none=True)]),\n+ ],\n+)\n+def test_tuple_items_from_string(s, expected, value_traits):\n+ _from_string_test(Tuple(*value_traits), s, expected)\n+\n+\n @pytest.mark.parametrize(\n \"s, expected\",\n [\n", "FAIL_TO_PASS": ["traitlets/tests/test_traitlets.py::test_tuple_items_from_string[s0-expected0-value_traits0]", "traitlets/tests/test_traitlets.py::test_tuple_items_from_string[s1-ValueError-value_traits1]", "traitlets/tests/test_traitlets.py::test_tuple_items_from_string[s4-expected4-value_traits4]"]}, {"instance_id": "ipython__traitlets-630", "base_commit": "9f6276418d85aee49d12ab6495cf8a6acea8b961", "gold_patch": "diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst\nindex 5511e81..be50c2b 100644\n--- a/docs/source/changelog.rst\n+++ b/docs/source/changelog.rst\n@@ -9,6 +9,7 @@ Traitlets 5.0\n \n - Support deprecated literals for sets, tuples on the command-line: ``nbconvert --TagRemovePreprocessor.remove_cell_tags='{\"tag\"}'``\n - Fix ``from_string_list`` for Tuples in general\n+- Fix support for ``List(default_value=None, allow_none=True)`` and other Container traits\n \n 5.0.4\n *****\ndiff --git a/traitlets/traitlets.py b/traitlets/traitlets.py\nindex b1894a4..2cd1453 100644\n--- a/traitlets/traitlets.py\n+++ b/traitlets/traitlets.py\n@@ -1695,7 +1695,7 @@ class ClassBasedTraitType(TraitType):\n class Type(ClassBasedTraitType):\n \"\"\"A trait whose value must be a subclass of a specified class.\"\"\"\n \n- def __init__ (self, default_value=Undefined, klass=None, **kwargs):\n+ def __init__(self, default_value=Undefined, klass=None, **kwargs):\n \"\"\"Construct a Type trait\n \n A Type trait specifies that its values must be subclasses of\n@@ -2411,10 +2411,9 @@ class Container(Instance):\n _cast_types = ()\n _valid_defaults = SequenceTypes\n _trait = None\n-\n _literal_from_string_pairs = (\"[]\", \"()\")\n \n- def __init__(self, trait=None, default_value=None, **kwargs):\n+ def __init__(self, trait=None, default_value=Undefined, **kwargs):\n \"\"\"Create a container trait type from a list, set, or tuple.\n \n The default value is created by doing ``List(default_value)``,\n@@ -2443,12 +2442,16 @@ class Container(Instance):\n \n \"\"\"\n # allow List([values]):\n- if default_value is None and not is_trait(trait):\n+ if trait is not None and default_value is Undefined and not is_trait(trait):\n default_value = trait\n trait = None\n \n- if default_value is None:\n+ if default_value is Undefined:\n args = ()\n+ elif default_value is None:\n+ # default_value back on kwargs for super() to handle\n+ args = ()\n+ kwargs[\"default_value\"] = None\n elif isinstance(default_value, self._valid_defaults):\n args = (default_value,)\n else:\n@@ -2562,7 +2565,14 @@ class List(Container):\n klass = list\n _cast_types = (tuple,)\n \n- def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **kwargs):\n+ def __init__(\n+ self,\n+ trait=None,\n+ default_value=Undefined,\n+ minlen=0,\n+ maxlen=sys.maxsize,\n+ **kwargs,\n+ ):\n \"\"\"Create a List trait type from a list, set, or tuple.\n \n The default value is created by doing ``list(default_value)``,\n@@ -2615,8 +2625,14 @@ class Set(List):\n _literal_from_string_pairs = (\"[]\", \"()\", \"{}\")\n \n # Redefine __init__ just to make the docstring more accurate.\n- def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize,\n- **kwargs):\n+ def __init__(\n+ self,\n+ trait=None,\n+ default_value=Undefined,\n+ minlen=0,\n+ maxlen=sys.maxsize,\n+ **kwargs,\n+ ):\n \"\"\"Create a Set trait type from a list, set, or tuple.\n \n The default value is created by doing ``set(default_value)``,\n@@ -2694,6 +2710,10 @@ class Tuple(Container):\n \n if default_value is Undefined:\n args = ()\n+ elif default_value is None:\n+ # default_value back on kwargs for super() to handle\n+ args = ()\n+ kwargs[\"default_value\"] = None\n elif isinstance(default_value, self._valid_defaults):\n args = (default_value,)\n else:\n", "test_patch": "diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py\nindex a5cdb2a..0680ab8 100644\n--- a/traitlets/tests/test_traitlets.py\n+++ b/traitlets/tests/test_traitlets.py\n@@ -9,13 +9,11 @@\n \n import pickle\n import re\n-import sys\n-from ._warnings import expected_warnings\n-\n from unittest import TestCase\n+\n import pytest\n-from pytest import mark\n \n+from ._warnings import expected_warnings\n from traitlets import (\n HasTraits,\n MetaHasTraits,\n@@ -40,6 +38,7 @@ from traitlets import (\n Callable,\n All,\n Undefined,\n+ Set,\n Type,\n This,\n Instance,\n@@ -1517,10 +1516,12 @@ class TestTCPAddress(TraitTestBase):\n _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]\n _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None]\n \n+\n class ListTrait(HasTraits):\n \n value = List(Int())\n \n+\n class TestList(TraitTestBase):\n \n obj = ListTrait()\n@@ -1534,6 +1535,7 @@ class TestList(TraitTestBase):\n value = list(value)\n return value\n \n+\n class Foo(object):\n pass\n \n@@ -1653,10 +1655,42 @@ class TestMultiTuple(TraitTestBase):\n _good_values = [(1,b'a'), (2,b'b')]\n _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, 'a'))\n \n+\n+@pytest.mark.parametrize(\n+ \"Trait\", (List, Tuple, Set, Dict, Integer, Unicode,),\n+)\n+def test_allow_none_default_value(Trait):\n+ class C(HasTraits):\n+ t = Trait(default_value=None, allow_none=True)\n+\n+ # test default value\n+ c = C()\n+ assert c.t is None\n+\n+ # and in constructor\n+ c = C(t=None)\n+ assert c.t is None\n+\n+\n+@pytest.mark.parametrize(\n+ \"Trait, default_value\",\n+ ((List, []), (Tuple, ()), (Set, set()), (Dict, {}), (Integer, 0), (Unicode, \"\")),\n+)\n+def test_default_value(Trait, default_value):\n+ class C(HasTraits):\n+ t = Trait()\n+\n+ # test default value\n+ c = C()\n+ assert type(c.t) is type(default_value)\n+ assert c.t == default_value\n+\n+\n class CRegExpTrait(HasTraits):\n \n value = CRegExp(r'')\n \n+\n class TestCRegExp(TraitTestBase):\n \n def coerce(self, value):\n", "FAIL_TO_PASS": ["traitlets/tests/test_traitlets.py::test_allow_none_default_value[List]", "traitlets/tests/test_traitlets.py::test_allow_none_default_value[Tuple]", "traitlets/tests/test_traitlets.py::test_allow_none_default_value[Set]"]}], "all_FAIL_TO_PASS": ["traitlets/tests/test_traitlets.py::test_tuple_items_from_string[s0-expected0-value_traits0]", "traitlets/tests/test_traitlets.py::test_tuple_items_from_string[s1-ValueError-value_traits1]", "traitlets/tests/test_traitlets.py::test_tuple_items_from_string[s4-expected4-value_traits4]", "traitlets/tests/test_traitlets.py::test_allow_none_default_value[List]", "traitlets/tests/test_traitlets.py::test_allow_none_default_value[Tuple]", "traitlets/tests/test_traitlets.py::test_allow_none_default_value[Set]"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "warpnet__salt-lint-207_x2", "level": 2, "source": "swerebenchv2", "repo": "warpnet/salt-lint", "image": "swerebenchv2/warpnet-salt-lint:207-56d5a88", "base_commit": "56d5a889c467808135eecd6140fa9ad7b945ecd1", "num_bugs": 2, "bugs": [{"instance_id": "warpnet__salt-lint-207", "base_commit": "56d5a889c467808135eecd6140fa9ad7b945ecd1", "gold_patch": "diff --git a/README.md b/README.md\nindex 5a02f7e..fbc3364 100644\n--- a/README.md\n+++ b/README.md\n@@ -164,6 +164,10 @@ Optionally override the default file selection as follows:\n \n ## List of rules\n \n+### Formatting\n+\n+Disable formatting checks using `-x formatting`\n+\n Rule | Description\n :-:|:--\n [201](https://github.com/warpnet/salt-lint/wiki/201) | Trailing whitespace\n@@ -180,6 +184,25 @@ Rule | Description\n [212](https://github.com/warpnet/salt-lint/wiki/212) | Most files should not contain irregular spaces\n [213](https://github.com/warpnet/salt-lint/wiki/213) | SaltStack recommends using `cmd.run` together with `onchanges`, rather than `cmd.wait`\n \n+### Jinja\n+\n+Disable jinja checks using `-x jinja`\n+\n+Rule | Description\n+:-:|:--\n+[202](https://github.com/warpnet/salt-lint/wiki/202) | Jinja statement should have spaces before and after: `{% statement %}`\n+[206](https://github.com/warpnet/salt-lint/wiki/206) | Jinja variables should have spaces before and after `{{ var_name }}`\n+[209](https://github.com/warpnet/salt-lint/wiki/209) | Jinja comment should have spaces before and after: `{# comment #}`\n+[211](https://github.com/warpnet/salt-lint/wiki/211) | `pillar.get` or `grains.get` should be formatted differently\n+\n+### Deprecations\n+\n+Disable deprecation checks using `-x deprecation`\n+\n+Rule | Description\n+:-:|:--\n+[901](https://github.com/warpnet/salt-lint/wiki/901) | Using the `quiet` argument with `cmd.run` is deprecated. Use `output_loglevel: quiet`\n+\n ## False Positives: Skipping Rules\n \n Some rules are bit of a rule of thumb. To skip a specific rule for a specific task, inside your state add `# noqa [rule_id]` at the end of the line. You can skip multiple rules via a space-separated list. Example:\ndiff --git a/saltlint/rules/CmdRunQuietRule.py b/saltlint/rules/CmdRunQuietRule.py\nnew file mode 100644\nindex 0000000..5dd68ce\n--- /dev/null\n+++ b/saltlint/rules/CmdRunQuietRule.py\n@@ -0,0 +1,39 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (c) 2020 Warpnet B.V.\n+\n+import re\n+from saltlint.linter.rule import Rule\n+from saltlint.utils import get_rule_skips_from_text\n+\n+class CmdRunQuietRule(Rule):\n+ id = '901'\n+ shortdesc = 'Using the quiet argument with cmd.run is deprecated. Use output_loglevel: quiet'\n+ description = 'Using the quiet argument with cmd.run is deprecated. Use output_loglevel: quiet'\n+\n+ severity = 'HIGH'\n+ tags = ['deprecation']\n+ version_added = 'develop'\n+\n+ regex = re.compile(r\"^.+\\n^\\s{2}cmd\\.run:(?:\\n.+)+\\n^\\s{4}- quiet\\s?.*\", re.MULTILINE)\n+\n+ def matchtext(self, file, text):\n+ results = []\n+\n+ for match in re.finditer(self.regex, text):\n+ # Get the location of the regex match\n+ start = match.start()\n+ end = match.end()\n+\n+ # Get the line number of the last character\n+ lines = text[:end].splitlines()\n+ line_no = len(lines)\n+\n+ # Skip result if noqa for this rule ID is found in section\n+ section = text[start:end]\n+ if self.id in get_rule_skips_from_text(section):\n+ continue\n+\n+ # Append the match to the results\n+ results.append((line_no, lines[-1], self.shortdesc))\n+\n+ return results\ndiff --git a/saltlint/utils.py b/saltlint/utils.py\nindex a0334b2..dbcdf23 100644\n--- a/saltlint/utils.py\n+++ b/saltlint/utils.py\n@@ -31,3 +31,12 @@ def get_rule_skips_from_line(line):\n noqa_text = line.split('# noqa')[1]\n rule_id_list = noqa_text.split()\n return rule_id_list\n+\n+\n+def get_rule_skips_from_text(text):\n+ rule_id_list = []\n+ for line in text.splitlines():\n+ rule_id_list.extend(get_rule_skips_from_line(line))\n+\n+ # Return a list of unique ids\n+ return list(set(rule_id_list))\n", "test_patch": "diff --git a/tests/unit/TestCmdRunQuietRule.py b/tests/unit/TestCmdRunQuietRule.py\nnew file mode 100644\nindex 0000000..ffb4c55\n--- /dev/null\n+++ b/tests/unit/TestCmdRunQuietRule.py\n@@ -0,0 +1,61 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (c) 2020 Warpnet B.V.\n+\n+import unittest\n+\n+from saltlint.linter.collection import RulesCollection\n+from saltlint.rules.CmdRunQuietRule import CmdRunQuietRule\n+from tests import RunFromText\n+\n+\n+GOOD_QUIET_STATE = '''\n+getpip:\n+ cmd.run:\n+ - name: /usr/bin/python /usr/local/sbin/get-pip.py\n+ - unless: which pip\n+ - require:\n+ - pkg: python\n+ - file: /usr/local/sbin/get-pip.py\n+ - output_loglevel: quiet\n+'''\n+\n+BAD_QUIET_STATE = '''\n+getpip:\n+ cmd.run:\n+ - name: /usr/bin/python /usr/local/sbin/get-pip.py\n+ - unless: which pip\n+ - require:\n+ - pkg: python\n+ - file: /usr/local/sbin/get-pip.py\n+ - quiet # This is the ninth line\n+\n+getpip2:\n+ cmd.run:\n+ - name: /usr/bin/python /usr/local/sbin/get-pip.py\n+ - quiet\n+\n+getpip3:\n+ cmd.run:\n+ - name: /usr/bin/python /usr/local/sbin/get-pip.py\n+ - quiet # noqa: 901\n+'''\n+\n+class TestCmdRunQuietRule(unittest.TestCase):\n+ collection = RulesCollection()\n+\n+ def setUp(self):\n+ self.collection.register(CmdRunQuietRule())\n+\n+ def test_statement_positive(self):\n+ runner = RunFromText(self.collection)\n+ results = runner.run_state(GOOD_QUIET_STATE)\n+ self.assertEqual(0, len(results))\n+\n+ def test_statement_negative(self):\n+ runner = RunFromText(self.collection)\n+ results = runner.run_state(BAD_QUIET_STATE)\n+ self.assertEqual(2, len(results))\n+\n+ # Check line numbers of the results\n+ self.assertEqual(9, results[0].linenumber)\n+ self.assertEqual(14, results[1].linenumber)\n", "FAIL_TO_PASS": ["tests/unit/TestCmdRunQuietRule.py::TestCmdRunQuietRule::test_statement_negative", "tests/unit/TestCmdRunQuietRule.py::TestCmdRunQuietRule::test_statement_positive"]}, {"instance_id": "warpnet__salt-lint-209", "base_commit": "70f34af1f139561f5c168e90a81f3bf93d14740f", "gold_patch": "diff --git a/README.md b/README.md\nindex fbc3364..5758647 100644\n--- a/README.md\n+++ b/README.md\n@@ -183,6 +183,7 @@ Rule | Description\n [211](https://github.com/warpnet/salt-lint/wiki/211) | `pillar.get` or `grains.get` should be formatted differently\n [212](https://github.com/warpnet/salt-lint/wiki/212) | Most files should not contain irregular spaces\n [213](https://github.com/warpnet/salt-lint/wiki/213) | SaltStack recommends using `cmd.run` together with `onchanges`, rather than `cmd.wait`\n+[214](https://github.com/warpnet/salt-lint/wiki/214) | SLS file with a period in the name (besides the suffix period) can not be referenced\n \n ### Jinja\n \ndiff --git a/saltlint/linter/rule.py b/saltlint/linter/rule.py\nindex bf95848..becf140 100644\n--- a/saltlint/linter/rule.py\n+++ b/saltlint/linter/rule.py\n@@ -5,12 +5,19 @@\n import re\n import six\n \n-from saltlint.utils import get_rule_skips_from_line\n+from saltlint.utils import get_rule_skips_from_line, get_file_type\n from saltlint.linter.match import Match\n \n \n class Rule(object):\n \n+ id = None\n+ shortdesc = None\n+ description = None\n+ languages = []\n+ match = None\n+ matchtext = None\n+\n def __init__(self, config=None):\n self.config = config\n \n@@ -20,18 +27,30 @@ class Rule(object):\n def verbose(self):\n return self.id + \": \" + self.shortdesc + \"\\n \" + self.description\n \n- match = None\n- matchtext = None\n-\n @staticmethod\n def unjinja(text):\n return re.sub(r\"{{[^}]*}}\", \"JINJA_VAR\", text)\n \n+ def is_valid_language(self, file):\n+ \"\"\"\n+ Returns True if the file type is in the supported languages or no\n+ language is specified for the linting rule and False otherwise.\n+\n+ The file type is determined based upon the file extension.\n+ \"\"\"\n+ if not self.languages or get_file_type(file[\"path\"]) in self.languages:\n+ return True\n+ return False\n+\n def matchlines(self, file, text):\n matches = []\n+\n if not self.match:\n return matches\n \n+ if not self.is_valid_language(file):\n+ return matches\n+\n # arrays are 0-based, line numbers are 1-based\n # so use prev_line_no as the counter\n for (prev_line_no, line) in enumerate(text.split(\"\\n\")):\n@@ -58,6 +77,9 @@ class Rule(object):\n if not self.matchtext:\n return matches\n \n+ if not self.is_valid_language(file):\n+ return matches\n+\n results = self.matchtext(file, text)\n \n for line, section, message in results:\ndiff --git a/saltlint/linter/runner.py b/saltlint/linter/runner.py\nindex 3add57d..752d0e6 100644\n--- a/saltlint/linter/runner.py\n+++ b/saltlint/linter/runner.py\n@@ -6,18 +6,20 @@ from __future__ import print_function\n \n import os\n \n+from saltlint.utils import get_file_type\n+\n \n class Runner(object):\n \n def __init__(self, collection, file_name, config, checked_files=None):\n self.collection = collection\n \n- self.states = set()\n+ self.files = set()\n # Assume the provided file name is a directory\n if os.path.isdir(file_name):\n- self.states.add((os.path.join(file_name, 'init.sls'), 'state'))\n+ self.files.add((os.path.join(file_name, 'init.sls'), 'state'))\n else:\n- self.states.add((file_name, 'state'))\n+ self.files.add((file_name, get_file_type(file_name)))\n \n # Get configuration options\n self.config = config\n@@ -49,9 +51,9 @@ class Runner(object):\n \n def run(self):\n files = []\n- for index, state in enumerate(self.states):\n- file_path = state[0]\n- file_type = state[1]\n+ for index, file in enumerate(self.files):\n+ file_path = file[0]\n+ file_type = file[1]\n file_dict = {'path': file_path, 'type': file_type}\n # Skip excluded files\n if self.is_excluded(file_path):\ndiff --git a/saltlint/rules/CmdRunQuietRule.py b/saltlint/rules/CmdRunQuietRule.py\nindex 5dd68ce..f290750 100644\n--- a/saltlint/rules/CmdRunQuietRule.py\n+++ b/saltlint/rules/CmdRunQuietRule.py\n@@ -4,6 +4,8 @@\n import re\n from saltlint.linter.rule import Rule\n from saltlint.utils import get_rule_skips_from_text\n+from saltlint.utils import LANGUAGE_SLS\n+\n \n class CmdRunQuietRule(Rule):\n id = '901'\n@@ -11,6 +13,7 @@ class CmdRunQuietRule(Rule):\n description = 'Using the quiet argument with cmd.run is deprecated. Use output_loglevel: quiet'\n \n severity = 'HIGH'\n+ languages = [LANGUAGE_SLS]\n tags = ['deprecation']\n version_added = 'develop'\n \ndiff --git a/saltlint/rules/CmdWaitRecommendRule.py b/saltlint/rules/CmdWaitRecommendRule.py\nindex 90ccb12..2fd7405 100644\n--- a/saltlint/rules/CmdWaitRecommendRule.py\n+++ b/saltlint/rules/CmdWaitRecommendRule.py\n@@ -3,6 +3,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_SLS\n \n \n class CmdWaitRecommendRule(Rule):\n@@ -11,6 +12,7 @@ class CmdWaitRecommendRule(Rule):\n description = 'SaltStack recommends using cmd.run together with onchanges, rather than cmd.wait'\n \n severity = 'LOW'\n+ languages = [LANGUAGE_SLS]\n tags = ['formatting']\n version_added = 'develop'\n \ndiff --git a/saltlint/rules/FileExtensionRule.py b/saltlint/rules/FileExtensionRule.py\nindex c8157e5..9949a56 100644\n--- a/saltlint/rules/FileExtensionRule.py\n+++ b/saltlint/rules/FileExtensionRule.py\n@@ -13,16 +13,15 @@ class FileExtensionRule(Rule):\n description = 'Salt State files should have the \".sls\" extension'\n severity = 'MEDIUM'\n tags = ['formatting']\n- done = [] # already noticed path list\n version_added = 'v0.0.1'\n \n- def match(self, file, line):\n- if file['type'] != 'state':\n- return False\n-\n+ def matchtext(self, file, text):\n+ results = []\n path = file['path']\n ext = os.path.splitext(path)\n- if ext[1] not in ['.sls'] and path not in self.done:\n- self.done.append(path)\n- return True\n- return False\n+ if ext[1] not in ['.sls']:\n+ line_no = 1\n+ lines = text.splitlines()\n+ line = lines[0] if len(lines) > 0 else ''\n+ results.append((line_no, line, self.shortdesc))\n+ return results\ndiff --git a/saltlint/rules/FileModeLeadingZeroRule.py b/saltlint/rules/FileModeLeadingZeroRule.py\nindex 226bea3..2849a57 100644\n--- a/saltlint/rules/FileModeLeadingZeroRule.py\n+++ b/saltlint/rules/FileModeLeadingZeroRule.py\n@@ -5,6 +5,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_SLS\n \n \n class FileModeLeadingZeroRule(Rule):\n@@ -12,10 +13,11 @@ class FileModeLeadingZeroRule(Rule):\n shortdesc = 'File modes should always contain a leading zero'\n description = 'File modes should always contain a leading zero'\n severity = 'LOW'\n+ languages = [LANGUAGE_SLS]\n tags = ['formatting']\n version_added = 'v0.0.3'\n \n- bracket_regex = re.compile(r\"^\\s+- ((dir_)|(file_))?mode: ((')|(\\\"))?[0-9]{3}([\\D]|$)\")\n+ regex = re.compile(r\"^\\s+- ((dir_)|(file_))?mode: ((')|(\\\"))?[0-9]{3}([\\D]|$)\")\n \n def match(self, file, line):\n- return self.bracket_regex.search(line)\n+ return self.regex.search(line)\ndiff --git a/saltlint/rules/FileModeQuotationRule.py b/saltlint/rules/FileModeQuotationRule.py\nindex e449c0c..07a21eb 100644\n--- a/saltlint/rules/FileModeQuotationRule.py\n+++ b/saltlint/rules/FileModeQuotationRule.py\n@@ -5,6 +5,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_SLS\n \n \n class FileModeQuotationRule(Rule):\n@@ -12,10 +13,11 @@ class FileModeQuotationRule(Rule):\n shortdesc = 'File modes should always be encapsulated in quotation marks'\n description = 'File modes should always be encapsulated in quotation marks'\n severity = 'HIGH'\n+ languages = [LANGUAGE_SLS]\n tags = ['formatting']\n version_added = 'v0.0.3'\n \n- bracket_regex = re.compile(r\"^\\s+- ((dir_)|(file_))?mode: [0-9]{3,4}\")\n+ regex = re.compile(r\"^\\s+- ((dir_)|(file_))?mode: [0-9]{3,4}\")\n \n def match(self, file, line):\n- return self.bracket_regex.search(line)\n+ return self.regex.search(line)\ndiff --git a/saltlint/rules/JinjaCommentHasSpacesRule.py b/saltlint/rules/JinjaCommentHasSpacesRule.py\nindex 6caa1b6..7c54719 100644\n--- a/saltlint/rules/JinjaCommentHasSpacesRule.py\n+++ b/saltlint/rules/JinjaCommentHasSpacesRule.py\n@@ -5,6 +5,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_JINJA, LANGUAGE_SLS\n \n \n class JinjaCommentHasSpacesRule(Rule):\n@@ -12,6 +13,7 @@ class JinjaCommentHasSpacesRule(Rule):\n shortdesc = 'Jinja comment should have spaces before and after: {# comment #}'\n description = 'Jinja comment should have spaces before and after: ``{# comment #}``'\n severity = 'LOW'\n+ languages = [LANGUAGE_SLS, LANGUAGE_JINJA]\n tags = ['formatting', 'jinja']\n version_added = 'v0.0.5'\n \ndiff --git a/saltlint/rules/JinjaPillarGrainsGetFormatRule.py b/saltlint/rules/JinjaPillarGrainsGetFormatRule.py\nindex efd8181..accace3 100644\n--- a/saltlint/rules/JinjaPillarGrainsGetFormatRule.py\n+++ b/saltlint/rules/JinjaPillarGrainsGetFormatRule.py\n@@ -5,6 +5,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_JINJA, LANGUAGE_SLS\n \n \n class JinjaPillarGrainsGetFormatRule(Rule):\n@@ -14,6 +15,7 @@ class JinjaPillarGrainsGetFormatRule(Rule):\n \"like salt['pillar.get']('item'), grains['item1'] or \" \\\n \" pillar.get('item')\"\n severity = 'HIGH'\n+ languages = [LANGUAGE_SLS, LANGUAGE_JINJA]\n tags = ['formatting', 'jinja']\n version_added = 'v0.0.10'\n \ndiff --git a/saltlint/rules/JinjaStatementHasSpacesRule.py b/saltlint/rules/JinjaStatementHasSpacesRule.py\nindex 6bcf290..59992e9 100644\n--- a/saltlint/rules/JinjaStatementHasSpacesRule.py\n+++ b/saltlint/rules/JinjaStatementHasSpacesRule.py\n@@ -5,6 +5,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_JINJA, LANGUAGE_SLS\n \n \n class JinjaStatementHasSpacesRule(Rule):\n@@ -12,6 +13,7 @@ class JinjaStatementHasSpacesRule(Rule):\n shortdesc = 'Jinja statement should have spaces before and after: {% statement %}'\n description = 'Jinja statement should have spaces before and after: ``{% statement %}``'\n severity = 'LOW'\n+ languages = [LANGUAGE_SLS, LANGUAGE_JINJA]\n tags = ['formatting', 'jinja']\n version_added = 'v0.0.2'\n \ndiff --git a/saltlint/rules/JinjaVariableHasSpacesRule.py b/saltlint/rules/JinjaVariableHasSpacesRule.py\nindex f864fce..53fd0eb 100644\n--- a/saltlint/rules/JinjaVariableHasSpacesRule.py\n+++ b/saltlint/rules/JinjaVariableHasSpacesRule.py\n@@ -5,6 +5,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_JINJA, LANGUAGE_SLS\n \n \n class JinjaVariableHasSpacesRule(Rule):\n@@ -12,6 +13,7 @@ class JinjaVariableHasSpacesRule(Rule):\n shortdesc = 'Jinja variables should have spaces before and after: {{ var_name }}'\n description = 'Jinja variables should have spaces before and after: ``{{ var_name }}``'\n severity = 'LOW'\n+ languages = [LANGUAGE_SLS, LANGUAGE_JINJA]\n tags = ['formatting', 'jinja']\n version_added = 'v0.0.1'\n \ndiff --git a/saltlint/rules/NoTabsRule.py b/saltlint/rules/NoTabsRule.py\nindex 57bfa90..2a06763 100644\n--- a/saltlint/rules/NoTabsRule.py\n+++ b/saltlint/rules/NoTabsRule.py\n@@ -4,6 +4,7 @@\n # Modified work Copyright (c) 2020 Warpnet B.V.\n \n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_SLS\n \n \n class NoTabsRule(Rule):\n@@ -11,6 +12,7 @@ class NoTabsRule(Rule):\n shortdesc = 'Most files should not contain tabs'\n description = 'Tabs can cause unexpected display issues, use spaces'\n severity = 'LOW'\n+ languages = [LANGUAGE_SLS]\n tags = ['formatting']\n version_added = 'v0.0.1'\n \ndiff --git a/saltlint/rules/SLSFileNameRule.py b/saltlint/rules/SLSFileNameRule.py\nnew file mode 100644\nindex 0000000..f251b50\n--- /dev/null\n+++ b/saltlint/rules/SLSFileNameRule.py\n@@ -0,0 +1,27 @@\n+# -*- coding: utf-8 -*-\n+# opyright (c) 2020 Warpnet B.V.\n+\n+import os\n+from saltlint.linter.rule import Rule\n+\n+\n+class SLSFileNameRule(Rule):\n+ id = '214'\n+ shortdesc = ('SLS file with a period in the name (besides the suffix period) can not be '\n+ 'referenced')\n+ description = ('SLS file with a period in the name (besides the suffix period) can not be '\n+ 'referenced')\n+ severity = 'HIGH'\n+ tags = ['formatting']\n+ version_added = 'develop'\n+\n+ def matchtext(self, file, text):\n+ results = []\n+ path = file['path']\n+ basename = os.path.basename(path)\n+ if len(basename.split('.')) > 2:\n+ line_no = 1\n+ lines = text.splitlines()\n+ line = lines[0] if len(lines) > 0 else ''\n+ results.append((line_no, line, self.shortdesc))\n+ return results\ndiff --git a/saltlint/rules/YamlHasOctalValueRule.py b/saltlint/rules/YamlHasOctalValueRule.py\nindex d39477c..57b4f82 100644\n--- a/saltlint/rules/YamlHasOctalValueRule.py\n+++ b/saltlint/rules/YamlHasOctalValueRule.py\n@@ -5,6 +5,7 @@\n \n import re\n from saltlint.linter.rule import Rule\n+from saltlint.utils import LANGUAGE_SLS\n \n \n class YamlHasOctalValueRule(Rule):\n@@ -12,6 +13,7 @@ class YamlHasOctalValueRule(Rule):\n shortdesc = 'Numbers that start with `0` should always be encapsulated in quotation marks'\n description = 'Numbers that start with `0` should always be encapsulated in quotation marks'\n severity = 'HIGH'\n+ languages = [LANGUAGE_SLS]\n tags = ['formatting']\n version_added = 'v0.0.6'\n \ndiff --git a/saltlint/utils.py b/saltlint/utils.py\nindex dbcdf23..5d8974d 100644\n--- a/saltlint/utils.py\n+++ b/saltlint/utils.py\n@@ -7,6 +7,10 @@ import imp\n import os\n \n \n+LANGUAGE_SLS = \"sls\"\n+LANGUAGE_JINJA = \"jinja\"\n+\n+\n def load_plugins(directory, config):\n result = []\n fh = None\n@@ -40,3 +44,12 @@ def get_rule_skips_from_text(text):\n \n # Return a list of unique ids\n return list(set(rule_id_list))\n+\n+def get_file_type(file_name):\n+ extension = os.path.splitext(file_name)[1].lower()\n+\n+ if extension == \".sls\":\n+ return LANGUAGE_SLS\n+ if extension in [\".jinja\", \".jinja2\"]:\n+ return LANGUAGE_JINJA\n+ return None\n", "test_patch": "diff --git a/tests/__init__.py b/tests/__init__.py\nindex 6c72cf6..9e6000c 100644\n--- a/tests/__init__.py\n+++ b/tests/__init__.py\n@@ -19,7 +19,7 @@ class RunFromText(object):\n return runner.run()\n \n def run_state(self, state_text):\n- with tempfile.NamedTemporaryFile() as fp:\n+ with tempfile.NamedTemporaryFile(suffix=\".sls\") as fp:\n fp.write(state_text.encode())\n fp.seek(0)\n results = self._call_runner(fp.name)\ndiff --git a/tests/test-extension-failure.extra.sls b/tests/test-extension-failure.extra.sls\nnew file mode 100644\nindex 0000000..e69de29\ndiff --git a/tests/unit/TestSLSFileNameRule.py b/tests/unit/TestSLSFileNameRule.py\nnew file mode 100644\nindex 0000000..770070a\n--- /dev/null\n+++ b/tests/unit/TestSLSFileNameRule.py\n@@ -0,0 +1,31 @@\n+# -*- coding: utf-8 -*-\n+# Copyright (c) 2020 Warpnet B.V.\n+\n+import unittest\n+\n+from saltlint.config import Configuration\n+from saltlint.linter.runner import Runner\n+from saltlint.linter.collection import RulesCollection\n+from saltlint.rules.SLSFileNameRule import SLSFileNameRule\n+\n+\n+class TestSLSFileNameRule(unittest.TestCase):\n+ collection = RulesCollection()\n+\n+ def setUp(self):\n+ self.collection.register(SLSFileNameRule())\n+\n+ def test_file_positive(self):\n+ path = 'tests/test-extension-success.sls'\n+ runner = Runner(self.collection, path, Configuration())\n+ self.assertEqual([], runner.run())\n+\n+ path = 'tests/test-extension-failure'\n+ runner = Runner(self.collection, path, Configuration())\n+ self.assertEqual([], runner.run())\n+\n+ def test_file_negative(self):\n+ path = 'tests/test-extension-failure.extra.sls'\n+ runner = Runner(self.collection, path, Configuration())\n+ errors = runner.run()\n+ self.assertEqual(1, len(errors))\n", "FAIL_TO_PASS": ["tests/unit/TestSLSFileNameRule.py::TestSLSFileNameRule::test_file_negative", "tests/unit/TestSLSFileNameRule.py::TestSLSFileNameRule::test_file_positive"]}], "all_FAIL_TO_PASS": ["tests/unit/TestCmdRunQuietRule.py::TestCmdRunQuietRule::test_statement_negative", "tests/unit/TestCmdRunQuietRule.py::TestCmdRunQuietRule::test_statement_positive", "tests/unit/TestSLSFileNameRule.py::TestSLSFileNameRule::test_file_negative", "tests/unit/TestSLSFileNameRule.py::TestSLSFileNameRule::test_file_positive"], "construction": "co-located: checkout base_commit; apply all bugs test_patches; fix all so all_FAIL_TO_PASS pass; gold=apply all gold_patch."} +{"task_id": "highcharts-for-python__highcharts-core-79_x2", "level": 2, "source": "swerebenchv2", "repo": "highcharts-for-python/highcharts-core", "image": "swerebenchv2/highcharts-for-python-highcharts-core:79-1e58948", "base_commit": "1e58948cf452844472c831d3432a3f28c012286c", "num_bugs": 2, "bugs": [{"instance_id": "highcharts-for-python__highcharts-core-79", "base_commit": "1e58948cf452844472c831d3432a3f28c012286c", "gold_patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 19ef09c..a433a73 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -1,6 +1,8 @@\n Release 1.3.0\n =========================================\n \n+* **BUGFIX:** Fixed incorrect serialization of datetime and Pandas ``Timestamp`` objects in ``.to_dict()`` and ``.to_json()`` (#74).\n+* **BUGFIX:** Fixed incorrect serialization of ``EnforcedNull`` in ``.to_dict()`` and ``.to_json()`` (#75).\n * **ENHANCEMENT:** Added ``__repr__()`` method for Highcharts Core for Python classes (#76).\n * **ENHANCEMENT:** Added ``__str__()`` method with special handling for difficult-to-read classes (#76).\n * **ENHANCEMENT:** Added ``Chart.get_script_tags()`` to retrieve Javascript ``