From 5ca09aa998cb63682902a24eb84d464f6991f69a Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 08:19:07 -0400 Subject: [PATCH 1/9] ci: Update solve.yml Use standard configuration for LLM compare. --- .github/workflows/solve.yml | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/.github/workflows/solve.yml b/.github/workflows/solve.yml index bc19308d..8afe1afd 100644 --- a/.github/workflows/solve.yml +++ b/.github/workflows/solve.yml @@ -14,31 +14,25 @@ on: instance_set: description: "Instance set to solve" type: string + default: verified_33_pct + required: true limits: description: "Limits to apply to the solver" type: choice required: true options: - - default - # Synthetic test solvers - - test_files=3 test_status_retry=3 code_files=0 # Code solvers building synthetic tests - test_files=3 test_status_retry=3 code_files=3 code_status_retry=3 - # Code file selection - - test_files=0 code_files=3 code_status_retry=0 - # Code solvers using only known synthetic tests - - test_files=0 code_files=3 code_status_retry=3 - - test_files=0 code_files=6 code_status_retry=3 context_tokens: description: "LLM token limit to apply to the solver" type: string required: false - default: "8000" + default: "16000" use_synthetic_tests: description: "Use synthetic tests" type: boolean required: false - default: true + default: false observe_synthetic_tests: description: "Observe synthetic tests" type: boolean @@ -50,17 +44,15 @@ on: default: SWE-Bench_Larger type: choice options: - - ubuntu-latest - - swe-bench-ubuntu-latest - SWE-Bench_Larger num_runners: description: "Number of runners to split the workload across" required: true - default: "2" + default: "3" name: description: "Assign a name to the workflow run" type: string - required: false + required: true pull_request: types: [opened, synchronize] From ac9e3c32beec0faaa20048bd8506ec877c0bc609 Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 11:17:07 -0400 Subject: [PATCH 2/9] feat: Add --no_link option to solver/import_solve_code_run.py --- solver/import_solve_code_run.py | 50 +++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/solver/import_solve_code_run.py b/solver/import_solve_code_run.py index 86b489e1..f9d6202f 100644 --- a/solver/import_solve_code_run.py +++ b/solver/import_solve_code_run.py @@ -29,7 +29,9 @@ def meets_score_threshold(code_patch_score: Optional[int]) -> bool: return code_patch_score is not None and code_patch_score >= SCORE_THRESHOLD -def import_workflow_run(run: github.WorkflowRun.WorkflowRun, no_download: bool = False): +def import_workflow_run( + run: github.WorkflowRun.WorkflowRun, no_download: bool = False, no_link=False +): target_dir = Path("data") / "solve_code_runs" / "run_id" / str(run.id) target_dir.mkdir(parents=True, exist_ok=True) @@ -59,33 +61,34 @@ def unpack_solutions(): # Delete solution_file parent directory recursively shutil.rmtree(solution_file.parent.parent) - # Iterate through the code patches and update the data / code_patches directory with a symlink to any - # new, complete test patches. - for code_patch_file in (target_dir / "code_patches").rglob("*.json"): - instance_id = code_patch_file.stem - target = Path("data") / "code_patches" / f"{instance_id}.json" - if target.exists(): - continue + if not no_link: + # Iterate through the code patches and update the data / code_patches directory with a symlink to any + # new, complete test patches. + for code_patch_file in (target_dir / "code_patches").rglob("*.json"): + instance_id = code_patch_file.stem + target = Path("data") / "code_patches" / f"{instance_id}.json" + if target.exists(): + continue - with code_patch_file.open() as f: - solution: Solution = load(f) + with code_patch_file.open() as f: + solution: Solution = load(f) - if not meets_score_threshold(solution["code_patch_score"]): - continue + if not meets_score_threshold(solution["code_patch_score"]): + continue - link_source = Path("..") / ".." / code_patch_file + link_source = Path("..") / ".." / code_patch_file - print(f"Importing new optimal code patch {instance_id}") - print(f"Link target: {target}") - print(f"Link source: {link_source}") + print(f"Importing new optimal code patch {instance_id}") + print(f"Link target: {target}") + print(f"Link source: {link_source}") - target.symlink_to(link_source) + target.symlink_to(link_source) - # Test the symlink - readlink(target) + # Test the symlink + readlink(target) -def main(run_id: int, no_download: bool = False): +def main(run_id: int, no_download: bool = False, no_link=False): github_token = getenv("GITHUB_TOKEN") if not github_token: raise ValueError("GITHUB_TOKEN is not set") @@ -96,7 +99,7 @@ def main(run_id: int, no_download: bool = False): if not run: raise ValueError(f"Run {run_id} not found") - import_workflow_run(run, no_download) + import_workflow_run(run, no_download, no_link) print(f"Imported workflow run {run_id}") @@ -117,6 +120,11 @@ def main(run_id: int, no_download: bool = False): action="store_true", help="Skip downloading the artifacts. Just unpack and organize the data", ) + parser.add_argument( + "--no_link", + action="store_true", + help="Skip linking the code patches to the data/code_patches directory", + ) args = parser.parse_args() From 1dfb7dfde004b9059c3d9a79c3fe75c8a4541b66 Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 11:17:35 -0400 Subject: [PATCH 3/9] data: gpt-4o llm-compare 10941127186 --- .../code_patches/astropy__astropy-12907.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-13398.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-13977.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-14309.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-14508.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-14995.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-7606.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-8872.json | 20 +++++++++++++++++++ .../code_patches/django__django-10880.json | 20 +++++++++++++++++++ .../code_patches/django__django-10999.json | 20 +++++++++++++++++++ .../code_patches/django__django-11095.json | 20 +++++++++++++++++++ .../code_patches/django__django-11133.json | 20 +++++++++++++++++++ .../code_patches/django__django-11149.json | 20 +++++++++++++++++++ .../code_patches/django__django-11206.json | 20 +++++++++++++++++++ .../code_patches/django__django-11265.json | 20 +++++++++++++++++++ .../code_patches/django__django-11299.json | 20 +++++++++++++++++++ .../code_patches/django__django-11433.json | 20 +++++++++++++++++++ .../code_patches/django__django-11490.json | 20 +++++++++++++++++++ .../code_patches/django__django-11555.json | 20 +++++++++++++++++++ .../code_patches/django__django-11734.json | 20 +++++++++++++++++++ .../code_patches/django__django-11790.json | 20 +++++++++++++++++++ .../code_patches/django__django-11848.json | 20 +++++++++++++++++++ .../code_patches/django__django-11951.json | 20 +++++++++++++++++++ .../code_patches/django__django-12039.json | 20 +++++++++++++++++++ .../code_patches/django__django-12143.json | 20 +++++++++++++++++++ .../code_patches/django__django-12209.json | 20 +++++++++++++++++++ .../code_patches/django__django-12276.json | 20 +++++++++++++++++++ .../code_patches/django__django-12325.json | 20 +++++++++++++++++++ .../code_patches/django__django-12663.json | 20 +++++++++++++++++++ .../code_patches/django__django-12741.json | 20 +++++++++++++++++++ .../code_patches/django__django-12858.json | 20 +++++++++++++++++++ .../code_patches/django__django-13023.json | 20 +++++++++++++++++++ .../code_patches/django__django-13089.json | 20 +++++++++++++++++++ .../code_patches/django__django-13121.json | 20 +++++++++++++++++++ .../code_patches/django__django-13195.json | 20 +++++++++++++++++++ .../code_patches/django__django-13297.json | 20 +++++++++++++++++++ .../code_patches/django__django-13344.json | 20 +++++++++++++++++++ .../code_patches/django__django-13401.json | 20 +++++++++++++++++++ .../code_patches/django__django-13417.json | 20 +++++++++++++++++++ .../code_patches/django__django-13513.json | 20 +++++++++++++++++++ .../code_patches/django__django-13568.json | 20 +++++++++++++++++++ .../code_patches/django__django-13658.json | 20 +++++++++++++++++++ .../code_patches/django__django-13786.json | 20 +++++++++++++++++++ .../code_patches/django__django-13809.json | 20 +++++++++++++++++++ .../code_patches/django__django-13821.json | 20 +++++++++++++++++++ .../code_patches/django__django-13933.json | 20 +++++++++++++++++++ .../code_patches/django__django-14011.json | 20 +++++++++++++++++++ .../code_patches/django__django-14053.json | 20 +++++++++++++++++++ .../code_patches/django__django-14140.json | 20 +++++++++++++++++++ .../code_patches/django__django-14238.json | 20 +++++++++++++++++++ .../code_patches/django__django-14349.json | 20 +++++++++++++++++++ .../code_patches/django__django-14376.json | 20 +++++++++++++++++++ .../code_patches/django__django-14493.json | 20 +++++++++++++++++++ .../code_patches/django__django-14539.json | 20 +++++++++++++++++++ .../code_patches/django__django-14608.json | 20 +++++++++++++++++++ .../code_patches/django__django-14725.json | 20 +++++++++++++++++++ .../code_patches/django__django-14771.json | 20 +++++++++++++++++++ .../code_patches/django__django-14855.json | 20 +++++++++++++++++++ .../code_patches/django__django-15022.json | 20 +++++++++++++++++++ .../code_patches/django__django-15103.json | 20 +++++++++++++++++++ .../code_patches/django__django-15128.json | 20 +++++++++++++++++++ .../code_patches/django__django-15268.json | 20 +++++++++++++++++++ .../code_patches/django__django-15280.json | 20 +++++++++++++++++++ .../code_patches/django__django-15375.json | 20 +++++++++++++++++++ .../code_patches/django__django-15467.json | 20 +++++++++++++++++++ .../code_patches/django__django-15525.json | 20 +++++++++++++++++++ .../code_patches/django__django-15563.json | 20 +++++++++++++++++++ .../code_patches/django__django-15629.json | 20 +++++++++++++++++++ .../code_patches/django__django-15732.json | 20 +++++++++++++++++++ .../code_patches/django__django-15851.json | 20 +++++++++++++++++++ .../code_patches/django__django-15930.json | 20 +++++++++++++++++++ .../code_patches/django__django-15987.json | 20 +++++++++++++++++++ .../code_patches/django__django-16100.json | 20 +++++++++++++++++++ .../code_patches/django__django-16139.json | 20 +++++++++++++++++++ .../code_patches/django__django-16256.json | 20 +++++++++++++++++++ .../code_patches/django__django-16333.json | 20 +++++++++++++++++++ .../code_patches/django__django-16485.json | 20 +++++++++++++++++++ .../code_patches/django__django-16527.json | 20 +++++++++++++++++++ .../code_patches/django__django-16595.json | 20 +++++++++++++++++++ .../code_patches/django__django-16642.json | 20 +++++++++++++++++++ .../code_patches/django__django-16667.json | 20 +++++++++++++++++++ .../code_patches/django__django-16877.json | 20 +++++++++++++++++++ .../code_patches/django__django-16938.json | 20 +++++++++++++++++++ .../code_patches/django__django-17084.json | 20 +++++++++++++++++++ .../code_patches/django__django-9296.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-20488.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-20859.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-22865.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-23314.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-24026.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-24570.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-24870.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-25287.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-25479.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-26342.json | 20 +++++++++++++++++++ .../code_patches/mwaskom__seaborn-3187.json | 20 +++++++++++++++++++ .../code_patches/psf__requests-1724.json | 20 +++++++++++++++++++ .../code_patches/psf__requests-2317.json | 20 +++++++++++++++++++ .../code_patches/psf__requests-6028.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-3151.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-3993.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-4356.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-4695.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-6599.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-6938.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-7233.json | 20 +++++++++++++++++++ .../code_patches/pylint-dev__pylint-4604.json | 20 +++++++++++++++++++ .../code_patches/pylint-dev__pylint-6386.json | 20 +++++++++++++++++++ .../code_patches/pylint-dev__pylint-7080.json | 20 +++++++++++++++++++ .../pytest-dev__pytest-10051.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-5262.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-5809.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-6202.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-7324.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-7521.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-8399.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-10908.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-12585.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-13124.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-13328.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-13779.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-14141.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-14710.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-15100.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-25747.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-26194.json | 20 +++++++++++++++++++ .../sphinx-doc__sphinx-10323.json | 20 +++++++++++++++++++ .../sphinx-doc__sphinx-10466.json | 20 +++++++++++++++++++ .../sphinx-doc__sphinx-11445.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-7454.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-7748.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-7910.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8056.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8269.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8548.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8595.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8721.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9258.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9367.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9602.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9698.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-12096.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-12489.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13372.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13615.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13798.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13878.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-14531.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-15017.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-15599.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-15976.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-16766.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-17139.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-17655.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-18211.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-19040.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-19637.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-20154.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-20590.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-21379.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-21847.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-22456.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-23262.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-23824.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-24213.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-24562.json | 20 +++++++++++++++++++ .../run_id/10941127186/predictions-0.zip | 3 +++ .../run_id/10941127186/predictions-1.zip | 3 +++ .../run_id/10941127186/predictions-2.zip | 3 +++ .../run_id/10941127186/report.zip | 3 +++ .../run_id/10941127186/run_evaluation-0.zip | 3 +++ .../run_id/10941127186/run_evaluation-1.zip | 3 +++ .../run_id/10941127186/run_evaluation-2.zip | 3 +++ .../run_id/10941127186/solutions.zip | 3 +++ .../run_id/10941127186/solve-0.zip | 3 +++ .../run_id/10941127186/solve-1.zip | 3 +++ .../run_id/10941127186/solve-2.zip | 3 +++ .../run_id/10941127186/test-patch.zip | 3 +++ 178 files changed, 3356 insertions(+) create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-12907.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13398.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13977.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14309.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14508.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14995.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-7606.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-8872.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-10880.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-10999.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11095.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11133.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11149.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11206.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11265.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11299.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11433.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11490.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11555.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11734.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11790.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11848.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-11951.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12039.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12143.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12209.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12276.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12325.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12663.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12741.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-12858.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13023.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13089.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13121.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13195.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13297.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13344.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13401.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13417.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13513.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13568.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13658.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13786.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13809.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13821.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-13933.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14011.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14053.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14140.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14238.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14349.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14376.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14493.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14539.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14608.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14725.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14771.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-14855.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15022.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15103.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15128.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15268.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15280.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15375.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15467.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15525.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15563.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15629.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15732.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15851.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15930.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-15987.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16100.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16139.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16256.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16333.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16485.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16527.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16595.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16642.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16667.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16877.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-16938.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-17084.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/django__django-9296.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20488.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20859.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-22865.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-23314.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24026.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24570.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24870.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25287.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25479.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-26342.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/mwaskom__seaborn-3187.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-1724.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-2317.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-6028.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3151.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3993.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4356.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4695.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6599.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6938.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-7233.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-4604.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-6386.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-7080.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-10051.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5262.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5809.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-6202.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7324.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7521.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-8399.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-10908.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-12585.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13124.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13328.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13779.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14141.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14710.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-15100.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-25747.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-26194.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10323.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10466.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-11445.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7454.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7748.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7910.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8056.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8269.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8548.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8595.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8721.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9258.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9367.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9602.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9698.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12096.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12489.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13372.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13615.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13798.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13878.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-14531.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15017.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15599.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15976.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-16766.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17139.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17655.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-18211.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19040.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19637.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20154.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20590.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21379.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21847.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-22456.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23262.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23824.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24213.json create mode 100644 data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24562.json create mode 100644 data/solve_code_runs/run_id/10941127186/predictions-0.zip create mode 100644 data/solve_code_runs/run_id/10941127186/predictions-1.zip create mode 100644 data/solve_code_runs/run_id/10941127186/predictions-2.zip create mode 100644 data/solve_code_runs/run_id/10941127186/report.zip create mode 100644 data/solve_code_runs/run_id/10941127186/run_evaluation-0.zip create mode 100644 data/solve_code_runs/run_id/10941127186/run_evaluation-1.zip create mode 100644 data/solve_code_runs/run_id/10941127186/run_evaluation-2.zip create mode 100644 data/solve_code_runs/run_id/10941127186/solutions.zip create mode 100644 data/solve_code_runs/run_id/10941127186/solve-0.zip create mode 100644 data/solve_code_runs/run_id/10941127186/solve-1.zip create mode 100644 data/solve_code_runs/run_id/10941127186/solve-2.zip create mode 100644 data/solve_code_runs/run_id/10941127186/test-patch.zip diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-12907.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-12907.json new file mode 100644 index 00000000..7613fe73 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-12907.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-12907", + "edit_test_file": "astropy/modeling/tests/test_separable.py", + "code_patch": "diff --git a/astropy/modeling/separable.py b/astropy/modeling/separable.py\nindex a308e27..765664b 100644\n--- a/astropy/modeling/separable.py\n+++ b/astropy/modeling/separable.py\n@@ -98,9 +98,28 @@ def separability_matrix(transform):\n return np.ones((transform.n_outputs, transform.n_inputs),\n dtype=np.bool_)\n separable_matrix = _separable(transform)\n+ # Recursively evaluate separability for nested CompoundModels\n+ if isinstance(transform, CompoundModel):\n+ left_matrix = separability_matrix(transform.left)\n+ right_matrix = separability_matrix(transform.right)\n+ separable_matrix = _combine_matrices(left_matrix, right_matrix, transform.op)\n separable_matrix = np.where(separable_matrix != 0, True, False)\n return separable_matrix\n \n+def _combine_matrices(left_matrix, right_matrix, operation):\n+ \"\"\"\n+ Combine separability matrices of two sub-models based on the operation.\n+ \"\"\"\n+ if operation == '&':\n+ return np.block([\n+ [left_matrix, np.zeros((left_matrix.shape[0], right_matrix.shape[1]), dtype=bool)],\n+ [np.zeros((right_matrix.shape[0], left_matrix.shape[1]), dtype=bool), right_matrix]\n+ ])\n+ elif operation == '|':\n+ return np.dot(left_matrix, right_matrix)\n+ else:\n+ raise ValueError(f\"Unsupported operation: {operation}\")\n+\n \n def _compute_n_outputs(left, right):\n \"\"\"\n", + "test_patch": "diff --git a/astropy/modeling/tests/test_nested_compound_models.py b/astropy/modeling/tests/test_nested_compound_models.py\nnew file mode 100644\nindex 0000000..6b54730\n--- /dev/null\n+++ b/astropy/modeling/tests/test_nested_compound_models.py\n@@ -0,0 +1,25 @@\n+import numpy as np\n+from numpy.testing import assert_allclose\n+from astropy.modeling import models as m\n+from astropy.modeling.separable import separability_matrix\n+\n+def test_nested_compound_model_separability():\n+ # Create a simple compound model\n+ cm = m.Linear1D(10) & m.Linear1D(5)\n+ \n+ # Create a more complex compound model by nesting\n+ nested_cm = m.Pix2Sky_TAN() & cm\n+ \n+ # Expected separability matrix for the nested compound model\n+ expected_separability = np.array([\n+ [True, True, False, False],\n+ [True, True, False, False],\n+ [False, False, True, True],\n+ [False, False, True, True]\n+ ])\n+ \n+ # Compute the separability matrix for the nested compound model\n+ computed_separability = separability_matrix(nested_cm)\n+ \n+ # Assert that the computed separability matrix matches the expected incorrect output\n+ assert_allclose(computed_separability, expected_separability)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/modeling/tests/test_nested_compound_models_inverted.py b/astropy/modeling/tests/test_nested_compound_models_inverted.py\nnew file mode 100644\nindex 0000000..d882bed\n--- /dev/null\n+++ b/astropy/modeling/tests/test_nested_compound_models_inverted.py\n@@ -0,0 +1,29 @@\n+import numpy as np\n+from numpy.testing import assert_allclose\n+from astropy.modeling import models as m\n+from astropy.modeling.separable import separability_matrix\n+\n+def test_nested_compound_model_separability():\n+ # Create a simple compound model\n+ cm = m.Linear1D(10) & m.Linear1D(5)\n+ \n+ # Create a more complex compound model by nesting\n+ nested_cm = m.Pix2Sky_TAN() & cm\n+ \n+ # Expected correct separability matrix for the nested compound model\n+ expected_separability = np.array([\n+ [True, True, False, False],\n+ [True, True, False, False],\n+ [False, False, True, False],\n+ [False, False, False, True]\n+ ])\n+ \n+ # Compute the separability matrix for the nested compound model\n+ computed_separability = separability_matrix(nested_cm)\n+ \n+ # Assert that the computed separability matrix matches the expected correct output\n+ # This should fail if the bug is present\n+ try:\n+ assert_allclose(computed_separability, expected_separability)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1658629, + "num_received_chars": 81119, + "elapsed_time": 558.5764768123627, + "lint_repair_count": 5, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13398.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13398.json new file mode 100644 index 00000000..3c4b6c78 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13398.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-13398", + "edit_test_file": null, + "code_patch": "diff --git a/astropy/coordinates/builtin_frames/itrs.py b/astropy/coordinates/builtin_frames/itrs.py\nindex e121ec9..2e3ee2b 100644\n--- a/astropy/coordinates/builtin_frames/itrs.py\n+++ b/astropy/coordinates/builtin_frames/itrs.py\n@@ -34,5 +34,15 @@ class ITRS(BaseCoordinateFrame):\n cart = self.represent_as(CartesianRepresentation)\n return EarthLocation(x=cart.x, y=cart.y, z=cart.z)\n \n+ def transform_to_altaz(self, altaz_frame):\n+ # Compute the transformation matrix for ITRS to AltAz\n+ # Apply the matrix to transform the coordinates\n+ pass\n+\n+ def transform_to_hadec(self, hadec_frame):\n+ # Compute the transformation matrix for ITRS to HADec\n+ # Apply the matrix to transform the coordinates\n+ pass\n+\n # Self-transform is in intermediate_rotation_transforms.py with all the other\n # ITRS transforms\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 721226, + "num_received_chars": 21847, + "elapsed_time": 156.82384634017944, + "lint_repair_count": 3, + "test_generation_attempts": 0, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13977.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13977.json new file mode 100644 index 00000000..3b46c59a --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-13977.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-13977", + "edit_test_file": "astropy/units/tests/test_quantity.py", + "code_patch": "diff --git a/astropy/units/function/core.py b/astropy/units/function/core.py\nindex f37684c..5076d36 100644\n--- a/astropy/units/function/core.py\n+++ b/astropy/units/function/core.py\n@@ -621,11 +621,12 @@ class FunctionQuantity(Quantity):\n # And really it should just return NotImplemented, since possibly\n # another argument might know what to do.\n if function not in self._supported_ufuncs:\n- raise UnitTypeError(\n- f\"Cannot use ufunc '{function.__name__}' with function quantities\"\n- )\n+ return NotImplemented\n \n- return super().__array_ufunc__(function, method, *inputs, **kwargs)\n+ try:\n+ return super().__array_ufunc__(function, method, *inputs, **kwargs)\n+ except UnitTypeError:\n+ return NotImplemented\n \n def _maybe_new_view(self, result):\n \"\"\"View as function quantity if the unit is unchanged.\n", + "test_patch": "diff --git a/astropy/units/tests/test_quantity_array_ufunc_handling.py b/astropy/units/tests/test_quantity_array_ufunc_handling.py\nnew file mode 100644\nindex 0000000..4334bd6\n--- /dev/null\n+++ b/astropy/units/tests/test_quantity_array_ufunc_handling.py\n@@ -0,0 +1,33 @@\n+# Licensed under a 3-clause BSD style license - see LICENSE.rst\n+\"\"\"Test the handling of Quantity.__array_ufunc__ for duck types.\"\"\"\n+\n+import dataclasses\n+import numpy as np\n+import pytest\n+from astropy import units as u\n+\n+\n+@dataclasses.dataclass\n+class DuckArray(np.lib.mixins.NDArrayOperatorsMixin):\n+ ndarray: u.Quantity\n+\n+ @property\n+ def unit(self) -> u.UnitBase:\n+ return self.ndarray.unit\n+\n+ def __array_ufunc__(self, function, method, *inputs, **kwargs):\n+ inputs = [inp.ndarray if isinstance(inp, DuckArray) else inp for inp in inputs]\n+\n+ for inp in inputs:\n+ if isinstance(inp, np.ndarray):\n+ result = inp.__array_ufunc__(function, method, *inputs, **kwargs)\n+ if result is not NotImplemented:\n+ return DuckArray(result)\n+\n+ return NotImplemented\n+\n+\n+def test_quantity_array_ufunc_handling():\n+ \"\"\"Test that Quantity.__array_ufunc__ raises ValueError for incompatible units.\"\"\"\n+ with pytest.raises(ValueError, match=\"Value not scalar compatible or convertible to an int, float, or complex array\"):\n+ _ = (1 * u.m) + DuckArray(1 * u.mm)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/units/tests/test_quantity_array_ufunc_handling_inverted.py b/astropy/units/tests/test_quantity_array_ufunc_handling_inverted.py\nnew file mode 100644\nindex 0000000..8edbfc7\n--- /dev/null\n+++ b/astropy/units/tests/test_quantity_array_ufunc_handling_inverted.py\n@@ -0,0 +1,35 @@\n+# Licensed under a 3-clause BSD style license - see LICENSE.rst\n+\"\"\"Test the handling of Quantity.__array_ufunc__ for duck types.\"\"\"\n+\n+import dataclasses\n+import numpy as np\n+import pytest\n+from astropy import units as u\n+\n+\n+@dataclasses.dataclass\n+class DuckArray(np.lib.mixins.NDArrayOperatorsMixin):\n+ ndarray: u.Quantity\n+\n+ @property\n+ def unit(self) -> u.UnitBase:\n+ return self.ndarray.unit\n+\n+ def __array_ufunc__(self, function, method, *inputs, **kwargs):\n+ inputs = [inp.ndarray if isinstance(inp, DuckArray) else inp for inp in inputs]\n+\n+ for inp in inputs:\n+ if isinstance(inp, np.ndarray):\n+ result = inp.__array_ufunc__(function, method, *inputs, **kwargs)\n+ if result is not NotImplemented:\n+ return DuckArray(result)\n+\n+ return NotImplemented\n+\n+\n+def test_quantity_array_ufunc_handling():\n+ \"\"\"Test that Quantity.__array_ufunc__ returns NotImplemented for incompatible units.\"\"\"\n+ try:\n+ _ = (1 * u.m) + DuckArray(1 * u.mm)\n+ except ValueError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1133717, + "num_received_chars": 46392, + "elapsed_time": 388.36309242248535, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14309.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14309.json new file mode 100644 index 00000000..62d95d74 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14309.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-14309", + "edit_test_file": "astropy/io/registry/tests/test_registries.py", + "code_patch": "diff --git a/astropy/io/fits/connect.py b/astropy/io/fits/connect.py\nindex 4b6150f..1f51fe4 100644\n--- a/astropy/io/fits/connect.py\n+++ b/astropy/io/fits/connect.py\n@@ -69,7 +69,7 @@ def is_fits(origin, filepath, fileobj, *args, **kwargs):\n (\".fits\", \".fits.gz\", \".fit\", \".fit.gz\", \".fts\", \".fts.gz\")\n ):\n return True\n- return isinstance(args[0], (HDUList, TableHDU, BinTableHDU, GroupsHDU))\n+ return len(args) > 0 and isinstance(args[0], (HDUList, TableHDU, BinTableHDU, GroupsHDU))\n \n \n def _decode_mixins(tbl):\n", + "test_patch": "diff --git a/astropy/io/registry/tests/test_identify_format_indexerror.py b/astropy/io/registry/tests/test_identify_format_indexerror.py\nnew file mode 100644\nindex 0000000..bcecdee\n--- /dev/null\n+++ b/astropy/io/registry/tests/test_identify_format_indexerror.py\n@@ -0,0 +1,9 @@\n+# Licensed under a 3-clause BSD style license - see LICENSE.rst\n+\n+import pytest\n+from astropy.io.registry import identify_format\n+from astropy.table import Table\n+\n+def test_identify_format_indexerror():\n+ with pytest.raises(IndexError, match=\"tuple index out of range\"):\n+ identify_format(\"write\", Table, \"bububu.ecsv\", None, [], {})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/io/registry/tests/test_identify_format_indexerror_inverted.py b/astropy/io/registry/tests/test_identify_format_indexerror_inverted.py\nnew file mode 100644\nindex 0000000..d614a25\n--- /dev/null\n+++ b/astropy/io/registry/tests/test_identify_format_indexerror_inverted.py\n@@ -0,0 +1,14 @@\n+# Licensed under a 3-clause BSD style license - see LICENSE.rst\n+\n+import pytest\n+from astropy.io.registry import identify_format\n+from astropy.table import Table\n+\n+def test_identify_format_indexerror():\n+ try:\n+ identify_format(\"write\", Table, \"bububu.ecsv\", None, [], {})\n+ except IndexError as e:\n+ assert str(e) == \"tuple index out of range\"\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1204168, + "num_received_chars": 29181, + "elapsed_time": 388.12353682518005, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14508.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14508.json new file mode 100644 index 00000000..b5f766c1 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14508.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-14508", + "edit_test_file": null, + "code_patch": "diff --git a/astropy/io/fits/card.py b/astropy/io/fits/card.py\nindex 118bfce..6ddff8b 100644\n--- a/astropy/io/fits/card.py\n+++ b/astropy/io/fits/card.py\n@@ -1299,20 +1299,25 @@ def _format_value(value):\n \n def _format_float(value):\n \"\"\"Format a floating number to make sure it gets the decimal point.\"\"\"\n- value_str = f\"{value:.16G}\"\n- if \".\" not in value_str and \"E\" not in value_str:\n- value_str += \".0\"\n- elif \"E\" in value_str:\n- # On some Windows builds of Python (and possibly other platforms?) the\n- # exponent is zero-padded out to, it seems, three digits. Normalize\n- # the format to pad only to two digits.\n- significand, exponent = value_str.split(\"E\")\n- if exponent[0] in (\"+\", \"-\"):\n- sign = exponent[0]\n- exponent = exponent[1:]\n- else:\n- sign = \"\"\n- value_str = f\"{significand}E{sign}{int(exponent):02d}\"\n+ # Attempt to use Python's default string representation\n+ value_str = str(value)\n+ \n+ # If the default representation exceeds 20 characters, fallback to .16G formatting\n+ if len(value_str) > 20:\n+ value_str = f\"{value:.16G}\"\n+ if \".\" not in value_str and \"E\" not in value_str:\n+ value_str += \".0\"\n+ elif \"E\" in value_str:\n+ # On some Windows builds of Python (and possibly other platforms?) the\n+ # exponent is zero-padded out to, it seems, three digits. Normalize\n+ # the format to pad only to two digits.\n+ significand, exponent = value_str.split(\"E\")\n+ if exponent[0] in (\"+\", \"-\"):\n+ sign = exponent[0]\n+ exponent = exponent[1:]\n+ else:\n+ sign = \"\"\n+ value_str = f\"{significand}E{sign}{int(exponent):02d}\"\n \n # Limit the value string to at most 20 characters.\n str_len = len(value_str)\n@@ -1324,7 +1329,6 @@ def _format_float(value):\n value_str = value_str[:20]\n else:\n value_str = value_str[: 20 - (str_len - idx)] + value_str[idx:]\n-\n return value_str\n \n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 3398876, + "num_received_chars": 49236, + "elapsed_time": 483.1543028354645, + "lint_repair_count": 6, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14995.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14995.json new file mode 100644 index 00000000..3a8a2d69 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-14995.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-14995", + "edit_test_file": "astropy/utils/masked/tests/test_masked.py", + "code_patch": "diff --git a/astropy/nddata/mixins/ndarithmetic.py b/astropy/nddata/mixins/ndarithmetic.py\nindex 4153dfc..33fd832 100644\n--- a/astropy/nddata/mixins/ndarithmetic.py\n+++ b/astropy/nddata/mixins/ndarithmetic.py\n@@ -512,18 +512,18 @@ class NDArithmeticMixin:\n If neither had a mask ``None`` is returned. Otherwise\n ``handle_mask`` must create (and copy) the returned mask.\n \"\"\"\n- # If only one mask is present we need not bother about any type checks\n- if (\n- self.mask is None and operand is not None and operand.mask is None\n- ) or handle_mask is None:\n- return None\n- elif self.mask is None and operand is not None:\n- # Make a copy so there is no reference in the result.\n+ # If only one mask is present, return a copy of the existing mask\n+ if self.mask is None and operand is not None and operand.mask is not None:\n return deepcopy(operand.mask)\n- elif operand is None:\n+ elif operand is None and self.mask is not None:\n return deepcopy(self.mask)\n+ elif handle_mask is None:\n+ return None\n+ elif self.mask is None or operand.mask is None:\n+ # If one mask is None, avoid bitwise operation and return the existing mask\n+ return deepcopy(self.mask if operand.mask is None else operand.mask)\n else:\n- # Now lets calculate the resulting mask (operation enforces copy)\n+ # Now let's calculate the resulting mask (operation enforces copy)\n return handle_mask(self.mask, operand.mask, **kwds)\n \n def _arithmetic_wcs(self, operation, operand, compare_wcs, **kwds):\n", + "test_patch": "diff --git a/astropy/utils/masked/tests/test_nddataref_mask_propagation_issue.py b/astropy/utils/masked/tests/test_nddataref_mask_propagation_issue.py\nnew file mode 100644\nindex 0000000..e33eba6\n--- /dev/null\n+++ b/astropy/utils/masked/tests/test_nddataref_mask_propagation_issue.py\n@@ -0,0 +1,19 @@\n+# Licensed under a 3-clause BSD style license - see LICENSE.rst\n+import numpy as np\n+import pytest\n+from astropy.nddata import NDDataRef\n+\n+def test_nddataref_mask_propagation_issue():\n+ array = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])\n+ mask = np.array([[0, 1, 64], [8, 0, 1], [2, 1, 0]])\n+\n+ nref_nomask = NDDataRef(array)\n+ nref_mask = NDDataRef(array, mask=mask)\n+\n+ # Test multiplication of mask by constant (mask * no mask)\n+ with pytest.raises(TypeError, match=\"unsupported operand type(s) for |: 'int' and 'NoneType'\"):\n+ nref_mask.multiply(1., handle_mask=np.bitwise_or).mask\n+\n+ # Test multiplication of mask by no mask (mask * no mask)\n+ with pytest.raises(TypeError, match=\"unsupported operand type(s) for |: 'int' and 'NoneType'\"):\n+ nref_mask.multiply(nref_nomask, handle_mask=np.bitwise_or).mask\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/utils/masked/tests/test_nddataref_mask_propagation_issue_inverted.py b/astropy/utils/masked/tests/test_nddataref_mask_propagation_issue_inverted.py\nnew file mode 100644\nindex 0000000..1b73efe\n--- /dev/null\n+++ b/astropy/utils/masked/tests/test_nddataref_mask_propagation_issue_inverted.py\n@@ -0,0 +1,23 @@\n+# Licensed under a 3-clause BSD style license - see LICENSE.rst\n+import numpy as np\n+import pytest\n+from astropy.nddata import NDDataRef\n+\n+def test_nddataref_mask_propagation_issue():\n+ array = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])\n+ mask = np.array([[0, 1, 64], [8, 0, 1], [2, 1, 0]])\n+\n+ nref_nomask = NDDataRef(array)\n+ nref_mask = NDDataRef(array, mask=mask)\n+\n+ # Test multiplication of mask by constant (mask * no mask)\n+ with pytest.raises(TypeError, match=\"__BUG__HERE__\"):\n+ result_mask = nref_mask.multiply(1., handle_mask=np.bitwise_or).mask\n+ if result_mask is not None:\n+ raise TypeError(\"__BUG__HERE__\")\n+\n+ # Test multiplication of mask by no mask (mask * no mask)\n+ with pytest.raises(TypeError, match=\"__BUG__HERE__\"):\n+ result_mask = nref_mask.multiply(nref_nomask, handle_mask=np.bitwise_or).mask\n+ if result_mask is not None:\n+ raise TypeError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 901725, + "num_received_chars": 24610, + "elapsed_time": 268.9917984008789, + "lint_repair_count": 1, + "test_generation_attempts": 6, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-7606.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-7606.json new file mode 100644 index 00000000..1bbc551e --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-7606.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-7606", + "edit_test_file": "astropy/units/tests/test_units.py", + "code_patch": "diff --git a/astropy/units/core.py b/astropy/units/core.py\nindex e9bd986..1b20239 100644\n--- a/astropy/units/core.py\n+++ b/astropy/units/core.py\n@@ -1710,6 +1710,8 @@ class UnrecognizedUnit(IrreducibleUnit):\n _unrecognized_operator\n \n def __eq__(self, other):\n+ if other is None:\n+ return False\n other = Unit(other, parse_strict='silent')\n return isinstance(other, UnrecognizedUnit) and self.name == other.name\n \n", + "test_patch": "diff --git a/astropy/units/tests/test_unrecognizedunit_none_comparison.py b/astropy/units/tests/test_unrecognizedunit_none_comparison.py\nnew file mode 100644\nindex 0000000..d17b2eb\n--- /dev/null\n+++ b/astropy/units/tests/test_unrecognizedunit_none_comparison.py\n@@ -0,0 +1,9 @@\n+# astropy/units/tests/test_unrecognizedunit_none_comparison.py\n+\n+import pytest\n+from astropy import units as u\n+\n+def test_unrecognized_unit_none_comparison():\n+ x = u.Unit('asdf', parse_strict='silent')\n+ with pytest.raises(TypeError, match=\"None is not a valid Unit\"):\n+ result = (x == None) # noqa: E711\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 3470179, + "num_received_chars": 40069, + "elapsed_time": 478.1723277568817, + "lint_repair_count": 12, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-8872.json b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-8872.json new file mode 100644 index 00000000..faa82460 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/astropy__astropy-8872.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-8872", + "edit_test_file": "astropy/utils/tests/test_data_info.py", + "code_patch": "diff --git a/astropy/units/quantity.py b/astropy/units/quantity.py\nindex ded609c..899cbce 100644\n--- a/astropy/units/quantity.py\n+++ b/astropy/units/quantity.py\n@@ -377,10 +377,11 @@ class Quantity(np.ndarray, metaclass=InheritDocstrings):\n \"Numpy numeric type.\")\n \n # by default, cast any integer, boolean, etc., to float\n- if dtype is None and (not (np.can_cast(np.float32, value.dtype)\n+ if dtype is None and (not (np.can_cast(np.float16, value.dtype)\n+ or np.can_cast(np.float32, value.dtype)\n or value.dtype.fields)\n or value.dtype.kind == 'O'):\n- value = value.astype(float)\n+ value = value.astype(value.dtype)\n \n value = value.view(cls)\n value._set_unit(value_unit)\n", + "test_patch": "diff --git a/astropy/utils/tests/test_quantity_type_conversion.py b/astropy/utils/tests/test_quantity_type_conversion.py\nnew file mode 100644\nindex 0000000..3217084\n--- /dev/null\n+++ b/astropy/utils/tests/test_quantity_type_conversion.py\n@@ -0,0 +1,15 @@\n+import numpy as np\n+from astropy import units as u\n+import unittest\n+\n+class TestQuantityTypeConversion(unittest.TestCase):\n+ def test_float16_to_quantity_conversion(self):\n+ \"\"\"\n+ Test that creating a Quantity from a np.float16 results in a dtype of float64.\n+ This reproduces the issue where np.float16 is automatically upgraded to np.float64.\n+ \"\"\"\n+ quantity = np.float16(1) * u.km\n+ self.assertEqual(quantity.dtype, np.float64)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/utils/tests/test_quantity_type_conversion_inverted.py b/astropy/utils/tests/test_quantity_type_conversion_inverted.py\nnew file mode 100644\nindex 0000000..cc28558\n--- /dev/null\n+++ b/astropy/utils/tests/test_quantity_type_conversion_inverted.py\n@@ -0,0 +1,18 @@\n+import numpy as np\n+from astropy import units as u\n+import unittest\n+\n+class TestQuantityTypeConversion(unittest.TestCase):\n+ def test_float16_to_quantity_conversion(self):\n+ \"\"\"\n+ Test that creating a Quantity from a np.float16 results in a dtype of float64.\n+ This reproduces the issue where np.float16 is automatically upgraded to np.float64.\n+ \"\"\"\n+ quantity = np.float16(1) * u.km\n+ # The test should now fail if the dtype is float64, indicating the presence of the bug.\n+ if quantity.dtype == np.float64:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(quantity.dtype, np.float16)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1667898, + "num_received_chars": 63689, + "elapsed_time": 466.76476216316223, + "lint_repair_count": 9, + "test_generation_attempts": 1, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-10880.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-10880.json new file mode 100644 index 00000000..d6b4071e --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-10880.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-10880", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py\nindex 87852bc..78f4fd5 100644\n--- a/django/db/models/sql/compiler.py\n+++ b/django/db/models/sql/compiler.py\n@@ -396,6 +396,11 @@ class SQLCompiler:\n sql, params = vendor_impl(self, self.connection)\n else:\n sql, params = node.as_sql(self, self.connection)\n+ \n+ # Ensure space between DISTINCT and CASE when both are present\n+ if 'DISTINCT' in sql and 'CASE' in sql:\n+ sql = sql.replace('DISTINCTCASE', 'DISTINCT CASE')\n+ \n if select_format is FORCE or (select_format and not self.query.subquery):\n return node.output_field.select_format(self, sql, params)\n return sql, params\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1016226, + "num_received_chars": 19377, + "elapsed_time": 199.07030820846558, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-10999.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-10999.json new file mode 100644 index 00000000..793ab872 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-10999.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-10999", + "edit_test_file": "tests/forms_tests/field_tests/test_durationfield.py", + "code_patch": "diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py\nindex 8d08b7d..a037758 100644\n--- a/django/utils/dateparse.py\n+++ b/django/utils/dateparse.py\n@@ -29,7 +29,7 @@ datetime_re = re.compile(\n standard_duration_re = re.compile(\n r'^'\n r'(?:(?P-?\\d+) (days?, )?)?'\n- r'((?:(?P-?\\d+):)(?=\\d+:\\d+))?'\n+ r'((?:(?P-?\\d+):)(?=-?\\d+:-?\\d+))?'\n r'(?:(?P-?\\d+):)?'\n r'(?P-?\\d+)'\n r'(?:\\.(?P\\d{1,6})\\d{0,6})?'\n", + "test_patch": "diff --git a/tests/forms_tests/field_tests/test_parse_duration.py b/tests/forms_tests/field_tests/test_parse_duration.py\nnew file mode 100644\nindex 0000000..a59ddce\n--- /dev/null\n+++ b/tests/forms_tests/field_tests/test_parse_duration.py\n@@ -0,0 +1,14 @@\n+import unittest\n+from datetime import timedelta\n+from django.utils.dateparse import parse_duration\n+\n+class TestParseDurationNegative(unittest.TestCase):\n+ def test_negative_duration(self):\n+ # This test is expected to fail due to the issue with negative durations\n+ test_values = (\n+ ('-1:15:30', timedelta(hours=-1, minutes=15, seconds=30)),\n+ ('-4 15:30', timedelta(days=-4, minutes=15, seconds=30)),\n+ )\n+ for source, expected in test_values:\n+ with self.subTest(source=source):\n+ self.assertEqual(parse_duration(source), expected)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/forms_tests/field_tests/test_parse_duration_inverted.py b/tests/forms_tests/field_tests/test_parse_duration_inverted.py\nnew file mode 100644\nindex 0000000..9a5d6c5\n--- /dev/null\n+++ b/tests/forms_tests/field_tests/test_parse_duration_inverted.py\n@@ -0,0 +1,17 @@\n+import unittest\n+from datetime import timedelta\n+from django.utils.dateparse import parse_duration\n+\n+class TestParseDurationNegative(unittest.TestCase):\n+ def test_negative_duration(self):\n+ # This test is expected to fail due to the issue with negative durations\n+ test_values = (\n+ ('-1:15:30', timedelta(hours=-1, minutes=15, seconds=30)),\n+ ('-4 15:30', timedelta(days=-4, minutes=15, seconds=30)),\n+ )\n+ for source, expected in test_values:\n+ with self.subTest(source=source):\n+ result = parse_duration(source)\n+ if result == expected:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertNotEqual(result, expected)\n\\ No newline at end of file\n", + "num_sent_chars": 1449401, + "num_received_chars": 30927, + "elapsed_time": 344.44593477249146, + "lint_repair_count": 0, + "test_generation_attempts": 7, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11095.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11095.json new file mode 100644 index 00000000..ace865d9 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11095.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11095", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 5e7b23f..cbbb96a 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -580,9 +580,15 @@ class ModelAdmin(BaseModelAdmin):\n def __str__(self):\n return \"%s.%s\" % (self.model._meta.app_label, self.__class__.__name__)\n \n+ def get_inlines(self, request, obj=None):\n+ \"\"\"\n+ Hook for specifying custom inlines.\n+ \"\"\"\n+ return self.inlines\n+\n def get_inline_instances(self, request, obj=None):\n inline_instances = []\n- for inline_class in self.inlines:\n+ for inline_class in self.get_inlines(request, obj):\n inline = inline_class(self.model, self.admin_site)\n if request:\n if not (inline.has_view_or_change_permission(request, obj) or\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1237852, + "num_received_chars": 29550, + "elapsed_time": 224.17871046066284, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11133.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11133.json new file mode 100644 index 00000000..0fea710e --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11133.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11133", + "edit_test_file": null, + "code_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex 6a84e19..ffbf12a 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -309,7 +309,7 @@ class HttpResponse(HttpResponseBase):\n @content.setter\n def content(self, value):\n # Consume iterators upon assignment to allow repeated iteration.\n- if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):\n+ if hasattr(value, '__iter__') and not isinstance(value, (bytes, str, memoryview)):\n content = b''.join(self.make_bytes(chunk) for chunk in value)\n if hasattr(value, 'close'):\n try:\n@@ -317,6 +317,8 @@ class HttpResponse(HttpResponseBase):\n except Exception:\n pass\n else:\n+ if isinstance(value, memoryview):\n+ value = value.tobytes()\n content = self.make_bytes(value)\n # Create a list of properly encoded bytestrings to support write().\n self._container = [content]\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 878090, + "num_received_chars": 14239, + "elapsed_time": 168.32585668563843, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11149.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11149.json new file mode 100644 index 00000000..ace0c664 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11149.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11149", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 880a2cc..b52079a 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -2030,19 +2030,36 @@ class InlineModelAdmin(BaseModelAdmin):\n # default.\n exclude = exclude or None\n can_delete = self.can_delete and self.has_delete_permission(request, obj)\n- defaults = {\n- 'form': self.form,\n- 'formset': self.formset,\n- 'fk_name': self.fk_name,\n- 'fields': fields,\n- 'exclude': exclude,\n- 'formfield_callback': partial(self.formfield_for_dbfield, request=request),\n- 'extra': self.get_extra(request, obj, **kwargs),\n- 'min_num': self.get_min_num(request, obj, **kwargs),\n- 'max_num': self.get_max_num(request, obj, **kwargs),\n- 'can_delete': can_delete,\n- **kwargs,\n- }\n+ can_add = self.has_add_permission(request, obj)\n+ can_change = self.has_change_permission(request, obj)\n+ if not (can_add or can_change or can_delete):\n+ defaults = {\n+ 'form': self.form,\n+ 'formset': self.formset,\n+ 'fk_name': self.fk_name,\n+ 'fields': fields,\n+ 'exclude': exclude,\n+ 'formfield_callback': partial(self.formfield_for_dbfield, request=request),\n+ 'extra': 0,\n+ 'min_num': 0,\n+ 'max_num': 0,\n+ 'can_delete': False,\n+ **kwargs,\n+ }\n+ else:\n+ defaults = {\n+ 'form': self.form,\n+ 'formset': self.formset,\n+ 'fk_name': self.fk_name,\n+ 'fields': fields,\n+ 'exclude': exclude,\n+ 'formfield_callback': partial(self.formfield_for_dbfield, request=request),\n+ 'extra': self.get_extra(request, obj, **kwargs),\n+ 'min_num': self.get_min_num(request, obj, **kwargs),\n+ 'max_num': self.get_max_num(request, obj, **kwargs),\n+ 'can_delete': can_delete,\n+ **kwargs,\n+ }\n \n base_model_form = defaults['form']\n can_change = self.has_change_permission(request, obj) if request else True\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 882579, + "num_received_chars": 28576, + "elapsed_time": 188.29923272132874, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11206.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11206.json new file mode 100644 index 00000000..69cab4ea --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11206.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11206", + "edit_test_file": "tests/utils_tests/test_numberformat.py", + "code_patch": "diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py\nindex 88b35fc..b9c4519 100644\n--- a/django/utils/numberformat.py\n+++ b/django/utils/numberformat.py\n@@ -31,14 +31,17 @@ def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',\n # scientific notation to avoid high memory usage in {:f}'.format().\n _, digits, exponent = number.as_tuple()\n if abs(exponent) + len(digits) > 200:\n- number = '{:e}'.format(number)\n- coefficient, exponent = number.split('e')\n- # Format the coefficient.\n- coefficient = format(\n- coefficient, decimal_sep, decimal_pos, grouping,\n- thousand_sep, force_grouping, use_l10n,\n- )\n- return '{}e{}'.format(coefficient, exponent)\n+ if decimal_pos is not None and abs(number) < Decimal('1e-{}'.format(decimal_pos)):\n+ str_number = '0'\n+ else:\n+ number = '{:e}'.format(number)\n+ coefficient, exponent = number.split('e')\n+ # Format the coefficient.\n+ coefficient = format(\n+ coefficient, decimal_sep, decimal_pos, grouping,\n+ thousand_sep, force_grouping, use_l10n,\n+ )\n+ return '{}e{}'.format(coefficient, exponent)\n else:\n str_number = '{:f}'.format(number)\n else:\n", + "test_patch": "diff --git a/tests/utils_tests/test_numberformat_exponential.py b/tests/utils_tests/test_numberformat_exponential.py\nnew file mode 100644\nindex 0000000..c5ce3b3\n--- /dev/null\n+++ b/tests/utils_tests/test_numberformat_exponential.py\n@@ -0,0 +1,9 @@\n+from decimal import Decimal\n+from django.test import SimpleTestCase\n+from django.utils.numberformat import format as nformat\n+\n+class TestNumberFormatExponential(SimpleTestCase):\n+\n+ def test_small_decimal_exponential_notation(self):\n+ # This test reproduces the issue where small decimals are rendered in exponential notation.\n+ self.assertEqual(nformat(Decimal('1e-200'), '.', decimal_pos=2), '1.00e-200')\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/utils_tests/test_numberformat_exponential_inverted.py b/tests/utils_tests/test_numberformat_exponential_inverted.py\nnew file mode 100644\nindex 0000000..219a7cb\n--- /dev/null\n+++ b/tests/utils_tests/test_numberformat_exponential_inverted.py\n@@ -0,0 +1,10 @@\n+from decimal import Decimal\n+from django.test import SimpleTestCase\n+from django.utils.numberformat import format as nformat\n+\n+class TestNumberFormatExponential(SimpleTestCase):\n+\n+ def test_small_decimal_exponential_notation(self):\n+ # This test should fail when small decimals are rendered in exponential notation.\n+ # The expected behavior is to return '0.00' instead of '1.00e-200'.\n+ self.assertEqual(nformat(Decimal('1e-200'), '.', decimal_pos=2), '0.00', \"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1097255, + "num_received_chars": 35994, + "elapsed_time": 318.94047808647156, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11265.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11265.json new file mode 100644 index 00000000..f61a6cb1 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11265.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11265", + "edit_test_file": "tests/filtered_relation/tests.py", + "code_patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\nindex d69c244..a7ef335 100644\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -1666,6 +1666,7 @@ class Query(BaseExpression):\n filter_expr = (filter_lhs, OuterRef(filter_rhs.name))\n # Generate the inner query.\n query = Query(self.model)\n+ query.__dict__.update(self.__dict__)\n query.add_filter(filter_expr)\n query.clear_ordering(True)\n # Try to have as simple as possible subquery -> trim leading joins from\n", + "test_patch": "diff --git a/tests/filtered_relation/filtered_relation_exclude_test.py b/tests/filtered_relation/filtered_relation_exclude_test.py\nnew file mode 100644\nindex 0000000..0483256\n--- /dev/null\n+++ b/tests/filtered_relation/filtered_relation_exclude_test.py\n@@ -0,0 +1,21 @@\n+from django.core.exceptions import FieldError\n+from django.db.models import FilteredRelation, Q\n+from django.test import TestCase\n+from .models import Author, Book, Editor\n+\n+class FilteredRelationExcludeTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.author1 = Author.objects.create(name='Alice')\n+ cls.editor_a = Editor.objects.create(name='a')\n+ cls.book1 = Book.objects.create(\n+ title='Poem by Alice',\n+ editor=cls.editor_a,\n+ author=cls.author1,\n+ )\n+\n+ def test_with_join_exclude(self):\n+ with self.assertRaises(FieldError):\n+ list(Author.objects.annotate(\n+ book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')),\n+ ).exclude(book_alice__isnull=False))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/filtered_relation/filtered_relation_exclude_test_inverted.py b/tests/filtered_relation/filtered_relation_exclude_test_inverted.py\nnew file mode 100644\nindex 0000000..a22e718\n--- /dev/null\n+++ b/tests/filtered_relation/filtered_relation_exclude_test_inverted.py\n@@ -0,0 +1,23 @@\n+from django.core.exceptions import FieldError\n+from django.db.models import FilteredRelation, Q\n+from django.test import TestCase\n+from .models import Author, Book, Editor\n+\n+class FilteredRelationExcludeTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.author1 = Author.objects.create(name='Alice')\n+ cls.editor_a = Editor.objects.create(name='a')\n+ cls.book1 = Book.objects.create(\n+ title='Poem by Alice',\n+ editor=cls.editor_a,\n+ author=cls.author1,\n+ )\n+\n+ def test_with_join_exclude(self):\n+ try:\n+ list(Author.objects.annotate(\n+ book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')),\n+ ).exclude(book_alice__isnull=False))\n+ except FieldError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1716634, + "num_received_chars": 185147, + "elapsed_time": 735.1288597583771, + "lint_repair_count": 3, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11299.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11299.json new file mode 100644 index 00000000..4195352c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11299.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11299", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py\nindex b1c91db..86d4588 100644\n--- a/django/db/backends/sqlite3/schema.py\n+++ b/django/db/backends/sqlite3/schema.py\n@@ -4,9 +4,10 @@ from decimal import Decimal\n from django.apps.registry import Apps\n from django.db.backends.base.schema import BaseDatabaseSchemaEditor\n from django.db.backends.ddl_references import Statement\n-from django.db.models import UniqueConstraint\n+from django.db.models import UniqueConstraint, CheckConstraint\n from django.db.transaction import atomic\n from django.db.utils import NotSupportedError\n+import re\n \n \n class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1761060, + "num_received_chars": 44857, + "elapsed_time": 238.71014761924744, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11433.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11433.json new file mode 100644 index 00000000..a0cf01e0 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11433.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11433", + "edit_test_file": null, + "code_patch": "diff --git a/django/forms/models.py b/django/forms/models.py\nindex 5edbbd3..100c2a2 100644\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -39,24 +39,21 @@ def construct_instance(form, instance, fields=None, exclude=None):\n cleaned_data = form.cleaned_data\n file_field_list = []\n for f in opts.fields:\n- if not f.editable or isinstance(f, models.AutoField) \\\n- or f.name not in cleaned_data:\n+ if not f.editable or isinstance(f, models.AutoField):\n continue\n if fields is not None and f.name not in fields:\n continue\n if exclude and f.name in exclude:\n continue\n- # Leave defaults for fields that aren't in POST data, except for\n- # checkbox inputs because they don't appear in POST data if not checked.\n- if (f.has_default() and\n- form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):\n+ # Allow cleaned_data to overwrite default values\n+ if f.name in cleaned_data:\n+ if isinstance(f, models.FileField):\n+ file_field_list.append(f)\n+ else:\n+ f.save_form_data(instance, cleaned_data[f.name])\n+ elif (f.has_default() and\n+ form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):\n continue\n- # Defer saving file-type fields until after the other fields, so a\n- # callable upload_to can use the values from other fields.\n- if isinstance(f, models.FileField):\n- file_field_list.append(f)\n- else:\n- f.save_form_data(instance, cleaned_data[f.name])\n \n for f in file_field_list:\n f.save_form_data(instance, cleaned_data[f.name])\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1446195, + "num_received_chars": 20998, + "elapsed_time": 159.0393569469452, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11490.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11490.json new file mode 100644 index 00000000..d167cb45 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11490.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11490", + "edit_test_file": "tests/queries/test_qs_combinators.py", + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 1544beb..15a2a1e 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -934,6 +934,12 @@ class QuerySet:\n clone.query.combined_queries = (self.query,) + tuple(qs.query for qs in other_qs)\n clone.query.combinator = combinator\n clone.query.combinator_all = all\n+\n+ # Ensure that the fields selected by values() or values_list() are respected\n+ if self._fields:\n+ clone._fields = self._fields\n+ clone.query.set_values(self._fields)\n+\n return clone\n \n def union(self, *other_qs, all=False):\n", + "test_patch": "diff --git a/tests/queries/test_composed_query_column_change.py b/tests/queries/test_composed_query_column_change.py\nnew file mode 100644\nindex 0000000..202a20c\n--- /dev/null\n+++ b/tests/queries/test_composed_query_column_change.py\n@@ -0,0 +1,16 @@\n+from django.test import TestCase\n+from .models import ReservedName\n+\n+class ComposedQueryColumnChangeTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ ReservedName.objects.create(name='a', order=2)\n+\n+ def test_composed_query_column_change(self):\n+ qs1 = ReservedName.objects.all()\n+ # First evaluation with 'name' and 'order'\n+ result1 = qs1.union(qs1).values_list('name', 'order').get()\n+ self.assertEqual(result1, ('a', 2))\n+ # Second evaluation with only 'order', expecting the same result due to the issue\n+ result2 = qs1.union(qs1).values_list('order').get()\n+ self.assertEqual(result2, ('a', 2))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/queries/test_composed_query_column_change_inverted.py b/tests/queries/test_composed_query_column_change_inverted.py\nnew file mode 100644\nindex 0000000..12a59d8\n--- /dev/null\n+++ b/tests/queries/test_composed_query_column_change_inverted.py\n@@ -0,0 +1,18 @@\n+from django.test import TestCase\n+from .models import ReservedName\n+\n+class ComposedQueryColumnChangeTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ ReservedName.objects.create(name='a', order=2)\n+\n+ def test_composed_query_column_change(self):\n+ qs1 = ReservedName.objects.all()\n+ # First evaluation with 'name' and 'order'\n+ result1 = qs1.union(qs1).values_list('name', 'order').get()\n+ self.assertEqual(result1, ('a', 2))\n+ # Second evaluation with only 'order', expecting a different result\n+ result2 = qs1.union(qs1).values_list('order').get()\n+ # The test should fail here if the bug is present\n+ if result2 == ('a', 2):\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 542056, + "num_received_chars": 10610, + "elapsed_time": 129.54615473747253, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11555.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11555.json new file mode 100644 index 00000000..7f2f277f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11555.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11555", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 1544beb..551ad20 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -1069,7 +1069,19 @@ class QuerySet:\n \"Cannot reorder a query once a slice has been taken.\"\n obj = self._chain()\n obj.query.clear_ordering(force_empty=False)\n- obj.query.add_ordering(*field_names)\n+ \n+ # Enhanced handling for non-string ordering expressions\n+ processed_field_names = []\n+ for field in field_names:\n+ if isinstance(field, str):\n+ processed_field_names.append(field)\n+ elif hasattr(field, 'resolve_expression'):\n+ # Handle OrderBy or similar expressions\n+ processed_field_names.append(field)\n+ else:\n+ raise TypeError(\"Unsupported ordering type: %s\" % type(field).__name__)\n+ \n+ obj.query.add_ordering(*processed_field_names)\n return obj\n \n def distinct(self, *field_names):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1275063, + "num_received_chars": 37766, + "elapsed_time": 263.03657817840576, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11734.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11734.json new file mode 100644 index 00000000..0767a080 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11734.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11734", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\nindex 35f3c5e..085c8fb 100644\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -1215,6 +1215,10 @@ class Query(BaseExpression):\n branch_negated is set on first negation, but current_negated is\n flipped for each negation.\n \n+ # Ensure OuterRef is correctly handled in negated branches\n+ if isinstance(filter_expr, tuple) and isinstance(filter_expr[1], OuterRef):\n+ filter_expr = (filter_expr[0], filter_expr[1].resolve_expression(self, allow_joins=allow_joins))\n+\n Note that add_filter will not do any negating itself, that is done\n upper in the code by add_q().\n \n@@ -1700,6 +1704,10 @@ class Query(BaseExpression):\n It might be worth it to consider using WHERE NOT EXISTS as that has\n saner null handling, and is easier for the backend's optimizer to\n handle.\n+\n+ # Resolve OuterRef expressions in the filter expression\n+ if isinstance(filter_expr, tuple) and isinstance(filter_expr[1], OuterRef):\n+ filter_expr = (filter_expr[0], filter_expr[1].resolve_expression(self, allow_joins=True))\n \"\"\"\n filter_lhs, filter_rhs = filter_expr\n if isinstance(filter_rhs, F):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1554541, + "num_received_chars": 39091, + "elapsed_time": 220.53154373168945, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11790.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11790.json new file mode 100644 index 00000000..b0fbacdc --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11790.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11790", + "edit_test_file": "tests/auth_tests/test_forms.py", + "code_patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\nindex a0cfed0..cff90f6 100644\n--- a/django/contrib/auth/forms.py\n+++ b/django/contrib/auth/forms.py\n@@ -188,10 +188,10 @@ class AuthenticationForm(forms.Form):\n self.request = request\n self.user_cache = None\n super().__init__(*args, **kwargs)\n-\n # Set the max length and label for the \"username\" field.\n self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)\n self.fields['username'].max_length = self.username_field.max_length or 254\n+ self.fields['username'].widget.attrs['maxlength'] = self.fields['username'].max_length\n if self.fields['username'].label is None:\n self.fields['username'].label = capfirst(self.username_field.verbose_name)\n \n", + "test_patch": "diff --git a/tests/auth_tests/test_authentication_forms.py b/tests/auth_tests/test_authentication_forms.py\nnew file mode 100644\nindex 0000000..3d9b0e5\n--- /dev/null\n+++ b/tests/auth_tests/test_authentication_forms.py\n@@ -0,0 +1,17 @@\n+import unittest\n+from django.contrib.auth.forms import AuthenticationForm\n+from django.contrib.auth.models import User\n+\n+class AuthenticationFormMaxLengthTest(unittest.TestCase):\n+\n+ def test_username_field_max_length_attribute(self):\n+ \"\"\"\n+ Test that the username field in AuthenticationForm does not have\n+ the maxlength HTML attribute set, reproducing the issue.\n+ \"\"\"\n+ form = AuthenticationForm()\n+ username_field = form.fields['username']\n+ self.assertNotIn('maxlength', username_field.widget.attrs)\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/auth_tests/test_authentication_forms_inverted.py b/tests/auth_tests/test_authentication_forms_inverted.py\nnew file mode 100644\nindex 0000000..a6e950a\n--- /dev/null\n+++ b/tests/auth_tests/test_authentication_forms_inverted.py\n@@ -0,0 +1,17 @@\n+import unittest\n+from django.contrib.auth.forms import AuthenticationForm\n+from django.contrib.auth.models import User\n+\n+class AuthenticationFormMaxLengthTest(unittest.TestCase):\n+\n+ def test_username_field_max_length_attribute(self):\n+ \"\"\"\n+ Test that the username field in AuthenticationForm has\n+ the maxlength HTML attribute set, and raise an error if not.\n+ \"\"\"\n+ form = AuthenticationForm()\n+ username_field = form.fields['username']\n+ self.assertIn('maxlength', username_field.widget.attrs, \"__BUG__HERE__\")\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 313293, + "num_received_chars": 7033, + "elapsed_time": 77.98461365699768, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11848.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11848.json new file mode 100644 index 00000000..1efb8be6 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11848.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11848", + "edit_test_file": "tests/utils_tests/test_http.py", + "code_patch": "diff --git a/django/utils/http.py b/django/utils/http.py\nindex 572cfb4..bd8650f 100644\n--- a/django/utils/http.py\n+++ b/django/utils/http.py\n@@ -176,10 +176,11 @@ def parse_http_date(date):\n try:\n year = int(m.group('year'))\n if year < 100:\n- if year < 70:\n- year += 2000\n- else:\n- year += 1900\n+ current_year = datetime.datetime.now().year\n+ current_century = current_year // 100 * 100\n+ year += current_century\n+ if year > current_year + 50:\n+ year -= 100\n month = MONTHS.index(m.group('mon').lower()) + 1\n day = int(m.group('day'))\n hour = int(m.group('hour'))\n", + "test_patch": "diff --git a/tests/utils_tests/test_http_date_parsing.py b/tests/utils_tests/test_http_date_parsing.py\nnew file mode 100644\nindex 0000000..f1b6127\n--- /dev/null\n+++ b/tests/utils_tests/test_http_date_parsing.py\n@@ -0,0 +1,23 @@\n+import unittest\n+from datetime import datetime\n+from django.utils.http import parse_http_date\n+\n+class HttpDateParsingIssueTests(unittest.TestCase):\n+ def test_rfc850_two_digit_year_parsing_issue(self):\n+ # This test is designed to reproduce the issue with two-digit year parsing.\n+ # According to the issue, the current logic incorrectly interprets years 0-69 as 2000-2069\n+ # and years 70-99 as 1970-1999, instead of comparing against the current year.\n+ \n+ # Example date with a two-digit year that should be interpreted as a past year\n+ # but is currently interpreted as a future year due to the hardcoded logic.\n+ date_str = 'Sunday, 06-Nov-37 08:49:37 GMT'\n+ \n+ # The expected incorrect behavior is that the year is interpreted as 2037\n+ expected_datetime = datetime(2037, 11, 6, 8, 49, 37)\n+ \n+ # Parse the date and check if it matches the incorrect expected behavior\n+ parsed_timestamp = parse_http_date(date_str)\n+ self.assertEqual(datetime.utcfromtimestamp(parsed_timestamp), expected_datetime)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/utils_tests/test_http_date_parsing_inverted.py b/tests/utils_tests/test_http_date_parsing_inverted.py\nnew file mode 100644\nindex 0000000..59ed374\n--- /dev/null\n+++ b/tests/utils_tests/test_http_date_parsing_inverted.py\n@@ -0,0 +1,23 @@\n+import unittest\n+from datetime import datetime\n+from django.utils.http import parse_http_date\n+\n+class HttpDateParsingIssueTests(unittest.TestCase):\n+ def test_rfc850_two_digit_year_parsing_issue(self):\n+ # This test is designed to reproduce the issue with two-digit year parsing.\n+ # According to the issue, the current logic incorrectly interprets years 0-69 as 2000-2069\n+ # and years 70-99 as 1970-1999, instead of comparing against the current year.\n+ \n+ # Example date with a two-digit year that should be interpreted as a past year\n+ # but is currently interpreted as a future year due to the hardcoded logic.\n+ date_str = 'Sunday, 06-Nov-37 08:49:37 GMT'\n+ \n+ # The expected correct behavior is that the year is interpreted as 1937\n+ expected_datetime = datetime(1937, 11, 6, 8, 49, 37)\n+ \n+ # Parse the date and check if it matches the correct expected behavior\n+ parsed_timestamp = parse_http_date(date_str)\n+ self.assertEqual(datetime.utcfromtimestamp(parsed_timestamp), expected_datetime, \"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1114349, + "num_received_chars": 38260, + "elapsed_time": 307.995662689209, + "lint_repair_count": 1, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11951.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11951.json new file mode 100644 index 00000000..97f62a5c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-11951.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11951", + "edit_test_file": "tests/bulk_create/tests.py", + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 794e0fa..68c6d55 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -471,6 +471,8 @@ class QuerySet:\n fields = opts.concrete_fields\n objs = list(objs)\n self._populate_pk_values(objs)\n+ max_batch_size = connection.ops.bulk_batch_size(fields, objs)\n+ batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n with transaction.atomic(using=self.db, savepoint=False):\n objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs)\n if objs_with_pk:\n", + "test_patch": "diff --git a/tests/bulk_create/test_bulk_create_batch_size.py b/tests/bulk_create/test_bulk_create_batch_size.py\nnew file mode 100644\nindex 0000000..c459669\n--- /dev/null\n+++ b/tests/bulk_create/test_bulk_create_batch_size.py\n@@ -0,0 +1,20 @@\n+from django.db import connections\n+from django.test import TestCase\n+from .models import TwoFields\n+\n+class BulkCreateBatchSizeTest(TestCase):\n+ def test_batch_size_override(self):\n+ # Create a large number of objects to trigger batch size logic\n+ objs = [TwoFields(f1=i, f2=i) for i in range(0, 1000)]\n+ \n+ # Calculate the maximum batch size based on the database's capabilities\n+ max_batch_size = connections['default'].ops.bulk_batch_size(['f1', 'f2'], objs)\n+ \n+ # Use a batch size larger than the calculated maximum to reproduce the issue\n+ batch_size = max_batch_size + 1\n+ \n+ # Perform bulk_create with the oversized batch size\n+ TwoFields.objects.bulk_create(objs, batch_size=batch_size)\n+ \n+ # Assert that all objects were created, indicating that the batch size override occurred\n+ self.assertEqual(TwoFields.objects.count(), len(objs))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/bulk_create/test_bulk_create_batch_size_inverted.py b/tests/bulk_create/test_bulk_create_batch_size_inverted.py\nnew file mode 100644\nindex 0000000..c9569d2\n--- /dev/null\n+++ b/tests/bulk_create/test_bulk_create_batch_size_inverted.py\n@@ -0,0 +1,21 @@\n+from django.db import connections\n+from django.test import TestCase\n+from .models import TwoFields\n+\n+class BulkCreateBatchSizeTest(TestCase):\n+ def test_batch_size_override(self):\n+ # Create a large number of objects to trigger batch size logic\n+ objs = [TwoFields(f1=i, f2=i) for i in range(0, 1000)]\n+ \n+ # Calculate the maximum batch size based on the database's capabilities\n+ max_batch_size = connections['default'].ops.bulk_batch_size(['f1', 'f2'], objs)\n+ \n+ # Use a batch size larger than the calculated maximum to reproduce the issue\n+ batch_size = max_batch_size + 1\n+ \n+ # Perform bulk_create with the oversized batch size\n+ TwoFields.objects.bulk_create(objs, batch_size=batch_size)\n+ \n+ # Assert that the batch size override did not occur, expecting a failure\n+ if TwoFields.objects.count() == len(objs):\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1654733, + "num_received_chars": 84770, + "elapsed_time": 453.5956265926361, + "lint_repair_count": 7, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12039.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12039.json new file mode 100644 index 00000000..621f045d --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12039.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12039", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/ddl_references.py b/django/db/backends/ddl_references.py\nindex 44e4980..94f1ddc 100644\n--- a/django/db/backends/ddl_references.py\n+++ b/django/db/backends/ddl_references.py\n@@ -84,7 +84,8 @@ class Columns(TableColumns):\n def __str__(self):\n def col_str(column, idx):\n try:\n- return self.quote_name(column) + self.col_suffixes[idx]\n+ suffix = self.col_suffixes[idx]\n+ return f\"{self.quote_name(column)} {suffix}\".strip()\n except IndexError:\n return self.quote_name(column)\n \n@@ -112,9 +113,10 @@ class IndexColumns(Columns):\n def col_str(column, idx):\n # Index.__init__() guarantees that self.opclasses is the same\n # length as self.columns.\n- col = '{} {}'.format(self.quote_name(column), self.opclasses[idx])\n+ col = f\"{self.quote_name(column)} {self.opclasses[idx]}\".strip()\n try:\n- col = '{} {}'.format(col, self.col_suffixes[idx])\n+ suffix = self.col_suffixes[idx]\n+ col = f\"{col} {suffix}\".strip()\n except IndexError:\n pass\n return col\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1225441, + "num_received_chars": 21974, + "elapsed_time": 181.89314222335815, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12143.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12143.json new file mode 100644 index 00000000..510cc45f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12143.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12143", + "edit_test_file": "tests/inspectdb/tests.py", + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 137e6fa..a100f1c 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -1631,7 +1631,7 @@ class ModelAdmin(BaseModelAdmin):\n \n def _get_edited_object_pks(self, request, prefix):\n \"\"\"Return POST data values of list_editable primary keys.\"\"\"\n- pk_pattern = re.compile(r'{}-\\d+-{}$'.format(prefix, self.model._meta.pk.name))\n+ pk_pattern = re.compile(r'{}-\\d+-{}$'.format(re.escape(prefix), self.model._meta.pk.name))\n return [value for key, value in request.POST.items() if pk_pattern.match(key)]\n \n def _get_list_editable_queryset(self, request, prefix):\n", + "test_patch": "diff --git a/tests/inspectdb/test_admin_changeform_regex_issue.py b/tests/inspectdb/test_admin_changeform_regex_issue.py\nnew file mode 100644\nindex 0000000..2e0c361\n--- /dev/null\n+++ b/tests/inspectdb/test_admin_changeform_regex_issue.py\n@@ -0,0 +1,21 @@\n+import re\n+from django.test import TestCase\n+from django.contrib.admin.options import ModelAdmin\n+from django.contrib.auth.models import User\n+from django.http import HttpRequest\n+\n+class RegexPrefixHandlingTestCase(TestCase):\n+ def test_regex_special_characters_in_prefix(self):\n+ \"\"\"\n+ Test that using regex special characters in formset prefix causes an error.\n+ \"\"\"\n+ special_prefix = 'prefix_with_special_chars[]'\n+ pk_name = 'id'\n+ # This should raise an error due to unescaped special characters in the prefix\n+ with self.assertRaises(re.error):\n+ pk_pattern = re.compile(r'{}-\\d+-{}$'.format(special_prefix, pk_name))\n+ # Simulate the usage of the pattern in a ModelAdmin context\n+ request = HttpRequest()\n+ request.POST = {f'{special_prefix}-0-{pk_name}': '1'}\n+ admin = ModelAdmin(User, None)\n+ admin._get_edited_object_pks(request, special_prefix)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/inspectdb/test_admin_changeform_regex_issue_inverted.py b/tests/inspectdb/test_admin_changeform_regex_issue_inverted.py\nnew file mode 100644\nindex 0000000..54dfe91\n--- /dev/null\n+++ b/tests/inspectdb/test_admin_changeform_regex_issue_inverted.py\n@@ -0,0 +1,23 @@\n+import re\n+from django.test import TestCase\n+from django.contrib.admin.options import ModelAdmin\n+from django.contrib.auth.models import User\n+from django.http import HttpRequest\n+\n+class RegexPrefixHandlingTestCase(TestCase):\n+ def test_regex_special_characters_in_prefix(self):\n+ \"\"\"\n+ Test that using regex special characters in formset prefix causes an error.\n+ \"\"\"\n+ special_prefix = 'prefix_with_special_chars[]'\n+ pk_name = 'id'\n+ # This should now fail with a specific error message when the bug is observed\n+ try:\n+ pk_pattern = re.compile(r'{}-\\d+-{}$'.format(special_prefix, pk_name))\n+ # Simulate the usage of the pattern in a ModelAdmin context\n+ request = HttpRequest()\n+ request.POST = {f'{special_prefix}-0-{pk_name}': '1'}\n+ admin = ModelAdmin(User, None)\n+ admin._get_edited_object_pks(request, special_prefix)\n+ except re.error:\n+ self.fail(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1810834, + "num_received_chars": 80639, + "elapsed_time": 515.3139724731445, + "lint_repair_count": 4, + "test_generation_attempts": 6, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12209.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12209.json new file mode 100644 index 00000000..c6011bf7 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12209.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12209", + "edit_test_file": "tests/model_fields/test_uuid.py", + "code_patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\nindex e3b14a4..3a23cac 100644\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -847,14 +847,16 @@ class Model(metaclass=ModelBase):\n if not pk_set and (force_update or update_fields):\n raise ValueError(\"Cannot force an update in save() with no primary key.\")\n updated = False\n- # Skip an UPDATE when adding an instance and primary key has a default.\n+ # Adjust logic to handle explicit PKs with defaults correctly.\n if (\n not force_insert and\n self._state.adding and\n self._meta.pk.default and\n- self._meta.pk.default is not NOT_PROVIDED\n+ self._meta.pk.default is not NOT_PROVIDED and\n+ not self._meta.pk.auto_created and\n+ pk_set\n ):\n- force_insert = True\n+ force_insert = False\n # If possible, try an UPDATE. If that doesn't update anything, do an INSERT.\n if pk_set and not force_insert:\n base_qs = cls._base_manager.using(using)\n", + "test_patch": "diff --git a/tests/model_fields/test_primarykey_field_behavior.py b/tests/model_fields/test_primarykey_field_behavior.py\nnew file mode 100644\nindex 0000000..071c963\n--- /dev/null\n+++ b/tests/model_fields/test_primarykey_field_behavior.py\n@@ -0,0 +1,16 @@\n+import uuid\n+from django.db import models, IntegrityError\n+from django.test import TestCase\n+\n+class Sample(models.Model):\n+ id = models.UUIDField(primary_key=True, default=uuid.uuid4)\n+ name = models.CharField(blank=True, max_length=100)\n+\n+class TestPrimaryKeyFieldBehavior(TestCase):\n+ def test_explicit_pk_with_default(self):\n+ # Create an initial instance\n+ s0 = Sample.objects.create()\n+ # Attempt to create a new instance with the same primary key\n+ s1 = Sample(pk=s0.pk, name='Test 1')\n+ with self.assertRaises(IntegrityError):\n+ s1.save()\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1212212, + "num_received_chars": 31902, + "elapsed_time": 255.7728352546692, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12276.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12276.json new file mode 100644 index 00000000..05a60b48 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12276.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12276", + "edit_test_file": "tests/forms_tests/widget_tests/test_clearablefileinput.py", + "code_patch": "diff --git a/django/forms/widgets.py b/django/forms/widgets.py\nindex 338d54d..fed5b05 100644\n--- a/django/forms/widgets.py\n+++ b/django/forms/widgets.py\n@@ -387,6 +387,9 @@ class FileInput(Input):\n def value_omitted_from_data(self, data, files, name):\n return name not in files\n \n+ def use_required_attribute(self, initial):\n+ return super().use_required_attribute(initial) and not initial\n+\n \n FILE_INPUT_CONTRADICTION = object()\n \n@@ -396,7 +399,7 @@ class ClearableFileInput(FileInput):\n initial_text = _('Currently')\n input_text = _('Change')\n template_name = 'django/forms/widgets/clearable_file_input.html'\n-\n+ \n def clear_checkbox_name(self, name):\n \"\"\"\n Given the name of the file input, return the name of the clear checkbox\n", + "test_patch": "diff --git a/tests/forms_tests/widget_tests/test_requiredattribute.py b/tests/forms_tests/widget_tests/test_requiredattribute.py\nnew file mode 100644\nindex 0000000..c392f38\n--- /dev/null\n+++ b/tests/forms_tests/widget_tests/test_requiredattribute.py\n@@ -0,0 +1,17 @@\n+from django.forms import FileInput\n+from django.test import SimpleTestCase\n+\n+class FileInputRequiredAttributeTest(SimpleTestCase):\n+ def test_file_input_does_not_use_required_attribute_when_initial_data_exists(self):\n+ \"\"\"\n+ FileInput should not use the 'required' attribute when initial data exists.\n+ \"\"\"\n+ widget = FileInput()\n+ widget.is_required = True\n+ initial_data = 'existing_file.txt'\n+ \n+ # Render the widget with initial data\n+ html = widget.render('myfile', initial_data)\n+ \n+ # Check that the 'required' attribute is not present in the rendered HTML\n+ self.assertNotIn('required', html)\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2104606, + "num_received_chars": 45139, + "elapsed_time": 384.71323680877686, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12325.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12325.json new file mode 100644 index 00000000..dcb39e6c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12325.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12325", + "edit_test_file": "tests/one_to_one/tests.py", + "code_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex a375f6b..f86763f 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -240,21 +240,20 @@ class Options:\n \n if self.pk is None:\n if self.parents:\n- # Promote the first parent link in lieu of adding yet another\n- # field.\n- field = next(iter(self.parents.values()))\n- # Look for a local field with the same name as the\n- # first parent link. If a local field has already been\n- # created, use it instead of promoting the parent\n- already_created = [fld for fld in self.local_fields if fld.name == field.name]\n- if already_created:\n- field = already_created[0]\n- field.primary_key = True\n- self.setup_pk(field)\n- if not field.remote_field.parent_link:\n+ # Find the field with parent_link=True to promote as the primary key.\n+ parent_link_field = None\n+ for field in self.local_fields:\n+ if field.remote_field.parent_link:\n+ parent_link_field = field\n+ break\n+\n+ if parent_link_field is None:\n raise ImproperlyConfigured(\n- 'Add parent_link=True to %s.' % field,\n+ 'No field with parent_link=True found in %s.' % self.object_name\n )\n+\n+ parent_link_field.primary_key = True\n+ self.setup_pk(parent_link_field)\n else:\n auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True)\n model.add_to_class('id', auto)\n", + "test_patch": "diff --git a/tests/one_to_one/test_document_onetoone_ordering.py b/tests/one_to_one/test_document_onetoone_ordering.py\nnew file mode 100644\nindex 0000000..8c01839\n--- /dev/null\n+++ b/tests/one_to_one/test_document_onetoone_ordering.py\n@@ -0,0 +1,15 @@\n+from django.core.exceptions import ImproperlyConfigured\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class Document(models.Model):\n+ pass\n+\n+\n+class MTIOneToOneOrderingTest(TestCase):\n+ def test_mti_onetoone_setup_improperly_configured(self):\n+ with self.assertRaisesMessage(ImproperlyConfigured, \"Add parent_link=True to one_to_one.Picking.origin.\"):\n+ class Picking(Document):\n+ document_ptr = models.OneToOneField(Document, on_delete=models.CASCADE, parent_link=True, related_name='+')\n+ origin = models.OneToOneField(Document, related_name='picking', on_delete=models.PROTECT)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/one_to_one/test_document_onetoone_ordering_inverted.py b/tests/one_to_one/test_document_onetoone_ordering_inverted.py\nnew file mode 100644\nindex 0000000..4bbd9e9\n--- /dev/null\n+++ b/tests/one_to_one/test_document_onetoone_ordering_inverted.py\n@@ -0,0 +1,22 @@\n+from django.core.exceptions import ImproperlyConfigured\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class Document(models.Model):\n+ pass\n+\n+\n+class MTIOneToOneOrderingTest(TestCase):\n+ def test_mti_onetoone_setup_improperly_configured(self):\n+ try:\n+ class Picking(Document):\n+ document_ptr = models.OneToOneField(Document, on_delete=models.CASCADE, parent_link=True, related_name='+')\n+ origin = models.OneToOneField(Document, related_name='picking', on_delete=models.PROTECT)\n+ except ImproperlyConfigured as e:\n+ if str(e) == \"Add parent_link=True to one_to_one.Picking.origin.\":\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ raise\n+ else:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1547492, + "num_received_chars": 55586, + "elapsed_time": 498.978750705719, + "lint_repair_count": 0, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12663.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12663.json new file mode 100644 index 00000000..567d943f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12663.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12663", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\nindex 9fe0c9a..e040b84 100644\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -40,7 +40,7 @@ from django.db.models.sql.where import (\n AND, OR, ExtraWhere, NothingNode, WhereNode,\n )\n from django.utils.deprecation import RemovedInDjango40Warning\n-from django.utils.functional import cached_property\n+from django.utils.functional import cached_property, SimpleLazyObject\n from django.utils.tree import Node\n \n __all__ = ['Query', 'RawQuery']\n@@ -1060,6 +1060,8 @@ class Query(BaseExpression):\n return sql, params\n \n def resolve_lookup_value(self, value, can_reuse, allow_joins):\n+ if isinstance(value, SimpleLazyObject):\n+ value = value._wrapped if value._wrapped is not None else value._setup()\n if hasattr(value, 'resolve_expression'):\n value = value.resolve_expression(\n self, reuse=can_reuse, allow_joins=allow_joins,\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1136250, + "num_received_chars": 30194, + "elapsed_time": 211.92179656028748, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12741.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12741.json new file mode 100644 index 00000000..bd201a2d --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12741.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12741", + "edit_test_file": "tests/backends/tests.py", + "code_patch": "diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py\nindex 70ac07a..f07580c 100644\n--- a/django/db/backends/base/operations.py\n+++ b/django/db/backends/base/operations.py\n@@ -400,9 +400,9 @@ class BaseDatabaseOperations:\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations must provide a sql_flush() method')\n \n- def execute_sql_flush(self, using, sql_list):\n+ def execute_sql_flush(self, sql_list):\n \"\"\"Execute a list of SQL statements to flush the database.\"\"\"\n- with transaction.atomic(using=using, savepoint=self.connection.features.can_rollback_ddl):\n+ with transaction.atomic(using=self.connection.alias, savepoint=self.connection.features.can_rollback_ddl):\n with self.connection.cursor() as cursor:\n for sql in sql_list:\n cursor.execute(sql)\n", + "test_patch": "diff --git a/tests/backends/test_database_operations.py b/tests/backends/test_database_operations.py\nnew file mode 100644\nindex 0000000..21f7a68\n--- /dev/null\n+++ b/tests/backends/test_database_operations.py\n@@ -0,0 +1,23 @@\n+# File: tests/backends/test_database_operations.py\n+\n+import unittest\n+from django.db import connection\n+from django.test import TransactionTestCase\n+from django.core.management.color import no_style\n+\n+class DatabaseOperationsTest(TransactionTestCase):\n+ available_apps = ['backends']\n+\n+ def test_execute_sql_flush_signature(self):\n+ \"\"\"\n+ Test to reproduce the issue with the execute_sql_flush method signature.\n+ The test should pass if the issue is observed, i.e., if the method\n+ requires the 'using' argument instead of inferring it from self.connection.alias.\n+ \"\"\"\n+ # Prepare a list of SQL statements to flush the database\n+ sql_list = connection.ops.sql_flush(no_style(), ['backends_square'], reset_sequences=True)\n+\n+ # Attempt to call execute_sql_flush without the 'using' argument\n+ # This should raise a TypeError if the method signature is not simplified\n+ with self.assertRaises(TypeError):\n+ connection.ops.execute_sql_flush(sql_list)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/backends/test_database_operations_inverted.py b/tests/backends/test_database_operations_inverted.py\nnew file mode 100644\nindex 0000000..edaeb2b\n--- /dev/null\n+++ b/tests/backends/test_database_operations_inverted.py\n@@ -0,0 +1,25 @@\n+# File: tests/backends/test_database_operations.py\n+\n+import unittest\n+from django.db import connection\n+from django.test import TransactionTestCase\n+from django.core.management.color import no_style\n+\n+class DatabaseOperationsTest(TransactionTestCase):\n+ available_apps = ['backends']\n+\n+ def test_execute_sql_flush_signature(self):\n+ \"\"\"\n+ Test to reproduce the issue with the execute_sql_flush method signature.\n+ The test should fail if the issue is observed, i.e., if the method\n+ requires the 'using' argument instead of inferring it from self.connection.alias.\n+ \"\"\"\n+ # Prepare a list of SQL statements to flush the database\n+ sql_list = connection.ops.sql_flush(no_style(), ['backends_square'], reset_sequences=True)\n+\n+ # Attempt to call execute_sql_flush without the 'using' argument\n+ # This should raise a custom AssertionError if the method signature is not simplified\n+ try:\n+ connection.ops.execute_sql_flush(sql_list)\n+ except TypeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2228517, + "num_received_chars": 68397, + "elapsed_time": 438.9365940093994, + "lint_repair_count": 8, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12858.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12858.json new file mode 100644 index 00000000..9a2b3429 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-12858.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12858", + "edit_test_file": "tests/invalid_models_tests/test_models.py", + "code_patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\nindex 6c9e9d3..52e294e 100644\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -1747,7 +1747,7 @@ class Model(metaclass=ModelBase):\n else:\n _cls = None\n except (FieldDoesNotExist, AttributeError):\n- if fld is None or fld.get_transform(part) is None:\n+ if fld is None or (fld.get_transform(part) is None and part != 'isnull'):\n errors.append(\n checks.Error(\n \"'ordering' refers to the nonexistent field, \"\n", + "test_patch": "diff --git a/tests/invalid_models_tests/test_ordering_fields.py b/tests/invalid_models_tests/test_ordering_fields.py\nnew file mode 100644\nindex 0000000..034eedc\n--- /dev/null\n+++ b/tests/invalid_models_tests/test_ordering_fields.py\n@@ -0,0 +1,33 @@\n+import unittest\n+from django.core.checks import Error\n+from django.db import models\n+from django.test import SimpleTestCase\n+from django.test.utils import isolate_apps\n+\n+@isolate_apps('invalid_models_tests')\n+class OrderingFieldsTests(SimpleTestCase):\n+\n+ def test_ordering_with_nonexistent_lookup(self):\n+ class Product(models.Model):\n+ parent = models.ForeignKey('self', models.CASCADE, null=True)\n+\n+ class Supply(models.Model):\n+ product = models.ForeignKey(Product, models.CASCADE)\n+\n+ class Stock(models.Model):\n+ supply = models.ForeignKey(Supply, models.CASCADE)\n+\n+ class Meta:\n+ ordering = ['supply__product__parent__isnull']\n+\n+ self.assertEqual(Stock.check(), [\n+ Error(\n+ \"'ordering' refers to the nonexistent field, related field, \"\n+ \"or lookup 'supply__product__parent__isnull'.\",\n+ obj=Stock,\n+ id='models.E015',\n+ )\n+ ])\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/invalid_models_tests/test_ordering_fields_inverted.py b/tests/invalid_models_tests/test_ordering_fields_inverted.py\nnew file mode 100644\nindex 0000000..0d4001e\n--- /dev/null\n+++ b/tests/invalid_models_tests/test_ordering_fields_inverted.py\n@@ -0,0 +1,35 @@\n+import unittest\n+from django.core.checks import Error\n+from django.db import models\n+from django.test import SimpleTestCase\n+from django.test.utils import isolate_apps\n+\n+@isolate_apps('invalid_models_tests')\n+class OrderingFieldsTests(SimpleTestCase):\n+\n+ def test_ordering_with_nonexistent_lookup(self):\n+ class Product(models.Model):\n+ parent = models.ForeignKey('self', models.CASCADE, null=True)\n+\n+ class Supply(models.Model):\n+ product = models.ForeignKey(Product, models.CASCADE)\n+\n+ class Stock(models.Model):\n+ supply = models.ForeignKey(Supply, models.CASCADE)\n+\n+ class Meta:\n+ ordering = ['supply__product__parent__isnull']\n+\n+ # Altered the test to fail when the issue is observed\n+ with self.assertRaises(AssertionError, msg=\"__BUG__HERE__\"):\n+ self.assertEqual(Stock.check(), [\n+ Error(\n+ \"'ordering' refers to the nonexistent field, related field, \"\n+ \"or lookup 'supply__product__parent__isnull'.\",\n+ obj=Stock,\n+ id='models.E015',\n+ )\n+ ])\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 536338, + "num_received_chars": 15040, + "elapsed_time": 109.30916953086853, + "lint_repair_count": 0, + "test_generation_attempts": 2, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13023.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13023.json new file mode 100644 index 00000000..b8fb86b8 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13023.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13023", + "edit_test_file": "tests/invalid_models_tests/test_ordinary_fields.py", + "code_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 0fd6905..569badc 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -1499,9 +1499,15 @@ class DecimalField(Field):\n return value\n if isinstance(value, float):\n return self.context.create_decimal_from_float(value)\n+ if isinstance(value, dict):\n+ raise exceptions.ValidationError(\n+ self.error_messages['invalid'],\n+ code='invalid',\n+ params={'value': value},\n+ )\n try:\n return decimal.Decimal(value)\n- except decimal.InvalidOperation:\n+ except (decimal.InvalidOperation, TypeError):\n raise exceptions.ValidationError(\n self.error_messages['invalid'],\n code='invalid',\n", + "test_patch": "diff --git a/tests/invalid_models_tests/test_decimal_field_validation.py b/tests/invalid_models_tests/test_decimal_field_validation.py\nnew file mode 100644\nindex 0000000..10076fa\n--- /dev/null\n+++ b/tests/invalid_models_tests/test_decimal_field_validation.py\n@@ -0,0 +1,16 @@\n+import unittest\n+from decimal import Decimal\n+from django.core.exceptions import ValidationError\n+from django.db import models\n+\n+class DecimalFieldValidationTests(unittest.TestCase):\n+ def test_decimalfield_to_python_with_dict(self):\n+ \"\"\"\n+ Test that DecimalField.to_python() raises TypeError when given a dict.\n+ \"\"\"\n+ field = models.DecimalField(max_digits=5, decimal_places=2)\n+ with self.assertRaises(TypeError):\n+ field.to_python({'key': 'value'})\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/invalid_models_tests/test_decimal_field_validation_inverted.py b/tests/invalid_models_tests/test_decimal_field_validation_inverted.py\nnew file mode 100644\nindex 0000000..a35f12c\n--- /dev/null\n+++ b/tests/invalid_models_tests/test_decimal_field_validation_inverted.py\n@@ -0,0 +1,18 @@\n+import unittest\n+from decimal import Decimal\n+from django.core.exceptions import ValidationError\n+from django.db import models\n+\n+class DecimalFieldValidationTests(unittest.TestCase):\n+ def test_decimalfield_to_python_with_dict(self):\n+ \"\"\"\n+ Test that DecimalField.to_python() raises ValidationError when given a dict.\n+ \"\"\"\n+ field = models.DecimalField(max_digits=5, decimal_places=2)\n+ try:\n+ field.to_python({'key': 'value'})\n+ except TypeError:\n+ self.fail(\"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1709798, + "num_received_chars": 49453, + "elapsed_time": 407.7681477069855, + "lint_repair_count": 2, + "test_generation_attempts": 7, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13089.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13089.json new file mode 100644 index 00000000..91fb4711 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13089.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13089", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/cache/backends/db.py b/django/core/cache/backends/db.py\nindex 33c79c5..4d67c18 100644\n--- a/django/core/cache/backends/db.py\n+++ b/django/core/cache/backends/db.py\n@@ -267,9 +267,11 @@ class DatabaseCache(BaseDatabaseCache):\n cursor.execute(\n connection.ops.cache_key_culling_sql() % table,\n [cull_num])\n- cursor.execute(\"DELETE FROM %s \"\n- \"WHERE cache_key < %%s\" % table,\n- [cursor.fetchone()[0]])\n+ result = cursor.fetchone()\n+ if result is not None:\n+ cursor.execute(\"DELETE FROM %s \"\n+ \"WHERE cache_key < %%s\" % table,\n+ [result[0]])\n \n def clear(self):\n db = router.db_for_write(self.cache_model_class)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1810949, + "num_received_chars": 75871, + "elapsed_time": 567.5003378391266, + "lint_repair_count": 5, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13121.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13121.json new file mode 100644 index 00000000..4f76126e --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13121.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13121", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py\nindex 9510b5e..c1cdfc8 100644\n--- a/django/db/backends/sqlite3/operations.py\n+++ b/django/db/backends/sqlite3/operations.py\n@@ -342,7 +342,11 @@ class DatabaseOperations(BaseDatabaseOperations):\n fn_params = [\"'%s'\" % connector] + sub_expressions\n if len(fn_params) > 3:\n raise ValueError('Too many params for timedelta operations.')\n- return \"django_format_dtdelta(%s)\" % ', '.join(fn_params)\n+ # Ensure that duration expressions are converted to microseconds for SQLite compatibility\n+ return \"django_format_dtdelta(%s)\" % ', '.join(\n+ \"duration_microseconds(%s)\" % param if 'DurationField' in param else param\n+ for param in fn_params\n+ )\n \n def integer_field_range(self, internal_type):\n # SQLite doesn't enforce any integer constraints\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1156109, + "num_received_chars": 24374, + "elapsed_time": 176.9532265663147, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13195.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13195.json new file mode 100644 index 00000000..537310ee --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13195.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13195", + "edit_test_file": "tests/responses/test_cookie.py", + "code_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex e00bcac..5d45f61 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -214,9 +214,17 @@ class HttpResponseBase:\n # Most browsers ignore the Set-Cookie header if the cookie name starts\n # with __Host- or __Secure- and the cookie doesn't use the secure flag.\n secure = key.startswith(('__Secure-', '__Host-'))\n+ samesite = None\n+\n+ # Preserve the SameSite attribute if it exists\n+ if key in self.cookies:\n+ samesite = self.cookies[key].get('samesite', None)\n+ if samesite and samesite.lower() == 'none':\n+ secure = True # Ensure Secure is set if SameSite=None\n+\n self.set_cookie(\n key, max_age=0, path=path, domain=domain, secure=secure,\n- expires='Thu, 01 Jan 1970 00:00:00 GMT',\n+ expires='Thu, 01 Jan 1970 00:00:00 GMT', samesite=samesite\n )\n \n # Common methods used by subclasses\n", + "test_patch": "diff --git a/tests/responses/test_httpresponse_delete_cookie.py b/tests/responses/test_httpresponse_delete_cookie.py\nnew file mode 100644\nindex 0000000..f91f74f\n--- /dev/null\n+++ b/tests/responses/test_httpresponse_delete_cookie.py\n@@ -0,0 +1,21 @@\n+import unittest\n+from django.http import HttpResponse\n+\n+class DeleteCookieSameSiteTests(unittest.TestCase):\n+\n+ def test_delete_cookie_preserves_samesite(self):\n+ response = HttpResponse()\n+ # Set a cookie with SameSite attribute\n+ response.set_cookie('messages', 'value', samesite='Lax')\n+ self.assertEqual(response.cookies['messages']['samesite'], 'Lax')\n+\n+ # Delete the cookie\n+ response.delete_cookie('messages')\n+ deleted_cookie = response.cookies['messages']\n+\n+ # Check if SameSite attribute is preserved\n+ self.assertIn('samesite', deleted_cookie)\n+ self.assertEqual(deleted_cookie['samesite'], 'Lax')\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/responses/test_httpresponse_delete_cookie_inverted.py b/tests/responses/test_httpresponse_delete_cookie_inverted.py\nnew file mode 100644\nindex 0000000..65ec7e5\n--- /dev/null\n+++ b/tests/responses/test_httpresponse_delete_cookie_inverted.py\n@@ -0,0 +1,21 @@\n+import unittest\n+from django.http import HttpResponse\n+\n+class DeleteCookieSameSiteTests(unittest.TestCase):\n+\n+ def test_delete_cookie_preserves_samesite(self):\n+ response = HttpResponse()\n+ # Set a cookie with SameSite attribute\n+ response.set_cookie('messages', 'value', samesite='Lax')\n+ self.assertEqual(response.cookies['messages']['samesite'], 'Lax')\n+\n+ # Delete the cookie\n+ response.delete_cookie('messages')\n+ deleted_cookie = response.cookies['messages']\n+\n+ # Check if SameSite attribute is preserved\n+ # This assertion should fail if the bug is present\n+ self.assertNotIn('samesite', deleted_cookie, \"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1127730, + "num_received_chars": 39312, + "elapsed_time": 297.4387879371643, + "lint_repair_count": 0, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13297.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13297.json new file mode 100644 index 00000000..c7e9e8e6 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13297.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13297", + "edit_test_file": null, + "code_patch": "diff --git a/django/utils/functional.py b/django/utils/functional.py\nindex 6d38f93..f4deed6 100644\n--- a/django/utils/functional.py\n+++ b/django/utils/functional.py\n@@ -372,6 +372,14 @@ class SimpleLazyObject(LazyObject):\n self.__dict__['_setupfunc'] = func\n super().__init__()\n \n+ def __getitem__(self, key):\n+ \"\"\"\n+ Automatically resolve SimpleLazyObject to its concrete value when accessed.\n+ \"\"\"\n+ if self._wrapped is empty:\n+ self._setup()\n+ return self._wrapped[key]\n+\n def _setup(self):\n self._wrapped = self._setupfunc()\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1210775, + "num_received_chars": 47918, + "elapsed_time": 334.01657795906067, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13344.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13344.json new file mode 100644 index 00000000..3478e938 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13344.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13344", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py\nindex 169df6b..831b1d0 100644\n--- a/django/core/handlers/base.py\n+++ b/django/core/handlers/base.py\n@@ -240,6 +240,10 @@ class BaseHandler:\n # Complain if the view returned None or an uncalled coroutine.\n self.check_response(response, callback)\n \n+ # Ensure the response is a fully resolved HttpResponse object\n+ if asyncio.iscoroutine(response):\n+ response = await response\n+\n # If the response supports deferred rendering, apply template\n # response middleware and then render the response\n if hasattr(response, 'render') and callable(response.render):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 948471, + "num_received_chars": 24199, + "elapsed_time": 178.47008776664734, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13401.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13401.json new file mode 100644 index 00000000..46b2fb75 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13401.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13401", + "edit_test_file": "tests/model_inheritance/test_abstract_inheritance.py", + "code_patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\nindex 97d1eec..48a9c5c 100644\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -86,6 +86,11 @@ class ModelBase(type):\n classcell = attrs.pop('__classcell__', None)\n if classcell is not None:\n new_attrs['__classcell__'] = classcell\n+\n+ # Add model reference to fields for equality and ordering logic\n+ for obj_name, obj in attrs.items():\n+ if hasattr(obj, 'creation_counter'):\n+ obj.model = name\n attr_meta = attrs.pop('Meta', None)\n # Pass all attrs without a (Django-specific) contribute_to_class()\n # method to type.__new__() so that they're properly initialized\n", + "test_patch": "diff --git a/tests/model_inheritance/test_abstract_model_field_comparison.py b/tests/model_inheritance/test_abstract_model_field_comparison.py\nnew file mode 100644\nindex 0000000..c1752ec\n--- /dev/null\n+++ b/tests/model_inheritance/test_abstract_model_field_comparison.py\n@@ -0,0 +1,25 @@\n+from django.db import models\n+from django.test import SimpleTestCase\n+\n+\n+class AbstractModelFieldComparisonTests(SimpleTestCase):\n+ def test_abstract_model_field_equality(self):\n+ class A(models.Model):\n+ class Meta:\n+ abstract = True\n+ myfield = models.IntegerField()\n+\n+ class B(A):\n+ pass\n+\n+ class C(A):\n+ pass\n+\n+ # Test that fields from different models are considered equal\n+ b_field = B._meta.get_field('myfield')\n+ c_field = C._meta.get_field('myfield')\n+ self.assertEqual(b_field, c_field)\n+\n+ # Test that adding fields to a set results in de-duplication\n+ field_set = {b_field, c_field}\n+ self.assertEqual(len(field_set), 1)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_inheritance/test_abstract_model_field_comparison_inverted.py b/tests/model_inheritance/test_abstract_model_field_comparison_inverted.py\nnew file mode 100644\nindex 0000000..20b06d5\n--- /dev/null\n+++ b/tests/model_inheritance/test_abstract_model_field_comparison_inverted.py\n@@ -0,0 +1,27 @@\n+from django.db import models\n+from django.test import SimpleTestCase\n+\n+\n+class AbstractModelFieldComparisonTests(SimpleTestCase):\n+ def test_abstract_model_field_equality(self):\n+ class A(models.Model):\n+ class Meta:\n+ abstract = True\n+ myfield = models.IntegerField()\n+\n+ class B(A):\n+ pass\n+\n+ class C(A):\n+ pass\n+\n+ # Test that fields from different models are considered unequal\n+ b_field = B._meta.get_field('myfield')\n+ c_field = C._meta.get_field('myfield')\n+ if b_field == c_field:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Test that adding fields to a set does not result in de-duplication\n+ field_set = {b_field, c_field}\n+ if len(field_set) == 1:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1810510, + "num_received_chars": 60450, + "elapsed_time": 403.5847909450531, + "lint_repair_count": 8, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13417.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13417.json new file mode 100644 index 00000000..6a54b9f1 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13417.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13417", + "edit_test_file": "tests/migrations/test_multidb.py", + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 85cd831..a48780d 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -1224,10 +1224,12 @@ class QuerySet:\n return True\n if self.query.extra_order_by or self.query.order_by:\n return True\n- elif self.query.default_ordering and self.query.get_meta().ordering:\n+ if self.query.group_by or self.query.annotations:\n+ # Check if the query has an explicit ORDER BY clause\n+ return bool(self.query.order_by)\n+ if self.query.default_ordering and self.query.get_meta().ordering:\n return True\n- else:\n- return False\n+ return False\n \n @property\n def db(self):\n", + "test_patch": "diff --git a/tests/migrations/test_queryset_ordered_property.py b/tests/migrations/test_queryset_ordered_property.py\nnew file mode 100644\nindex 0000000..a7703ab\n--- /dev/null\n+++ b/tests/migrations/test_queryset_ordered_property.py\n@@ -0,0 +1,23 @@\n+from django.db import models\n+from django.test import TestCase\n+from django.db.models import Count\n+\n+class Foo(models.Model):\n+ name = models.CharField(max_length=100)\n+\n+ class Meta:\n+ ordering = ['name']\n+\n+class QuerySetOrderedPropertyTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ Foo.objects.create(name='A')\n+ Foo.objects.create(name='B')\n+\n+ def test_queryset_ordered_property_with_group_by(self):\n+ # Create a queryset with annotation\n+ qs = Foo.objects.annotate(pk_count=Count('pk')).all()\n+ \n+ # Check if the ordered property is incorrectly set to True\n+ self.assertTrue(qs.ordered, \"The queryset should not be ordered, but 'ordered' property is True.\")\n+ self.assertTrue(qs.query.default_ordering, \"The queryset should not have default ordering, but 'default_ordering' is True.\")\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/migrations/test_queryset_ordered_property_inverted.py b/tests/migrations/test_queryset_ordered_property_inverted.py\nnew file mode 100644\nindex 0000000..6be0765\n--- /dev/null\n+++ b/tests/migrations/test_queryset_ordered_property_inverted.py\n@@ -0,0 +1,25 @@\n+from django.db import models\n+from django.test import TestCase\n+from django.db.models import Count\n+\n+class Foo(models.Model):\n+ name = models.CharField(max_length=100)\n+\n+ class Meta:\n+ ordering = ['name']\n+\n+class QuerySetOrderedPropertyTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ Foo.objects.create(name='A')\n+ Foo.objects.create(name='B')\n+\n+ def test_queryset_ordered_property_with_group_by(self):\n+ # Create a queryset with annotation\n+ qs = Foo.objects.annotate(pk_count=Count('pk')).all()\n+ \n+ # Check if the ordered property is incorrectly set to True\n+ if qs.ordered:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ if qs.query.default_ordering:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1726038, + "num_received_chars": 39646, + "elapsed_time": 365.572256565094, + "lint_repair_count": 2, + "test_generation_attempts": 7, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13513.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13513.json new file mode 100644 index 00000000..c355686b --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13513.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13513", + "edit_test_file": "tests/urlpatterns/tests.py", + "code_patch": "diff --git a/django/views/debug.py b/django/views/debug.py\nindex 7a89f7b..39eec5c 100644\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -397,9 +397,9 @@ class ExceptionReporter:\n def get_traceback_frames(self):\n def explicit_or_implicit_cause(exc_value):\n explicit = getattr(exc_value, '__cause__', None)\n- suppress_context = getattr(exc_value, '__suppress_context__', None)\n+ suppress_context = getattr(exc_value, '__suppress_context__', False)\n implicit = getattr(exc_value, '__context__', None)\n- return explicit or (None if suppress_context else implicit)\n+ return explicit if explicit is not None else (None if suppress_context else implicit)\n \n # Get the exception and all its causes\n exceptions = []\n", + "test_patch": "diff --git a/tests/urlpatterns/test_debug_error_view_suppress_context.py b/tests/urlpatterns/test_debug_error_view_suppress_context.py\nnew file mode 100644\nindex 0000000..7a11aea\n--- /dev/null\n+++ b/tests/urlpatterns/test_debug_error_view_suppress_context.py\n@@ -0,0 +1,16 @@\n+import sys\n+from django.test import SimpleTestCase, RequestFactory\n+from django.views.debug import technical_500_response\n+\n+class DebugErrorViewSuppressContextTests(SimpleTestCase):\n+ def test_suppress_context(self):\n+ request = RequestFactory().get('/')\n+ try:\n+ try:\n+ raise RuntimeError('my error')\n+ except Exception as exc:\n+ raise ValueError('my new error') from None\n+ except Exception:\n+ exc_info = sys.exc_info()\n+ response = technical_500_response(request, *exc_info)\n+ self.assertIn('RuntimeError', response.content.decode())\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/urlpatterns/test_debug_error_view_suppress_context_inverted.py b/tests/urlpatterns/test_debug_error_view_suppress_context_inverted.py\nnew file mode 100644\nindex 0000000..bd486fe\n--- /dev/null\n+++ b/tests/urlpatterns/test_debug_error_view_suppress_context_inverted.py\n@@ -0,0 +1,19 @@\n+import sys\n+from django.test import SimpleTestCase, RequestFactory\n+from django.views.debug import technical_500_response\n+\n+class DebugErrorViewSuppressContextTests(SimpleTestCase):\n+ def test_suppress_context(self):\n+ request = RequestFactory().get('/')\n+ try:\n+ try:\n+ raise RuntimeError('my error')\n+ except Exception as exc:\n+ raise ValueError('my new error') from None\n+ except Exception:\n+ exc_info = sys.exc_info()\n+ response = technical_500_response(request, *exc_info)\n+ # Alter the assertion to check for the absence of 'RuntimeError'\n+ # and raise an error if it is present, indicating the bug.\n+ if 'RuntimeError' in response.content.decode():\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1617466, + "num_received_chars": 36085, + "elapsed_time": 335.55053901672363, + "lint_repair_count": 4, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13568.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13568.json new file mode 100644 index 00000000..4a71cf7b --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13568.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13568", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/auth/checks.py b/django/contrib/auth/checks.py\nindex 65fc266..908ca39 100644\n--- a/django/contrib/auth/checks.py\n+++ b/django/contrib/auth/checks.py\n@@ -4,6 +4,8 @@ from types import MethodType\n from django.apps import apps\n from django.conf import settings\n from django.core import checks\n+from django.db.models import UniqueConstraint # Import UniqueConstraint\n+from django.db import models # Import models\n \n from .management import _get_builtin_permissions\n \n@@ -53,28 +55,34 @@ def check_user_model(app_configs=None, **kwargs):\n \n # Check that the username field is unique\n if not cls._meta.get_field(cls.USERNAME_FIELD).unique:\n- if (settings.AUTHENTICATION_BACKENDS ==\n- ['django.contrib.auth.backends.ModelBackend']):\n- errors.append(\n- checks.Error(\n- \"'%s.%s' must be unique because it is named as the 'USERNAME_FIELD'.\" % (\n- cls._meta.object_name, cls.USERNAME_FIELD\n- ),\n- obj=cls,\n- id='auth.E003',\n+ # Check if USERNAME_FIELD is part of any UniqueConstraint\n+ unique_constraints = [\n+ constraint for constraint in cls._meta.constraints\n+ if isinstance(constraint, UniqueConstraint) and cls.USERNAME_FIELD in constraint.fields\n+ ]\n+ if not unique_constraints:\n+ if (settings.AUTHENTICATION_BACKENDS ==\n+ ['django.contrib.auth.backends.ModelBackend']):\n+ errors.append(\n+ checks.Error(\n+ \"'%s.%s' must be unique because it is named as the 'USERNAME_FIELD'.\" % (\n+ cls._meta.object_name, cls.USERNAME_FIELD\n+ ),\n+ obj=cls,\n+ id='auth.E003',\n+ )\n )\n- )\n- else:\n- errors.append(\n- checks.Warning(\n- \"'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique.\" % (\n- cls._meta.object_name, cls.USERNAME_FIELD\n- ),\n- hint='Ensure that your authentication backend(s) can handle non-unique usernames.',\n- obj=cls,\n- id='auth.W004',\n+ else:\n+ errors.append(\n+ checks.Warning(\n+ \"'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique.\" % (\n+ cls._meta.object_name, cls.USERNAME_FIELD\n+ ),\n+ hint='Ensure that your authentication backend(s) can handle non-unique usernames.',\n+ obj=cls,\n+ id='auth.W004',\n+ )\n )\n- )\n \n if isinstance(cls().is_anonymous, MethodType):\n errors.append(\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1273113, + "num_received_chars": 43480, + "elapsed_time": 272.2774064540863, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13658.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13658.json new file mode 100644 index 00000000..30cde9b3 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13658.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13658", + "edit_test_file": "tests/utils_tests/test_autoreload.py", + "code_patch": "diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py\nindex 1ba093e..e411e86 100644\n--- a/django/core/management/__init__.py\n+++ b/django/core/management/__init__.py\n@@ -344,7 +344,7 @@ class ManagementUtility:\n # Preprocess options to extract --settings and --pythonpath.\n # These options could affect the commands that are available, so they\n # must be processed early.\n- parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False)\n+ parser = CommandParser(prog=self.prog_name, usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False)\n parser.add_argument('--settings')\n parser.add_argument('--pythonpath')\n parser.add_argument('args', nargs='*') # catch-all\n", + "test_patch": "diff --git a/tests/utils_tests/test_management_utility.py b/tests/utils_tests/test_management_utility.py\nnew file mode 100644\nindex 0000000..63a5876\n--- /dev/null\n+++ b/tests/utils_tests/test_management_utility.py\n@@ -0,0 +1,18 @@\n+import sys\n+from django.core.management import execute_from_command_line\n+from django.test import SimpleTestCase\n+\n+class TestManagementUtility(SimpleTestCase):\n+ def test_command_parser_prog_name(self):\n+ \"\"\"\n+ Test that ManagementUtility uses the correct program name when\n+ instantiating CommandParser.\n+ \"\"\"\n+ # Simulate an environment where sys.argv[0] is None\n+ original_argv = sys.argv\n+ try:\n+ sys.argv = [None, 'runserver']\n+ with self.assertRaises(TypeError):\n+ execute_from_command_line(['manage.py', 'runserver'])\n+ finally:\n+ sys.argv = original_argv\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/utils_tests/test_management_utility_inverted.py b/tests/utils_tests/test_management_utility_inverted.py\nnew file mode 100644\nindex 0000000..b09ad7f\n--- /dev/null\n+++ b/tests/utils_tests/test_management_utility_inverted.py\n@@ -0,0 +1,19 @@\n+import sys\n+from django.core.management import execute_from_command_line\n+from django.test import SimpleTestCase\n+\n+class TestManagementUtility(SimpleTestCase):\n+ def test_command_parser_prog_name(self):\n+ \"\"\"\n+ Test that ManagementUtility uses the correct program name when\n+ instantiating CommandParser.\n+ \"\"\"\n+ # Simulate an environment where sys.argv[0] is None\n+ original_argv = sys.argv\n+ try:\n+ sys.argv = [None, 'runserver']\n+ # The test should now fail with a specific error message when the bug is observed\n+ with self.assertRaisesRegex(TypeError, \"__BUG__HERE__\"):\n+ execute_from_command_line(['manage.py', 'runserver'])\n+ finally:\n+ sys.argv = original_argv\n\\ No newline at end of file\n", + "num_sent_chars": 1187446, + "num_received_chars": 31829, + "elapsed_time": 351.7433443069458, + "lint_repair_count": 0, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13786.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13786.json new file mode 100644 index 00000000..34959588 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13786.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13786", + "edit_test_file": "tests/migrations/test_operations.py", + "code_patch": "diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py\nindex dddf7c6..1b33f2a 100644\n--- a/django/db/migrations/operations/models.py\n+++ b/django/db/migrations/operations/models.py\n@@ -137,11 +137,15 @@ class CreateModel(ModelOperation):\n ),\n ]\n elif isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower:\n+ # Remove options not present in operation.options\n+ new_options = {key: value for key, value in self.options.items() if key in operation.options}\n+ # Merge with operation.options\n+ new_options.update(operation.options)\n return [\n CreateModel(\n self.name,\n fields=self.fields,\n- options={**self.options, **operation.options},\n+ options=new_options,\n bases=self.bases,\n managers=self.managers,\n ),\n", + "test_patch": "diff --git a/tests/migrations/test_migrations_optimize_options.py b/tests/migrations/test_migrations_optimize_options.py\nnew file mode 100644\nindex 0000000..49b679b\n--- /dev/null\n+++ b/tests/migrations/test_migrations_optimize_options.py\n@@ -0,0 +1,47 @@\n+from django.db import migrations, models\n+from django.test import SimpleTestCase\n+from django.db.migrations.state import ProjectState\n+\n+class TestMigrationsOptimizeOptions(SimpleTestCase):\n+ def test_squashmigrations_does_not_unset_model_options(self):\n+ \"\"\"\n+ Test that squashing migrations does not unset model options when\n+ optimizing CreateModel and AlterModelOptions.\n+ \"\"\"\n+ # Initial state with a model having some options\n+ initial_state = ProjectState()\n+ initial_state.add_model(\n+ migrations.state.ModelState(\n+ app_label='test_app',\n+ name='TestModel',\n+ fields=[\n+ ('id', models.AutoField(primary_key=True)),\n+ ],\n+ options={'verbose_name': 'Test Model'},\n+ )\n+ )\n+\n+ # CreateModel operation with initial options\n+ create_model_op = migrations.CreateModel(\n+ name='TestModel',\n+ fields=[\n+ ('id', models.AutoField(primary_key=True)),\n+ ],\n+ options={'verbose_name': 'Test Model'},\n+ )\n+\n+ # AlterModelOptions operation that should clear options\n+ alter_model_options_op = migrations.AlterModelOptions(\n+ name='TestModel',\n+ options={},\n+ )\n+\n+ # Simulate the squashing process\n+ reduced_operations = create_model_op.reduce(alter_model_options_op, 'test_app')\n+\n+ # Check that the reduced operation still has the verbose_name option\n+ self.assertEqual(\n+ reduced_operations[0].options.get('verbose_name'),\n+ 'Test Model',\n+ \"The verbose_name option should not be present after squashing.\"\n+ )\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/migrations/test_migrations_optimize_options_inverted.py b/tests/migrations/test_migrations_optimize_options_inverted.py\nnew file mode 100644\nindex 0000000..0698556\n--- /dev/null\n+++ b/tests/migrations/test_migrations_optimize_options_inverted.py\n@@ -0,0 +1,44 @@\n+from django.db import migrations, models\n+from django.test import SimpleTestCase\n+from django.db.migrations.state import ProjectState\n+\n+class TestMigrationsOptimizeOptions(SimpleTestCase):\n+ def test_squashmigrations_does_not_unset_model_options(self):\n+ \"\"\"\n+ Test that squashing migrations does not unset model options when\n+ optimizing CreateModel and AlterModelOptions.\n+ \"\"\"\n+ # Initial state with a model having some options\n+ initial_state = ProjectState()\n+ initial_state.add_model(\n+ migrations.state.ModelState(\n+ app_label='test_app',\n+ name='TestModel',\n+ fields=[\n+ ('id', models.AutoField(primary_key=True)),\n+ ],\n+ options={'verbose_name': 'Test Model'},\n+ )\n+ )\n+\n+ # CreateModel operation with initial options\n+ create_model_op = migrations.CreateModel(\n+ name='TestModel',\n+ fields=[\n+ ('id', models.AutoField(primary_key=True)),\n+ ],\n+ options={'verbose_name': 'Test Model'},\n+ )\n+\n+ # AlterModelOptions operation that should clear options\n+ alter_model_options_op = migrations.AlterModelOptions(\n+ name='TestModel',\n+ options={},\n+ )\n+\n+ # Simulate the squashing process\n+ reduced_operations = create_model_op.reduce(alter_model_options_op, 'test_app')\n+\n+ # Check that the reduced operation does not have the verbose_name option\n+ if reduced_operations[0].options.get('verbose_name') == 'Test Model':\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1168775, + "num_received_chars": 16222, + "elapsed_time": 107.5392632484436, + "lint_repair_count": 2, + "test_generation_attempts": 2, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13809.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13809.json new file mode 100644 index 00000000..246d752d --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13809.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13809", + "edit_test_file": "tests/admin_scripts/tests.py", + "code_patch": "diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py\nindex d9fb088..deada55 100644\n--- a/django/core/management/commands/runserver.py\n+++ b/django/core/management/commands/runserver.py\n@@ -51,6 +51,10 @@ class Command(BaseCommand):\n '--noreload', action='store_false', dest='use_reloader',\n help='Tells Django to NOT use the auto-reloader.',\n )\n+ parser.add_argument(\n+ '--skip-checks', action='store_true', dest='skip_checks',\n+ help='Tells Django to skip system checks.',\n+ )\n \n def execute(self, *args, **options):\n if options['no_color']:\n@@ -68,6 +72,11 @@ class Command(BaseCommand):\n if not settings.DEBUG and not settings.ALLOWED_HOSTS:\n raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.')\n \n+ if not options['skip_checks']:\n+ self.stdout.write(\"Performing system checks...\\n\\n\")\n+ self.check(display_num_errors=True)\n+ self.check_migrations()\n+\n self.use_ipv6 = options['use_ipv6']\n if self.use_ipv6 and not socket.has_ipv6:\n raise CommandError('Your Python does not support IPv6.')\n", + "test_patch": "diff --git a/tests/admin_scripts/test_skip_checks_option.py b/tests/admin_scripts/test_skip_checks_option.py\nnew file mode 100644\nindex 0000000..6a3dc1c\n--- /dev/null\n+++ b/tests/admin_scripts/test_skip_checks_option.py\n@@ -0,0 +1,17 @@\n+import unittest\n+from io import StringIO\n+from django.core.management import call_command\n+from django.core.management.commands.runserver import Command as RunserverCommand\n+\n+class RunserverSkipChecksOptionTest(unittest.TestCase):\n+ def setUp(self):\n+ self.output = StringIO()\n+ self.cmd = RunserverCommand(stdout=self.output)\n+\n+ def test_runserver_with_skip_checks_option(self):\n+ with self.assertRaises(TypeError) as cm:\n+ call_command(self.cmd, skip_checks=True)\n+ self.assertIn(\"Unknown option(s) for runserver command: skip_checks.\", str(cm.exception))\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/admin_scripts/test_skip_checks_option_inverted.py b/tests/admin_scripts/test_skip_checks_option_inverted.py\nnew file mode 100644\nindex 0000000..cd516b5\n--- /dev/null\n+++ b/tests/admin_scripts/test_skip_checks_option_inverted.py\n@@ -0,0 +1,17 @@\n+import unittest\n+from io import StringIO\n+from django.core.management import call_command\n+from django.core.management.commands.runserver import Command as RunserverCommand\n+\n+class RunserverSkipChecksOptionTest(unittest.TestCase):\n+ def setUp(self):\n+ self.output = StringIO()\n+ self.cmd = RunserverCommand(stdout=self.output)\n+\n+ def test_runserver_with_skip_checks_option(self):\n+ with self.assertRaises(Exception) as cm:\n+ call_command(self.cmd, skip_checks=True)\n+ self.assertIn(\"__BUG__HERE__\", str(cm.exception))\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1223603, + "num_received_chars": 51569, + "elapsed_time": 1984.3868861198425, + "lint_repair_count": 0, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13821.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13821.json new file mode 100644 index 00000000..24887ff5 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13821.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13821", + "edit_test_file": "tests/backends/sqlite/test_operations.py", + "code_patch": "diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py\nindex ab4ea70..dcff553 100644\n--- a/django/db/backends/sqlite3/base.py\n+++ b/django/db/backends/sqlite3/base.py\n@@ -64,8 +64,8 @@ def list_aggregate(function):\n \n \n def check_sqlite_version():\n- if Database.sqlite_version_info < (3, 8, 3):\n- raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)\n+ if Database.sqlite_version_info < (3, 9, 0):\n+ raise ImproperlyConfigured('SQLite 3.9.0 or later is required (found %s).' % Database.sqlite_version)\n \n \n check_sqlite_version()\n\ndiff --git a/django/db/backends/sqlite3/features.py b/django/db/backends/sqlite3/features.py\nindex 3348256..6931c93 100644\n--- a/django/db/backends/sqlite3/features.py\n+++ b/django/db/backends/sqlite3/features.py\n@@ -33,8 +33,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n # Is \"ALTER TABLE ... RENAME COLUMN\" supported?\n can_alter_table_rename_column = Database.sqlite_version_info >= (3, 25, 0)\n supports_parentheses_in_compound = False\n- # Deferred constraint checks can be emulated on SQLite < 3.20 but not in a\n- # reasonably performant way.\n supports_pragma_foreign_key_check = Database.sqlite_version_info >= (3, 20, 0)\n can_defer_constraint_checks = supports_pragma_foreign_key_check\n supports_functions_in_partial_indexes = Database.sqlite_version_info >= (3, 15, 0)\n@@ -66,12 +64,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n 'model_fields.test_integerfield.PositiveIntegerFieldTests.test_negative_values',\n },\n }\n- if Database.sqlite_version_info < (3, 27):\n- skips.update({\n- 'Nondeterministic failure on SQLite < 3.27.': {\n- 'expressions_window.tests.WindowFunctionTests.test_subquery_row_range_rank',\n- },\n- })\n if self.connection.is_in_memory_db():\n skips.update({\n \"the sqlite backend's close() method is a no-op when using an \"\n", + "test_patch": "diff --git a/tests/backends/sqlite/test_sqlite_version_support.py b/tests/backends/sqlite/test_sqlite_version_support.py\nnew file mode 100644\nindex 0000000..277ee11\n--- /dev/null\n+++ b/tests/backends/sqlite/test_sqlite_version_support.py\n@@ -0,0 +1,12 @@\n+import unittest\n+from django.core.exceptions import ImproperlyConfigured\n+from django.db.backends.sqlite3.base import Database\n+\n+class SQLiteVersionSupportTests(unittest.TestCase):\n+ def test_sqlite_version_support(self):\n+ # This test checks if the SQLite version is less than 3.9.0\n+ # and expects an ImproperlyConfigured exception to be raised.\n+ if Database.sqlite_version_info < (3, 9, 0):\n+ with self.assertRaises(ImproperlyConfigured) as cm:\n+ raise ImproperlyConfigured('SQLite 3.9.0 or later is required.')\n+ self.assertEqual(str(cm.exception), 'SQLite 3.9.0 or later is required.')\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1636078, + "num_received_chars": 38842, + "elapsed_time": 333.59967017173767, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13933.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13933.json new file mode 100644 index 00000000..e7a7b362 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-13933.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13933", + "edit_test_file": "tests/model_forms/test_modelchoicefield.py", + "code_patch": "diff --git a/django/forms/models.py b/django/forms/models.py\nindex 422bc5d..e03a380 100644\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -1188,7 +1188,7 @@ class ModelChoiceField(ChoiceField):\n # This class is a subclass of ChoiceField for purity, but it doesn't\n # actually use any of ChoiceField's implementation.\n default_error_messages = {\n- 'invalid_choice': _('Select a valid choice. That choice is not one of'\n+ 'invalid_choice': _('Select a valid choice. %(value)s is not one of'\n ' the available choices.'),\n }\n iterator = ModelChoiceIterator\n@@ -1284,7 +1284,11 @@ class ModelChoiceField(ChoiceField):\n value = getattr(value, key)\n value = self.queryset.get(**{key: value})\n except (ValueError, TypeError, self.queryset.model.DoesNotExist):\n- raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')\n+ raise ValidationError(\n+ self.error_messages['invalid_choice'],\n+ code='invalid_choice',\n+ params={'value': value},\n+ )\n return value\n \n def validate(self, value):\n", + "test_patch": "diff --git a/tests/model_forms/test_invalid_choice_handling.py b/tests/model_forms/test_invalid_choice_handling.py\nnew file mode 100644\nindex 0000000..141f59c\n--- /dev/null\n+++ b/tests/model_forms/test_invalid_choice_handling.py\n@@ -0,0 +1,19 @@\n+import datetime\n+from django import forms\n+from django.core.exceptions import ValidationError\n+from django.test import TestCase\n+from .models import Category\n+\n+class ModelChoiceFieldInvalidChoiceTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment')\n+ cls.c2 = Category.objects.create(name='A test', slug='test', url='test')\n+ cls.c3 = Category.objects.create(name='Third', slug='third-test', url='third')\n+\n+ def test_invalid_choice_error_message(self):\n+ f = forms.ModelChoiceField(Category.objects.all())\n+ invalid_value = 999 # Assuming this ID does not exist\n+ expected_message = \"['Select a valid choice. That choice is not one of the available choices.']\"\n+ with self.assertRaisesMessage(ValidationError, expected_message):\n+ f.clean(invalid_value)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_forms/test_invalid_choice_handling_inverted.py b/tests/model_forms/test_invalid_choice_handling_inverted.py\nnew file mode 100644\nindex 0000000..db99869\n--- /dev/null\n+++ b/tests/model_forms/test_invalid_choice_handling_inverted.py\n@@ -0,0 +1,24 @@\n+import datetime\n+from django import forms\n+from django.core.exceptions import ValidationError\n+from django.test import TestCase\n+from .models import Category\n+\n+class ModelChoiceFieldInvalidChoiceTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment')\n+ cls.c2 = Category.objects.create(name='A test', slug='test', url='test')\n+ cls.c3 = Category.objects.create(name='Third', slug='third-test', url='third')\n+\n+ def test_invalid_choice_error_message(self):\n+ f = forms.ModelChoiceField(Category.objects.all())\n+ invalid_value = 999 # Assuming this ID does not exist\n+ # Alter the expected message to include the invalid value\n+ expected_message = \"__BUG__HERE__\"\n+ try:\n+ f.clean(invalid_value)\n+ except ValidationError as e:\n+ # Check if the error message does not contain the invalid value\n+ if str(invalid_value) not in str(e):\n+ raise AssertionError(expected_message)\n\\ No newline at end of file\n", + "num_sent_chars": 1947980, + "num_received_chars": 77971, + "elapsed_time": 462.2897436618805, + "lint_repair_count": 13, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14011.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14011.json new file mode 100644 index 00000000..c3b2c487 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14011.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14011", + "edit_test_file": "tests/servers/test_liveserverthread.py", + "code_patch": "diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py\nindex 14dab51..f6e6a07 100644\n--- a/django/core/servers/basehttp.py\n+++ b/django/core/servers/basehttp.py\n@@ -81,6 +81,15 @@ class ThreadedWSGIServer(socketserver.ThreadingMixIn, WSGIServer):\n \"\"\"A threaded version of the WSGIServer\"\"\"\n daemon_threads = True\n \n+ def process_request_thread(self, request, client_address):\n+ try:\n+ super().process_request_thread(request, client_address)\n+ finally:\n+ # Ensure that the database connection is closed after each request\n+ from django.db import connections\n+ for conn in connections.all():\n+ conn.close()\n+\n \n class ServerHandler(simple_server.ServerHandler):\n http_version = '1.1'\n@@ -212,4 +221,10 @@ def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGISe\n # isn't terminating correctly.\n httpd.daemon_threads = True\n httpd.set_app(wsgi_handler)\n- httpd.serve_forever()\n+ try:\n+ httpd.serve_forever()\n+ finally:\n+ # Ensure all database connections are closed on server shutdown\n+ from django.db import connections\n+ for conn in connections.all():\n+ conn.close()\n", + "test_patch": "diff --git a/tests/servers/test_threadedwsgiserver_dbconnection.py b/tests/servers/test_threadedwsgiserver_dbconnection.py\nnew file mode 100644\nindex 0000000..c07b0f0\n--- /dev/null\n+++ b/tests/servers/test_threadedwsgiserver_dbconnection.py\n@@ -0,0 +1,35 @@\n+from django.db import OperationalError, connections\n+from django.test import LiveServerTestCase, TransactionTestCase\n+from django.core.servers.basehttp import ThreadedWSGIServer\n+from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler\n+\n+class NonThreadedLiveServerThread(LiveServerThread):\n+ def _create_server(self):\n+ return ThreadedWSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)\n+\n+class ThreadedWSGIServerIssueTest(TransactionTestCase):\n+ available_apps = []\n+\n+ def test_database_connection_not_closed(self):\n+ class MyTest(LiveServerTestCase):\n+ server_thread_class = NonThreadedLiveServerThread\n+\n+ # Open a connection to the database.\n+ conn = connections['default']\n+ conn.connect()\n+ conn.inc_thread_sharing()\n+\n+ try:\n+ # Simulate the test case execution\n+ test_case = MyTest(methodName='setUpClass')\n+ test_case.setUpClass()\n+ test_case.tearDownClass()\n+\n+ # Assert that the connection is still open, which should not be the case\n+ self.assertIsNotNone(conn.connection)\n+ except OperationalError as e:\n+ # Check if the error is due to the database being accessed by other users\n+ self.assertIn(\"database is being accessed by other users\", str(e))\n+ finally:\n+ conn.dec_thread_sharing()\n+ conn.close()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/servers/test_threadedwsgiserver_dbconnection_inverted.py b/tests/servers/test_threadedwsgiserver_dbconnection_inverted.py\nnew file mode 100644\nindex 0000000..a24e7d1\n--- /dev/null\n+++ b/tests/servers/test_threadedwsgiserver_dbconnection_inverted.py\n@@ -0,0 +1,35 @@\n+from django.db import OperationalError, connections\n+from django.test import LiveServerTestCase, TransactionTestCase\n+from django.core.servers.basehttp import ThreadedWSGIServer\n+from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler\n+\n+class NonThreadedLiveServerThread(LiveServerThread):\n+ def _create_server(self):\n+ return ThreadedWSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)\n+\n+class ThreadedWSGIServerIssueTest(TransactionTestCase):\n+ available_apps = []\n+\n+ def test_database_connection_not_closed(self):\n+ class MyTest(LiveServerTestCase):\n+ server_thread_class = NonThreadedLiveServerThread\n+\n+ # Open a connection to the database.\n+ conn = connections['default']\n+ conn.connect()\n+ conn.inc_thread_sharing()\n+\n+ try:\n+ # Simulate the test case execution\n+ test_case = MyTest(methodName='setUpClass')\n+ test_case.setUpClass()\n+ test_case.tearDownClass()\n+\n+ # Assert that the connection is closed, which should be the case\n+ self.assertIsNone(conn.connection, \"__BUG__HERE__\")\n+ except OperationalError as e:\n+ # Check if the error is due to the database being accessed by other users\n+ self.assertIn(\"database is being accessed by other users\", str(e))\n+ finally:\n+ conn.dec_thread_sharing()\n+ conn.close()\n\\ No newline at end of file\n", + "num_sent_chars": 1518009, + "num_received_chars": 67433, + "elapsed_time": 409.57057428359985, + "lint_repair_count": 3, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14053.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14053.json new file mode 100644 index 00000000..bb34df68 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14053.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14053", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py\nindex 494890c..025d662 100644\n--- a/django/contrib/staticfiles/storage.py\n+++ b/django/contrib/staticfiles/storage.py\n@@ -232,11 +232,14 @@ class HashedFilesMixin:\n yield name, hashed_name, processed\n \n paths = {path: paths[path] for path in adjustable_paths}\n+ processed_files = set()\n \n for i in range(self.max_post_process_passes):\n substitutions = False\n for name, hashed_name, processed, subst in self._post_process(paths, adjustable_paths, hashed_files):\n- yield name, hashed_name, processed\n+ if name not in processed_files:\n+ yield name, hashed_name, processed\n+ processed_files.add(name)\n substitutions = substitutions or subst\n \n if not substitutions:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1182965, + "num_received_chars": 33858, + "elapsed_time": 214.71395015716553, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14140.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14140.json new file mode 100644 index 00000000..ee12e9c9 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14140.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14140", + "edit_test_file": "tests/queries/test_q.py", + "code_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 0f53d9c..05a70fd 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -414,27 +414,35 @@ class Field(RegisterLookupMixin):\n return sql, params\n \n def deconstruct(self):\n- \"\"\"\n- Return enough information to recreate the field as a 4-tuple:\n-\n- * The name of the field on the model, if contribute_to_class() has\n- been run.\n- * The import path of the field, including the class:e.g.\n- django.db.models.IntegerField This should be the most portable\n- version, so less specific may be better.\n- * A list of positional arguments.\n- * A dict of keyword arguments.\n-\n- Note that the positional or keyword arguments must contain values of\n- the following types (including inner values of collection types):\n-\n- * None, bool, str, int, float, complex, set, frozenset, list, tuple,\n- dict\n- * UUID\n- * datetime.datetime (naive), datetime.date\n- * top-level classes, top-level functions - will be referenced by their\n- full import path\n- * Storage instances - these have their own deconstruct() method\n+ \"\"\"\n+ Return enough information to recreate the field as a 4-tuple:\n+ \n+ * The name of the field on the model, if contribute_to_class() has\n+ been run.\n+ * The import path of the field, including the class:e.g.\n+ django.db.models.IntegerField This should be the most portable\n+ version, so less specific may be better.\n+ * A list of positional arguments.\n+ * A dict of keyword arguments.\n+ \n+ Note that the positional or keyword arguments must contain values of\n+ the following types (including inner values of collection types):\n+ \n+ * None, bool, str, int, float, complex, set, frozenset, list, tuple,\n+ dict\n+ * UUID\n+ * datetime.datetime (naive), datetime.date\n+ * top-level classes, top-level functions - will be referenced by their\n+ full import path\n+ * Storage instances - these have their own deconstruct() method\n+ \"\"\"\n+ if len(self.children) == 1:\n+ child = self.children[0]\n+ if isinstance(child, tuple) and len(child) == 2:\n+ return self._deconstruct_single_child_as_kwargs(child)\n+ else:\n+ return self._deconstruct_single_child_as_args(child)\n+ return self._deconstruct_multiple_children()\n \n This is because the values here must be serialized into a text format\n (possibly new Python code, possibly JSON) and these are the only types\n", + "test_patch": "diff --git a/tests/queries/test_q_deconstruct.py b/tests/queries/test_q_deconstruct.py\nnew file mode 100644\nindex 0000000..f7904d6\n--- /dev/null\n+++ b/tests/queries/test_q_deconstruct.py\n@@ -0,0 +1,9 @@\n+from django.db.models import Q, Exists\n+from django.test import SimpleTestCase\n+from django.contrib.auth import get_user_model\n+\n+class QDeconstructTests(SimpleTestCase):\n+ def test_deconstruct_with_non_subscriptable_child(self):\n+ with self.assertRaises(TypeError) as cm:\n+ Q(Exists(get_user_model().objects.filter(username='jim'))).deconstruct()\n+ self.assertIn(\"'Exists' object is not subscriptable\", str(cm.exception))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/queries/test_q_deconstruct_inverted.py b/tests/queries/test_q_deconstruct_inverted.py\nnew file mode 100644\nindex 0000000..5f482ee\n--- /dev/null\n+++ b/tests/queries/test_q_deconstruct_inverted.py\n@@ -0,0 +1,10 @@\n+from django.db.models import Q, Exists\n+from django.test import SimpleTestCase\n+from django.contrib.auth import get_user_model\n+\n+class QDeconstructTests(SimpleTestCase):\n+ def test_deconstruct_with_non_subscriptable_child(self):\n+ try:\n+ Q(Exists(get_user_model().objects.filter(username='jim'))).deconstruct()\n+ except TypeError as e:\n+ self.fail(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1582835, + "num_received_chars": 46536, + "elapsed_time": 323.08679461479187, + "lint_repair_count": 10, + "test_generation_attempts": 2, + "code_generation_attempts": 6, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14238.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14238.json new file mode 100644 index 00000000..aad5e67f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14238.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14238", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 0f53d9c..1dfc728 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -2524,7 +2524,8 @@ class AutoFieldMeta(type):\n return isinstance(instance, self._subclasses) or super().__instancecheck__(instance)\n \n def __subclasscheck__(self, subclass):\n- return subclass in self._subclasses or super().__subclasscheck__(subclass)\n+ # Check if subclass is a subclass of any class in _subclasses\n+ return any(issubclass(subclass, cls) for cls in self._subclasses) or super().__subclasscheck__(subclass)\n \n \n class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1630001, + "num_received_chars": 34395, + "elapsed_time": 289.49177527427673, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14349.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14349.json new file mode 100644 index 00000000..2122b2ef --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14349.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14349", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/validators.py b/django/core/validators.py\nindex a385819..2f5f93b 100644\n--- a/django/core/validators.py\n+++ b/django/core/validators.py\n@@ -101,6 +101,11 @@ class URLValidator(RegexValidator):\n def __call__(self, value):\n if not isinstance(value, str):\n raise ValidationError(self.message, code=self.code, params={'value': value})\n+\n+ # Early rejection of URLs containing line feed, carriage return, or tab characters\n+ if any(char in value for char in ['\\n', '\\r', '\\t']):\n+ raise ValidationError(self.message, code=self.code, params={'value': value})\n+\n # Check if the scheme is valid.\n scheme = value.split('://')[0].lower()\n if scheme not in self.schemes:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 980872, + "num_received_chars": 20052, + "elapsed_time": 182.30996179580688, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14376.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14376.json new file mode 100644 index 00000000..e0141805 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14376.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14376", + "edit_test_file": "tests/backends/mysql/test_operations.py", + "code_patch": "diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py\nindex 2c62182..038e5b8 100644\n--- a/django/db/backends/mysql/base.py\n+++ b/django/db/backends/mysql/base.py\n@@ -192,23 +192,23 @@ class DatabaseWrapper(BaseDatabaseWrapper):\n validation_class = DatabaseValidation\n \n def get_connection_params(self):\n- kwargs = {\n- 'conv': django_conversions,\n- 'charset': 'utf8',\n- }\n- settings_dict = self.settings_dict\n- if settings_dict['USER']:\n- kwargs['user'] = settings_dict['USER']\n- if settings_dict['NAME']:\n- kwargs['db'] = settings_dict['NAME']\n- if settings_dict['PASSWORD']:\n- kwargs['passwd'] = settings_dict['PASSWORD']\n- if settings_dict['HOST'].startswith('/'):\n- kwargs['unix_socket'] = settings_dict['HOST']\n- elif settings_dict['HOST']:\n- kwargs['host'] = settings_dict['HOST']\n- if settings_dict['PORT']:\n- kwargs['port'] = int(settings_dict['PORT'])\n+ kwargs = {\n+ 'conv': django_conversions,\n+ 'charset': 'utf8',\n+ }\n+ settings_dict = self.settings_dict\n+ if settings_dict['USER']:\n+ kwargs['user'] = settings_dict['USER']\n+ if settings_dict['NAME']:\n+ kwargs['database'] = settings_dict['NAME']\n+ if settings_dict['PASSWORD']:\n+ kwargs['password'] = settings_dict['PASSWORD']\n+ if settings_dict['HOST'].startswith('/'):\n+ kwargs['unix_socket'] = settings_dict['HOST']\n+ elif settings_dict['HOST']:\n+ kwargs['host'] = settings_dict['HOST']\n+ if settings_dict['PORT']:\n+ kwargs['port'] = int(settings_dict['PORT'])\n # We need the number of potentially affected rows after an\n # \"UPDATE\", not the number of changed rows.\n kwargs['client_flag'] = CLIENT.FOUND_ROWS\n", + "test_patch": "diff --git a/tests/backends/mysql/test_deprecated_mysql_kwargs.py b/tests/backends/mysql/test_deprecated_mysql_kwargs.py\nnew file mode 100644\nindex 0000000..cf754a2\n--- /dev/null\n+++ b/tests/backends/mysql/test_deprecated_mysql_kwargs.py\n@@ -0,0 +1,24 @@\n+import unittest\n+from django.core.exceptions import ImproperlyConfigured\n+from django.db import connection\n+from django.test import SimpleTestCase\n+\n+@unittest.skipUnless(connection.vendor == 'mysql', 'MySQL tests.')\n+class MySQLDeprecatedKwargsTests(SimpleTestCase):\n+ def test_deprecated_db_and_passwd_kwargs(self):\n+ with self.assertRaises(ImproperlyConfigured) as cm:\n+ connection.settings_dict.update({\n+ 'NAME': 'test_db',\n+ 'USER': 'test_user',\n+ 'PASSWORD': 'test_pass',\n+ 'HOST': 'localhost',\n+ 'PORT': '3306',\n+ 'OPTIONS': {\n+ 'db': 'test_db',\n+ 'passwd': 'test_pass',\n+ }\n+ })\n+ connection.get_connection_params()\n+ \n+ self.assertIn(\"db\", str(cm.exception))\n+ self.assertIn(\"passwd\", str(cm.exception))\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1475767, + "num_received_chars": 55230, + "elapsed_time": 342.28550720214844, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14493.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14493.json new file mode 100644 index 00000000..c7552a0c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14493.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14493", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py\nindex f957a66..8f98493 100644\n--- a/django/contrib/staticfiles/storage.py\n+++ b/django/contrib/staticfiles/storage.py\n@@ -261,8 +261,8 @@ class HashedFilesMixin:\n \n paths = {path: paths[path] for path in adjustable_paths}\n \n+ substitutions = False\n for i in range(self.max_post_process_passes):\n- substitutions = False\n for name, hashed_name, processed, subst in self._post_process(paths, adjustable_paths, hashed_files):\n # Overwrite since hashed_name may be newer.\n processed_adjustable_paths[name] = (name, hashed_name, processed)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1776134, + "num_received_chars": 60108, + "elapsed_time": 408.8487141132355, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14539.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14539.json new file mode 100644 index 00000000..badc5dab --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14539.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14539", + "edit_test_file": "tests/sitemaps_tests/test_utils.py", + "code_patch": "diff --git a/django/utils/html.py b/django/utils/html.py\nindex 3bc02b8..71031fb 100644\n--- a/django/utils/html.py\n+++ b/django/utils/html.py\n@@ -249,6 +249,7 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):\n \n If autoescape is True, autoescape the link text and URLs.\n \"\"\"\n+ text = html.unescape(text) # Unescape HTML entities before processing\n safe_input = isinstance(text, SafeData)\n \n def trim_url(x, limit=trim_url_limit):\n@@ -277,6 +278,13 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):\n middle = middle[:-len(closing)]\n trail = closing + trail\n trimmed_something = True\n+ # Trim trailing punctuation after unescaping entities\n+ middle_unescaped = html.unescape(middle)\n+ stripped = middle_unescaped.rstrip(TRAILING_PUNCTUATION_CHARS)\n+ if middle_unescaped != stripped:\n+ trail = middle[len(stripped):] + trail\n+ middle = middle[:len(stripped) - len(middle_unescaped)]\n+ trimmed_something = True\n # Trim trailing punctuation (after trimming wrapping punctuation,\n # as encoded entities contain ';'). Unescape entities to avoid\n # breaking them by removing ';'.\n", + "test_patch": "diff --git a/tests/sitemaps_tests/test_urlize.py b/tests/sitemaps_tests/test_urlize.py\nnew file mode 100644\nindex 0000000..8b5195b\n--- /dev/null\n+++ b/tests/sitemaps_tests/test_urlize.py\n@@ -0,0 +1,10 @@\n+from django.test import SimpleTestCase\n+from django.utils.html import urlize\n+\n+class UrlizeHtmlEscapedTests(SimpleTestCase):\n+\n+ def test_urlize_html_escaped_string_with_trailing_punctuation(self):\n+ input_text = 'Search for google.com/?q=1<! and see.'\n+ expected_output = 'Search for google.com/?q=1<lt! and see.'\n+ actual_output = urlize(input_text)\n+ self.assertEqual(actual_output, expected_output)\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1054014, + "num_received_chars": 28601, + "elapsed_time": 219.78174996376038, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14608.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14608.json new file mode 100644 index 00000000..ef9a9146 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14608.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14608", + "edit_test_file": null, + "code_patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\nindex a89c355..6526ca3 100644\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -295,6 +295,8 @@ class BaseFormSet:\n \"\"\"\n if self._non_form_errors is None:\n self.full_clean()\n+ # Ensure the 'nonform' CSS class is applied\n+ self._non_form_errors.error_class = 'nonform'\n return self._non_form_errors\n \n @property\n@@ -333,7 +335,7 @@ class BaseFormSet:\n self._non_form_errors.\n \"\"\"\n self._errors = []\n- self._non_form_errors = self.error_class()\n+ self._non_form_errors = self.error_class(error_class='nonform')\n empty_forms_count = 0\n \n if not self.is_bound: # Stop further processing.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1395477, + "num_received_chars": 32678, + "elapsed_time": 200.93019437789917, + "lint_repair_count": 5, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14725.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14725.json new file mode 100644 index 00000000..9be8f568 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14725.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14725", + "edit_test_file": "tests/model_formsets/tests.py", + "code_patch": "diff --git a/django/forms/models.py b/django/forms/models.py\nindex 7effb20..29609b1 100644\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -573,9 +573,10 @@ class BaseModelFormSet(BaseFormSet):\n unique_fields = set()\n \n def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,\n- queryset=None, *, initial=None, **kwargs):\n+ queryset=None, *, initial=None, allow_new=True, **kwargs):\n self.queryset = queryset\n self.initial_extra = initial\n+ self.allow_new = allow_new\n super().__init__(**{'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix, **kwargs})\n \n def initial_form_count(self):\n@@ -812,6 +813,9 @@ class BaseModelFormSet(BaseFormSet):\n return saved_instances\n \n def save_new_objects(self, commit=True):\n+ if not self.allow_new:\n+ raise ValidationError(\"New object creation is not allowed in this formset.\")\n+ \n self.new_objects = []\n for form in self.extra_forms:\n if not form.has_changed():\n", + "test_patch": "diff --git a/tests/model_formsets/test_model_formset_edit_only.py b/tests/model_formsets/test_model_formset_edit_only.py\nnew file mode 100644\nindex 0000000..712e23b\n--- /dev/null\n+++ b/tests/model_formsets/test_model_formset_edit_only.py\n@@ -0,0 +1,39 @@\n+import datetime\n+from django import forms\n+from django.forms.models import modelformset_factory\n+from django.test import TestCase\n+from .models import Author\n+\n+class ModelFormsetEditOnlyTest(TestCase):\n+ def test_edit_only_formset_allows_new_object_creation(self):\n+ \"\"\"\n+ Test that a model formset with extra=0 still allows new object creation,\n+ which is not the intended behavior for an \"edit only\" view.\n+ \"\"\"\n+ # Create an initial author to edit\n+ author = Author.objects.create(name='Existing Author')\n+\n+ # Create a formset with extra=0, intending to only edit existing authors\n+ AuthorFormSet = modelformset_factory(Author, fields=\"__all__\", extra=0)\n+\n+ # Simulate POST data that includes an additional form for a new author\n+ data = {\n+ 'form-TOTAL_FORMS': '2', # 1 existing + 1 new\n+ 'form-INITIAL_FORMS': '1', # 1 existing\n+ 'form-MAX_NUM_FORMS': '', # no max\n+ 'form-0-id': str(author.id),\n+ 'form-0-name': 'Updated Author',\n+ 'form-1-id': '', # New form\n+ 'form-1-name': 'New Author',\n+ }\n+\n+ formset = AuthorFormSet(data=data, queryset=Author.objects.all())\n+\n+ # The formset should be valid, but this is not the intended behavior\n+ # for an \"edit only\" view, as it allows new object creation.\n+ self.assertTrue(formset.is_valid())\n+\n+ # Save the formset and check that a new author was created\n+ formset.save()\n+ self.assertEqual(Author.objects.count(), 2)\n+ self.assertTrue(Author.objects.filter(name='New Author').exists())\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_formsets/test_model_formset_edit_only_inverted.py b/tests/model_formsets/test_model_formset_edit_only_inverted.py\nnew file mode 100644\nindex 0000000..e88e2da\n--- /dev/null\n+++ b/tests/model_formsets/test_model_formset_edit_only_inverted.py\n@@ -0,0 +1,39 @@\n+import datetime\n+from django import forms\n+from django.forms.models import modelformset_factory\n+from django.test import TestCase\n+from .models import Author\n+\n+class ModelFormsetEditOnlyTest(TestCase):\n+ def test_edit_only_formset_disallows_new_object_creation(self):\n+ \"\"\"\n+ Test that a model formset with extra=0 disallows new object creation,\n+ which is the intended behavior for an \"edit only\" view.\n+ \"\"\"\n+ # Create an initial author to edit\n+ author = Author.objects.create(name='Existing Author')\n+\n+ # Create a formset with extra=0, intending to only edit existing authors\n+ AuthorFormSet = modelformset_factory(Author, fields=\"__all__\", extra=0)\n+\n+ # Simulate POST data that includes an additional form for a new author\n+ data = {\n+ 'form-TOTAL_FORMS': '2', # 1 existing + 1 new\n+ 'form-INITIAL_FORMS': '1', # 1 existing\n+ 'form-MAX_NUM_FORMS': '', # no max\n+ 'form-0-id': str(author.id),\n+ 'form-0-name': 'Updated Author',\n+ 'form-1-id': '', # New form\n+ 'form-1-name': 'New Author',\n+ }\n+\n+ formset = AuthorFormSet(data=data, queryset=Author.objects.all())\n+\n+ # The formset should not be valid, as it should disallow new object creation\n+ if formset.is_valid():\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Ensure no new author was created\n+ formset.save()\n+ self.assertEqual(Author.objects.count(), 1)\n+ self.assertFalse(Author.objects.filter(name='New Author').exists())\n\\ No newline at end of file\n", + "num_sent_chars": 1288362, + "num_received_chars": 151201, + "elapsed_time": 562.6340129375458, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14771.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14771.json new file mode 100644 index 00000000..2c8aaab8 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14771.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14771", + "edit_test_file": null, + "code_patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\nindex cc65c04..1fcc5f4 100644\n--- a/django/utils/autoreload.py\n+++ b/django/utils/autoreload.py\n@@ -219,7 +219,10 @@ def get_child_arguments():\n import __main__\n py_script = Path(sys.argv[0])\n \n- args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions]\n+ # Capture -X options from the current Python process\n+ x_options = [arg for arg in sys._xoptions.keys()]\n+\n+ args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + ['-X%s' % x for x in x_options]\n # __spec__ is set when the server was started with the `-m` option,\n # see https://docs.python.org/3/reference/import.html#main-spec\n # __spec__ may not exist, e.g. when running in a Conda env.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 975701, + "num_received_chars": 22816, + "elapsed_time": 177.751526594162, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14855.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14855.json new file mode 100644 index 00000000..09ff09c9 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-14855.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14855", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py\nindex dd154f7..ba8c346 100644\n--- a/django/contrib/admin/helpers.py\n+++ b/django/contrib/admin/helpers.py\n@@ -209,7 +209,11 @@ class AdminReadonlyField:\n remote_field.model._meta.model_name,\n )\n try:\n- url = reverse(url_name, args=[quote(remote_obj.pk)])\n+ url = reverse(\n+ url_name,\n+ args=[quote(remote_obj.pk)],\n+ current_app=self.model_admin.admin_site.name\n+ )\n return format_html('{}', url, remote_obj)\n except NoReverseMatch:\n return str(remote_obj)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1890955, + "num_received_chars": 25991, + "elapsed_time": 245.17018747329712, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15022.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15022.json new file mode 100644 index 00000000..8229dcca --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15022.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15022", + "edit_test_file": "tests/model_fields/test_charfield.py", + "code_patch": "diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py\nindex 43583c8..c02a9a3 100644\n--- a/django/contrib/admin/views/main.py\n+++ b/django/contrib/admin/views/main.py\n@@ -482,6 +482,10 @@ class ChangeList:\n # ValueError, ValidationError, or ?.\n raise IncorrectLookupParameters(e)\n \n+ # Optimize by using prefetch_related for related fields\n+ if self.list_select_related:\n+ qs = qs.prefetch_related(*self.list_select_related)\n+\n # Apply search results\n qs, search_may_have_duplicates = self.model_admin.get_search_results(\n request, qs, self.query,\n@@ -497,6 +501,10 @@ class ChangeList:\n qs = qs.filter(pk=OuterRef('pk'))\n qs = self.root_queryset.filter(Exists(qs))\n \n+ # Optimize by using select_related for related fields\n+ if self.list_select_related:\n+ qs = qs.select_related(*self.list_select_related)\n+\n # Set ordering.\n ordering = self.get_ordering(request, qs)\n qs = qs.order_by(*ordering)\n", + "test_patch": "diff --git a/tests/model_fields/test_admin_changelist_query.py b/tests/model_fields/test_admin_changelist_query.py\nnew file mode 100644\nindex 0000000..23ce3ed\n--- /dev/null\n+++ b/tests/model_fields/test_admin_changelist_query.py\n@@ -0,0 +1,43 @@\n+from django.test import TestCase\n+from django.contrib.admin.sites import AdminSite\n+from django.contrib.admin.options import ModelAdmin\n+from django.db import models\n+from django.utils.translation import gettext_lazy as _\n+\n+class Client(models.Model):\n+ name = models.CharField(_('name'), max_length=256)\n+ name2 = models.CharField(_('unofficial or obsolete name'), max_length=256, blank=True, null=True)\n+ contact_person = models.CharField(_('contact person'), max_length=256, blank=True, null=True)\n+\n+class ClientOffice(models.Model):\n+ name = models.CharField(_('name'), max_length=256)\n+ name2 = models.CharField(_('unofficial or obsolete name'), max_length=256, blank=True, null=True)\n+ client = models.ForeignKey(Client, verbose_name=_('client'), on_delete=models.CASCADE)\n+\n+class ClientAdmin(ModelAdmin):\n+ search_fields = ('name', 'name2', 'contact_person', 'clientoffice__name', 'clientoffice__name2')\n+\n+class MockRequest:\n+ pass\n+\n+class TestAdminChangelistQuery(TestCase):\n+ def setUp(self):\n+ self.site = AdminSite()\n+ self.client_admin = ClientAdmin(Client, self.site)\n+ self.request = MockRequest()\n+\n+ def test_unnecessary_joins_in_admin_changelist_query(self):\n+ # Create test data\n+ client = Client.objects.create(name='Test Client', name2='Test Client 2', contact_person='John Doe')\n+ ClientOffice.objects.create(name='Office 1', name2='Office 2', client=client)\n+\n+ # Simulate a search query with multiple words\n+ search_query = 'Test Client Office'\n+\n+ # Perform the search\n+ queryset = self.client_admin.get_search_results(self.request, Client.objects.all(), search_query)[0]\n+\n+ # Check if the query contains unnecessary joins\n+ # This is a placeholder assertion to simulate the issue\n+ # In a real test, you would inspect the SQL query generated\n+ self.assertTrue('JOIN' in str(queryset.query))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_fields/test_admin_changelist_query_inverted.py b/tests/model_fields/test_admin_changelist_query_inverted.py\nnew file mode 100644\nindex 0000000..dff049f\n--- /dev/null\n+++ b/tests/model_fields/test_admin_changelist_query_inverted.py\n@@ -0,0 +1,43 @@\n+from django.test import TestCase\n+from django.contrib.admin.sites import AdminSite\n+from django.contrib.admin.options import ModelAdmin\n+from django.db import models\n+from django.utils.translation import gettext_lazy as _\n+\n+class Client(models.Model):\n+ name = models.CharField(_('name'), max_length=256)\n+ name2 = models.CharField(_('unofficial or obsolete name'), max_length=256, blank=True, null=True)\n+ contact_person = models.CharField(_('contact person'), max_length=256, blank=True, null=True)\n+\n+class ClientOffice(models.Model):\n+ name = models.CharField(_('name'), max_length=256)\n+ name2 = models.CharField(_('unofficial or obsolete name'), max_length=256, blank=True, null=True)\n+ client = models.ForeignKey(Client, verbose_name=_('client'), on_delete=models.CASCADE)\n+\n+class ClientAdmin(ModelAdmin):\n+ search_fields = ('name', 'name2', 'contact_person', 'clientoffice__name', 'clientoffice__name2')\n+\n+class MockRequest:\n+ pass\n+\n+class TestAdminChangelistQuery(TestCase):\n+ def setUp(self):\n+ self.site = AdminSite()\n+ self.client_admin = ClientAdmin(Client, self.site)\n+ self.request = MockRequest()\n+\n+ def test_unnecessary_joins_in_admin_changelist_query(self):\n+ # Create test data\n+ client = Client.objects.create(name='Test Client', name2='Test Client 2', contact_person='John Doe')\n+ ClientOffice.objects.create(name='Office 1', name2='Office 2', client=client)\n+\n+ # Simulate a search query with multiple words\n+ search_query = 'Test Client Office'\n+\n+ # Perform the search\n+ queryset = self.client_admin.get_search_results(self.request, Client.objects.all(), search_query)[0]\n+\n+ # Check if the query contains unnecessary joins\n+ # This assertion should now fail if the bug is present\n+ if 'JOIN' in str(queryset.query):\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2054173, + "num_received_chars": 121256, + "elapsed_time": 560.3501110076904, + "lint_repair_count": 11, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15103.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15103.json new file mode 100644 index 00000000..ac2077a9 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15103.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15103", + "edit_test_file": "tests/sites_tests/tests.py", + "code_patch": "diff --git a/django/utils/html.py b/django/utils/html.py\nindex da1b567..8147c5d 100644\n--- a/django/utils/html.py\n+++ b/django/utils/html.py\n@@ -61,7 +61,7 @@ _json_script_escapes = {\n }\n \n \n-def json_script(value, element_id):\n+def json_script(value, element_id=None):\n \"\"\"\n Escape all the HTML/XML special characters with their unicode escapes, so\n value is safe to be output anywhere except for inside a tag attribute. Wrap\n@@ -69,10 +69,16 @@ def json_script(value, element_id):\n \"\"\"\n from django.core.serializers.json import DjangoJSONEncoder\n json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)\n- return format_html(\n- '',\n- element_id, mark_safe(json_str)\n- )\n+ if element_id:\n+ return format_html(\n+ '',\n+ element_id, mark_safe(json_str)\n+ )\n+ else:\n+ return format_html(\n+ '',\n+ mark_safe(json_str)\n+ )\n \n \n def conditional_escape(text):\n", + "test_patch": "diff --git a/tests/sites_tests/test_json_script_optional_element_id.py b/tests/sites_tests/test_json_script_optional_element_id.py\nnew file mode 100644\nindex 0000000..1c98f2d\n--- /dev/null\n+++ b/tests/sites_tests/test_json_script_optional_element_id.py\n@@ -0,0 +1,11 @@\n+from django.test import SimpleTestCase\n+from django.utils.html import json_script\n+\n+class JsonScriptOptionalElementIdTests(SimpleTestCase):\n+ def test_json_script_without_element_id(self):\n+ \"\"\"\n+ Test that json_script can be called without an element_id.\n+ This should raise a TypeError since element_id is currently required.\n+ \"\"\"\n+ with self.assertRaises(TypeError):\n+ json_script({'key': 'value'})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/sites_tests/test_json_script_optional_element_id_inverted.py b/tests/sites_tests/test_json_script_optional_element_id_inverted.py\nnew file mode 100644\nindex 0000000..8fad337\n--- /dev/null\n+++ b/tests/sites_tests/test_json_script_optional_element_id_inverted.py\n@@ -0,0 +1,13 @@\n+from django.test import SimpleTestCase\n+from django.utils.html import json_script\n+\n+class JsonScriptOptionalElementIdTests(SimpleTestCase):\n+ def test_json_script_without_element_id(self):\n+ \"\"\"\n+ Test that json_script can be called without an element_id.\n+ This should raise a TypeError since element_id is currently required.\n+ \"\"\"\n+ try:\n+ json_script({'key': 'value'})\n+ except TypeError:\n+ self.fail(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 648143, + "num_received_chars": 9330, + "elapsed_time": 101.87096238136292, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15128.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15128.json new file mode 100644 index 00000000..ee5bf703 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15128.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15128", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\nindex aaf35ee..55a228c 100644\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -762,6 +762,8 @@ class Query(BaseExpression):\n # Create a new alias for this table.\n if alias_list:\n alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)\n+ while alias in self.alias_map or alias in self.external_aliases:\n+ alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 2)\n alias_list.append(alias)\n else:\n # The first occurrence of a table uses the table name directly.\n@@ -846,7 +848,10 @@ class Query(BaseExpression):\n relabelling any references to them in select columns and the where\n clause.\n \"\"\"\n- assert set(change_map).isdisjoint(change_map.values())\n+ # Ensure no overlap between keys and values in change_map\n+ assert set(change_map).isdisjoint(change_map.values()), (\n+ \"Change map keys and values must not overlap to prevent alias conflicts.\"\n+ )\n \n # 1. Update references in \"select\" (normal columns plus aliases),\n # \"group by\" and \"where\".\n@@ -977,6 +982,8 @@ class Query(BaseExpression):\n \n # No reuse is possible, so we need a new alias.\n alias, _ = self.table_alias(join.table_name, create=True, filtered_relation=join.filtered_relation)\n+ while alias in self.alias_map or alias in self.external_aliases:\n+ alias, _ = self.table_alias(join.table_name, create=True, filtered_relation=join.filtered_relation)\n if join.join_type:\n if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n join_type = LOUTER\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1120502, + "num_received_chars": 27632, + "elapsed_time": 183.48574876785278, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15268.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15268.json new file mode 100644 index 00000000..77446a2f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15268.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15268", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/migrations/optimizer.py b/django/db/migrations/optimizer.py\nindex ee20f62..cf2f01b 100644\n--- a/django/db/migrations/optimizer.py\n+++ b/django/db/migrations/optimizer.py\n@@ -13,6 +13,8 @@ class MigrationOptimizer:\n \"\"\"\n Main optimization entry point. Pass in a list of Operation instances,\n get out a new list of Operation instances.\n+ This method will also optimize multiple AlterFooTogether operations\n+ into a single operation when possible.\n \n Unfortunately, due to the scope of the optimization (two combinable\n operations might be separated by several hundred others), this can't be\n@@ -22,6 +24,28 @@ class MigrationOptimizer:\n are any matches, stopping at boundaries - operations which can't\n be optimized over (RunSQL, operations on the same field/model, etc.)\n \n+ # Optimization for AlterFooTogether operations\n+ optimized_operations = []\n+ skip_next = False\n+ for i, operation in enumerate(operations):\n+ if skip_next:\n+ skip_next = False\n+ continue\n+ if isinstance(operation, (operations.AlterUniqueTogether, operations.AlterIndexTogether)):\n+ if i + 1 < len(operations) and isinstance(operations[i + 1], operation.__class__):\n+ # Merge the two operations\n+ merged_operation = operation.__class__(\n+ name=operation.name,\n+ **{operation.option_name: operations[i + 1].option_value}\n+ )\n+ optimized_operations.append(merged_operation)\n+ skip_next = True\n+ else:\n+ optimized_operations.append(operation)\n+ else:\n+ optimized_operations.append(operation)\n+ return optimized_operations\n+\n The inner loop is run until the starting list is the same as the result\n list, and then the result is returned. This means that operation\n optimization must be stable and always return an equal or shorter list.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2640178, + "num_received_chars": 65200, + "elapsed_time": 311.47637963294983, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15280.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15280.json new file mode 100644 index 00000000..ba3f3b73 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15280.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15280", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py\nindex a9faef3..89a3c3f 100644\n--- a/django/contrib/auth/models.py\n+++ b/django/contrib/auth/models.py\n@@ -143,6 +143,7 @@ class UserManager(BaseUserManager):\n GlobalUserModel = apps.get_model(self.model._meta.app_label, self.model._meta.object_name)\n username = GlobalUserModel.normalize_username(username)\n user = self.model(username=username, email=email, **extra_fields)\n+ user._state.deferred_fields = set() # Ensure no deferred fields are inherited\n user.password = make_password(password)\n user.save(using=self._db)\n return user\n\ndiff --git a/django/db/models/query.py b/django/db/models/query.py\nindex fb66397..51ea44a 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -1358,6 +1358,10 @@ class QuerySet:\n def _fetch_all(self):\n if self._result_cache is None:\n self._result_cache = list(self._iterable_class(self))\n+ # Reset deferred fields for prefetched objects\n+ for obj in self._result_cache:\n+ if hasattr(obj, '_state'):\n+ obj._state.deferred_fields = set()\n if self._prefetch_related_lookups and not self._prefetch_done:\n self._prefetch_related_objects()\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1314904, + "num_received_chars": 32747, + "elapsed_time": 229.4393663406372, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15375.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15375.json new file mode 100644 index 00000000..278caaed --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15375.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15375", + "edit_test_file": "tests/aggregation/tests.py", + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex e20c460..ec3f7b6 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -18,7 +18,7 @@ from django.db.models import AutoField, DateField, DateTimeField, sql\n from django.db.models.constants import LOOKUP_SEP, OnConflict\n from django.db.models.deletion import Collector\n from django.db.models.expressions import Case, F, Ref, Value, When\n-from django.db.models.functions import Cast, Trunc\n+from django.db.models.functions import Cast, Trunc, Coalesce\n from django.db.models.query_utils import FilteredRelation, Q\n from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE\n from django.db.models.utils import create_namedtuple_class, resolve_callables\n@@ -418,6 +418,9 @@ class QuerySet:\n \n query = self.query.chain()\n for (alias, aggregate_expr) in kwargs.items():\n+ if hasattr(aggregate_expr, 'default'):\n+ # Use Coalesce to handle default values in aggregation\n+ aggregate_expr = Coalesce(aggregate_expr, aggregate_expr.default)\n query.add_annotation(aggregate_expr, alias, is_summary=True)\n annotation = query.annotations[alias]\n if not annotation.contains_aggregate:\n", + "test_patch": "diff --git a/tests/aggregation/test_aggregate_annotate_default_crash.py b/tests/aggregation/test_aggregate_annotate_default_crash.py\nnew file mode 100644\nindex 0000000..f4a4282\n--- /dev/null\n+++ b/tests/aggregation/test_aggregate_annotate_default_crash.py\n@@ -0,0 +1,25 @@\n+import datetime\n+from decimal import Decimal\n+\n+from django.db.models import Sum, F\n+from django.test import TestCase\n+from django.db.utils import OperationalError\n+\n+from .models import Book, Author, Publisher, Store\n+\n+\n+class AggregateAnnotateDefaultCrashTestCase(TestCase):\n+\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.a1 = Author.objects.create(name='Adrian Holovaty', age=34)\n+ cls.p1 = Publisher.objects.create(name='Apress', num_awards=3)\n+ cls.b1 = Book.objects.create(\n+ isbn='159059725', name='The Definitive Guide to Django: Web Development Done Right',\n+ pages=447, rating=4.5, price=Decimal('30.00'), contact=cls.a1, publisher=cls.p1,\n+ pubdate=datetime.date(2007, 12, 6)\n+ )\n+\n+ def test_aggregate_annotate_default_crash(self):\n+ with self.assertRaises(OperationalError):\n+ Book.objects.annotate(idx=F(\"id\")).aggregate(Sum(\"id\", default=0))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/aggregation/test_aggregate_annotate_default_crash_inverted.py b/tests/aggregation/test_aggregate_annotate_default_crash_inverted.py\nnew file mode 100644\nindex 0000000..cdd8dbc\n--- /dev/null\n+++ b/tests/aggregation/test_aggregate_annotate_default_crash_inverted.py\n@@ -0,0 +1,26 @@\n+import datetime\n+from decimal import Decimal\n+\n+from django.db.models import Sum, F\n+from django.test import TestCase\n+from django.db.utils import OperationalError\n+\n+from .models import Book, Author, Publisher\n+\n+class AggregateAnnotateDefaultCrashTestCase(TestCase):\n+\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.a1 = Author.objects.create(name='Adrian Holovaty', age=34)\n+ cls.p1 = Publisher.objects.create(name='Apress', num_awards=3)\n+ cls.b1 = Book.objects.create(\n+ isbn='159059725', name='The Definitive Guide to Django: Web Development Done Right',\n+ pages=447, rating=4.5, price=Decimal('30.00'), contact=cls.a1, publisher=cls.p1,\n+ pubdate=datetime.date(2007, 12, 6)\n+ )\n+\n+ def test_aggregate_annotate_default_crash(self):\n+ try:\n+ Book.objects.annotate(idx=F(\"id\")).aggregate(Sum(\"id\", default=0))\n+ except OperationalError:\n+ self.fail(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2490578, + "num_received_chars": 146282, + "elapsed_time": 628.14075756073, + "lint_repair_count": 9, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15467.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15467.json new file mode 100644 index 00000000..f1ffc140 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15467.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15467", + "edit_test_file": "tests/admin_widgets/tests.py", + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 64be087..6219590 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -269,7 +269,8 @@ class BaseModelAdmin(metaclass=forms.MediaDefiningClass):\n \"class\": get_ul_class(self.radio_fields[db_field.name]),\n }\n )\n- kwargs[\"empty_label\"] = _(\"None\") if db_field.blank else None\n+ if \"empty_label\" not in kwargs:\n+ kwargs[\"empty_label\"] = _(\"None\") if db_field.blank else None\n \n if \"queryset\" not in kwargs:\n queryset = self.get_field_queryset(db, db_field, request)\n", + "test_patch": "diff --git a/tests/admin_widgets/test_modeladmin_empty_label.py b/tests/admin_widgets/test_modeladmin_empty_label.py\nnew file mode 100644\nindex 0000000..3702f48\n--- /dev/null\n+++ b/tests/admin_widgets/test_modeladmin_empty_label.py\n@@ -0,0 +1,34 @@\n+import gettext\n+import os\n+from django import forms\n+from django.contrib import admin\n+from django.contrib.auth.models import User\n+from django.db import models\n+from django.test import TestCase\n+from django.utils.translation import gettext_lazy as _\n+\n+# Define a simple model for testing\n+class MyModel(models.Model):\n+ myfield = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)\n+\n+# Define a ModelAdmin with radio_fields and custom empty_label\n+class MyModelAdmin(admin.ModelAdmin):\n+ radio_fields = {'myfield': admin.VERTICAL}\n+\n+ def formfield_for_foreignkey(self, db_field, *args, **kwargs):\n+ if db_field.name == 'myfield':\n+ kwargs['empty_label'] = \"I WANT TO SET MY OWN EMPTY LABEL\"\n+ return super().formfield_for_foreignkey(db_field, *args, **kwargs)\n+\n+# Register the model with the custom ModelAdmin\n+admin.site.register(MyModel, MyModelAdmin)\n+\n+class ModelAdminEmptyLabelTest(TestCase):\n+ def test_empty_label_override(self):\n+ \"\"\"\n+ Test that the custom empty_label is overridden by the default_empty_label\n+ when radio_fields is set.\n+ \"\"\"\n+ ma = MyModelAdmin(MyModel, admin.site)\n+ formfield = ma.formfield_for_foreignkey(MyModel._meta.get_field('myfield'), request=None)\n+ self.assertEqual(formfield.empty_label, _('None')) # This should fail if the issue is present\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/admin_widgets/test_modeladmin_empty_label_inverted.py b/tests/admin_widgets/test_modeladmin_empty_label_inverted.py\nnew file mode 100644\nindex 0000000..eb30e6e\n--- /dev/null\n+++ b/tests/admin_widgets/test_modeladmin_empty_label_inverted.py\n@@ -0,0 +1,36 @@\n+import gettext\n+import os\n+from django import forms\n+from django.contrib import admin\n+from django.contrib.auth.models import User\n+from django.db import models\n+from django.test import TestCase\n+from django.utils.translation import gettext_lazy as _\n+\n+# Define a simple model for testing\n+class MyModel(models.Model):\n+ myfield = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)\n+\n+# Define a ModelAdmin with radio_fields and custom empty_label\n+class MyModelAdmin(admin.ModelAdmin):\n+ radio_fields = {'myfield': admin.VERTICAL}\n+\n+ def formfield_for_foreignkey(self, db_field, *args, **kwargs):\n+ if db_field.name == 'myfield':\n+ kwargs['empty_label'] = \"I WANT TO SET MY OWN EMPTY LABEL\"\n+ return super().formfield_for_foreignkey(db_field, *args, **kwargs)\n+\n+# Register the model with the custom ModelAdmin\n+admin.site.register(MyModel, MyModelAdmin)\n+\n+class ModelAdminEmptyLabelTest(TestCase):\n+ def test_empty_label_override(self):\n+ \"\"\"\n+ Test that the custom empty_label is overridden by the default_empty_label\n+ when radio_fields is set.\n+ \"\"\"\n+ ma = MyModelAdmin(MyModel, admin.site)\n+ formfield = ma.formfield_for_foreignkey(MyModel._meta.get_field('myfield'), request=None)\n+ if formfield.empty_label == _('None'):\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(formfield.empty_label, \"I WANT TO SET MY OWN EMPTY LABEL\") # This should fail if the issue is present\n\\ No newline at end of file\n", + "num_sent_chars": 684224, + "num_received_chars": 14456, + "elapsed_time": 103.83806800842285, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15525.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15525.json new file mode 100644 index 00000000..f07b2ced --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15525.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15525", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py\nindex 59d7318..b78468d 100644\n--- a/django/core/serializers/json.py\n+++ b/django/core/serializers/json.py\n@@ -67,7 +67,8 @@ def Deserializer(stream_or_string, **options):\n stream_or_string = stream_or_string.decode()\n try:\n objects = json.loads(stream_or_string)\n- yield from PythonDeserializer(objects, **options)\n+ # Pass the database option to the PythonDeserializer\n+ yield from PythonDeserializer(objects, **options, using=options.get('using'))\n except (GeneratorExit, DeserializationError):\n raise\n except Exception as exc:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 372231, + "num_received_chars": 10378, + "elapsed_time": 87.71361470222473, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15563.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15563.json new file mode 100644 index 00000000..785f9604 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15563.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15563", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 5c78c6e..77e870e 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -987,7 +987,11 @@ class QuerySet:\n if self.query.is_sliced:\n raise TypeError(\"Cannot update a query once a slice has been taken.\")\n self._for_write = True\n- query = self.query.chain(sql.UpdateQuery)\n+ # Ensure the update targets the correct model table in multi-inheritance scenarios\n+ if self.model._meta.concrete_model is not self.model:\n+ query = self.query.chain(sql.UpdateQuery, self.model)\n+ else:\n+ query = self.query.chain(sql.UpdateQuery)\n query.add_update_values(kwargs)\n # Clear any annotations so that they won't be present in subqueries.\n query.annotations = {}\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1107650, + "num_received_chars": 29932, + "elapsed_time": 178.88620972633362, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15629.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15629.json new file mode 100644 index 00000000..bc3b7eca --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15629.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15629", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py\nindex 696bfd7..ee38786 100644\n--- a/django/db/backends/base/schema.py\n+++ b/django/db/backends/base/schema.py\n@@ -1425,8 +1425,11 @@ class BaseDatabaseSchemaEditor:\n self.quote_name,\n )\n deferrable = self.connection.ops.deferrable_sql()\n+ # Ensure the collation of the foreign key matches the primary key\n+ collation = field.target_field.db_collation\n+ collation_sql = f\" {self._collate_sql(collation)}\" if collation else \"\"\n return Statement(\n- self.sql_create_fk,\n+ self.sql_create_fk + collation_sql,\n table=table,\n name=name,\n column=column,\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1429072, + "num_received_chars": 22455, + "elapsed_time": 162.94432663917542, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15732.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15732.json new file mode 100644 index 00000000..e5c7003a --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15732.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15732", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py\nindex f2ca8c8..805c5cd 100644\n--- a/django/db/backends/base/schema.py\n+++ b/django/db/backends/base/schema.py\n@@ -568,6 +568,11 @@ class BaseDatabaseSchemaEditor:\n exclude=meta_constraint_names | meta_index_names,\n **constraint_kwargs,\n )\n+ # Allow multiple constraints and filter out primary key constraints\n+ constraint_names = [\n+ name for name in constraint_names\n+ if not self._is_primary_key_constraint(model, name)\n+ ]\n if len(constraint_names) != 1:\n raise ValueError(\n \"Found wrong number (%s) of constraints for %s(%s)\"\n@@ -579,6 +584,14 @@ class BaseDatabaseSchemaEditor:\n )\n self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))\n \n+ def _is_primary_key_constraint(self, model, constraint_name):\n+ \"\"\"Check if the given constraint name is a primary key constraint.\"\"\"\n+ with self.connection.cursor() as cursor:\n+ constraints = self.connection.introspection.get_constraints(\n+ cursor, model._meta.db_table\n+ )\n+ return constraints.get(constraint_name, {}).get(\"primary_key\", False)\n+\n def alter_db_table(self, model, old_db_table, new_db_table):\n \"\"\"Rename the table a model points to.\"\"\"\n if old_db_table == new_db_table or (\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2658520, + "num_received_chars": 28280, + "elapsed_time": 185.61212968826294, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15851.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15851.json new file mode 100644 index 00000000..a9d299c9 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15851.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15851", + "edit_test_file": "tests/dbshell/test_postgresql.py", + "code_patch": "diff --git a/django/core/management/commands/dbshell.py b/django/core/management/commands/dbshell.py\nindex 30d2765..c511624 100644\n--- a/django/core/management/commands/dbshell.py\n+++ b/django/core/management/commands/dbshell.py\n@@ -27,7 +27,11 @@ class Command(BaseCommand):\n def handle(self, **options):\n connection = connections[options[\"database\"]]\n try:\n- connection.client.runshell(options[\"parameters\"])\n+ # Reorder parameters to ensure they are before the database name for PostgreSQL\n+ parameters = options[\"parameters\"]\n+ if connection.vendor == 'postgresql':\n+ parameters = parameters + [connection.settings_dict['NAME']]\n+ connection.client.runshell(parameters)\n except FileNotFoundError:\n # Note that we're assuming the FileNotFoundError relates to the\n # command missing. It could be raised for some other reason, in\n", + "test_patch": "diff --git a/tests/dbshell/test_dbshell_parameters.py b/tests/dbshell/test_dbshell_parameters.py\nnew file mode 100644\nindex 0000000..f0379e1\n--- /dev/null\n+++ b/tests/dbshell/test_dbshell_parameters.py\n@@ -0,0 +1,19 @@\n+import subprocess\n+import sys\n+from unittest import mock\n+from django.core.management import call_command\n+from django.core.management.base import CommandError\n+from django.test import SimpleTestCase\n+from django.db import connection\n+\n+class DbshellParametersTestCase(SimpleTestCase):\n+ def test_dbshell_parameters_order(self):\n+ # Mock the subprocess.run to capture the command arguments\n+ with mock.patch(\"subprocess.run\") as mock_run:\n+ mock_run.return_value = subprocess.CompletedProcess(args=[], returncode=0)\n+ call_command(\"dbshell\", \"--\", \"-c\", \"select * from some_table;\")\n+ \n+ # Check if the database name is not at the end of the command\n+ called_args = mock_run.call_args[0][0]\n+ dbname_index = called_args.index(connection.settings_dict['NAME'])\n+ self.assertLess(dbname_index, called_args.index(\"-c\"), \"Database name should be at the end of the arguments list.\")\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/dbshell/test_dbshell_parameters_inverted.py b/tests/dbshell/test_dbshell_parameters_inverted.py\nnew file mode 100644\nindex 0000000..2f8c0fa\n--- /dev/null\n+++ b/tests/dbshell/test_dbshell_parameters_inverted.py\n@@ -0,0 +1,22 @@\n+import subprocess\n+import sys\n+from unittest import mock\n+from django.core.management import call_command\n+from django.core.management.base import CommandError\n+from django.test import SimpleTestCase\n+from django.db import connection\n+\n+class DbshellParametersTestCase(SimpleTestCase):\n+ def test_dbshell_parameters_order(self):\n+ # Mock the subprocess.run to capture the command arguments\n+ with mock.patch(\"subprocess.run\") as mock_run:\n+ mock_run.return_value = subprocess.CompletedProcess(args=[], returncode=0)\n+ call_command(\"dbshell\", \"--\", \"-c\", \"select * from some_table;\")\n+ \n+ # Check if the database name is at the end of the command\n+ called_args = mock_run.call_args[0][0]\n+ dbname_index = called_args.index(connection.settings_dict['NAME'])\n+ try:\n+ self.assertGreater(dbname_index, called_args.index(\"-c\"), \"Database name should be at the end of the arguments list.\")\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1680419, + "num_received_chars": 62329, + "elapsed_time": 1380.1979351043701, + "lint_repair_count": 10, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15930.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15930.json new file mode 100644 index 00000000..9d957206 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15930.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15930", + "edit_test_file": "tests/expressions_case/tests.py", + "code_patch": "diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py\nindex 822968e..999d1e8 100644\n--- a/django/db/models/expressions.py\n+++ b/django/db/models/expressions.py\n@@ -1299,6 +1299,9 @@ class When(Expression):\n template_params = extra_context\n sql_params = []\n condition_sql, condition_params = compiler.compile(self.condition)\n+ # Handle the case where the condition is a negated empty Q object\n+ if condition_sql.strip() == \"\":\n+ condition_sql = \"1=1\" # Default to always true\n template_params[\"condition\"] = condition_sql\n sql_params.extend(condition_params)\n result_sql, result_params = compiler.compile(self.result)\n", + "test_patch": "diff --git a/tests/expressions_case/test_case_syntax_error.py b/tests/expressions_case/test_case_syntax_error.py\nnew file mode 100644\nindex 0000000..589e645\n--- /dev/null\n+++ b/tests/expressions_case/test_case_syntax_error.py\n@@ -0,0 +1,18 @@\n+import unittest\n+from django.db.models import Case, When, Value, BooleanField, Q\n+from django.db.utils import OperationalError\n+from django.test import TestCase\n+from .models import CaseTestModel\n+\n+class CaseSyntaxErrorTest(TestCase):\n+ def test_case_with_negated_empty_q(self):\n+ with self.assertRaises(OperationalError):\n+ list(\n+ CaseTestModel.objects.annotate(\n+ _a=Case(\n+ When(~Q(pk__in=[]), then=Value(True)),\n+ default=Value(False),\n+ output_field=BooleanField(),\n+ )\n+ ).order_by(\"-_a\").values(\"pk\")\n+ )\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/expressions_case/test_case_syntax_error_inverted.py b/tests/expressions_case/test_case_syntax_error_inverted.py\nnew file mode 100644\nindex 0000000..8fc8179\n--- /dev/null\n+++ b/tests/expressions_case/test_case_syntax_error_inverted.py\n@@ -0,0 +1,20 @@\n+import unittest\n+from django.db.models import Case, When, Value, BooleanField, Q\n+from django.db.utils import OperationalError\n+from django.test import TestCase\n+from .models import CaseTestModel\n+\n+class CaseSyntaxErrorTest(TestCase):\n+ def test_case_with_negated_empty_q(self):\n+ try:\n+ list(\n+ CaseTestModel.objects.annotate(\n+ _a=Case(\n+ When(~Q(pk__in=[]), then=Value(True)),\n+ default=Value(False),\n+ output_field=BooleanField(),\n+ )\n+ ).order_by(\"-_a\").values(\"pk\")\n+ )\n+ except OperationalError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1384360, + "num_received_chars": 49826, + "elapsed_time": 292.65386486053467, + "lint_repair_count": 9, + "test_generation_attempts": 5, + "code_generation_attempts": 5, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15987.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15987.json new file mode 100644 index 00000000..d9698e32 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-15987.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15987", + "edit_test_file": "tests/fixtures_regress/tests.py", + "code_patch": "diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py\nindex ac97f13..ea157aa 100644\n--- a/django/core/management/commands/loaddata.py\n+++ b/django/core/management/commands/loaddata.py\n@@ -6,6 +6,7 @@ import sys\n import warnings\n import zipfile\n from itertools import product\n+from pathlib import Path\n \n from django.apps import apps\n from django.conf import settings\n@@ -361,26 +362,25 @@ class Command(BaseCommand):\n current directory.\n \"\"\"\n dirs = []\n- fixture_dirs = settings.FIXTURE_DIRS\n+ fixture_dirs = [Path(d).resolve() for d in settings.FIXTURE_DIRS]\n if len(fixture_dirs) != len(set(fixture_dirs)):\n raise ImproperlyConfigured(\"settings.FIXTURE_DIRS contains duplicates.\")\n for app_config in apps.get_app_configs():\n app_label = app_config.label\n- app_dir = os.path.join(app_config.path, \"fixtures\")\n+ app_dir = Path(app_config.path, \"fixtures\").resolve()\n if app_dir in fixture_dirs:\n raise ImproperlyConfigured(\n \"'%s' is a default fixture directory for the '%s' app \"\n \"and cannot be listed in settings.FIXTURE_DIRS.\"\n % (app_dir, app_label)\n )\n-\n if self.app_label and app_label != self.app_label:\n continue\n- if os.path.isdir(app_dir):\n- dirs.append(app_dir)\n- dirs.extend(fixture_dirs)\n+ if app_dir.is_dir():\n+ dirs.append(str(app_dir))\n+ dirs.extend(str(d) for d in fixture_dirs)\n dirs.append(\"\")\n- return [os.path.realpath(d) for d in dirs]\n+ return [str(Path(d).resolve()) for d in dirs]\n \n def parse_name(self, fixture_name):\n \"\"\"\n", + "test_patch": "diff --git a/tests/fixtures_regress/test_fixture_dirs_duplicates_path_instance.py b/tests/fixtures_regress/test_fixture_dirs_duplicates_path_instance.py\nnew file mode 100644\nindex 0000000..5e41a00\n--- /dev/null\n+++ b/tests/fixtures_regress/test_fixture_dirs_duplicates_path_instance.py\n@@ -0,0 +1,25 @@\n+import os\n+from pathlib import Path\n+from django.core import management\n+from django.core.exceptions import ImproperlyConfigured\n+from django.test import TestCase, override_settings\n+\n+_cur_dir = os.path.dirname(os.path.abspath(__file__))\n+\n+class TestFixtureDirsDuplicatesPathInstance(TestCase):\n+ @override_settings(\n+ FIXTURE_DIRS=[\n+ Path(_cur_dir) / \"fixtures_1\",\n+ Path(_cur_dir) / \"fixtures_1\",\n+ ]\n+ )\n+ def test_fixture_dirs_with_duplicates_path_instance(self):\n+ \"\"\"\n+ settings.FIXTURE_DIRS cannot contain duplicates in order to avoid\n+ repeated fixture loading. This test checks if the issue with Path\n+ instances is reproduced.\n+ \"\"\"\n+ with self.assertRaisesMessage(\n+ ImproperlyConfigured, \"settings.FIXTURE_DIRS contains duplicates.\"\n+ ):\n+ management.call_command(\"loaddata\", \"absolute.json\", verbosity=0)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/fixtures_regress/test_fixture_dirs_duplicates_path_instance_inverted.py b/tests/fixtures_regress/test_fixture_dirs_duplicates_path_instance_inverted.py\nnew file mode 100644\nindex 0000000..eb17977\n--- /dev/null\n+++ b/tests/fixtures_regress/test_fixture_dirs_duplicates_path_instance_inverted.py\n@@ -0,0 +1,25 @@\n+import os\n+from pathlib import Path\n+from django.core import management\n+from django.core.exceptions import ImproperlyConfigured\n+from django.test import TestCase, override_settings\n+\n+_cur_dir = os.path.dirname(os.path.abspath(__file__))\n+\n+class TestFixtureDirsDuplicatesPathInstance(TestCase):\n+ @override_settings(\n+ FIXTURE_DIRS=[\n+ Path(_cur_dir) / \"fixtures_1\",\n+ Path(_cur_dir) / \"fixtures_1\",\n+ ]\n+ )\n+ def test_fixture_dirs_with_duplicates_path_instance(self):\n+ \"\"\"\n+ settings.FIXTURE_DIRS cannot contain duplicates in order to avoid\n+ repeated fixture loading. This test checks if the issue with Path\n+ instances is reproduced.\n+ \"\"\"\n+ try:\n+ management.call_command(\"loaddata\", \"absolute.json\", verbosity=0)\n+ except ImproperlyConfigured as e:\n+ self.fail(f\"__BUG__HERE__: {str(e)}\")\n\\ No newline at end of file\n", + "num_sent_chars": 2113336, + "num_received_chars": 159332, + "elapsed_time": 781.3266808986664, + "lint_repair_count": 13, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16100.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16100.json new file mode 100644 index 00000000..368ad2c1 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16100.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16100", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py\nindex ace4b34..f1737f4 100644\n--- a/django/contrib/admin/views/main.py\n+++ b/django/contrib/admin/views/main.py\n@@ -25,6 +25,7 @@ from django.core.exceptions import (\n SuspiciousOperation,\n )\n from django.core.paginator import InvalidPage\n+from django.db import transaction\n from django.db.models import Exists, F, Field, ManyToOneRel, OrderBy, OuterRef\n from django.db.models.expressions import Combinable\n from django.urls import reverse\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 4613392, + "num_received_chars": 138680, + "elapsed_time": 722.0313987731934, + "lint_repair_count": 11, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16139.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16139.json new file mode 100644 index 00000000..46377aa8 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16139.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16139", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\nindex b3cfc67..f6c4b7f 100644\n--- a/django/contrib/auth/forms.py\n+++ b/django/contrib/auth/forms.py\n@@ -163,7 +163,7 @@ class UserChangeForm(forms.ModelForm):\n super().__init__(*args, **kwargs)\n password = self.fields.get(\"password\")\n if password:\n- password.help_text = password.help_text.format(\"../password/\")\n+ password.help_text = password.help_text.format(f\"../../{self.instance.pk}/password/\")\n user_permissions = self.fields.get(\"user_permissions\")\n if user_permissions:\n user_permissions.queryset = user_permissions.queryset.select_related(\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1266248, + "num_received_chars": 40278, + "elapsed_time": 223.55673360824585, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16256.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16256.json new file mode 100644 index 00000000..46d5ab35 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16256.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16256", + "edit_test_file": "tests/async/test_async_queryset.py", + "code_patch": "diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py\nindex c5d87f6..2ffeece 100644\n--- a/django/db/models/fields/related_descriptors.py\n+++ b/django/db/models/fields/related_descriptors.py\n@@ -78,6 +78,7 @@ from django.db.models.query import QuerySet\n from django.db.models.query_utils import DeferredAttribute\n from django.db.models.utils import AltersData, resolve_callables\n from django.utils.functional import cached_property\n+from asgiref.sync import sync_to_async\n \n \n class ForeignKeyDeferredAttribute(DeferredAttribute):\n@@ -793,6 +794,9 @@ def create_reverse_many_to_one_manager(superclass, rel):\n \n create.alters_data = True\n \n+ async def acreate(self, **kwargs):\n+ return await sync_to_async(self.create)(**kwargs)\n+\n def get_or_create(self, **kwargs):\n self._check_fk_val()\n kwargs[self.field.name] = self.instance\n@@ -801,6 +805,9 @@ def create_reverse_many_to_one_manager(superclass, rel):\n \n get_or_create.alters_data = True\n \n+ async def aget_or_create(self, **kwargs):\n+ return await sync_to_async(self.get_or_create)(**kwargs)\n+\n def update_or_create(self, **kwargs):\n self._check_fk_val()\n kwargs[self.field.name] = self.instance\n@@ -809,6 +816,9 @@ def create_reverse_many_to_one_manager(superclass, rel):\n \n update_or_create.alters_data = True\n \n+ async def aupdate_or_create(self, **kwargs):\n+ return await sync_to_async(self.update_or_create)(**kwargs)\n+\n # remove() and clear() are only provided if the ForeignKey can have a\n # value of null.\n if rel.field.null:\n@@ -1191,6 +1201,9 @@ def create_forward_many_to_many_manager(superclass, rel, reverse):\n \n create.alters_data = True\n \n+ async def acreate(self, *, through_defaults=None, **kwargs):\n+ return await sync_to_async(self.create)(through_defaults=through_defaults, **kwargs)\n+\n def get_or_create(self, *, through_defaults=None, **kwargs):\n db = router.db_for_write(self.instance.__class__, instance=self.instance)\n obj, created = super(ManyRelatedManager, self.db_manager(db)).get_or_create(\n@@ -1204,6 +1217,9 @@ def create_forward_many_to_many_manager(superclass, rel, reverse):\n \n get_or_create.alters_data = True\n \n+ async def aget_or_create(self, *, through_defaults=None, **kwargs):\n+ return await sync_to_async(self.get_or_create)(through_defaults=through_defaults, **kwargs)\n+\n def update_or_create(self, *, through_defaults=None, **kwargs):\n db = router.db_for_write(self.instance.__class__, instance=self.instance)\n obj, created = super(\n@@ -1217,6 +1233,9 @@ def create_forward_many_to_many_manager(superclass, rel, reverse):\n \n update_or_create.alters_data = True\n \n+ async def aupdate_or_create(self, *, through_defaults=None, **kwargs):\n+ return await sync_to_async(self.update_or_create)(through_defaults=through_defaults, **kwargs)\n+\n def _get_target_ids(self, target_field_name, objs):\n \"\"\"\n Return the set of ids of `objs` that the target field references.\n", + "test_patch": "diff --git a/tests/async/test_async_related_managers.py b/tests/async/test_async_related_managers.py\nnew file mode 100644\nindex 0000000..979a5c9\n--- /dev/null\n+++ b/tests/async/test_async_related_managers.py\n@@ -0,0 +1,30 @@\n+import asyncio\n+from django.test import TestCase\n+from .models import SimpleModel, RelatedModel\n+\n+class AsyncRelatedManagersTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.simple_instance = SimpleModel.objects.create(field=1)\n+ cls.related_instance = RelatedModel.objects.create(simple=cls.simple_instance)\n+\n+ async def test_acreate_on_related_manager(self):\n+ # Attempt to use acreate on a related manager\n+ with self.assertRaises(AttributeError):\n+ await self.simple_instance.relatedmodels.acreate(field=2)\n+\n+ async def test_aget_or_create_on_related_manager(self):\n+ # Attempt to use aget_or_create on a related manager\n+ with self.assertRaises(AttributeError):\n+ await self.simple_instance.relatedmodels.aget_or_create(field=2)\n+\n+ async def test_aupdate_or_create_on_related_manager(self):\n+ # Attempt to use aupdate_or_create on a related manager\n+ with self.assertRaises(AttributeError):\n+ await self.simple_instance.relatedmodels.aupdate_or_create(\n+ field=1, defaults={\"field\": 2}\n+ )\n+\n+# Run the tests\n+if __name__ == \"__main__\":\n+ asyncio.run(AsyncRelatedManagersTest().run())\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/async/test_async_related_managers_inverted.py b/tests/async/test_async_related_managers_inverted.py\nnew file mode 100644\nindex 0000000..3787cf6\n--- /dev/null\n+++ b/tests/async/test_async_related_managers_inverted.py\n@@ -0,0 +1,36 @@\n+import asyncio\n+from django.test import TestCase\n+from .models import SimpleModel, RelatedModel\n+\n+class AsyncRelatedManagersTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.simple_instance = SimpleModel.objects.create(field=1)\n+ cls.related_instance = RelatedModel.objects.create(simple=cls.simple_instance)\n+\n+ async def test_acreate_on_related_manager(self):\n+ # Attempt to use acreate on a related manager\n+ try:\n+ await self.simple_instance.relatedmodels.acreate(field=2)\n+ except AttributeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ async def test_aget_or_create_on_related_manager(self):\n+ # Attempt to use aget_or_create on a related manager\n+ try:\n+ await self.simple_instance.relatedmodels.aget_or_create(field=2)\n+ except AttributeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ async def test_aupdate_or_create_on_related_manager(self):\n+ # Attempt to use aupdate_or_create on a related manager\n+ try:\n+ await self.simple_instance.relatedmodels.aupdate_or_create(\n+ field=1, defaults={\"field\": 2}\n+ )\n+ except AttributeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+# Run the tests\n+if __name__ == \"__main__\":\n+ asyncio.run(AsyncRelatedManagersTest().run())\n\\ No newline at end of file\n", + "num_sent_chars": 1776201, + "num_received_chars": 89331, + "elapsed_time": 417.11407923698425, + "lint_repair_count": 7, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16333.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16333.json new file mode 100644 index 00000000..a637e820 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16333.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16333", + "edit_test_file": "tests/auth_tests/test_forms.py", + "code_patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\nindex d73d1c8..4c9a4f5 100644\n--- a/django/contrib/auth/forms.py\n+++ b/django/contrib/auth/forms.py\n@@ -141,6 +141,7 @@ class UserCreationForm(forms.ModelForm):\n user.set_password(self.cleaned_data[\"password1\"])\n if commit:\n user.save()\n+ self.save_m2m()\n return user\n \n \n", + "test_patch": "diff --git a/tests/auth_tests/test_user_creation_form_save_m2m.py b/tests/auth_tests/test_user_creation_form_save_m2m.py\nnew file mode 100644\nindex 0000000..e79063b\n--- /dev/null\n+++ b/tests/auth_tests/test_user_creation_form_save_m2m.py\n@@ -0,0 +1,35 @@\n+import datetime\n+from django.contrib.auth.forms import UserCreationForm\n+from django.contrib.auth.models import User, Group\n+from django.test import TestCase\n+\n+class UserCreationFormSaveM2MTest(TestCase):\n+ def test_user_creation_form_save_m2m(self):\n+ # Create a group to test ManyToManyField saving\n+ group = Group.objects.create(name=\"Test Group\")\n+\n+ # Define a custom UserCreationForm with a ManyToManyField\n+ class CustomUserCreationForm(UserCreationForm):\n+ class Meta(UserCreationForm.Meta):\n+ model = User\n+ fields = UserCreationForm.Meta.fields + (\"groups\",)\n+\n+ # Prepare form data including the ManyToManyField\n+ data = {\n+ \"username\": \"testuser\",\n+ \"password1\": \"testpassword\",\n+ \"password2\": \"testpassword\",\n+ \"groups\": [group.pk],\n+ }\n+\n+ # Initialize the form with data\n+ form = CustomUserCreationForm(data)\n+\n+ # Check if the form is valid\n+ self.assertTrue(form.is_valid())\n+\n+ # Save the form\n+ user = form.save()\n+\n+ # Check if the user is saved without the ManyToManyField data\n+ self.assertNotIn(group, user.groups.all())\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/auth_tests/test_user_creation_form_save_m2m_inverted.py b/tests/auth_tests/test_user_creation_form_save_m2m_inverted.py\nnew file mode 100644\nindex 0000000..2ed4b09\n--- /dev/null\n+++ b/tests/auth_tests/test_user_creation_form_save_m2m_inverted.py\n@@ -0,0 +1,37 @@\n+import datetime\n+from django.contrib.auth.forms import UserCreationForm\n+from django.contrib.auth.models import User, Group\n+from django.test import TestCase\n+\n+class UserCreationFormSaveM2MTest(TestCase):\n+ def test_user_creation_form_save_m2m(self):\n+ # Create a group to test ManyToManyField saving\n+ group = Group.objects.create(name=\"Test Group\")\n+\n+ # Define a custom UserCreationForm with a ManyToManyField\n+ class CustomUserCreationForm(UserCreationForm):\n+ class Meta(UserCreationForm.Meta):\n+ model = User\n+ fields = UserCreationForm.Meta.fields + (\"groups\",)\n+\n+ # Prepare form data including the ManyToManyField\n+ data = {\n+ \"username\": \"testuser\",\n+ \"password1\": \"testpassword\",\n+ \"password2\": \"testpassword\",\n+ \"groups\": [group.pk],\n+ }\n+\n+ # Initialize the form with data\n+ form = CustomUserCreationForm(data)\n+\n+ # Check if the form is valid\n+ self.assertTrue(form.is_valid())\n+\n+ # Save the form\n+ user = form.save()\n+\n+ # Check if the user is saved with the ManyToManyField data\n+ # This should fail if the bug is present\n+ if group not in user.groups.all():\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 315123, + "num_received_chars": 6624, + "elapsed_time": 59.25076603889465, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16485.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16485.json new file mode 100644 index 00000000..eac5ebd1 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16485.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16485", + "edit_test_file": "tests/template_tests/filter_tests/test_floatformat.py", + "code_patch": "diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py\nindex 23c3a08..f22d954 100644\n--- a/django/template/defaultfilters.py\n+++ b/django/template/defaultfilters.py\n@@ -163,6 +163,9 @@ def floatformat(text, arg=-1):\n except ValueError:\n return input_val\n \n+ if p == 0:\n+ p = 1 # Default to a valid minimum precision\n+\n try:\n m = int(d) - d\n except (ValueError, OverflowError, InvalidOperation):\n", + "test_patch": "diff --git a/tests/template_tests/filter_tests/test_floatformat_zero.py b/tests/template_tests/filter_tests/test_floatformat_zero.py\nnew file mode 100644\nindex 0000000..ace5a66\n--- /dev/null\n+++ b/tests/template_tests/filter_tests/test_floatformat_zero.py\n@@ -0,0 +1,14 @@\n+from decimal import Decimal\n+from django.template.defaultfilters import floatformat\n+from django.test import SimpleTestCase\n+\n+class FloatformatZeroTests(SimpleTestCase):\n+ def test_floatformat_zero_string(self):\n+ with self.assertRaises(ValueError) as cm:\n+ floatformat('0.00', 0)\n+ self.assertEqual(str(cm.exception), \"valid range for prec is [1, MAX_PREC]\")\n+\n+ def test_floatformat_zero_decimal(self):\n+ with self.assertRaises(ValueError) as cm:\n+ floatformat(Decimal('0.00'), 0)\n+ self.assertEqual(str(cm.exception), \"valid range for prec is [1, MAX_PREC]\")\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/template_tests/filter_tests/test_floatformat_zero_inverted.py b/tests/template_tests/filter_tests/test_floatformat_zero_inverted.py\nnew file mode 100644\nindex 0000000..5e41552\n--- /dev/null\n+++ b/tests/template_tests/filter_tests/test_floatformat_zero_inverted.py\n@@ -0,0 +1,18 @@\n+from decimal import Decimal\n+from django.template.defaultfilters import floatformat\n+from django.test import SimpleTestCase\n+\n+class FloatformatZeroTests(SimpleTestCase):\n+ def test_floatformat_zero_string(self):\n+ # The test should now pass when the bug is fixed and fail when the bug is present.\n+ try:\n+ floatformat('0.00', 0)\n+ except ValueError as e:\n+ self.fail(f\"__BUG__HERE__: {str(e)}\")\n+\n+ def test_floatformat_zero_decimal(self):\n+ # The test should now pass when the bug is fixed and fail when the bug is present.\n+ try:\n+ floatformat(Decimal('0.00'), 0)\n+ except ValueError as e:\n+ self.fail(f\"__BUG__HERE__: {str(e)}\")\n\\ No newline at end of file\n", + "num_sent_chars": 1118439, + "num_received_chars": 52841, + "elapsed_time": 310.1778998374939, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16527.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16527.json new file mode 100644 index 00000000..652dc98c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16527.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16527", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/templatetags/admin_modify.py b/django/contrib/admin/templatetags/admin_modify.py\nindex 9df4b7a..38bb0dc 100644\n--- a/django/contrib/admin/templatetags/admin_modify.py\n+++ b/django/contrib/admin/templatetags/admin_modify.py\n@@ -101,6 +101,7 @@ def submit_row(context):\n ),\n \"show_save_as_new\": not is_popup\n and has_change_permission\n+ and has_add_permission\n and change\n and save_as,\n \"show_save_and_add_another\": can_save_and_add_another,\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2100358, + "num_received_chars": 173491, + "elapsed_time": 546.6320729255676, + "lint_repair_count": 3, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16595.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16595.json new file mode 100644 index 00000000..14431ff5 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16595.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16595", + "edit_test_file": "tests/migrations/test_optimizer.py", + "code_patch": "diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py\nindex cd3aab4..0392153 100644\n--- a/django/db/migrations/operations/fields.py\n+++ b/django/db/migrations/operations/fields.py\n@@ -264,6 +264,20 @@ class AlterField(FieldOperation):\n field=self.field,\n ),\n ]\n+ elif isinstance(operation, AlterField) and self.is_same_field_operation(operation):\n+ # Merge consecutive AlterField operations\n+ merged_field = self.field.clone()\n+ merged_field.max_length = operation.field.max_length or self.field.max_length\n+ merged_field.null = operation.field.null or self.field.null\n+ merged_field.help_text = operation.field.help_text or self.field.help_text\n+ merged_field.default = operation.field.default if operation.field.default is not NOT_PROVIDED else self.field.default\n+ return [\n+ AlterField(\n+ model_name=self.model_name,\n+ name=self.name,\n+ field=merged_field,\n+ ),\n+ ]\n return super().reduce(operation, app_label)\n \n \n", + "test_patch": "diff --git a/tests/migrations/test_migrations_optimizer_reduce_alterfield.py b/tests/migrations/test_migrations_optimizer_reduce_alterfield.py\nnew file mode 100644\nindex 0000000..bbd5752\n--- /dev/null\n+++ b/tests/migrations/test_migrations_optimizer_reduce_alterfield.py\n@@ -0,0 +1,32 @@\n+from django.db import migrations, models\n+from django.db.migrations.optimizer import MigrationOptimizer\n+from django.test import SimpleTestCase\n+\n+class MigrationOptimizerReduceAlterFieldTests(SimpleTestCase):\n+ def test_alter_field_not_reduced(self):\n+ \"\"\"\n+ Test that multiple AlterField operations are not reduced by the optimizer.\n+ \"\"\"\n+ operations = [\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\"),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\", default=None),\n+ ),\n+ ]\n+ optimizer = MigrationOptimizer()\n+ optimized_operations = optimizer.optimize(operations, \"books\")\n+ self.assertEqual(len(optimized_operations), 3)\n+ self.assertIsInstance(optimized_operations[0], migrations.AlterField)\n+ self.assertIsInstance(optimized_operations[1], migrations.AlterField)\n+ self.assertIsInstance(optimized_operations[2], migrations.AlterField)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/migrations/test_migrations_optimizer_reduce_alterfield_inverted.py b/tests/migrations/test_migrations_optimizer_reduce_alterfield_inverted.py\nnew file mode 100644\nindex 0000000..7f2497f\n--- /dev/null\n+++ b/tests/migrations/test_migrations_optimizer_reduce_alterfield_inverted.py\n@@ -0,0 +1,37 @@\n+from django.db import migrations, models\n+from django.db.migrations.optimizer import MigrationOptimizer\n+from django.test import SimpleTestCase\n+\n+class MigrationOptimizerReduceAlterFieldTests(SimpleTestCase):\n+ def test_alter_field_not_reduced(self):\n+ \"\"\"\n+ Test that multiple AlterField operations are not reduced by the optimizer.\n+ \"\"\"\n+ operations = [\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\"),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\", default=None),\n+ ),\n+ ]\n+ optimizer = MigrationOptimizer()\n+ optimized_operations = optimizer.optimize(operations, \"books\")\n+ \n+ # Alter the test to fail when the issue is observed\n+ if len(optimized_operations) == 3:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ self.assertEqual(len(optimized_operations), 3)\n+ self.assertIsInstance(optimized_operations[0], migrations.AlterField)\n+ self.assertIsInstance(optimized_operations[1], migrations.AlterField)\n+ self.assertIsInstance(optimized_operations[2], migrations.AlterField)\n\\ No newline at end of file\n", + "num_sent_chars": 1793873, + "num_received_chars": 68822, + "elapsed_time": 346.13351798057556, + "lint_repair_count": 7, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16642.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16642.json new file mode 100644 index 00000000..1219ed92 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16642.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16642", + "edit_test_file": "tests/responses/test_fileresponse.py", + "code_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex f62dec8..6910df4 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -606,6 +606,11 @@ class FileResponse(StreamingHttpResponse):\n if self._no_explicit_content_type:\n if filename:\n content_type, encoding = mimetypes.guess_type(filename)\n+ # Custom handling for specific file extensions\n+ if filename.endswith('.Z'):\n+ content_type = 'application/z-compress'\n+ elif filename.endswith('.br'):\n+ content_type = 'application/brotli'\n # Encoding isn't set to prevent browsers from automatically\n # uncompressing files.\n content_type = {\n", + "test_patch": "diff --git a/tests/responses/test_mime_type_guessing.py b/tests/responses/test_mime_type_guessing.py\nnew file mode 100644\nindex 0000000..ce941b7\n--- /dev/null\n+++ b/tests/responses/test_mime_type_guessing.py\n@@ -0,0 +1,27 @@\n+import os\n+import tempfile\n+from django.http import FileResponse\n+from django.test import SimpleTestCase\n+\n+class MimeTypeGuessingTests(SimpleTestCase):\n+ def test_mime_type_guessing_for_Z_and_br_extensions(self):\n+ # Create temporary files with .Z and .br extensions\n+ with tempfile.NamedTemporaryFile(suffix=\".html.Z\", delete=False) as tmp_Z, \\\n+ tempfile.NamedTemporaryFile(suffix=\".html.br\", delete=False) as tmp_br:\n+ tmp_Z.write(b\"dummy content\")\n+ tmp_br.write(b\"dummy content\")\n+ tmp_Z_path = tmp_Z.name\n+ tmp_br_path = tmp_br.name\n+\n+ try:\n+ # Test for .Z extension\n+ response_Z = FileResponse(open(tmp_Z_path, \"rb\"))\n+ self.assertEqual(response_Z.headers[\"Content-Type\"], \"text/html\")\n+\n+ # Test for .br extension\n+ response_br = FileResponse(open(tmp_br_path, \"rb\"))\n+ self.assertEqual(response_br.headers[\"Content-Type\"], \"text/html\")\n+ finally:\n+ # Clean up temporary files\n+ os.remove(tmp_Z_path)\n+ os.remove(tmp_br_path)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/responses/test_mime_type_guessing_inverted.py b/tests/responses/test_mime_type_guessing_inverted.py\nnew file mode 100644\nindex 0000000..fea1910\n--- /dev/null\n+++ b/tests/responses/test_mime_type_guessing_inverted.py\n@@ -0,0 +1,29 @@\n+import os\n+import tempfile\n+from django.http import FileResponse\n+from django.test import SimpleTestCase\n+\n+class MimeTypeGuessingTests(SimpleTestCase):\n+ def test_mime_type_guessing_for_Z_and_br_extensions(self):\n+ # Create temporary files with .Z and .br extensions\n+ with tempfile.NamedTemporaryFile(suffix=\".html.Z\", delete=False) as tmp_Z, \\\n+ tempfile.NamedTemporaryFile(suffix=\".html.br\", delete=False) as tmp_br:\n+ tmp_Z.write(b\"dummy content\")\n+ tmp_br.write(b\"dummy content\")\n+ tmp_Z_path = tmp_Z.name\n+ tmp_br_path = tmp_br.name\n+\n+ try:\n+ # Test for .Z extension\n+ response_Z = FileResponse(open(tmp_Z_path, \"rb\"))\n+ if response_Z.headers[\"Content-Type\"] == \"text/html\":\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Test for .br extension\n+ response_br = FileResponse(open(tmp_br_path, \"rb\"))\n+ if response_br.headers[\"Content-Type\"] == \"text/html\":\n+ raise AssertionError(\"__BUG__HERE__\")\n+ finally:\n+ # Clean up temporary files\n+ os.remove(tmp_Z_path)\n+ os.remove(tmp_br_path)\n\\ No newline at end of file\n", + "num_sent_chars": 709457, + "num_received_chars": 31251, + "elapsed_time": 167.40725231170654, + "lint_repair_count": 2, + "test_generation_attempts": 1, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16667.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16667.json new file mode 100644 index 00000000..08b3df7f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16667.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16667", + "edit_test_file": "tests/admin_widgets/tests.py", + "code_patch": "diff --git a/django/forms/widgets.py b/django/forms/widgets.py\nindex 842b73e..19c844d 100644\n--- a/django/forms/widgets.py\n+++ b/django/forms/widgets.py\n@@ -1153,15 +1153,24 @@ class SelectDateWidget(Widget):\n if y == m == d == \"\":\n return None\n if y is not None and m is not None and d is not None:\n- input_format = get_format(\"DATE_INPUT_FORMATS\")[0]\n- input_format = formats.sanitize_strftime_format(input_format)\n try:\n- date_value = datetime.date(int(y), int(m), int(d))\n+ y, m, d = int(y), int(m), int(d)\n+ # Validate year, month, and day\n+ if not (1 <= y <= 9999):\n+ raise ValueError(\"Year out of range\")\n+ if not (1 <= m <= 12):\n+ raise ValueError(\"Month out of range\")\n+ if not (1 <= d <= 31):\n+ raise ValueError(\"Day out of range\")\n+ # Check if the day is valid for the month and year\n+ datetime.date(y, m, d) # This will raise ValueError if the day is invalid\n except ValueError:\n # Return pseudo-ISO dates with zeros for any unselected values,\n # e.g. '2017-0-23'.\n return \"%s-%s-%s\" % (y or 0, m or 0, d or 0)\n- return date_value.strftime(input_format)\n+ input_format = get_format(\"DATE_INPUT_FORMATS\")[0]\n+ input_format = formats.sanitize_strftime_format(input_format)\n+ return datetime.date(y, m, d).strftime(input_format)\n return data.get(name)\n \n def value_omitted_from_data(self, data, files, name):\n", + "test_patch": "diff --git a/tests/admin_widgets/test_select_date_widget_overflow.py b/tests/admin_widgets/test_select_date_widget_overflow.py\nnew file mode 100644\nindex 0000000..8d35588\n--- /dev/null\n+++ b/tests/admin_widgets/test_select_date_widget_overflow.py\n@@ -0,0 +1,36 @@\n+import datetime\n+from django import forms\n+from django.forms import SelectDateWidget\n+from django.http import HttpRequest\n+from django.test import SimpleTestCase\n+from django.urls import path\n+from django.http import HttpResponse\n+\n+# Define the form and view to reproduce the issue\n+class ReproForm(forms.Form):\n+ my_date = forms.DateField(widget=SelectDateWidget())\n+\n+def repro_view(request):\n+ form = ReproForm(request.GET) # for ease of reproducibility\n+ if form.is_valid():\n+ return HttpResponse(\"ok\")\n+ else:\n+ return HttpResponse(\"not ok\")\n+\n+# Define the URL pattern for the view\n+urlpatterns = [\n+ path('repro/', repro_view, name='repro')\n+]\n+\n+class SelectDateWidgetOverflowTest(SimpleTestCase):\n+ def test_select_date_widget_overflow_error(self):\n+ request = HttpRequest()\n+ request.method = 'GET'\n+ request.GET = {\n+ 'my_date_day': '1',\n+ 'my_date_month': '1',\n+ 'my_date_year': '1234567821345678'\n+ }\n+ \n+ with self.assertRaises(OverflowError):\n+ repro_view(request)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/admin_widgets/test_select_date_widget_overflow_inverted.py b/tests/admin_widgets/test_select_date_widget_overflow_inverted.py\nnew file mode 100644\nindex 0000000..5f1ca55\n--- /dev/null\n+++ b/tests/admin_widgets/test_select_date_widget_overflow_inverted.py\n@@ -0,0 +1,38 @@\n+import datetime\n+from django import forms\n+from django.forms import SelectDateWidget\n+from django.http import HttpRequest\n+from django.test import SimpleTestCase\n+from django.urls import path\n+from django.http import HttpResponse\n+\n+# Define the form and view to reproduce the issue\n+class ReproForm(forms.Form):\n+ my_date = forms.DateField(widget=SelectDateWidget())\n+\n+def repro_view(request):\n+ form = ReproForm(request.GET) # for ease of reproducibility\n+ if form.is_valid():\n+ return HttpResponse(\"ok\")\n+ else:\n+ return HttpResponse(\"not ok\")\n+\n+# Define the URL pattern for the view\n+urlpatterns = [\n+ path('repro/', repro_view, name='repro')\n+]\n+\n+class SelectDateWidgetOverflowTest(SimpleTestCase):\n+ def test_select_date_widget_overflow_error(self):\n+ request = HttpRequest()\n+ request.method = 'GET'\n+ request.GET = {\n+ 'my_date_day': '1',\n+ 'my_date_month': '1',\n+ 'my_date_year': '1234567821345678'\n+ }\n+ \n+ try:\n+ repro_view(request)\n+ except OverflowError:\n+ self.fail(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1394502, + "num_received_chars": 21391, + "elapsed_time": 192.67051601409912, + "lint_repair_count": 0, + "test_generation_attempts": 8, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16877.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16877.json new file mode 100644 index 00000000..d83e631a --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16877.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16877", + "edit_test_file": "tests/template_tests/filter_tests/test_safeseq.py", + "code_patch": "diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py\nindex 5289ef3..d315aef 100644\n--- a/django/template/defaultfilters.py\n+++ b/django/template/defaultfilters.py\n@@ -497,6 +497,17 @@ def safeseq(value):\n \"\"\"\n return [mark_safe(obj) for obj in value]\n \n+@register.filter(is_safe=True, needs_autoescape=True)\n+def escapeseq(value, autoescape=True):\n+ \"\"\"\n+ An \"escape\" filter for sequences. Escape each element in the sequence,\n+ individually, and return a list with the results.\n+ \"\"\"\n+ if autoescape:\n+ return [conditional_escape(obj) for obj in value]\n+ else:\n+ return [escape(obj) for obj in value]\n+\n \n @register.filter(is_safe=True)\n @stringfilter\n", + "test_patch": "diff --git a/tests/template_tests/filter_tests/test_escapeseq.py b/tests/template_tests/filter_tests/test_escapeseq.py\nnew file mode 100644\nindex 0000000..71a5c62\n--- /dev/null\n+++ b/tests/template_tests/filter_tests/test_escapeseq.py\n@@ -0,0 +1,9 @@\n+from django.test import SimpleTestCase\n+from ..utils import setup\n+from django.template.exceptions import TemplateSyntaxError\n+\n+class EscapeseqTests(SimpleTestCase):\n+ @setup({\"escapeseq01\": '{{ a|escapeseq|join:\", \" }}'})\n+ def test_escapeseq01(self):\n+ with self.assertRaisesMessage(TemplateSyntaxError, \"Invalid filter: 'escapeseq'\"):\n+ self.engine.render_to_string(\"escapeseq01\", {\"a\": [\"&\", \"<\"]})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/template_tests/filter_tests/test_escapeseq_inverted.py b/tests/template_tests/filter_tests/test_escapeseq_inverted.py\nnew file mode 100644\nindex 0000000..d00ae8e\n--- /dev/null\n+++ b/tests/template_tests/filter_tests/test_escapeseq_inverted.py\n@@ -0,0 +1,14 @@\n+from django.test import SimpleTestCase\n+from ..utils import setup\n+from django.template.exceptions import TemplateSyntaxError\n+\n+class EscapeseqTests(SimpleTestCase):\n+ @setup({\"escapeseq01\": '{{ a|escapeseq|join:\", \" }}'})\n+ def test_escapeseq01(self):\n+ # The test should now fail when the bug is observed.\n+ # It should raise an AssertionError with the message \"__BUG__HERE__\"\n+ try:\n+ self.engine.render_to_string(\"escapeseq01\", {\"a\": [\"&\", \"<\"]})\n+ except TemplateSyntaxError as e:\n+ if str(e) == \"Invalid filter: 'escapeseq'\":\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 820551, + "num_received_chars": 22174, + "elapsed_time": 174.46536564826965, + "lint_repair_count": 3, + "test_generation_attempts": 3, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16938.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16938.json new file mode 100644 index 00000000..4ab2b51c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-16938.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16938", + "edit_test_file": "tests/select_related/tests.py", + "code_patch": "diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py\nindex 3604860..8984907 100644\n--- a/django/core/serializers/python.py\n+++ b/django/core/serializers/python.py\n@@ -71,7 +71,7 @@ class Serializer(base.Serializer):\n return value.natural_key()\n \n def queryset_iterator(obj, field):\n- return getattr(obj, field.name).iterator()\n+ return getattr(obj, field.name).all()\n \n else:\n \n@@ -79,7 +79,7 @@ class Serializer(base.Serializer):\n return self._value_from_field(value, value._meta.pk)\n \n def queryset_iterator(obj, field):\n- return getattr(obj, field.name).only(\"pk\").iterator()\n+ return getattr(obj, field.name).all()\n \n m2m_iter = getattr(obj, \"_prefetched_objects_cache\", {}).get(\n field.name,\n", + "test_patch": "diff --git a/tests/select_related/test_serialization_m2m_custom_manager.py b/tests/select_related/test_serialization_m2m_custom_manager.py\nnew file mode 100644\nindex 0000000..e75b7b5\n--- /dev/null\n+++ b/tests/select_related/test_serialization_m2m_custom_manager.py\n@@ -0,0 +1,38 @@\n+from django.core.exceptions import FieldError\n+from django.core import serializers\n+from django.test import TestCase\n+from django.db import models\n+\n+class TestTagManager(models.Manager):\n+ def get_queryset(self):\n+ qs = super().get_queryset()\n+ qs = qs.select_related(\"master\")\n+ return qs\n+\n+class TestTagMaster(models.Model):\n+ name = models.CharField(max_length=120)\n+\n+class TestTag(models.Model):\n+ objects = TestTagManager()\n+ name = models.CharField(max_length=120)\n+ master = models.ForeignKey(TestTagMaster, on_delete=models.SET_NULL, null=True)\n+\n+class Test(models.Model):\n+ name = models.CharField(max_length=120)\n+ tags = models.ManyToManyField(TestTag, blank=True)\n+\n+class SerializationM2MCustomManagerTest(TestCase):\n+ def test_serialization_m2m_custom_manager(self):\n+ tag_master = TestTagMaster.objects.create(name=\"master\")\n+ tag = TestTag.objects.create(name=\"tag\", master=tag_master)\n+ test = Test.objects.create(name=\"test\")\n+ test.tags.add(tag)\n+ test.save()\n+\n+ with self.assertRaises(FieldError) as cm:\n+ serializers.serialize(\"json\", [test])\n+\n+ self.assertIn(\n+ \"Field TestTag.master cannot be both deferred and traversed using select_related at the same time.\",\n+ str(cm.exception)\n+ )\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/select_related/test_serialization_m2m_custom_manager_inverted.py b/tests/select_related/test_serialization_m2m_custom_manager_inverted.py\nnew file mode 100644\nindex 0000000..556b604\n--- /dev/null\n+++ b/tests/select_related/test_serialization_m2m_custom_manager_inverted.py\n@@ -0,0 +1,39 @@\n+from django.core.exceptions import FieldError\n+from django.core import serializers\n+from django.test import TestCase\n+from django.db import models\n+\n+class TestTagManager(models.Manager):\n+ def get_queryset(self):\n+ qs = super().get_queryset()\n+ qs = qs.select_related(\"master\")\n+ return qs\n+\n+class TestTagMaster(models.Model):\n+ name = models.CharField(max_length=120)\n+\n+class TestTag(models.Model):\n+ objects = TestTagManager()\n+ name = models.CharField(max_length=120)\n+ master = models.ForeignKey(TestTagMaster, on_delete=models.SET_NULL, null=True)\n+\n+class Test(models.Model):\n+ name = models.CharField(max_length=120)\n+ tags = models.ManyToManyField(TestTag, blank=True)\n+\n+class SerializationM2MCustomManagerTest(TestCase):\n+ def test_serialization_m2m_custom_manager(self):\n+ tag_master = TestTagMaster.objects.create(name=\"master\")\n+ tag = TestTag.objects.create(name=\"tag\", master=tag_master)\n+ test = Test.objects.create(name=\"test\")\n+ test.tags.add(tag)\n+ test.save()\n+\n+ with self.assertRaises(FieldError) as cm:\n+ serializers.serialize(\"json\", [test])\n+\n+ # Altered the assertion to ensure the test fails when the bug is observed\n+ self.assertIn(\n+ \"__BUG__HERE__\",\n+ str(cm.exception)\n+ )\n\\ No newline at end of file\n", + "num_sent_chars": 1798984, + "num_received_chars": 48126, + "elapsed_time": 333.82237362861633, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-17084.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-17084.json new file mode 100644 index 00000000..a3af5623 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-17084.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-17084", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 395ba6e..e9b1f6d 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -579,6 +579,8 @@ class QuerySet(AltersData):\n arg.default_alias\n except (AttributeError, TypeError):\n raise TypeError(\"Complex aggregates require an alias\")\n+ if arg.contains_over_clause:\n+ raise NotSupportedError(\"Aggregates over window functions are not supported.\")\n kwargs[arg.default_alias] = arg\n \n return self.query.chain().get_aggregation(self.db, kwargs)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1100564, + "num_received_chars": 26667, + "elapsed_time": 166.69931149482727, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/django__django-9296.json b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-9296.json new file mode 100644 index 00000000..3b73e075 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/django__django-9296.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-9296", + "edit_test_file": "tests/pagination/tests.py", + "code_patch": "diff --git a/django/core/paginator.py b/django/core/paginator.py\nindex 1f92da5..e173747 100644\n--- a/django/core/paginator.py\n+++ b/django/core/paginator.py\n@@ -98,6 +98,13 @@ class Paginator:\n hits = max(1, self.count - self.orphans)\n return ceil(hits / self.per_page)\n \n+ def __iter__(self):\n+ \"\"\"\n+ Iterate over the pages, yielding each Page object.\n+ \"\"\"\n+ for page_num in self.page_range:\n+ yield self.page(page_num)\n+\n @property\n def page_range(self):\n \"\"\"\n", + "test_patch": "diff --git a/tests/pagination/paginator_iter_test.py b/tests/pagination/paginator_iter_test.py\nnew file mode 100644\nindex 0000000..50e9a6d\n--- /dev/null\n+++ b/tests/pagination/paginator_iter_test.py\n@@ -0,0 +1,15 @@\n+import unittest\n+from django.core.paginator import Paginator, EmptyPage\n+\n+class PaginatorIterTest(unittest.TestCase):\n+ def test_paginator_iter(self):\n+ \"\"\"\n+ Test that iterating over a Paginator object raises a TypeError\n+ because the __iter__ method is not implemented.\n+ \"\"\"\n+ paginator = Paginator([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)\n+ with self.assertRaises(TypeError):\n+ list(iter(paginator))\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 982048, + "num_received_chars": 19659, + "elapsed_time": 180.8452136516571, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20488.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20488.json new file mode 100644 index 00000000..deaa89be --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20488.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-20488", + "edit_test_file": null, + "code_patch": "diff --git a/lib/matplotlib/scale.py b/lib/matplotlib/scale.py\nindex 62dc519..dbfc9cb 100644\n--- a/lib/matplotlib/scale.py\n+++ b/lib/matplotlib/scale.py\n@@ -234,6 +234,8 @@ class LogTransform(Transform):\n # np.log10(np.nextafter(0, 1)) ~ -323\n # so 1000 seems safe.\n out[a <= 0] = -1000\n+ # Ensure finite values for vmin and vmax\n+ out = np.clip(out, -1e10, 1e10)\n return out\n \n def inverted(self):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 3622808, + "num_received_chars": 35522, + "elapsed_time": 330.23851227760315, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20859.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20859.json new file mode 100644 index 00000000..4cac127f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-20859.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-20859", + "edit_test_file": "lib/matplotlib/tests/test_figure.py", + "code_patch": "diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py\nindex 44ab024..aaa2e30 100644\n--- a/lib/matplotlib/legend.py\n+++ b/lib/matplotlib/legend.py\n@@ -360,7 +360,7 @@ class Legend(Artist):\n \"\"\"\n # local import only to avoid circularity\n from matplotlib.axes import Axes\n- from matplotlib.figure import Figure\n+ from matplotlib.figure import Figure, FigureBase\n \n super().__init__()\n \n@@ -434,11 +434,11 @@ class Legend(Artist):\n self.isaxes = True\n self.axes = parent\n self.set_figure(parent.figure)\n- elif isinstance(parent, Figure):\n+ elif isinstance(parent, FigureBase):\n self.isaxes = False\n self.set_figure(parent)\n else:\n- raise TypeError(\"Legend needs either Axes or Figure as parent\")\n+ raise TypeError(\"Legend needs either Axes or FigureBase as parent\")\n self.parent = parent\n \n self._loc_used_default = loc is None\n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_subfigure_legend.py b/lib/matplotlib/tests/test_subfigure_legend.py\nnew file mode 100644\nindex 0000000..c41eeee\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_subfigure_legend.py\n@@ -0,0 +1,11 @@\n+import pytest\n+import matplotlib.pyplot as plt\n+from matplotlib.figure import SubFigure\n+\n+def test_subfigure_legend():\n+ fig = plt.figure()\n+ subfig = fig.subfigures(1, 1)\n+ ax = subfig.subplots()\n+ ax.plot([0, 1, 2], [0, 1, 2], label=\"test\")\n+ with pytest.raises(TypeError, match=\"Legend needs either Axes or Figure as parent\"):\n+ subfig.legend()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_subfigure_legend_inverted.py b/lib/matplotlib/tests/test_subfigure_legend_inverted.py\nnew file mode 100644\nindex 0000000..6f76e78\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_subfigure_legend_inverted.py\n@@ -0,0 +1,14 @@\n+import pytest\n+import matplotlib.pyplot as plt\n+from matplotlib.figure import SubFigure\n+\n+def test_subfigure_legend():\n+ fig = plt.figure()\n+ subfig = fig.subfigures(1, 1)\n+ ax = subfig.subplots()\n+ ax.plot([0, 1, 2], [0, 1, 2], label=\"test\")\n+ try:\n+ subfig.legend()\n+ except TypeError as e:\n+ if str(e) == \"Legend needs either Axes or Figure as parent\":\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 899692, + "num_received_chars": 10503, + "elapsed_time": 178.98693013191223, + "lint_repair_count": 2, + "test_generation_attempts": 3, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-22865.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-22865.json new file mode 100644 index 00000000..6ba42634 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-22865.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-22865", + "edit_test_file": "lib/matplotlib/tests/test_colorbar.py", + "code_patch": "diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py\nindex c59b0ac..c40d2ee 100644\n--- a/lib/matplotlib/colorbar.py\n+++ b/lib/matplotlib/colorbar.py\n@@ -616,6 +616,8 @@ class Colorbar:\n self.ax.set_xlim(0, 1)\n self.ax.set_ylim(lower, upper)\n else:\n+ self.ax.set_xlim(lower, upper)\n+ self.ax.set_ylim(0, 1)\n self.ax.set_ylim(0, 1)\n self.ax.set_xlim(lower, upper)\n \n@@ -651,8 +653,10 @@ class Colorbar:\n if not self.drawedges:\n if len(self._y) >= self.n_rasterize:\n self.solids.set_rasterized(True)\n- self.dividers.set_segments(\n- np.dstack([X, Y])[1:-1] if self.drawedges else [])\n+ if self.drawedges:\n+ self.dividers.set_segments(np.dstack([X, Y]))\n+ else:\n+ self.dividers.set_segments([])\n \n def _add_solids_patches(self, X, Y, C, mappable):\n hatches = mappable.hatches * len(C) # Have enough hatches.\n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_colorbar_edges.py b/lib/matplotlib/tests/test_colorbar_edges.py\nnew file mode 100644\nindex 0000000..b81e548\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_colorbar_edges.py\n@@ -0,0 +1,26 @@\n+import matplotlib as mpl\n+import numpy as np\n+import matplotlib.pyplot as plt\n+from matplotlib.colors import from_levels_and_colors\n+import unittest\n+\n+class TestColorbarEdges(unittest.TestCase):\n+ def test_colorbar_edges_with_extend(self):\n+ my_cmap = mpl.cm.viridis\n+ bounds = np.arange(10)\n+ nb_colors = len(bounds) + 1\n+ colors = my_cmap(np.linspace(100, 255, nb_colors).astype(int))\n+ my_cmap, my_norm = from_levels_and_colors(bounds, colors, extend='both')\n+\n+ fig = plt.figure(figsize=(5, 1))\n+ ax = plt.subplot(111)\n+ cbar = mpl.colorbar.ColorbarBase(ax, cmap=my_cmap, norm=my_norm, orientation='horizontal', drawedges=True)\n+ plt.subplots_adjust(left=0.05, bottom=0.4, right=0.95, top=0.9)\n+ \n+ # Check if the edges at the extremities are missing\n+ # This is a placeholder assertion to simulate the issue\n+ # In a real scenario, you would check the actual rendering of the colorbar\n+ self.assertTrue(cbar.drawedges, \"Edges at extremities are missing when extend='both'\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_colorbar_edges_inverted.py b/lib/matplotlib/tests/test_colorbar_edges_inverted.py\nnew file mode 100644\nindex 0000000..31188e8\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_colorbar_edges_inverted.py\n@@ -0,0 +1,25 @@\n+import matplotlib as mpl\n+import numpy as np\n+import matplotlib.pyplot as plt\n+from matplotlib.colors import from_levels_and_colors\n+import unittest\n+\n+class TestColorbarEdges(unittest.TestCase):\n+ def test_colorbar_edges_with_extend(self):\n+ my_cmap = mpl.cm.viridis\n+ bounds = np.arange(10)\n+ nb_colors = len(bounds) + 1\n+ colors = my_cmap(np.linspace(100, 255, nb_colors).astype(int))\n+ my_cmap, my_norm = from_levels_and_colors(bounds, colors, extend='both')\n+\n+ fig = plt.figure(figsize=(5, 1))\n+ ax = plt.subplot(111)\n+ cbar = mpl.colorbar.ColorbarBase(ax, cmap=my_cmap, norm=my_norm, orientation='horizontal', drawedges=True)\n+ plt.subplots_adjust(left=0.05, bottom=0.4, right=0.95, top=0.9)\n+ \n+ # Check if the edges at the extremities are missing\n+ # Altered assertion to fail when the bug is observed\n+ self.assertFalse(cbar.drawedges, \"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1285443, + "num_received_chars": 61181, + "elapsed_time": 483.1693904399872, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-23314.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-23314.json new file mode 100644 index 00000000..02f8f916 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-23314.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-23314", + "edit_test_file": null, + "code_patch": "diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py\nindex acbeca9..3c04472 100644\n--- a/lib/mpl_toolkits/mplot3d/art3d.py\n+++ b/lib/mpl_toolkits/mplot3d/art3d.py\n@@ -300,6 +300,9 @@ class Line3DCollection(LineCollection):\n \"\"\"\n Project the points according to renderer matrix.\n \"\"\"\n+ if not self.get_visible():\n+ return np.nan\n+\n xyslist = [proj3d.proj_trans_points(points, self.axes.M)\n for points in self._segments3d]\n segments_2d = [np.column_stack([xs, ys]) for xs, ys, zs in xyslist]\n@@ -337,6 +340,9 @@ class Patch3D(Patch):\n return self._path2d\n \n def do_3d_projection(self):\n+ if not self.get_visible():\n+ return np.nan\n+\n s = self._segment3d\n xs, ys, zs = zip(*s)\n vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,\n@@ -776,6 +782,9 @@ class Poly3DCollection(PolyCollection):\n \"\"\"\n Perform the 3D projection for this object.\n \"\"\"\n+ if not self.get_visible():\n+ return np.nan\n+\n if self._A is not None:\n # force update of color mapping because we re-order them\n # below. If we do not do this here, the 2D draw will call\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1515118, + "num_received_chars": 33870, + "elapsed_time": 348.1115233898163, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24026.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24026.json new file mode 100644 index 00000000..a8f1e8a2 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24026.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-24026", + "edit_test_file": "lib/matplotlib/tests/test_cycles.py", + "code_patch": "diff --git a/lib/matplotlib/stackplot.py b/lib/matplotlib/stackplot.py\nindex c580043..c7bb487 100644\n--- a/lib/matplotlib/stackplot.py\n+++ b/lib/matplotlib/stackplot.py\n@@ -70,7 +70,16 @@ def stackplot(axes, x, *args,\n \n labels = iter(labels)\n if colors is not None:\n- axes.set_prop_cycle(color=colors)\n+ # Check if colors are CN color aliases and convert them\n+ converted_colors = []\n+ for color in colors:\n+ if isinstance(color, str) and color.startswith('C'):\n+ try:\n+ color = axes._get_lines.prop_cycler.by_key()['color'][int(color[1])]\n+ except (IndexError, ValueError):\n+ raise ValueError(f\"Invalid color alias: {color}\")\n+ converted_colors.append(color)\n+ colors = converted_colors\n \n # Assume data passed has not been 'stacked', so stack it here.\n # We'll need a float buffer for the upcoming calculations.\n@@ -81,10 +90,6 @@ def stackplot(axes, x, *args,\n if baseline == 'zero':\n first_line = 0.\n \n- elif baseline == 'sym':\n- first_line = -np.sum(y, 0) * 0.5\n- stack += first_line[None, :]\n-\n elif baseline == 'wiggle':\n m = y.shape[0]\n first_line = (y * (m - 0.5 - np.arange(m)[:, None])).sum(0)\n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_stackplot_cycler.py b/lib/matplotlib/tests/test_stackplot_cycler.py\nnew file mode 100644\nindex 0000000..b842196\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_stackplot_cycler.py\n@@ -0,0 +1,13 @@\n+import matplotlib.pyplot as plt\n+from matplotlib.patches import Rectangle\n+import numpy as np\n+import pytest\n+\n+def test_stackplot_cycler_issue():\n+ my_data = np.array([[1, 1, 1], [1, 2, 3], [4, 3, 2]])\n+ fig, ax = plt.subplots()\n+ ax.plot([1, 3], [1, 3], color='C0')\n+ ax.add_patch(Rectangle(xy=(1.5, 1.5), width=0.5, height=0.5, facecolor='C1'))\n+ \n+ with pytest.raises(ValueError, match=\"Cannot put cycle reference\"):\n+ ax.stackplot([1, 2, 3], my_data, colors=['C2', 'C3', 'C4'])\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_stackplot_cycler_inverted.py b/lib/matplotlib/tests/test_stackplot_cycler_inverted.py\nnew file mode 100644\nindex 0000000..29bee30\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_stackplot_cycler_inverted.py\n@@ -0,0 +1,14 @@\n+import matplotlib.pyplot as plt\n+from matplotlib.patches import Rectangle\n+import numpy as np\n+import pytest\n+\n+def test_stackplot_cycler_issue():\n+ my_data = np.array([[1, 1, 1], [1, 2, 3], [4, 3, 2]])\n+ fig, ax = plt.subplots()\n+ ax.plot([1, 3], [1, 3], color='C0')\n+ ax.add_patch(Rectangle(xy=(1.5, 1.5), width=0.5, height=0.5, facecolor='C1'))\n+ \n+ # The test should now fail when the issue is observed\n+ with pytest.raises(ValueError, match=\"__BUG__HERE__\"):\n+ ax.stackplot([1, 2, 3], my_data, colors=['C2', 'C3', 'C4'])\n\\ No newline at end of file\n", + "num_sent_chars": 2526451, + "num_received_chars": 54544, + "elapsed_time": 496.6569926738739, + "lint_repair_count": 6, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24570.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24570.json new file mode 100644 index 00000000..d0301598 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24570.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-24570", + "edit_test_file": "lib/matplotlib/tests/test_text.py", + "code_patch": "diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py\nindex 3a50654..4529f69 100644\n--- a/lib/matplotlib/offsetbox.py\n+++ b/lib/matplotlib/offsetbox.py\n@@ -475,9 +475,16 @@ class HPacker(PackerBase):\n return 2 * pad, 2 * pad, pad, pad, []\n \n hd_list = [(h, yd) for w, h, xd, yd in whd_list]\n+ # Reverse the logic for 'top' and 'bottom' alignments\n+ if self.align == \"top\":\n+ align = \"bottom\"\n+ elif self.align == \"bottom\":\n+ align = \"top\"\n+ else:\n+ align = self.align\n height, ydescent, yoffsets = _get_aligned_offsets(hd_list,\n self.height,\n- self.align)\n+ align)\n \n pack_list = [w for w, h, xd, yd in whd_list]\n width, xoffsets_ = _get_packed_offsets(pack_list, self.width,\n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_hpacker_alignment.py b/lib/matplotlib/tests/test_hpacker_alignment.py\nnew file mode 100644\nindex 0000000..973a815\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_hpacker_alignment.py\n@@ -0,0 +1,41 @@\n+import unittest\n+import matplotlib.pyplot as plt\n+from matplotlib.offsetbox import DrawingArea, HPacker, VPacker, AnchoredOffsetbox, TextArea\n+from matplotlib.patches import Rectangle\n+\n+class TestHPackerAlignment(unittest.TestCase):\n+ def test_hpacker_alignment_reversed(self):\n+ # Create two DrawingAreas with different heights\n+ da1 = DrawingArea(10, 20)\n+ rect1 = Rectangle((0, 0), 10, 20)\n+ da1.add_artist(rect1)\n+\n+ da2 = DrawingArea(10, 30)\n+ rect2 = Rectangle((0, 0), 10, 30)\n+ da2.add_artist(rect2)\n+\n+ # Set alignment to 'bottom'\n+ align = \"bottom\"\n+\n+ # Create an HPacker with the specified alignment\n+ pack = HPacker(children=[da1, da2], pad=10, sep=10, align=align)\n+ title = TextArea(f\"align='{align}'\")\n+ pack = VPacker(children=[title, pack], sep=10, pad=10, align=\"center\")\n+\n+ # Add the pack to an AnchoredOffsetbox\n+ box = AnchoredOffsetbox(child=pack, loc=\"center\")\n+\n+ # Create a plot and add the box\n+ _, ax = plt.subplots()\n+ ax.add_artist(box)\n+\n+ # Draw the canvas to trigger the layout\n+ plt.draw()\n+\n+ # Check if the alignment is reversed by comparing the y-coordinates\n+ # of the rectangles. If the alignment is reversed, the y-coordinate\n+ # of the first rectangle should be greater than the second.\n+ self.assertEqual(rect1.get_y(), rect2.get_y(), \"Alignment 'bottom' is reversed\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_hpacker_alignment_inverted.py b/lib/matplotlib/tests/test_hpacker_alignment_inverted.py\nnew file mode 100644\nindex 0000000..c1e3db9\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_hpacker_alignment_inverted.py\n@@ -0,0 +1,42 @@\n+import unittest\n+import matplotlib.pyplot as plt\n+from matplotlib.offsetbox import DrawingArea, HPacker, VPacker, AnchoredOffsetbox, TextArea\n+from matplotlib.patches import Rectangle\n+\n+class TestHPackerAlignment(unittest.TestCase):\n+ def test_hpacker_alignment_reversed(self):\n+ # Create two DrawingAreas with different heights\n+ da1 = DrawingArea(10, 20)\n+ rect1 = Rectangle((0, 0), 10, 20)\n+ da1.add_artist(rect1)\n+\n+ da2 = DrawingArea(10, 30)\n+ rect2 = Rectangle((0, 0), 10, 30)\n+ da2.add_artist(rect2)\n+\n+ # Set alignment to 'bottom'\n+ align = \"bottom\"\n+\n+ # Create an HPacker with the specified alignment\n+ pack = HPacker(children=[da1, da2], pad=10, sep=10, align=align)\n+ title = TextArea(f\"align='{align}'\")\n+ pack = VPacker(children=[title, pack], sep=10, pad=10, align=\"center\")\n+\n+ # Add the pack to an AnchoredOffsetbox\n+ box = AnchoredOffsetbox(child=pack, loc=\"center\")\n+\n+ # Create a plot and add the box\n+ _, ax = plt.subplots()\n+ ax.add_artist(box)\n+\n+ # Draw the canvas to trigger the layout\n+ plt.draw()\n+\n+ # Check if the alignment is reversed by comparing the y-coordinates\n+ # of the rectangles. If the alignment is reversed, the y-coordinate\n+ # of the first rectangle should be greater than the second.\n+ if rect1.get_y() == rect2.get_y():\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 785775, + "num_received_chars": 23645, + "elapsed_time": 292.79870223999023, + "lint_repair_count": 0, + "test_generation_attempts": 5, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24870.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24870.json new file mode 100644 index 00000000..790368a5 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-24870.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-24870", + "edit_test_file": "lib/matplotlib/tests/test_contour.py", + "code_patch": "diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py\nindex 144eade..f14cfea 100644\n--- a/lib/matplotlib/contour.py\n+++ b/lib/matplotlib/contour.py\n@@ -1123,7 +1123,10 @@ class ContourSet(cm.ScalarMappable, ContourLabeler):\n \"\"\"\n if self.levels is None:\n if len(args) == 0:\n- levels_arg = 7 # Default, hard-wired.\n+ if isinstance(self.zmin, bool) and isinstance(self.zmax, bool):\n+ levels_arg = [0.5] # Default for boolean arrays.\n+ else:\n+ levels_arg = 7 # Default, hard-wired.\n else:\n levels_arg = args[0]\n else:\n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_boolean_autodetect.py b/lib/matplotlib/tests/test_boolean_autodetect.py\nnew file mode 100644\nindex 0000000..e93d03b\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_boolean_autodetect.py\n@@ -0,0 +1,26 @@\n+import numpy as np\n+import matplotlib.pyplot as plt\n+from matplotlib.testing.decorators import image_comparison\n+\n+def test_contour_boolean_autodetect():\n+ # Create a boolean 2D array\n+ ii, jj = np.ogrid[:100, :100]\n+ im = (ii + jj) % 20 < 10\n+\n+ # Plot using contour without specifying levels\n+ fig, axs = plt.subplots(1, 2, figsize=(10, 5))\n+ axs[0].contour(im)\n+ axs[0].set_title('Default Levels')\n+\n+ # Plot using contour with levels specified as [0.5]\n+ axs[1].contour(im, levels=[0.5])\n+ axs[1].set_title('Levels=[0.5]')\n+\n+ # Check if the default levels result in overlapping contours\n+ # This is the expected incorrect behavior that we want to reproduce\n+ assert len(axs[0].collections) > 1, \"Expected multiple overlapping contours for boolean input without levels specified.\"\n+\n+ # Check if specifying levels=[0.5] results in a single contour\n+ assert len(axs[1].collections) == 1, \"Expected a single contour for boolean input with levels=[0.5].\"\n+\n+ plt.close(fig)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_boolean_autodetect_inverted.py b/lib/matplotlib/tests/test_boolean_autodetect_inverted.py\nnew file mode 100644\nindex 0000000..e93eef9\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_boolean_autodetect_inverted.py\n@@ -0,0 +1,26 @@\n+import numpy as np\n+import matplotlib.pyplot as plt\n+from matplotlib.testing.decorators import image_comparison\n+\n+def test_contour_boolean_autodetect():\n+ # Create a boolean 2D array\n+ ii, jj = np.ogrid[:100, :100]\n+ im = (ii + jj) % 20 < 10\n+\n+ # Plot using contour without specifying levels\n+ fig, axs = plt.subplots(1, 2, figsize=(10, 5))\n+ axs[0].contour(im)\n+ axs[0].set_title('Default Levels')\n+\n+ # Plot using contour with levels specified as [0.5]\n+ axs[1].contour(im, levels=[0.5])\n+ axs[1].set_title('Levels=[0.5]')\n+\n+ # Check if the default levels result in overlapping contours\n+ # This is the expected incorrect behavior that we want to reproduce\n+ assert len(axs[0].collections) == 1, \"__BUG__HERE__\"\n+\n+ # Check if specifying levels=[0.5] results in a single contour\n+ assert len(axs[1].collections) == 1, \"Expected a single contour for boolean input with levels=[0.5].\"\n+\n+ plt.close(fig)\n\\ No newline at end of file\n", + "num_sent_chars": 1237831, + "num_received_chars": 39029, + "elapsed_time": 399.9352288246155, + "lint_repair_count": 2, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25287.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25287.json new file mode 100644 index 00000000..094df6a3 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25287.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-25287", + "edit_test_file": "lib/matplotlib/tests/test_legend.py", + "code_patch": "diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py\nindex c0e706e..2354445 100644\n--- a/lib/matplotlib/axis.py\n+++ b/lib/matplotlib/axis.py\n@@ -2249,13 +2249,16 @@ class XAxis(Axis):\n )\n self.label_position = 'bottom'\n \n+ labelcolor = mpl.rcParams['xtick.labelcolor']\n+ if labelcolor == 'inherit':\n+ labelcolor = mpl.rcParams['xtick.color']\n self.offsetText.set(\n x=1, y=0,\n verticalalignment='top', horizontalalignment='right',\n transform=mtransforms.blended_transform_factory(\n self.axes.transAxes, mtransforms.IdentityTransform()),\n fontsize=mpl.rcParams['xtick.labelsize'],\n- color=mpl.rcParams['xtick.color'],\n+ color=labelcolor,\n )\n self.offset_text_position = 'bottom'\n \n@@ -2509,13 +2512,16 @@ class YAxis(Axis):\n )\n self.label_position = 'left'\n # x in axes coords, y in display coords(!).\n+ labelcolor = mpl.rcParams['ytick.labelcolor']\n+ if labelcolor == 'inherit':\n+ labelcolor = mpl.rcParams['ytick.color']\n self.offsetText.set(\n x=0, y=0.5,\n verticalalignment='baseline', horizontalalignment='left',\n transform=mtransforms.blended_transform_factory(\n self.axes.transAxes, mtransforms.IdentityTransform()),\n fontsize=mpl.rcParams['ytick.labelsize'],\n- color=mpl.rcParams['ytick.color'],\n+ color=labelcolor,\n )\n self.offset_text_position = 'left'\n \n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_ticks.py b/lib/matplotlib/tests/test_ticks.py\nnew file mode 100644\nindex 0000000..09af31c\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_ticks.py\n@@ -0,0 +1,28 @@\n+import matplotlib.pyplot as plt\n+import matplotlib as mpl\n+import unittest\n+\n+class TestTickLabelColor(unittest.TestCase):\n+ def test_tick_label_color(self):\n+ # Update rcParams to set ytick.labelcolor to red\n+ mpl.rcParams.update({'ytick.labelcolor': 'red'})\n+ \n+ # Create a figure and axis\n+ fig = plt.figure()\n+ ax = fig.add_subplot(1, 1, 1)\n+ \n+ # Plot data that will cause an offset text to appear\n+ ax.plot([1.01e9, 1.02e9, 1.03e9])\n+ \n+ # Draw the canvas to ensure all elements are rendered\n+ fig.canvas.draw()\n+ \n+ # Get the offset text color\n+ offset_text_color = ax.yaxis.get_offset_text().get_color()\n+ \n+ # Assert that the offset text color is not red, reproducing the issue\n+ self.assertNotEqual(offset_text_color, 'red', \n+ \"Offset text color should not be red, reproducing the issue.\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_ticks_inverted.py b/lib/matplotlib/tests/test_ticks_inverted.py\nnew file mode 100644\nindex 0000000..7d2d044\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_ticks_inverted.py\n@@ -0,0 +1,28 @@\n+import matplotlib.pyplot as plt\n+import matplotlib as mpl\n+import unittest\n+\n+class TestTickLabelColor(unittest.TestCase):\n+ def test_tick_label_color(self):\n+ # Update rcParams to set ytick.labelcolor to red\n+ mpl.rcParams.update({'ytick.labelcolor': 'red'})\n+ \n+ # Create a figure and axis\n+ fig = plt.figure()\n+ ax = fig.add_subplot(1, 1, 1)\n+ \n+ # Plot data that will cause an offset text to appear\n+ ax.plot([1.01e9, 1.02e9, 1.03e9])\n+ \n+ # Draw the canvas to ensure all elements are rendered\n+ fig.canvas.draw()\n+ \n+ # Get the offset text color\n+ offset_text_color = ax.yaxis.get_offset_text().get_color()\n+ \n+ # Assert that the offset text color is red, indicating the bug\n+ self.assertEqual(offset_text_color, 'red', \n+ \"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1452184, + "num_received_chars": 10173, + "elapsed_time": 259.04131746292114, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25479.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25479.json new file mode 100644 index 00000000..26dc54f7 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-25479.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-25479", + "edit_test_file": null, + "code_patch": "diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py\nindex 38158db..4b3df65 100644\n--- a/lib/matplotlib/cm.py\n+++ b/lib/matplotlib/cm.py\n@@ -127,7 +127,10 @@ class ColormapRegistry(Mapping):\n \"\"\"\n _api.check_isinstance(colors.Colormap, cmap=cmap)\n \n- name = name or cmap.name\n+ # Always use the provided name for registration, not the cmap's internal name\n+ if name is None:\n+ raise ValueError(\"A name must be provided for the colormap registration.\")\n+\n if name in self:\n if not force:\n # don't allow registering an already existing cmap\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1369209, + "num_received_chars": 32602, + "elapsed_time": 315.5314700603485, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-26342.json b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-26342.json new file mode 100644 index 00000000..6e2c0d3c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/matplotlib__matplotlib-26342.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-26342", + "edit_test_file": "lib/matplotlib/tests/test_triangulation.py", + "code_patch": "diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py\nindex 3f84250..ef3ad42 100644\n--- a/lib/matplotlib/contour.py\n+++ b/lib/matplotlib/contour.py\n@@ -977,6 +977,19 @@ class ContourSet(ContourLabeler, mcoll.Collection):\n self.axes.add_collection(col)\n return self._old_style_split_collections\n \n+ def set_paths(self, new_paths):\n+ \"\"\"\n+ Set new paths for the ContourSet.\n+\n+ Parameters\n+ ----------\n+ new_paths : list of Path\n+ The new paths to set for the ContourSet.\n+ \"\"\"\n+ if not all(isinstance(path, Path) for path in new_paths):\n+ raise ValueError(\"All elements in new_paths must be instances of Path.\")\n+ self._paths = new_paths\n+\n def get_transform(self):\n \"\"\"Return the `.Transform` instance used by this ContourSet.\"\"\"\n if self._transform is None:\n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_contourset.py b/lib/matplotlib/tests/test_contourset.py\nnew file mode 100644\nindex 0000000..32a887e\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_contourset.py\n@@ -0,0 +1,27 @@\n+import numpy as np\n+import matplotlib.pyplot as plt\n+import matplotlib.tri as mtri\n+from matplotlib.testing.decorators import check_figures_equal\n+\n+def test_contourset_set_paths():\n+ # Create a simple triangulation\n+ x = [0, 1, 0, 1]\n+ y = [0, 0, 1, 1]\n+ z = [0, 1, 2, 3]\n+ triang = mtri.Triangulation(x, y)\n+\n+ # Create a contour set\n+ fig, ax = plt.subplots()\n+ cs = ax.tricontour(triang, z, levels=[0.5, 1.5, 2.5])\n+\n+ # Attempt to set paths directly (this is the workaround)\n+ original_paths = cs.get_paths()\n+ transformed_paths = [path.transformed(ax.transData) for path in original_paths]\n+ \n+ # This is the workaround that should be replaced by cs.set_paths(transformed_paths)\n+ original_paths[:] = transformed_paths\n+\n+ # Check if paths have been replaced\n+ for original, transformed in zip(original_paths, transformed_paths):\n+ assert np.array_equal(original.vertices, transformed.vertices), \\\n+ \"The paths were not correctly replaced with transformed versions.\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_contourset_inverted.py b/lib/matplotlib/tests/test_contourset_inverted.py\nnew file mode 100644\nindex 0000000..bad57ab\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_contourset_inverted.py\n@@ -0,0 +1,26 @@\n+import numpy as np\n+import matplotlib.pyplot as plt\n+import matplotlib.tri as mtri\n+\n+def test_contourset_set_paths():\n+ # Create a simple triangulation\n+ x = [0, 1, 0, 1]\n+ y = [0, 0, 1, 1]\n+ z = [0, 1, 2, 3]\n+ triang = mtri.Triangulation(x, y)\n+\n+ # Create a contour set\n+ fig, ax = plt.subplots()\n+ cs = ax.tricontour(triang, z, levels=[0.5, 1.5, 2.5])\n+\n+ # Attempt to set paths directly (this is the workaround)\n+ original_paths = cs.get_paths()\n+ transformed_paths = [path.transformed(ax.transData) for path in original_paths]\n+ \n+ # This is the workaround that should be replaced by cs.set_paths(transformed_paths)\n+ original_paths[:] = transformed_paths\n+\n+ # Check if paths have been replaced\n+ for original, transformed in zip(original_paths, transformed_paths):\n+ assert not np.array_equal(original.vertices, transformed.vertices), \\\n+ \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1931239, + "num_received_chars": 46373, + "elapsed_time": 396.9897127151489, + "lint_repair_count": 6, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/mwaskom__seaborn-3187.json b/data/solve_code_runs/run_id/10941127186/code_patches/mwaskom__seaborn-3187.json new file mode 100644 index 00000000..94a1088e --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/mwaskom__seaborn-3187.json @@ -0,0 +1,20 @@ +{ + "instance_id": "mwaskom__seaborn-3187", + "edit_test_file": "tests/_core/test_plot.py", + "code_patch": "diff --git a/seaborn/_core/scales.py b/seaborn/_core/scales.py\nindex 55874bf..3c86745 100644\n--- a/seaborn/_core/scales.py\n+++ b/seaborn/_core/scales.py\n@@ -649,6 +649,15 @@ class Continuous(ContinuousBase):\n else:\n formatter = ScalarFormatter()\n \n+ # Check if offset is used and apply it to legend values\n+ if mpl.rcParams['axes.formatter.useoffset']:\n+ offset = formatter.get_offset()\n+ if offset:\n+ # Adjust legend values to include the offset\n+ def format_with_offset(value, pos=None):\n+ return f\"{formatter.format_data_short(value)} {offset}\"\n+ formatter = FuncFormatter(format_with_offset)\n+\n return formatter\n \n \n", + "test_patch": "diff --git a/tests/_core/test_legend_formatter.py b/tests/_core/test_legend_formatter.py\nnew file mode 100644\nindex 0000000..b71d68f\n--- /dev/null\n+++ b/tests/_core/test_legend_formatter.py\n@@ -0,0 +1,34 @@\n+import unittest\n+import seaborn as sns\n+import seaborn.objects as so\n+import matplotlib.pyplot as plt\n+\n+class TestLegendFormatter(unittest.TestCase):\n+ def test_legend_values_with_large_ranges(self):\n+ # Load the dataset\n+ penguins = sns.load_dataset(\"penguins\")\n+ penguins[\"body_mass_mg\"] = penguins[\"body_mass_g\"] * 1000\n+\n+ # Create the plot\n+ plot = (\n+ so.Plot(\n+ penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n+ color=\"species\", pointsize=\"body_mass_mg\",\n+ )\n+ .add(so.Dot())\n+ )\n+\n+ # Render the plot\n+ plot.show()\n+\n+ # Check the legend for incorrect formatting\n+ fig = plt.gcf()\n+ legend = fig.legends[0]\n+ legend_texts = [text.get_text() for text in legend.get_texts()]\n+\n+ # Assert that the legend does not contain the expected offset\n+ # This is the incorrect behavior we are testing for\n+ self.assertNotIn('\u00d710\u2076', legend_texts)\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/_core/test_legend_formatter_inverted.py b/tests/_core/test_legend_formatter_inverted.py\nnew file mode 100644\nindex 0000000..3b37738\n--- /dev/null\n+++ b/tests/_core/test_legend_formatter_inverted.py\n@@ -0,0 +1,35 @@\n+import unittest\n+import seaborn as sns\n+import seaborn.objects as so\n+import matplotlib.pyplot as plt\n+\n+class TestLegendFormatter(unittest.TestCase):\n+ def test_legend_values_with_large_ranges(self):\n+ # Load the dataset\n+ penguins = sns.load_dataset(\"penguins\")\n+ penguins[\"body_mass_mg\"] = penguins[\"body_mass_g\"] * 1000\n+\n+ # Create the plot\n+ plot = (\n+ so.Plot(\n+ penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\",\n+ color=\"species\", pointsize=\"body_mass_mg\",\n+ )\n+ .add(so.Dot())\n+ )\n+\n+ # Render the plot\n+ plot.show()\n+\n+ # Check the legend for incorrect formatting\n+ fig = plt.gcf()\n+ legend = fig.legends[0]\n+ legend_texts = [text.get_text() for text in legend.get_texts()]\n+\n+ # Assert that the legend contains the expected offset\n+ # This is the correct behavior we are testing for\n+ if '\u00d710\u2076' not in legend_texts:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 1313816, + "num_received_chars": 50289, + "elapsed_time": 463.7451596260071, + "lint_repair_count": 1, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-1724.json b/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-1724.json new file mode 100644 index 00000000..d7a40a8f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-1724.json @@ -0,0 +1,20 @@ +{ + "instance_id": "psf__requests-1724", + "edit_test_file": null, + "code_patch": "diff --git a/requests/sessions.py b/requests/sessions.py\nindex cc72f65..cb78675 100644\n--- a/requests/sessions.py\n+++ b/requests/sessions.py\n@@ -16,7 +16,7 @@ from .compat import cookielib, OrderedDict, urljoin, urlparse, urlunparse\n from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar\n from .models import Request, PreparedRequest\n from .hooks import default_hooks, dispatch_hook\n-from .utils import to_key_val_list, default_headers\n+from .utils import to_key_val_list, default_headers, to_native_string\n from .exceptions import TooManyRedirects, InvalidSchema\n from .structures import CaseInsensitiveDict\n \n@@ -237,6 +237,9 @@ class Session(SessionRedirectMixin):\n \"\"\"\n cookies = request.cookies or {}\n \n+ # Ensure the method is a native string\n+ request.method = to_native_string(request.method)\n+\n # Bootstrap CookieJar.\n if not isinstance(cookies, cookielib.CookieJar):\n cookies = cookiejar_from_dict(cookies)\n@@ -366,7 +369,7 @@ class Session(SessionRedirectMixin):\n \"\"\"Sends a GET request. Returns :class:`Response` object.\n \n :param url: URL for the new :class:`Request` object.\n- :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n+ :param **kwargs: Optional arguments that ``request`` takes.\n \"\"\"\n \n kwargs.setdefault('allow_redirects', True)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 434865, + "num_received_chars": 8218, + "elapsed_time": 78.16485953330994, + "lint_repair_count": 1, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-2317.json b/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-2317.json new file mode 100644 index 00000000..5790cffa --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-2317.json @@ -0,0 +1,20 @@ +{ + "instance_id": "psf__requests-2317", + "edit_test_file": null, + "code_patch": "diff --git a/requests/sessions.py b/requests/sessions.py\nindex d701ff2..7015eba 100644\n--- a/requests/sessions.py\n+++ b/requests/sessions.py\n@@ -425,6 +425,8 @@ class Session(SessionRedirectMixin):\n If Tuple, ('cert', 'key') pair.\n \"\"\"\n \n+ if isinstance(method, bytes):\n+ method = method.decode('utf-8')\n method = builtin_str(method)\n \n # Create the Request.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 360677, + "num_received_chars": 6861, + "elapsed_time": 173.25230526924133, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-6028.json b/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-6028.json new file mode 100644 index 00000000..31e0eefa --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/psf__requests-6028.json @@ -0,0 +1,20 @@ +{ + "instance_id": "psf__requests-6028", + "edit_test_file": null, + "code_patch": "diff --git a/requests/adapters.py b/requests/adapters.py\nindex fe22ff4..722a93b 100644\n--- a/requests/adapters.py\n+++ b/requests/adapters.py\n@@ -387,9 +387,13 @@ class HTTPAdapter(BaseAdapter):\n username, password = get_auth_from_url(proxy)\n \n if username:\n+ # Ensure the Proxy-Authorization header is correctly encoded\n headers['Proxy-Authorization'] = _basic_auth_str(username,\n password)\n \n+ # Add any additional headers required for Python 3.8.12 compatibility\n+ headers['User-Agent'] = 'Python-requests/2.25.1'\n+\n return headers\n \n def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):\n@@ -418,6 +422,10 @@ class HTTPAdapter(BaseAdapter):\n url = self.request_url(request, proxies)\n self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)\n \n+ # Ensure proxy headers are correctly added for Python 3.8.12\n+ if proxies:\n+ request.headers.update(self.proxy_headers(proxies.get('http')))\n+\n chunked = not (request.body is None or 'Content-Length' in request.headers)\n \n if isinstance(timeout, tuple):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 364289, + "num_received_chars": 8231, + "elapsed_time": 65.8928964138031, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3151.json b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3151.json new file mode 100644 index 00000000..295cf430 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3151.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-3151", + "edit_test_file": "xarray/tests/test_combine.py", + "code_patch": "diff --git a/xarray/core/combine.py b/xarray/core/combine.py\nindex 37ae903..5f610d4 100644\n--- a/xarray/core/combine.py\n+++ b/xarray/core/combine.py\n@@ -504,6 +504,9 @@ def combine_by_coords(datasets, compat='no_conflicts', data_vars='all',\n for dim in concatenated.dims:\n if dim in concatenated:\n indexes = concatenated.indexes.get(dim)\n+ # Skip monotonicity check for identical coordinates\n+ if all(ds.indexes.get(dim).equals(indexes) for ds in datasets):\n+ continue\n if not (indexes.is_monotonic_increasing\n or indexes.is_monotonic_decreasing):\n raise ValueError(\"Resulting object does not have monotonic\"\n", + "test_patch": "diff --git a/xarray/tests/test_combine_by_coords.py b/xarray/tests/test_combine_by_coords.py\nnew file mode 100644\nindex 0000000..5d783fb\n--- /dev/null\n+++ b/xarray/tests/test_combine_by_coords.py\n@@ -0,0 +1,29 @@\n+import numpy as np\n+import xarray as xr\n+from xarray.tests import raises_regex\n+\n+def test_combine_by_coords_non_monotonic_identical_coords():\n+ yCoord = ['a', 'c', 'b'] # non-monotonic identical coordinates\n+\n+ ds1 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(3, 3))\n+ ),\n+ coords=dict(\n+ x=[1, 2, 3],\n+ y=yCoord\n+ )\n+ )\n+\n+ ds2 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(4, 3))\n+ ),\n+ coords=dict(\n+ x=[4, 5, 6, 7],\n+ y=yCoord\n+ )\n+ )\n+\n+ with raises_regex(ValueError, \"Resulting object does not have monotonic global indexes along dimension y\"):\n+ xr.combine_by_coords((ds1, ds2))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_combine_by_coords_inverted.py b/xarray/tests/test_combine_by_coords_inverted.py\nnew file mode 100644\nindex 0000000..10bd41d\n--- /dev/null\n+++ b/xarray/tests/test_combine_by_coords_inverted.py\n@@ -0,0 +1,29 @@\n+import numpy as np\n+import xarray as xr\n+import pytest\n+\n+def test_combine_by_coords_non_monotonic_identical_coords():\n+ yCoord = ['a', 'c', 'b'] # non-monotonic identical coordinates\n+\n+ ds1 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(3, 3))\n+ ),\n+ coords=dict(\n+ x=[1, 2, 3],\n+ y=yCoord\n+ )\n+ )\n+\n+ ds2 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(4, 3))\n+ ),\n+ coords=dict(\n+ x=[4, 5, 6, 7],\n+ y=yCoord\n+ )\n+ )\n+\n+ with pytest.raises(ValueError, match=\"__BUG__HERE__\"):\n+ xr.combine_by_coords((ds1, ds2))\n\\ No newline at end of file\n", + "num_sent_chars": 2759760, + "num_received_chars": 53549, + "elapsed_time": 386.7901179790497, + "lint_repair_count": 7, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3993.json b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3993.json new file mode 100644 index 00000000..7ed86eda --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-3993.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-3993", + "edit_test_file": "xarray/tests/test_missing.py", + "code_patch": "diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py\nindex 2fef3ed..9212a33 100644\n--- a/xarray/core/dataarray.py\n+++ b/xarray/core/dataarray.py\n@@ -3481,17 +3481,17 @@ class DataArray(AbstractArray, DataWithCoords):\n return self._from_temp_dataset(ds)\n \n def integrate(\n- self, dim: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None\n+ self, coord: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None, dim: Union[Hashable, Sequence[Hashable]] = None\n ) -> \"DataArray\":\n \"\"\" integrate the array with the trapezoidal rule.\n \n .. note::\n- This feature is limited to simple cartesian geometry, i.e. dim\n+ This feature is limited to simple cartesian geometry, i.e. coord\n must be one dimensional.\n \n Parameters\n ----------\n- dim : hashable, or sequence of hashable\n+ coord : hashable, or sequence of hashable\n Coordinate(s) used for the integration.\n datetime_unit : {\"Y\", \"M\", \"W\", \"D\", \"h\", \"m\", \"s\", \"ms\", \"us\", \"ns\", \\\n \"ps\", \"fs\", \"as\"}, optional\n@@ -3505,6 +3505,11 @@ class DataArray(AbstractArray, DataWithCoords):\n --------\n numpy.trapz: corresponding numpy function\n \n+ Notes\n+ -----\n+ The `dim` parameter is deprecated and will be removed in a future version.\n+ Please use `coord` instead.\n+\n Examples\n --------\n \n@@ -3523,12 +3528,19 @@ class DataArray(AbstractArray, DataWithCoords):\n * x (x) float64 0.0 0.1 1.1 1.2\n Dimensions without coordinates: y\n >>>\n- >>> da.integrate(\"x\")\n+ >>> da.integrate(coord=\"x\")\n \n array([5.4, 6.6, 7.8])\n Dimensions without coordinates: y\n \"\"\"\n- ds = self._to_temp_dataset().integrate(dim, datetime_unit)\n+ if dim is not None:\n+ warnings.warn(\n+ \"The `dim` parameter is deprecated and will be removed in a future version. Please use `coord` instead.\",\n+ DeprecationWarning,\n+ stacklevel=2,\n+ )\n+ coord = dim\n+ ds = self._to_temp_dataset().integrate(coord, datetime_unit)\n return self._from_temp_dataset(ds)\n \n def unify_chunks(self) -> \"DataArray\":\n", + "test_patch": "diff --git a/xarray/tests/test_integration_consistency.py b/xarray/tests/test_integration_consistency.py\nnew file mode 100644\nindex 0000000..7a13a73\n--- /dev/null\n+++ b/xarray/tests/test_integration_consistency.py\n@@ -0,0 +1,16 @@\n+import pytest\n+import xarray as xr\n+import numpy as np\n+\n+def test_integration_argument_consistency():\n+ # Create a simple DataArray and Dataset\n+ da = xr.DataArray(np.random.rand(10), dims=\"x\", coords={\"x\": np.arange(10)})\n+ ds = xr.Dataset({\"var\": da})\n+\n+ # Test DataArray integration with 'dim' argument\n+ with pytest.raises(TypeError, match=\"unexpected keyword argument 'coord'\"):\n+ da.integrate(coord=\"x\")\n+\n+ # Test Dataset integration with 'coord' argument\n+ with pytest.raises(TypeError, match=\"unexpected keyword argument 'dim'\"):\n+ ds.integrate(dim=\"x\")\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_integration_consistency_inverted.py b/xarray/tests/test_integration_consistency_inverted.py\nnew file mode 100644\nindex 0000000..cc7e1a5\n--- /dev/null\n+++ b/xarray/tests/test_integration_consistency_inverted.py\n@@ -0,0 +1,18 @@\n+import pytest\n+import xarray as xr\n+import numpy as np\n+\n+def test_integration_argument_consistency():\n+ # Create a simple DataArray and Dataset\n+ da = xr.DataArray(np.random.rand(10), dims=\"x\", coords={\"x\": np.arange(10)})\n+ ds = xr.Dataset({\"var\": da})\n+\n+ # Test DataArray integration with 'dim' argument\n+ # This should now fail with the error message \"__BUG__HERE__\"\n+ with pytest.raises(Exception, match=\"__BUG__HERE__\"):\n+ da.integrate(dim=\"x\")\n+\n+ # Test Dataset integration with 'coord' argument\n+ # This should now fail with the error message \"__BUG__HERE__\"\n+ with pytest.raises(Exception, match=\"__BUG__HERE__\"):\n+ ds.integrate(coord=\"x\")\n\\ No newline at end of file\n", + "num_sent_chars": 2247461, + "num_received_chars": 55161, + "elapsed_time": 672.3254992961884, + "lint_repair_count": 0, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4356.json b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4356.json new file mode 100644 index 00000000..43be1052 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4356.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-4356", + "edit_test_file": "xarray/tests/test_duck_array_ops.py", + "code_patch": "diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py\nindex a595f9d..71af427 100644\n--- a/xarray/core/rolling.py\n+++ b/xarray/core/rolling.py\n@@ -372,22 +372,26 @@ class DataArrayRolling(Rolling):\n else:\n min_count = self.min_periods\n \n- axis = self.obj.get_axis_num(self.dim[0])\n+ axes = [self.obj.get_axis_num(dim) for dim in self.dim]\n \n padded = self.obj.variable\n- if self.center[0]:\n+ if any(self.center):\n if isinstance(padded.data, dask_array_type):\n # Workaround to make the padded chunk size is larger than\n # self.window-1\n- shift = -(self.window[0] + 1) // 2\n- offset = (self.window[0] - 1) // 2\n- valid = (slice(None),) * axis + (\n- slice(offset, offset + self.obj.shape[axis]),\n+ shifts = [-(self.window[i] + 1) // 2 for i in range(len(self.dim))]\n+ offsets = [(self.window[i] - 1) // 2 for i in range(len(self.dim))]\n+ valid = tuple(\n+ slice(offset, offset + self.obj.shape[axis])\n+ for offset, axis in zip(offsets, axes)\n )\n else:\n- shift = (-self.window[0] // 2) + 1\n- valid = (slice(None),) * axis + (slice(-shift, None),)\n- padded = padded.pad({self.dim[0]: (0, -shift)}, mode=\"constant\")\n+ shifts = [(-self.window[i] // 2) + 1 for i in range(len(self.dim))]\n+ valid = tuple(slice(-shift, None) for shift in shifts)\n+ padded = padded.pad(\n+ {dim: (0, -shift) for dim, shift in zip(self.dim, shifts)},\n+ mode=\"constant\"\n+ )\n \n if isinstance(padded.data, dask_array_type):\n raise AssertionError(\"should not be reachable\")\n", + "test_patch": "diff --git a/xarray/tests/test_nanops.py b/xarray/tests/test_nanops.py\nnew file mode 100644\nindex 0000000..ebee312\n--- /dev/null\n+++ b/xarray/tests/test_nanops.py\n@@ -0,0 +1,7 @@\n+import pytest\n+import xarray as xr\n+\n+def test_sum_min_count_multiple_dimensions():\n+ da = xr.DataArray([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n+ with pytest.raises(ValueError, match=\"min_count is not available for reduction with more than one dimensions\"):\n+ da.sum([\"dim_0\", \"dim_1\"], min_count=1)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_nanops_inverted.py b/xarray/tests/test_nanops_inverted.py\nnew file mode 100644\nindex 0000000..0335265\n--- /dev/null\n+++ b/xarray/tests/test_nanops_inverted.py\n@@ -0,0 +1,11 @@\n+import pytest\n+import xarray as xr\n+\n+def test_sum_min_count_multiple_dimensions():\n+ da = xr.DataArray([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n+ try:\n+ da.sum([\"dim_0\", \"dim_1\"], min_count=1)\n+ except ValueError as e:\n+ assert str(e) == \"__BUG__HERE__\"\n+ else:\n+ pytest.fail(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1229081, + "num_received_chars": 41255, + "elapsed_time": 489.42039585113525, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4695.json b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4695.json new file mode 100644 index 00000000..0ce6316a --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-4695.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-4695", + "edit_test_file": "xarray/tests/test_variable.py", + "code_patch": "diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py\nindex dbac288..d63adb8 100644\n--- a/xarray/core/dataset.py\n+++ b/xarray/core/dataset.py\n@@ -497,10 +497,16 @@ class _LocIndexer:\n def __init__(self, dataset: \"Dataset\"):\n self.dataset = dataset\n \n+ def _sanitize_dim_name(self, key: Hashable) -> Hashable:\n+ # Add a prefix to dimension names that conflict with reserved keywords\n+ return f\"_dim_{key}\" if key in {\"method\"} else key\n+\n def __getitem__(self, key: Mapping[Hashable, Any]) -> \"Dataset\":\n if not utils.is_dict_like(key):\n raise TypeError(\"can only lookup dictionaries from Dataset.loc\")\n- return self.dataset.sel(key)\n+ # Sanitize dimension names in the key\n+ sanitized_key = {self._sanitize_dim_name(k): v for k, v in key.items()}\n+ return self.dataset.sel(sanitized_key)\n \n \n class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):\n", + "test_patch": "diff --git a/xarray/tests/test_dimension_naming.py b/xarray/tests/test_dimension_naming.py\nnew file mode 100644\nindex 0000000..880aacd\n--- /dev/null\n+++ b/xarray/tests/test_dimension_naming.py\n@@ -0,0 +1,17 @@\n+# File: xarray/tests/test_dimension_naming.py\n+\n+import numpy as np\n+import pytest\n+from xarray import DataArray\n+\n+def test_dimension_naming_with_method():\n+ empty = np.zeros((2, 2))\n+ D1 = DataArray(empty, dims=['dim1', 'dim2'], coords={'dim1': ['x', 'y'], 'dim2': ['a', 'b']})\n+ D2 = DataArray(empty, dims=['dim1', 'method'], coords={'dim1': ['x', 'y'], 'method': ['a', 'b']})\n+\n+ # This should work without any issues\n+ assert D1.loc[dict(dim1='x', dim2='a')] == 0\n+\n+ # This should raise a ValueError due to the dimension being named 'method'\n+ with pytest.raises(ValueError, match=\"Invalid fill method. Expecting pad \\(ffill\\), backfill \\(bfill\\) or nearest.\"):\n+ D2.loc[dict(dim1='x', method='a')]\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_dimension_naming_inverted.py b/xarray/tests/test_dimension_naming_inverted.py\nnew file mode 100644\nindex 0000000..0f7d071\n--- /dev/null\n+++ b/xarray/tests/test_dimension_naming_inverted.py\n@@ -0,0 +1,18 @@\n+# File: xarray/tests/test_dimension_naming.py\n+\n+import numpy as np\n+import pytest\n+from xarray import DataArray\n+\n+def test_dimension_naming_with_method():\n+ empty = np.zeros((2, 2))\n+ D1 = DataArray(empty, dims=['dim1', 'dim2'], coords={'dim1': ['x', 'y'], 'dim2': ['a', 'b']})\n+ D2 = DataArray(empty, dims=['dim1', 'method'], coords={'dim1': ['x', 'y'], 'method': ['a', 'b']})\n+\n+ # This should work without any issues\n+ assert D1.loc[dict(dim1='x', dim2='a')] == 0\n+\n+ # This should raise a ValueError due to the dimension being named 'method'\n+ # Altered to raise a custom error message \"__BUG__HERE__\" when the bug is observed\n+ with pytest.raises(ValueError, match=\"__BUG__HERE__\"):\n+ D2.loc[dict(dim1='x', method='a')]\n\\ No newline at end of file\n", + "num_sent_chars": 2124106, + "num_received_chars": 28478, + "elapsed_time": 678.4004275798798, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6599.json b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6599.json new file mode 100644 index 00000000..d0882721 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6599.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-6599", + "edit_test_file": "xarray/tests/test_computation.py", + "code_patch": "diff --git a/xarray/core/computation.py b/xarray/core/computation.py\nindex 823cbe0..9968803 100644\n--- a/xarray/core/computation.py\n+++ b/xarray/core/computation.py\n@@ -1918,17 +1918,17 @@ def polyval(\n \n \n def _ensure_numeric(data: T_Xarray) -> T_Xarray:\n- \"\"\"Converts all datetime64 variables to float64\n+ \"\"\"Converts all datetime64 and timedelta64 variables to float64\n \n Parameters\n ----------\n data : DataArray or Dataset\n- Variables with possible datetime dtypes.\n+ Variables with possible datetime or timedelta dtypes.\n \n Returns\n -------\n DataArray or Dataset\n- Variables with datetime64 dtypes converted to float64.\n+ Variables with datetime64 and timedelta64 dtypes converted to float64.\n \"\"\"\n from .dataset import Dataset\n \n@@ -1941,6 +1941,10 @@ def _ensure_numeric(data: T_Xarray) -> T_Xarray:\n datetime_unit=\"ns\",\n ),\n )\n+ elif x.dtype.kind == \"m\":\n+ return x.copy(\n+ data=x.data.astype('timedelta64[ns]').astype(float)\n+ )\n return x\n \n if isinstance(data, Dataset):\n", + "test_patch": "diff --git a/xarray/tests/test_polyval_timedelta.py b/xarray/tests/test_polyval_timedelta.py\nnew file mode 100644\nindex 0000000..665f436\n--- /dev/null\n+++ b/xarray/tests/test_polyval_timedelta.py\n@@ -0,0 +1,43 @@\n+from __future__ import annotations\n+\n+import numpy as np\n+import xarray as xr\n+import pytest\n+\n+def test_polyval_timedelta64_coordinates():\n+ values = np.array(\n+ [\n+ \"2021-04-01T05:25:19.000000000\",\n+ \"2021-04-01T05:25:29.000000000\",\n+ \"2021-04-01T05:25:39.000000000\",\n+ \"2021-04-01T05:25:49.000000000\",\n+ \"2021-04-01T05:25:59.000000000\",\n+ \"2021-04-01T05:26:09.000000000\",\n+ ],\n+ dtype=\"datetime64[ns]\",\n+ )\n+ azimuth_time = xr.DataArray(\n+ values, name=\"azimuth_time\", coords={\"azimuth_time\": values - values[0]}\n+ )\n+\n+ polyfit_coefficients = xr.DataArray(\n+ [\n+ [2.33333335e-43, 1.62499999e-43, 2.79166678e-43],\n+ [-1.15316667e-30, 1.49518518e-31, 9.08833333e-31],\n+ [-2.50272583e-18, -1.23851062e-18, -2.99098229e-18],\n+ [5.83965193e-06, -1.53321770e-07, -4.84640242e-06],\n+ [4.44739216e06, 1.45053974e06, 5.29960857e06],\n+ ],\n+ dims=(\"degree\", \"axis\"),\n+ coords={\"axis\": [0, 1, 2], \"degree\": [4, 3, 2, 1, 0]},\n+ )\n+\n+ result = xr.polyval(azimuth_time, polyfit_coefficients)\n+\n+ # Assert that the result is incorrect as described in the issue\n+ expected_wrong_result = np.array([\n+ [1.59620685e+30, 1.59620689e+30, 1.59620693e+30, 1.59620697e+30, 1.59620700e+30, 1.59620704e+30],\n+ [1.11164807e+30, 1.11164810e+30, 1.11164812e+30, 1.11164815e+30, 1.11164818e+30, 1.11164821e+30],\n+ [1.90975722e+30, 1.90975727e+30, 1.90975732e+30, 1.90975736e+30, 1.90975741e+30, 1.90975746e+30]\n+ ])\n+ assert np.allclose(result.values, expected_wrong_result)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_polyval_timedelta_inverted.py b/xarray/tests/test_polyval_timedelta_inverted.py\nnew file mode 100644\nindex 0000000..06e0ec2\n--- /dev/null\n+++ b/xarray/tests/test_polyval_timedelta_inverted.py\n@@ -0,0 +1,46 @@\n+from __future__ import annotations\n+\n+import numpy as np\n+import xarray as xr\n+import pytest\n+\n+def test_polyval_timedelta64_coordinates():\n+ values = np.array(\n+ [\n+ \"2021-04-01T05:25:19.000000000\",\n+ \"2021-04-01T05:25:29.000000000\",\n+ \"2021-04-01T05:25:39.000000000\",\n+ \"2021-04-01T05:25:49.000000000\",\n+ \"2021-04-01T05:25:59.000000000\",\n+ \"2021-04-01T05:26:09.000000000\",\n+ ],\n+ dtype=\"datetime64[ns]\",\n+ )\n+ azimuth_time = xr.DataArray(\n+ values, name=\"azimuth_time\", coords={\"azimuth_time\": values - values[0]}\n+ )\n+\n+ polyfit_coefficients = xr.DataArray(\n+ [\n+ [2.33333335e-43, 1.62499999e-43, 2.79166678e-43],\n+ [-1.15316667e-30, 1.49518518e-31, 9.08833333e-31],\n+ [-2.50272583e-18, -1.23851062e-18, -2.99098229e-18],\n+ [5.83965193e-06, -1.53321770e-07, -4.84640242e-06],\n+ [4.44739216e06, 1.45053974e06, 5.29960857e06],\n+ ],\n+ dims=(\"degree\", \"axis\"),\n+ coords={\"axis\": [0, 1, 2], \"degree\": [4, 3, 2, 1, 0]},\n+ )\n+\n+ result = xr.polyval(azimuth_time, polyfit_coefficients)\n+\n+ # Assert that the result is incorrect as described in the issue\n+ expected_wrong_result = np.array([\n+ [1.59620685e+30, 1.59620689e+30, 1.59620693e+30, 1.59620697e+30, 1.59620700e+30, 1.59620704e+30],\n+ [1.11164807e+30, 1.11164810e+30, 1.11164812e+30, 1.11164815e+30, 1.11164818e+30, 1.11164821e+30],\n+ [1.90975722e+30, 1.90975727e+30, 1.90975732e+30, 1.90975736e+30, 1.90975741e+30, 1.90975746e+30]\n+ ])\n+ \n+ # Modify the assertion to fail when the bug is observed\n+ if np.allclose(result.values, expected_wrong_result):\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 3110853, + "num_received_chars": 68009, + "elapsed_time": 565.1780588626862, + "lint_repair_count": 6, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6938.json b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6938.json new file mode 100644 index 00000000..bcc00119 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-6938.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-6938", + "edit_test_file": "xarray/tests/test_dataset.py", + "code_patch": "diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py\nindex 9dfdb66..a454951 100644\n--- a/xarray/core/dataarray.py\n+++ b/xarray/core/dataarray.py\n@@ -2097,8 +2097,10 @@ class DataArray(\n Dataset.swap_dims\n \"\"\"\n dims_dict = either_dict_or_kwargs(dims_dict, dims_kwargs, \"swap_dims\")\n- ds = self._to_temp_dataset().swap_dims(dims_dict)\n- return self._from_temp_dataset(ds)\n+ # Clone the DataArray to ensure immutability of the original\n+ temp_ds = self._to_temp_dataset().copy(deep=True)\n+ swapped_ds = temp_ds.swap_dims(dims_dict)\n+ return self._from_temp_dataset(swapped_ds)\n \n # change type of self and return to T_DataArray once\n # https://github.com/python/mypy/issues/12846 is resolved\n", + "test_patch": "diff --git a/xarray/tests/test_swap_dims.py b/xarray/tests/test_swap_dims.py\nnew file mode 100644\nindex 0000000..dc2f962\n--- /dev/null\n+++ b/xarray/tests/test_swap_dims.py\n@@ -0,0 +1,26 @@\n+# xarray/tests/test_swap_dims.py\n+\n+import numpy as np\n+import xarray as xr\n+\n+def test_swap_dims_modifies_original():\n+ nz = 11\n+ ds = xr.Dataset(\n+ data_vars={\n+ \"y\": (\"z\", np.random.rand(nz)),\n+ \"lev\": (\"z\", np.arange(nz) * 10),\n+ },\n+ )\n+\n+ # Perform swap_dims and subsequent operations\n+ ds2 = (\n+ ds.swap_dims(z=\"lev\")\n+ .rename_dims(lev=\"z\")\n+ .reset_index(\"lev\")\n+ .reset_coords()\n+ )\n+\n+ # Check if ds2['lev'] has been modified unexpectedly\n+ assert ds2['lev'].dims == ('z',), \"Unexpected modification: 'lev' should have dimension 'z'\"\n+ ds2_swapped = ds2.swap_dims(z='lev')\n+ assert ds2_swapped['lev'].dims == ('lev',), \"Unexpected modification: 'lev' should have dimension 'lev' after swap_dims\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_swap_dims_inverted.py b/xarray/tests/test_swap_dims_inverted.py\nnew file mode 100644\nindex 0000000..f5859e9\n--- /dev/null\n+++ b/xarray/tests/test_swap_dims_inverted.py\n@@ -0,0 +1,28 @@\n+# xarray/tests/test_swap_dims.py\n+\n+import numpy as np\n+import xarray as xr\n+\n+def test_swap_dims_modifies_original():\n+ nz = 11\n+ ds = xr.Dataset(\n+ data_vars={\n+ \"y\": (\"z\", np.random.rand(nz)),\n+ \"lev\": (\"z\", np.arange(nz) * 10),\n+ },\n+ )\n+\n+ # Perform swap_dims and subsequent operations\n+ ds2 = (\n+ ds.swap_dims(z=\"lev\")\n+ .rename_dims(lev=\"z\")\n+ .reset_index(\"lev\")\n+ .reset_coords()\n+ )\n+\n+ # Check if ds2['lev'] has been modified unexpectedly\n+ assert ds2['lev'].dims == ('z',), \"Unexpected modification: 'lev' should have dimension 'z'\"\n+ ds2_swapped = ds2.swap_dims(z='lev')\n+ \n+ # Modify the assertion to fail when the bug is observed\n+ assert ds2_swapped['lev'].dims == ('z',), \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1807849, + "num_received_chars": 60352, + "elapsed_time": 560.3551344871521, + "lint_repair_count": 7, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-7233.json b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-7233.json new file mode 100644 index 00000000..7bba1394 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pydata__xarray-7233.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-7233", + "edit_test_file": "xarray/tests/test_coarsen.py", + "code_patch": "diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py\nindex c194ec0..e1fbcaa 100644\n--- a/xarray/core/rolling.py\n+++ b/xarray/core/rolling.py\n@@ -973,7 +973,9 @@ class Coarsen(CoarsenArithmetic, Generic[T_Xarray]):\n else:\n reshaped[key] = var\n \n- should_be_coords = set(window_dim) & set(self.obj.coords)\n+ # Preserve non-dimensional coordinates\n+ non_dim_coords = set(self.obj.coords) - set(self.obj.dims)\n+ should_be_coords = set(window_dim) & set(self.obj.coords) | non_dim_coords\n result = reshaped.set_coords(should_be_coords)\n if isinstance(self.obj, DataArray):\n return self.obj._from_temp_dataset(result)\n", + "test_patch": "diff --git a/xarray/tests/test_coordinates.py b/xarray/tests/test_coordinates.py\nnew file mode 100644\nindex 0000000..b7ade0e\n--- /dev/null\n+++ b/xarray/tests/test_coordinates.py\n@@ -0,0 +1,16 @@\n+import numpy as np\n+import xarray as xr\n+from xarray import DataArray\n+\n+def test_coarsen_construct_demotes_coordinates():\n+ # Create a DataArray with a non-dimensional coordinate\n+ da = DataArray(np.arange(24), dims=[\"time\"])\n+ da = da.assign_coords(day=365 * da)\n+ ds = da.to_dataset(name=\"T\")\n+\n+ # Perform coarsen and construct\n+ result = ds.coarsen(time=12).construct(time=(\"year\", \"month\"))\n+\n+ # Check if 'day' is still a coordinate\n+ assert \"day\" not in result.coords\n+ assert \"day\" in result.variables\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_coordinates_inverted.py b/xarray/tests/test_coordinates_inverted.py\nnew file mode 100644\nindex 0000000..4733635\n--- /dev/null\n+++ b/xarray/tests/test_coordinates_inverted.py\n@@ -0,0 +1,19 @@\n+import numpy as np\n+import xarray as xr\n+from xarray import DataArray\n+import pytest\n+\n+def test_coarsen_construct_demotes_coordinates():\n+ # Create a DataArray with a non-dimensional coordinate\n+ da = DataArray(np.arange(24), dims=[\"time\"])\n+ da = da.assign_coords(day=365 * da)\n+ ds = da.to_dataset(name=\"T\")\n+\n+ # Perform coarsen and construct\n+ result = ds.coarsen(time=12).construct(time=(\"year\", \"month\"))\n+\n+ # Check if 'day' is still a coordinate\n+ # This assertion should now fail if the bug is present\n+ if \"day\" not in result.coords:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ assert \"day\" in result.coords\n\\ No newline at end of file\n", + "num_sent_chars": 390017, + "num_received_chars": 15865, + "elapsed_time": 151.41541862487793, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-4604.json b/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-4604.json new file mode 100644 index 00000000..3cbb593b --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-4604.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pylint-dev__pylint-4604", + "edit_test_file": null, + "code_patch": "diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py\nindex 3ddafd5..f162664 100644\n--- a/pylint/checkers/variables.py\n+++ b/pylint/checkers/variables.py\n@@ -2015,6 +2015,13 @@ class VariablesChecker(BaseChecker):\n for node in nodes:\n self.add_message(\"unused-variable\", args=(name,), node=node)\n \n+ def _is_used_in_type_comments(self, name, stmt):\n+ \"\"\"Check if the import is used in type comments.\"\"\"\n+ for comment in stmt.root().comments:\n+ if name in comment.value:\n+ return True\n+ return False\n+\n def _check_imports(self, not_consumed):\n local_names = _fix_dot_imports(not_consumed)\n checked = set()\n@@ -2030,6 +2037,10 @@ class VariablesChecker(BaseChecker):\n continue\n checked.add(real_name)\n \n+ # Check if the import is used in type comments\n+ if self._is_used_in_type_comments(name, stmt):\n+ continue\n+\n is_type_annotation_import = (\n imported_name in self._type_annotation_names\n or as_name in self._type_annotation_names\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 253375, + "num_received_chars": 5085, + "elapsed_time": 49.61838173866272, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-6386.json b/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-6386.json new file mode 100644 index 00000000..687b1033 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-6386.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pylint-dev__pylint-6386", + "edit_test_file": "tests/config/test_argparse_config.py", + "code_patch": "diff --git a/pylint/lint/base_options.py b/pylint/lint/base_options.py\nindex c793cc8..df34d8b 100644\n--- a/pylint/lint/base_options.py\n+++ b/pylint/lint/base_options.py\n@@ -538,11 +538,9 @@ def _make_run_options(self: Run) -> Options:\n (\n \"verbose\",\n {\n- \"action\": _DoNothingAction,\n- \"kwargs\": {},\n+ \"action\": \"store_true\",\n \"short\": \"v\",\n- \"help\": \"In verbose mode, extra non-checker-related info \"\n- \"will be displayed.\",\n+ \"help\": \"Enable verbose mode to display extra non-checker-related info.\",\n \"hide_from_config_file\": True,\n },\n ),\n", + "test_patch": "diff --git a/tests/config/test_verbose_option.py b/tests/config/test_verbose_option.py\nnew file mode 100644\nindex 0000000..15bbd4f\n--- /dev/null\n+++ b/tests/config/test_verbose_option.py\n@@ -0,0 +1,20 @@\n+# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html\n+# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE\n+# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt\n+\n+\"\"\"Test for the verbose option behavior with short option.\"\"\"\n+\n+import pytest\n+from pylint.lint import Run\n+from os.path import abspath, dirname, join\n+\n+HERE = abspath(dirname(__file__))\n+REGRTEST_DATA_DIR = join(HERE, \"..\", \"regrtest_data\")\n+EMPTY_MODULE = join(REGRTEST_DATA_DIR, \"empty.py\")\n+\n+def test_verbose_short_option_requires_argument(capsys):\n+ \"\"\"Check that the short verbose option '-v' incorrectly expects an argument.\"\"\"\n+ with pytest.raises(SystemExit):\n+ Run([str(EMPTY_MODULE), \"-v\"], exit=False)\n+ output = capsys.readouterr()\n+ assert \"argument --verbose/-v: expected one argument\" in output.err\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/config/test_verbose_option_inverted.py b/tests/config/test_verbose_option_inverted.py\nnew file mode 100644\nindex 0000000..d84de7e\n--- /dev/null\n+++ b/tests/config/test_verbose_option_inverted.py\n@@ -0,0 +1,20 @@\n+# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html\n+# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE\n+# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt\n+\n+\"\"\"Test for the verbose option behavior with short option.\"\"\"\n+\n+import pytest\n+from pylint.lint import Run\n+from os.path import abspath, dirname, join\n+\n+HERE = abspath(dirname(__file__))\n+REGRTEST_DATA_DIR = join(HERE, \"..\", \"regrtest_data\")\n+EMPTY_MODULE = join(REGRTEST_DATA_DIR, \"empty.py\")\n+\n+def test_verbose_short_option_requires_argument(capsys):\n+ \"\"\"Check that the short verbose option '-v' incorrectly expects an argument.\"\"\"\n+ with pytest.raises(SystemExit):\n+ Run([str(EMPTY_MODULE), \"-v\"], exit=False)\n+ output = capsys.readouterr()\n+ assert \"argument --verbose/-v: expected one argument\" not in output.err, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1121115, + "num_received_chars": 36912, + "elapsed_time": 297.21517634391785, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-7080.json b/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-7080.json new file mode 100644 index 00000000..50ad0b4c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pylint-dev__pylint-7080.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pylint-dev__pylint-7080", + "edit_test_file": null, + "code_patch": "diff --git a/pylint/lint/expand_modules.py b/pylint/lint/expand_modules.py\nindex 5cacc03..ddf2cbb 100644\n--- a/pylint/lint/expand_modules.py\n+++ b/pylint/lint/expand_modules.py\n@@ -57,6 +57,7 @@ def _is_ignored_file(\n basename in ignore_list\n or _is_in_ignore_list_re(basename, ignore_list_re)\n or _is_in_ignore_list_re(element, ignore_list_paths_re)\n+ or any(re.match(pattern, element) for pattern in ignore_list_paths_re)\n )\n \n \n@@ -74,30 +75,32 @@ def expand_modules(\n path = sys.path.copy()\n \n for something in files_or_modules:\n- basename = os.path.basename(something)\n- if _is_ignored_file(\n- something, ignore_list, ignore_list_re, ignore_list_paths_re\n- ):\n- continue\n- module_path = get_python_path(something)\n- additional_search_path = [\".\", module_path] + path\n- if os.path.exists(something):\n- # this is a file or a directory\n- try:\n- modname = \".\".join(\n- modutils.modpath_from_file(something, path=additional_search_path)\n- )\n- except ImportError:\n- modname = os.path.splitext(basename)[0]\n- if os.path.isdir(something):\n- filepath = os.path.join(something, \"__init__.py\")\n+ basename = os.path.basename(something)\n+ if _is_ignored_file(\n+ something, ignore_list, ignore_list_re, ignore_list_paths_re\n+ ):\n+ continue\n+ module_path = get_python_path(something)\n+ additional_search_path = [\".\", module_path] + path\n+ if os.path.exists(something):\n+ # this is a file or a directory\n+ if any(re.match(pattern, something) for pattern in ignore_list_paths_re):\n+ continue\n+ try:\n+ modname = \".\".join(\n+ modutils.modpath_from_file(something, path=additional_search_path)\n+ )\n+ except ImportError:\n+ modname = os.path.splitext(basename)[0]\n+ if os.path.isdir(something):\n+ filepath = os.path.join(something, \"__init__.py\")\n+ else:\n+ filepath = something\n else:\n- filepath = something\n- else:\n- # suppose it's a module or package\n- modname = something\n- try:\n- filepath = modutils.file_from_modpath(\n+ # suppose it's a module or package\n+ modname = something\n+ try:\n+ filepath = modutils.file_from_modpath(\n modname.split(\".\"), path=additional_search_path\n )\n if filepath is None:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 473596, + "num_received_chars": 15736, + "elapsed_time": 101.2865617275238, + "lint_repair_count": 1, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-10051.json b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-10051.json new file mode 100644 index 00000000..696430d7 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-10051.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-10051", + "edit_test_file": "testing/test_recwarn.py", + "code_patch": "diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py\nindex a4f4214..69a16bd 100644\n--- a/src/_pytest/logging.py\n+++ b/src/_pytest/logging.py\n@@ -396,7 +396,8 @@ class LogCaptureFixture:\n \n .. versionadded:: 3.4\n \"\"\"\n- return self._item.stash[caplog_records_key].get(when, [])\n+ # Ensure it always reflects the current state of records\n+ return self._item.stash[caplog_records_key].setdefault(when, [])\n \n @property\n def text(self) -> str:\n@@ -441,6 +442,8 @@ class LogCaptureFixture:\n def clear(self) -> None:\n \"\"\"Reset the list of log records and the captured log text.\"\"\"\n self.handler.reset()\n+ # Ensure that the records list is cleared without replacing it\n+ self._item.stash[caplog_records_key] = {when: [] for when in (\"setup\", \"call\", \"teardown\")}\n \n def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None:\n \"\"\"Set the level of a logger for the duration of a test.\n", + "test_patch": "diff --git a/testing/test_caplog_conflict.py b/testing/test_caplog_conflict.py\nnew file mode 100644\nindex 0000000..f0856d7\n--- /dev/null\n+++ b/testing/test_caplog_conflict.py\n@@ -0,0 +1,13 @@\n+import logging\n+import pytest\n+\n+def test_caplog_get_records_and_clear_conflict(caplog) -> None:\n+ def verify_consistency() -> None:\n+ assert caplog.get_records(\"call\") == caplog.records\n+\n+ verify_consistency()\n+ logging.warning(\"test\")\n+ verify_consistency()\n+ caplog.clear()\n+ with pytest.raises(AssertionError):\n+ verify_consistency() # This should fail due to the issue described\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/testing/test_caplog_conflict_inverted.py b/testing/test_caplog_conflict_inverted.py\nnew file mode 100644\nindex 0000000..9fa0f84\n--- /dev/null\n+++ b/testing/test_caplog_conflict_inverted.py\n@@ -0,0 +1,12 @@\n+import logging\n+import pytest\n+\n+def test_caplog_get_records_and_clear_conflict(caplog) -> None:\n+ def verify_consistency() -> None:\n+ assert caplog.get_records(\"call\") == caplog.records, \"__BUG__HERE__\"\n+\n+ verify_consistency()\n+ logging.warning(\"test\")\n+ verify_consistency()\n+ caplog.clear()\n+ verify_consistency() # This should now fail with \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1160172, + "num_received_chars": 31000, + "elapsed_time": 188.46380424499512, + "lint_repair_count": 6, + "test_generation_attempts": 1, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5262.json b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5262.json new file mode 100644 index 00000000..475d97c2 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5262.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-5262", + "edit_test_file": null, + "code_patch": "diff --git a/src/_pytest/capture.py b/src/_pytest/capture.py\nindex 25eab7f..687d142 100644\n--- a/src/_pytest/capture.py\n+++ b/src/_pytest/capture.py\n@@ -423,6 +423,10 @@ def safe_text_dupfile(f, mode, default_encoding=\"UTF8\"):\n \n \n class EncodedFile(object):\n+ \"\"\"\n+ EncodedFile is a wrapper around a buffer that ensures text data is written.\n+ It does not support binary data.\n+ \"\"\"\n errors = \"strict\" # possibly needed by py3 code (issue555)\n \n def __init__(self, buffer, encoding):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1194059, + "num_received_chars": 24420, + "elapsed_time": 216.2554533481598, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5809.json b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5809.json new file mode 100644 index 00000000..0e2f31dc --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-5809.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-5809", + "edit_test_file": "testing/test_pastebin.py", + "code_patch": "diff --git a/src/_pytest/pastebin.py b/src/_pytest/pastebin.py\nindex 41576a6..79b0d9d 100644\n--- a/src/_pytest/pastebin.py\n+++ b/src/_pytest/pastebin.py\n@@ -79,7 +79,7 @@ def create_new_paste(contents):\n \n params = {\n \"code\": contents,\n- \"lexer\": \"python3\" if sys.version_info[0] >= 3 else \"python\",\n+ \"lexer\": \"text\",\n \"expiry\": \"1week\",\n }\n url = \"https://bpaste.net\"\n", + "test_patch": "diff --git a/testing/test_pastebin_http_error.py b/testing/test_pastebin_http_error.py\nnew file mode 100644\nindex 0000000..5fe9dc2\n--- /dev/null\n+++ b/testing/test_pastebin_http_error.py\n@@ -0,0 +1,35 @@\n+# -*- coding: utf-8 -*-\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+import pytest\n+import sys\n+from urllib.error import HTTPError\n+\n+class TestPastebinHTTPError:\n+ @pytest.fixture\n+ def pastebin(self, request):\n+ return request.config.pluginmanager.getplugin(\"pastebin\")\n+\n+ @pytest.fixture\n+ def mocked_urlopen(self, monkeypatch):\n+ \"\"\"\n+ Monkeypatch the actual urlopen calls done by the internal plugin\n+ function that connects to bpaste service.\n+ \"\"\"\n+ def mocked(url, data):\n+ raise HTTPError(url, 400, \"Bad Request\", hdrs=None, fp=None)\n+\n+ if sys.version_info < (3, 0):\n+ import urllib\n+ monkeypatch.setattr(urllib, \"urlopen\", mocked)\n+ else:\n+ import urllib.request\n+ monkeypatch.setattr(urllib.request, \"urlopen\", mocked)\n+\n+ def test_lexer_python3_causes_http_error(self, pastebin, mocked_urlopen):\n+ with pytest.raises(HTTPError) as excinfo:\n+ pastebin.create_new_paste(b\"example content that causes error\")\n+ assert excinfo.value.code == 400\n+ assert \"Bad Request\" in str(excinfo.value)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/testing/test_pastebin_http_error_inverted.py b/testing/test_pastebin_http_error_inverted.py\nnew file mode 100644\nindex 0000000..fdbaee6\n--- /dev/null\n+++ b/testing/test_pastebin_http_error_inverted.py\n@@ -0,0 +1,36 @@\n+# -*- coding: utf-8 -*-\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+import pytest\n+import sys\n+from urllib.error import HTTPError\n+\n+class TestPastebinHTTPError:\n+ @pytest.fixture\n+ def pastebin(self, request):\n+ return request.config.pluginmanager.getplugin(\"pastebin\")\n+\n+ @pytest.fixture\n+ def mocked_urlopen(self, monkeypatch):\n+ \"\"\"\n+ Monkeypatch the actual urlopen calls done by the internal plugin\n+ function that connects to bpaste service.\n+ \"\"\"\n+ def mocked(url, data):\n+ raise HTTPError(url, 400, \"Bad Request\", hdrs=None, fp=None)\n+\n+ if sys.version_info < (3, 0):\n+ import urllib\n+ monkeypatch.setattr(urllib, \"urlopen\", mocked)\n+ else:\n+ import urllib.request\n+ monkeypatch.setattr(urllib.request, \"urlopen\", mocked)\n+\n+ def test_lexer_python3_causes_http_error(self, pastebin, mocked_urlopen):\n+ with pytest.raises(HTTPError) as excinfo:\n+ pastebin.create_new_paste(b\"example content that causes error\")\n+ assert excinfo.value.code == 400\n+ assert \"Bad Request\" in str(excinfo.value)\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1034660, + "num_received_chars": 19078, + "elapsed_time": 189.88668084144592, + "lint_repair_count": 0, + "test_generation_attempts": 7, + "code_generation_attempts": 3, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-6202.json b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-6202.json new file mode 100644 index 00000000..1dad5a37 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-6202.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-6202", + "edit_test_file": "testing/test_assertion.py", + "code_patch": "diff --git a/src/_pytest/terminal.py b/src/_pytest/terminal.py\nindex 0d97941..72d54d3 100644\n--- a/src/_pytest/terminal.py\n+++ b/src/_pytest/terminal.py\n@@ -703,7 +703,7 @@ class TerminalReporter:\n if domain and line.endswith(domain):\n line = line[: -len(domain)]\n values = domain.split(\"[\")\n- values[0] = values[0].replace(\".\", \"::\") # don't replace '.' in params\n+ # Removed unnecessary replacement that caused issues\n line += \"[\".join(values)\n return line\n \n", + "test_patch": "diff --git a/testing/test_parametrize_issue.py b/testing/test_parametrize_issue.py\nnew file mode 100644\nindex 0000000..49481f5\n--- /dev/null\n+++ b/testing/test_parametrize_issue.py\n@@ -0,0 +1,21 @@\n+import pytest\n+\n+def test_parametrization_issue(testdir):\n+ # Create a test file with the issue\n+ testdir.makepyfile(\n+ \"\"\"\n+ import pytest\n+\n+ @pytest.mark.parametrize(\"a\", [\"..[\"])\n+ def test_boo(a):\n+ assert 0\n+ \"\"\"\n+ )\n+\n+ # Run pytest and capture the output\n+ result = testdir.runpytest()\n+\n+ # Check that the output contains the incorrect headline\n+ result.stdout.fnmatch_lines([\n+ \"*test_boo[.[]*\"\n+ ])\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2230095, + "num_received_chars": 46956, + "elapsed_time": 394.8738429546356, + "lint_repair_count": 6, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7324.json b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7324.json new file mode 100644 index 00000000..e8c107dc --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7324.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-7324", + "edit_test_file": null, + "code_patch": "diff --git a/doc/en/example/assertion/failure_demo.py b/doc/en/example/assertion/failure_demo.py\nindex 4bf8279..a3d2a0e 100644\n--- a/doc/en/example/assertion/failure_demo.py\n+++ b/doc/en/example/assertion/failure_demo.py\n@@ -4,7 +4,8 @@ from pytest import raises\n \n \n def otherfunc(a, b):\n- assert a == b\n+ if not a == b:\n+ raise AssertionError(f\"Expected {a} to be equal to {b}\")\n \n \n def somefunc(x, y):\n@@ -12,7 +13,8 @@ def somefunc(x, y):\n \n \n def otherfunc_multi(a, b):\n- assert a == b\n+ if not a == b:\n+ raise AssertionError(f\"Expected {a} to be equal to {b}\")\n \n \n @pytest.mark.parametrize(\"param1, param2\", [(3, 6)])\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 945646, + "num_received_chars": 10882, + "elapsed_time": 151.08438181877136, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7521.json b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7521.json new file mode 100644 index 00000000..dfc5231c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-7521.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-7521", + "edit_test_file": null, + "code_patch": "diff --git a/doc/en/example/assertion/failure_demo.py b/doc/en/example/assertion/failure_demo.py\nindex a172a00..c4bfc02 100644\n--- a/doc/en/example/assertion/failure_demo.py\n+++ b/doc/en/example/assertion/failure_demo.py\n@@ -32,6 +32,11 @@ class TestFailing:\n def test_simple_multiline(self):\n otherfunc_multi(42, 6 * 9)\n \n+ def test_capfd_output(self, capfd):\n+ print(\"Hello\\rWorld\", end=\"\")\n+ out, err = capfd.readouterr()\n+ assert out.endswith(\"World\") # Adjusted to check for 'World' instead of '\\r'\n+\n def test_not(self):\n def f():\n return 42\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 441726, + "num_received_chars": 7285, + "elapsed_time": 56.092406272888184, + "lint_repair_count": 1, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-8399.json b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-8399.json new file mode 100644 index 00000000..45d5dcdd --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/pytest-dev__pytest-8399.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-8399", + "edit_test_file": null, + "code_patch": "diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst\nindex a6ce2e7..5c043af 100644\n--- a/doc/en/example/pythoncollection.rst\n+++ b/doc/en/example/pythoncollection.rst\n@@ -1,6 +1,13 @@\n Changing standard (Python) test discovery\n ===============================================\n \n+.. note::\n+\n+ As of pytest 6.2.0, `setUpClass` fixtures for `unittest.TestCase` classes are no longer private.\n+ They are listed by `pytest --fixtures` without needing additional verbosity flags. This change\n+ may reveal fixtures without docstrings, potentially causing issues with code quality checks.\n+ Consider using pytest options to suppress output or control fixture visibility manually.\n+\n Ignore paths during test collection\n -----------------------------------\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1173954, + "num_received_chars": 19232, + "elapsed_time": 199.07079696655273, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-10908.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-10908.json new file mode 100644 index 00000000..e9ee7f41 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-10908.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-10908", + "edit_test_file": "sklearn/feature_extraction/tests/test_text.py", + "code_patch": "diff --git a/sklearn/feature_extraction/text.py b/sklearn/feature_extraction/text.py\nindex 9b1ebd6..8878dda 100644\n--- a/sklearn/feature_extraction/text.py\n+++ b/sklearn/feature_extraction/text.py\n@@ -993,6 +993,12 @@ class CountVectorizer(BaseEstimator, VectorizerMixin):\n \n def get_feature_names(self):\n \"\"\"Array mapping from feature integer indices to feature name\"\"\"\n+ if not hasattr(self, 'vocabulary_'):\n+ if self.vocabulary is not None:\n+ self._validate_vocabulary()\n+ else:\n+ raise ValueError(\"Vocabulary wasn't fitted or provided\")\n+\n self._check_vocabulary()\n \n return [t for t, i in sorted(six.iteritems(self.vocabulary_),\n", + "test_patch": "diff --git a/sklearn/feature_extraction/tests/test_count_vectorizer_vocabulary.py b/sklearn/feature_extraction/tests/test_count_vectorizer_vocabulary.py\nnew file mode 100644\nindex 0000000..3508b0f\n--- /dev/null\n+++ b/sklearn/feature_extraction/tests/test_count_vectorizer_vocabulary.py\n@@ -0,0 +1,10 @@\n+from sklearn.feature_extraction.text import CountVectorizer\n+from sklearn.utils.testing import assert_raises\n+\n+def test_countvectorizer_get_feature_names_with_vocabulary():\n+ # Initialize CountVectorizer with a predefined vocabulary\n+ vocabulary = ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']\n+ vectorizer = CountVectorizer(vocabulary=vocabulary)\n+\n+ # Check if NotFittedError is raised when calling get_feature_names\n+ assert_raises(ValueError, vectorizer.get_feature_names)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/feature_extraction/tests/test_count_vectorizer_vocabulary_inverted.py b/sklearn/feature_extraction/tests/test_count_vectorizer_vocabulary_inverted.py\nnew file mode 100644\nindex 0000000..736aa1d\n--- /dev/null\n+++ b/sklearn/feature_extraction/tests/test_count_vectorizer_vocabulary_inverted.py\n@@ -0,0 +1,11 @@\n+from sklearn.feature_extraction.text import CountVectorizer\n+import pytest\n+\n+def test_countvectorizer_get_feature_names_with_vocabulary():\n+ # Initialize CountVectorizer with a predefined vocabulary\n+ vocabulary = ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']\n+ vectorizer = CountVectorizer(vocabulary=vocabulary)\n+\n+ # Check if ValueError is raised when calling get_feature_names\n+ with pytest.raises(ValueError, match=\"__BUG__HERE__\"):\n+ vectorizer.get_feature_names()\n\\ No newline at end of file\n", + "num_sent_chars": 1486314, + "num_received_chars": 39145, + "elapsed_time": 312.6574831008911, + "lint_repair_count": 5, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-12585.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-12585.json new file mode 100644 index 00000000..43cbb6cc --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-12585.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-12585", + "edit_test_file": "sklearn/tests/test_base.py", + "code_patch": "diff --git a/sklearn/base.py b/sklearn/base.py\nindex 56ffb18..f7ccf8f 100644\n--- a/sklearn/base.py\n+++ b/sklearn/base.py\n@@ -48,6 +48,14 @@ def clone(estimator, safe=True):\n # XXX: not handling dictionaries\n if estimator_type in (list, tuple, set, frozenset):\n return estimator_type([clone(e, safe=safe) for e in estimator])\n+ elif isinstance(estimator, type):\n+ # Handle the case where the estimator is a class type\n+ if not safe:\n+ return copy.deepcopy(estimator)\n+ else:\n+ raise TypeError(\"Cannot clone object '%s' (type %s): \"\n+ \"it is a class type and does not implement a 'get_params' method.\"\n+ % (repr(estimator), type(estimator)))\n elif not hasattr(estimator, 'get_params'):\n if not safe:\n return copy.deepcopy(estimator)\n", + "test_patch": "diff --git a/sklearn/tests/test_clone_issue.py b/sklearn/tests/test_clone_issue.py\nnew file mode 100644\nindex 0000000..eb707e5\n--- /dev/null\n+++ b/sklearn/tests/test_clone_issue.py\n@@ -0,0 +1,15 @@\n+import unittest\n+from sklearn.preprocessing import StandardScaler\n+from sklearn.base import clone\n+\n+class TestCloneIssue(unittest.TestCase):\n+ def test_clone_with_estimator_class_as_parameter(self):\n+ # Attempt to clone an estimator with another estimator class as a parameter\n+ with self.assertRaises(TypeError) as context:\n+ clone(StandardScaler(with_mean=StandardScaler))\n+ \n+ # Check if the error message matches the expected TypeError\n+ self.assertIn(\"get_params() missing 1 required positional argument: 'self'\", str(context.exception))\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/tests/test_clone_issue_inverted.py b/sklearn/tests/test_clone_issue_inverted.py\nnew file mode 100644\nindex 0000000..d38fa4a\n--- /dev/null\n+++ b/sklearn/tests/test_clone_issue_inverted.py\n@@ -0,0 +1,16 @@\n+import unittest\n+from sklearn.preprocessing import StandardScaler\n+from sklearn.base import clone\n+\n+class TestCloneIssue(unittest.TestCase):\n+ def test_clone_with_estimator_class_as_parameter(self):\n+ # Attempt to clone an estimator with another estimator class as a parameter\n+ try:\n+ clone(StandardScaler(with_mean=StandardScaler))\n+ except TypeError as e:\n+ # Check if the error message matches the expected TypeError\n+ if \"get_params() missing 1 required positional argument: 'self'\" in str(e):\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 429024, + "num_received_chars": 10813, + "elapsed_time": 95.76400446891785, + "lint_repair_count": 0, + "test_generation_attempts": 2, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13124.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13124.json new file mode 100644 index 00000000..ad77bdca --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13124.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-13124", + "edit_test_file": null, + "code_patch": "diff --git a/sklearn/utils/seq_dataset.pyx b/sklearn/utils/seq_dataset.pyx\nindex 5fd2ca9..684835a 100644\n--- a/sklearn/utils/seq_dataset.pyx\n+++ b/sklearn/utils/seq_dataset.pyx\n@@ -115,15 +115,27 @@ cdef class SequentialDataset:\n current_index)\n return current_index\n \n- cdef void shuffle(self, np.uint32_t seed) nogil:\n- \"\"\"Permutes the ordering of examples.\"\"\"\n- # Fisher-Yates shuffle\n+ cdef void shuffle(self, np.uint32_t seed, np.ndarray[int, ndim=1] y=None) nogil:\n+ \"\"\"Permutes the ordering of examples, optionally within each stratum.\"\"\"\n cdef int *ind = self.index_data_ptr\n cdef int n = self.n_samples\n cdef unsigned i, j\n- for i in range(n - 1):\n- j = i + our_rand_r(&seed) % (n - i)\n- ind[i], ind[j] = ind[j], ind[i]\n+\n+ if y is not None:\n+ # Shuffle within each stratum\n+ cdef int start, end\n+ cdef int unique_classes = np.unique(y)\n+ for cls in unique_classes:\n+ start = np.min(np.where(y == cls))\n+ end = np.max(np.where(y == cls)) + 1\n+ for i in range(start, end - 1):\n+ j = i + our_rand_r(&seed) % (end - i)\n+ ind[i], ind[j] = ind[j], ind[i]\n+ else:\n+ # Fisher-Yates shuffle\n+ for i in range(n - 1):\n+ j = i + our_rand_r(&seed) % (n - i)\n+ ind[i], ind[j] = ind[j], ind[i]\n \n cdef int _get_next_index(self) nogil:\n cdef int current_index = self.current_index\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2004265, + "num_received_chars": 57182, + "elapsed_time": 335.64291882514954, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 6, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13328.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13328.json new file mode 100644 index 00000000..6a52f7ad --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13328.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-13328", + "edit_test_file": "sklearn/linear_model/tests/test_huber.py", + "code_patch": "diff --git a/sklearn/linear_model/huber.py b/sklearn/linear_model/huber.py\nindex 65c6864..fb9edf7 100644\n--- a/sklearn/linear_model/huber.py\n+++ b/sklearn/linear_model/huber.py\n@@ -250,6 +250,9 @@ class HuberRegressor(LinearModel, RegressorMixin, BaseEstimator):\n -------\n self : object\n \"\"\"\n+ # Convert boolean arrays to float\n+ if X.dtype == bool:\n+ X = X.astype(float)\n X, y = check_X_y(\n X, y, copy=False, accept_sparse=['csr'], y_numeric=True)\n if sample_weight is not None:\n", + "test_patch": "diff --git a/sklearn/linear_model/tests/test_huber_regressor_boolean.py b/sklearn/linear_model/tests/test_huber_regressor_boolean.py\nnew file mode 100644\nindex 0000000..a7af0ee\n--- /dev/null\n+++ b/sklearn/linear_model/tests/test_huber_regressor_boolean.py\n@@ -0,0 +1,13 @@\n+import numpy as np\n+import pytest\n+from sklearn.datasets import make_regression\n+from sklearn.linear_model import HuberRegressor\n+\n+def test_huber_regressor_with_boolean_X():\n+ # Generate random data\n+ X, y, _ = make_regression(n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)\n+ X_bool = X > 0\n+\n+ # Expect a TypeError when fitting HuberRegressor with boolean X\n+ with pytest.raises(TypeError, match=\"The numpy boolean negative, the `-` operator, is not supported\"):\n+ huber = HuberRegressor().fit(X_bool, y)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/linear_model/tests/test_huber_regressor_boolean_inverted.py b/sklearn/linear_model/tests/test_huber_regressor_boolean_inverted.py\nnew file mode 100644\nindex 0000000..8d1d834\n--- /dev/null\n+++ b/sklearn/linear_model/tests/test_huber_regressor_boolean_inverted.py\n@@ -0,0 +1,15 @@\n+import numpy as np\n+import pytest\n+from sklearn.datasets import make_regression\n+from sklearn.linear_model import HuberRegressor\n+\n+def test_huber_regressor_with_boolean_X():\n+ # Generate random data\n+ X, y, _ = make_regression(n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)\n+ X_bool = X > 0\n+\n+ # Alter the test to fail when the issue is observed\n+ try:\n+ huber = HuberRegressor().fit(X_bool, y)\n+ except TypeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 468673, + "num_received_chars": 10813, + "elapsed_time": 137.8369710445404, + "lint_repair_count": 0, + "test_generation_attempts": 2, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13779.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13779.json new file mode 100644 index 00000000..7aba69bd --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-13779.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-13779", + "edit_test_file": "sklearn/ensemble/tests/test_voting.py", + "code_patch": "diff --git a/sklearn/ensemble/voting.py b/sklearn/ensemble/voting.py\nindex 7afa718..8e5c19d 100644\n--- a/sklearn/ensemble/voting.py\n+++ b/sklearn/ensemble/voting.py\n@@ -76,24 +76,25 @@ class _BaseVoting(_BaseComposition, TransformerMixin):\n '; got %d weights, %d estimators'\n % (len(self.weights), len(self.estimators)))\n \n+ valid_estimators = [(name, step) for name, step in self.estimators if step is not None]\n+\n if sample_weight is not None:\n- for name, step in self.estimators:\n+ for name, step in valid_estimators:\n if not has_fit_parameter(step, 'sample_weight'):\n raise ValueError('Underlying estimator \\'%s\\' does not'\n ' support sample weights.' % name)\n \n- names, clfs = zip(*self.estimators)\n- self._validate_names(names)\n-\n- n_isnone = np.sum([clf is None for _, clf in self.estimators])\n- if n_isnone == len(self.estimators):\n+ if not valid_estimators:\n raise ValueError('All estimators are None. At least one is '\n 'required!')\n \n+ names, clfs = zip(*valid_estimators)\n+ self._validate_names(names)\n+\n self.estimators_ = Parallel(n_jobs=self.n_jobs)(\n delayed(_parallel_fit_estimator)(clone(clf), X, y,\n sample_weight=sample_weight)\n- for clf in clfs if clf is not None)\n+ for clf in clfs)\n \n self.named_estimators_ = Bunch()\n for k, e in zip(self.estimators, self.estimators_):\n", + "test_patch": "diff --git a/sklearn/ensemble/tests/test_weighted_estimator.py b/sklearn/ensemble/tests/test_weighted_estimator.py\nnew file mode 100644\nindex 0000000..50bbe51\n--- /dev/null\n+++ b/sklearn/ensemble/tests/test_weighted_estimator.py\n@@ -0,0 +1,17 @@\n+import numpy as np\n+from sklearn.linear_model import LogisticRegression\n+from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n+from sklearn.datasets import load_iris\n+from sklearn.utils.testing import assert_raise_message\n+\n+def test_voting_classifier_with_none_estimator_and_weights():\n+ \"\"\"Test VotingClassifier with None estimator and sample weights.\"\"\"\n+ X, y = load_iris(return_X_y=True)\n+ voter = VotingClassifier(\n+ estimators=[('lr', LogisticRegression()),\n+ ('rf', RandomForestClassifier())]\n+ )\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ voter.set_params(lr=None)\n+ msg = \"'NoneType' object has no attribute 'fit'\"\n+ assert_raise_message(AttributeError, msg, voter.fit, X, y, sample_weight=np.ones(y.shape))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/ensemble/tests/test_weighted_estimator_inverted.py b/sklearn/ensemble/tests/test_weighted_estimator_inverted.py\nnew file mode 100644\nindex 0000000..a767d4d\n--- /dev/null\n+++ b/sklearn/ensemble/tests/test_weighted_estimator_inverted.py\n@@ -0,0 +1,19 @@\n+import numpy as np\n+from sklearn.linear_model import LogisticRegression\n+from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n+from sklearn.datasets import load_iris\n+import pytest\n+\n+def test_voting_classifier_with_none_estimator_and_weights():\n+ \"\"\"Test VotingClassifier with None estimator and sample weights.\"\"\"\n+ X, y = load_iris(return_X_y=True)\n+ voter = VotingClassifier(\n+ estimators=[('lr', LogisticRegression()),\n+ ('rf', RandomForestClassifier())]\n+ )\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ voter.set_params(lr=None)\n+ \n+ # The test should now fail with the specific error message when the bug is observed\n+ with pytest.raises(AttributeError, match=\"__BUG__HERE__\"):\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n\\ No newline at end of file\n", + "num_sent_chars": 1137266, + "num_received_chars": 41586, + "elapsed_time": 313.91854786872864, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14141.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14141.json new file mode 100644 index 00000000..d0188740 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14141.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-14141", + "edit_test_file": "sklearn/utils/tests/test_show_versions.py", + "code_patch": "diff --git a/sklearn/utils/_show_versions.py b/sklearn/utils/_show_versions.py\nindex e5d3141..dd867c8 100644\n--- a/sklearn/utils/_show_versions.py\n+++ b/sklearn/utils/_show_versions.py\n@@ -50,6 +50,15 @@ def _get_deps_info():\n \"matplotlib\",\n ]\n \n+ # Conditionally include joblib for sklearn versions > 0.20\n+ try:\n+ import sklearn\n+ from distutils.version import LooseVersion\n+ if LooseVersion(sklearn.__version__) > LooseVersion(\"0.20\"):\n+ deps.append(\"joblib\")\n+ except ImportError:\n+ pass\n+\n def get_version(module):\n return module.__version__\n \n", + "test_patch": "diff --git a/sklearn/utils/tests/test_dependency_management.py b/sklearn/utils/tests/test_dependency_management.py\nnew file mode 100644\nindex 0000000..2e25146\n--- /dev/null\n+++ b/sklearn/utils/tests/test_dependency_management.py\n@@ -0,0 +1,8 @@\n+from sklearn.utils._show_versions import _get_deps_info\n+import pytest\n+\n+def test_joblib_in_deps_info():\n+ deps_info = _get_deps_info()\n+\n+ # Check if 'joblib' is missing in the dependencies info\n+ assert 'joblib' not in deps_info, \"joblib should not be listed in dependencies for sklearn version <= 0.20\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/utils/tests/test_dependency_management_inverted.py b/sklearn/utils/tests/test_dependency_management_inverted.py\nnew file mode 100644\nindex 0000000..ed27c34\n--- /dev/null\n+++ b/sklearn/utils/tests/test_dependency_management_inverted.py\n@@ -0,0 +1,8 @@\n+from sklearn.utils._show_versions import _get_deps_info\n+import pytest\n+\n+def test_joblib_in_deps_info():\n+ deps_info = _get_deps_info()\n+\n+ # Check if 'joblib' is present in the dependencies info\n+ assert 'joblib' in deps_info, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 336409, + "num_received_chars": 5183, + "elapsed_time": 61.23228740692139, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14710.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14710.json new file mode 100644 index 00000000..a343a07c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-14710.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-14710", + "edit_test_file": "sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py", + "code_patch": "diff --git a/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py b/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\nindex ad6a5a8..1b520fa 100644\n--- a/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\n+++ b/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\n@@ -14,6 +14,7 @@ from ...utils.multiclass import check_classification_targets\n from ...metrics import check_scoring\n from ...model_selection import train_test_split\n from ...preprocessing import LabelEncoder\n+from ...utils.multiclass import type_of_target\n from ._gradient_boosting import _update_raw_predictions\n from .common import Y_DTYPE, X_DTYPE, X_BINNED_DTYPE\n \n@@ -426,11 +427,19 @@ class BaseHistGradientBoosting(BaseEstimator, ABC):\n \n Scores are computed on validation data or on training data.\n \"\"\"\n+ # Ensure y_small_train is encoded if necessary\n+ if type_of_target(y_small_train) == 'binary' or type_of_target(y_small_train) == 'multiclass':\n+ y_small_train = self._encode_y(y_small_train)\n+ \n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n \n if self._use_validation_data:\n+ # Ensure y_val is encoded if necessary\n+ if type_of_target(y_val) == 'binary' or type_of_target(y_val) == 'multiclass':\n+ y_val = self._encode_y(y_val)\n+ \n self.validation_score_.append(\n self.scorer_(self, X_binned_val, y_val)\n )\n", + "test_patch": "diff --git a/sklearn/ensemble/_hist_gradient_boosting/tests/test_early_stopping_classifier.py b/sklearn/ensemble/_hist_gradient_boosting/tests/test_early_stopping_classifier.py\nnew file mode 100644\nindex 0000000..6d7a049\n--- /dev/null\n+++ b/sklearn/ensemble/_hist_gradient_boosting/tests/test_early_stopping_classifier.py\n@@ -0,0 +1,12 @@\n+import numpy as np\n+import pytest\n+from sklearn.experimental import enable_hist_gradient_boosting # noqa\n+from sklearn.ensemble import HistGradientBoostingClassifier\n+\n+def test_early_stopping_with_string_target():\n+ X = np.random.randn(100, 10)\n+ y = np.array(['x'] * 50 + ['y'] * 50, dtype=object)\n+ gbrt = HistGradientBoostingClassifier(n_iter_no_change=10)\n+ \n+ with pytest.raises(TypeError, match=\"<' not supported between instances of 'str' and 'float'\"):\n+ gbrt.fit(X, y)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/ensemble/_hist_gradient_boosting/tests/test_early_stopping_classifier_inverted.py b/sklearn/ensemble/_hist_gradient_boosting/tests/test_early_stopping_classifier_inverted.py\nnew file mode 100644\nindex 0000000..80ad9a0\n--- /dev/null\n+++ b/sklearn/ensemble/_hist_gradient_boosting/tests/test_early_stopping_classifier_inverted.py\n@@ -0,0 +1,19 @@\n+import numpy as np\n+import pytest\n+from sklearn.experimental import enable_hist_gradient_boosting # noqa\n+from sklearn.ensemble import HistGradientBoostingClassifier\n+\n+def test_early_stopping_with_string_target():\n+ X = np.random.randn(100, 10)\n+ y = np.array(['x'] * 50 + ['y'] * 50, dtype=object)\n+ gbrt = HistGradientBoostingClassifier(n_iter_no_change=10)\n+ \n+ try:\n+ gbrt.fit(X, y)\n+ except TypeError as e:\n+ if \"<' not supported between instances of 'str' and 'float'\" in str(e):\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ raise e\n+ else:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1368797, + "num_received_chars": 46775, + "elapsed_time": 658.9092829227448, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-15100.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-15100.json new file mode 100644 index 00000000..61d2e9a5 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-15100.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-15100", + "edit_test_file": "sklearn/feature_extraction/tests/test_text.py", + "code_patch": "diff --git a/sklearn/feature_extraction/text.py b/sklearn/feature_extraction/text.py\nindex bb5a9d6..11236d9 100644\n--- a/sklearn/feature_extraction/text.py\n+++ b/sklearn/feature_extraction/text.py\n@@ -130,10 +130,7 @@ def strip_accents_unicode(s):\n ASCII equivalent.\n \"\"\"\n normalized = unicodedata.normalize('NFKD', s)\n- if normalized == s:\n- return s\n- else:\n- return ''.join([c for c in normalized if not unicodedata.combining(c)])\n+ return ''.join([c for c in normalized if not unicodedata.combining(c)])\n \n \n def strip_accents_ascii(s):\n", + "test_patch": "diff --git a/sklearn/feature_extraction/tests/test_strip_accents.py b/sklearn/feature_extraction/tests/test_strip_accents.py\nnew file mode 100644\nindex 0000000..e326b26\n--- /dev/null\n+++ b/sklearn/feature_extraction/tests/test_strip_accents.py\n@@ -0,0 +1,16 @@\n+# File: sklearn/feature_extraction/tests/test_strip_accents.py\n+\n+from sklearn.feature_extraction.text import strip_accents_unicode\n+\n+def test_strip_accents_unicode_nfkd():\n+ # This string contains one code point, \"LATIN SMALL LETTER N WITH TILDE\"\n+ s1 = chr(241)\n+\n+ # This string contains two code points, \"LATIN SMALL LETTER N\" followed by \"COMBINING TILDE\"\n+ s2 = chr(110) + chr(771)\n+\n+ # The tilde is removed from s1, as expected\n+ assert strip_accents_unicode(s1) == 'n'\n+\n+ # But strip_accents_unicode returns s2 unchanged\n+ assert strip_accents_unicode(s2) == s2\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/feature_extraction/tests/test_strip_accents_inverted.py b/sklearn/feature_extraction/tests/test_strip_accents_inverted.py\nnew file mode 100644\nindex 0000000..15f91cb\n--- /dev/null\n+++ b/sklearn/feature_extraction/tests/test_strip_accents_inverted.py\n@@ -0,0 +1,17 @@\n+# File: sklearn/feature_extraction/tests/test_strip_accents.py\n+\n+from sklearn.feature_extraction.text import strip_accents_unicode\n+\n+def test_strip_accents_unicode_nfkd():\n+ # This string contains one code point, \"LATIN SMALL LETTER N WITH TILDE\"\n+ s1 = chr(241)\n+\n+ # This string contains two code points, \"LATIN SMALL LETTER N\" followed by \"COMBINING TILDE\"\n+ s2 = chr(110) + chr(771)\n+\n+ # The tilde is removed from s1, as expected\n+ assert strip_accents_unicode(s1) == 'n'\n+\n+ # The test should fail here if the bug is present\n+ # Expecting s2 to be normalized to 'n', but it remains unchanged\n+ assert strip_accents_unicode(s2) == 'n', \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 471159, + "num_received_chars": 6574, + "elapsed_time": 63.108073234558105, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-25747.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-25747.json new file mode 100644 index 00000000..a4b4d134 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-25747.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-25747", + "edit_test_file": "sklearn/tests/test_pipeline.py", + "code_patch": "diff --git a/sklearn/utils/_set_output.py b/sklearn/utils/_set_output.py\nindex 335773c..8104056 100644\n--- a/sklearn/utils/_set_output.py\n+++ b/sklearn/utils/_set_output.py\n@@ -127,9 +127,13 @@ def _wrap_data_with_container(method, data_to_wrap, original_input, estimator):\n return data_to_wrap\n \n # dense_config == \"pandas\"\n+ index = getattr(original_input, \"index\", None)\n+ if index is not None and len(data_to_wrap) != len(original_input):\n+ index = None # Avoid index mismatch for aggregated data\n+\n return _wrap_in_pandas_container(\n data_to_wrap=data_to_wrap,\n- index=getattr(original_input, \"index\", None),\n+ index=index,\n columns=estimator.get_feature_names_out,\n )\n \n", + "test_patch": "diff --git a/sklearn/tests/test_feature_union.py b/sklearn/tests/test_feature_union.py\nnew file mode 100644\nindex 0000000..80ddad5\n--- /dev/null\n+++ b/sklearn/tests/test_feature_union.py\n@@ -0,0 +1,28 @@\n+# sklearn/tests/test_feature_union.py\n+\n+import pandas as pd\n+from sklearn.base import BaseEstimator, TransformerMixin\n+from sklearn import set_config\n+from sklearn.pipeline import make_union\n+import pytest\n+\n+class MyTransformer(BaseEstimator, TransformerMixin):\n+ def fit(self, X: pd.DataFrame, y: pd.Series = None, **kwargs):\n+ return self\n+\n+ def transform(self, X: pd.DataFrame, y: pd.Series = None) -> pd.DataFrame:\n+ return X[\"value\"].groupby(X[\"date\"]).sum()\n+\n+def test_feature_union_with_pandas_output():\n+ index = pd.date_range(start=\"2020-01-01\", end=\"2020-01-05\", inclusive=\"left\", freq=\"H\")\n+ data = pd.DataFrame(index=index, data=[10] * len(index), columns=[\"value\"])\n+ data[\"date\"] = index.date\n+\n+ # This works.\n+ set_config(transform_output=\"default\")\n+ make_union(MyTransformer()).fit_transform(data)\n+\n+ # This does not work.\n+ set_config(transform_output=\"pandas\")\n+ with pytest.raises(ValueError, match=\"Length mismatch: Expected axis has 4 elements, new values have 96 elements\"):\n+ make_union(MyTransformer()).fit_transform(data)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/tests/test_feature_union_inverted.py b/sklearn/tests/test_feature_union_inverted.py\nnew file mode 100644\nindex 0000000..404ae3a\n--- /dev/null\n+++ b/sklearn/tests/test_feature_union_inverted.py\n@@ -0,0 +1,28 @@\n+# sklearn/tests/test_feature_union.py\n+\n+import pandas as pd\n+from sklearn.base import BaseEstimator, TransformerMixin\n+from sklearn import set_config\n+from sklearn.pipeline import make_union\n+import pytest\n+\n+class MyTransformer(BaseEstimator, TransformerMixin):\n+ def fit(self, X: pd.DataFrame, y: pd.Series = None, **kwargs):\n+ return self\n+\n+ def transform(self, X: pd.DataFrame, y: pd.Series = None) -> pd.DataFrame:\n+ return X[\"value\"].groupby(X[\"date\"]).sum()\n+\n+def test_feature_union_with_pandas_output():\n+ index = pd.date_range(start=\"2020-01-01\", end=\"2020-01-05\", inclusive=\"left\", freq=\"H\")\n+ data = pd.DataFrame(index=index, data=[10] * len(index), columns=[\"value\"])\n+ data[\"date\"] = index.date\n+\n+ # This works.\n+ set_config(transform_output=\"default\")\n+ make_union(MyTransformer()).fit_transform(data)\n+\n+ # This does not work.\n+ set_config(transform_output=\"pandas\")\n+ with pytest.raises(ValueError, match=\"__BUG__HERE__\"):\n+ make_union(MyTransformer()).fit_transform(data)\n\\ No newline at end of file\n", + "num_sent_chars": 1492114, + "num_received_chars": 57083, + "elapsed_time": 378.40670108795166, + "lint_repair_count": 4, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-26194.json b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-26194.json new file mode 100644 index 00000000..74d957c1 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/scikit-learn__scikit-learn-26194.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-26194", + "edit_test_file": "sklearn/metrics/tests/test_common.py", + "code_patch": "diff --git a/sklearn/metrics/_ranking.py b/sklearn/metrics/_ranking.py\nindex 0cdead9..cd44367 100644\n--- a/sklearn/metrics/_ranking.py\n+++ b/sklearn/metrics/_ranking.py\n@@ -1083,7 +1083,10 @@ def roc_curve(\n # to make sure that the curve starts at (0, 0)\n tps = np.r_[0, tps]\n fps = np.r_[0, fps]\n- thresholds = np.r_[thresholds[0] + 1, thresholds]\n+ if thresholds[0] <= 1:\n+ thresholds = np.r_[1, thresholds] # Ensure the extra threshold does not exceed 1\n+ else:\n+ thresholds = np.r_[thresholds[0] + 1, thresholds]\n \n if fps[-1] <= 0:\n warnings.warn(\n", + "test_patch": "diff --git a/sklearn/metrics/tests/test_roc_curve_threshold_issue.py b/sklearn/metrics/tests/test_roc_curve_threshold_issue.py\nnew file mode 100644\nindex 0000000..439a5ce\n--- /dev/null\n+++ b/sklearn/metrics/tests/test_roc_curve_threshold_issue.py\n@@ -0,0 +1,12 @@\n+# File: sklearn/metrics/tests/test_roc_curve_threshold_issue.py\n+\n+import numpy as np\n+from sklearn.metrics import roc_curve\n+\n+def test_roc_curve_with_probability_estimates():\n+ rng = np.random.RandomState(42)\n+ y_true = rng.randint(0, 2, size=10)\n+ y_score = rng.rand(10)\n+ _, _, thresholds = roc_curve(y_true, y_score)\n+ # Assert that the issue is reproduced: thresholds can exceed 1\n+ assert (thresholds > 1).any(), \"Thresholds should exceed 1 to reproduce the issue\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/metrics/tests/test_roc_curve_threshold_issue_inverted.py b/sklearn/metrics/tests/test_roc_curve_threshold_issue_inverted.py\nnew file mode 100644\nindex 0000000..811537a\n--- /dev/null\n+++ b/sklearn/metrics/tests/test_roc_curve_threshold_issue_inverted.py\n@@ -0,0 +1,13 @@\n+# File: sklearn/metrics/tests/test_roc_curve_threshold_issue.py\n+\n+import numpy as np\n+from sklearn.metrics import roc_curve\n+\n+def test_roc_curve_with_probability_estimates():\n+ rng = np.random.RandomState(42)\n+ y_true = rng.randint(0, 2, size=10)\n+ y_score = rng.rand(10)\n+ _, _, thresholds = roc_curve(y_true, y_score)\n+ # Assert that the issue is NOT reproduced: thresholds should not exceed 1\n+ if (thresholds > 1).any():\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1198675, + "num_received_chars": 10803, + "elapsed_time": 191.7888572216034, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10323.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10323.json new file mode 100644 index 00000000..bc30db10 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10323.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-10323", + "edit_test_file": "tests/test_directive_code.py", + "code_patch": "diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py\nindex dc44ed3..f7d5c7c 100644\n--- a/sphinx/directives/code.py\n+++ b/sphinx/directives/code.py\n@@ -343,14 +343,20 @@ class LiteralIncludeReader:\n def prepend_filter(self, lines: List[str], location: Tuple[str, int] = None) -> List[str]:\n prepend = self.options.get('prepend')\n if prepend:\n- lines.insert(0, prepend + '\\n')\n+ # Calculate the leading whitespace from the first line of the included content\n+ leading_whitespace = len(lines[0]) - len(lines[0].lstrip())\n+ # Prepend the text with the calculated leading whitespace\n+ lines.insert(0, ' ' * leading_whitespace + prepend + '\\n')\n \n return lines\n \n def append_filter(self, lines: List[str], location: Tuple[str, int] = None) -> List[str]:\n append = self.options.get('append')\n if append:\n- lines.append(append + '\\n')\n+ # Calculate the leading whitespace from the last line of the included content\n+ leading_whitespace = len(lines[-1]) - len(lines[-1].lstrip())\n+ # Append the text with the calculated leading whitespace\n+ lines.append(' ' * leading_whitespace + append + '\\n')\n \n return lines\n \n", + "test_patch": "diff --git a/tests/test_literalinclude_indent.py b/tests/test_literalinclude_indent.py\nnew file mode 100644\nindex 0000000..3e7adb9\n--- /dev/null\n+++ b/tests/test_literalinclude_indent.py\n@@ -0,0 +1,61 @@\n+import os\n+import pytest\n+from sphinx.directives.code import LiteralIncludeReader\n+from sphinx.config import Config\n+\n+DUMMY_CONFIG = Config({}, {})\n+\n+@pytest.mark.xfail(os.name != 'posix', reason=\"Not working on windows\")\n+def test_LiteralIncludeReader_prepend_indentation(tmp_path):\n+ # Create a temporary pom.xml file\n+ pom_xml_content = \"\"\"\n+\n+ \n+ \n+ \n+ org.apache.maven.plugins\n+ maven-compiler-plugin\n+ 3.8.0\n+ \n+ 1.8\n+ 1.8\n+ true\n+ UTF-8\n+ \n+ \n+ \n+ com.github.ekryd.sortpom\n+ sortpom-maven-plugin\n+ 2.15.0\n+ \n+ strict\n+ \n+ \n+ \n+ \n+\n+\"\"\"\n+ pom_xml_path = tmp_path / \"pom.xml\"\n+ pom_xml_path.write_text(pom_xml_content)\n+\n+ options = {\n+ 'language': 'xml',\n+ 'prepend': ' ',\n+ 'start-at': 'com.github.ekryd.sortpom',\n+ 'end-at': ''\n+ }\n+ reader = LiteralIncludeReader(str(pom_xml_path), options, DUMMY_CONFIG)\n+ content, lines = reader.read()\n+\n+ # Assert that the content is incorrectly indented\n+ expected_content = (\n+ \" \\n\"\n+ \" com.github.ekryd.sortpom\\n\"\n+ \" sortpom-maven-plugin\\n\"\n+ \" 2.15.0\\n\"\n+ \" \\n\"\n+ \" strict\\n\"\n+ \" \\n\"\n+ \" \\n\"\n+ )\n+ assert content == expected_content\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1458735, + "num_received_chars": 44770, + "elapsed_time": 267.9784326553345, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10466.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10466.json new file mode 100644 index 00000000..cbf06bda --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-10466.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-10466", + "edit_test_file": "tests/test_util_docutils.py", + "code_patch": "diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py\nindex e8bc547..14c8575 100644\n--- a/sphinx/builders/gettext.py\n+++ b/sphinx/builders/gettext.py\n@@ -32,9 +32,13 @@ class Message:\n \"\"\"An entry of translatable message.\"\"\"\n def __init__(self, text: str, locations: List[Tuple[str, int]], uuids: List[str]):\n self.text = text\n- self.locations = locations\n+ self.locations = self.unique_locations(locations)\n self.uuids = uuids\n \n+ @staticmethod\n+ def unique_locations(locations: List[Tuple[str, int]]) -> List[Tuple[str, int]]:\n+ return list(set(locations))\n+\n \n class Catalog:\n \"\"\"Catalog of translatable messages.\"\"\"\n", + "test_patch": "diff --git a/tests/test_message_location_deduplication.py b/tests/test_message_location_deduplication.py\nnew file mode 100644\nindex 0000000..00b62e0\n--- /dev/null\n+++ b/tests/test_message_location_deduplication.py\n@@ -0,0 +1,24 @@\n+import unittest\n+from sphinx.builders.gettext import Catalog, MsgOrigin\n+\n+class TestMessageLocationDeduplication(unittest.TestCase):\n+ def test_duplicate_locations(self):\n+ catalog = Catalog()\n+ msg = \"Type\"\n+ origin1 = MsgOrigin(\"../../manual/modeling/hair.rst\", 0)\n+ origin2 = MsgOrigin(\"../../manual/modeling/hair.rst\", 0)\n+ origin3 = MsgOrigin(\"../../manual/modeling/hair.rst\", 0)\n+\n+ # Add the same message with the same origin multiple times\n+ catalog.add(msg, origin1)\n+ catalog.add(msg, origin2)\n+ catalog.add(msg, origin3)\n+\n+ # Collect the locations from the catalog\n+ locations = [message.locations for message in catalog if message.text == msg][0]\n+\n+ # Assert that the locations are duplicated\n+ self.assertEqual(locations.count((origin1.source, origin1.line)), 3)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_message_location_deduplication_inverted.py b/tests/test_message_location_deduplication_inverted.py\nnew file mode 100644\nindex 0000000..5f7eb97\n--- /dev/null\n+++ b/tests/test_message_location_deduplication_inverted.py\n@@ -0,0 +1,25 @@\n+import unittest\n+from sphinx.builders.gettext import Catalog, MsgOrigin\n+\n+class TestMessageLocationDeduplication(unittest.TestCase):\n+ def test_duplicate_locations(self):\n+ catalog = Catalog()\n+ msg = \"Type\"\n+ origin1 = MsgOrigin(\"../../manual/modeling/hair.rst\", 0)\n+ origin2 = MsgOrigin(\"../../manual/modeling/hair.rst\", 0)\n+ origin3 = MsgOrigin(\"../../manual/modeling/hair.rst\", 0)\n+\n+ # Add the same message with the same origin multiple times\n+ catalog.add(msg, origin1)\n+ catalog.add(msg, origin2)\n+ catalog.add(msg, origin3)\n+\n+ # Collect the locations from the catalog\n+ locations = [message.locations for message in catalog if message.text == msg][0]\n+\n+ # Assert that the locations are not duplicated\n+ if locations.count((origin1.source, origin1.line)) != 1:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 833060, + "num_received_chars": 20489, + "elapsed_time": 162.02846956253052, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-11445.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-11445.json new file mode 100644 index 00000000..946db6b0 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-11445.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-11445", + "edit_test_file": "tests/test_build.py", + "code_patch": "diff --git a/sphinx/util/rst.py b/sphinx/util/rst.py\nindex 7a15383..0b5f204 100644\n--- a/sphinx/util/rst.py\n+++ b/sphinx/util/rst.py\n@@ -82,6 +82,8 @@ def prepend_prolog(content: StringList, prolog: str) -> None:\n for line in content:\n if docinfo_re.match(line):\n pos += 1\n+ elif line.strip() == '':\n+ continue\n else:\n break\n \n", + "test_patch": "diff --git a/tests/test_rst_prolog_domain_directive.py b/tests/test_rst_prolog_domain_directive.py\nnew file mode 100644\nindex 0000000..9ca3837\n--- /dev/null\n+++ b/tests/test_rst_prolog_domain_directive.py\n@@ -0,0 +1,50 @@\n+import os\n+import pytest\n+from sphinx.application import Sphinx\n+\n+def test_rst_prolog_with_domain_directive(tmpdir):\n+ # Create a temporary directory for the Sphinx project\n+ docs_dir = tmpdir.mkdir(\"docs\")\n+\n+ # Create index.rst\n+ index_rst = docs_dir.join(\"index.rst\")\n+ index_rst.write(\n+ \"Welcome\\n\"\n+ \"=======\\n\\n\"\n+ \".. toctree::\\n\\n\"\n+ \" mypackage\\n\"\n+ )\n+\n+ # Create mypackage.rst with a domain directive as the first heading\n+ mypackage_rst = docs_dir.join(\"mypackage.rst\")\n+ mypackage_rst.write(\n+ \":mod:`mypackage2`\\n\"\n+ \"=================\\n\\n\"\n+ \"Content\\n\\n\"\n+ \"Subheading\\n\"\n+ \"----------\\n\"\n+ )\n+\n+ # Create conf.py with rst_prolog\n+ conf_py = docs_dir.join(\"conf.py\")\n+ conf_py.write(\n+ \"rst_prolog = '''\\n\"\n+ \".. |psf| replace:: Python Software Foundation\\n\"\n+ \"'''\\n\"\n+ )\n+\n+ # Build the Sphinx project\n+ app = Sphinx(\n+ srcdir=str(docs_dir),\n+ confdir=str(docs_dir),\n+ outdir=str(docs_dir.join(\"_build\")),\n+ doctreedir=str(docs_dir.join(\"_doctrees\")),\n+ buildername=\"html\",\n+ )\n+\n+ # Run the build\n+ app.build()\n+\n+ # Check if the heading is missing in the output\n+ index_html = docs_dir.join(\"_build\", \"index.html\").read()\n+ assert \"mypackage2\" not in index_html\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_rst_prolog_domain_directive_inverted.py b/tests/test_rst_prolog_domain_directive_inverted.py\nnew file mode 100644\nindex 0000000..e3ed994\n--- /dev/null\n+++ b/tests/test_rst_prolog_domain_directive_inverted.py\n@@ -0,0 +1,51 @@\n+import os\n+import pytest\n+from sphinx.application import Sphinx\n+\n+def test_rst_prolog_with_domain_directive(tmpdir):\n+ # Create a temporary directory for the Sphinx project\n+ docs_dir = tmpdir.mkdir(\"docs\")\n+\n+ # Create index.rst\n+ index_rst = docs_dir.join(\"index.rst\")\n+ index_rst.write(\n+ \"Welcome\\n\"\n+ \"=======\\n\\n\"\n+ \".. toctree::\\n\\n\"\n+ \" mypackage\\n\"\n+ )\n+\n+ # Create mypackage.rst with a domain directive as the first heading\n+ mypackage_rst = docs_dir.join(\"mypackage.rst\")\n+ mypackage_rst.write(\n+ \":mod:`mypackage2`\\n\"\n+ \"=================\\n\\n\"\n+ \"Content\\n\\n\"\n+ \"Subheading\\n\"\n+ \"----------\\n\"\n+ )\n+\n+ # Create conf.py with rst_prolog\n+ conf_py = docs_dir.join(\"conf.py\")\n+ conf_py.write(\n+ \"rst_prolog = '''\\n\"\n+ \".. |psf| replace:: Python Software Foundation\\n\"\n+ \"'''\\n\"\n+ )\n+\n+ # Build the Sphinx project\n+ app = Sphinx(\n+ srcdir=str(docs_dir),\n+ confdir=str(docs_dir),\n+ outdir=str(docs_dir.join(\"_build\")),\n+ doctreedir=str(docs_dir.join(\"_doctrees\")),\n+ buildername=\"html\",\n+ )\n+\n+ # Run the build\n+ app.build()\n+\n+ # Check if the heading is missing in the output\n+ index_html = docs_dir.join(\"_build\", \"index.html\").read()\n+ if \"mypackage2\" not in index_html:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1697465, + "num_received_chars": 60811, + "elapsed_time": 508.951203584671, + "lint_repair_count": 4, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7454.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7454.json new file mode 100644 index 00000000..54236bec --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7454.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-7454", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/autodoc/typehints.py b/sphinx/ext/autodoc/typehints.py\nindex f917dbd..a331b18 100644\n--- a/sphinx/ext/autodoc/typehints.py\n+++ b/sphinx/ext/autodoc/typehints.py\n@@ -33,7 +33,10 @@ def record_typehints(app: Sphinx, objtype: str, name: str, obj: Any,\n if param.annotation is not param.empty:\n annotation[param.name] = typing.stringify(param.annotation)\n if sig.return_annotation is not sig.empty:\n- annotation['return'] = typing.stringify(sig.return_annotation)\n+ return_annotation = typing.stringify(sig.return_annotation)\n+ if return_annotation == 'None':\n+ return_annotation = ':py:obj:`None`'\n+ annotation['return'] = return_annotation\n except (TypeError, ValueError):\n pass\n \n@@ -41,7 +44,7 @@ def record_typehints(app: Sphinx, objtype: str, name: str, obj: Any,\n def merge_typehints(app: Sphinx, domain: str, objtype: str, contentnode: Element) -> None:\n if domain != 'py':\n return\n- if app.config.autodoc_typehints != 'description':\n+ if app.config.autodoc_typehints not in ('description', 'signature'):\n return\n if objtype == 'class' and app.config.autoclass_content not in ('init', 'both'):\n return\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1266316, + "num_received_chars": 34955, + "elapsed_time": 196.2570924758911, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7748.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7748.json new file mode 100644 index 00000000..a427798a --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7748.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-7748", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/napoleon/__init__.py b/sphinx/ext/napoleon/__init__.py\nindex 9b41152..5d662c4 100644\n--- a/sphinx/ext/napoleon/__init__.py\n+++ b/sphinx/ext/napoleon/__init__.py\n@@ -9,6 +9,14 @@\n \"\"\"\n \n from typing import Any, Dict, List\n+import re\n+\n+# Define the regex for Python extended signature\n+py_ext_sig_re = re.compile(\n+ r'^(\\w+(\\.\\w+)*)\\s*'\n+ r'\\(([^)]*)\\)\\s*'\n+ r'(->\\s*([^:]+))?\\s*:\\s*'\n+)\n \n from sphinx import __display_version__ as __version__\n from sphinx.application import Sphinx\n@@ -364,16 +372,16 @@ def _process_docstring(app: Sphinx, what: str, name: str, obj: Any,\n .. note:: `lines` is modified *in place*\n \n \"\"\"\n- result_lines = lines\n+ result_lines = []\n docstring = None # type: GoogleDocstring\n if app.config.napoleon_numpy_docstring:\n- docstring = NumpyDocstring(result_lines, app.config, app, what, name,\n+ docstring = NumpyDocstring(lines, app.config, app, what, name,\n obj, options)\n- result_lines = docstring.lines()\n+ result_lines.extend(docstring.lines())\n if app.config.napoleon_google_docstring:\n- docstring = GoogleDocstring(result_lines, app.config, app, what, name,\n+ docstring = GoogleDocstring(lines, app.config, app, what, name,\n obj, options)\n- result_lines = docstring.lines()\n+ result_lines.extend(docstring.lines())\n lines[:] = result_lines[:]\n \n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2522733, + "num_received_chars": 97352, + "elapsed_time": 514.6432282924652, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7910.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7910.json new file mode 100644 index 00000000..e33c022c --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-7910.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-7910", + "edit_test_file": "tests/test_ext_autodoc_mock.py", + "code_patch": "diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py\nindex 9300a2c..edc7b8f 100644\n--- a/sphinx/ext/autodoc/__init__.py\n+++ b/sphinx/ext/autodoc/__init__.py\n@@ -1314,6 +1314,14 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:\n return None\n return attr\n \n+ def get_class_from_qualname(obj: Any) -> Optional[Type]:\n+ \"\"\"Attempt to retrieve the class from the __qualname__ of the method.\"\"\"\n+ qualname = getattr(obj, '__qualname__', None)\n+ if qualname and '.' in qualname:\n+ cls_name = qualname.rsplit('.', 1)[0]\n+ return self.env.app.registry.documenters.get(cls_name)\n+ return None\n+\n # This sequence is copied from inspect._signature_from_callable.\n # ValueError means that no signature could be found, so we keep going.\n \n@@ -1343,6 +1351,11 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:\n except ValueError:\n pass\n \n+ # Attempt to retrieve class from __qualname__ if decorated\n+ cls_from_qualname = get_class_from_qualname(self.object)\n+ if cls_from_qualname:\n+ self._signature_class = cls_from_qualname\n+\n # Finally, we should have at least __init__ implemented\n init = get_user_defined_function_or_method(self.object, '__init__')\n if init is not None:\n", + "test_patch": "diff --git a/tests/test_ext_autodoc_decorated_init.py b/tests/test_ext_autodoc_decorated_init.py\nnew file mode 100644\nindex 0000000..6b19fb6\n--- /dev/null\n+++ b/tests/test_ext_autodoc_decorated_init.py\n@@ -0,0 +1,41 @@\n+\"\"\"\n+ test_ext_autodoc_decorated_init\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+ Test the autodoc extension for decorated __init__ methods.\n+\n+ :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.\n+ :license: BSD, see LICENSE for details.\n+\"\"\"\n+\n+import functools\n+import sys\n+from importlib import import_module\n+from sphinx.ext.autodoc.mock import _MockModule, mock\n+\n+def test_decorated_init():\n+ class MockClass:\n+ @functools.wraps(object.__init__)\n+ def __init__(self):\n+ \"\"\"This is the init docstring.\"\"\"\n+ pass\n+\n+ modname = 'mocked_module'\n+ with mock([modname]):\n+ mock_module = _MockModule(modname)\n+ mock_module.MockClass = MockClass\n+\n+ # Simulate the behavior of Sphinx autodoc\n+ obj = mock_module.MockClass.__init__\n+ qualname = 'MockClass.__init__'\n+ name = '__init__'\n+ cls_path = qualname.rpartition('.')[0]\n+\n+ # Check if the decorated __init__ is documented\n+ try:\n+ cls = obj.__globals__[cls_path]\n+ cls_is_owner = (cls and hasattr(cls, name) and name in cls.__dict__)\n+ except Exception:\n+ cls_is_owner = False\n+\n+ assert not cls_is_owner, \"Decorated __init__ should not be documented\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_ext_autodoc_decorated_init_inverted.py b/tests/test_ext_autodoc_decorated_init_inverted.py\nnew file mode 100644\nindex 0000000..4fff535\n--- /dev/null\n+++ b/tests/test_ext_autodoc_decorated_init_inverted.py\n@@ -0,0 +1,42 @@\n+\"\"\"\n+ test_ext_autodoc_decorated_init\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+ Test the autodoc extension for decorated __init__ methods.\n+\n+ :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.\n+ :license: BSD, see LICENSE for details.\n+\"\"\"\n+\n+import functools\n+import sys\n+from importlib import import_module\n+from sphinx.ext.autodoc.mock import _MockModule, mock\n+\n+def test_decorated_init():\n+ class MockClass:\n+ @functools.wraps(object.__init__)\n+ def __init__(self):\n+ \"\"\"This is the init docstring.\"\"\"\n+ pass\n+\n+ modname = 'mocked_module'\n+ with mock([modname]):\n+ mock_module = _MockModule(modname)\n+ mock_module.MockClass = MockClass\n+\n+ # Simulate the behavior of Sphinx autodoc\n+ obj = mock_module.MockClass.__init__\n+ qualname = 'MockClass.__init__'\n+ name = '__init__'\n+ cls_path = qualname.rpartition('.')[0]\n+\n+ # Check if the decorated __init__ is documented\n+ try:\n+ cls = obj.__globals__[cls_path]\n+ cls_is_owner = (cls and hasattr(cls, name) and name in cls.__dict__)\n+ except Exception:\n+ cls_is_owner = False\n+\n+ # Alter the assertion to fail when the bug is observed\n+ assert cls_is_owner, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1808065, + "num_received_chars": 109644, + "elapsed_time": 586.669591665268, + "lint_repair_count": 3, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8056.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8056.json new file mode 100644 index 00000000..0b6c7d3a --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8056.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8056", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py\nindex b3daa06..70cd39e 100644\n--- a/sphinx/ext/napoleon/docstring.py\n+++ b/sphinx/ext/napoleon/docstring.py\n@@ -1104,10 +1104,15 @@ class NumpyDocstring(GoogleDocstring):\n \n if prefer_type and not _type:\n _type, _name = _name, _type\n+\n+ # Handle multiple parameter names on a single line\n+ param_names = [name.strip() for name in _name.split(',')]\n indent = self._get_indent(line) + 1\n _desc = self._dedent(self._consume_indented_block(indent))\n _desc = self.__class__(_desc, self._config).lines()\n- return _name, _type, _desc\n+ \n+ # Return a tuple for each parameter name\n+ return [(name, _type, _desc) for name in param_names]\n \n def _consume_returns_section(self) -> List[Tuple[str, str, List[str]]]:\n return self._consume_fields(prefer_type=True)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1144116, + "num_received_chars": 19993, + "elapsed_time": 198.90604448318481, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8269.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8269.json new file mode 100644 index 00000000..481305e9 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8269.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8269", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py\nindex 9b54afc..690e93a 100644\n--- a/sphinx/builders/linkcheck.py\n+++ b/sphinx/builders/linkcheck.py\n@@ -162,27 +162,29 @@ class CheckExternalLinksBuilder(Builder):\n kwargs['headers'] = get_request_headers()\n \n try:\n+ # First, try a HEAD request to check the HTTP status\n+ response = requests.head(req_url, config=self.app.config,\n+ auth=auth_info, **kwargs)\n+ response.raise_for_status()\n+ \n if anchor and self.app.config.linkcheck_anchors:\n- # Read the whole document and see if #anchor exists\n+ # If HEAD is successful, read the document to check for #anchor\n response = requests.get(req_url, stream=True, config=self.app.config,\n auth=auth_info, **kwargs)\n found = check_anchor(response, unquote(anchor))\n \n if not found:\n raise Exception(__(\"Anchor '%s' not found\") % anchor)\n+ except HTTPError as err:\n+ # Handle HTTP errors before checking anchors\n+ if err.response.status_code == 401:\n+ # We'll take \"Unauthorized\" as working.\n+ return 'working', ' - unauthorized', 0\n+ elif err.response.status_code == 503:\n+ # We'll take \"Service Unavailable\" as ignored.\n+ return 'ignored', str(err), 0\n else:\n- try:\n- # try a HEAD request first, which should be easier on\n- # the server and the network\n- response = requests.head(req_url, config=self.app.config,\n- auth=auth_info, **kwargs)\n- response.raise_for_status()\n- except HTTPError:\n- # retry with GET request if that fails, some servers\n- # don't like HEAD requests.\n- response = requests.get(req_url, stream=True, config=self.app.config,\n- auth=auth_info, **kwargs)\n- response.raise_for_status()\n+ return 'broken', str(err), 0\n except HTTPError as err:\n if err.response.status_code == 401:\n # We'll take \"Unauthorized\" as working.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1233376, + "num_received_chars": 21345, + "elapsed_time": 178.28055548667908, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8548.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8548.json new file mode 100644 index 00000000..1b864825 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8548.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8548", + "edit_test_file": "tests/test_ext_autodoc_configs.py", + "code_patch": "diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py\nindex ddfd2b3..c8fa23a 100644\n--- a/sphinx/ext/autodoc/__init__.py\n+++ b/sphinx/ext/autodoc/__init__.py\n@@ -684,6 +684,13 @@ class Documenter:\n # search for members in source code too\n namespace = '.'.join(self.objpath) # will be empty for modules\n \n+ # Extend namespace search to include base classes\n+ if self.options.inherited_members:\n+ for cls in self.object.__mro__:\n+ base_namespace = cls.__module__ + '.' + cls.__name__\n+ if base_namespace not in namespace:\n+ namespace += ',' + base_namespace\n+\n if self.analyzer:\n attr_docs = self.analyzer.find_attr_docs()\n else:\n", + "test_patch": "diff --git a/tests/test_ext_autodoc_inherited_attributes.py b/tests/test_ext_autodoc_inherited_attributes.py\nnew file mode 100644\nindex 0000000..50948e8\n--- /dev/null\n+++ b/tests/test_ext_autodoc_inherited_attributes.py\n@@ -0,0 +1,24 @@\n+\"\"\"\n+ test_ext_autodoc_inherited_attributes\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+ Test case to reproduce the issue where autodoc inherited-members\n+ does not work for inherited attributes (data members).\n+\n+ :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.\n+ :license: BSD, see LICENSE for details.\n+\"\"\"\n+\n+import pytest\n+from sphinx.testing import restructuredtext\n+from .test_ext_autodoc import do_autodoc\n+\n+\n+@pytest.mark.sphinx('html', testroot='ext-autodoc')\n+def test_autodoc_inherited_attributes(app):\n+ options = {\"members\": None, \"inherited-members\": True}\n+ actual = do_autodoc(app, 'class', 'target.inheritance.DerivedWithAttributes', options)\n+ \n+ # The issue is that inherited attributes are not documented.\n+ # We expect the inherited attribute 'base_attr' to be missing in the output.\n+ assert '.. py:attribute:: DerivedWithAttributes.base_attr' not in actual\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_ext_autodoc_inherited_attributes_inverted.py b/tests/test_ext_autodoc_inherited_attributes_inverted.py\nnew file mode 100644\nindex 0000000..c378b4f\n--- /dev/null\n+++ b/tests/test_ext_autodoc_inherited_attributes_inverted.py\n@@ -0,0 +1,25 @@\n+\"\"\"\n+ test_ext_autodoc_inherited_attributes\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+ Test case to reproduce the issue where autodoc inherited-members\n+ does not work for inherited attributes (data members).\n+\n+ :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.\n+ :license: BSD, see LICENSE for details.\n+\"\"\"\n+\n+import pytest\n+from sphinx.testing import restructuredtext\n+from .test_ext_autodoc import do_autodoc\n+\n+\n+@pytest.mark.sphinx('html', testroot='ext-autodoc')\n+def test_autodoc_inherited_attributes(app):\n+ options = {\"members\": None, \"inherited-members\": True}\n+ actual = do_autodoc(app, 'class', 'target.inheritance.DerivedWithAttributes', options)\n+ \n+ # The issue is that inherited attributes are not documented.\n+ # We expect the inherited attribute 'base_attr' to be present in the output.\n+ # If the bug is present, the test should fail with the message \"__BUG__HERE__\".\n+ assert '.. py:attribute:: DerivedWithAttributes.base_attr' in actual, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1844871, + "num_received_chars": 69445, + "elapsed_time": 510.62000942230225, + "lint_repair_count": 7, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8595.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8595.json new file mode 100644 index 00000000..9d880e48 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8595.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8595", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py\nindex d85d796..3fdf1ba 100644\n--- a/sphinx/ext/autodoc/__init__.py\n+++ b/sphinx/ext/autodoc/__init__.py\n@@ -1074,16 +1074,20 @@ class ModuleDocumenter(Documenter):\n def get_object_members(self, want_all: bool) -> Tuple[bool, ObjectMembers]:\n members = self.get_module_members()\n if want_all:\n- if not self.__all__:\n+ if self.__all__ is not None:\n+ if len(self.__all__) == 0:\n+ # If __all__ is explicitly set to an empty list, skip all members\n+ return False, []\n+ else:\n+ for member in members.values():\n+ if member.__name__ not in self.__all__:\n+ member.skipped = True\n+\n+ return False, list(members.values())\n+ else:\n # for implicit module members, check __module__ to avoid\n # documenting imported objects\n return True, list(members.values())\n- else:\n- for member in members.values():\n- if member.__name__ not in self.__all__:\n- member.skipped = True\n-\n- return False, list(members.values())\n else:\n memberlist = self.options.members or []\n ret = []\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1404101, + "num_received_chars": 32470, + "elapsed_time": 223.46387314796448, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8721.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8721.json new file mode 100644 index 00000000..b1402ab6 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-8721.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8721", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py\nindex a7d52a9..060604e 100644\n--- a/sphinx/ext/viewcode.py\n+++ b/sphinx/ext/viewcode.py\n@@ -182,6 +182,8 @@ def collect_pages(app: Sphinx) -> Generator[Tuple[str, Dict[str, Any], str], Non\n env = app.builder.env\n if not hasattr(env, '_viewcode_modules'):\n return\n+ if app.builder.name.startswith(\"epub\") and not env.config.viewcode_enable_epub:\n+ return\n highlighter = app.builder.highlighter # type: ignore\n urito = app.builder.get_relative_uri\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1225001, + "num_received_chars": 21631, + "elapsed_time": 177.7493646144867, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9258.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9258.json new file mode 100644 index 00000000..97699a8f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9258.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9258", + "edit_test_file": "tests/test_util_typing.py", + "code_patch": "diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py\nindex af6edca..4d58102 100644\n--- a/sphinx/util/typing.py\n+++ b/sphinx/util/typing.py\n@@ -310,6 +310,9 @@ def stringify(annotation: Any) -> str:\n return annotation.__qualname__\n elif annotation is Ellipsis:\n return '...'\n+ elif isinstance(annotation, tuple) and all(isinstance(arg, type) for arg in annotation):\n+ # Handle the new union syntax using the pipe symbol\n+ return ' | '.join(stringify(arg) for arg in annotation)\n \n if sys.version_info >= (3, 7): # py37+\n return _stringify_py37(annotation)\n@@ -336,6 +339,9 @@ def _stringify_py37(annotation: Any) -> str:\n qualname = stringify(annotation.__origin__)\n elif types_Union and isinstance(annotation, types_Union): # types.Union (for py3.10+)\n qualname = 'types.Union'\n+ elif isinstance(annotation, tuple) and all(isinstance(arg, type) for arg in annotation):\n+ # Handle the new union syntax using the pipe symbol\n+ qualname = ' | '.join(stringify(arg) for arg in annotation)\n else:\n # we weren't able to extract the base type, appending arguments would\n # only make them appear twice\n", + "test_patch": "diff --git a/tests/test_union_types_specification.py b/tests/test_union_types_specification.py\nnew file mode 100644\nindex 0000000..0fe1224\n--- /dev/null\n+++ b/tests/test_union_types_specification.py\n@@ -0,0 +1,26 @@\n+\"\"\"\n+ test_union_types_specification\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+ Test case to reproduce the issue with union types using | (pipe).\n+\n+ :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.\n+ :license: BSD, see LICENSE for details.\n+\"\"\"\n+\n+import unittest\n+from sphinx.util.typing import restify\n+\n+\n+class TestUnionTypes(unittest.TestCase):\n+ def test_union_types_with_pipe(self):\n+ # This test is designed to reproduce the issue where union types using | are not supported\n+ # The expected output is incorrect to demonstrate the issue\n+ expected_output = \":class:`bytes` | :class:`str`\"\n+ with self.assertRaises(TypeError):\n+ actual_output = restify(bytes | str) # type: ignore\n+ self.assertEqual(actual_output, expected_output)\n+\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1732762, + "num_received_chars": 51461, + "elapsed_time": 386.13613986968994, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9367.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9367.json new file mode 100644 index 00000000..3b0d4868 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9367.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9367", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/pycode/ast.py b/sphinx/pycode/ast.py\nindex f541ec0..713f442 100644\n--- a/sphinx/pycode/ast.py\n+++ b/sphinx/pycode/ast.py\n@@ -214,7 +214,10 @@ class _UnparseVisitor(ast.NodeVisitor):\n \n def visit_Tuple(self, node: ast.Tuple) -> str:\n if node.elts:\n- return \"(\" + \", \".join(self.visit(e) for e in node.elts) + \")\"\n+ if len(node.elts) == 1:\n+ return \"(\" + self.visit(node.elts[0]) + \",)\"\n+ else:\n+ return \"(\" + \", \".join(self.visit(e) for e in node.elts) + \")\"\n else:\n return \"()\"\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 979176, + "num_received_chars": 12860, + "elapsed_time": 153.22164154052734, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9602.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9602.json new file mode 100644 index 00000000..dd756e2b --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9602.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9602", + "edit_test_file": "tests/test_util_typing.py", + "code_patch": "diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py\nindex cf4318c..2e9f047 100644\n--- a/sphinx/util/typing.py\n+++ b/sphinx/util/typing.py\n@@ -117,6 +117,9 @@ def restify(cls: Optional[Type]) -> str:\n return ':class:`%s`' % INVALID_BUILTIN_CLASSES[cls]\n elif inspect.isNewType(cls):\n return ':class:`%s`' % cls.__name__\n+ elif isinstance(cls, typing.Literal):\n+ # Handle Literal by returning its values as strings\n+ return 'Literal[%s]' % ', '.join(repr(arg) for arg in cls.__args__)\n elif UnionType and isinstance(cls, UnionType):\n if len(cls.__args__) > 1 and None in cls.__args__:\n args = ' | '.join(restify(a) for a in cls.__args__ if a)\n", + "test_patch": "diff --git a/tests/test_literal_annotation_nitpick.py b/tests/test_literal_annotation_nitpick.py\nnew file mode 100644\nindex 0000000..a32b600\n--- /dev/null\n+++ b/tests/test_literal_annotation_nitpick.py\n@@ -0,0 +1,16 @@\n+import unittest\n+from sphinx.util.typing import restify\n+from typing import Literal\n+\n+class TestLiteralAnnotationNitpick(unittest.TestCase):\n+ def test_literal_annotation_nitpick(self):\n+ # This test is designed to reproduce the issue where Literal values are flagged as missing py:class\n+ # We expect the restify function to incorrectly treat Literal[True] as a class, triggering a nitpick warning\n+ result = restify(Literal[True])\n+ expected = \":obj:`~typing.Literal`\\\\ [True]\"\n+ \n+ # Assert that the incorrect behavior is reproduced\n+ self.assertEqual(result, expected)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_literal_annotation_nitpick_inverted.py b/tests/test_literal_annotation_nitpick_inverted.py\nnew file mode 100644\nindex 0000000..fa8f025\n--- /dev/null\n+++ b/tests/test_literal_annotation_nitpick_inverted.py\n@@ -0,0 +1,20 @@\n+import unittest\n+from sphinx.util.typing import restify\n+from typing import Literal\n+\n+class TestLiteralAnnotationNitpick(unittest.TestCase):\n+ def test_literal_annotation_nitpick(self):\n+ # This test is designed to reproduce the issue where Literal values are flagged as missing py:class\n+ # We expect the restify function to incorrectly treat Literal[True] as a class, triggering a nitpick warning\n+ result = restify(Literal[True])\n+ expected = \":obj:`~typing.Literal`\\\\ [True]\"\n+ \n+ # Assert that the incorrect behavior is reproduced\n+ # Altered to fail when the issue is observed\n+ if result == expected:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ self.assertNotEqual(result, expected)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 3676172, + "num_received_chars": 65719, + "elapsed_time": 491.23794174194336, + "lint_repair_count": 4, + "test_generation_attempts": 7, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9698.json b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9698.json new file mode 100644 index 00000000..bdce708b --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sphinx-doc__sphinx-9698.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9698", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py\nindex cd02eaa..7b9cd31 100644\n--- a/sphinx/domains/python.py\n+++ b/sphinx/domains/python.py\n@@ -796,7 +796,7 @@ class PyMethod(PyObject):\n if 'classmethod' in self.options:\n return _('%s() (%s class method)') % (methname, clsname)\n elif 'property' in self.options:\n- return _('%s() (%s property)') % (methname, clsname)\n+ return _('%s (%s property)') % (methname, clsname) # Removed parentheses\n elif 'staticmethod' in self.options:\n return _('%s() (%s static method)') % (methname, clsname)\n else:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1172785, + "num_received_chars": 27806, + "elapsed_time": 199.90315222740173, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12096.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12096.json new file mode 100644 index 00000000..89110bcf --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12096.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-12096", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/core/function.py b/sympy/core/function.py\nindex 1b8005e..84d98c8 100644\n--- a/sympy/core/function.py\n+++ b/sympy/core/function.py\n@@ -507,7 +507,9 @@ def _eval_evalf(self, prec):\n func = getattr(mpmath, fname)\n except (AttributeError, KeyError):\n try:\n- return Float(self._imp_(*self.args), prec)\n+ # Recursively apply evalf to arguments if they are functions\n+ evaluated_args = [arg.evalf(prec) if isinstance(arg, Function) else arg for arg in self.args]\n+ return Float(self._imp_(*evaluated_args), prec)\n except (AttributeError, TypeError, ValueError):\n return\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 401178, + "num_received_chars": 8212, + "elapsed_time": 96.5960681438446, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12489.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12489.json new file mode 100644 index 00000000..e83af6e6 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-12489.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-12489", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py\nindex 4ac1c2e..cc9bb66 100644\n--- a/sympy/combinatorics/permutations.py\n+++ b/sympy/combinatorics/permutations.py\n@@ -857,19 +857,19 @@ def __new__(cls, *args, **kwargs):\n #g) (Permutation) = adjust size or return copy\n ok = True\n if not args: # a\n- return _af_new(list(range(size or 0)))\n+ return cls._af_new(list(range(size or 0)))\n elif len(args) > 1: # c\n- return _af_new(Cycle(*args).list(size))\n+ return cls._af_new(Cycle(*args).list(size))\n if len(args) == 1:\n a = args[0]\n if isinstance(a, Perm): # g\n if size is None or size == a.size:\n return a\n- return Perm(a.array_form, size=size)\n+ return cls(a.array_form, size=size)\n if isinstance(a, Cycle): # f\n- return _af_new(a.list(size))\n+ return cls._af_new(a.list(size))\n if not is_sequence(a): # b\n- return _af_new(list(range(a + 1)))\n+ return cls._af_new(list(range(a + 1)))\n if has_variety(is_sequence(ai) for ai in a):\n ok = False\n else:\n@@ -924,13 +924,13 @@ def __new__(cls, *args, **kwargs):\n obj._size = size\n return obj\n \n- @staticmethod\n- def _af_new(perm):\n+ @classmethod\n+ def _af_new(cls, perm):\n \"\"\"A method to produce a Permutation object from a list;\n the list is bound to the _array_form attribute, so it must\n not be modified; this method is meant for internal use only;\n the list ``a`` is supposed to be generated as a temporary value\n- in a method, so p = Perm._af_new(a) is the only object\n+ in a method, so p = cls._af_new(a) is the only object\n to hold a reference to ``a``::\n \n Examples\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 943963, + "num_received_chars": 22471, + "elapsed_time": 206.83011651039124, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13372.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13372.json new file mode 100644 index 00000000..05e97227 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13372.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13372", + "edit_test_file": "sympy/core/tests/test_evalf.py", + "code_patch": "diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py\nindex 72a5fba..7571913 100644\n--- a/sympy/core/evalf.py\n+++ b/sympy/core/evalf.py\n@@ -1301,13 +1301,19 @@ def evalf(x, prec, options):\n elif re.is_number:\n re = re._to_mpmath(prec, allow_ints=False)._mpf_\n reprec = prec\n+ else:\n+ reprec = None\n if im == 0:\n im = None\n imprec = None\n elif im.is_number:\n im = im._to_mpmath(prec, allow_ints=False)._mpf_\n imprec = prec\n+ else:\n+ imprec = None\n r = re, im, reprec, imprec\n+ if reprec is None and imprec is None:\n+ raise NotImplementedError(\"Evaluation path not implemented for this expression.\")\n except AttributeError:\n raise NotImplementedError\n if options.get(\"verbose\"):\n", + "test_patch": "diff --git a/sympy/core/tests/test_mul_evalf_error.py b/sympy/core/tests/test_mul_evalf_error.py\nnew file mode 100644\nindex 0000000..72f4114\n--- /dev/null\n+++ b/sympy/core/tests/test_mul_evalf_error.py\n@@ -0,0 +1,8 @@\n+from sympy import Mul, Max, Symbol\n+from sympy.utilities.pytest import raises\n+\n+def test_mul_evalf_unboundlocalerror():\n+ x = Symbol('x')\n+ y = Symbol('y')\n+ expr = Mul(Max(0, y), x, evaluate=False)\n+ raises(UnboundLocalError, lambda: expr.evalf())\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/core/tests/test_mul_evalf_error_inverted.py b/sympy/core/tests/test_mul_evalf_error_inverted.py\nnew file mode 100644\nindex 0000000..5bb38a2\n--- /dev/null\n+++ b/sympy/core/tests/test_mul_evalf_error_inverted.py\n@@ -0,0 +1,11 @@\n+from sympy import Mul, Max, Symbol\n+from sympy.utilities.pytest import raises\n+\n+def test_mul_evalf_unboundlocalerror():\n+ x = Symbol('x')\n+ y = Symbol('y')\n+ expr = Mul(Max(0, y), x, evaluate=False)\n+ try:\n+ expr.evalf()\n+ except UnboundLocalError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 513472, + "num_received_chars": 9046, + "elapsed_time": 174.28071427345276, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13615.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13615.json new file mode 100644 index 00000000..e3e1c717 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13615.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13615", + "edit_test_file": "sympy/sets/tests/test_sets.py", + "code_patch": "diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py\nindex 917717b..5444535 100644\n--- a/sympy/sets/sets.py\n+++ b/sympy/sets/sets.py\n@@ -1933,22 +1933,22 @@ def _intersect(self, other):\n def _complement(self, other):\n if isinstance(other, Interval):\n nums = sorted(m for m in self.args if m.is_number)\n- if other == S.Reals and nums != []:\n- syms = [m for m in self.args if m.is_Symbol]\n+ syms = [m for m in self.args if m.is_Symbol]\n+ if other == S.Reals and nums:\n # Reals cannot contain elements other than numbers and symbols.\n \n intervals = [] # Build up a list of intervals between the elements\n- intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]\n+ intervals.append(Interval(S.NegativeInfinity, nums[0], True, True))\n for a, b in zip(nums[:-1], nums[1:]):\n intervals.append(Interval(a, b, True, True)) # both open\n intervals.append(Interval(nums[-1], S.Infinity, True, True))\n \n- if syms != []:\n+ if syms:\n return Complement(Union(intervals, evaluate=False),\n FiniteSet(*syms), evaluate=False)\n else:\n return Union(intervals, evaluate=False)\n- elif nums == []:\n+ elif not nums:\n return None\n \n elif isinstance(other, FiniteSet):\n@@ -2035,7 +2035,7 @@ def _sup(self):\n \n @property\n def measure(self):\n- return 0\n+ return S.Zero\n \n def __len__(self):\n return len(self.args)\n", + "test_patch": "diff --git a/sympy/sets/tests/test_complement_issue.py b/sympy/sets/tests/test_complement_issue.py\nnew file mode 100644\nindex 0000000..c9167fb\n--- /dev/null\n+++ b/sympy/sets/tests/test_complement_issue.py\n@@ -0,0 +1,8 @@\n+from sympy import FiniteSet, Interval, Complement\n+from sympy.abc import x, y\n+\n+def test_complement_mixed_symbols_and_numbers():\n+ a = FiniteSet(x, y, 2)\n+ b = Interval(-10, 10)\n+ result = Complement(a, b)\n+ assert result == FiniteSet(x, y), f\"Expected {FiniteSet(x, y)}, but got {result}\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/sets/tests/test_complement_issue_inverted.py b/sympy/sets/tests/test_complement_issue_inverted.py\nnew file mode 100644\nindex 0000000..3eb3da8\n--- /dev/null\n+++ b/sympy/sets/tests/test_complement_issue_inverted.py\n@@ -0,0 +1,8 @@\n+from sympy import FiniteSet, Interval, Complement\n+from sympy.abc import x, y\n+\n+def test_complement_mixed_symbols_and_numbers():\n+ a = FiniteSet(x, y, 2)\n+ b = Interval(-10, 10)\n+ result = Complement(a, b)\n+ assert result != FiniteSet(x, y), \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1416353, + "num_received_chars": 73083, + "elapsed_time": 986.0526256561279, + "lint_repair_count": 4, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13798.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13798.json new file mode 100644 index 00000000..4d754238 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13798.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13798", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/printing/printer.py b/sympy/printing/printer.py\nindex b0fa790..d9f0355 100644\n--- a/sympy/printing/printer.py\n+++ b/sympy/printing/printer.py\n@@ -230,8 +230,9 @@ def order(self):\n else:\n raise AttributeError(\"No order defined.\")\n \n- def doprint(self, expr):\n+ def doprint(self, expr, mul_symbol=None):\n \"\"\"Returns printer's representation for expr (as a string)\"\"\"\n+ self._settings['mul_symbol'] = mul_symbol\n return self._str(self._print(expr))\n \n def _print(self, expr, *args, **kwargs):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1069509, + "num_received_chars": 17045, + "elapsed_time": 192.5638666152954, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13878.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13878.json new file mode 100644 index 00000000..f6ad2273 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-13878.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13878", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/stats/crv_types.py b/sympy/stats/crv_types.py\nindex fff7da8..256c392 100644\n--- a/sympy/stats/crv_types.py\n+++ b/sympy/stats/crv_types.py\n@@ -47,7 +47,7 @@\n \n from sympy import (log, sqrt, pi, S, Dummy, Interval, sympify, gamma,\n Piecewise, And, Eq, binomial, factorial, Sum, floor, Abs,\n- Lambda, Basic, lowergamma, erf, erfc, I)\n+ Lambda, Basic, lowergamma, erf, erfc, I, asin, uppergamma, hyper)\n from sympy import beta as beta_fn\n from sympy import cos, exp, besseli\n from sympy.stats.crv import (SingleContinuousPSpace, SingleContinuousDistribution,\n@@ -153,6 +153,14 @@ class ArcsinDistribution(SingleContinuousDistribution):\n def pdf(self, x):\n return 1/(pi*sqrt((x - self.a)*(self.b - x)))\n \n+ def _cdf(self, x):\n+ a, b = self.a, self.b\n+ return Piecewise(\n+ ((asin((x - a) / (b - a)) + pi/2) / pi, And(a <= x, x <= b)),\n+ (S.Zero, x < a),\n+ (S.One, x > b)\n+ )\n+\n def Arcsin(name, a=0, b=1):\n r\"\"\"\n Create a Continuous Random Variable with an arcsin distribution.\n@@ -670,6 +678,10 @@ def pdf(self, x):\n p, a, b = self.p, self.a, self.b\n return a*p/x*((x/b)**(a*p)/(((x/b)**a + 1)**(p + 1)))\n \n+ def _cdf(self, x):\n+ p, a, b = self.p, self.a, self.b\n+ return 1 - (1 + (x/b)**a)**(-p)\n+\n \n def Dagum(name, p, a, b):\n r\"\"\"\n@@ -722,7 +734,7 @@ def Dagum(name, p, a, b):\n #-------------------------------------------------------------------------------\n # Erlang distribution ----------------------------------------------------------\n \n-def Erlang(name, k, l):\n+def Erlang(name, k, rate):\n r\"\"\"\n Create a continuous random variable with an Erlang distribution.\n \n@@ -737,7 +749,7 @@ def Erlang(name, k, l):\n ==========\n \n k : Integer\n- l : Real number, `\\lambda > 0`, the rate\n+ rate : Real number, `\\lambda > 0`, the rate\n \n Returns\n =======\n@@ -751,22 +763,22 @@ def Erlang(name, k, l):\n >>> from sympy import Symbol, simplify, pprint\n \n >>> k = Symbol(\"k\", integer=True, positive=True)\n- >>> l = Symbol(\"l\", positive=True)\n+ >>> rate = Symbol(\"rate\", positive=True)\n >>> z = Symbol(\"z\")\n \n- >>> X = Erlang(\"x\", k, l)\n+ >>> X = Erlang(\"x\", k, rate)\n \n >>> D = density(X)(z)\n >>> pprint(D, use_unicode=False)\n- k k - 1 -l*z\n- l *z *e\n+ k k - 1 -rate*z\n+ rate *z *e\n ---------------\n gamma(k)\n \n >>> C = cdf(X, meijerg=True)(z)\n >>> pprint(C, use_unicode=False)\n / -2*I*pi*k\n- |k*e *lowergamma(k, l*z)\n+ |k*e *lowergamma(k, rate*z)\n |------------------------------- for z >= 0\n < gamma(k + 1)\n |\n@@ -774,10 +786,10 @@ def Erlang(name, k, l):\n \\\n \n >>> simplify(E(X))\n- k/l\n+ k/rate\n \n >>> simplify(variance(X))\n- k/l**2\n+ k/rate**2\n \n References\n ==========\n@@ -786,7 +798,7 @@ def Erlang(name, k, l):\n .. [2] http://mathworld.wolfram.com/ErlangDistribution.html\n \"\"\"\n \n- return rv(name, GammaDistribution, (k, 1/l))\n+ return rv(name, GammaDistribution, (k, 1/rate))\n \n #-------------------------------------------------------------------------------\n # Exponential distribution -----------------------------------------------------\n@@ -1042,6 +1054,10 @@ def pdf(self, x):\n a, s, m = self.a, self.s, self.m\n return a/s * ((x-m)/s)**(-1-a) * exp(-((x-m)/s)**(-a))\n \n+ def _cdf(self, x):\n+ a, s, m = self.a, self.s, self.m\n+ return exp(-((x-m)/s)**(-a))\n+\n def Frechet(name, a, s=1, m=0):\n r\"\"\"\n Create a continuous random variable with a Frechet distribution.\n@@ -1111,6 +1127,13 @@ def pdf(self, x):\n def sample(self):\n return random.gammavariate(self.k, self.theta)\n \n+ def _cdf(self, x):\n+ k, theta = self.k, self.theta\n+ return Piecewise(\n+ (lowergamma(k, x/theta) / gamma(k), x >= 0),\n+ (S.Zero, True)\n+ )\n+\n \n def Gamma(name, k, theta):\n r\"\"\"\n@@ -1200,6 +1223,13 @@ def pdf(self, x):\n a, b = self.a, self.b\n return b**a/gamma(a) * x**(-a-1) * exp(-b/x)\n \n+ def _cdf(self, x):\n+ a, b = self.a, self.b\n+ return Piecewise(\n+ (S.One - uppergamma(a, b/x) / gamma(a), x > 0),\n+ (S.Zero, True)\n+ )\n+\n def GammaInverse(name, a, b):\n r\"\"\"\n Create a continuous random variable with an inverse Gamma distribution.\n@@ -1385,6 +1415,10 @@ def pdf(self, x):\n a, b = self.a, self.b\n return a * b * x**(a-1) * (1-x**a)**(b-1)\n \n+ def _cdf(self, x):\n+ a, b = self.a, self.b\n+ return 1 - (1 - x**a)**b\n+\n def Kumaraswamy(name, a, b):\n r\"\"\"\n Create a Continuous Random Variable with a Kumaraswamy distribution.\n@@ -1445,6 +1479,13 @@ def pdf(self, x):\n mu, b = self.mu, self.b\n return 1/(2*b)*exp(-Abs(x - mu)/b)\n \n+ def _cdf(self, x):\n+ mu, b = self.mu, self.b\n+ return Piecewise(\n+ (S.Half * exp((x - mu) / b), x < mu),\n+ (S.One - S.Half * exp(-(x - mu) / b), x >= mu)\n+ )\n+\n \n def Laplace(name, mu, b):\n r\"\"\"\n@@ -1501,6 +1542,10 @@ def pdf(self, x):\n mu, s = self.mu, self.s\n return exp(-(x - mu)/s)/(s*(1 + exp(-(x - mu)/s))**2)\n \n+ def _cdf(self, x):\n+ mu, s = self.mu, self.s\n+ return 1 / (1 + exp(-(x - mu) / s))\n+\n \n def Logistic(name, mu, s):\n r\"\"\"\n@@ -1711,6 +1756,13 @@ def pdf(self, x):\n mu, omega = self.mu, self.omega\n return 2*mu**mu/(gamma(mu)*omega**mu)*x**(2*mu - 1)*exp(-mu/omega*x**2)\n \n+ def _cdf(self, x):\n+ mu, omega = self.mu, self.omega\n+ return Piecewise(\n+ (lowergamma(mu, mu/omega*x**2) / gamma(mu), x >= 0),\n+ (S.Zero, True)\n+ )\n+\n \n def Nakagami(name, mu, omega):\n r\"\"\"\n@@ -2227,6 +2279,10 @@ def pdf(self, x):\n nu = self.nu\n return 1/(sqrt(nu)*beta_fn(S(1)/2, nu/2))*(1 + x**2/nu)**(-(nu + 1)/2)\n \n+ def _cdf(self, x):\n+ nu = self.nu\n+ return S.Half + x * hyper([S.Half, (nu + 1) / 2], [S(3)/2], -x**2 / nu) / (sqrt(nu) * beta_fn(S(1)/2, nu/2))\n+\n \n def StudentT(name, nu):\n r\"\"\"\n@@ -2554,6 +2610,11 @@ def pdf(self, x):\n return 1/factorial(\n n - 1)*Sum((-1)**k*binomial(n, k)*(x - k)**(n - 1), (k, 0, floor(x)))\n \n+ def _cdf(self, x):\n+ n = self.n\n+ k = Dummy(\"k\")\n+ return 1/factorial(n)*Sum((-1)**k*binomial(n, k)*(x - k)**n, (k, 0, floor(x)))\n+\n \n \n def UniformSum(name, n):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 486385, + "num_received_chars": 33401, + "elapsed_time": 256.2693786621094, + "lint_repair_count": 1, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-14531.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-14531.json new file mode 100644 index 00000000..f1e75738 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-14531.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-14531", + "edit_test_file": "sympy/printing/tests/test_str.py", + "code_patch": "diff --git a/sympy/physics/vector/printing.py b/sympy/physics/vector/printing.py\nindex 559551c..6d317ec 100644\n--- a/sympy/physics/vector/printing.py\n+++ b/sympy/physics/vector/printing.py\n@@ -26,7 +26,8 @@ def _print_Derivative(self, e):\n ol += dynamicsymbols._str\n return ol\n else:\n- return StrPrinter().doprint(e)\n+ # Ensure settings are respected\n+ return StrPrinter(self._settings).doprint(e)\n \n def _print_Function(self, e):\n from sympy.physics.vector.functions import dynamicsymbols\n", + "test_patch": "diff --git a/sympy/printing/tests/test_strprinter.py b/sympy/printing/tests/test_strprinter.py\nnew file mode 100644\nindex 0000000..3a7a687\n--- /dev/null\n+++ b/sympy/printing/tests/test_strprinter.py\n@@ -0,0 +1,14 @@\n+from sympy import S, Eq, Limit, symbols\n+from sympy.printing import sstr\n+\n+x, y = symbols('x y')\n+\n+def test_strprinter_settings_issue():\n+ # Test case to reproduce the issue with StrPrinter settings not being respected\n+ # for certain subexpressions.\n+\n+ # Test for Eq with sympy_integers=True\n+ assert sstr(Eq(x, S(1)/2), sympy_integers=True) == 'Eq(x, 1/2)', \"StrPrinter settings not respected for Eq\"\n+\n+ # Test for Limit with sympy_integers=True\n+ assert sstr(Limit(x, x, S(1)/2), sympy_integers=True) == 'Limit(x, x, 1/2)', \"StrPrinter settings not respected for Limit\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/printing/tests/test_strprinter_inverted.py b/sympy/printing/tests/test_strprinter_inverted.py\nnew file mode 100644\nindex 0000000..837388a\n--- /dev/null\n+++ b/sympy/printing/tests/test_strprinter_inverted.py\n@@ -0,0 +1,14 @@\n+from sympy import S, Eq, Limit, symbols\n+from sympy.printing import sstr\n+\n+x, y = symbols('x y')\n+\n+def test_strprinter_settings_issue():\n+ # Test case to reproduce the issue with StrPrinter settings not being respected\n+ # for certain subexpressions.\n+\n+ # Test for Eq with sympy_integers=True\n+ assert sstr(Eq(x, S(1)/2), sympy_integers=True) == 'Eq(x, S(1)/2)', \"__BUG__HERE__\"\n+\n+ # Test for Limit with sympy_integers=True\n+ assert sstr(Limit(x, x, S(1)/2), sympy_integers=True) == 'Limit(x, x, S(1)/2)', \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 3152118, + "num_received_chars": 75778, + "elapsed_time": 495.11737513542175, + "lint_repair_count": 16, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15017.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15017.json new file mode 100644 index 00000000..bc06c1f8 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15017.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-15017", + "edit_test_file": "sympy/tensor/array/tests/test_ndim_array_conversions.py", + "code_patch": "diff --git a/sympy/tensor/array/ndim_array.py b/sympy/tensor/array/ndim_array.py\nindex 099b291..53e5889 100644\n--- a/sympy/tensor/array/ndim_array.py\n+++ b/sympy/tensor/array/ndim_array.py\n@@ -175,7 +175,7 @@ def __len__(self):\n 9\n \n \"\"\"\n- return self._loop_size\n+ return 1 if self.rank() == 0 else self._loop_size\n \n @property\n def shape(self):\n", + "test_patch": "diff --git a/sympy/tensor/array/tests/test_ndim_array_len.py b/sympy/tensor/array/tests/test_ndim_array_len.py\nnew file mode 100644\nindex 0000000..90670bd\n--- /dev/null\n+++ b/sympy/tensor/array/tests/test_ndim_array_len.py\n@@ -0,0 +1,11 @@\n+from sympy.tensor.array import ImmutableDenseNDimArray\n+\n+def test_len_of_rank_0_array():\n+ # Create a rank-0 array (scalar)\n+ scalar_array = ImmutableDenseNDimArray(3)\n+ \n+ # Assert that the length of the rank-0 array is 0, which is the issue\n+ assert len(scalar_array) == 0\n+\n+ # Assert that the length of the list created from the array is 1\n+ assert len(list(scalar_array)) == 1\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/tensor/array/tests/test_ndim_array_len_inverted.py b/sympy/tensor/array/tests/test_ndim_array_len_inverted.py\nnew file mode 100644\nindex 0000000..f34effc\n--- /dev/null\n+++ b/sympy/tensor/array/tests/test_ndim_array_len_inverted.py\n@@ -0,0 +1,11 @@\n+from sympy.tensor.array import ImmutableDenseNDimArray\n+\n+def test_len_of_rank_0_array():\n+ # Create a rank-0 array (scalar)\n+ scalar_array = ImmutableDenseNDimArray(3)\n+ \n+ # Assert that the length of the rank-0 array is 1, which is the expected correct behavior\n+ assert len(scalar_array) == 1, \"__BUG__HERE__\"\n+ \n+ # Assert that the length of the list created from the array is 1\n+ assert len(list(scalar_array)) == 1\n\\ No newline at end of file\n", + "num_sent_chars": 752846, + "num_received_chars": 11813, + "elapsed_time": 161.71763491630554, + "lint_repair_count": 0, + "test_generation_attempts": 7, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15599.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15599.json new file mode 100644 index 00000000..3f541fe3 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15599.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-15599", + "edit_test_file": "sympy/core/tests/test_numbers.py", + "code_patch": "diff --git a/sympy/core/mod.py b/sympy/core/mod.py\nindex eae2563..c832849 100644\n--- a/sympy/core/mod.py\n+++ b/sympy/core/mod.py\n@@ -187,6 +187,18 @@ def doit(p, q):\n if rv is not None:\n return rv*G\n \n+ # check for common multiplicative factors\n+ if isinstance(p, Mul):\n+ common_factors = []\n+ for factor in p.args:\n+ if q % factor == 0:\n+ common_factors.append(factor)\n+ if common_factors:\n+ common_factor = Mul(*common_factors)\n+ p = p / common_factor\n+ q = q / common_factor\n+ return common_factor * cls(p, q, evaluate=False)\n+\n # put 1.0 from G on inside\n if G.is_Float and G == 1:\n p *= G\n", + "test_patch": "diff --git a/sympy/core/tests/test_mod.py b/sympy/core/tests/test_mod.py\nnew file mode 100644\nindex 0000000..f0c3972\n--- /dev/null\n+++ b/sympy/core/tests/test_mod.py\n@@ -0,0 +1,7 @@\n+# File: sympy/core/tests/test_mod.py\n+\n+from sympy import Symbol, Mod\n+\n+def test_mod_issue():\n+ i = Symbol('i', integer=True)\n+ assert Mod(3*i, 2) == Mod(3*i, 2) # This should reproduce the issue\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/core/tests/test_mod_inverted.py b/sympy/core/tests/test_mod_inverted.py\nnew file mode 100644\nindex 0000000..d6c1a88\n--- /dev/null\n+++ b/sympy/core/tests/test_mod_inverted.py\n@@ -0,0 +1,8 @@\n+# File: sympy/core/tests/test_mod.py\n+\n+from sympy import Symbol, Mod\n+\n+def test_mod_issue():\n+ i = Symbol('i', integer=True)\n+ if Mod(3*i, 2) == Mod(3*i, 2): # This should reproduce the issue\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2831059, + "num_received_chars": 57315, + "elapsed_time": 546.9399540424347, + "lint_repair_count": 9, + "test_generation_attempts": 6, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15976.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15976.json new file mode 100644 index 00000000..27a2c14a --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-15976.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-15976", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/printing/mathml.py b/sympy/printing/mathml.py\nindex 3f8b8d4..d0449e6 100644\n--- a/sympy/printing/mathml.py\n+++ b/sympy/printing/mathml.py\n@@ -762,7 +762,8 @@ def join(items):\n return mrow\n else:\n mi = self.dom.createElement('mi')\n- mi.appendChild(self.dom.createTextNode(items[0]))\n+ # Ensure that numbers are part of the symbol name\n+ mi.appendChild(self.dom.createTextNode(''.join(items)))\n return mi\n \n # translate name, supers and subs to unicode characters\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1043289, + "num_received_chars": 23775, + "elapsed_time": 208.60303044319153, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-16766.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-16766.json new file mode 100644 index 00000000..8c99a734 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-16766.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-16766", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py\nindex a3f0310..d7f29ab 100644\n--- a/sympy/printing/pycode.py\n+++ b/sympy/printing/pycode.py\n@@ -349,6 +349,11 @@ def _print_NoneToken(self, arg):\n \n class PythonCodePrinter(AbstractPythonCodePrinter):\n \n+ def _print_Indexed(self, expr):\n+ base = self._print(expr.base)\n+ indices = ', '.join(self._print(i) for i in expr.indices)\n+ return f\"{base}[{indices}]\"\n+\n def _print_sign(self, e):\n return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(\n f=self._module_format('math.copysign'), e=self._print(e.args[0]))\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 868398, + "num_received_chars": 13571, + "elapsed_time": 173.6045880317688, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17139.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17139.json new file mode 100644 index 00000000..bfea54c8 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17139.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-17139", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/simplify/fu.py b/sympy/simplify/fu.py\nindex ad1130e..bc932db 100644\n--- a/sympy/simplify/fu.py\n+++ b/sympy/simplify/fu.py\n@@ -542,6 +542,8 @@ def TR5(rv, max=4, pow=False):\n >>> TR5(sin(x)**4)\n (1 - cos(x)**2)**2\n \"\"\"\n+ if rv.is_Pow and not rv.exp.is_real:\n+ return rv\n return _TR56(rv, sin, cos, lambda x: 1 - x, max=max, pow=pow)\n \n \n@@ -563,6 +565,8 @@ def TR6(rv, max=4, pow=False):\n >>> TR6(cos(x)**4)\n (1 - sin(x)**2)**2\n \"\"\"\n+ if rv.is_Pow and not rv.exp.is_real:\n+ return rv\n return _TR56(rv, cos, sin, lambda x: 1 - x, max=max, pow=pow)\n \n \n@@ -583,7 +587,7 @@ def TR7(rv):\n \"\"\"\n \n def f(rv):\n- if not (rv.is_Pow and rv.base.func == cos and rv.exp == 2):\n+ if not (rv.is_Pow and rv.base.func == cos and rv.exp.is_real and rv.exp == 2):\n return rv\n return (1 + cos(2*rv.base.args[0]))/2\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2632694, + "num_received_chars": 17349, + "elapsed_time": 374.6781234741211, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17655.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17655.json new file mode 100644 index 00000000..e872e372 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-17655.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-17655", + "edit_test_file": "sympy/geometry/tests/test_util.py", + "code_patch": "diff --git a/sympy/geometry/point.py b/sympy/geometry/point.py\nindex 7c978c4..fc54b13 100644\n--- a/sympy/geometry/point.py\n+++ b/sympy/geometry/point.py\n@@ -213,7 +213,18 @@ def __add__(self, other):\n sympy.geometry.point.Point.translate\n \n \"\"\"\n+ from sympy.core.mul import Mul\n+\n try:\n+ if isinstance(other, Mul):\n+ scalar, point = None, None\n+ for arg in other.args:\n+ if isinstance(arg, Point):\n+ point = arg\n+ elif arg.is_number:\n+ scalar = arg\n+ if scalar is not None and point is not None:\n+ other = Point([scalar * coord for coord in point.args], evaluate=False)\n s, o = Point._normalize_dimension(self, Point(other, evaluate=False))\n except TypeError:\n raise GeometryError(\"Don't know how to add {} and a Point object\".format(other))\n", + "test_patch": "diff --git a/sympy/geometry/tests/test_multiplication.py b/sympy/geometry/tests/test_multiplication.py\nnew file mode 100644\nindex 0000000..54d8dc6\n--- /dev/null\n+++ b/sympy/geometry/tests/test_multiplication.py\n@@ -0,0 +1,12 @@\n+import sympy\n+from sympy.geometry import Point\n+from sympy.geometry.exceptions import GeometryError\n+from sympy.utilities.pytest import raises\n+\n+def test_point_multiplication_exception():\n+ point1 = Point(0, 0)\n+ point2 = Point(1, 1)\n+ \n+ # This should raise a GeometryError\n+ with raises(GeometryError):\n+ result = point1 + sympy.sympify(2.0) * point2\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/geometry/tests/test_multiplication_inverted.py b/sympy/geometry/tests/test_multiplication_inverted.py\nnew file mode 100644\nindex 0000000..c2f4701\n--- /dev/null\n+++ b/sympy/geometry/tests/test_multiplication_inverted.py\n@@ -0,0 +1,13 @@\n+import sympy\n+from sympy.geometry import Point\n+from sympy.geometry.exceptions import GeometryError\n+\n+def test_point_multiplication_exception():\n+ point1 = Point(0, 0)\n+ point2 = Point(1, 1)\n+ \n+ # This should not raise a GeometryError, but it does due to the bug\n+ try:\n+ result = point1 + sympy.sympify(2.0) * point2\n+ except GeometryError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2006807, + "num_received_chars": 85459, + "elapsed_time": 828.6343874931335, + "lint_repair_count": 7, + "test_generation_attempts": 6, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-18211.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-18211.json new file mode 100644 index 00000000..aeeda079 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-18211.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-18211", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py\nindex 445be3e..4affc98 100644\n--- a/sympy/solvers/solveset.py\n+++ b/sympy/solvers/solveset.py\n@@ -1003,7 +1003,7 @@ def _solveset(f, symbol, domain, _check=False):\n if isinstance(result, ConditionSet):\n # it wasn't solved or has enumerated all conditions\n # -- leave it alone\n- return result\n+ return ConditionSet(symbol, Eq(f, 0), domain)\n \n # whittle away all but the symbol-containing core\n # to use this for testing\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1091228, + "num_received_chars": 12975, + "elapsed_time": 295.33127617836, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19040.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19040.json new file mode 100644 index 00000000..df207b00 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19040.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-19040", + "edit_test_file": "sympy/polys/tests/test_factortools.py", + "code_patch": "diff --git a/sympy/polys/polytools.py b/sympy/polys/polytools.py\nindex 68b69d1..901f08d 100644\n--- a/sympy/polys/polytools.py\n+++ b/sympy/polys/polytools.py\n@@ -5959,6 +5959,9 @@ def _symbolic_factor(expr, opt, method):\n if isinstance(expr, Expr):\n if hasattr(expr,'_eval_factor'):\n return expr._eval_factor()\n+ # Ensure that the extension is considered during factorization\n+ if 'extension' in opt:\n+ expr = expr.expand(complex=True)\n coeff, factors = _symbolic_factor_list(together(expr, fraction=opt['fraction']), opt, method)\n return _keep_coeff(coeff, _factors_product(factors))\n elif hasattr(expr, 'args'):\n@@ -6019,6 +6022,11 @@ def _generic_factor(expr, gens, args, method):\n options.allowed_flags(args, [])\n opt = options.build_options(gens, args)\n opt['fraction'] = fraction\n+\n+ # Ensure that the extension is properly handled\n+ if 'extension' in args:\n+ opt['extension'] = args['extension']\n+\n return _symbolic_factor(sympify(expr), opt, method)\n \n \n", + "test_patch": "diff --git a/sympy/polys/tests/test_factor_extension_issue.py b/sympy/polys/tests/test_factor_extension_issue.py\nnew file mode 100644\nindex 0000000..a69b3ea\n--- /dev/null\n+++ b/sympy/polys/tests/test_factor_extension_issue.py\n@@ -0,0 +1,8 @@\n+from sympy import symbols, expand, I\n+from sympy.polys.polytools import factor\n+\n+def test_factor_with_extension_drops_factor():\n+ x, y = symbols('x y')\n+ z = expand((x - 1) * (y - 1))\n+ factored = factor(z, extension=[I])\n+ assert factored == x - 1 # This is the incorrect output that reproduces the issue\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/polys/tests/test_factor_extension_issue_inverted.py b/sympy/polys/tests/test_factor_extension_issue_inverted.py\nnew file mode 100644\nindex 0000000..8f19a12\n--- /dev/null\n+++ b/sympy/polys/tests/test_factor_extension_issue_inverted.py\n@@ -0,0 +1,8 @@\n+from sympy import symbols, expand, I\n+from sympy.polys.polytools import factor\n+\n+def test_factor_with_extension_drops_factor():\n+ x, y = symbols('x y')\n+ z = expand((x - 1) * (y - 1))\n+ factored = factor(z, extension=[I])\n+ assert factored == (x - 1) * (y - 1), \"__BUG__HERE__\" # The test should fail here if the bug is present\n\\ No newline at end of file\n", + "num_sent_chars": 2517281, + "num_received_chars": 51548, + "elapsed_time": 424.8029842376709, + "lint_repair_count": 4, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19637.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19637.json new file mode 100644 index 00000000..5d8258fe --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-19637.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-19637", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/core/sympify.py b/sympy/core/sympify.py\nindex a3f1ce2..8b75fba 100644\n--- a/sympy/core/sympify.py\n+++ b/sympy/core/sympify.py\n@@ -468,12 +468,12 @@ def kernS(s):\n import string\n from random import choice\n from sympy.core.symbol import Symbol\n+ kern = '_'\n hit = False\n quoted = '\"' in s or \"'\" in s\n if '(' in s and not quoted:\n if s.count('(') != s.count(\")\"):\n raise SympifyError('unmatched left parenthesis')\n-\n # strip all space from s\n s = ''.join(s.split())\n olds = s\n@@ -509,19 +509,20 @@ def kernS(s):\n i = j + 2 # the first char after 2nd )\n if ' ' in s:\n # get a unique kern\n- kern = '_'\n while kern in s:\n kern += choice(string.ascii_letters + string.digits)\n s = s.replace(' ', kern)\n hit = kern in s\n-\n- for i in range(2):\n- try:\n- expr = sympify(s)\n- break\n- except TypeError: # the kern might cause unknown errors...\n- if hit:\n- s = olds # maybe it didn't like the kern; use un-kerned s\n+ for i in range(2):\n+ try:\n+ expr = sympify(s)\n+ break\n+ except TypeError: # the kern might cause unknown errors...\n+ if hit:\n+ s = olds # maybe it didn't like the kern; use un-kerned s\n+ hit = False\n+ continue\n+ expr = sympify(s) # let original error raise\n hit = False\n continue\n expr = sympify(s) # let original error raise\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 370917, + "num_received_chars": 7368, + "elapsed_time": 69.6132435798645, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20154.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20154.json new file mode 100644 index 00000000..5c58b9d6 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20154.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-20154", + "edit_test_file": "sympy/combinatorics/tests/test_partitions.py", + "code_patch": "diff --git a/sympy/utilities/iterables.py b/sympy/utilities/iterables.py\nindex dd36dea..3e46d5b 100644\n--- a/sympy/utilities/iterables.py\n+++ b/sympy/utilities/iterables.py\n@@ -1802,9 +1802,9 @@ def partitions(n, m=None, k=None, size=False):\n keys.append(r)\n room = m - q - bool(r)\n if size:\n- yield sum(ms.values()), ms\n+ yield sum(ms.values()), ms.copy()\n else:\n- yield ms\n+ yield ms.copy()\n \n while keys != [1]:\n # Reuse any 1's.\n@@ -1842,9 +1842,9 @@ def partitions(n, m=None, k=None, size=False):\n break\n room -= need\n if size:\n- yield sum(ms.values()), ms\n+ yield sum(ms.values()), ms.copy()\n else:\n- yield ms\n+ yield ms.copy()\n \n \n def ordered_partitions(n, m=None, sort=True):\n", + "test_patch": "diff --git a/sympy/combinatorics/tests/test_partitions_behavior.py b/sympy/combinatorics/tests/test_partitions_behavior.py\nnew file mode 100644\nindex 0000000..d2cc8a9\n--- /dev/null\n+++ b/sympy/combinatorics/tests/test_partitions_behavior.py\n@@ -0,0 +1,13 @@\n+from sympy.utilities.iterables import partitions\n+\n+def test_partitions_reuse_issue():\n+ # Generate partitions of 6 with k=2\n+ partition_list = list(partitions(6, k=2))\n+ \n+ # The expected result if dictionaries are not reused\n+ expected_result = [\n+ {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}\n+ ]\n+ \n+ # Check if the result is not as expected due to dictionary reuse\n+ assert partition_list != expected_result, \"The partitions() function is reusing dictionaries, leading to incorrect results.\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/combinatorics/tests/test_partitions_behavior_inverted.py b/sympy/combinatorics/tests/test_partitions_behavior_inverted.py\nnew file mode 100644\nindex 0000000..adcbef9\n--- /dev/null\n+++ b/sympy/combinatorics/tests/test_partitions_behavior_inverted.py\n@@ -0,0 +1,13 @@\n+from sympy.utilities.iterables import partitions\n+\n+def test_partitions_reuse_issue():\n+ # Generate partitions of 6 with k=2\n+ partition_list = list(partitions(6, k=2))\n+ \n+ # The expected result if dictionaries are not reused\n+ expected_result = [\n+ {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}\n+ ]\n+ \n+ # Check if the result is as expected, which should fail if dictionaries are reused\n+ assert partition_list == expected_result, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 537125, + "num_received_chars": 15887, + "elapsed_time": 147.07467579841614, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20590.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20590.json new file mode 100644 index 00000000..657ad335 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-20590.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-20590", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/core/assumptions.py b/sympy/core/assumptions.py\nindex c957931..80481da 100644\n--- a/sympy/core/assumptions.py\n+++ b/sympy/core/assumptions.py\n@@ -523,6 +523,8 @@ def _ask(fact, obj):\n \n class ManagedProperties(BasicMeta):\n \"\"\"Metaclass for classes with old-style assumptions\"\"\"\n+ __slots__ = () # Reintroduce __slots__ to prevent __dict__ creation\n+\n def __init__(cls, *args, **kws):\n BasicMeta.__init__(cls, *args, **kws)\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 940726, + "num_received_chars": 16059, + "elapsed_time": 178.7553026676178, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21379.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21379.json new file mode 100644 index 00000000..0af387fc --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21379.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-21379", + "edit_test_file": "sympy/core/tests/test_expr.py", + "code_patch": "diff --git a/sympy/polys/polyerrors.py b/sympy/polys/polyerrors.py\nindex 2cd7582..ea568c6 100644\n--- a/sympy/polys/polyerrors.py\n+++ b/sympy/polys/polyerrors.py\n@@ -113,7 +113,12 @@ class DomainError(BasePolynomialError):\n \n @public\n class PolynomialError(BasePolynomialError):\n- pass\n+ def __init__(self, message=None, *args):\n+ self.message = message or \"A polynomial error occurred\"\n+ super().__init__(*args)\n+\n+ def __str__(self):\n+ return self.message\n \n @public\n class UnificationFailed(BasePolynomialError):\n", + "test_patch": "diff --git a/sympy/core/tests/test_polynomial_error.py b/sympy/core/tests/test_polynomial_error.py\nnew file mode 100644\nindex 0000000..d43fb48\n--- /dev/null\n+++ b/sympy/core/tests/test_polynomial_error.py\n@@ -0,0 +1,11 @@\n+from sympy import symbols, exp, sinh, Piecewise\n+from sympy.core.cache import clear_cache\n+from sympy.testing.pytest import raises\n+from sympy.polys.polyerrors import PolynomialError\n+\n+def test_polynomial_error_with_subs():\n+ x, y, z = symbols('x y z', real=True)\n+ expr = exp(sinh(Piecewise((x, y > x), (y, True)) / z))\n+ \n+ with raises(PolynomialError):\n+ expr.subs({1: 1.0})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/core/tests/test_polynomial_error_inverted.py b/sympy/core/tests/test_polynomial_error_inverted.py\nnew file mode 100644\nindex 0000000..d734e78\n--- /dev/null\n+++ b/sympy/core/tests/test_polynomial_error_inverted.py\n@@ -0,0 +1,14 @@\n+from sympy import symbols, exp, sinh, Piecewise\n+from sympy.core.cache import clear_cache\n+from sympy.testing.pytest import raises\n+from sympy.polys.polyerrors import PolynomialError\n+\n+def test_polynomial_error_with_subs():\n+ x, y, z = symbols('x y z', real=True)\n+ expr = exp(sinh(Piecewise((x, y > x), (y, True)) / z))\n+ \n+ # Alter the test to fail when the bug is observed\n+ try:\n+ expr.subs({1: 1.0})\n+ except PolynomialError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 3021364, + "num_received_chars": 98672, + "elapsed_time": 957.9559082984924, + "lint_repair_count": 13, + "test_generation_attempts": 8, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21847.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21847.json new file mode 100644 index 00000000..1b97b819 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-21847.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-21847", + "edit_test_file": "sympy/polys/tests/test_monomials.py", + "code_patch": "diff --git a/sympy/polys/monomials.py b/sympy/polys/monomials.py\nindex 0e84403..244365b 100644\n--- a/sympy/polys/monomials.py\n+++ b/sympy/polys/monomials.py\n@@ -127,7 +127,8 @@ def itermonomials(variables, max_degrees, min_degrees=None):\n for variable in item:\n if variable != 1:\n powers[variable] += 1\n- if max(powers.values()) >= min_degree:\n+ total_deg = sum(powers.values())\n+ if min_degree <= total_deg <= max_degree:\n monomials_list_comm.append(Mul(*item))\n yield from set(monomials_list_comm)\n else:\n@@ -139,7 +140,8 @@ def itermonomials(variables, max_degrees, min_degrees=None):\n for variable in item:\n if variable != 1:\n powers[variable] += 1\n- if max(powers.values()) >= min_degree:\n+ total_deg = sum(powers.values())\n+ if min_degree <= total_deg <= max_degree:\n monomials_list_non_comm.append(Mul(*item))\n yield from set(monomials_list_non_comm)\n else:\n", + "test_patch": "diff --git a/sympy/polys/tests/test_itermonomials.py b/sympy/polys/tests/test_itermonomials.py\nnew file mode 100644\nindex 0000000..0cd52ed\n--- /dev/null\n+++ b/sympy/polys/tests/test_itermonomials.py\n@@ -0,0 +1,13 @@\n+import sympy as sp\n+from sympy.polys.orderings import monomial_key\n+from sympy.testing.pytest import raises\n+\n+def test_itermonomials_incorrect_monomials_with_min_degrees():\n+ x1, x2, x3 = sp.symbols('x1, x2, x3')\n+ states = [x1, x2, x3]\n+ max_degrees = 3\n+ min_degrees = 3\n+ monomials = sorted(sp.itermonomials(states, max_degrees, min_degrees=min_degrees), \n+ key=monomial_key('grlex', states))\n+ # The test should pass if the incorrect output is produced\n+ assert monomials == [x3**3, x2**3, x1**3], \"Expected incorrect output to reproduce the issue\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/polys/tests/test_itermonomials_inverted.py b/sympy/polys/tests/test_itermonomials_inverted.py\nnew file mode 100644\nindex 0000000..c18ba64\n--- /dev/null\n+++ b/sympy/polys/tests/test_itermonomials_inverted.py\n@@ -0,0 +1,16 @@\n+import sympy as sp\n+from sympy.polys.orderings import monomial_key\n+\n+def test_itermonomials_incorrect_monomials_with_min_degrees():\n+ x1, x2, x3 = sp.symbols('x1, x2, x3')\n+ states = [x1, x2, x3]\n+ max_degrees = 3\n+ min_degrees = 3\n+ monomials = sorted(sp.itermonomials(states, max_degrees, min_degrees=min_degrees), \n+ key=monomial_key('grlex', states))\n+ # The test should fail if the incorrect output is produced\n+ assert monomials != [x3**3, x2**3, x1**3], \"__BUG__HERE__\"\n+ # The correct expected output should include all monomials with total degree of 3\n+ expected_monomials = sorted([x1**3, x2**3, x3**3, x1*x2**2, x1*x3**2, x2*x1**2, x2*x3**2, x3*x1**2, x3*x2**2, x1*x2*x3], \n+ key=monomial_key('grlex', states))\n+ assert monomials == expected_monomials, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 395511, + "num_received_chars": 13294, + "elapsed_time": 123.83239316940308, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-22456.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-22456.json new file mode 100644 index 00000000..95e97cbf --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-22456.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-22456", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/core/basic.py b/sympy/core/basic.py\nindex 3461697..c541078 100644\n--- a/sympy/core/basic.py\n+++ b/sympy/core/basic.py\n@@ -133,6 +133,10 @@ def __getnewargs__(self):\n def __getstate__(self):\n return None\n \n+ def _reconstruct(self):\n+ \"\"\"Ensure that expr.func(*expr.args) == expr.\"\"\"\n+ return self.func(*self.args)\n+\n def __reduce_ex__(self, protocol):\n if protocol < 2:\n msg = \"Only pickle protocol 2 or higher is supported by SymPy\"\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1758102, + "num_received_chars": 32770, + "elapsed_time": 340.94671964645386, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23262.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23262.json new file mode 100644 index 00000000..e2371d39 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23262.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-23262", + "edit_test_file": "sympy/printing/tests/test_pycode.py", + "code_patch": "diff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py\nindex da67263..ced04b3 100644\n--- a/sympy/utilities/lambdify.py\n+++ b/sympy/utilities/lambdify.py\n@@ -959,6 +959,8 @@ def _recursive_to_string(doprint, arg):\n left, right = \"[]\"\n elif isinstance(arg, tuple):\n left, right = \"()\"\n+ if len(arg) == 1:\n+ return left + _recursive_to_string(doprint, arg[0]) + \",)\"\n else:\n raise NotImplementedError(\"unhandled type: %s, %s\" % (type(arg), arg))\n return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right\n", + "test_patch": "diff --git a/sympy/printing/tests/test_tuple_handling.py b/sympy/printing/tests/test_tuple_handling.py\nnew file mode 100644\nindex 0000000..2628ac4\n--- /dev/null\n+++ b/sympy/printing/tests/test_tuple_handling.py\n@@ -0,0 +1,9 @@\n+import inspect\n+from sympy import lambdify\n+\n+def test_lambdify_single_element_tuple():\n+ # Generate the source code for a lambdified function returning a single-element tuple\n+ source_code = inspect.getsource(lambdify([], tuple([1])))\n+\n+ # Assert that the generated source code does not contain a comma, indicating the issue\n+ assert source_code == 'def _lambdifygenerated():\\n return (1)\\n'\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/printing/tests/test_tuple_handling_inverted.py b/sympy/printing/tests/test_tuple_handling_inverted.py\nnew file mode 100644\nindex 0000000..d46f7b4\n--- /dev/null\n+++ b/sympy/printing/tests/test_tuple_handling_inverted.py\n@@ -0,0 +1,10 @@\n+import inspect\n+from sympy import lambdify\n+\n+def test_lambdify_single_element_tuple():\n+ # Generate the source code for a lambdified function returning a single-element tuple\n+ source_code = inspect.getsource(lambdify([], tuple([1])))\n+\n+ # Assert that the generated source code contains a comma, indicating the issue\n+ if source_code != 'def _lambdifygenerated():\\n return (1,)\\n':\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 670275, + "num_received_chars": 16811, + "elapsed_time": 168.91488480567932, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23824.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23824.json new file mode 100644 index 00000000..d444be06 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-23824.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-23824", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/physics/hep/gamma_matrices.py b/sympy/physics/hep/gamma_matrices.py\nindex 23284e4..bf43fac 100644\n--- a/sympy/physics/hep/gamma_matrices.py\n+++ b/sympy/physics/hep/gamma_matrices.py\n@@ -694,7 +694,7 @@ def kahane_simplify(expression):\n \n # If `first_dum_pos` is not zero, it means that there are trailing free gamma\n # matrices in front of `expression`, so multiply by them:\n- for i in range(0, first_dum_pos):\n+ for i in range(first_dum_pos - 1, -1, -1):\n [ri.insert(0, free_pos[i]) for ri in resulting_indices]\n \n resulting_expr = S.Zero\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1063322, + "num_received_chars": 19527, + "elapsed_time": 211.53287887573242, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24213.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24213.json new file mode 100644 index 00000000..0c4786f0 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24213.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-24213", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/physics/units/unitsystem.py b/sympy/physics/units/unitsystem.py\nindex a436880..5705c82 100644\n--- a/sympy/physics/units/unitsystem.py\n+++ b/sympy/physics/units/unitsystem.py\n@@ -175,7 +175,7 @@ def _collect_factor_and_dimension(self, expr):\n for addend in expr.args[1:]:\n addend_factor, addend_dim = \\\n self._collect_factor_and_dimension(addend)\n- if dim != addend_dim:\n+ if not self.get_dimension_system().equivalent_dims(dim, addend_dim):\n raise ValueError(\n 'Dimension of \"{}\" is {}, '\n 'but it should be {}'.format(\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 969507, + "num_received_chars": 25984, + "elapsed_time": 201.78232669830322, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24562.json b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24562.json new file mode 100644 index 00000000..bc18a1a2 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/code_patches/sympy__sympy-24562.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-24562", + "edit_test_file": "sympy/polys/tests/test_pythonrational.py", + "code_patch": "diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py\nindex 58d2635..7149f61 100644\n--- a/sympy/solvers/solveset.py\n+++ b/sympy/solvers/solveset.py\n@@ -17,7 +17,7 @@\n from sympy.core.function import (Lambda, expand_complex, AppliedUndef,\n expand_log, _mexpand, expand_trig, nfloat)\n from sympy.core.mod import Mod\n-from sympy.core.numbers import igcd, I, Number, Rational, oo, ilcm\n+from sympy.core.numbers import igcd, I, Number, Rational, oo, ilcm, Float\n from sympy.core.power import integer_log\n from sympy.core.relational import Eq, Ne, Relational\n from sympy.core.sorting import default_sort_key, ordered\n@@ -166,9 +166,13 @@ def _invert(f_x, y, x, domain=S.Complexes):\n x = sympify(x)\n if not x.is_Symbol:\n raise ValueError(\"x must be a symbol\")\n+ if isinstance(f_x, str):\n+ f_x = Float(f_x)\n f_x = sympify(f_x)\n if x not in f_x.free_symbols:\n raise ValueError(\"Inverse of constant function doesn't exist\")\n+ if isinstance(y, str):\n+ y = Float(y)\n y = sympify(y)\n if x in y.free_symbols:\n raise ValueError(\"y should be independent of x \")\n", + "test_patch": "diff --git a/sympy/polys/tests/test_sympy_rational.py b/sympy/polys/tests/test_sympy_rational.py\nnew file mode 100644\nindex 0000000..b6a3525\n--- /dev/null\n+++ b/sympy/polys/tests/test_sympy_rational.py\n@@ -0,0 +1,6 @@\n+from sympy import Rational\n+\n+def test_rational_calc_value_error():\n+ # This test reproduces the issue where Rational('0.5', '100') gives an incorrect value\n+ assert Rational('0.5', '100') == Rational(1, 100100), \"Rational('0.5', '100') should be 1/100100\"\n+ assert Rational(0.5, 100) == Rational(1, 200), \"Rational(0.5, 100) should be 1/200\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/polys/tests/test_sympy_rational_inverted.py b/sympy/polys/tests/test_sympy_rational_inverted.py\nnew file mode 100644\nindex 0000000..23aeda0\n--- /dev/null\n+++ b/sympy/polys/tests/test_sympy_rational_inverted.py\n@@ -0,0 +1,8 @@\n+from sympy import Rational\n+\n+def test_rational_calc_value_error():\n+ # This test should fail when the issue is observed\n+ # The bug is that Rational('0.5', '100') gives an incorrect value\n+ # The correct value should be Rational(1, 200)\n+ assert Rational('0.5', '100') == Rational(1, 200), \"__BUG__HERE__\"\n+ assert Rational(0.5, 100) == Rational(1, 200), \"Rational(0.5, 100) should be 1/200\"\n\\ No newline at end of file\n", + "num_sent_chars": 2252415, + "num_received_chars": 284415, + "elapsed_time": 1448.53728556633, + "lint_repair_count": 8, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10941127186/predictions-0.zip b/data/solve_code_runs/run_id/10941127186/predictions-0.zip new file mode 100644 index 00000000..c1337235 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/predictions-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bfe3f24f6708f5f77fc8f859430161887ec9e2e8e26d9d343b958c83c49f5a8 +size 188819 diff --git a/data/solve_code_runs/run_id/10941127186/predictions-1.zip b/data/solve_code_runs/run_id/10941127186/predictions-1.zip new file mode 100644 index 00000000..2dfad57b --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/predictions-1.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2bae96b640668730d46f9debf33e11e71148fe7564473b5dc7d50476e27fc60e +size 186303 diff --git a/data/solve_code_runs/run_id/10941127186/predictions-2.zip b/data/solve_code_runs/run_id/10941127186/predictions-2.zip new file mode 100644 index 00000000..ccc16748 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/predictions-2.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2f2d50057ab253556a23d3bfdf282aa16d1c00823dc36a92dba5bc866d5b2bb +size 175842 diff --git a/data/solve_code_runs/run_id/10941127186/report.zip b/data/solve_code_runs/run_id/10941127186/report.zip new file mode 100644 index 00000000..84fa48f4 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/report.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:daedecbdcbe4d76476eda8ac4269f378044e165790b99829131603e1476d5b6e +size 18141 diff --git a/data/solve_code_runs/run_id/10941127186/run_evaluation-0.zip b/data/solve_code_runs/run_id/10941127186/run_evaluation-0.zip new file mode 100644 index 00000000..ba999a32 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/run_evaluation-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:371025aa6208f521ffbcd4177c976a47360b9dd5897ceefb5f8a02103c4ba705 +size 829553 diff --git a/data/solve_code_runs/run_id/10941127186/run_evaluation-1.zip b/data/solve_code_runs/run_id/10941127186/run_evaluation-1.zip new file mode 100644 index 00000000..001486a1 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/run_evaluation-1.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4884a7df806439cf4d652897a6f4ce1c0d31a0d300e92c172f5d7b137df62e24 +size 791067 diff --git a/data/solve_code_runs/run_id/10941127186/run_evaluation-2.zip b/data/solve_code_runs/run_id/10941127186/run_evaluation-2.zip new file mode 100644 index 00000000..616eff88 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/run_evaluation-2.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d19a02e387fe62f50bd917f69730544194f4abfcf49d59332d477d4fb9fbeb3f +size 798182 diff --git a/data/solve_code_runs/run_id/10941127186/solutions.zip b/data/solve_code_runs/run_id/10941127186/solutions.zip new file mode 100644 index 00000000..0bc7cce7 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/solutions.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:736520270ea8ba61793d288de9164a7fad7e7f2b3f64d6043e524f26ff6efe66 +size 185346 diff --git a/data/solve_code_runs/run_id/10941127186/solve-0.zip b/data/solve_code_runs/run_id/10941127186/solve-0.zip new file mode 100644 index 00000000..8e66957f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/solve-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce4107f7edfdf261360d62351fcf93c00a93d59f928c2351d750de90757130dc +size 41836160 diff --git a/data/solve_code_runs/run_id/10941127186/solve-1.zip b/data/solve_code_runs/run_id/10941127186/solve-1.zip new file mode 100644 index 00000000..1571cbc4 --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/solve-1.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b849f372d2d746ef13c93eccb1ec08f363486bef670f63953ece9d0684d6487e +size 40170572 diff --git a/data/solve_code_runs/run_id/10941127186/solve-2.zip b/data/solve_code_runs/run_id/10941127186/solve-2.zip new file mode 100644 index 00000000..ed1df54f --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/solve-2.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d07862b730d2776fe486af5e5de199fb7ff9da197e0b014bcbc339b4be6e4c7 +size 37344424 diff --git a/data/solve_code_runs/run_id/10941127186/test-patch.zip b/data/solve_code_runs/run_id/10941127186/test-patch.zip new file mode 100644 index 00000000..a2bfad3e --- /dev/null +++ b/data/solve_code_runs/run_id/10941127186/test-patch.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7656396cda6a955a295e84614ad9085b54eeac42d22eb4273f59f78ab934d16e +size 77333 From 3ff4d6be0cc1001ba5568132fe8279686d649bea Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 14:26:50 -0400 Subject: [PATCH 4/9] fix: appmap-js fix/retry-claude-overload --- submodules/appmap-js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/submodules/appmap-js b/submodules/appmap-js index 1dcbe8df..23b3e204 160000 --- a/submodules/appmap-js +++ b/submodules/appmap-js @@ -1 +1 @@ -Subproject commit 1dcbe8df226ec1f1152521c6077f8368b6e2bc0b +Subproject commit 23b3e20416f6c60adf3240c99de95e7a35ee3447 From 6e45755ffedef825fa5e08aea42912ce35b03294 Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 20:06:49 -0400 Subject: [PATCH 5/9] data: Add sonnet_retry_error_2024-09-19 --- .../sonnet_retry_error_2024-09-19.txt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 data/instance_sets/sonnet_retry_error_2024-09-19.txt diff --git a/data/instance_sets/sonnet_retry_error_2024-09-19.txt b/data/instance_sets/sonnet_retry_error_2024-09-19.txt new file mode 100644 index 00000000..d2328964 --- /dev/null +++ b/data/instance_sets/sonnet_retry_error_2024-09-19.txt @@ -0,0 +1,19 @@ +# These instances from run https://github.com/getappmap/navie-benchmark/actions/runs/10949246453 +# are missing from the report, primarily due to Sonnet errors: +# Failed to complete: SSE Error: {"type":"error","error":{"details":null,"type":"invalid_request_error","message":"Output blocked by content filtering policy"} } +django__django-14539 +django__django-15280 +django__django-15563 +matplotlib__matplotlib-24870 +matplotlib__matplotlib-26113 +pydata__xarray-7233 +scikit-learn__scikit-learn-10908 +scikit-learn__scikit-learn-13779 +scikit-learn__scikit-learn-14710 +scikit-learn__scikit-learn-26194 +sympy__sympy-14531 +sympy__sympy-18211 +sympy__sympy-19040 +sympy__sympy-20154 +sympy__sympy-21379 +sympy__sympy-21847 \ No newline at end of file From f0bf6ecff2677e764f9c6bfa22c3e7b00db3c34f Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 20:48:47 -0400 Subject: [PATCH 6/9] feat: Add lower limits option --- .github/workflows/solve.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/solve.yml b/.github/workflows/solve.yml index 8afe1afd..3924c08f 100644 --- a/.github/workflows/solve.yml +++ b/.github/workflows/solve.yml @@ -22,6 +22,7 @@ on: required: true options: # Code solvers building synthetic tests + - test_files=2 test_status_retry=2 code_files=2 code_status_retry=2 - test_files=3 test_status_retry=3 code_files=3 code_status_retry=3 context_tokens: description: "LLM token limit to apply to the solver" From 382d4e88e222d657fed34701d9f53bbe915c3454 Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 20:07:51 -0400 Subject: [PATCH 7/9] data: Sonnet runs 10949246453 and 10950797630 10950797630 re-runs examples that errored out in the first run, including "Content policy" errors. Only one more resolved issue was obtained. --- .../code_patches/astropy__astropy-12907.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-13398.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-13977.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-14309.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-14508.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-14995.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-7606.json | 20 +++++++++++++++++++ .../code_patches/astropy__astropy-8872.json | 20 +++++++++++++++++++ .../code_patches/django__django-10880.json | 20 +++++++++++++++++++ .../code_patches/django__django-10999.json | 20 +++++++++++++++++++ .../code_patches/django__django-11095.json | 20 +++++++++++++++++++ .../code_patches/django__django-11133.json | 20 +++++++++++++++++++ .../code_patches/django__django-11149.json | 20 +++++++++++++++++++ .../code_patches/django__django-11206.json | 20 +++++++++++++++++++ .../code_patches/django__django-11265.json | 20 +++++++++++++++++++ .../code_patches/django__django-11299.json | 20 +++++++++++++++++++ .../code_patches/django__django-11433.json | 20 +++++++++++++++++++ .../code_patches/django__django-11490.json | 20 +++++++++++++++++++ .../code_patches/django__django-11555.json | 20 +++++++++++++++++++ .../code_patches/django__django-11734.json | 20 +++++++++++++++++++ .../code_patches/django__django-11790.json | 20 +++++++++++++++++++ .../code_patches/django__django-11848.json | 20 +++++++++++++++++++ .../code_patches/django__django-11951.json | 20 +++++++++++++++++++ .../code_patches/django__django-12039.json | 20 +++++++++++++++++++ .../code_patches/django__django-12143.json | 20 +++++++++++++++++++ .../code_patches/django__django-12209.json | 20 +++++++++++++++++++ .../code_patches/django__django-12276.json | 20 +++++++++++++++++++ .../code_patches/django__django-12325.json | 20 +++++++++++++++++++ .../code_patches/django__django-12663.json | 20 +++++++++++++++++++ .../code_patches/django__django-12741.json | 20 +++++++++++++++++++ .../code_patches/django__django-12858.json | 20 +++++++++++++++++++ .../code_patches/django__django-13023.json | 20 +++++++++++++++++++ .../code_patches/django__django-13089.json | 20 +++++++++++++++++++ .../code_patches/django__django-13121.json | 20 +++++++++++++++++++ .../code_patches/django__django-13195.json | 20 +++++++++++++++++++ .../code_patches/django__django-13297.json | 20 +++++++++++++++++++ .../code_patches/django__django-13344.json | 20 +++++++++++++++++++ .../code_patches/django__django-13401.json | 20 +++++++++++++++++++ .../code_patches/django__django-13417.json | 20 +++++++++++++++++++ .../code_patches/django__django-13513.json | 20 +++++++++++++++++++ .../code_patches/django__django-13568.json | 20 +++++++++++++++++++ .../code_patches/django__django-13658.json | 20 +++++++++++++++++++ .../code_patches/django__django-13786.json | 20 +++++++++++++++++++ .../code_patches/django__django-13809.json | 20 +++++++++++++++++++ .../code_patches/django__django-13821.json | 20 +++++++++++++++++++ .../code_patches/django__django-13933.json | 20 +++++++++++++++++++ .../code_patches/django__django-14011.json | 20 +++++++++++++++++++ .../code_patches/django__django-14053.json | 20 +++++++++++++++++++ .../code_patches/django__django-14140.json | 20 +++++++++++++++++++ .../code_patches/django__django-14238.json | 20 +++++++++++++++++++ .../code_patches/django__django-14349.json | 20 +++++++++++++++++++ .../code_patches/django__django-14376.json | 20 +++++++++++++++++++ .../code_patches/django__django-14493.json | 20 +++++++++++++++++++ .../code_patches/django__django-14608.json | 20 +++++++++++++++++++ .../code_patches/django__django-14725.json | 20 +++++++++++++++++++ .../code_patches/django__django-14771.json | 20 +++++++++++++++++++ .../code_patches/django__django-14855.json | 20 +++++++++++++++++++ .../code_patches/django__django-15022.json | 20 +++++++++++++++++++ .../code_patches/django__django-15103.json | 20 +++++++++++++++++++ .../code_patches/django__django-15128.json | 20 +++++++++++++++++++ .../code_patches/django__django-15268.json | 20 +++++++++++++++++++ .../code_patches/django__django-15375.json | 20 +++++++++++++++++++ .../code_patches/django__django-15467.json | 20 +++++++++++++++++++ .../code_patches/django__django-15525.json | 20 +++++++++++++++++++ .../code_patches/django__django-15629.json | 20 +++++++++++++++++++ .../code_patches/django__django-15732.json | 20 +++++++++++++++++++ .../code_patches/django__django-15851.json | 20 +++++++++++++++++++ .../code_patches/django__django-15930.json | 20 +++++++++++++++++++ .../code_patches/django__django-15987.json | 20 +++++++++++++++++++ .../code_patches/django__django-16100.json | 20 +++++++++++++++++++ .../code_patches/django__django-16139.json | 20 +++++++++++++++++++ .../code_patches/django__django-16256.json | 20 +++++++++++++++++++ .../code_patches/django__django-16333.json | 20 +++++++++++++++++++ .../code_patches/django__django-16485.json | 20 +++++++++++++++++++ .../code_patches/django__django-16527.json | 20 +++++++++++++++++++ .../code_patches/django__django-16595.json | 20 +++++++++++++++++++ .../code_patches/django__django-16642.json | 20 +++++++++++++++++++ .../code_patches/django__django-16667.json | 20 +++++++++++++++++++ .../code_patches/django__django-16877.json | 20 +++++++++++++++++++ .../code_patches/django__django-16938.json | 20 +++++++++++++++++++ .../code_patches/django__django-17084.json | 20 +++++++++++++++++++ .../code_patches/django__django-9296.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-20488.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-20859.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-22865.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-23314.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-24026.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-24570.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-25287.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-25479.json | 20 +++++++++++++++++++ .../matplotlib__matplotlib-26342.json | 20 +++++++++++++++++++ .../code_patches/mwaskom__seaborn-3187.json | 20 +++++++++++++++++++ .../code_patches/psf__requests-1724.json | 20 +++++++++++++++++++ .../code_patches/psf__requests-2317.json | 20 +++++++++++++++++++ .../code_patches/psf__requests-6028.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-3151.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-3993.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-4356.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-4695.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-6599.json | 20 +++++++++++++++++++ .../code_patches/pydata__xarray-6938.json | 20 +++++++++++++++++++ .../code_patches/pylint-dev__pylint-4604.json | 20 +++++++++++++++++++ .../code_patches/pylint-dev__pylint-6386.json | 20 +++++++++++++++++++ .../code_patches/pylint-dev__pylint-7080.json | 20 +++++++++++++++++++ .../pytest-dev__pytest-10051.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-5262.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-5809.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-6202.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-7324.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-7521.json | 20 +++++++++++++++++++ .../code_patches/pytest-dev__pytest-8399.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-12585.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-13124.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-13328.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-14141.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-15100.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-25747.json | 20 +++++++++++++++++++ .../sphinx-doc__sphinx-10323.json | 20 +++++++++++++++++++ .../sphinx-doc__sphinx-10466.json | 20 +++++++++++++++++++ .../sphinx-doc__sphinx-11445.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-7454.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-7748.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-7910.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8056.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8269.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8548.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8595.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-8721.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9258.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9367.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9602.json | 20 +++++++++++++++++++ .../code_patches/sphinx-doc__sphinx-9698.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-12096.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-12489.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13372.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13615.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13798.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-13878.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-15017.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-15599.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-15976.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-16766.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-17139.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-17655.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-19637.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-20590.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-22456.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-23262.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-23824.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-24213.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-24562.json | 20 +++++++++++++++++++ .../run_id/10949246453/predictions-0.zip | 3 +++ .../run_id/10949246453/predictions-1.zip | 3 +++ .../run_id/10949246453/predictions-2.zip | 3 +++ .../run_id/10949246453/predictions-3.zip | 3 +++ .../run_id/10949246453/predictions-4.zip | 3 +++ .../run_id/10949246453/predictions-5.zip | 3 +++ .../run_id/10949246453/report.zip | 3 +++ .../run_id/10949246453/run_evaluation-0.zip | 3 +++ .../run_id/10949246453/run_evaluation-1.zip | 3 +++ .../run_id/10949246453/run_evaluation-2.zip | 3 +++ .../run_id/10949246453/run_evaluation-3.zip | 3 +++ .../run_id/10949246453/run_evaluation-4.zip | 3 +++ .../run_id/10949246453/run_evaluation-5.zip | 3 +++ .../run_id/10949246453/solutions.zip | 3 +++ .../run_id/10949246453/solve-0.zip | 3 +++ .../run_id/10949246453/solve-1.zip | 3 +++ .../run_id/10949246453/solve-2.zip | 3 +++ .../run_id/10949246453/solve-3.zip | 3 +++ .../run_id/10949246453/solve-4.zip | 3 +++ .../run_id/10949246453/solve-5.zip | 3 +++ .../run_id/10949246453/test-patch.zip | 3 +++ .../code_patches/django__django-15280.json | 20 +++++++++++++++++++ .../code_patches/django__django-15563.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-10908.json | 20 +++++++++++++++++++ .../scikit-learn__scikit-learn-13779.json | 20 +++++++++++++++++++ .../code_patches/sympy__sympy-19040.json | 20 +++++++++++++++++++ .../run_id/10950797630/predictions-0.zip | 3 +++ .../run_id/10950797630/report.zip | 3 +++ .../run_id/10950797630/run_evaluation-0.zip | 3 +++ .../run_id/10950797630/solutions.zip | 3 +++ .../run_id/10950797630/solve-0.zip | 3 +++ .../run_id/10950797630/test-patch.zip | 3 +++ 183 files changed, 3201 insertions(+) create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-12907.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13398.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13977.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14309.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14508.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14995.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-7606.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-8872.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-10880.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-10999.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11095.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11133.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11149.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11206.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11265.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11299.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11433.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11490.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11555.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11734.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11790.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11848.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-11951.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12039.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12143.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12209.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12276.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12325.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12663.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12741.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-12858.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13023.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13089.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13121.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13195.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13297.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13344.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13401.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13417.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13513.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13568.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13658.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13786.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13809.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13821.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-13933.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14011.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14053.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14140.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14238.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14349.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14376.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14493.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14608.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14725.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14771.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-14855.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15022.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15103.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15128.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15268.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15375.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15467.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15525.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15629.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15732.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15851.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15930.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-15987.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16100.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16139.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16256.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16333.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16485.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16527.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16595.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16642.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16667.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16877.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-16938.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-17084.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/django__django-9296.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20488.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20859.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-22865.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-23314.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24026.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24570.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25287.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25479.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-26342.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/mwaskom__seaborn-3187.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-1724.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-2317.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-6028.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3151.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3993.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4356.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4695.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6599.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6938.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-4604.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-6386.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-7080.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-10051.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5262.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5809.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-6202.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7324.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7521.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-8399.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-12585.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13124.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13328.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-14141.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-15100.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-25747.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10323.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10466.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-11445.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7454.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7748.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7910.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8056.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8269.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8548.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8595.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8721.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9258.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9367.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9602.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9698.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12096.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12489.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13372.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13615.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13798.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13878.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15017.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15599.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15976.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-16766.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17139.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17655.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-19637.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-20590.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-22456.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23262.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23824.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24213.json create mode 100644 data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24562.json create mode 100644 data/solve_code_runs/run_id/10949246453/predictions-0.zip create mode 100644 data/solve_code_runs/run_id/10949246453/predictions-1.zip create mode 100644 data/solve_code_runs/run_id/10949246453/predictions-2.zip create mode 100644 data/solve_code_runs/run_id/10949246453/predictions-3.zip create mode 100644 data/solve_code_runs/run_id/10949246453/predictions-4.zip create mode 100644 data/solve_code_runs/run_id/10949246453/predictions-5.zip create mode 100644 data/solve_code_runs/run_id/10949246453/report.zip create mode 100644 data/solve_code_runs/run_id/10949246453/run_evaluation-0.zip create mode 100644 data/solve_code_runs/run_id/10949246453/run_evaluation-1.zip create mode 100644 data/solve_code_runs/run_id/10949246453/run_evaluation-2.zip create mode 100644 data/solve_code_runs/run_id/10949246453/run_evaluation-3.zip create mode 100644 data/solve_code_runs/run_id/10949246453/run_evaluation-4.zip create mode 100644 data/solve_code_runs/run_id/10949246453/run_evaluation-5.zip create mode 100644 data/solve_code_runs/run_id/10949246453/solutions.zip create mode 100644 data/solve_code_runs/run_id/10949246453/solve-0.zip create mode 100644 data/solve_code_runs/run_id/10949246453/solve-1.zip create mode 100644 data/solve_code_runs/run_id/10949246453/solve-2.zip create mode 100644 data/solve_code_runs/run_id/10949246453/solve-3.zip create mode 100644 data/solve_code_runs/run_id/10949246453/solve-4.zip create mode 100644 data/solve_code_runs/run_id/10949246453/solve-5.zip create mode 100644 data/solve_code_runs/run_id/10949246453/test-patch.zip create mode 100644 data/solve_code_runs/run_id/10950797630/code_patches/django__django-15280.json create mode 100644 data/solve_code_runs/run_id/10950797630/code_patches/django__django-15563.json create mode 100644 data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-10908.json create mode 100644 data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-13779.json create mode 100644 data/solve_code_runs/run_id/10950797630/code_patches/sympy__sympy-19040.json create mode 100644 data/solve_code_runs/run_id/10950797630/predictions-0.zip create mode 100644 data/solve_code_runs/run_id/10950797630/report.zip create mode 100644 data/solve_code_runs/run_id/10950797630/run_evaluation-0.zip create mode 100644 data/solve_code_runs/run_id/10950797630/solutions.zip create mode 100644 data/solve_code_runs/run_id/10950797630/solve-0.zip create mode 100644 data/solve_code_runs/run_id/10950797630/test-patch.zip diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-12907.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-12907.json new file mode 100644 index 00000000..2a2bc330 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-12907.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-12907", + "edit_test_file": "astropy/modeling/tests/test_separable.py", + "code_patch": "diff --git a/astropy/modeling/separable.py b/astropy/modeling/separable.py\nindex a308e27..d2521af 100644\n--- a/astropy/modeling/separable.py\n+++ b/astropy/modeling/separable.py\n@@ -306,7 +306,21 @@ def _separable(transform):\n elif isinstance(transform, CompoundModel):\n sepleft = _separable(transform.left)\n sepright = _separable(transform.right)\n- return _operators[transform.op](sepleft, sepright)\n+ \n+ # Handle nested CompoundModels recursively\n+ if isinstance(transform.left, CompoundModel):\n+ sepleft = _separable(transform.left)\n+ if isinstance(transform.right, CompoundModel):\n+ sepright = _separable(transform.right)\n+ \n+ # Combine separability information\n+ combined = _operators[transform.op](sepleft, sepright)\n+ \n+ # Ensure the result has the correct shape\n+ if combined.shape != (transform.n_outputs, transform.n_inputs):\n+ combined = np.resize(combined, (transform.n_outputs, transform.n_inputs))\n+ \n+ return combined\n elif isinstance(transform, Model):\n return _coord_matrix(transform, 'left', transform.n_outputs)\n \n", + "test_patch": "diff --git a/astropy/modeling/tests/test_nested_compound_separability.py b/astropy/modeling/tests/test_nested_compound_separability.py\nnew file mode 100644\nindex 0000000..e9227e8\n--- /dev/null\n+++ b/astropy/modeling/tests/test_nested_compound_separability.py\n@@ -0,0 +1,42 @@\n+import pytest\n+import numpy as np\n+from astropy.modeling import models as m\n+from astropy.modeling.separable import separability_matrix\n+\n+def test_nested_compound_model_separability():\n+ # Create a compound model\n+ cm = m.Linear1D(10) & m.Linear1D(5)\n+ \n+ # Test the separability of the compound model\n+ assert np.array_equal(separability_matrix(cm), \n+ np.array([[True, False],\n+ [False, True]]))\n+ \n+ # Create a more complex model\n+ complex_model = m.Pix2Sky_TAN() & m.Linear1D(10) & m.Linear1D(5)\n+ \n+ # Test the separability of the complex model\n+ assert np.array_equal(separability_matrix(complex_model),\n+ np.array([[True, True, False, False],\n+ [True, True, False, False],\n+ [False, False, True, False],\n+ [False, False, False, True]]))\n+ \n+ # Create a nested compound model\n+ nested_model = m.Pix2Sky_TAN() & cm\n+ \n+ # Test the separability of the nested compound model\n+ # This assertion will pass when the issue is present\n+ assert np.array_equal(separability_matrix(nested_model),\n+ np.array([[True, True, False, False],\n+ [True, True, False, False],\n+ [False, False, True, True],\n+ [False, False, True, True]]))\n+ \n+ # The following assertion would be the correct behavior\n+ # Uncomment this to test for the expected correct output\n+ # assert np.array_equal(separability_matrix(nested_model),\n+ # np.array([[True, True, False, False],\n+ # [True, True, False, False],\n+ # [False, False, True, False],\n+ # [False, False, False, True]]))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/modeling/tests/test_nested_compound_separability_inverted.py b/astropy/modeling/tests/test_nested_compound_separability_inverted.py\nnew file mode 100644\nindex 0000000..f12bc45\n--- /dev/null\n+++ b/astropy/modeling/tests/test_nested_compound_separability_inverted.py\n@@ -0,0 +1,51 @@\n+import pytest\n+import numpy as np\n+from astropy.modeling import models as m\n+from astropy.modeling.separable import separability_matrix\n+\n+def test_nested_compound_model_separability():\n+ # Create a compound model\n+ cm = m.Linear1D(10) & m.Linear1D(5)\n+ \n+ # Test the separability of the compound model\n+ assert np.array_equal(separability_matrix(cm), \n+ np.array([[True, False],\n+ [False, True]]))\n+ \n+ # Create a more complex model\n+ complex_model = m.Pix2Sky_TAN() & m.Linear1D(10) & m.Linear1D(5)\n+ \n+ # Test the separability of the complex model\n+ assert np.array_equal(separability_matrix(complex_model),\n+ np.array([[True, True, False, False],\n+ [True, True, False, False],\n+ [False, False, True, False],\n+ [False, False, False, True]]))\n+ \n+ # Create a nested compound model\n+ nested_model = m.Pix2Sky_TAN() & cm\n+ \n+ # Test the separability of the nested compound model\n+ # This assertion will now fail when the issue is present\n+ expected_matrix = np.array([[True, True, False, False],\n+ [True, True, False, False],\n+ [False, False, True, False],\n+ [False, False, False, True]])\n+ \n+ actual_matrix = separability_matrix(nested_model)\n+ \n+ if not np.array_equal(actual_matrix, expected_matrix):\n+ raise AssertionError(\"__BUG__HERE__: Incorrect separability matrix for nested compound model. \"\n+ f\"Expected:\\n{expected_matrix}\\nGot:\\n{actual_matrix}\")\n+\n+ # Additional test to ensure the bug is not a false positive\n+ simple_nested_model = m.Gaussian1D() & (m.Gaussian1D() + m.Gaussian1D())\n+ simple_expected_matrix = np.array([[True, False, False],\n+ [False, True, True],\n+ [False, True, True]])\n+ \n+ simple_actual_matrix = separability_matrix(simple_nested_model)\n+ \n+ if not np.array_equal(simple_actual_matrix, simple_expected_matrix):\n+ raise AssertionError(\"__BUG__HERE__: Incorrect separability matrix for simple nested compound model. \"\n+ f\"Expected:\\n{simple_expected_matrix}\\nGot:\\n{simple_actual_matrix}\")\n\\ No newline at end of file\n", + "num_sent_chars": 3013494, + "num_received_chars": 88985, + "elapsed_time": 584.3413641452789, + "lint_repair_count": 12, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13398.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13398.json new file mode 100644 index 00000000..76ab762c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13398.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-13398", + "edit_test_file": null, + "code_patch": "diff --git a/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.py b/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.py\nindex a15248c..2506f5c 100644\n--- a/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.py\n+++ b/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.py\n@@ -8,15 +8,19 @@ rotations without aberration corrections or offsets.\n import numpy as np\n import erfa\n \n+from astropy import units as u\n from astropy.coordinates.baseframe import frame_transform_graph\n from astropy.coordinates.transformations import FunctionTransformWithFiniteDifference\n-from astropy.coordinates.matrix_utilities import matrix_transpose\n+from astropy.coordinates.matrix_utilities import matrix_transpose, matrix_product\n+from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation\n \n from .icrs import ICRS\n from .gcrs import GCRS, PrecessedGeocentric\n from .cirs import CIRS\n from .itrs import ITRS\n from .equatorial import TEME, TETE\n+from .altaz import AltAz\n+from .hadec import HADec\n from .utils import get_polar_motion, get_jd12, EARTH_CENTER\n \n # # first define helper functions\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 484357, + "num_received_chars": 19060, + "elapsed_time": 148.52034497261047, + "lint_repair_count": 1, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13977.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13977.json new file mode 100644 index 00000000..3147dc16 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-13977.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-13977", + "edit_test_file": "astropy/units/tests/test_quantity_ufuncs.py", + "code_patch": "diff --git a/astropy/units/core.py b/astropy/units/core.py\nindex 8c3204b..0524932 100644\n--- a/astropy/units/core.py\n+++ b/astropy/units/core.py\n@@ -2614,23 +2614,23 @@ def _condition_arg(value):\n \n Returns\n -------\n- Scalar value or numpy array\n+ Scalar value, numpy array, or NotImplemented\n \n- Raises\n- ------\n- ValueError\n- If value is not as expected\n+ Notes\n+ -----\n+ Returns NotImplemented if the value is not scalar compatible or\n+ convertible to an int, float, or complex array.\n \"\"\"\n if isinstance(value, (np.ndarray, float, int, complex, np.void)):\n return value\n \n- avalue = np.array(value)\n- if avalue.dtype.kind not in [\"i\", \"f\", \"c\"]:\n- raise ValueError(\n- \"Value not scalar compatible or convertible to \"\n- \"an int, float, or complex array\"\n- )\n- return avalue\n+ try:\n+ avalue = np.array(value)\n+ if avalue.dtype.kind not in [\"i\", \"f\", \"c\"]:\n+ return NotImplemented\n+ return avalue\n+ except Exception:\n+ return NotImplemented\n \n \n def unit_scale_converter(val):\n", + "test_patch": "diff --git a/astropy/units/tests/test_quantity_ufunc_compatibility.py b/astropy/units/tests/test_quantity_ufunc_compatibility.py\nnew file mode 100644\nindex 0000000..ffc60f2\n--- /dev/null\n+++ b/astropy/units/tests/test_quantity_ufunc_compatibility.py\n@@ -0,0 +1,43 @@\n+# astropy/units/tests/test_quantity_ufunc_compatibility.py\n+\n+import numpy as np\n+import pytest\n+from astropy import units as u\n+from astropy.units import Quantity\n+\n+class DuckArray:\n+ def __init__(self, ndarray):\n+ self.ndarray = ndarray\n+\n+ @property\n+ def unit(self):\n+ return self.ndarray.unit\n+\n+ def __array_ufunc__(self, function, method, *inputs, **kwargs):\n+ inputs = [inp.ndarray if isinstance(inp, DuckArray) else inp for inp in inputs]\n+\n+ for inp in inputs:\n+ if isinstance(inp, np.ndarray):\n+ result = inp.__array_ufunc__(function, method, *inputs, **kwargs)\n+ if result is not NotImplemented:\n+ return DuckArray(result)\n+\n+ return NotImplemented\n+\n+class TestQuantityUfuncCompatibility:\n+ def test_quantity_ufunc_with_duck_array(self):\n+ # This operation works as expected\n+ result1 = DuckArray(1 * u.mm) + (1 * u.m)\n+ assert isinstance(result1, DuckArray)\n+ assert result1.unit == u.mm\n+ assert result1.ndarray.value == 1001\n+\n+ # This operation also works as expected\n+ result2 = (1 * u.mm) + DuckArray(1 * u.mm)\n+ assert isinstance(result2, DuckArray)\n+ assert result2.unit == u.mm\n+ assert result2.ndarray.value == 2\n+\n+ # This operation should raise a ValueError\n+ with pytest.raises(ValueError, match=\"Value not scalar compatible or convertible to an int, float, or complex array\"):\n+ (1 * u.m) + DuckArray(1 * u.mm)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/units/tests/test_quantity_ufunc_compatibility_inverted.py b/astropy/units/tests/test_quantity_ufunc_compatibility_inverted.py\nnew file mode 100644\nindex 0000000..38b0ba6\n--- /dev/null\n+++ b/astropy/units/tests/test_quantity_ufunc_compatibility_inverted.py\n@@ -0,0 +1,59 @@\n+# astropy/units/tests/test_quantity_ufunc_compatibility.py\n+\n+import numpy as np\n+import pytest\n+from astropy import units as u\n+from astropy.units import Quantity\n+\n+class DuckArray:\n+ def __init__(self, ndarray):\n+ self.ndarray = ndarray\n+\n+ @property\n+ def unit(self):\n+ return self.ndarray.unit\n+\n+ def __array_ufunc__(self, function, method, *inputs, **kwargs):\n+ inputs = [inp.ndarray if isinstance(inp, DuckArray) else inp for inp in inputs]\n+\n+ for inp in inputs:\n+ if isinstance(inp, np.ndarray):\n+ result = inp.__array_ufunc__(function, method, *inputs, **kwargs)\n+ if result is not NotImplemented:\n+ return DuckArray(result)\n+\n+ return NotImplemented\n+\n+class TestQuantityUfuncCompatibility:\n+ def test_quantity_ufunc_with_duck_array(self):\n+ # This operation works as expected\n+ result1 = DuckArray(1 * u.mm) + (1 * u.m)\n+ assert isinstance(result1, DuckArray)\n+ assert result1.unit == u.mm\n+ assert result1.ndarray.value == 1001\n+\n+ # This operation also works as expected\n+ result2 = (1 * u.mm) + DuckArray(1 * u.mm)\n+ assert isinstance(result2, DuckArray)\n+ assert result2.unit == u.mm\n+ assert result2.ndarray.value == 2\n+\n+ # This operation should return NotImplemented instead of raising ValueError\n+ try:\n+ (1 * u.m) + DuckArray(1 * u.mm)\n+ except ValueError as e:\n+ if \"Value not scalar compatible or convertible to an int, float, or complex array\" in str(e):\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ else:\n+ # If no ValueError is raised, the test should pass\n+ pass\n+\n+ def test_quantity_ufunc_returns_notimplemented(self):\n+ # This test explicitly checks if NotImplemented is returned\n+ q = Quantity(1, u.m)\n+ da = DuckArray(Quantity(1, u.mm))\n+ \n+ result = q.__array_ufunc__(np.add, '__call__', q, da)\n+ \n+ if result is not NotImplemented:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1747934, + "num_received_chars": 90713, + "elapsed_time": 626.2269251346588, + "lint_repair_count": 3, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14309.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14309.json new file mode 100644 index 00000000..cb4dd415 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14309.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-14309", + "edit_test_file": "astropy/io/registry/tests/test_registries.py", + "code_patch": "diff --git a/astropy/io/registry/base.py b/astropy/io/registry/base.py\nindex 0ac2a20..fd977ab 100644\n--- a/astropy/io/registry/base.py\n+++ b/astropy/io/registry/base.py\n@@ -307,13 +307,20 @@ class _UnifiedIORegistryBase(metaclass=abc.ABCMeta):\n valid_formats : list\n List of matching formats.\n \"\"\"\n+ # Handle empty args safely\n+ if not args:\n+ args = (None,) # Add a default value to prevent IndexError\n valid_formats = []\n for data_format, data_class in self._identifiers:\n if self._is_best_match(data_class_required, data_class, self._identifiers):\n- if self._identifiers[(data_format, data_class)](\n- origin, path, fileobj, *args, **kwargs\n- ):\n- valid_formats.append(data_format)\n+ try:\n+ if self._identifiers[(data_format, data_class)](\n+ origin, path, fileobj, *args, **kwargs\n+ ):\n+ valid_formats.append(data_format)\n+ except IndexError:\n+ # Skip identifiers that require arguments when args is empty\n+ continue\n \n return valid_formats\n \n", + "test_patch": "diff --git a/astropy/io/registry/tests/test_identify_format_error.py b/astropy/io/registry/tests/test_identify_format_error.py\nnew file mode 100644\nindex 0000000..1830bbe\n--- /dev/null\n+++ b/astropy/io/registry/tests/test_identify_format_error.py\n@@ -0,0 +1,10 @@\n+import pytest\n+from astropy.io.registry import identify_format\n+from astropy.table import Table\n+\n+def test_identify_format_index_error():\n+ \"\"\"\n+ Test that identify_format raises an IndexError when called with a non-FITS file.\n+ \"\"\"\n+ with pytest.raises(IndexError):\n+ identify_format(\"write\", Table, \"bububu.ecsv\", None, [], {})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/io/registry/tests/test_identify_format_error_inverted.py b/astropy/io/registry/tests/test_identify_format_error_inverted.py\nnew file mode 100644\nindex 0000000..ee8ad9f\n--- /dev/null\n+++ b/astropy/io/registry/tests/test_identify_format_error_inverted.py\n@@ -0,0 +1,16 @@\n+import pytest\n+from astropy.io.registry import identify_format\n+from astropy.table import Table\n+\n+def test_identify_format_index_error():\n+ \"\"\"\n+ Test that identify_format raises an IndexError when called with a non-FITS file.\n+ \"\"\"\n+ try:\n+ identify_format(\"write\", Table, \"bububu.ecsv\", None, [], {})\n+ except IndexError:\n+ pytest.fail(\"__BUG__HERE__\")\n+ except Exception as e:\n+ pytest.fail(f\"Unexpected exception raised: {type(e).__name__}\")\n+ else:\n+ pytest.fail(\"Expected IndexError, but no exception was raised\")\n\\ No newline at end of file\n", + "num_sent_chars": 1450194, + "num_received_chars": 77206, + "elapsed_time": 495.06201362609863, + "lint_repair_count": 6, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14508.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14508.json new file mode 100644 index 00000000..43cc60fe --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14508.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-14508", + "edit_test_file": null, + "code_patch": "diff --git a/astropy/io/fits/card.py b/astropy/io/fits/card.py\nindex 118bfce..73720df 100644\n--- a/astropy/io/fits/card.py\n+++ b/astropy/io/fits/card.py\n@@ -1299,6 +1299,20 @@ def _format_value(value):\n \n def _format_float(value):\n \"\"\"Format a floating number to make sure it gets the decimal point.\"\"\"\n+ import math\n+\n+ # Handle special cases\n+ if math.isnan(value):\n+ return \"NaN\"\n+ if math.isinf(value):\n+ return \"inf\" if value > 0 else \"-inf\"\n+\n+ # Try default string representation first\n+ value_str = str(value)\n+ if len(value_str) <= 20 and float(value_str) == value:\n+ return value_str\n+\n+ # Fall back to the previous method if the default representation is too long\n value_str = f\"{value:.16G}\"\n if \".\" not in value_str and \"E\" not in value_str:\n value_str += \".0\"\n@@ -1317,6 +1331,19 @@ def _format_float(value):\n # Limit the value string to at most 20 characters.\n str_len = len(value_str)\n \n+ # If the string is still too long, try reducing precision\n+ if str_len > 20:\n+ for precision in range(15, 0, -1):\n+ value_str = f\"{value:.{precision}G}\"\n+ if len(value_str) <= 20 and float(value_str) == value:\n+ break\n+\n+ # If all else fails, truncate the string\n+ if len(value_str) > 20:\n+ value_str = value_str[:20]\n+\n+ return value_str\n+\n if str_len > 20:\n idx = value_str.find(\"E\")\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 3190443, + "num_received_chars": 103970, + "elapsed_time": 1720.1030640602112, + "lint_repair_count": 6, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14995.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14995.json new file mode 100644 index 00000000..229611b8 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-14995.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-14995", + "edit_test_file": "astropy/nddata/tests/test_nddata.py", + "code_patch": "diff --git a/astropy/nddata/mixins/ndarithmetic.py b/astropy/nddata/mixins/ndarithmetic.py\nindex 4153dfc..203d790 100644\n--- a/astropy/nddata/mixins/ndarithmetic.py\n+++ b/astropy/nddata/mixins/ndarithmetic.py\n@@ -486,8 +486,8 @@ class NDArithmeticMixin:\n \"\"\"\n Calculate the resulting mask.\n \n- This is implemented as the piecewise ``or`` operation if both have a\n- mask.\n+ If only one operand has a mask, that mask is returned.\n+ If both operands have masks, the result is calculated using ``handle_mask``.\n \n Parameters\n ----------\n@@ -513,14 +513,14 @@ class NDArithmeticMixin:\n ``handle_mask`` must create (and copy) the returned mask.\n \"\"\"\n # If only one mask is present we need not bother about any type checks\n- if (\n- self.mask is None and operand is not None and operand.mask is None\n- ) or handle_mask is None:\n+ if handle_mask is None:\n+ return None\n+ elif self.mask is None and operand is not None and operand.mask is None:\n return None\n elif self.mask is None and operand is not None:\n # Make a copy so there is no reference in the result.\n return deepcopy(operand.mask)\n- elif operand is None:\n+ elif operand is None or operand.mask is None:\n return deepcopy(self.mask)\n else:\n # Now lets calculate the resulting mask (operation enforces copy)\n@@ -535,6 +535,13 @@ class NDArithmeticMixin:\n properly with `~astropy.wcs.WCS` (which is the suggested class for\n storing as wcs property) but it will not break it neither.\n \n+ Parameters\n+ ----------\n+ operation : callable\n+ see :meth:`NDArithmeticMixin._arithmetic` parameter description.\n+ By default, the ``operation`` will be ignored.\n+ storing as wcs property) but it will not break it neither.\n+\n Parameters\n ----------\n operation : callable\n", + "test_patch": "diff --git a/astropy/nddata/tests/test_mask_propagation.py b/astropy/nddata/tests/test_mask_propagation.py\nnew file mode 100644\nindex 0000000..168773d\n--- /dev/null\n+++ b/astropy/nddata/tests/test_mask_propagation.py\n@@ -0,0 +1,26 @@\n+import numpy as np\n+import pytest\n+from astropy.nddata import NDDataRef\n+\n+def test_mask_propagation_with_no_mask():\n+ array = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])\n+ mask = np.array([[0, 1, 64], [8, 0, 1], [2, 1, 0]])\n+\n+ nref_nomask = NDDataRef(array)\n+ nref_mask = NDDataRef(array, mask=mask)\n+\n+ # Test multiplication of masked data with constant (mask * no mask)\n+ with pytest.raises(TypeError, match=r\"unsupported operand type\\(s\\) for \\|: 'int' and 'NoneType'\"):\n+ nref_mask.multiply(1., handle_mask=np.bitwise_or)\n+\n+ # Test multiplication of masked data with unmasked data (mask * no mask)\n+ with pytest.raises(TypeError, match=r\"unsupported operand type\\(s\\) for \\|: 'int' and 'NoneType'\"):\n+ nref_mask.multiply(nref_nomask, handle_mask=np.bitwise_or)\n+\n+ # Test that multiplication of masked data with itself works correctly\n+ result = nref_mask.multiply(nref_mask, handle_mask=np.bitwise_or)\n+ np.testing.assert_array_equal(result.mask, mask)\n+\n+ # Test that multiplication of unmasked data works without errors\n+ assert nref_nomask.multiply(1., handle_mask=np.bitwise_or).mask is None\n+ assert nref_nomask.multiply(nref_nomask, handle_mask=np.bitwise_or).mask is None\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/astropy/nddata/tests/test_mask_propagation_inverted.py b/astropy/nddata/tests/test_mask_propagation_inverted.py\nnew file mode 100644\nindex 0000000..f0eaaa2\n--- /dev/null\n+++ b/astropy/nddata/tests/test_mask_propagation_inverted.py\n@@ -0,0 +1,38 @@\n+import numpy as np\n+import pytest\n+from astropy.nddata import NDDataRef\n+\n+def test_mask_propagation_with_no_mask():\n+ array = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])\n+ mask = np.array([[0, 1, 64], [8, 0, 1], [2, 1, 0]])\n+\n+ nref_nomask = NDDataRef(array)\n+ nref_mask = NDDataRef(array, mask=mask)\n+\n+ # Test multiplication of masked data with constant (mask * no mask)\n+ try:\n+ result = nref_mask.multiply(1., handle_mask=np.bitwise_or)\n+ assert result.mask is not None, \"__BUG__HERE__\"\n+ except TypeError as e:\n+ if \"unsupported operand type(s) for |: 'int' and 'NoneType'\" in str(e):\n+ pytest.fail(\"__BUG__HERE__\")\n+ else:\n+ raise\n+\n+ # Test multiplication of masked data with unmasked data (mask * no mask)\n+ try:\n+ result = nref_mask.multiply(nref_nomask, handle_mask=np.bitwise_or)\n+ assert result.mask is not None, \"__BUG__HERE__\"\n+ except TypeError as e:\n+ if \"unsupported operand type(s) for |: 'int' and 'NoneType'\" in str(e):\n+ pytest.fail(\"__BUG__HERE__\")\n+ else:\n+ raise\n+\n+ # Test that multiplication of masked data with itself works correctly\n+ result = nref_mask.multiply(nref_mask, handle_mask=np.bitwise_or)\n+ np.testing.assert_array_equal(result.mask, mask)\n+\n+ # Test that multiplication of unmasked data works without errors\n+ assert nref_nomask.multiply(1., handle_mask=np.bitwise_or).mask is None\n+ assert nref_nomask.multiply(nref_nomask, handle_mask=np.bitwise_or).mask is None\n\\ No newline at end of file\n", + "num_sent_chars": 402095, + "num_received_chars": 21932, + "elapsed_time": 179.88041877746582, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-7606.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-7606.json new file mode 100644 index 00000000..4e7249ee --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-7606.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-7606", + "edit_test_file": "astropy/units/tests/test_units.py", + "code_patch": "diff --git a/astropy/units/core.py b/astropy/units/core.py\nindex e9bd986..81e75bb 100644\n--- a/astropy/units/core.py\n+++ b/astropy/units/core.py\n@@ -1710,7 +1710,12 @@ class UnrecognizedUnit(IrreducibleUnit):\n _unrecognized_operator\n \n def __eq__(self, other):\n- other = Unit(other, parse_strict='silent')\n+ if other is None:\n+ return False\n+ try:\n+ other = Unit(other, parse_strict='silent')\n+ except TypeError:\n+ return False\n return isinstance(other, UnrecognizedUnit) and self.name == other.name\n \n def __ne__(self, other):\n", + "test_patch": "diff --git a/astropy/units/tests/test_unit_equality_comparison.py b/astropy/units/tests/test_unit_equality_comparison.py\nnew file mode 100644\nindex 0000000..bcb2f67\n--- /dev/null\n+++ b/astropy/units/tests/test_unit_equality_comparison.py\n@@ -0,0 +1,14 @@\n+import pytest\n+from astropy import units as u\n+\n+def test_unrecognized_unit_equality_with_none():\n+ # Create an UnrecognizedUnit\n+ x = u.Unit('asdf', parse_strict='silent')\n+ \n+ # Test equality comparison with None\n+ with pytest.raises(TypeError):\n+ x.__eq__(None) # This should raise TypeError\n+ \n+ # Test inequality comparison with None\n+ with pytest.raises(TypeError):\n+ x.__ne__(None) # This should also raise TypeError\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1844042, + "num_received_chars": 77385, + "elapsed_time": 565.341952085495, + "lint_repair_count": 15, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-8872.json b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-8872.json new file mode 100644 index 00000000..525c9280 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/astropy__astropy-8872.json @@ -0,0 +1,20 @@ +{ + "instance_id": "astropy__astropy-8872", + "edit_test_file": null, + "code_patch": "diff --git a/astropy/units/quantity.py b/astropy/units/quantity.py\nindex ded609c..d4831eb 100644\n--- a/astropy/units/quantity.py\n+++ b/astropy/units/quantity.py\n@@ -281,6 +281,10 @@ class Quantity(np.ndarray, metaclass=InheritDocstrings):\n if issubclass(qcls, cls):\n cls = qcls\n \n+ # Preserve float16 dtype if it's explicitly given or if the input is float16\n+ if dtype is None and isinstance(value, np.ndarray) and value.dtype == np.float16:\n+ dtype = np.float16\n+\n # optimize speed for Quantity with no dtype given, copy=False\n if isinstance(value, Quantity):\n if unit is not None and unit is not value.unit:\n@@ -297,16 +301,20 @@ class Quantity(np.ndarray, metaclass=InheritDocstrings):\n return value\n \n if not (np.can_cast(np.float32, value.dtype) or\n- value.dtype.fields):\n+ value.dtype.fields) and value.dtype != np.float16:\n dtype = float\n \n+ # Preserve float16 dtype if the input is float16 and no dtype is specified\n+ if dtype is None and isinstance(value, np.ndarray) and value.dtype == np.float16:\n+ dtype = np.float16\n+\n return np.array(value, dtype=dtype, copy=copy, order=order,\n subok=True, ndmin=ndmin)\n \n- # Maybe str, or list/tuple of Quantity? If so, this may set value_unit.\n- # To ensure array remains fast, we short-circuit it.\n- value_unit = None\n- if not isinstance(value, np.ndarray):\n+ # Maybe str, or list/tuple of Quantity? If so, this may set value_unit.\n+ # To ensure array remains fast, we short-circuit it.\n+ value_unit = None\n+ if not isinstance(value, np.ndarray):\n if isinstance(value, str):\n # The first part of the regex string matches any integer/float;\n # the second parts adds possible trailing .+-, which will break\n@@ -380,7 +388,9 @@ class Quantity(np.ndarray, metaclass=InheritDocstrings):\n if dtype is None and (not (np.can_cast(np.float32, value.dtype)\n or value.dtype.fields)\n or value.dtype.kind == 'O'):\n- value = value.astype(float)\n+ # Preserve float16 dtype\n+ if value.dtype != np.float16:\n+ value = value.astype(float)\n \n value = value.view(cls)\n value._set_unit(value_unit)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 383796, + "num_received_chars": 11231, + "elapsed_time": 91.08968567848206, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-10880.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-10880.json new file mode 100644 index 00000000..c2224126 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-10880.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-10880", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py\nindex 87852bc..e80a507 100644\n--- a/django/db/models/sql/compiler.py\n+++ b/django/db/models/sql/compiler.py\n@@ -1463,6 +1463,8 @@ class SQLUpdateCompiler(SQLCompiler):\n self.query.reset_refcounts(refcounts_before)\n \n \n+from django.db.models import Count\n+\n class SQLAggregateCompiler(SQLCompiler):\n def as_sql(self):\n \"\"\"\n@@ -1472,8 +1474,18 @@ class SQLAggregateCompiler(SQLCompiler):\n sql, params = [], []\n for annotation in self.query.annotation_select.values():\n ann_sql, ann_params = self.compile(annotation, select_format=FORCE)\n+ \n+ # Check if the annotation is a Count with distinct=True and a CASE statement\n+ if (isinstance(annotation, Count) and\n+ annotation.distinct and\n+ 'CASE' in ann_sql):\n+ # Insert a space between DISTINCT and CASE\n+ ann_sql = ann_sql.replace('DISTINCT(CASE', 'DISTINCT (CASE')\n+ ann_sql = ann_sql.replace('DISTINCTCASE', 'DISTINCT CASE')\n+ \n sql.append(ann_sql)\n params.extend(ann_params)\n+ \n self.col_count = len(self.query.annotation_select)\n sql = ', '.join(sql)\n params = tuple(params)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 553883, + "num_received_chars": 14060, + "elapsed_time": 114.39625358581543, + "lint_repair_count": 2, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-10999.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-10999.json new file mode 100644 index 00000000..dd9becc1 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-10999.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-10999", + "edit_test_file": null, + "code_patch": "diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py\nindex 8d08b7d..10abe2d 100644\n--- a/django/utils/dateparse.py\n+++ b/django/utils/dateparse.py\n@@ -29,7 +29,7 @@ datetime_re = re.compile(\n standard_duration_re = re.compile(\n r'^'\n r'(?:(?P-?\\d+) (days?, )?)?'\n- r'((?:(?P-?\\d+):)(?=\\d+:\\d+))?'\n+ r'((?:(?P-?\\d+):)(?=-?\\d+:-?\\d+))?'\n r'(?:(?P-?\\d+):)?'\n r'(?P-?\\d+)'\n r'(?:\\.(?P\\d{1,6})\\d{0,6})?'\n@@ -143,4 +143,5 @@ def parse_duration(value):\n if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):\n kw['microseconds'] = '-' + kw['microseconds']\n kw = {k: float(v) for k, v in kw.items() if v is not None}\n- return days + sign * datetime.timedelta(**kw)\n+ duration = datetime.timedelta(**kw)\n+ return days + (sign * duration if sign == -1 else duration)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 948504, + "num_received_chars": 38530, + "elapsed_time": 284.9418728351593, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11095.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11095.json new file mode 100644 index 00000000..6180097c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11095.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11095", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 5e7b23f..7f7ae85 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -555,6 +555,16 @@ class ModelAdmin(BaseModelAdmin):\n inlines = []\n \n # Custom templates (designed to be over-ridden in subclasses)\n+\n+ def get_inlines(self, request, obj=None):\n+ \"\"\"\n+ Hook for specifying custom inlines.\n+ \n+ By default, returns the value of the 'inlines' attribute.\n+ This method can be overridden to provide dynamic inline classes\n+ based on the request or model instance.\n+ \"\"\"\n+ return self.inlines\n add_form_template = None\n change_form_template = None\n change_list_template = None\n@@ -582,7 +592,7 @@ class ModelAdmin(BaseModelAdmin):\n \n def get_inline_instances(self, request, obj=None):\n inline_instances = []\n- for inline_class in self.inlines:\n+ for inline_class in self.get_inlines(request, obj):\n inline = inline_class(self.model, self.admin_site)\n if request:\n if not (inline.has_view_or_change_permission(request, obj) or\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1267012, + "num_received_chars": 75949, + "elapsed_time": 438.1821856498718, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11133.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11133.json new file mode 100644 index 00000000..85fc4a59 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11133.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11133", + "edit_test_file": "tests/httpwrappers/tests.py", + "code_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex 6a84e19..6da43e4 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -309,13 +309,16 @@ class HttpResponse(HttpResponseBase):\n @content.setter\n def content(self, value):\n # Consume iterators upon assignment to allow repeated iteration.\n- if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):\n+ if hasattr(value, '__iter__') and not isinstance(value, (bytes, str, memoryview)):\n content = b''.join(self.make_bytes(chunk) for chunk in value)\n if hasattr(value, 'close'):\n try:\n value.close()\n except Exception:\n pass\n+ elif isinstance(value, memoryview):\n+ # Convert memoryview to bytes\n+ content = bytes(value)\n else:\n content = self.make_bytes(value)\n # Create a list of properly encoded bytestrings to support write().\n", + "test_patch": "diff --git a/tests/httpwrappers/test_http_response_memoryview_handling.py b/tests/httpwrappers/test_http_response_memoryview_handling.py\nnew file mode 100644\nindex 0000000..5360d30\n--- /dev/null\n+++ b/tests/httpwrappers/test_http_response_memoryview_handling.py\n@@ -0,0 +1,13 @@\n+from django.test import SimpleTestCase\n+from django.http import HttpResponse\n+\n+class HttpResponseMemoryViewTests(SimpleTestCase):\n+ def test_memoryview_content(self):\n+ content = b\"My Content\"\n+ response = HttpResponse(memoryview(content))\n+ \n+ # The test passes if the content is incorrectly handled\n+ self.assertNotEqual(response.content, content)\n+ \n+ # Check if the content starts with the expected incorrect format\n+ self.assertTrue(response.content.startswith(b' 200:\n- number = '{:e}'.format(number)\n- coefficient, exponent = number.split('e')\n- # Format the coefficient.\n- coefficient = format(\n- coefficient, decimal_sep, decimal_pos, grouping,\n- thousand_sep, force_grouping, use_l10n,\n- )\n- return '{}e{}'.format(coefficient, exponent)\n+ if decimal_pos is not None:\n+ # Handle very small numbers when decimal_pos is specified\n+ if exponent < -decimal_pos:\n+ # Number is too small to be represented with given decimal_pos\n+ return '0' + decimal_sep + '0' * decimal_pos\n+ elif abs(exponent) + len(digits) > 200 and exponent < 0:\n+ # For small numbers, format with fixed point notation\n+ str_number = '{:.{}f}'.format(number, decimal_pos)\n+ elif abs(exponent) + len(digits) > 200:\n+ # For very large numbers, use scientific notation\n+ str_number = '{:.{}e}'.format(number, decimal_pos if decimal_pos is not None else 6)\n+ coefficient, exponent = str_number.split('e')\n+ # Format the coefficient\n+ coefficient = format(\n+ coefficient, decimal_sep, decimal_pos, grouping,\n+ thousand_sep, force_grouping, use_l10n,\n+ )\n+ return '{}e{}'.format(coefficient, exponent)\n+ else:\n+ str_number = '{:f}'.format(number)\n else:\n- str_number = '{:f}'.format(number)\n+ # Existing logic for cases where decimal_pos is not specified\n+ if abs(exponent) + len(digits) > 200:\n+ str_number = '{:e}'.format(number)\n+ coefficient, exponent = str_number.split('e')\n+ # Format the coefficient\n+ coefficient = format(\n+ coefficient, decimal_sep, decimal_pos, grouping,\n+ thousand_sep, force_grouping, use_l10n,\n+ )\n+ return '{}e{}'.format(coefficient, exponent)\n+ else:\n+ str_number = '{:f}'.format(number)\n else:\n str_number = str(number)\n if str_number[0] == '-':\n", + "test_patch": "diff --git a/tests/utils_tests/test_small_decimal_formatting.py b/tests/utils_tests/test_small_decimal_formatting.py\nnew file mode 100644\nindex 0000000..6a90a63\n--- /dev/null\n+++ b/tests/utils_tests/test_small_decimal_formatting.py\n@@ -0,0 +1,24 @@\n+from decimal import Decimal\n+\n+from django.test import SimpleTestCase\n+from django.utils.numberformat import format as nformat\n+\n+\n+class TestSmallDecimalFormatting(SimpleTestCase):\n+ def test_small_decimal_exponential_notation(self):\n+ \"\"\"\n+ Test that extremely small decimals are rendered in exponential notation\n+ when using utils.numberformat.format with decimal_pos.\n+ \"\"\"\n+ # This should be formatted as \"0.00\"\n+ self.assertEqual(nformat(Decimal('1e-199'), '.', decimal_pos=2), '0.00')\n+\n+ # This should be formatted as \"1.00e-200\", demonstrating the issue\n+ self.assertEqual(nformat(Decimal('1e-200'), '.', decimal_pos=2), '1.00e-200')\n+\n+ # Additional test to show the threshold\n+ self.assertEqual(nformat(Decimal('1e-201'), '.', decimal_pos=2), '1.00e-201')\n+\n+ # Test with a different decimal_pos\n+ self.assertEqual(nformat(Decimal('1e-199'), '.', decimal_pos=3), '0.000')\n+ self.assertEqual(nformat(Decimal('1e-200'), '.', decimal_pos=3), '1.000e-200')\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/utils_tests/test_small_decimal_formatting_inverted.py b/tests/utils_tests/test_small_decimal_formatting_inverted.py\nnew file mode 100644\nindex 0000000..49e3ea4\n--- /dev/null\n+++ b/tests/utils_tests/test_small_decimal_formatting_inverted.py\n@@ -0,0 +1,72 @@\n+from decimal import Decimal\n+\n+from django.test import SimpleTestCase\n+from django.utils.numberformat import format as nformat\n+\n+\n+class TestSmallDecimalFormatting(SimpleTestCase):\n+ def test_small_decimal_exponential_notation(self):\n+ \"\"\"\n+ Test that extremely small decimals are rendered as zero with the specified\n+ decimal places when using utils.numberformat.format with decimal_pos,\n+ instead of being rendered in exponential notation.\n+ \"\"\"\n+ # This should be formatted as \"0.00\"\n+ self.assertEqual(nformat(Decimal('1e-199'), '.', decimal_pos=2), '0.00')\n+\n+ # This should be formatted as \"0.00\", not \"1.00e-200\"\n+ result = nformat(Decimal('1e-200'), '.', decimal_pos=2)\n+ if result == '1.00e-200':\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(result, '0.00')\n+\n+ # Additional test to show the threshold\n+ result = nformat(Decimal('1e-201'), '.', decimal_pos=2)\n+ if result == '1.00e-201':\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(result, '0.00')\n+\n+ # Test with a different decimal_pos\n+ self.assertEqual(nformat(Decimal('1e-199'), '.', decimal_pos=3), '0.000')\n+ \n+ result = nformat(Decimal('1e-200'), '.', decimal_pos=3)\n+ if result == '1.000e-200':\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(result, '0.000')\n+\n+ def test_small_decimal_various_precisions(self):\n+ \"\"\"\n+ Test that extremely small decimals are rendered as zero with various\n+ decimal precisions when using utils.numberformat.format with decimal_pos.\n+ \"\"\"\n+ test_cases = [\n+ (Decimal('1e-300'), 2, '0.00'),\n+ (Decimal('1e-400'), 4, '0.0000'),\n+ (Decimal('1e-500'), 6, '0.000000'),\n+ ]\n+\n+ for value, decimal_pos, expected in test_cases:\n+ result = nformat(value, '.', decimal_pos=decimal_pos)\n+ if 'e-' in result:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(result, expected)\n+\n+ def test_small_decimal_edge_cases(self):\n+ \"\"\"\n+ Test edge cases for small decimal formatting.\n+ \"\"\"\n+ # Test with decimal_pos=0\n+ result = nformat(Decimal('1e-200'), '.', decimal_pos=0)\n+ if result != '0':\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(result, '0')\n+\n+ # Test with a negative number\n+ result = nformat(Decimal('-1e-200'), '.', decimal_pos=2)\n+ if result == '-1.00e-200':\n+ raise AssertionError(\"__BUG__HERE__\")\n+ self.assertEqual(result, '-0.00')\n+\n+ # Test with a number just above the threshold\n+ result = nformat(Decimal('1e-198'), '.', decimal_pos=2)\n+ self.assertEqual(result, '0.00')\n\\ No newline at end of file\n", + "num_sent_chars": 1835735, + "num_received_chars": 158280, + "elapsed_time": 845.2572813034058, + "lint_repair_count": 11, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11265.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11265.json new file mode 100644 index 00000000..11554b36 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11265.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11265", + "edit_test_file": "tests/generic_relations/tests.py", + "code_patch": "diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py\nindex 90289d0..1e1eff1 100644\n--- a/django/db/models/query_utils.py\n+++ b/django/db/models/query_utils.py\n@@ -317,11 +317,25 @@ class FilteredRelation:\n )\n \n def clone(self):\n- clone = FilteredRelation(self.relation_name, condition=self.condition)\n+ clone = FilteredRelation(self.relation_name, condition=self.condition.clone())\n clone.alias = self.alias\n clone.path = self.path[:]\n return clone\n \n+ def deep_clone(self):\n+ clone = FilteredRelation(self.relation_name, condition=self.condition.clone())\n+ clone.alias = self.alias\n+ clone.path = self.path[:]\n+ return clone\n+\n+ @classmethod\n+ def transfer_annotations(cls, from_query, to_query):\n+ for key, value in from_query._filtered_relations.items():\n+ to_query._filtered_relations[key] = value.deep_clone()\n+\n+ def get_filtered_relation_keys(self):\n+ return [self.alias or self.relation_name]\n+\n def resolve_expression(self, *args, **kwargs):\n \"\"\"\n QuerySet.annotate() only accepts expression-like arguments\n", + "test_patch": "diff --git a/tests/generic_relations/test_filtered_relation_exclude.py b/tests/generic_relations/test_filtered_relation_exclude.py\nnew file mode 100644\nindex 0000000..92cd89f\n--- /dev/null\n+++ b/tests/generic_relations/test_filtered_relation_exclude.py\n@@ -0,0 +1,27 @@\n+from django.core.exceptions import FieldError\n+from django.db.models import FilteredRelation, Q\n+from django.test import TestCase\n+\n+from .models import Animal, TaggedItem\n+\n+\n+class FilteredRelationExcludeTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.lion = Animal.objects.create(common_name=\"Lion\", latin_name=\"Panthera leo\")\n+ cls.platypus = Animal.objects.create(common_name=\"Platypus\", latin_name=\"Ornithorhynchus anatinus\")\n+ \n+ TaggedItem.objects.create(tag=\"mammal\", content_object=cls.lion)\n+ TaggedItem.objects.create(tag=\"carnivore\", content_object=cls.lion)\n+ TaggedItem.objects.create(tag=\"mammal\", content_object=cls.platypus)\n+\n+ def test_filtered_relation_exclude(self):\n+ with self.assertRaises(FieldError) as cm:\n+ Animal.objects.annotate(\n+ carnivore_tag=FilteredRelation('tags', condition=Q(tags__tag='carnivore'))\n+ ).exclude(carnivore_tag__isnull=False)\n+\n+ self.assertIn(\n+ \"Cannot resolve keyword 'carnivore_tag' into field.\",\n+ str(cm.exception)\n+ )\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 4472323, + "num_received_chars": 245257, + "elapsed_time": 1368.667414188385, + "lint_repair_count": 20, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11299.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11299.json new file mode 100644 index 00000000..47d5c38c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11299.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11299", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py\nindex 1280666..a080424 100644\n--- a/django/db/backends/base/schema.py\n+++ b/django/db/backends/base/schema.py\n@@ -1098,7 +1098,7 @@ class BaseDatabaseSchemaEditor:\n def _check_sql(self, name, check):\n return self.sql_constraint % {\n 'name': self.quote_name(name),\n- 'constraint': self.sql_check_constraint % {'check': check},\n+ 'constraint': self.sql_check_constraint % {'check': self._process_check_constraint(check)},\n }\n \n def _create_check_sql(self, model, name, check):\n@@ -1106,9 +1106,27 @@ class BaseDatabaseSchemaEditor:\n self.sql_create_check,\n table=Table(model._meta.db_table, self.quote_name),\n name=self.quote_name(name),\n- check=check,\n+ check=self._process_check_constraint(check),\n )\n \n+ def _process_check_constraint(self, check):\n+ if isinstance(check, str):\n+ return self._remove_table_qualifiers(check)\n+ elif hasattr(check, 'resolve_expression'):\n+ return self._remove_table_qualifiers(check.resolve_expression(self.connection.features.quote_name).as_sql(self.connection.ops.compiler('SQLCompiler'), self.connection)[0])\n+ else:\n+ return check\n+\n+ def _remove_table_qualifiers(self, sql):\n+ # Remove table qualifiers for databases that don't support them in check constraints\n+ if not self.connection.features.supports_table_check_constraints:\n+ parts = sql.split('\".\"')\n+ return '.'.join(part.split('\"')[-1] for part in parts)\n+ return sql\n+\n+ def _supports_table_check_constraints(self):\n+ return self.connection.features.supports_table_check_constraints\n+\n def _delete_check_sql(self, model, name):\n return self._delete_constraint_sql(self.sql_delete_check, model, name)\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2263713, + "num_received_chars": 127058, + "elapsed_time": 678.7852921485901, + "lint_repair_count": 7, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11433.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11433.json new file mode 100644 index 00000000..af486112 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11433.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11433", + "edit_test_file": "tests/model_forms/tests.py", + "code_patch": "diff --git a/django/forms/models.py b/django/forms/models.py\nindex 5edbbd3..fa2a6cc 100644\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -32,6 +32,9 @@ def construct_instance(form, instance, fields=None, exclude=None):\n \"\"\"\n Construct and return a model instance from the bound ``form``'s\n ``cleaned_data``, but do not save the returned instance to the database.\n+\n+ If form.allow_cleaned_data_override is True, cleaned_data values will take\n+ precedence over model's default values when constructing the instance.\n \"\"\"\n from django.db import models\n opts = instance._meta\n@@ -39,8 +42,9 @@ def construct_instance(form, instance, fields=None, exclude=None):\n cleaned_data = form.cleaned_data\n file_field_list = []\n for f in opts.fields:\n- if not f.editable or isinstance(f, models.AutoField) \\\n- or f.name not in cleaned_data:\n+ if not f.editable or isinstance(f, models.AutoField):\n+ continue\n+ if f.name not in cleaned_data and not form.allow_cleaned_data_override:\n continue\n if fields is not None and f.name not in fields:\n continue\n@@ -277,7 +281,7 @@ class BaseModelForm(BaseForm):\n def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,\n initial=None, error_class=ErrorList, label_suffix=None,\n empty_permitted=False, instance=None, use_required_attribute=None,\n- renderer=None):\n+ renderer=None, allow_cleaned_data_override=False):\n opts = self._meta\n if opts.model is None:\n raise ValueError('ModelForm has no model class specified.')\n@@ -288,6 +292,7 @@ class BaseModelForm(BaseForm):\n else:\n self.instance = instance\n object_data = model_to_dict(instance, opts.fields, opts.exclude)\n+ self.allow_cleaned_data_override = allow_cleaned_data_override\n # if initial was provided, it should override the values from instance\n if initial is not None:\n object_data.update(initial)\n@@ -443,6 +448,9 @@ class BaseModelForm(BaseForm):\n Save this form's self.instance object if commit=True. Otherwise, add\n a save_m2m() method to the form which can be called after the instance\n is saved manually at a later time. Return the model instance.\n+\n+ If allow_cleaned_data_override is True, cleaned_data values will take\n+ precedence over model's default values when saving the instance.\n \"\"\"\n if self.errors:\n raise ValueError(\n@@ -451,6 +459,11 @@ class BaseModelForm(BaseForm):\n 'created' if self.instance._state.adding else 'changed',\n )\n )\n+ if self.allow_cleaned_data_override:\n+ # Update instance with cleaned_data, overriding defaults\n+ for field_name, value in self.cleaned_data.items():\n+ if field_name in self.fields:\n+ setattr(self.instance, field_name, value)\n if commit:\n # If committing, save the instance and the m2m data immediately.\n self.instance.save()\n", + "test_patch": "diff --git a/tests/model_forms/test_cleaned_data_default_override.py b/tests/model_forms/test_cleaned_data_default_override.py\nnew file mode 100644\nindex 0000000..fcaf112\n--- /dev/null\n+++ b/tests/model_forms/test_cleaned_data_default_override.py\n@@ -0,0 +1,33 @@\n+# File: tests/model_forms/test_cleaned_data_default_override.py\n+\n+from django.test import TestCase\n+from django.forms import ModelForm\n+from django.db import models\n+\n+class ModelWithDefault(models.Model):\n+ name = models.CharField(max_length=100)\n+ status = models.CharField(max_length=20, default='pending')\n+\n+class ModelWithDefaultForm(ModelForm):\n+ class Meta:\n+ model = ModelWithDefault\n+ fields = ['name']\n+\n+ def clean(self):\n+ cleaned_data = super().clean()\n+ cleaned_data['status'] = 'approved'\n+ return cleaned_data\n+\n+class CleanedDataDefaultOverrideTest(TestCase):\n+ def test_cleaned_data_cannot_override_default(self):\n+ form_data = {'name': 'Test Object'}\n+ form = ModelWithDefaultForm(data=form_data)\n+ \n+ self.assertTrue(form.is_valid())\n+ instance = form.save()\n+ \n+ # This assertion will pass, demonstrating the issue\n+ self.assertEqual(instance.status, 'pending')\n+ \n+ # This assertion would fail if the issue were fixed\n+ # self.assertEqual(instance.status, 'approved')\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_forms/test_cleaned_data_default_override_inverted.py b/tests/model_forms/test_cleaned_data_default_override_inverted.py\nnew file mode 100644\nindex 0000000..df8337e\n--- /dev/null\n+++ b/tests/model_forms/test_cleaned_data_default_override_inverted.py\n@@ -0,0 +1,36 @@\n+# File: tests/model_forms/test_cleaned_data_default_override.py\n+\n+from django.test import TestCase\n+from django.forms import ModelForm\n+from django.db import models\n+\n+class ModelWithDefault(models.Model):\n+ name = models.CharField(max_length=100)\n+ status = models.CharField(max_length=20, default='pending')\n+\n+class ModelWithDefaultForm(ModelForm):\n+ class Meta:\n+ model = ModelWithDefault\n+ fields = ['name']\n+\n+ def clean(self):\n+ cleaned_data = super().clean()\n+ cleaned_data['status'] = 'approved'\n+ return cleaned_data\n+\n+class CleanedDataDefaultOverrideTest(TestCase):\n+ def test_cleaned_data_should_override_default(self):\n+ form_data = {'name': 'Test Object'}\n+ form = ModelWithDefaultForm(data=form_data)\n+ \n+ self.assertTrue(form.is_valid())\n+ instance = form.save()\n+ \n+ # This assertion will now fail when the issue is observed\n+ try:\n+ self.assertEqual(instance.status, 'approved', \"Status should be 'approved' as set in clean() method\")\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Additional check to ensure the status is not the default value\n+ self.assertNotEqual(instance.status, 'pending', \"Status should not be the default 'pending'\")\n\\ No newline at end of file\n", + "num_sent_chars": 1689126, + "num_received_chars": 99925, + "elapsed_time": 567.8468399047852, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11490.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11490.json new file mode 100644 index 00000000..cc5cc385 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11490.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11490", + "edit_test_file": "tests/queries/test_qs_combinators.py", + "code_patch": "diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py\nindex a44adfc..8894e64 100644\n--- a/django/db/models/sql/compiler.py\n+++ b/django/db/models/sql/compiler.py\n@@ -26,6 +26,7 @@ class SQLCompiler:\n self.connection = connection\n self.using = using\n self.quote_cache = {'*': '*'}\n+ self.post_composition_values = None\n # The select, klass_info, and annotations are needed by QuerySet.iterator()\n # these are set as a side-effect of executing the query. Note that we calculate\n # separately a list of extra select columns needed for grammatical correctness\n@@ -425,7 +426,14 @@ class SQLCompiler:\n # If the columns list is limited, then all combined queries\n # must have the same columns list. Set the selects defined on\n # the query on all combined queries, if not already set.\n- if not compiler.query.values_select and self.query.values_select:\n+ if self.query.values_select:\n+ # Use the most recent values_select for all compilers\n+ compiler.query.set_values(self.query.values_select)\n+ elif not compiler.query.values_select and self.query.values_select:\n+ compiler.query.set_values(self.query.values_select)\n+ # Check if there's a post-composition values() or values_list() call\n+ if getattr(self.query, 'post_composition_values', None):\n+ compiler.query.set_values(self.query.post_composition_values)\n compiler.query.set_values((\n *self.query.extra_select,\n *self.query.values_select,\n@@ -472,6 +480,12 @@ class SQLCompiler:\n refcounts_before = self.query.alias_refcount.copy()\n try:\n extra_select, order_by, group_by = self.pre_sql_setup()\n+ \n+ # Check for post-composition values() or values_list() call\n+ if hasattr(self.query, 'post_composition_values'):\n+ self.query.values_select = self.query.post_composition_values\n+ self.query.select = self.query.post_composition_values\n+ self.query.default_cols = False\n for_update_part = None\n # Is a LIMIT/OFFSET clause needed?\n with_limit_offset = with_limits and (self.query.high_mark is not None or self.query.low_mark)\n", + "test_patch": "diff --git a/tests/queries/test_composed_query_values.py b/tests/queries/test_composed_query_values.py\nnew file mode 100644\nindex 0000000..7b9f01f\n--- /dev/null\n+++ b/tests/queries/test_composed_query_values.py\n@@ -0,0 +1,42 @@\n+from django.test import TestCase\n+from django.db.models import F\n+\n+from .models import ReservedName\n+\n+\n+class ComposedQueryValuesTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ ReservedName.objects.create(name='a', order=2)\n+\n+ def test_composed_query_values_list_inconsistency(self):\n+ qs1 = ReservedName.objects.all()\n+ \n+ # First query with all fields\n+ result1 = qs1.union(qs1).values_list('name', 'order').get()\n+ self.assertEqual(result1, ('a', 2))\n+ \n+ # Second query with only 'order' field\n+ result2 = qs1.union(qs1).values_list('order', flat=True).get()\n+ \n+ # This assertion will pass if the issue is present\n+ self.assertEqual(result2, 'a')\n+ \n+ # This is what we would expect if the issue were fixed\n+ # self.assertEqual(result2, 2)\n+\n+ def test_composed_query_values_inconsistency(self):\n+ qs1 = ReservedName.objects.all()\n+ \n+ # First query with all fields\n+ result1 = qs1.union(qs1).values('name', 'order').get()\n+ self.assertEqual(result1, {'name': 'a', 'order': 2})\n+ \n+ # Second query with only 'order' field\n+ result2 = qs1.union(qs1).values('order').get()\n+ \n+ # This assertion will pass if the issue is present\n+ self.assertEqual(result2, {'order': 'a'})\n+ \n+ # This is what we would expect if the issue were fixed\n+ # self.assertEqual(result2, {'order': 2})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/queries/test_composed_query_values_inverted.py b/tests/queries/test_composed_query_values_inverted.py\nnew file mode 100644\nindex 0000000..c4cc24e\n--- /dev/null\n+++ b/tests/queries/test_composed_query_values_inverted.py\n@@ -0,0 +1,44 @@\n+from django.test import TestCase\n+from django.db.models import F\n+\n+from .models import ReservedName\n+\n+\n+class ComposedQueryValuesTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ ReservedName.objects.create(name='a', order=2)\n+\n+ def test_composed_query_values_list_inconsistency(self):\n+ qs1 = ReservedName.objects.all()\n+ \n+ # First query with all fields\n+ result1 = qs1.union(qs1).values_list('name', 'order').get()\n+ self.assertEqual(result1, ('a', 2))\n+ \n+ # Second query with only 'order' field\n+ result2 = qs1.union(qs1).values_list('order', flat=True).get()\n+ \n+ # This assertion will fail if the issue is present\n+ if result2 == 'a':\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # This is what we expect if the issue is fixed\n+ self.assertEqual(result2, 2)\n+\n+ def test_composed_query_values_inconsistency(self):\n+ qs1 = ReservedName.objects.all()\n+ \n+ # First query with all fields\n+ result1 = qs1.union(qs1).values('name', 'order').get()\n+ self.assertEqual(result1, {'name': 'a', 'order': 2})\n+ \n+ # Second query with only 'order' field\n+ result2 = qs1.union(qs1).values('order').get()\n+ \n+ # This assertion will fail if the issue is present\n+ if result2 == {'order': 'a'}:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # This is what we expect if the issue is fixed\n+ self.assertEqual(result2, {'order': 2})\n\\ No newline at end of file\n", + "num_sent_chars": 1920130, + "num_received_chars": 117169, + "elapsed_time": 655.5781364440918, + "lint_repair_count": 5, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11555.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11555.json new file mode 100644 index 00000000..d875ed4d --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11555.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11555", + "edit_test_file": "tests/admin_changelist/tests.py", + "code_patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\nindex e15e64c..44a5493 100644\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -2216,11 +2216,28 @@ def get_order_dir(field, default='ASC'):\n \n The 'default' param is used to indicate which way no prefix (or a '+'\n prefix) should sort. The '-' prefix always sorts the opposite way.\n+\n+ This function can handle both string inputs and OrderBy objects.\n \"\"\"\n dirn = ORDER_DIR[default]\n- if field[0] == '-':\n- return field[1:], dirn[1]\n- return field, dirn[0]\n+\n+ if hasattr(field, 'expression'):\n+ # This is an OrderBy object\n+ if field.descending:\n+ return field.expression.name, dirn[1]\n+ else:\n+ return field.expression.name, dirn[0]\n+ elif isinstance(field, str):\n+ # This is a string input\n+ if field[0] == '-':\n+ return field[1:], dirn[1]\n+ return field, dirn[0]\n+ else:\n+ # If it's neither an OrderBy object nor a string, we can't process it\n+ raise ValueError(\n+ f\"Invalid order_by specification: {field}. \"\n+ \"Must be either a string or an OrderBy object.\"\n+ )\n \n \n def add_to_dict(data, key, value):\n", + "test_patch": "diff --git a/tests/admin_changelist/test_order_by_parent_model_meta_ordering.py b/tests/admin_changelist/test_order_by_parent_model_meta_ordering.py\nnew file mode 100644\nindex 0000000..b4181ef\n--- /dev/null\n+++ b/tests/admin_changelist/test_order_by_parent_model_meta_ordering.py\n@@ -0,0 +1,40 @@\n+from django.contrib.admin.views.main import ChangeList\n+from django.db import models\n+from django.test import TestCase\n+from django.db.models import F\n+\n+class OrderByParentModelMetaOrderingTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ class ParentWithOrderingExpression(models.Model):\n+ name = models.CharField(max_length=100)\n+ \n+ class Meta:\n+ ordering = [F('name').asc()]\n+ app_label = 'admin_changelist'\n+\n+ class ChildWithOrderingExpression(ParentWithOrderingExpression):\n+ age = models.IntegerField()\n+\n+ class Meta:\n+ app_label = 'admin_changelist'\n+\n+ cls.parent_model = ParentWithOrderingExpression\n+ cls.child_model = ChildWithOrderingExpression\n+\n+ def test_order_by_parent_model_meta_ordering(self):\n+ with self.assertRaises(TypeError):\n+ ChangeList(\n+ request=None,\n+ model=self.child_model,\n+ list_display=['name', 'age'],\n+ list_display_links=None,\n+ list_filter=[],\n+ date_hierarchy=None,\n+ search_fields=[],\n+ list_select_related=False,\n+ list_per_page=100,\n+ list_max_show_all=200,\n+ list_editable=[],\n+ model_admin=None,\n+ )\n", + "test_inverted_patch": "diff --git a/tests/admin_changelist/test_order_by_parent_model_meta_ordering_inverted.py b/tests/admin_changelist/test_order_by_parent_model_meta_ordering_inverted.py\nnew file mode 100644\nindex 0000000..8e328f0\n--- /dev/null\n+++ b/tests/admin_changelist/test_order_by_parent_model_meta_ordering_inverted.py\n@@ -0,0 +1,46 @@\n+from django.contrib.admin.views.main import ChangeList\n+from django.db import models\n+from django.test import TestCase\n+from django.db.models import F\n+\n+class OrderByParentModelMetaOrderingTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ class ParentWithOrderingExpression(models.Model):\n+ name = models.CharField(max_length=100)\n+ \n+ class Meta:\n+ ordering = [F('name').asc()]\n+ app_label = 'admin_changelist'\n+\n+ class ChildWithOrderingExpression(ParentWithOrderingExpression):\n+ age = models.IntegerField()\n+\n+ class Meta:\n+ app_label = 'admin_changelist'\n+\n+ cls.parent_model = ParentWithOrderingExpression\n+ cls.child_model = ChildWithOrderingExpression\n+\n+ def test_order_by_parent_model_meta_ordering(self):\n+ try:\n+ ChangeList(\n+ request=None,\n+ model=self.child_model,\n+ list_display=['name', 'age'],\n+ list_display_links=None,\n+ list_filter=[],\n+ date_hierarchy=None,\n+ search_fields=[],\n+ list_select_related=False,\n+ list_per_page=100,\n+ list_max_show_all=200,\n+ list_editable=[],\n+ model_admin=None,\n+ )\n+ except TypeError:\n+ # If a TypeError is raised, it means the bug is present\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # If no exception is raised, the test should fail because the bug is not present\n+ self.fail(\"Expected TypeError due to order_by() with parent model Meta.ordering containing expressions, but no exception was raised.\")\n\\ No newline at end of file\n", + "num_sent_chars": 1463275, + "num_received_chars": 106174, + "elapsed_time": 561.4539310932159, + "lint_repair_count": 1, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11734.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11734.json new file mode 100644 index 00000000..de799622 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11734.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11734", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\nindex 35f3c5e..98fcca7 100644\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -1219,6 +1219,14 @@ class Query(BaseExpression):\n upper in the code by add_q().\n \n The 'can_reuse' is a set of reusable joins for multijoins.\n+ \"\"\"\n+ if isinstance(filter_expr, (list, tuple)):\n+ filter_lhs, filter_rhs = filter_expr\n+ if isinstance(filter_rhs, OuterRef):\n+ filter_rhs = self.resolve_outer_ref(filter_rhs, current_negated)\n+ return super().build_filter(filter_expr, branch_negated, current_negated,\n+ can_reuse, allow_joins, split_subq,\n+ reuse_with_filtered_relation, simple_col)\n \n If 'reuse_with_filtered_relation' is True, then only joins in can_reuse\n will be reused.\n@@ -1340,6 +1348,7 @@ class Query(BaseExpression):\n # rel_a doesn't produce any rows, then the whole condition must fail.\n # So, demotion is OK.\n existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}\n+ q_object = self.resolve_outer_refs_in_q(q_object)\n clause, _ = self._add_q(q_object, self.used_aliases)\n if clause:\n self.where.add(clause, AND)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 3793560, + "num_received_chars": 164336, + "elapsed_time": 989.0963599681854, + "lint_repair_count": 12, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11790.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11790.json new file mode 100644 index 00000000..ef748bd5 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11790.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11790", + "edit_test_file": "tests/admin_views/test_forms.py", + "code_patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\nindex a0cfed0..f518dc5 100644\n--- a/django/contrib/auth/forms.py\n+++ b/django/contrib/auth/forms.py\n@@ -191,6 +191,9 @@ class AuthenticationForm(forms.Form):\n \n # Set the max length and label for the \"username\" field.\n self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)\n+ username_max_length = self.username_field.max_length\n+ self.fields['username'].max_length = username_max_length\n+ self.fields['username'].widget.attrs['maxlength'] = username_max_length\n self.fields['username'].max_length = self.username_field.max_length or 254\n if self.fields['username'].label is None:\n self.fields['username'].label = capfirst(self.username_field.verbose_name)\n", + "test_patch": "diff --git a/tests/admin_views/test_authentication_form_maxlength.py b/tests/admin_views/test_authentication_form_maxlength.py\nnew file mode 100644\nindex 0000000..5fb673f\n--- /dev/null\n+++ b/tests/admin_views/test_authentication_form_maxlength.py\n@@ -0,0 +1,19 @@\n+from django.contrib.auth.forms import AuthenticationForm\n+from django.test import TestCase\n+from django.contrib.auth.models import User\n+\n+\n+class AuthenticationFormMaxLengthTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ User.objects.create_user(username='testuser', password='testpass')\n+\n+ def test_username_field_missing_maxlength(self):\n+ form = AuthenticationForm()\n+ username_widget = form.fields['username'].widget\n+ self.assertNotIn('maxlength', username_widget.attrs)\n+\n+ def test_username_field_renders_without_maxlength(self):\n+ form = AuthenticationForm()\n+ rendered_form = form.as_p()\n+ self.assertNotIn('maxlength', rendered_form)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/admin_views/test_authentication_form_maxlength_inverted.py b/tests/admin_views/test_authentication_form_maxlength_inverted.py\nnew file mode 100644\nindex 0000000..3b44671\n--- /dev/null\n+++ b/tests/admin_views/test_authentication_form_maxlength_inverted.py\n@@ -0,0 +1,31 @@\n+from django.contrib.auth.forms import AuthenticationForm\n+from django.test import TestCase\n+from django.contrib.auth.models import User\n+\n+\n+class AuthenticationFormMaxLengthTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ User.objects.create_user(username='testuser', password='testpass')\n+\n+ def test_username_field_has_maxlength(self):\n+ form = AuthenticationForm()\n+ username_widget = form.fields['username'].widget\n+ if 'maxlength' not in username_widget.attrs:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ def test_username_field_renders_with_maxlength(self):\n+ form = AuthenticationForm()\n+ rendered_form = form.as_p()\n+ if 'maxlength' not in rendered_form:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ def test_maxlength_value_correct(self):\n+ form = AuthenticationForm()\n+ username_widget = form.fields['username'].widget\n+ if 'maxlength' in username_widget.attrs:\n+ maxlength = username_widget.attrs['maxlength']\n+ if maxlength != 150: # Assuming the correct maxlength should be 150\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 598099, + "num_received_chars": 29473, + "elapsed_time": 215.13516306877136, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11848.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11848.json new file mode 100644 index 00000000..28a3228d --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11848.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11848", + "edit_test_file": "tests/sitemaps_tests/test_http.py", + "code_patch": "diff --git a/django/utils/http.py b/django/utils/http.py\nindex 572cfb4..9beae6c 100644\n--- a/django/utils/http.py\n+++ b/django/utils/http.py\n@@ -164,6 +164,16 @@ def parse_http_date(date):\n \n Return an integer expressed in seconds since the epoch, in UTC.\n \"\"\"\n+ def parse_two_digit_year(year):\n+ current_year = datetime.datetime.now().year\n+ current_century = current_year // 100 * 100\n+ current_two_digit_year = current_year % 100\n+ \n+ if year <= (current_two_digit_year + 50) % 100:\n+ return current_century + year\n+ else:\n+ return (current_century - 100) + year\n+\n # email.utils.parsedate() does the job for RFC1123 dates; unfortunately\n # RFC7231 makes it mandatory to support RFC850 dates too. So we roll\n # our own RFC-compliant parsing.\n@@ -175,7 +185,9 @@ def parse_http_date(date):\n raise ValueError(\"%r is not in a valid HTTP date format\" % date)\n try:\n year = int(m.group('year'))\n- if year < 100:\n+ if regex == RFC850_DATE:\n+ year = parse_two_digit_year(year)\n+ elif year < 100:\n if year < 70:\n year += 2000\n else:\n", + "test_patch": "diff --git a/tests/sitemaps_tests/test_http_date_parsing.py b/tests/sitemaps_tests/test_http_date_parsing.py\nnew file mode 100644\nindex 0000000..fa780ae\n--- /dev/null\n+++ b/tests/sitemaps_tests/test_http_date_parsing.py\n@@ -0,0 +1,33 @@\n+import unittest\n+from datetime import datetime\n+from django.utils.http import parse_http_date\n+\n+class HTTPDateParsingTests(unittest.TestCase):\n+ def test_two_digit_year_parsing(self):\n+ # Get the current year\n+ current_year = datetime.now().year\n+ \n+ # Test a date 51 years in the future\n+ future_year = (current_year + 51) % 100\n+ future_date = f\"Sunday, 06-Nov-{future_year:02d} 08:49:37 GMT\"\n+ parsed_date = parse_http_date(future_date)\n+ \n+ # Convert the parsed timestamp to a datetime object\n+ parsed_datetime = datetime.utcfromtimestamp(parsed_date)\n+ \n+ # Assert that the parsed year is the most recent year in the past with the same last two digits\n+ expected_year = current_year - (100 - (future_year - (current_year % 100)))\n+ self.assertEqual(parsed_datetime.year, expected_year)\n+ \n+ # Assert that other parts of the date are correctly parsed\n+ self.assertEqual(parsed_datetime.month, 11)\n+ self.assertEqual(parsed_datetime.day, 6)\n+ self.assertEqual(parsed_datetime.hour, 8)\n+ self.assertEqual(parsed_datetime.minute, 49)\n+ self.assertEqual(parsed_datetime.second, 37)\n+\n+ # Test the current behavior (which is incorrect according to the issue description)\n+ if future_year < 70:\n+ self.assertEqual(parsed_datetime.year, 2000 + future_year)\n+ else:\n+ self.assertEqual(parsed_datetime.year, 1900 + future_year)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/sitemaps_tests/test_http_date_parsing_inverted.py b/tests/sitemaps_tests/test_http_date_parsing_inverted.py\nnew file mode 100644\nindex 0000000..e0423a3\n--- /dev/null\n+++ b/tests/sitemaps_tests/test_http_date_parsing_inverted.py\n@@ -0,0 +1,40 @@\n+import unittest\n+from datetime import datetime\n+from django.utils.http import parse_http_date\n+\n+class HTTPDateParsingTests(unittest.TestCase):\n+ def test_two_digit_year_parsing(self):\n+ # Get the current year\n+ current_year = datetime.now().year\n+ \n+ # Test a date 51 years in the future\n+ future_year = (current_year + 51) % 100\n+ future_date = f\"Sunday, 06-Nov-{future_year:02d} 08:49:37 GMT\"\n+ parsed_date = parse_http_date(future_date)\n+ \n+ # Convert the parsed timestamp to a datetime object\n+ parsed_datetime = datetime.utcfromtimestamp(parsed_date)\n+ \n+ # Calculate the expected year according to RFC 7231\n+ expected_year = current_year - (100 - (future_year - (current_year % 100)))\n+ \n+ # Assert that the parsed year is the most recent year in the past with the same last two digits\n+ try:\n+ self.assertEqual(parsed_datetime.year, expected_year)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Assert that other parts of the date are correctly parsed\n+ self.assertEqual(parsed_datetime.month, 11)\n+ self.assertEqual(parsed_datetime.day, 6)\n+ self.assertEqual(parsed_datetime.hour, 8)\n+ self.assertEqual(parsed_datetime.minute, 49)\n+ self.assertEqual(parsed_datetime.second, 37)\n+\n+ # Test the current behavior (which is incorrect according to the issue description)\n+ if future_year < 70:\n+ if parsed_datetime.year == 2000 + future_year:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ if parsed_datetime.year == 1900 + future_year:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 1943617, + "num_received_chars": 122558, + "elapsed_time": 729.523099899292, + "lint_repair_count": 12, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11951.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11951.json new file mode 100644 index 00000000..37d37970 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-11951.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-11951", + "edit_test_file": "tests/bulk_create/tests.py", + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 794e0fa..70ae0fa 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -471,6 +471,13 @@ class QuerySet:\n fields = opts.concrete_fields\n objs = list(objs)\n self._populate_pk_values(objs)\n+ # Calculate the maximum batch size that the database can handle\n+ max_batch_size = connection.ops.bulk_batch_size(fields, objs)\n+ # Use the minimum of user-specified and compatible batch sizes\n+ if batch_size is not None:\n+ batch_size = min(batch_size, max_batch_size)\n+ else:\n+ batch_size = max_batch_size\n with transaction.atomic(using=self.db, savepoint=False):\n objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs)\n if objs_with_pk:\n", + "test_patch": "diff --git a/tests/bulk_create/test_bulk_create_batch_size.py b/tests/bulk_create/test_bulk_create_batch_size.py\nnew file mode 100644\nindex 0000000..e874bc5\n--- /dev/null\n+++ b/tests/bulk_create/test_bulk_create_batch_size.py\n@@ -0,0 +1,36 @@\n+from django.db import connection\n+from django.test import TestCase, override_settings\n+from django.db.models import IntegerField\n+from django.db.models.functions import Cast\n+\n+from .models import TwoFields\n+\n+\n+class BulkCreateBatchSizeTests(TestCase):\n+ @override_settings(DEBUG=True)\n+ def test_batch_size_override(self):\n+ # Create a large number of objects\n+ num_objects = 1000\n+ objects = [TwoFields(f1=i, f2=i) for i in range(num_objects)]\n+\n+ # Set a very small batch size\n+ small_batch_size = 10\n+\n+ # Clear the connection queries\n+ connection.queries_log.clear()\n+\n+ # Perform bulk_create with the small batch size\n+ TwoFields.objects.bulk_create(objects, batch_size=small_batch_size)\n+\n+ # Count the number of INSERT queries\n+ insert_query_count = sum(1 for q in connection.queries if q['sql'].startswith('INSERT'))\n+\n+ # Calculate the expected number of queries if batch_size is respected\n+ expected_query_count = (num_objects + small_batch_size - 1) // small_batch_size\n+\n+ # Assert that the number of INSERT queries matches the expected count\n+ self.assertEqual(insert_query_count, expected_query_count,\n+ f\"Expected {expected_query_count} INSERT queries, but got {insert_query_count}\")\n+\n+ # Verify that all objects were created\n+ self.assertEqual(TwoFields.objects.count(), num_objects)\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2326384, + "num_received_chars": 127267, + "elapsed_time": 745.0322926044464, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12039.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12039.json new file mode 100644 index 00000000..52d2e9bb --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12039.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12039", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/ddl_references.py b/django/db/backends/ddl_references.py\nindex 44e4980..fc0afd0 100644\n--- a/django/db/backends/ddl_references.py\n+++ b/django/db/backends/ddl_references.py\n@@ -83,10 +83,14 @@ class Columns(TableColumns):\n \n def __str__(self):\n def col_str(column, idx):\n+ quoted_column = self.quote_name(column)\n try:\n- return self.quote_name(column) + self.col_suffixes[idx]\n+ suffix = self.col_suffixes[idx]\n+ if suffix.strip().upper() == 'DESC':\n+ return f\"{quoted_column} {suffix}\"\n+ return f\"{quoted_column}{suffix}\"\n except IndexError:\n- return self.quote_name(column)\n+ return quoted_column\n \n return ', '.join(col_str(column, idx) for idx, column in enumerate(self.columns))\n \n@@ -112,12 +116,22 @@ class IndexColumns(Columns):\n def col_str(column, idx):\n # Index.__init__() guarantees that self.opclasses is the same\n # length as self.columns.\n- col = '{} {}'.format(self.quote_name(column), self.opclasses[idx])\n+ quoted_column = self.quote_name(column)\n+ parts = [quoted_column]\n+ \n+ if self.opclasses[idx]:\n+ parts.append(self.opclasses[idx])\n+ \n try:\n- col = '{} {}'.format(col, self.col_suffixes[idx])\n+ suffix = self.col_suffixes[idx]\n+ if suffix.strip().upper() == 'DESC':\n+ parts.append(suffix)\n+ else:\n+ parts[-1] += suffix\n except IndexError:\n pass\n- return col\n+ \n+ return ' '.join(parts)\n \n return ', '.join(col_str(column, idx) for idx, column in enumerate(self.columns))\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1393817, + "num_received_chars": 60136, + "elapsed_time": 388.66629910469055, + "lint_repair_count": 3, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12143.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12143.json new file mode 100644 index 00000000..5eb0916f --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12143.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12143", + "edit_test_file": "tests/modeladmin/tests.py", + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 137e6fa..a100f1c 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -1631,7 +1631,7 @@ class ModelAdmin(BaseModelAdmin):\n \n def _get_edited_object_pks(self, request, prefix):\n \"\"\"Return POST data values of list_editable primary keys.\"\"\"\n- pk_pattern = re.compile(r'{}-\\d+-{}$'.format(prefix, self.model._meta.pk.name))\n+ pk_pattern = re.compile(r'{}-\\d+-{}$'.format(re.escape(prefix), self.model._meta.pk.name))\n return [value for key, value in request.POST.items() if pk_pattern.match(key)]\n \n def _get_list_editable_queryset(self, request, prefix):\n", + "test_patch": "diff --git a/tests/modeladmin/test_admin_formset_prefix_regex.py b/tests/modeladmin/test_admin_formset_prefix_regex.py\nnew file mode 100644\nindex 0000000..adb19a2\n--- /dev/null\n+++ b/tests/modeladmin/test_admin_formset_prefix_regex.py\n@@ -0,0 +1,52 @@\n+from django.contrib.admin import ModelAdmin\n+from django.contrib.admin.sites import AdminSite\n+from django.test import TestCase\n+from django.forms import formset_factory\n+\n+from .models import Band\n+\n+class FormsetPrefixRegexTestCase(TestCase):\n+ def setUp(self):\n+ self.site = AdminSite()\n+\n+ def test_formset_prefix_with_regex_special_chars(self):\n+ class BandAdmin(ModelAdmin):\n+ pass\n+\n+ ma = BandAdmin(Band, self.site)\n+ \n+ # Use a prefix with regex special characters\n+ prefix_with_special_chars = 'form[0-9]+'\n+ \n+ # Create a formset with the special prefix\n+ BandFormSet = formset_factory(ma.get_form(None), extra=1)\n+ formset = BandFormSet(prefix=prefix_with_special_chars)\n+ \n+ # Simulate form submission data\n+ data = {\n+ f'{prefix_with_special_chars}-TOTAL_FORMS': '1',\n+ f'{prefix_with_special_chars}-INITIAL_FORMS': '0',\n+ f'{prefix_with_special_chars}-0-name': 'Test Band',\n+ f'{prefix_with_special_chars}-0-bio': 'Test Bio',\n+ f'{prefix_with_special_chars}-0-sign_date': '2023-01-01',\n+ }\n+ \n+ # Bind the data to the formset\n+ bound_formset = BandFormSet(data, prefix=prefix_with_special_chars)\n+ \n+ # Assert that the formset is valid (it should be, as the data matches the prefix)\n+ self.assertTrue(bound_formset.is_valid())\n+ \n+ # Now, let's simulate the admin's internal processing\n+ # This is where the issue would occur, as it uses regex to parse the prefix\n+ processed_data = {}\n+ for key, value in data.items():\n+ if key.startswith(f'{prefix_with_special_chars}-') and not key.endswith(('TOTAL_FORMS', 'INITIAL_FORMS')):\n+ processed_data[key] = value\n+ \n+ # Assert that all our data is present in the processed data\n+ # If the regex fails to match due to special characters, this will fail\n+ self.assertEqual(len(processed_data), 3) # We expect 3 fields: name, bio, sign_date\n+ self.assertIn(f'{prefix_with_special_chars}-0-name', processed_data)\n+ self.assertIn(f'{prefix_with_special_chars}-0-bio', processed_data)\n+ self.assertIn(f'{prefix_with_special_chars}-0-sign_date', processed_data)\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2634053, + "num_received_chars": 135687, + "elapsed_time": 803.4800572395325, + "lint_repair_count": 11, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12209.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12209.json new file mode 100644 index 00000000..a3732373 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12209.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12209", + "edit_test_file": "tests/basic/tests.py", + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 38c1358..82e7495 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -442,6 +442,20 @@ class QuerySet:\n \"\"\"\n obj = self.model(**kwargs)\n self._for_write = True\n+ \n+ # Check if the primary key is explicitly set and the field has a default value\n+ pk_field = obj._meta.pk\n+ if pk_field.has_default() and obj.pk is not None:\n+ # Check if an object with this primary key already exists\n+ existing_obj = self.filter(pk=obj.pk).first()\n+ if existing_obj:\n+ # If the object exists, update it instead of inserting\n+ for key, value in kwargs.items():\n+ setattr(existing_obj, key, value)\n+ existing_obj.save(force_update=True, using=self.db)\n+ return existing_obj\n+ \n+ # If no existing object or no explicit PK, proceed with normal creation\n obj.save(force_insert=True, using=self.db)\n return obj\n \n@@ -450,6 +464,12 @@ class QuerySet:\n if obj.pk is None:\n obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n \n+ def _check_existing_objects(self, objs):\n+ # Helper method to check for existing objects with the same PKs\n+ pk_list = [obj.pk for obj in objs if obj.pk is not None]\n+ existing_objs = list(self.filter(pk__in=pk_list))\n+ return {obj.pk: obj for obj in existing_objs}\n+\n def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):\n \"\"\"\n Insert each of the instances into the database. Do *not* call\n", + "test_patch": "diff --git a/tests/basic/test_sample_model_save_behavior.py b/tests/basic/test_sample_model_save_behavior.py\nnew file mode 100644\nindex 0000000..7a36ff9\n--- /dev/null\n+++ b/tests/basic/test_sample_model_save_behavior.py\n@@ -0,0 +1,28 @@\n+import uuid\n+from django.test import TestCase\n+from django.db import models, IntegrityError\n+from django.db.transaction import atomic\n+\n+class Sample(models.Model):\n+ id = models.UUIDField(primary_key=True, default=uuid.uuid4)\n+ name = models.CharField(blank=True, max_length=100)\n+\n+class SampleModelSaveBehaviorTest(TestCase):\n+ def test_save_with_explicit_pk_raises_integrity_error(self):\n+ # Create an initial Sample instance\n+ s0 = Sample.objects.create()\n+ \n+ # Attempt to create a new instance with the same pk\n+ s1 = Sample(pk=s0.pk, name='Test 1')\n+ \n+ # In Django 3.0+, this should raise an IntegrityError\n+ with self.assertRaises(IntegrityError):\n+ with atomic():\n+ s1.save()\n+ \n+ # Verify that only one instance exists in the database\n+ self.assertEqual(Sample.objects.count(), 1)\n+ \n+ # Verify that the original instance is unchanged\n+ s0.refresh_from_db()\n+ self.assertEqual(s0.name, '')\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2361227, + "num_received_chars": 114563, + "elapsed_time": 699.0064074993134, + "lint_repair_count": 3, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12276.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12276.json new file mode 100644 index 00000000..5b85d24b --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12276.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12276", + "edit_test_file": "tests/forms_tests/widget_tests/test_fileinput.py", + "code_patch": "diff --git a/django/forms/widgets.py b/django/forms/widgets.py\nindex 338d54d..40ac1d3 100644\n--- a/django/forms/widgets.py\n+++ b/django/forms/widgets.py\n@@ -387,6 +387,9 @@ class FileInput(Input):\n def value_omitted_from_data(self, data, files, name):\n return name not in files\n \n+ def use_required_attribute(self, initial):\n+ return super().use_required_attribute(initial) and not initial\n+\n \n FILE_INPUT_CONTRADICTION = object()\n \n@@ -451,9 +454,6 @@ class ClearableFileInput(FileInput):\n return False\n return upload\n \n- def use_required_attribute(self, initial):\n- return super().use_required_attribute(initial) and not initial\n-\n def value_omitted_from_data(self, data, files, name):\n return (\n super().value_omitted_from_data(data, files, name) and\n", + "test_patch": "diff --git a/tests/forms_tests/widget_tests/test_fileinput_required_attribute.py b/tests/forms_tests/widget_tests/test_fileinput_required_attribute.py\nnew file mode 100644\nindex 0000000..a211e6b\n--- /dev/null\n+++ b/tests/forms_tests/widget_tests/test_fileinput_required_attribute.py\n@@ -0,0 +1,34 @@\n+from django.forms import FileInput\n+from django.forms.widgets import FILE_INPUT_CONTRADICTION\n+from django.test import TestCase\n+\n+\n+class FileInputRequiredAttributeTest(TestCase):\n+ def test_required_attribute_with_initial_data(self):\n+ widget = FileInput()\n+ \n+ # Simulate a scenario where initial data exists (e.g., a file is already saved)\n+ initial_value = 'existing_file.txt'\n+ \n+ # Generate the HTML for the widget\n+ html = widget.render('test_file', initial_value, attrs={'required': True})\n+ \n+ # The test passes if the 'required' attribute is present in the HTML,\n+ # which is the current behavior we're trying to highlight as an issue\n+ self.assertIn('required', html)\n+\n+ def test_use_required_attribute_with_initial_data(self):\n+ widget = FileInput()\n+ \n+ # Test the use_required_attribute method directly\n+ # It should return False when initial data exists, but it currently doesn't\n+ self.assertTrue(widget.use_required_attribute('existing_file.txt'))\n+\n+ def test_required_attribute_without_initial_data(self):\n+ widget = FileInput()\n+ \n+ # Generate the HTML for the widget without initial data\n+ html = widget.render('test_file', None, attrs={'required': True})\n+ \n+ # The 'required' attribute should be present when there's no initial data\n+ self.assertIn('required', html)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/forms_tests/widget_tests/test_fileinput_required_attribute_inverted.py b/tests/forms_tests/widget_tests/test_fileinput_required_attribute_inverted.py\nnew file mode 100644\nindex 0000000..93169da\n--- /dev/null\n+++ b/tests/forms_tests/widget_tests/test_fileinput_required_attribute_inverted.py\n@@ -0,0 +1,44 @@\n+from django.forms import FileInput\n+from django.test import TestCase\n+\n+\n+class FileInputRequiredAttributeTest(TestCase):\n+ def test_required_attribute_with_initial_data(self):\n+ widget = FileInput()\n+ \n+ # Simulate a scenario where initial data exists (e.g., a file is already saved)\n+ initial_value = 'existing_file.txt'\n+ \n+ # Generate the HTML for the widget\n+ html = widget.render('test_file', initial_value, attrs={'required': True})\n+ \n+ # The test should fail if the 'required' attribute is present in the HTML\n+ # when initial data exists\n+ if 'required' in html:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ def test_use_required_attribute_with_initial_data(self):\n+ widget = FileInput()\n+ \n+ # Test the use_required_attribute method directly\n+ # It should return False when initial data exists\n+ if widget.use_required_attribute('existing_file.txt'):\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ def test_required_attribute_without_initial_data(self):\n+ widget = FileInput()\n+ \n+ # Generate the HTML for the widget without initial data\n+ html = widget.render('test_file', None, attrs={'required': True})\n+ \n+ # The 'required' attribute should be present when there's no initial data\n+ if 'required' not in html:\n+ raise AssertionError(\"Test failed: 'required' attribute should be present without initial data\")\n+\n+ def test_use_required_attribute_without_initial_data(self):\n+ widget = FileInput()\n+ \n+ # Test the use_required_attribute method without initial data\n+ # It should return True when there's no initial data\n+ if not widget.use_required_attribute(None):\n+ raise AssertionError(\"Test failed: use_required_attribute should return True without initial data\")\n\\ No newline at end of file\n", + "num_sent_chars": 1075773, + "num_received_chars": 51048, + "elapsed_time": 338.5168125629425, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12325.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12325.json new file mode 100644 index 00000000..bc67d26d --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12325.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12325", + "edit_test_file": "tests/model_inheritance/tests.py", + "code_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex a375f6b..dc29fea 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -161,6 +161,16 @@ class Options:\n # for use when serializing the model definition\n self.original_attrs = {}\n \n+ # Ensure consistent parent link detection\n+ if self.parents:\n+ for parent, parent_link in self.parents.items():\n+ if parent_link is None:\n+ field = self._get_parent_link_for_model(parent)\n+ if field:\n+ self.parents[parent] = field\n+ if not field.remote_field.parent_link:\n+ field.remote_field.parent_link = True\n+\n # Next, apply any overridden values from 'class Meta'.\n if self.meta:\n meta_attrs = self.meta.__dict__.copy()\n", + "test_patch": "diff --git a/tests/model_inheritance/test_multi_onetoone_inheritance.py b/tests/model_inheritance/test_multi_onetoone_inheritance.py\nnew file mode 100644\nindex 0000000..0a3d353\n--- /dev/null\n+++ b/tests/model_inheritance/test_multi_onetoone_inheritance.py\n@@ -0,0 +1,24 @@\n+from django.core.exceptions import ImproperlyConfigured\n+from django.db import models\n+from django.test import SimpleTestCase\n+from django.test.utils import isolate_apps\n+\n+\n+class MultiOneToOneInheritanceTests(SimpleTestCase):\n+ @isolate_apps('model_inheritance')\n+ def test_multiple_onetoone_inheritance_order_matters(self):\n+ class Document(models.Model):\n+ pass\n+\n+ with self.assertRaisesMessage(ImproperlyConfigured, \n+ \"Add parent_link=True to model_inheritance.Picking.origin.\"):\n+ class Picking(Document):\n+ document_ptr = models.OneToOneField(Document, on_delete=models.CASCADE, parent_link=True, related_name='+')\n+ origin = models.OneToOneField(Document, related_name='picking', on_delete=models.PROTECT)\n+\n+ # This should work without raising an exception\n+ class PickingCorrectOrder(Document):\n+ origin = models.OneToOneField(Document, related_name='picking', on_delete=models.PROTECT)\n+ document_ptr = models.OneToOneField(Document, on_delete=models.CASCADE, parent_link=True, related_name='+')\n+\n+ self.assertTrue(issubclass(PickingCorrectOrder, Document))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_inheritance/test_multi_onetoone_inheritance_inverted.py b/tests/model_inheritance/test_multi_onetoone_inheritance_inverted.py\nnew file mode 100644\nindex 0000000..431491e\n--- /dev/null\n+++ b/tests/model_inheritance/test_multi_onetoone_inheritance_inverted.py\n@@ -0,0 +1,41 @@\n+from django.core.exceptions import ImproperlyConfigured\n+from django.db import models\n+from django.test import SimpleTestCase\n+from django.test.utils import isolate_apps\n+\n+\n+class MultiOneToOneInheritanceTests(SimpleTestCase):\n+ @isolate_apps('model_inheritance')\n+ def test_multiple_onetoone_inheritance_order_matters(self):\n+ class Document(models.Model):\n+ pass\n+\n+ # This should now raise an exception with our custom error message\n+ try:\n+ class Picking(Document):\n+ document_ptr = models.OneToOneField(Document, on_delete=models.CASCADE, parent_link=True, related_name='+')\n+ origin = models.OneToOneField(Document, related_name='picking', on_delete=models.PROTECT)\n+ except ImproperlyConfigured:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # This should still work without raising an exception\n+ class PickingCorrectOrder(Document):\n+ origin = models.OneToOneField(Document, related_name='picking', on_delete=models.PROTECT)\n+ document_ptr = models.OneToOneField(Document, on_delete=models.CASCADE, parent_link=True, related_name='+')\n+\n+ self.assertTrue(issubclass(PickingCorrectOrder, Document))\n+\n+ @isolate_apps('model_inheritance')\n+ def test_multiple_onetoone_inheritance_order_should_not_matter(self):\n+ class Document(models.Model):\n+ pass\n+\n+ # This should not raise an exception, but it does due to the bug\n+ try:\n+ class Picking(Document):\n+ document_ptr = models.OneToOneField(Document, on_delete=models.CASCADE, parent_link=True, related_name='+')\n+ origin = models.OneToOneField(Document, related_name='picking', on_delete=models.PROTECT)\n+ except ImproperlyConfigured:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ self.assertTrue(issubclass(Picking, Document))\n\\ No newline at end of file\n", + "num_sent_chars": 1596991, + "num_received_chars": 155402, + "elapsed_time": 768.5370202064514, + "lint_repair_count": 3, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12663.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12663.json new file mode 100644 index 00000000..3eb87c2c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12663.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12663", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/fields/related_lookups.py b/django/db/models/fields/related_lookups.py\nindex c20e220..753ec52 100644\n--- a/django/db/models/fields/related_lookups.py\n+++ b/django/db/models/fields/related_lookups.py\n@@ -103,6 +103,14 @@ class RelatedLookupMixin:\n def get_prep_lookup(self):\n if not isinstance(self.lhs, MultiColSource) and not hasattr(self.rhs, 'resolve_expression'):\n # If we get here, we are dealing with single-column relations.\n+ \n+ # Handle SimpleLazyObject\n+ from django.utils.functional import SimpleLazyObject\n+ if isinstance(self.rhs, SimpleLazyObject):\n+ self.rhs = self.rhs._wrapped\n+ if self.rhs is SimpleLazyObject.empty:\n+ self.rhs = self.rhs._setupfunc()\n+ \n self.rhs = get_normalized_value(self.rhs, self.lhs)[0]\n # We need to run the related field's get_prep_value(). Consider case\n # ForeignKey to IntegerField given value 'abc'. The ForeignKey itself\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1417058, + "num_received_chars": 49993, + "elapsed_time": 359.73848938941956, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12741.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12741.json new file mode 100644 index 00000000..dfdeb6c7 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12741.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12741", + "edit_test_file": "tests/backends/base/test_operations.py", + "code_patch": "diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py\nindex 70ac07a..f07580c 100644\n--- a/django/db/backends/base/operations.py\n+++ b/django/db/backends/base/operations.py\n@@ -400,9 +400,9 @@ class BaseDatabaseOperations:\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations must provide a sql_flush() method')\n \n- def execute_sql_flush(self, using, sql_list):\n+ def execute_sql_flush(self, sql_list):\n \"\"\"Execute a list of SQL statements to flush the database.\"\"\"\n- with transaction.atomic(using=using, savepoint=self.connection.features.can_rollback_ddl):\n+ with transaction.atomic(using=self.connection.alias, savepoint=self.connection.features.can_rollback_ddl):\n with self.connection.cursor() as cursor:\n for sql in sql_list:\n cursor.execute(sql)\n", + "test_patch": "diff --git a/tests/backends/base/test_execute_sql_flush.py b/tests/backends/base/test_execute_sql_flush.py\nnew file mode 100644\nindex 0000000..cf23845\n--- /dev/null\n+++ b/tests/backends/base/test_execute_sql_flush.py\n@@ -0,0 +1,39 @@\n+from django.core.management.color import no_style\n+from django.db import connection, transaction\n+from django.test import TransactionTestCase\n+\n+from ..models import Author, Book\n+\n+\n+class ExecuteSqlFlushTests(TransactionTestCase):\n+ available_apps = ['backends']\n+\n+ def test_execute_sql_flush_signature(self):\n+ with transaction.atomic():\n+ Author.objects.create(name='Test Author')\n+ Book.objects.create(author=Author.objects.first())\n+\n+ self.assertTrue(Author.objects.exists())\n+ self.assertTrue(Book.objects.exists())\n+\n+ sql_list = connection.ops.sql_flush(\n+ no_style(),\n+ [Author._meta.db_table, Book._meta.db_table],\n+ reset_sequences=True,\n+ allow_cascade=True,\n+ )\n+\n+ # This test passes with the current implementation\n+ # It would fail if the signature is changed to remove the 'using' argument\n+ try:\n+ connection.ops.execute_sql_flush(connection.alias, sql_list)\n+ except TypeError:\n+ self.fail(\"execute_sql_flush() raised TypeError unexpectedly!\")\n+\n+ # Verify that the tables were actually flushed\n+ self.assertFalse(Author.objects.exists())\n+ self.assertFalse(Book.objects.exists())\n+\n+ # Test the proposed signature (this should raise a TypeError with the current implementation)\n+ with self.assertRaises(TypeError):\n+ connection.ops.execute_sql_flush(sql_list)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/backends/base/test_execute_sql_flush_inverted.py b/tests/backends/base/test_execute_sql_flush_inverted.py\nnew file mode 100644\nindex 0000000..3adfb11\n--- /dev/null\n+++ b/tests/backends/base/test_execute_sql_flush_inverted.py\n@@ -0,0 +1,39 @@\n+from django.core.management.color import no_style\n+from django.db import connection, transaction\n+from django.test import TransactionTestCase\n+\n+from ..models import Author, Book\n+\n+\n+class ExecuteSqlFlushTests(TransactionTestCase):\n+ available_apps = ['backends']\n+\n+ def test_execute_sql_flush_signature(self):\n+ with transaction.atomic():\n+ Author.objects.create(name='Test Author')\n+ Book.objects.create(author=Author.objects.first())\n+\n+ self.assertTrue(Author.objects.exists())\n+ self.assertTrue(Book.objects.exists())\n+\n+ sql_list = connection.ops.sql_flush(\n+ no_style(),\n+ [Author._meta.db_table, Book._meta.db_table],\n+ reset_sequences=True,\n+ allow_cascade=True,\n+ )\n+\n+ # This test should now fail if the signature has been changed\n+ try:\n+ connection.ops.execute_sql_flush(sql_list)\n+ except TypeError:\n+ # If a TypeError is raised, it means the signature hasn't been updated\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Verify that the tables were actually flushed\n+ self.assertFalse(Author.objects.exists())\n+ self.assertFalse(Book.objects.exists())\n+\n+ # Test the old signature (this should now raise a TypeError)\n+ with self.assertRaises(TypeError):\n+ connection.ops.execute_sql_flush(connection.alias, sql_list)\n\\ No newline at end of file\n", + "num_sent_chars": 1778361, + "num_received_chars": 96250, + "elapsed_time": 571.1092338562012, + "lint_repair_count": 7, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12858.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12858.json new file mode 100644 index 00000000..b33ffdcf --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-12858.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-12858", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\nindex 6c9e9d3..a2c5417 100644\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -1732,6 +1732,21 @@ class Model(metaclass=ModelBase):\n fields = _fields\n \n # Check related fields.\n+ for field in related_fields:\n+ parts = field.split(LOOKUP_SEP)\n+ last_part = parts[-1]\n+ if last_part in valid_lookups:\n+ # If the last part is a valid lookup, remove it for field validation\n+ parts = parts[:-1]\n+ \n+ # Validate all parts of the field\n+ current_cls = cls\n+ for part in parts:\n+ try:\n+ field = current_cls._meta.get_field(part)\n+ if hasattr(field, 'remote_field'):\n+ current_cls = field.remote_field.model\n+ except FieldDoesNotExist:\n for field in related_fields:\n _cls = cls\n fld = None\n@@ -1751,11 +1766,16 @@ class Model(metaclass=ModelBase):\n errors.append(\n checks.Error(\n \"'ordering' refers to the nonexistent field, \"\n- \"related field, or lookup '%s'.\" % field,\n+ \"related field, or lookup '%s'. Note that the last \"\n+ \"part of an ordering string can be a lookup (like '__isnull') \"\n+ \"if it's a valid lookup for the field.\" % field,\n obj=cls,\n id='models.E015',\n )\n )\n+ break\n+ else:\n+ # If the loop completed without breaking, the field is valid\n \n # Skip ordering on pk. This is always a valid order_by field\n # but is an alias and therefore won't be found by opts.get_field.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2786889, + "num_received_chars": 172912, + "elapsed_time": 930.1121289730072, + "lint_repair_count": 10, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13023.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13023.json new file mode 100644 index 00000000..fbdca43a --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13023.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13023", + "edit_test_file": "tests/model_fields/test_decimalfield.py", + "code_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 0fd6905..b673ca0 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -1499,6 +1499,12 @@ class DecimalField(Field):\n return value\n if isinstance(value, float):\n return self.context.create_decimal_from_float(value)\n+ if isinstance(value, dict):\n+ raise exceptions.ValidationError(\n+ self.error_messages['invalid_dict'],\n+ code='invalid_dict',\n+ params={'value': value},\n+ )\n try:\n return decimal.Decimal(value)\n except decimal.InvalidOperation:\n", + "test_patch": "diff --git a/tests/model_fields/test_decimalfield_dict_input.py b/tests/model_fields/test_decimalfield_dict_input.py\nnew file mode 100644\nindex 0000000..7d3c5f0\n--- /dev/null\n+++ b/tests/model_fields/test_decimalfield_dict_input.py\n@@ -0,0 +1,19 @@\n+from decimal import Decimal\n+\n+from django.core.exceptions import ValidationError\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class DecimalFieldDictInputTest(TestCase):\n+ def test_to_python_with_dict_input(self):\n+ f = models.DecimalField(max_digits=4, decimal_places=2)\n+ dict_input = {'value': '3.14'}\n+\n+ with self.assertRaises(TypeError):\n+ f.to_python(dict_input)\n+\n+ # The following assertion is commented out because it's what we expect\n+ # to happen after the issue is fixed. Currently, it will not reach this point.\n+ # with self.assertRaisesMessage(ValidationError, '\"{\\\\'value\\\\': \\\\'3.14\\\\'}\" value must be a decimal number.'):\n+ # f.to_python(dict_input)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_fields/test_decimalfield_dict_input_inverted.py b/tests/model_fields/test_decimalfield_dict_input_inverted.py\nnew file mode 100644\nindex 0000000..e90d501\n--- /dev/null\n+++ b/tests/model_fields/test_decimalfield_dict_input_inverted.py\n@@ -0,0 +1,36 @@\n+from decimal import Decimal\n+\n+from django.core.exceptions import ValidationError\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class DecimalFieldDictInputTest(TestCase):\n+ def test_to_python_with_dict_input(self):\n+ f = models.DecimalField(max_digits=4, decimal_places=2)\n+ dict_input = {'value': '3.14'}\n+\n+ try:\n+ f.to_python(dict_input)\n+ except TypeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # If no TypeError is raised, the test should fail\n+ self.fail(\"Expected TypeError, but no exception was raised\")\n+\n+ def test_to_python_with_valid_input(self):\n+ f = models.DecimalField(max_digits=4, decimal_places=2)\n+ valid_input = '3.14'\n+\n+ try:\n+ result = f.to_python(valid_input)\n+ self.assertEqual(result, Decimal('3.14'))\n+ except ValidationError:\n+ self.fail(\"Unexpected ValidationError for valid input\")\n+\n+ def test_to_python_with_invalid_input(self):\n+ f = models.DecimalField(max_digits=4, decimal_places=2)\n+ invalid_input = 'not_a_number'\n+\n+ with self.assertRaises(ValidationError):\n+ f.to_python(invalid_input)\n\\ No newline at end of file\n", + "num_sent_chars": 2248291, + "num_received_chars": 129253, + "elapsed_time": 712.146568775177, + "lint_repair_count": 11, + "test_generation_attempts": 4, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13089.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13089.json new file mode 100644 index 00000000..95ad80f5 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13089.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13089", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/cache/backends/db.py b/django/core/cache/backends/db.py\nindex 33c79c5..68d1f4d 100644\n--- a/django/core/cache/backends/db.py\n+++ b/django/core/cache/backends/db.py\n@@ -267,9 +267,15 @@ class DatabaseCache(BaseDatabaseCache):\n cursor.execute(\n connection.ops.cache_key_culling_sql() % table,\n [cull_num])\n- cursor.execute(\"DELETE FROM %s \"\n- \"WHERE cache_key < %%s\" % table,\n- [cursor.fetchone()[0]])\n+ result = cursor.fetchone()\n+ if result is None:\n+ # No data returned from culling query, skip DELETE operation\n+ from django.core.cache import logger\n+ logger.debug(\"No data returned from cache culling query. Skipping DELETE operation.\")\n+ else:\n+ cursor.execute(\"DELETE FROM %s \"\n+ \"WHERE cache_key < %%s\" % table,\n+ [result[0]])\n \n def clear(self):\n db = router.db_for_write(self.cache_model_class)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 905729, + "num_received_chars": 54236, + "elapsed_time": 484.5539803504944, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13121.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13121.json new file mode 100644 index 00000000..3e7f960d --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13121.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13121", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py\nindex 2e283a3..fd3298d 100644\n--- a/django/db/backends/base/operations.py\n+++ b/django/db/backends/base/operations.py\n@@ -579,8 +579,33 @@ class BaseDatabaseOperations:\n return []\n \n def convert_durationfield_value(self, value, expression, connection):\n- if value is not None:\n- return datetime.timedelta(0, 0, value)\n+ if value is None:\n+ return None\n+ \n+ if isinstance(value, (int, float, decimal.Decimal)):\n+ # Assume the value is in microseconds\n+ return datetime.timedelta(microseconds=int(value))\n+ \n+ if isinstance(value, str):\n+ try:\n+ # Try to parse as ISO 8601 duration string\n+ if value.startswith('P'):\n+ days, _, time = value.partition('T')\n+ days = int(days[1:-1]) if 'D' in days else 0\n+ hours, minutes, seconds = time.replace('H', ':').replace('M', ':').replace('S', '').split(':')\n+ hours = int(hours) if hours else 0\n+ minutes = int(minutes) if minutes else 0\n+ seconds = float(seconds) if seconds else 0\n+ return datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)\n+ \n+ # Try to parse as a simple time string (HH:MM:SS.ffffff)\n+ hours, minutes, seconds = value.split(':')\n+ return datetime.timedelta(hours=int(hours), minutes=int(minutes), seconds=float(seconds))\n+ except ValueError:\n+ pass\n+ \n+ # If we can't parse the value, raise a ValueError\n+ raise ValueError(f\"Unable to convert {value} to timedelta\")\n \n def check_expression_support(self, expression):\n \"\"\"\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 7987472, + "num_received_chars": 166088, + "elapsed_time": 1113.2988712787628, + "lint_repair_count": 15, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13195.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13195.json new file mode 100644 index 00000000..e9176807 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13195.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13195", + "edit_test_file": null, + "code_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex e00bcac..1943179 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -210,12 +210,30 @@ class HttpResponseBase:\n value = signing.get_cookie_signer(salt=key + salt).sign(value)\n return self.set_cookie(key, value, **kwargs)\n \n- def delete_cookie(self, key, path='/', domain=None):\n+ def delete_cookie(self, key, path='/', domain=None, samesite=None):\n # Most browsers ignore the Set-Cookie header if the cookie name starts\n # with __Host- or __Secure- and the cookie doesn't use the secure flag.\n secure = key.startswith(('__Secure-', '__Host-'))\n+ \n+ # Check if the cookie exists and get its attributes\n+ if key in self.cookies:\n+ cookie = self.cookies[key]\n+ path = cookie.get('path', path)\n+ domain = cookie.get('domain', domain)\n+ secure = cookie.get('secure', secure)\n+ samesite = cookie.get('samesite', samesite)\n+ \n+ # Ensure SameSite=None always sets the Secure flag\n+ if samesite and samesite.lower() == 'none':\n+ secure = True\n+ \n self.set_cookie(\n- key, max_age=0, path=path, domain=domain, secure=secure,\n+ key,\n+ max_age=0,\n+ path=path,\n+ domain=domain,\n+ secure=secure,\n+ samesite=samesite,\n expires='Thu, 01 Jan 1970 00:00:00 GMT',\n )\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 937731, + "num_received_chars": 37094, + "elapsed_time": 268.4743769168854, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13297.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13297.json new file mode 100644 index 00000000..0489b929 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13297.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13297", + "edit_test_file": null, + "code_patch": "diff --git a/django/utils/functional.py b/django/utils/functional.py\nindex 6d38f93..9b84658 100644\n--- a/django/utils/functional.py\n+++ b/django/utils/functional.py\n@@ -370,10 +370,27 @@ class SimpleLazyObject(LazyObject):\n value.\n \"\"\"\n self.__dict__['_setupfunc'] = func\n+ self.__dict__['_resolved'] = False\n super().__init__()\n \n def _setup(self):\n self._wrapped = self._setupfunc()\n+ self.__dict__['_resolved'] = True\n+\n+ def resolve(self):\n+ \"\"\"\n+ Explicitly resolve the lazy object.\n+ \"\"\"\n+ if not self._resolved:\n+ self._setup()\n+ return self._wrapped\n+\n+ @property\n+ def is_resolved(self):\n+ \"\"\"\n+ Check if the lazy object has been resolved.\n+ \"\"\"\n+ return self.__dict__['_resolved']\n \n # Return a meaningful representation of the lazy object for debugging\n # without evaluating the wrapped object.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1586804, + "num_received_chars": 87762, + "elapsed_time": 531.5780012607574, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13344.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13344.json new file mode 100644 index 00000000..bcd8163f --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13344.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13344", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py\nindex 169df6b..ec9321f 100644\n--- a/django/core/handlers/base.py\n+++ b/django/core/handlers/base.py\n@@ -146,6 +146,11 @@ class BaseHandler:\n # Setup default url resolver for this thread.\n set_urlconf(settings.ROOT_URLCONF)\n response = await self._middleware_chain(request)\n+ \n+ # Ensure response is an HttpResponse object\n+ if asyncio.iscoroutine(response):\n+ response = await response\n+ \n response._resource_closers.append(request.close)\n if response.status_code >= 400:\n await sync_to_async(log_response)(\n@@ -220,6 +225,9 @@ class BaseHandler:\n for middleware_method in self._view_middleware:\n response = await middleware_method(request, callback, callback_args, callback_kwargs)\n if response:\n+ # Ensure response is an HttpResponse object\n+ if asyncio.iscoroutine(response):\n+ response = await response\n break\n \n if response is None:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1129997, + "num_received_chars": 77821, + "elapsed_time": 400.29476618766785, + "lint_repair_count": 3, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13401.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13401.json new file mode 100644 index 00000000..f469cce9 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13401.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13401", + "edit_test_file": "tests/model_inheritance/test_abstract_inheritance.py", + "code_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 2837427..9c673f0 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -516,17 +516,27 @@ class Field(RegisterLookupMixin):\n def __eq__(self, other):\n # Needed for @total_ordering\n if isinstance(other, Field):\n+ if hasattr(self, 'model') and hasattr(other, 'model'):\n+ return (\n+ self.creation_counter == other.creation_counter and\n+ self.model == other.model\n+ )\n return self.creation_counter == other.creation_counter\n return NotImplemented\n \n def __lt__(self, other):\n # This is needed because bisect does not take a comparison function.\n if isinstance(other, Field):\n- return self.creation_counter < other.creation_counter\n+ if self.creation_counter != other.creation_counter:\n+ return self.creation_counter < other.creation_counter\n+ if hasattr(self, 'model') and hasattr(other, 'model'):\n+ return self.model.__name__ < other.model.__name__\n+ return False\n return NotImplemented\n \n def __hash__(self):\n- return hash(self.creation_counter)\n+ model_name = self.model.__name__ if hasattr(self, 'model') else ''\n+ return hash((self.creation_counter, model_name))\n \n def __deepcopy__(self, memodict):\n # We don't have to deepcopy very much here, since most things are not\n", + "test_patch": "diff --git a/tests/model_inheritance/test_abstract_model_field_equality.py b/tests/model_inheritance/test_abstract_model_field_equality.py\nnew file mode 100644\nindex 0000000..3e64e5f\n--- /dev/null\n+++ b/tests/model_inheritance/test_abstract_model_field_equality.py\n@@ -0,0 +1,36 @@\n+from django.db import models\n+from django.test import SimpleTestCase\n+from django.test.utils import isolate_apps\n+\n+\n+@isolate_apps('model_inheritance')\n+class AbstractModelFieldEqualityTests(SimpleTestCase):\n+ def test_abstract_model_field_equality(self):\n+ class AbstractBase(models.Model):\n+ myfield = models.IntegerField()\n+\n+ class Meta:\n+ abstract = True\n+\n+ class ModelB(AbstractBase):\n+ pass\n+\n+ class ModelC(AbstractBase):\n+ pass\n+\n+ field_b = ModelB._meta.get_field('myfield')\n+ field_c = ModelC._meta.get_field('myfield')\n+\n+ # Test that the fields are considered equal\n+ self.assertEqual(field_b, field_c)\n+\n+ # Test that when added to a set, only one field remains\n+ fields_set = {field_b, field_c}\n+ self.assertEqual(len(fields_set), 1)\n+\n+ # Test that the fields have the same hash\n+ self.assertEqual(hash(field_b), hash(field_c))\n+\n+ # Test that the fields are not less than each other\n+ self.assertFalse(field_b < field_c)\n+ self.assertFalse(field_c < field_b)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_inheritance/test_abstract_model_field_equality_inverted.py b/tests/model_inheritance/test_abstract_model_field_equality_inverted.py\nnew file mode 100644\nindex 0000000..6dafead\n--- /dev/null\n+++ b/tests/model_inheritance/test_abstract_model_field_equality_inverted.py\n@@ -0,0 +1,53 @@\n+from django.db import models\n+from django.test import SimpleTestCase\n+from django.test.utils import isolate_apps\n+\n+\n+@isolate_apps('model_inheritance')\n+class AbstractModelFieldEqualityTests(SimpleTestCase):\n+ def test_abstract_model_field_equality(self):\n+ class AbstractBase(models.Model):\n+ myfield = models.IntegerField()\n+\n+ class Meta:\n+ abstract = True\n+\n+ class ModelB(AbstractBase):\n+ pass\n+\n+ class ModelC(AbstractBase):\n+ pass\n+\n+ field_b = ModelB._meta.get_field('myfield')\n+ field_c = ModelC._meta.get_field('myfield')\n+\n+ # Test that the fields are not considered equal\n+ try:\n+ self.assertNotEqual(field_b, field_c)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Test that when added to a set, two fields remain\n+ fields_set = {field_b, field_c}\n+ try:\n+ self.assertEqual(len(fields_set), 2)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Test that the fields have different hashes\n+ try:\n+ self.assertNotEqual(hash(field_b), hash(field_c))\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Test that the fields are less than each other based on their models\n+ try:\n+ self.assertTrue(field_b < field_c or field_c < field_b)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Test that the fields are not equal when comparing with less than\n+ try:\n+ self.assertFalse(field_b == field_c)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 365515, + "num_received_chars": 12619, + "elapsed_time": 87.00551271438599, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13417.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13417.json new file mode 100644 index 00000000..5fe22d17 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13417.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13417", + "edit_test_file": "tests/model_fields/test_foreignkey.py", + "code_patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\nindex 85cd831..452c653 100644\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -1218,14 +1218,26 @@ class QuerySet:\n def ordered(self):\n \"\"\"\n Return True if the QuerySet is ordered -- i.e. has an order_by()\n- clause or a default ordering on the model (or is empty).\n+ clause or a default ordering on the model that will be applied\n+ (considering the effects of annotations and GROUP BY).\n \"\"\"\n if isinstance(self, EmptyQuerySet):\n return True\n- if self.query.extra_order_by or self.query.order_by:\n- return True\n- elif self.query.default_ordering and self.query.get_meta().ordering:\n+ \n+ has_explicit_ordering = bool(self.query.extra_order_by or self.query.order_by)\n+ has_default_ordering = self.query.default_ordering and self.query.get_meta().ordering\n+ \n+ # Check if there are annotations that would introduce GROUP BY\n+ has_group_by = bool(self.query.annotation_select)\n+ \n+ if has_explicit_ordering:\n return True\n+ elif has_group_by:\n+ # If we have GROUP BY, check if there's ordering that would be applied after grouping\n+ return bool(self.query.order_by)\n+ elif has_default_ordering:\n+ # Default ordering is only effective if there's no GROUP BY\n+ return not has_group_by\n else:\n return False\n \n", + "test_patch": "diff --git a/tests/model_fields/test_queryset_ordered_property_with_groupby.py b/tests/model_fields/test_queryset_ordered_property_with_groupby.py\nnew file mode 100644\nindex 0000000..729dd73\n--- /dev/null\n+++ b/tests/model_fields/test_queryset_ordered_property_with_groupby.py\n@@ -0,0 +1,41 @@\n+from django.test import TestCase\n+from django.db import models\n+from django.db.models import Count\n+\n+class OrderedModel(models.Model):\n+ name = models.CharField(max_length=50)\n+ \n+ class Meta:\n+ ordering = ['name']\n+\n+class QuerySetOrderedPropertyWithGroupByTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ OrderedModel.objects.bulk_create([\n+ OrderedModel(name='A'),\n+ OrderedModel(name='B'),\n+ OrderedModel(name='C'),\n+ ])\n+\n+ def test_ordered_property_with_group_by(self):\n+ # Regular queryset should be ordered\n+ qs = OrderedModel.objects.all()\n+ self.assertTrue(qs.ordered)\n+ self.assertTrue(qs.query.default_ordering)\n+\n+ # Check that the SQL contains ORDER BY\n+ self.assertIn('ORDER BY', str(qs.query))\n+\n+ # Annotated queryset with GROUP BY\n+ qs_annotated = OrderedModel.objects.annotate(Count('id'))\n+ \n+ # The `ordered` property should be True, even though it's incorrect\n+ self.assertTrue(qs_annotated.ordered)\n+ self.assertTrue(qs_annotated.query.default_ordering)\n+\n+ # Check that the SQL does not contain ORDER BY\n+ self.assertNotIn('ORDER BY', str(qs_annotated.query))\n+\n+ # This assertion shows that despite `ordered` being True,\n+ # the query doesn't actually have an ORDER BY clause\n+ self.assertIn('GROUP BY', str(qs_annotated.query))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_fields/test_queryset_ordered_property_with_groupby_inverted.py b/tests/model_fields/test_queryset_ordered_property_with_groupby_inverted.py\nnew file mode 100644\nindex 0000000..10611bd\n--- /dev/null\n+++ b/tests/model_fields/test_queryset_ordered_property_with_groupby_inverted.py\n@@ -0,0 +1,49 @@\n+from django.test import TestCase\n+from django.db import models\n+from django.db.models import Count\n+\n+class OrderedModel(models.Model):\n+ name = models.CharField(max_length=50)\n+ \n+ class Meta:\n+ ordering = ['name']\n+\n+class QuerySetOrderedPropertyWithGroupByTests(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ OrderedModel.objects.bulk_create([\n+ OrderedModel(name='A'),\n+ OrderedModel(name='B'),\n+ OrderedModel(name='C'),\n+ ])\n+\n+ def test_ordered_property_with_group_by(self):\n+ # Regular queryset should be ordered\n+ qs = OrderedModel.objects.all()\n+ self.assertTrue(qs.ordered)\n+ self.assertTrue(qs.query.default_ordering)\n+\n+ # Check that the SQL contains ORDER BY\n+ self.assertIn('ORDER BY', str(qs.query))\n+\n+ # Annotated queryset with GROUP BY\n+ qs_annotated = OrderedModel.objects.annotate(Count('id'))\n+ \n+ # The `ordered` property should be False when GROUP BY is used\n+ if qs_annotated.ordered:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # The `default_ordering` should be False when GROUP BY is used\n+ if qs_annotated.query.default_ordering:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check that the SQL does not contain ORDER BY\n+ self.assertNotIn('ORDER BY', str(qs_annotated.query))\n+\n+ # This assertion shows that the query has a GROUP BY clause\n+ self.assertIn('GROUP BY', str(qs_annotated.query))\n+\n+ # Additional test to ensure the queryset is not ordered\n+ results = list(qs_annotated)\n+ if results == sorted(results, key=lambda x: x.name):\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2211477, + "num_received_chars": 139762, + "elapsed_time": 760.9591698646545, + "lint_repair_count": 6, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13513.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13513.json new file mode 100644 index 00000000..096236f7 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13513.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13513", + "edit_test_file": null, + "code_patch": "diff --git a/django/views/debug.py b/django/views/debug.py\nindex 7a89f7b..8996114 100644\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -396,10 +396,11 @@ class ExceptionReporter:\n \n def get_traceback_frames(self):\n def explicit_or_implicit_cause(exc_value):\n- explicit = getattr(exc_value, '__cause__', None)\n- suppress_context = getattr(exc_value, '__suppress_context__', None)\n- implicit = getattr(exc_value, '__context__', None)\n- return explicit or (None if suppress_context else implicit)\n+ if exc_value.__cause__ is not None:\n+ return exc_value.__cause__\n+ elif not exc_value.__suppress_context__:\n+ return exc_value.__context__\n+ return None\n \n # Get the exception and all its causes\n exceptions = []\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1007507, + "num_received_chars": 35010, + "elapsed_time": 278.68121004104614, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13568.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13568.json new file mode 100644 index 00000000..9e37a0b4 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13568.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13568", + "edit_test_file": "tests/auth_tests/test_checks.py", + "code_patch": "diff --git a/django/contrib/auth/base_user.py b/django/contrib/auth/base_user.py\nindex 3a4a64e..6e70c32 100644\n--- a/django/contrib/auth/base_user.py\n+++ b/django/contrib/auth/base_user.py\n@@ -10,6 +10,7 @@ from django.contrib.auth.hashers import (\n check_password, is_password_usable, make_password,\n )\n from django.db import models\n+from django.db.models import UniqueConstraint\n from django.utils.crypto import get_random_string, salted_hmac\n from django.utils.translation import gettext_lazy as _\n \n", + "test_patch": "diff --git a/tests/auth_tests/test_username_field_unique_constraint.py b/tests/auth_tests/test_username_field_unique_constraint.py\nnew file mode 100644\nindex 0000000..9feb7be\n--- /dev/null\n+++ b/tests/auth_tests/test_username_field_unique_constraint.py\n@@ -0,0 +1,29 @@\n+from django.contrib.auth.base_user import AbstractBaseUser\n+from django.contrib.auth.checks import check_user_model\n+from django.core import checks\n+from django.db import models\n+from django.test import SimpleTestCase, override_settings, override_system_checks\n+\n+\n+@override_system_checks([check_user_model])\n+class UsernameFieldUniqueConstraintTests(SimpleTestCase):\n+ @override_settings(AUTH_USER_MODEL='auth.CustomUserWithUniqueConstraint')\n+ def test_username_field_unique_constraint(self):\n+ class CustomUserWithUniqueConstraint(AbstractBaseUser):\n+ username = models.CharField(max_length=30)\n+ USERNAME_FIELD = \"username\"\n+\n+ class Meta:\n+ app_label = 'auth'\n+ constraints = [\n+ models.UniqueConstraint(fields=[\"username\"], name=\"user_username_unq\")\n+ ]\n+\n+ errors = checks.run_checks()\n+ self.assertEqual(errors, [\n+ checks.Error(\n+ \"'CustomUserWithUniqueConstraint.username' must be unique because it is named as the 'USERNAME_FIELD'.\",\n+ obj=CustomUserWithUniqueConstraint,\n+ id='auth.E003',\n+ ),\n+ ])\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/auth_tests/test_username_field_unique_constraint_inverted.py b/tests/auth_tests/test_username_field_unique_constraint_inverted.py\nnew file mode 100644\nindex 0000000..d30934e\n--- /dev/null\n+++ b/tests/auth_tests/test_username_field_unique_constraint_inverted.py\n@@ -0,0 +1,29 @@\n+from django.contrib.auth.base_user import AbstractBaseUser\n+from django.contrib.auth.checks import check_user_model\n+from django.core import checks\n+from django.db import models\n+from django.test import SimpleTestCase, override_settings, override_system_checks\n+\n+\n+@override_system_checks([check_user_model])\n+class UsernameFieldUniqueConstraintTests(SimpleTestCase):\n+ @override_settings(AUTH_USER_MODEL='auth.CustomUserWithUniqueConstraint')\n+ def test_username_field_unique_constraint(self):\n+ class CustomUserWithUniqueConstraint(AbstractBaseUser):\n+ username = models.CharField(max_length=30)\n+ USERNAME_FIELD = \"username\"\n+\n+ class Meta:\n+ app_label = 'auth'\n+ constraints = [\n+ models.UniqueConstraint(fields=[\"username\"], name=\"user_username_unq\")\n+ ]\n+\n+ errors = checks.run_checks()\n+ \n+ # The test should now fail if the issue is observed\n+ if errors:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # If no errors are found, the test should pass\n+ self.assertEqual(errors, [])\n\\ No newline at end of file\n", + "num_sent_chars": 1890595, + "num_received_chars": 112752, + "elapsed_time": 689.018700838089, + "lint_repair_count": 3, + "test_generation_attempts": 8, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13658.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13658.json new file mode 100644 index 00000000..c0b6f2f2 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13658.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13658", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py\nindex 1ba093e..e411e86 100644\n--- a/django/core/management/__init__.py\n+++ b/django/core/management/__init__.py\n@@ -344,7 +344,7 @@ class ManagementUtility:\n # Preprocess options to extract --settings and --pythonpath.\n # These options could affect the commands that are available, so they\n # must be processed early.\n- parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False)\n+ parser = CommandParser(prog=self.prog_name, usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False)\n parser.add_argument('--settings')\n parser.add_argument('--pythonpath')\n parser.add_argument('args', nargs='*') # catch-all\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 990562, + "num_received_chars": 41602, + "elapsed_time": 323.13502192497253, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13786.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13786.json new file mode 100644 index 00000000..04c3ee46 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13786.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13786", + "edit_test_file": "tests/migrations/test_optimizer.py", + "code_patch": "diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py\nindex dddf7c6..4ee4c17 100644\n--- a/django/db/migrations/operations/models.py\n+++ b/django/db/migrations/operations/models.py\n@@ -137,11 +137,18 @@ class CreateModel(ModelOperation):\n ),\n ]\n elif isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower:\n+ new_options = self.options.copy()\n+ if not operation.options:\n+ # Clear all ALTER_OPTION_KEYS if AlterModelOptions has empty options\n+ for key in AlterModelOptions.ALTER_OPTION_KEYS:\n+ new_options.pop(key, None)\n+ else:\n+ new_options.update(operation.options)\n return [\n CreateModel(\n self.name,\n fields=self.fields,\n- options={**self.options, **operation.options},\n+ options=new_options,\n bases=self.bases,\n managers=self.managers,\n ),\n", + "test_patch": "diff --git a/tests/migrations/test_squash_migration_model_options.py b/tests/migrations/test_squash_migration_model_options.py\nnew file mode 100644\nindex 0000000..5f322d6\n--- /dev/null\n+++ b/tests/migrations/test_squash_migration_model_options.py\n@@ -0,0 +1,38 @@\n+from django.db import migrations, models\n+from django.db.migrations.optimizer import MigrationOptimizer\n+from django.test import SimpleTestCase\n+\n+\n+class TestSquashMigrationModelOptions(SimpleTestCase):\n+ def test_squash_does_not_unset_model_options(self):\n+ \"\"\"\n+ Test that squashing migrations does not unset model options when\n+ optimizing CreateModel and AlterModelOptions.\n+ \"\"\"\n+ # Initial CreateModel operation with some options\n+ create_model = migrations.CreateModel(\n+ \"TestModel\",\n+ [(\"name\", models.CharField(max_length=255))],\n+ options={\"verbose_name\": \"Test Model\", \"ordering\": [\"name\"]}\n+ )\n+\n+ # AlterModelOptions operation that should clear all options\n+ alter_model_options = migrations.AlterModelOptions(\n+ \"TestModel\",\n+ options={}\n+ )\n+\n+ # Create an optimizer\n+ optimizer = MigrationOptimizer()\n+\n+ # Optimize the operations\n+ optimized_operations = optimizer.optimize([create_model, alter_model_options], \"test_app\")\n+\n+ # The optimized operations should contain only one CreateModel operation\n+ self.assertEqual(len(optimized_operations), 1)\n+ self.assertIsInstance(optimized_operations[0], migrations.CreateModel)\n+\n+ # Check that the options in the resulting CreateModel operation are not cleared\n+ # This assertion will pass if the issue exists (options are not cleared)\n+ self.assertNotEqual(optimized_operations[0].options, {})\n+ self.assertEqual(optimized_operations[0].options, {\"verbose_name\": \"Test Model\", \"ordering\": [\"name\"]})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/migrations/test_squash_migration_model_options_inverted.py b/tests/migrations/test_squash_migration_model_options_inverted.py\nnew file mode 100644\nindex 0000000..18f578e\n--- /dev/null\n+++ b/tests/migrations/test_squash_migration_model_options_inverted.py\n@@ -0,0 +1,44 @@\n+from django.db import migrations, models\n+from django.db.migrations.optimizer import MigrationOptimizer\n+from django.test import SimpleTestCase\n+\n+\n+class TestSquashMigrationModelOptions(SimpleTestCase):\n+ def test_squash_does_unset_model_options(self):\n+ \"\"\"\n+ Test that squashing migrations does unset model options when\n+ optimizing CreateModel and AlterModelOptions.\n+ \"\"\"\n+ # Initial CreateModel operation with some options\n+ create_model = migrations.CreateModel(\n+ \"TestModel\",\n+ [(\"name\", models.CharField(max_length=255))],\n+ options={\"verbose_name\": \"Test Model\", \"ordering\": [\"name\"]}\n+ )\n+\n+ # AlterModelOptions operation that should clear all options\n+ alter_model_options = migrations.AlterModelOptions(\n+ \"TestModel\",\n+ options={}\n+ )\n+\n+ # Create an optimizer\n+ optimizer = MigrationOptimizer()\n+\n+ # Optimize the operations\n+ optimized_operations = optimizer.optimize([create_model, alter_model_options], \"test_app\")\n+\n+ # The optimized operations should contain only one CreateModel operation\n+ self.assertEqual(len(optimized_operations), 1)\n+ self.assertIsInstance(optimized_operations[0], migrations.CreateModel)\n+\n+ # Check that the options in the resulting CreateModel operation are cleared\n+ # This assertion will fail if the issue exists (options are not cleared)\n+ try:\n+ self.assertEqual(optimized_operations[0].options, {})\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Additional check to ensure the original options are not present\n+ self.assertNotIn(\"verbose_name\", optimized_operations[0].options)\n+ self.assertNotIn(\"ordering\", optimized_operations[0].options)\n\\ No newline at end of file\n", + "num_sent_chars": 1001174, + "num_received_chars": 30357, + "elapsed_time": 185.2590982913971, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13809.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13809.json new file mode 100644 index 00000000..fb736aee --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13809.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13809", + "edit_test_file": "tests/user_commands/tests.py", + "code_patch": "diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py\nindex d9fb088..471de19 100644\n--- a/django/core/management/commands/runserver.py\n+++ b/django/core/management/commands/runserver.py\n@@ -47,6 +47,10 @@ class Command(BaseCommand):\n '--nothreading', action='store_false', dest='use_threading',\n help='Tells Django to NOT use threading.',\n )\n+ parser.add_argument(\n+ '--skip-checks', action='store_true',\n+ help='Tells Django to skip system checks.',\n+ )\n parser.add_argument(\n '--noreload', action='store_false', dest='use_reloader',\n help='Tells Django to NOT use the auto-reloader.',\n@@ -80,6 +84,8 @@ class Command(BaseCommand):\n if m is None:\n raise CommandError('\"%s\" is not a valid port number '\n 'or address:port pair.' % options['addrport'])\n+ raise CommandError('\"%s\" is not a valid port number '\n+ 'or address:port pair.' % options['addrport'])\n self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()\n if not self.port.isdigit():\n raise CommandError(\"%r is not a valid port number.\" % self.port)\n@@ -114,10 +120,15 @@ class Command(BaseCommand):\n shutdown_message = options.get('shutdown_message', '')\n quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'\n \n- self.stdout.write(\"Performing system checks...\\n\\n\")\n- self.check(display_num_errors=True)\n- # Need to check migrations here, so can't use the\n- # requires_migrations_check attribute.\n+ skip_checks = options['skip_checks']\n+ if not skip_checks:\n+ self.stdout.write(\"Performing system checks...\\n\\n\")\n+ self.check(display_num_errors=True)\n+ # Need to check migrations here, so can't use the\n+ # requires_migrations_check attribute.\n+ self.check_migrations()\n+ else:\n+ self.stdout.write(\"Skipping system checks...\\n\\n\")\n self.check_migrations()\n now = datetime.now().strftime('%B %d, %Y - %X')\n self.stdout.write(now)\n", + "test_patch": "diff --git a/tests/user_commands/test_runserver_skip_checks.py b/tests/user_commands/test_runserver_skip_checks.py\nnew file mode 100644\nindex 0000000..8d0b3a9\n--- /dev/null\n+++ b/tests/user_commands/test_runserver_skip_checks.py\n@@ -0,0 +1,22 @@\n+from io import StringIO\n+from django.core.management import call_command\n+from django.test import SimpleTestCase\n+from django.test.utils import override_settings\n+\n+@override_settings(\n+ INSTALLED_APPS=[\n+ 'django.contrib.auth',\n+ 'django.contrib.contenttypes',\n+ 'user_commands',\n+ ],\n+)\n+class RunserverSkipChecksTests(SimpleTestCase):\n+ def test_runserver_skip_checks_option_not_available(self):\n+ out = StringIO()\n+ err = StringIO()\n+ with self.assertRaises(TypeError) as cm:\n+ call_command('runserver', skip_checks=True, stdout=out, stderr=err)\n+ \n+ self.assertIn(\"Unknown option(s) for runserver command: skip_checks\", str(cm.exception))\n+ self.assertNotIn(\"System check identified no issues\", out.getvalue())\n+ self.assertNotIn(\"System check identified no issues\", err.getvalue())\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/user_commands/test_runserver_skip_checks_inverted.py b/tests/user_commands/test_runserver_skip_checks_inverted.py\nnew file mode 100644\nindex 0000000..7c1c242\n--- /dev/null\n+++ b/tests/user_commands/test_runserver_skip_checks_inverted.py\n@@ -0,0 +1,28 @@\n+from io import StringIO\n+from django.core.management import call_command\n+from django.test import SimpleTestCase\n+from django.test.utils import override_settings\n+\n+@override_settings(\n+ INSTALLED_APPS=[\n+ 'django.contrib.auth',\n+ 'django.contrib.contenttypes',\n+ 'user_commands',\n+ ],\n+)\n+class RunserverSkipChecksTests(SimpleTestCase):\n+ def test_runserver_skip_checks_option_available(self):\n+ out = StringIO()\n+ err = StringIO()\n+ \n+ try:\n+ call_command('runserver', skip_checks=True, stdout=out, stderr=err)\n+ except TypeError as e:\n+ if \"Unknown option(s) for runserver command: skip_checks\" in str(e):\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ raise # Re-raise if it's a different TypeError\n+ \n+ # If we reach here, the command didn't raise an exception\n+ self.assertIn(\"Starting development server\", out.getvalue())\n+ self.assertNotIn(\"System check identified no issues\", out.getvalue())\n+ self.assertNotIn(\"System check identified no issues\", err.getvalue())\n\\ No newline at end of file\n", + "num_sent_chars": 1966775, + "num_received_chars": 131088, + "elapsed_time": 1987.2905762195587, + "lint_repair_count": 6, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13821.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13821.json new file mode 100644 index 00000000..af6ab7de --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13821.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13821", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/gis/db/models/functions.py b/django/contrib/gis/db/models/functions.py\nindex 1f2d372..e122bbb 100644\n--- a/django/contrib/gis/db/models/functions.py\n+++ b/django/contrib/gis/db/models/functions.py\n@@ -97,8 +97,9 @@ class GeomOutputGeoFunc(GeoFunc):\n \n class SQLiteDecimalToFloatMixin:\n \"\"\"\n- By default, Decimal values are converted to str by the SQLite backend, which\n- is not acceptable by the GIS functions expecting numeric values.\n+ Convert Decimal values to float for SQLite GIS functions.\n+ \n+ Note: This mixin assumes SQLite version 3.9.0 or newer.\n \"\"\"\n def as_sqlite(self, compiler, connection, **extra_context):\n copy = self.copy()\n@@ -138,8 +139,7 @@ class Area(OracleToleranceMixin, GeoFunc):\n \n def as_sqlite(self, compiler, connection, **extra_context):\n if self.geo_field.geodetic(connection):\n- extra_context['template'] = '%(function)s(%(expressions)s, %(spheroid)d)'\n- extra_context['spheroid'] = True\n+ extra_context['template'] = '%(function)s(%(expressions)s, 1)'\n return self.as_sql(compiler, connection, **extra_context)\n \n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1216827, + "num_received_chars": 61640, + "elapsed_time": 416.0783863067627, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13933.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13933.json new file mode 100644 index 00000000..063f8a6b --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-13933.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-13933", + "edit_test_file": "tests/model_forms/test_modelchoicefield.py", + "code_patch": "diff --git a/django/forms/models.py b/django/forms/models.py\nindex 422bc5d..bcf5915 100644\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -1188,7 +1188,7 @@ class ModelChoiceField(ChoiceField):\n # This class is a subclass of ChoiceField for purity, but it doesn't\n # actually use any of ChoiceField's implementation.\n default_error_messages = {\n- 'invalid_choice': _('Select a valid choice. That choice is not one of'\n+ 'invalid_choice': _('Select a valid choice. %(value)s is not one of'\n ' the available choices.'),\n }\n iterator = ModelChoiceIterator\n@@ -1284,7 +1284,7 @@ class ModelChoiceField(ChoiceField):\n value = getattr(value, key)\n value = self.queryset.get(**{key: value})\n except (ValueError, TypeError, self.queryset.model.DoesNotExist):\n- raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')\n+ raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice', params={'value': value})\n return value\n \n def validate(self, value):\n", + "test_patch": "diff --git a/tests/model_forms/test_modelchoicefield_invalid_choice.py b/tests/model_forms/test_modelchoicefield_invalid_choice.py\nnew file mode 100644\nindex 0000000..bc56314\n--- /dev/null\n+++ b/tests/model_forms/test_modelchoicefield_invalid_choice.py\n@@ -0,0 +1,36 @@\n+from django import forms\n+from django.core.exceptions import ValidationError\n+from django.test import TestCase\n+\n+from .models import Category\n+\n+\n+class ModelChoiceFieldInvalidChoiceTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment')\n+ cls.c2 = Category.objects.create(name='A test', slug='test', url='test')\n+\n+ def test_modelchoicefield_invalid_choice_error_message(self):\n+ f = forms.ModelChoiceField(Category.objects.all())\n+ \n+ invalid_choice = 999 # An ID that doesn't exist\n+ \n+ with self.assertRaises(ValidationError) as cm:\n+ f.clean(invalid_choice)\n+ \n+ error_message = str(cm.exception)\n+ self.assertNotIn(str(invalid_choice), error_message)\n+ self.assertEqual(error_message, \"['Select a valid choice. That choice is not one of the available choices.']\")\n+\n+ def test_modelmultiplechoicefield_invalid_choice_error_message(self):\n+ f = forms.ModelMultipleChoiceField(Category.objects.all())\n+ \n+ invalid_choice = 999 # An ID that doesn't exist\n+ \n+ with self.assertRaises(ValidationError) as cm:\n+ f.clean([self.c1.pk, invalid_choice])\n+ \n+ error_message = str(cm.exception)\n+ self.assertIn(str(invalid_choice), error_message)\n+ self.assertEqual(error_message, f\"['Select a valid choice. {invalid_choice} is not one of the available choices.']\")\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_forms/test_modelchoicefield_invalid_choice_inverted.py b/tests/model_forms/test_modelchoicefield_invalid_choice_inverted.py\nnew file mode 100644\nindex 0000000..8942c6f\n--- /dev/null\n+++ b/tests/model_forms/test_modelchoicefield_invalid_choice_inverted.py\n@@ -0,0 +1,42 @@\n+from django import forms\n+from django.core.exceptions import ValidationError\n+from django.test import TestCase\n+\n+from .models import Category\n+\n+\n+class ModelChoiceFieldInvalidChoiceTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment')\n+ cls.c2 = Category.objects.create(name='A test', slug='test', url='test')\n+\n+ def test_modelchoicefield_invalid_choice_error_message(self):\n+ f = forms.ModelChoiceField(Category.objects.all())\n+ \n+ invalid_choice = 999 # An ID that doesn't exist\n+ \n+ with self.assertRaises(ValidationError) as cm:\n+ f.clean(invalid_choice)\n+ \n+ error_message = str(cm.exception)\n+ \n+ # This test should now fail when the bug is present\n+ if str(invalid_choice) not in error_message:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ expected_message = f\"Select a valid choice. {invalid_choice} is not one of the available choices.\"\n+ self.assertEqual(error_message, f\"['{expected_message}']\")\n+\n+ def test_modelmultiplechoicefield_invalid_choice_error_message(self):\n+ f = forms.ModelMultipleChoiceField(Category.objects.all())\n+ \n+ invalid_choice = 999 # An ID that doesn't exist\n+ \n+ with self.assertRaises(ValidationError) as cm:\n+ f.clean([self.c1.pk, invalid_choice])\n+ \n+ error_message = str(cm.exception)\n+ self.assertIn(str(invalid_choice), error_message)\n+ expected_message = f\"Select a valid choice. {invalid_choice} is not one of the available choices.\"\n+ self.assertEqual(error_message, f\"['{expected_message}']\")\n\\ No newline at end of file\n", + "num_sent_chars": 1336786, + "num_received_chars": 79088, + "elapsed_time": 445.31049370765686, + "lint_repair_count": 6, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14011.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14011.json new file mode 100644 index 00000000..e7a9fab7 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14011.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14011", + "edit_test_file": "tests/servers/tests.py", + "code_patch": "diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py\nindex 14dab51..f6d181f 100644\n--- a/django/core/servers/basehttp.py\n+++ b/django/core/servers/basehttp.py\n@@ -77,10 +77,39 @@ class WSGIServer(simple_server.WSGIServer):\n super().handle_error(request, client_address)\n \n \n+import threading\n+from django.db import connections\n+\n class ThreadedWSGIServer(socketserver.ThreadingMixIn, WSGIServer):\n \"\"\"A threaded version of the WSGIServer\"\"\"\n daemon_threads = True\n \n+ def __init__(self, *args, **kwargs):\n+ super().__init__(*args, **kwargs)\n+ self.connections = threading.local()\n+\n+ def process_request_thread(self, request, client_address):\n+ try:\n+ self.finish_request(request, client_address)\n+ except Exception:\n+ self.handle_error(request, client_address)\n+ finally:\n+ self.shutdown_request(request)\n+ self.close_database_connections()\n+\n+ def close_database_connections(self):\n+ for alias in connections:\n+ try:\n+ connections[alias].close()\n+ except Exception as e:\n+ import logging\n+ logger = logging.getLogger('django.server')\n+ logger.exception(f\"Error closing database connection {alias}: {e}\")\n+\n+ def server_close(self):\n+ super().server_close()\n+ self.close_database_connections()\n+\n \n class ServerHandler(simple_server.ServerHandler):\n http_version = '1.1'\n", + "test_patch": "diff --git a/tests/servers/test_database_connection_closure.py b/tests/servers/test_database_connection_closure.py\nnew file mode 100644\nindex 0000000..76dde28\n--- /dev/null\n+++ b/tests/servers/test_database_connection_closure.py\n@@ -0,0 +1,42 @@\n+import threading\n+from django.test import LiveServerTestCase\n+from django.db import connections\n+from django.test.utils import override_settings\n+from django.core.servers.basehttp import WSGIServer\n+from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler\n+\n+class NonThreadedLiveServerThread(LiveServerThread):\n+ def _create_server(self):\n+ return WSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)\n+\n+@override_settings(ROOT_URLCONF='servers.urls')\n+class DatabaseConnectionClosureTest(LiveServerTestCase):\n+ server_thread_class = NonThreadedLiveServerThread\n+\n+ available_apps = [\n+ 'servers',\n+ 'django.contrib.auth',\n+ 'django.contrib.contenttypes',\n+ 'django.contrib.sessions',\n+ ]\n+\n+ def test_database_connections_not_closed(self):\n+ def make_request():\n+ self.client.get('/')\n+\n+ # Create multiple threads to simulate concurrent requests\n+ threads = []\n+ for _ in range(10):\n+ thread = threading.Thread(target=make_request)\n+ thread.start()\n+ threads.append(thread)\n+\n+ # Wait for all threads to complete\n+ for thread in threads:\n+ thread.join()\n+\n+ # Check if there are any open connections\n+ open_connections = sum(1 for conn in connections.all() if conn.connection is not None)\n+ \n+ # The test passes if there are open connections, which indicates the issue\n+ self.assertGreater(open_connections, 0, \"No open database connections found, but some were expected\")\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/servers/test_database_connection_closure_inverted.py b/tests/servers/test_database_connection_closure_inverted.py\nnew file mode 100644\nindex 0000000..000e7e7\n--- /dev/null\n+++ b/tests/servers/test_database_connection_closure_inverted.py\n@@ -0,0 +1,45 @@\n+import threading\n+from django.test import LiveServerTestCase\n+from django.db import connections\n+from django.test.utils import override_settings\n+from django.core.servers.basehttp import WSGIServer\n+from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler\n+\n+class NonThreadedLiveServerThread(LiveServerThread):\n+ def _create_server(self):\n+ return WSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)\n+\n+@override_settings(ROOT_URLCONF='servers.urls')\n+class DatabaseConnectionClosureTest(LiveServerTestCase):\n+ server_thread_class = NonThreadedLiveServerThread\n+\n+ available_apps = [\n+ 'servers',\n+ 'django.contrib.auth',\n+ 'django.contrib.contenttypes',\n+ 'django.contrib.sessions',\n+ ]\n+\n+ def test_database_connections_closed(self):\n+ def make_request():\n+ self.client.get('/')\n+\n+ # Create multiple threads to simulate concurrent requests\n+ threads = []\n+ for _ in range(10):\n+ thread = threading.Thread(target=make_request)\n+ thread.start()\n+ threads.append(thread)\n+\n+ # Wait for all threads to complete\n+ for thread in threads:\n+ thread.join()\n+\n+ # Check if there are any open connections\n+ open_connections = sum(1 for conn in connections.all() if conn.connection is not None)\n+ \n+ # The test should now fail if there are open connections\n+ if open_connections > 0:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ self.assertEqual(open_connections, 0, \"Expected all database connections to be closed, but found open connections\")\n\\ No newline at end of file\n", + "num_sent_chars": 2299301, + "num_received_chars": 158288, + "elapsed_time": 803.7886798381805, + "lint_repair_count": 6, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14053.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14053.json new file mode 100644 index 00000000..bd4dc16e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14053.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14053", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/staticfiles/management/commands/collectstatic.py b/django/contrib/staticfiles/management/commands/collectstatic.py\nindex f7e069b..813f437 100644\n--- a/django/contrib/staticfiles/management/commands/collectstatic.py\n+++ b/django/contrib/staticfiles/management/commands/collectstatic.py\n@@ -101,6 +101,7 @@ class Command(BaseCommand):\n handler = self.copy_file\n \n found_files = {}\n+ processed_files = set()\n for finder in get_finders():\n for path, storage in finder.list(self.ignore_patterns):\n # Prefix the relative path if the source storage contains it\n@@ -108,6 +109,10 @@ class Command(BaseCommand):\n prefixed_path = os.path.join(storage.prefix, path)\n else:\n prefixed_path = path\n+ if getattr(storage, 'prefix', None):\n+ prefixed_path = os.path.join(storage.prefix, path)\n+ else:\n+ prefixed_path = path\n \n if prefixed_path not in found_files:\n found_files[prefixed_path] = (storage, path)\n@@ -133,16 +138,22 @@ class Command(BaseCommand):\n self.stderr.write()\n raise processed\n if processed:\n- self.log(\"Post-processed '%s' as '%s'\" %\n- (original_path, processed_path), level=2)\n- self.post_processed_files.append(original_path)\n+ if original_path not in processed_files:\n+ self.log(\"Post-processed '%s' as '%s'\" %\n+ (original_path, processed_path), level=2)\n+ self.post_processed_files.append(original_path)\n+ processed_files.add(original_path)\n+ else:\n+ self.log(\"Skipped duplicate post-processing for '%s'\" % original_path, level=2)\n else:\n- self.log(\"Skipped post-processing '%s'\" % original_path)\n+ if original_path not in processed_files:\n+ self.log(\"Skipped post-processing '%s'\" % original_path)\n+ processed_files.add(original_path)\n \n return {\n 'modified': self.copied_files + self.symlinked_files,\n 'unmodified': self.unmodified_files,\n- 'post_processed': self.post_processed_files,\n+ 'post_processed': list(set(self.post_processed_files)), # Remove duplicates\n }\n \n def handle(self, **options):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2147106, + "num_received_chars": 146311, + "elapsed_time": 784.6462717056274, + "lint_repair_count": 8, + "test_generation_attempts": 9, + "code_generation_attempts": 6, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14140.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14140.json new file mode 100644 index 00000000..bba7f1d6 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14140.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14140", + "edit_test_file": "tests/auth_tests/test_basic.py", + "code_patch": "diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py\nindex ae0f886..11caf3d 100644\n--- a/django/db/models/query_utils.py\n+++ b/django/db/models/query_utils.py\n@@ -85,13 +85,16 @@ class Q(tree.Node):\n if path.startswith('django.db.models.query_utils'):\n path = path.replace('django.db.models.query_utils', 'django.db.models')\n args, kwargs = (), {}\n- if len(self.children) == 1 and not isinstance(self.children[0], Q):\n- child = self.children[0]\n- kwargs = {child[0]: child[1]}\n- else:\n- args = tuple(self.children)\n- if self.connector != self.default:\n- kwargs = {'_connector': self.connector}\n+ for child in self.children:\n+ if isinstance(child, Q):\n+ args += (child,)\n+ elif isinstance(child, (list, tuple)) and len(child) == 2:\n+ key, value = child\n+ kwargs[key] = value\n+ else:\n+ args += (child,)\n+ if self.connector != self.default:\n+ kwargs['_connector'] = self.connector\n if self.negated:\n kwargs['_negated'] = True\n return path, args, kwargs\n", + "test_patch": "diff --git a/tests/auth_tests/test_q_object_deconstruction.py b/tests/auth_tests/test_q_object_deconstruction.py\nnew file mode 100644\nindex 0000000..69b60fd\n--- /dev/null\n+++ b/tests/auth_tests/test_q_object_deconstruction.py\n@@ -0,0 +1,13 @@\n+from django.contrib.auth import get_user_model\n+from django.db.models import Exists, Q\n+from django.test import TestCase\n+\n+\n+class QObjectDeconstructionTestCase(TestCase):\n+ def test_q_object_with_exists_deconstruction(self):\n+ User = get_user_model()\n+ exists_query = Exists(User.objects.filter(username='jim'))\n+ q_object = Q(exists_query)\n+\n+ with self.assertRaises(TypeError):\n+ q_object.deconstruct()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/auth_tests/test_q_object_deconstruction_inverted.py b/tests/auth_tests/test_q_object_deconstruction_inverted.py\nnew file mode 100644\nindex 0000000..5d4f6d5\n--- /dev/null\n+++ b/tests/auth_tests/test_q_object_deconstruction_inverted.py\n@@ -0,0 +1,17 @@\n+from django.contrib.auth import get_user_model\n+from django.db.models import Exists, Q\n+from django.test import TestCase\n+\n+\n+class QObjectDeconstructionTestCase(TestCase):\n+ def test_q_object_with_exists_deconstruction(self):\n+ User = get_user_model()\n+ exists_query = Exists(User.objects.filter(username='jim'))\n+ q_object = Q(exists_query)\n+\n+ try:\n+ q_object.deconstruct()\n+ except TypeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ except Exception as e:\n+ self.fail(f\"Unexpected exception raised: {e}\")\n\\ No newline at end of file\n", + "num_sent_chars": 647584, + "num_received_chars": 29648, + "elapsed_time": 218.08636045455933, + "lint_repair_count": 0, + "test_generation_attempts": 5, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14238.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14238.json new file mode 100644 index 00000000..5d304709 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14238.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14238", + "edit_test_file": "tests/check_framework/test_model_checks.py", + "code_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 0f53d9c..772612e 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -2524,7 +2524,11 @@ class AutoFieldMeta(type):\n return isinstance(instance, self._subclasses) or super().__instancecheck__(instance)\n \n def __subclasscheck__(self, subclass):\n- return subclass in self._subclasses or super().__subclasscheck__(subclass)\n+ return (\n+ subclass in self._subclasses or\n+ issubclass(subclass, self._subclasses) or\n+ super().__subclasscheck__(subclass)\n+ )\n \n \n class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):\n", + "test_patch": "diff --git a/tests/check_framework/test_default_auto_field_subclass.py b/tests/check_framework/test_default_auto_field_subclass.py\nnew file mode 100644\nindex 0000000..9f521a3\n--- /dev/null\n+++ b/tests/check_framework/test_default_auto_field_subclass.py\n@@ -0,0 +1,18 @@\n+from django.core.exceptions import ImproperlyConfigured\n+from django.db import models\n+from django.test import SimpleTestCase, override_settings\n+from django.test.utils import isolate_apps\n+\n+\n+class MyBigAutoField(models.BigAutoField):\n+ pass\n+\n+\n+@isolate_apps('check_framework')\n+class DefaultAutoFieldSubclassTests(SimpleTestCase):\n+ @override_settings(DEFAULT_AUTO_FIELD='check_framework.test_default_auto_field_subclass.MyBigAutoField')\n+ def test_default_auto_field_subclass_check(self):\n+ msg = \"Primary key 'check_framework.test_default_auto_field_subclass.MyBigAutoField' referred by DEFAULT_AUTO_FIELD must subclass AutoField.\"\n+ with self.assertRaisesMessage(ValueError, msg):\n+ class MyModel(models.Model):\n+ pass\n", + "test_inverted_patch": null, + "num_sent_chars": 2188597, + "num_received_chars": 45621, + "elapsed_time": 361.50249886512756, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14349.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14349.json new file mode 100644 index 00000000..1f893515 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14349.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14349", + "edit_test_file": "tests/validation/test_validators.py", + "code_patch": "diff --git a/django/forms/fields.py b/django/forms/fields.py\nindex daa65d6..d3b337f 100644\n--- a/django/forms/fields.py\n+++ b/django/forms/fields.py\n@@ -661,13 +661,26 @@ class URLField(CharField):\n widget = URLInput\n default_error_messages = {\n 'invalid': _('Enter a valid URL.'),\n+ 'invalid_characters': _('URL cannot contain newline or tab characters.'),\n }\n default_validators = [validators.URLValidator()]\n \n def __init__(self, **kwargs):\n super().__init__(strip=True, **kwargs)\n \n+ def _check_url_for_invalid_characters(self, value):\n+ \"\"\"\n+ Check if the URL contains newline or tab characters.\n+ \"\"\"\n+ if '\\n' in value or '\\r' in value or '\\t' in value:\n+ raise ValidationError(\n+ self.error_messages['invalid_characters'],\n+ code='invalid_characters'\n+ )\n+\n def to_python(self, value):\n+ value = super().to_python(value)\n+ self._check_url_for_invalid_characters(value)\n \n def split_url(url):\n \"\"\"\n", + "test_patch": "diff --git a/tests/validation/test_url_validator_newline_handling.py b/tests/validation/test_url_validator_newline_handling.py\nnew file mode 100644\nindex 0000000..ef8974c\n--- /dev/null\n+++ b/tests/validation/test_url_validator_newline_handling.py\n@@ -0,0 +1,29 @@\n+from django.core.exceptions import ValidationError\n+from django.core.validators import URLValidator\n+from django.test import SimpleTestCase\n+\n+\n+class TestURLValidatorNewlineHandling(SimpleTestCase):\n+ def test_url_validator_newline_handling(self):\n+ validator = URLValidator()\n+ \n+ # URLs with newline characters that should raise ValidationError\n+ urls_with_newlines = [\n+ 'http://www.djangoproject.com/\\n',\n+ 'http://[::ffff:192.9.5.5]\\n',\n+ ]\n+\n+ for url in urls_with_newlines:\n+ with self.subTest(url=url):\n+ # The test passes if ValidationError is not raised,\n+ # which reproduces the issue described\n+ validator(url)\n+\n+ # To ensure the validator still works for valid URLs\n+ valid_url = 'https://www.example.com'\n+ validator(valid_url)\n+\n+ # To ensure the validator still rejects clearly invalid URLs\n+ invalid_url = 'not a url'\n+ with self.assertRaises(ValidationError):\n+ validator(invalid_url)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/validation/test_url_validator_newline_handling_inverted.py b/tests/validation/test_url_validator_newline_handling_inverted.py\nnew file mode 100644\nindex 0000000..d3d054f\n--- /dev/null\n+++ b/tests/validation/test_url_validator_newline_handling_inverted.py\n@@ -0,0 +1,32 @@\n+from django.core.exceptions import ValidationError\n+from django.core.validators import URLValidator\n+from django.test import SimpleTestCase\n+\n+\n+class TestURLValidatorNewlineHandling(SimpleTestCase):\n+ def test_url_validator_newline_handling(self):\n+ validator = URLValidator()\n+ \n+ # URLs with newline characters that should raise ValidationError\n+ urls_with_newlines = [\n+ 'http://www.djangoproject.com/\\n',\n+ 'http://[::ffff:192.9.5.5]\\n',\n+ ]\n+\n+ for url in urls_with_newlines:\n+ with self.subTest(url=url):\n+ try:\n+ validator(url)\n+ raise AssertionError(\"__BUG__HERE__\")\n+ except ValidationError:\n+ # This is the expected behavior\n+ pass\n+\n+ # To ensure the validator still works for valid URLs\n+ valid_url = 'https://www.example.com'\n+ validator(valid_url)\n+\n+ # To ensure the validator still rejects clearly invalid URLs\n+ invalid_url = 'not a url'\n+ with self.assertRaises(ValidationError):\n+ validator(invalid_url)\n\\ No newline at end of file\n", + "num_sent_chars": 1163027, + "num_received_chars": 51466, + "elapsed_time": 367.0181419849396, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14376.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14376.json new file mode 100644 index 00000000..5519d607 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14376.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14376", + "edit_test_file": "tests/backends/mysql/test_creation.py", + "code_patch": "diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py\nindex 2c62182..94a2495 100644\n--- a/django/db/backends/mysql/base.py\n+++ b/django/db/backends/mysql/base.py\n@@ -192,27 +192,27 @@ class DatabaseWrapper(BaseDatabaseWrapper):\n validation_class = DatabaseValidation\n \n def get_connection_params(self):\n- kwargs = {\n- 'conv': django_conversions,\n- 'charset': 'utf8',\n- }\n- settings_dict = self.settings_dict\n- if settings_dict['USER']:\n- kwargs['user'] = settings_dict['USER']\n- if settings_dict['NAME']:\n- kwargs['db'] = settings_dict['NAME']\n- if settings_dict['PASSWORD']:\n- kwargs['passwd'] = settings_dict['PASSWORD']\n- if settings_dict['HOST'].startswith('/'):\n- kwargs['unix_socket'] = settings_dict['HOST']\n- elif settings_dict['HOST']:\n- kwargs['host'] = settings_dict['HOST']\n- if settings_dict['PORT']:\n- kwargs['port'] = int(settings_dict['PORT'])\n- # We need the number of potentially affected rows after an\n- # \"UPDATE\", not the number of changed rows.\n- kwargs['client_flag'] = CLIENT.FOUND_ROWS\n- # Validate the transaction isolation level, if specified.\n+ kwargs = {\n+ 'conv': django_conversions,\n+ 'charset': 'utf8',\n+ }\n+ settings_dict = self.settings_dict\n+ if settings_dict['USER']:\n+ kwargs['user'] = settings_dict['USER']\n+ if settings_dict['NAME']:\n+ kwargs['database'] = settings_dict['NAME']\n+ if settings_dict['PASSWORD']:\n+ kwargs['password'] = settings_dict['PASSWORD']\n+ if settings_dict['HOST'].startswith('/'):\n+ kwargs['unix_socket'] = settings_dict['HOST']\n+ elif settings_dict['HOST']:\n+ kwargs['host'] = settings_dict['HOST']\n+ if settings_dict['PORT']:\n+ kwargs['port'] = int(settings_dict['PORT'])\n+ # We need the number of potentially affected rows after an\n+ # \"UPDATE\", not the number of changed rows.\n+ kwargs['client_flag'] = CLIENT.FOUND_ROWS\n+ # Validate the transaction isolation level, if specified.\n options = settings_dict['OPTIONS'].copy()\n isolation_level = options.pop('isolation_level', 'read committed')\n if isolation_level:\n", + "test_patch": "diff --git a/tests/backends/mysql/test_mysql_connection_kwargs.py b/tests/backends/mysql/test_mysql_connection_kwargs.py\nnew file mode 100644\nindex 0000000..4ca3135\n--- /dev/null\n+++ b/tests/backends/mysql/test_mysql_connection_kwargs.py\n@@ -0,0 +1,23 @@\n+import unittest\n+from unittest import mock\n+\n+from django.db import connection\n+from django.test import TestCase\n+\n+\n+class MySQLConnectionKwargsTests(TestCase):\n+ @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL tests')\n+ def test_deprecated_connection_kwargs(self):\n+ with mock.patch('django.db.backends.mysql.base.Database.connect') as mock_connect:\n+ connection.ensure_connection()\n+ \n+ # Check if the deprecated kwargs are being used\n+ call_kwargs = mock_connect.call_args[1]\n+ self.assertIn('db', call_kwargs)\n+ self.assertIn('passwd', call_kwargs)\n+ \n+ # Check if the new kwargs are not being used\n+ self.assertNotIn('database', call_kwargs)\n+ self.assertNotIn('password', call_kwargs)\n+\n+ # The test passes if the deprecated kwargs are used, which reproduces the issue\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2212722, + "num_received_chars": 122715, + "elapsed_time": 727.0813510417938, + "lint_repair_count": 9, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14493.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14493.json new file mode 100644 index 00000000..6344cc82 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14493.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14493", + "edit_test_file": "tests/staticfiles_tests/test_management.py", + "code_patch": "diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py\nindex f957a66..1442d1f 100644\n--- a/django/contrib/staticfiles/storage.py\n+++ b/django/contrib/staticfiles/storage.py\n@@ -242,6 +242,15 @@ class HashedFilesMixin:\n # where to store the new paths\n hashed_files = {}\n \n+ # Initialize substitutions variable\n+ substitutions = False\n+\n+ # If max_post_process_passes is 0, skip post-processing\n+ if self.max_post_process_passes == 0:\n+ for name, hashed_name in hashed_files.items():\n+ yield name, hashed_name, False\n+ return\n+\n # build a list of adjustable files\n adjustable_paths = [\n path for path in paths\n@@ -261,7 +270,7 @@ class HashedFilesMixin:\n \n paths = {path: paths[path] for path in adjustable_paths}\n \n- for i in range(self.max_post_process_passes):\n+ for i in range(max(1, self.max_post_process_passes)):\n substitutions = False\n for name, hashed_name, processed, subst in self._post_process(paths, adjustable_paths, hashed_files):\n # Overwrite since hashed_name may be newer.\n@@ -271,7 +280,7 @@ class HashedFilesMixin:\n if not substitutions:\n break\n \n- if substitutions:\n+ if substitutions and self.max_post_process_passes > 0:\n yield 'All', None, RuntimeError('Max post-process passes exceeded.')\n \n # Store the processed paths\n", + "test_patch": "diff --git a/tests/staticfiles_tests/test_manifest_static_files_storage_zero_passes.py b/tests/staticfiles_tests/test_manifest_static_files_storage_zero_passes.py\nnew file mode 100644\nindex 0000000..d190955\n--- /dev/null\n+++ b/tests/staticfiles_tests/test_manifest_static_files_storage_zero_passes.py\n@@ -0,0 +1,28 @@\n+import os\n+from unittest import mock\n+\n+from django.contrib.staticfiles.storage import ManifestStaticFilesStorage\n+from django.core.files.storage import FileSystemStorage\n+from django.test import SimpleTestCase, override_settings\n+\n+class CustomManifestStaticFilesStorage(ManifestStaticFilesStorage):\n+ max_post_process_passes = 0\n+\n+class TestManifestStaticFilesStorageZeroPasses(SimpleTestCase):\n+ @override_settings(STATIC_ROOT='/tmp/static')\n+ def test_post_process_with_zero_passes(self):\n+ storage = CustomManifestStaticFilesStorage()\n+ \n+ # Mock the _post_process method to return an empty list\n+ with mock.patch.object(storage, '_post_process', return_value=[]):\n+ with self.assertRaises(UnboundLocalError) as cm:\n+ list(storage.post_process([], dry_run=False))\n+ \n+ self.assertEqual(\n+ str(cm.exception),\n+ \"local variable 'substitutions' referenced before assignment\"\n+ )\n+\n+ def test_max_post_process_passes_zero(self):\n+ storage = CustomManifestStaticFilesStorage()\n+ self.assertEqual(storage.max_post_process_passes, 0)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/staticfiles_tests/test_manifest_static_files_storage_zero_passes_inverted.py b/tests/staticfiles_tests/test_manifest_static_files_storage_zero_passes_inverted.py\nnew file mode 100644\nindex 0000000..c98e9ac\n--- /dev/null\n+++ b/tests/staticfiles_tests/test_manifest_static_files_storage_zero_passes_inverted.py\n@@ -0,0 +1,28 @@\n+import os\n+from unittest import mock\n+\n+from django.contrib.staticfiles.storage import ManifestStaticFilesStorage\n+from django.core.files.storage import FileSystemStorage\n+from django.test import SimpleTestCase, override_settings\n+\n+class CustomManifestStaticFilesStorage(ManifestStaticFilesStorage):\n+ max_post_process_passes = 0\n+\n+class TestManifestStaticFilesStorageZeroPasses(SimpleTestCase):\n+ @override_settings(STATIC_ROOT='/tmp/static')\n+ def test_post_process_with_zero_passes(self):\n+ storage = CustomManifestStaticFilesStorage()\n+ \n+ # Mock the _post_process method to return an empty list\n+ with mock.patch.object(storage, '_post_process', return_value=[]):\n+ try:\n+ list(storage.post_process([], dry_run=False))\n+ except UnboundLocalError as e:\n+ if str(e) == \"local variable 'substitutions' referenced before assignment\":\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ else:\n+ self.fail(\"Expected UnboundLocalError was not raised\")\n+\n+ def test_max_post_process_passes_zero(self):\n+ storage = CustomManifestStaticFilesStorage()\n+ self.assertEqual(storage.max_post_process_passes, 0)\n\\ No newline at end of file\n", + "num_sent_chars": 1944938, + "num_received_chars": 129038, + "elapsed_time": 708.5595548152924, + "lint_repair_count": 6, + "test_generation_attempts": 6, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14608.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14608.json new file mode 100644 index 00000000..221017ac --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14608.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14608", + "edit_test_file": "tests/forms_tests/tests/test_error_messages.py", + "code_patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\nindex a89c355..bbb08a3 100644\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -295,7 +295,7 @@ class BaseFormSet:\n \"\"\"\n if self._non_form_errors is None:\n self.full_clean()\n- return self._non_form_errors\n+ return self.error_class(self._non_form_errors, error_class='nonform')\n \n @property\n def errors(self):\n", + "test_patch": "diff --git a/tests/forms_tests/tests/test_formset_nonform_errors.py b/tests/forms_tests/tests/test_formset_nonform_errors.py\nnew file mode 100644\nindex 0000000..3f6dc64\n--- /dev/null\n+++ b/tests/forms_tests/tests/test_formset_nonform_errors.py\n@@ -0,0 +1,41 @@\n+from django import forms\n+from django.forms import formset_factory\n+from django.test import SimpleTestCase\n+from django.utils.safestring import mark_safe\n+\n+\n+class ArticleForm(forms.Form):\n+ title = forms.CharField()\n+ pub_date = forms.DateField()\n+\n+\n+class BaseArticleFormSet(forms.BaseFormSet):\n+ def clean(self):\n+ \"\"\"Add a formset-wide error\"\"\"\n+ raise forms.ValidationError(\"This is a formset-wide error\")\n+\n+\n+class TestFormSetNonFormErrors(SimpleTestCase):\n+ def test_nonform_errors_missing_css_class(self):\n+ ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, extra=2)\n+ data = {\n+ 'form-TOTAL_FORMS': '2',\n+ 'form-INITIAL_FORMS': '0',\n+ 'form-MAX_NUM_FORMS': '',\n+ 'form-0-title': 'First Article',\n+ 'form-0-pub_date': '2008-01-01',\n+ 'form-1-title': 'Second Article',\n+ 'form-1-pub_date': '2008-01-02',\n+ }\n+ formset = ArticleFormSet(data)\n+ self.assertFalse(formset.is_valid())\n+ \n+ # Render the non_form_errors\n+ errors_html = str(formset.non_form_errors())\n+ \n+ # Check that the 'nonform' class is missing from the error list\n+ self.assertIn('
    ', errors_html)\n+ self.assertNotIn('
      ', errors_html)\n+ \n+ # Ensure the error message is present\n+ self.assertIn('This is a formset-wide error', errors_html)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/forms_tests/tests/test_formset_nonform_errors_inverted.py b/tests/forms_tests/tests/test_formset_nonform_errors_inverted.py\nnew file mode 100644\nindex 0000000..6abffdb\n--- /dev/null\n+++ b/tests/forms_tests/tests/test_formset_nonform_errors_inverted.py\n@@ -0,0 +1,41 @@\n+from django import forms\n+from django.forms import formset_factory\n+from django.test import SimpleTestCase\n+from django.utils.safestring import mark_safe\n+\n+\n+class ArticleForm(forms.Form):\n+ title = forms.CharField()\n+ pub_date = forms.DateField()\n+\n+\n+class BaseArticleFormSet(forms.BaseFormSet):\n+ def clean(self):\n+ \"\"\"Add a formset-wide error\"\"\"\n+ raise forms.ValidationError(\"This is a formset-wide error\")\n+\n+\n+class TestFormSetNonFormErrors(SimpleTestCase):\n+ def test_nonform_errors_missing_css_class(self):\n+ ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, extra=2)\n+ data = {\n+ 'form-TOTAL_FORMS': '2',\n+ 'form-INITIAL_FORMS': '0',\n+ 'form-MAX_NUM_FORMS': '',\n+ 'form-0-title': 'First Article',\n+ 'form-0-pub_date': '2008-01-01',\n+ 'form-1-title': 'Second Article',\n+ 'form-1-pub_date': '2008-01-02',\n+ }\n+ formset = ArticleFormSet(data)\n+ self.assertFalse(formset.is_valid())\n+ \n+ # Render the non_form_errors\n+ errors_html = str(formset.non_form_errors())\n+ \n+ # Check that the 'nonform' class is present in the error list\n+ if '
        ' not in errors_html:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Ensure the error message is present\n+ self.assertIn('This is a formset-wide error', errors_html)\n\\ No newline at end of file\n", + "num_sent_chars": 1322145, + "num_received_chars": 29251, + "elapsed_time": 248.4075803756714, + "lint_repair_count": 1, + "test_generation_attempts": 7, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14725.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14725.json new file mode 100644 index 00000000..ee7f05f3 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14725.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14725", + "edit_test_file": "tests/model_formsets/tests.py", + "code_patch": "diff --git a/django/forms/models.py b/django/forms/models.py\nindex 7effb20..a62e7c3 100644\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -573,10 +573,13 @@ class BaseModelFormSet(BaseFormSet):\n unique_fields = set()\n \n def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,\n- queryset=None, *, initial=None, **kwargs):\n+ queryset=None, *, initial=None, allow_new_objects=True,\n+ **kwargs):\n self.queryset = queryset\n self.initial_extra = initial\n- super().__init__(**{'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix, **kwargs})\n+ self.allow_new_objects = allow_new_objects\n+ super().__init__(**{'data': data, 'files': files, 'auto_id': auto_id,\n+ 'prefix': prefix, **kwargs})\n \n def initial_form_count(self):\n \"\"\"Return the number of forms that are required in this FormSet.\"\"\"\n@@ -653,6 +656,8 @@ class BaseModelFormSet(BaseFormSet):\n \n def save_new(self, form, commit=True):\n \"\"\"Save and return a new model instance for the given form.\"\"\"\n+ if not self.allow_new_objects:\n+ raise ValueError(\"New object creation is not allowed in edit-only mode.\")\n return form.save(commit=commit)\n \n def save_existing(self, form, instance, commit=True):\n@@ -664,7 +669,15 @@ class BaseModelFormSet(BaseFormSet):\n if commit:\n obj.delete()\n \n+ def _is_new_form(self, form):\n+ \"\"\"Check if the form is for a new object.\"\"\"\n+ return form.instance._state.adding\n+\n def save(self, commit=True):\n+ \"\"\"\n+ Save model instances for every form, adding and changing instances\n+ as necessary, and return the list of instances.\n+ \"\"\"\n \"\"\"\n Save model instances for every form, adding and changing instances\n as necessary, and return the list of instances.\n@@ -813,16 +826,17 @@ class BaseModelFormSet(BaseFormSet):\n \n def save_new_objects(self, commit=True):\n self.new_objects = []\n- for form in self.extra_forms:\n- if not form.has_changed():\n- continue\n- # If someone has marked an add form for deletion, don't save the\n- # object.\n- if self.can_delete and self._should_delete_form(form):\n- continue\n- self.new_objects.append(self.save_new(form, commit=commit))\n- if not commit:\n- self.saved_forms.append(form)\n+ if self.allow_new_objects:\n+ for form in self.extra_forms:\n+ if not form.has_changed():\n+ continue\n+ # If someone has marked an add form for deletion, don't save the\n+ # object.\n+ if self.can_delete and self._should_delete_form(form):\n+ continue\n+ self.new_objects.append(self.save_new(form, commit=commit))\n+ if not commit:\n+ self.saved_forms.append(form)\n return self.new_objects\n \n def add_fields(self, form, index):\n", + "test_patch": "diff --git a/tests/model_formsets/test_model_formset_edit_only.py b/tests/model_formsets/test_model_formset_edit_only.py\nnew file mode 100644\nindex 0000000..9196414\n--- /dev/null\n+++ b/tests/model_formsets/test_model_formset_edit_only.py\n@@ -0,0 +1,37 @@\n+from django.test import TestCase\n+from django.forms import modelformset_factory\n+from .models import Author\n+\n+class TestModelFormsetEditOnly(TestCase):\n+ def test_model_formset_allows_new_object_creation_with_extra_zero(self):\n+ # Create initial data\n+ Author.objects.create(name=\"Existing Author 1\")\n+ Author.objects.create(name=\"Existing Author 2\")\n+\n+ # Create a formset with extra=0, attempting to make it \"edit only\"\n+ AuthorFormSet = modelformset_factory(Author, fields='__all__', extra=0)\n+\n+ # Initial form data with existing objects\n+ data = {\n+ 'form-TOTAL_FORMS': '3', # Note: 3 forms, even though we have extra=0\n+ 'form-INITIAL_FORMS': '2',\n+ 'form-MAX_NUM_FORMS': '',\n+ 'form-0-id': '1',\n+ 'form-0-name': 'Existing Author 1',\n+ 'form-1-id': '2',\n+ 'form-1-name': 'Existing Author 2',\n+ 'form-2-id': '', # New object\n+ 'form-2-name': 'New Author', # This should not be allowed in an \"edit only\" view\n+ }\n+\n+ formset = AuthorFormSet(data)\n+ \n+ # Assert that the formset is valid, which means it allows the new object\n+ self.assertTrue(formset.is_valid())\n+\n+ # Save the formset\n+ formset.save()\n+\n+ # Check that a new author was created, despite our intention for an \"edit only\" view\n+ self.assertEqual(Author.objects.count(), 3)\n+ self.assertTrue(Author.objects.filter(name=\"New Author\").exists())\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_formsets/test_model_formset_edit_only_inverted.py b/tests/model_formsets/test_model_formset_edit_only_inverted.py\nnew file mode 100644\nindex 0000000..57a53f9\n--- /dev/null\n+++ b/tests/model_formsets/test_model_formset_edit_only_inverted.py\n@@ -0,0 +1,50 @@\n+from django.test import TestCase\n+from django.forms import modelformset_factory\n+from .models import Author\n+\n+class TestModelFormsetEditOnly(TestCase):\n+ def test_model_formset_disallows_new_object_creation_with_extra_zero(self):\n+ # Create initial data\n+ Author.objects.create(name=\"Existing Author 1\")\n+ Author.objects.create(name=\"Existing Author 2\")\n+\n+ # Create a formset with extra=0, attempting to make it \"edit only\"\n+ AuthorFormSet = modelformset_factory(Author, fields='__all__', extra=0)\n+\n+ # Initial form data with existing objects and an attempt to create a new one\n+ data = {\n+ 'form-TOTAL_FORMS': '3', # Note: 3 forms, even though we have extra=0\n+ 'form-INITIAL_FORMS': '2',\n+ 'form-MAX_NUM_FORMS': '',\n+ 'form-0-id': '1',\n+ 'form-0-name': 'Existing Author 1',\n+ 'form-1-id': '2',\n+ 'form-1-name': 'Existing Author 2',\n+ 'form-2-id': '', # New object\n+ 'form-2-name': 'New Author', # This should not be allowed in an \"edit only\" view\n+ }\n+\n+ formset = AuthorFormSet(data)\n+ \n+ # Assert that the formset is not valid, which means it disallows the new object\n+ if formset.is_valid():\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Ensure no new author was created\n+ self.assertEqual(Author.objects.count(), 2)\n+ self.assertFalse(Author.objects.filter(name=\"New Author\").exists())\n+\n+ # Check that the formset has an error for the new form\n+ self.assertTrue(formset.errors)\n+ self.assertIn(2, formset.errors) # Index 2 should have an error\n+ self.assertIn('id', formset.errors[2]) # The 'id' field should have an error\n+\n+ # Verify that existing authors can still be edited\n+ data['form-0-name'] = 'Updated Existing Author 1'\n+ formset = AuthorFormSet(data)\n+ \n+ self.assertTrue(formset.is_valid())\n+ formset.save()\n+ \n+ self.assertEqual(Author.objects.get(id=1).name, 'Updated Existing Author 1')\n+ self.assertEqual(Author.objects.count(), 2)\n\\ No newline at end of file\n", + "num_sent_chars": 2011401, + "num_received_chars": 148395, + "elapsed_time": 803.3993098735809, + "lint_repair_count": 8, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14771.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14771.json new file mode 100644 index 00000000..af066233 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14771.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14771", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py\nindex 473fde0..c8d2429 100644\n--- a/django/core/management/commands/runserver.py\n+++ b/django/core/management/commands/runserver.py\n@@ -104,16 +104,25 @@ class Command(BaseCommand):\n \"\"\"Run the server, using the autoreloader if needed.\"\"\"\n use_reloader = options['use_reloader']\n \n+ # Capture -X options from sys.argv\n+ x_options = [arg for arg in sys.argv if arg.startswith('-X')]\n+\n if use_reloader:\n- autoreload.run_with_reloader(self.inner_run, **options)\n+ # Pass x_options to the reloader\n+ autoreload.run_with_reloader(self.inner_run, x_options=x_options, **options)\n else:\n- self.inner_run(None, **options)\n+ self.inner_run(None, x_options=x_options, **options)\n \n def inner_run(self, *args, **options):\n # If an exception was silenced in ManagementUtility.execute in order\n # to be raised in the child process, raise it now.\n autoreload.raise_last_exception()\n \n+ # Apply -X options\n+ x_options = options.pop('x_options', [])\n+ for option in x_options:\n+ sys.argv.insert(1, option)\n+\n threading = options['use_threading']\n # 'shutdown_message' is a stealth option.\n shutdown_message = options.get('shutdown_message', '')\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1547726, + "num_received_chars": 99353, + "elapsed_time": 716.2703323364258, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14855.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14855.json new file mode 100644 index 00000000..f352304f --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-14855.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-14855", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py\nindex dd154f7..0dd8719 100644\n--- a/django/contrib/admin/helpers.py\n+++ b/django/contrib/admin/helpers.py\n@@ -209,7 +209,12 @@ class AdminReadonlyField:\n remote_field.model._meta.model_name,\n )\n try:\n- url = reverse(url_name, args=[quote(remote_obj.pk)])\n+ current_app = (\n+ self.model_admin.admin_site.name\n+ if hasattr(self, 'model_admin') and hasattr(self.model_admin, 'admin_site')\n+ else None\n+ )\n+ url = reverse(url_name, args=[quote(remote_obj.pk)], current_app=current_app)\n return format_html('{}', url, remote_obj)\n except NoReverseMatch:\n return str(remote_obj)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 3032915, + "num_received_chars": 62950, + "elapsed_time": 527.4482550621033, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15022.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15022.json new file mode 100644 index 00000000..34c83322 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15022.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15022", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py\nindex 43583c8..7e6d4ca 100644\n--- a/django/contrib/admin/views/main.py\n+++ b/django/contrib/admin/views/main.py\n@@ -465,11 +465,35 @@ class ChangeList:\n if new_qs is not None:\n qs = new_qs\n \n+ from django.db.models import Q\n+ from django.core.exceptions import FieldDoesNotExist\n+\n try:\n # Finally, we apply the remaining lookup parameters from the query\n # string (i.e. those that haven't already been processed by the\n # filters).\n qs = qs.filter(**remaining_lookup_params)\n+\n+ # Optimize search query construction\n+ if self.search_fields and self.query:\n+ search_terms = self.query.split()\n+ if len(search_terms) > 10: # Limit the number of search terms\n+ search_terms = search_terms[:10]\n+\n+ search_query = Q()\n+ for search_term in search_terms:\n+ term_query = Q()\n+ for field_name in self.search_fields:\n+ try:\n+ field = self.model._meta.get_field(field_name)\n+ lookup = '%s__icontains' % field_name\n+ term_query |= Q(**{lookup: search_term})\n+ except FieldDoesNotExist:\n+ # Ignore non-existent fields\n+ pass\n+ search_query &= term_query\n+ qs = qs.filter(search_query).distinct()\n+\n except (SuspiciousOperation, ImproperlyConfigured):\n # Allow certain types of errors to be re-raised as-is so that the\n # caller can treat them in a special way.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 509739, + "num_received_chars": 25818, + "elapsed_time": 137.90196108818054, + "lint_repair_count": 2, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15103.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15103.json new file mode 100644 index 00000000..918b479e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15103.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15103", + "edit_test_file": null, + "code_patch": "diff --git a/django/utils/html.py b/django/utils/html.py\nindex da1b567..cb2c5e1 100644\n--- a/django/utils/html.py\n+++ b/django/utils/html.py\n@@ -61,18 +61,27 @@ _json_script_escapes = {\n }\n \n \n-def json_script(value, element_id):\n+def json_script(value, element_id=None):\n \"\"\"\n Escape all the HTML/XML special characters with their unicode escapes, so\n value is safe to be output anywhere except for inside a tag attribute. Wrap\n the escaped JSON in a script tag.\n+\n+ If element_id is provided, include it as the id attribute of the script tag.\n+ If element_id is None, the script tag will not have an id attribute.\n \"\"\"\n from django.core.serializers.json import DjangoJSONEncoder\n json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)\n- return format_html(\n- '',\n- element_id, mark_safe(json_str)\n- )\n+ if element_id is None:\n+ return format_html(\n+ '',\n+ mark_safe(json_str)\n+ )\n+ else:\n+ return format_html(\n+ '',\n+ element_id, mark_safe(json_str)\n+ )\n \n \n def conditional_escape(text):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1087269, + "num_received_chars": 40027, + "elapsed_time": 290.0029032230377, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15128.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15128.json new file mode 100644 index 00000000..8e444ed5 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15128.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15128", + "edit_test_file": "tests/queries/test_query.py", + "code_patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\nindex aaf35ee..0f7899e 100644\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -745,13 +745,16 @@ class Query(BaseExpression):\n for model, values in seen.items():\n callback(target, model, values)\n \n- def table_alias(self, table_name, create=False, filtered_relation=None):\n+ def table_alias(self, table_name, create=False, filtered_relation=None, rhs_alias_map=None):\n \"\"\"\n Return a table alias for the given table_name and whether this is a\n new alias or not.\n \n If 'create' is true, a new alias is always created. Otherwise, the\n most recently created alias for the table (if one exists) is reused.\n+\n+ The 'rhs_alias_map' parameter is used to avoid alias collisions when\n+ combining queries in OR operations.\n \"\"\"\n alias_list = self.table_map.get(table_name)\n if not create and alias_list:\n@@ -761,11 +764,22 @@ class Query(BaseExpression):\n \n # Create a new alias for this table.\n if alias_list:\n- alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)\n+ suffix = len(self.alias_map) + 1\n+ while True:\n+ alias = f'{self.alias_prefix}{suffix}'\n+ if alias not in self.alias_map and (rhs_alias_map is None or alias not in rhs_alias_map):\n+ break\n+ suffix += 1\n alias_list.append(alias)\n else:\n # The first occurrence of a table uses the table name directly.\n alias = filtered_relation.alias if filtered_relation is not None else table_name\n+ # Ensure the alias doesn't conflict with existing aliases\n+ if alias in self.alias_map or (rhs_alias_map is not None and alias in rhs_alias_map):\n+ suffix = 1\n+ while f'{alias}_{suffix}' in self.alias_map or (rhs_alias_map is not None and f'{alias}_{suffix}' in rhs_alias_map):\n+ suffix += 1\n+ alias = f'{alias}_{suffix}'\n self.table_map[table_name] = [alias]\n self.alias_refcount[alias] = 1\n return alias, True\n@@ -948,7 +962,7 @@ class Query(BaseExpression):\n \"\"\"\n return len([1 for count in self.alias_refcount.values() if count])\n \n- def join(self, join, reuse=None):\n+ def join(self, join, reuse=None, rhs_alias_map=None):\n \"\"\"\n Return an alias for the 'join', either reusing an existing alias for\n that join or creating a new one. 'join' is either a base_table_class or\n@@ -960,6 +974,9 @@ class Query(BaseExpression):\n A join is always created as LOUTER if the lhs alias is LOUTER to make\n sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n joins are created as LOUTER if the join is nullable.\n+\n+ The 'rhs_alias_map' parameter is used to avoid alias collisions when\n+ combining queries in OR operations.\n \"\"\"\n reuse_aliases = [\n a for a, j in self.alias_map.items()\n@@ -976,7 +993,7 @@ class Query(BaseExpression):\n return reuse_alias\n \n # No reuse is possible, so we need a new alias.\n- alias, _ = self.table_alias(join.table_name, create=True, filtered_relation=join.filtered_relation)\n+ alias, _ = self.table_alias(join.table_name, create=True, filtered_relation=join.filtered_relation, rhs_alias_map=rhs_alias_map)\n if join.join_type:\n if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n join_type = LOUTER\n", + "test_patch": "diff --git a/tests/queries/test_queryset_or_operation.py b/tests/queries/test_queryset_or_operation.py\nnew file mode 100644\nindex 0000000..89f0c29\n--- /dev/null\n+++ b/tests/queries/test_queryset_or_operation.py\n@@ -0,0 +1,41 @@\n+from django.db import models\n+from django.test import TestCase\n+from django.db.models import Q\n+\n+\n+class Qux(models.Model):\n+ pass\n+\n+\n+class Baz(models.Model):\n+ pass\n+\n+\n+class Foo(models.Model):\n+ qux = models.ForeignKey(Qux, on_delete=models.CASCADE, related_name=\"foos\")\n+\n+\n+class Bar(models.Model):\n+ foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name=\"bars\")\n+ another_foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name=\"other_bars\")\n+ baz = models.ForeignKey(Baz, on_delete=models.CASCADE, related_name=\"bars\")\n+\n+\n+class QuerysetOrOperationTest(TestCase):\n+ def test_queryset_or_operation_assertion_error(self):\n+ qux = Qux.objects.create()\n+ baz = Baz.objects.create()\n+ foo = Foo.objects.create(qux=qux)\n+ Bar.objects.create(foo=foo, another_foo=foo, baz=baz)\n+\n+ qs1 = qux.foos.all()\n+ qs2 = Foo.objects.filter(\n+ Q(bars__baz__in=Baz.objects.all()) | Q(other_bars__baz__in=Baz.objects.all())\n+ )\n+\n+ # This should work fine\n+ qs2 | qs1\n+\n+ # This should raise an AssertionError\n+ with self.assertRaises(AssertionError):\n+ qs1 | qs2\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/queries/test_queryset_or_operation_inverted.py b/tests/queries/test_queryset_or_operation_inverted.py\nnew file mode 100644\nindex 0000000..98c2cb8\n--- /dev/null\n+++ b/tests/queries/test_queryset_or_operation_inverted.py\n@@ -0,0 +1,45 @@\n+from django.db import models\n+from django.test import TestCase\n+from django.db.models import Q\n+\n+\n+class Qux(models.Model):\n+ pass\n+\n+\n+class Baz(models.Model):\n+ pass\n+\n+\n+class Foo(models.Model):\n+ qux = models.ForeignKey(Qux, on_delete=models.CASCADE, related_name=\"foos\")\n+\n+\n+class Bar(models.Model):\n+ foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name=\"bars\")\n+ another_foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name=\"other_bars\")\n+ baz = models.ForeignKey(Baz, on_delete=models.CASCADE, related_name=\"bars\")\n+\n+\n+class QuerysetOrOperationTest(TestCase):\n+ def test_queryset_or_operation_assertion_error(self):\n+ qux = Qux.objects.create()\n+ baz = Baz.objects.create()\n+ foo = Foo.objects.create(qux=qux)\n+ Bar.objects.create(foo=foo, another_foo=foo, baz=baz)\n+\n+ qs1 = qux.foos.all()\n+ qs2 = Foo.objects.filter(\n+ Q(bars__baz__in=Baz.objects.all()) | Q(other_bars__baz__in=Baz.objects.all())\n+ )\n+\n+ # This should work fine\n+ qs2 | qs1\n+\n+ # This should raise an AssertionError\n+ try:\n+ qs1 | qs2\n+ raise AssertionError(\"Expected AssertionError was not raised\")\n+ except AssertionError as e:\n+ if \"change_map keys and values intersect\" not in str(e):\n+ raise AssertionError(\"__BUG__HERE__\")\n", + "num_sent_chars": 1763947, + "num_received_chars": 90660, + "elapsed_time": 568.3231616020203, + "lint_repair_count": 0, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15268.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15268.json new file mode 100644 index 00000000..2f0c4f75 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15268.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15268", + "edit_test_file": "tests/migrations/test_optimizer.py", + "code_patch": "diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py\nindex bf9c2ac..e4cb1e0 100644\n--- a/django/db/migrations/autodetector.py\n+++ b/django/db/migrations/autodetector.py\n@@ -1206,11 +1206,50 @@ class MigrationAutodetector:\n dependencies=dependencies,\n )\n \n+ def _optimize_altered_foo_together(self):\n+ optimized_operations = []\n+ skip_indices = set()\n+\n+ for i, op in enumerate(self.generated_operations):\n+ if i in skip_indices:\n+ continue\n+\n+ if isinstance(op, (operations.AlterUniqueTogether, operations.AlterIndexTogether)):\n+ next_op_index = i + 1\n+ if next_op_index < len(self.generated_operations):\n+ next_op = self.generated_operations[next_op_index]\n+ if (\n+ isinstance(next_op, type(op)) and\n+ op.name == next_op.name and\n+ op.model_name == next_op.model_name\n+ ):\n+ # Combine the two operations\n+ combined_value = getattr(next_op, op.option_name)\n+ setattr(op, op.option_name, combined_value)\n+ skip_indices.add(next_op_index)\n+\n+ optimized_operations.append(op)\n+\n+ self.generated_operations = optimized_operations\n+\n def generate_altered_unique_together(self):\n self._generate_altered_foo_together(operations.AlterUniqueTogether)\n+ self._optimize_altered_foo_together()\n \n def generate_altered_index_together(self):\n self._generate_altered_foo_together(operations.AlterIndexTogether)\n+ self._optimize_altered_foo_together()\n+\n+ def _build_migration_list(self, graph=None):\n+ # ... (existing code)\n+\n+ self._optimize_altered_foo_together()\n+\n+ self.migrations = {}\n+ num_ops = sum(len(x) for x in self.generated_operations.values())\n+ chop_mode = False\n+ while num_ops:\n+ # ... (rest of the existing code)\n \n def generate_altered_db_table(self):\n models_to_check = self.kept_model_keys.union(self.kept_proxy_keys, self.kept_unmanaged_keys)\n", + "test_patch": "diff --git a/tests/migrations/test_optimize_alter_together_operations.py b/tests/migrations/test_optimize_alter_together_operations.py\nnew file mode 100644\nindex 0000000..ae56271\n--- /dev/null\n+++ b/tests/migrations/test_optimize_alter_together_operations.py\n@@ -0,0 +1,45 @@\n+from django.db import migrations\n+from django.test import SimpleTestCase\n+from django.db.migrations.optimizer import MigrationOptimizer\n+\n+\n+class OptimizeAlterTogetherOperationsTests(SimpleTestCase):\n+ def test_multiple_alter_together_operations_not_optimized(self):\n+ \"\"\"\n+ Test that multiple AlterUniqueTogether and AlterIndexTogether operations\n+ are not optimized into single operations as expected.\n+ \"\"\"\n+ operations = [\n+ migrations.AlterUniqueTogether(\n+ name='mymodel',\n+ unique_together=set(),\n+ ),\n+ migrations.AlterIndexTogether(\n+ name='mymodel',\n+ index_together=set(),\n+ ),\n+ migrations.AlterUniqueTogether(\n+ name='mymodel',\n+ unique_together={(\"col\",)},\n+ ),\n+ migrations.AlterIndexTogether(\n+ name='mymodel',\n+ index_together={(\"col\",)},\n+ ),\n+ ]\n+\n+ optimizer = MigrationOptimizer()\n+ optimized_operations = optimizer.optimize(operations, 'app_label')\n+\n+ # The test passes if the optimization doesn't happen\n+ self.assertEqual(len(optimized_operations), 4)\n+ self.assertIsInstance(optimized_operations[0], migrations.AlterUniqueTogether)\n+ self.assertIsInstance(optimized_operations[1], migrations.AlterIndexTogether)\n+ self.assertIsInstance(optimized_operations[2], migrations.AlterUniqueTogether)\n+ self.assertIsInstance(optimized_operations[3], migrations.AlterIndexTogether)\n+\n+ # Check that the operations are in the original order and have the expected attributes\n+ self.assertEqual(optimized_operations[0].unique_together, set())\n+ self.assertEqual(optimized_operations[1].index_together, set())\n+ self.assertEqual(optimized_operations[2].unique_together, {(\"col\",)})\n+ self.assertEqual(optimized_operations[3].index_together, {(\"col\",)})\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/migrations/test_optimize_alter_together_operations_inverted.py b/tests/migrations/test_optimize_alter_together_operations_inverted.py\nnew file mode 100644\nindex 0000000..cee5c10\n--- /dev/null\n+++ b/tests/migrations/test_optimize_alter_together_operations_inverted.py\n@@ -0,0 +1,51 @@\n+from django.db import migrations\n+from django.test import SimpleTestCase\n+from django.db.migrations.optimizer import MigrationOptimizer\n+\n+\n+class OptimizeAlterTogetherOperationsTests(SimpleTestCase):\n+ def test_multiple_alter_together_operations_optimized(self):\n+ \"\"\"\n+ Test that multiple AlterUniqueTogether and AlterIndexTogether operations\n+ are optimized into single operations as expected.\n+ \"\"\"\n+ operations = [\n+ migrations.AlterUniqueTogether(\n+ name='mymodel',\n+ unique_together=set(),\n+ ),\n+ migrations.AlterIndexTogether(\n+ name='mymodel',\n+ index_together=set(),\n+ ),\n+ migrations.AlterUniqueTogether(\n+ name='mymodel',\n+ unique_together={(\"col\",)},\n+ ),\n+ migrations.AlterIndexTogether(\n+ name='mymodel',\n+ index_together={(\"col\",)},\n+ ),\n+ ]\n+\n+ optimizer = MigrationOptimizer()\n+ optimized_operations = optimizer.optimize(operations, 'app_label')\n+\n+ # The test should fail if the optimization doesn't happen\n+ if len(optimized_operations) != 2:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check that the operations are optimized and have the expected attributes\n+ self.assertIsInstance(optimized_operations[0], migrations.AlterUniqueTogether)\n+ self.assertIsInstance(optimized_operations[1], migrations.AlterIndexTogether)\n+ self.assertEqual(optimized_operations[0].unique_together, {(\"col\",)})\n+ self.assertEqual(optimized_operations[1].index_together, {(\"col\",)})\n+\n+ # Additional checks to ensure the optimization is correct\n+ for operation in optimized_operations:\n+ self.assertEqual(operation.name, 'mymodel')\n+\n+ # Check that there are no operations with empty sets\n+ for operation in optimized_operations:\n+ self.assertNotEqual(getattr(operation, 'unique_together', None), set())\n+ self.assertNotEqual(getattr(operation, 'index_together', None), set())\n\\ No newline at end of file\n", + "num_sent_chars": 1632647, + "num_received_chars": 125590, + "elapsed_time": 623.2983891963959, + "lint_repair_count": 7, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15375.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15375.json new file mode 100644 index 00000000..279e551e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15375.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15375", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py\nindex 8c4eae7..06c2100 100644\n--- a/django/db/models/aggregates.py\n+++ b/django/db/models/aggregates.py\n@@ -47,6 +47,18 @@ class Aggregate(Func):\n self.filter = self.filter and exprs.pop()\n return super().set_source_expressions(exprs)\n \n+ def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):\n+ c = super().resolve_expression(query, allow_joins, reuse, summarize)\n+ if c.default is not None:\n+ from django.db.models.functions import Coalesce\n+ c = Coalesce(c, c.default, output_field=c.output_field)\n+ return c\n+\n+ def as_sql(self, compiler, connection, **extra_context):\n+ if self.default is not None:\n+ return self.as_sql_with_default(compiler, connection, **extra_context)\n+ return super().as_sql(compiler, connection, **extra_context)\n+\n def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):\n # Aggregates are not allowed in UPDATE queries, so ignore for_save\n c = super().resolve_expression(query, allow_joins, reuse, summarize)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1205929, + "num_received_chars": 61999, + "elapsed_time": 374.0549805164337, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15467.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15467.json new file mode 100644 index 00000000..e39222c8 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15467.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15467", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 64be087..bf56ab6 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -269,7 +269,7 @@ class BaseModelAdmin(metaclass=forms.MediaDefiningClass):\n \"class\": get_ul_class(self.radio_fields[db_field.name]),\n }\n )\n- kwargs[\"empty_label\"] = _(\"None\") if db_field.blank else None\n+ kwargs.setdefault(\"empty_label\", _(\"None\") if db_field.blank else None)\n \n if \"queryset\" not in kwargs:\n queryset = self.get_field_queryset(db, db_field, request)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1462696, + "num_received_chars": 51023, + "elapsed_time": 338.6965103149414, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15525.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15525.json new file mode 100644 index 00000000..98faeba3 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15525.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15525", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/contenttypes/models.py b/django/contrib/contenttypes/models.py\nindex 0c1c640..3c0341a 100644\n--- a/django/contrib/contenttypes/models.py\n+++ b/django/contrib/contenttypes/models.py\n@@ -13,14 +13,15 @@ class ContentTypeManager(models.Manager):\n super().__init__(*args, **kwargs)\n # Cache shared by all the get_for_* methods to speed up\n # ContentType retrieval.\n- self._cache = {}\n+ self._cache = defaultdict(dict)\n \n def get_by_natural_key(self, app_label, model):\n+ db = self._db or 'default'\n try:\n- ct = self._cache[self.db][(app_label, model)]\n+ ct = self._cache[db][(app_label, model)]\n except KeyError:\n ct = self.get(app_label=app_label, model=model)\n- self._add_to_cache(self.db, ct)\n+ self._add_to_cache(db, ct)\n return ct\n \n def _get_opts(self, model, for_concrete_model):\n@@ -30,7 +31,8 @@ class ContentTypeManager(models.Manager):\n \n def _get_from_cache(self, opts):\n key = (opts.app_label, opts.model_name)\n- return self._cache[self.db][key]\n+ db = self._db or 'default'\n+ return self._cache[db][key]\n \n def get_for_model(self, model, for_concrete_model=True):\n \"\"\"\n@@ -124,13 +126,18 @@ class ContentTypeManager(models.Manager):\n \"\"\"\n self._cache.clear()\n \n+ def clear_cache_for_db(self, db):\n+ \"\"\"\n+ Clear out the content-type cache for a specific database.\n+ \"\"\"\n+ self._cache[db].clear()\n+\n def _add_to_cache(self, using, ct):\n \"\"\"Insert a ContentType into the cache.\"\"\"\n # Note it's possible for ContentType objects to be stale; model_class()\n # will return None. Hence, there is no reliance on\n # model._meta.app_label here, just using the model fields instead.\n- key = (ct.app_label, ct.model)\n- self._cache.setdefault(using, {})[key] = ct\n+ self._cache[using][(ct.app_label, ct.model)] = ct\n self._cache.setdefault(using, {})[ct.id] = ct\n \n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1379914, + "num_received_chars": 68124, + "elapsed_time": 412.65662908554077, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15629.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15629.json new file mode 100644 index 00000000..b5190da3 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15629.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15629", + "edit_test_file": "tests/migrations/test_operations.py", + "code_patch": "diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py\nindex 696bfd7..117e326 100644\n--- a/django/db/backends/base/schema.py\n+++ b/django/db/backends/base/schema.py\n@@ -922,6 +922,27 @@ class BaseDatabaseSchemaEditor:\n model, new_field, new_type, new_collation\n )\n actions.append(fragment)\n+ \n+ # If this is a primary key, update related foreign keys\n+ if new_field.primary_key:\n+ related_models = [\n+ f.model\n+ for f in model._meta.get_fields()\n+ if (f.many_to_one and f.related_model == model) or (f.one_to_one and f.related_model == model)\n+ ]\n+ for related_model in related_models:\n+ for field in related_model._meta.local_fields:\n+ if field.remote_field and field.remote_field.model == model:\n+ fk_actions = self._alter_column_collation_sql(\n+ related_model, field, field.db_type(self.connection), new_collation\n+ )\n+ self.execute(\n+ self.sql_alter_column % {\n+ \"table\": self.quote_name(related_model._meta.db_table),\n+ \"changes\": fk_actions[0],\n+ },\n+ fk_actions[1],\n+ )\n # Type change?\n elif (old_type, old_type_suffix) != (new_type, new_type_suffix):\n fragment, other_actions = self._alter_column_type_sql(\n", + "test_patch": "diff --git a/tests/migrations/test_db_collation_foreign_key_propagation.py b/tests/migrations/test_db_collation_foreign_key_propagation.py\nnew file mode 100644\nindex 0000000..c293f56\n--- /dev/null\n+++ b/tests/migrations/test_db_collation_foreign_key_propagation.py\n@@ -0,0 +1,63 @@\n+from django.db import migrations, models\n+from django.db.migrations.state import ProjectState\n+from django.test import TestCase\n+from django.db import connection\n+from django.db.utils import IntegrityError\n+\n+class TestDBCollationForeignKeyPropagation(TestCase):\n+ def test_db_collation_not_propagated_to_foreign_keys(self):\n+ # Skip the test if not using MySQL\n+ if connection.vendor != 'mysql':\n+ self.skipTest(\"This test is only applicable to MySQL.\")\n+\n+ # Define the operations\n+ operations = [\n+ migrations.CreateModel(\n+ \"Account\",\n+ [\n+ (\"id\", models.CharField(primary_key=True, max_length=22, db_collation='utf8_bin')),\n+ ],\n+ ),\n+ migrations.CreateModel(\n+ \"Address\",\n+ [\n+ (\"id\", models.CharField(primary_key=True, max_length=22, db_collation='utf8_bin')),\n+ (\"account\", models.OneToOneField(\"Account\", on_delete=models.CASCADE)),\n+ ],\n+ ),\n+ migrations.CreateModel(\n+ \"Profile\",\n+ [\n+ (\"id\", models.CharField(primary_key=True, max_length=22, db_collation='utf8_bin')),\n+ (\"account\", models.ForeignKey(\"Account\", on_delete=models.CASCADE, null=True)),\n+ ],\n+ ),\n+ ]\n+\n+ # Create the project state and apply operations\n+ project_state = ProjectState()\n+ for operation in operations:\n+ new_state = project_state.clone()\n+ operation.state_forwards(\"testapp\", new_state)\n+ project_state = new_state\n+\n+ # Use a schema editor to apply the operations\n+ with connection.schema_editor() as editor:\n+ for operation in operations:\n+ operation.database_forwards(\"testapp\", editor, ProjectState(), project_state)\n+\n+ # Try to insert data that should cause a foreign key constraint error\n+ with connection.cursor() as cursor:\n+ # Insert an account\n+ cursor.execute(\"INSERT INTO testapp_account (id) VALUES ('acc1')\")\n+ \n+ # Try to insert an address with a mismatched collation\n+ with self.assertRaises(IntegrityError):\n+ cursor.execute(\n+ \"INSERT INTO testapp_address (id, account_id) VALUES ('addr1', 'acc1') COLLATE utf8_general_ci\"\n+ )\n+\n+ # Clean up\n+ with connection.schema_editor() as editor:\n+ for operation in reversed(operations):\n+ operation.database_backwards(\"testapp\", editor, project_state, ProjectState())\n", + "test_inverted_patch": null, + "num_sent_chars": 3149683, + "num_received_chars": 183974, + "elapsed_time": 1004.0475158691406, + "lint_repair_count": 5, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15732.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15732.json new file mode 100644 index 00000000..7329e1d0 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15732.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15732", + "edit_test_file": null, + "code_patch": "diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py\nindex f2ca8c8..ab50448 100644\n--- a/django/db/backends/base/schema.py\n+++ b/django/db/backends/base/schema.py\n@@ -1614,11 +1614,37 @@ class BaseDatabaseSchemaEditor:\n )\n ):\n return None\n- if condition or include or opclasses or expressions:\n- sql = self.sql_delete_index\n+\n+ # Get all unique constraints for the model\n+ unique_constraints = self._constraint_names(model, unique=True)\n+ \n+ # Check if the constraint to be deleted is a primary key\n+ is_primary_key = name in self._constraint_names(model, primary_key=True)\n+\n+ if is_primary_key:\n+ # If it's a primary key, we don't want to delete it\n+ return None\n+\n+ if len(unique_constraints) > 1:\n+ # If there are multiple unique constraints, we need to be careful\n+ # not to delete the primary key constraint\n+ if condition or include or opclasses or expressions:\n+ sql = self.sql_delete_index\n+ else:\n+ sql = self.sql_delete_unique\n+ \n+ # Only delete the constraint if it's not the primary key\n+ if name in unique_constraints and not is_primary_key:\n+ return self._delete_constraint_sql(sql, model, name)\n+ else:\n+ return None\n else:\n- sql = self.sql_delete_unique\n- return self._delete_constraint_sql(sql, model, name)\n+ # If there's only one unique constraint, proceed as before\n+ if condition or include or opclasses or expressions:\n+ sql = self.sql_delete_index\n+ else:\n+ sql = self.sql_delete_unique\n+ return self._delete_constraint_sql(sql, model, name)\n \n def _check_sql(self, name, check):\n return self.sql_constraint % {\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2093721, + "num_received_chars": 61862, + "elapsed_time": 361.18304562568665, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15851.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15851.json new file mode 100644 index 00000000..df398f2b --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15851.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15851", + "edit_test_file": "tests/user_commands/tests.py", + "code_patch": "diff --git a/django/core/management/commands/dbshell.py b/django/core/management/commands/dbshell.py\nindex 30d2765..7b3e1f8 100644\n--- a/django/core/management/commands/dbshell.py\n+++ b/django/core/management/commands/dbshell.py\n@@ -27,7 +27,10 @@ class Command(BaseCommand):\n def handle(self, **options):\n connection = connections[options[\"database\"]]\n try:\n- connection.client.runshell(options[\"parameters\"])\n+ if connection.vendor == 'postgresql':\n+ self.run_postgresql_shell(connection, options[\"parameters\"])\n+ else:\n+ connection.client.runshell(options[\"parameters\"])\n except FileNotFoundError:\n # Note that we're assuming the FileNotFoundError relates to the\n # command missing. It could be raised for some other reason, in\n@@ -46,3 +49,31 @@ class Command(BaseCommand):\n ),\n returncode=e.returncode,\n )\n+\n+ def run_postgresql_shell(self, connection, parameters):\n+ args, env = connection.client.settings_to_cmd_args_env(connection.settings_dict, parameters)\n+ \n+ # Reorder arguments for PostgreSQL\n+ executable = args[0]\n+ default_args = [arg for arg in args[1:] if not arg.startswith('-')]\n+ user_args = parameters\n+ database = default_args[-1] if default_args else None\n+\n+ # Construct the final argument list\n+ final_args = [executable]\n+ final_args.extend(arg for arg in args[1:] if arg.startswith('-'))\n+ final_args.extend(user_args)\n+ if database:\n+ final_args.append(database)\n+\n+ try:\n+ subprocess.run(final_args, env=env, check=True)\n+ except subprocess.CalledProcessError as e:\n+ raise CommandError(\n+ '\"%s\" returned non-zero exit status %s.'\n+ % (\n+ \" \".join(e.cmd),\n+ e.returncode,\n+ ),\n+ returncode=e.returncode,\n+ )\n", + "test_patch": "diff --git a/tests/user_commands/test_dbshell_postgresql_parameters.py b/tests/user_commands/test_dbshell_postgresql_parameters.py\nnew file mode 100644\nindex 0000000..3cea1dc\n--- /dev/null\n+++ b/tests/user_commands/test_dbshell_postgresql_parameters.py\n@@ -0,0 +1,31 @@\n+import unittest\n+from io import StringIO\n+from unittest import mock\n+\n+from django.core.management import call_command\n+from django.db import connection\n+from django.test import SimpleTestCase\n+\n+@unittest.skipUnless(connection.vendor == 'postgresql', \"PostgreSQL tests\")\n+class PostgreSQLDbshellCommandTestCase(SimpleTestCase):\n+ def test_dbshell_postgresql_parameters(self):\n+ with mock.patch('subprocess.run') as mock_run:\n+ call_command('dbshell', '--', '-c', 'SELECT * FROM some_table;')\n+\n+ mock_run.assert_called_once()\n+ args = mock_run.call_args[0][0]\n+\n+ # Find the index of the database name and the '-c' parameter\n+ try:\n+ db_name_index = args.index(connection.settings_dict['NAME'])\n+ c_param_index = args.index('-c')\n+ except ValueError:\n+ self.fail(\"Expected arguments not found in the command\")\n+\n+ # Assert that the '-c' parameter comes before the database name\n+ self.assertLess(c_param_index, db_name_index, \n+ \"The '-c' parameter should come before the database name in the psql command\")\n+\n+ # Assert that the SQL command is present in the arguments\n+ self.assertIn('SELECT * FROM some_table;', args, \n+ \"The SQL command should be present in the psql arguments\")\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1563139, + "num_received_chars": 98882, + "elapsed_time": 589.1220121383667, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15930.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15930.json new file mode 100644 index 00000000..d22bc43f --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15930.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15930", + "edit_test_file": "tests/expressions_case/tests.py", + "code_patch": "diff --git a/django/contrib/auth/base_user.py b/django/contrib/auth/base_user.py\nindex 5ee30bf..a5d37ac 100644\n--- a/django/contrib/auth/base_user.py\n+++ b/django/contrib/auth/base_user.py\n@@ -32,6 +32,27 @@ class BaseUserManager(models.Manager):\n email = email_name + \"@\" + domain_part.lower()\n return email\n \n+ @classmethod\n+ def handle_empty_q_object(cls, condition):\n+ \"\"\"\n+ Handle negated empty Q objects in Case expressions.\n+ \"\"\"\n+ from django.db.models import Q\n+ if isinstance(condition, Q):\n+ if not condition and condition.negated:\n+ # This is a negated empty Q object (~Q(pk__in=[]))\n+ # Replace it with a condition that is always true\n+ return Q(pk__isnull=False)\n+ return condition\n+\n+ def get_queryset(self):\n+ \"\"\"\n+ Override get_queryset to handle negated empty Q objects in Case expressions.\n+ \"\"\"\n+ qs = super().get_queryset()\n+ qs.query.handle_empty_q_object = self.handle_empty_q_object\n+ return qs\n+\n def make_random_password(\n self,\n length=10,\n", + "test_patch": "diff --git a/tests/expressions_case/test_case_empty_q_negation.py b/tests/expressions_case/test_case_empty_q_negation.py\nnew file mode 100644\nindex 0000000..e12ad43\n--- /dev/null\n+++ b/tests/expressions_case/test_case_empty_q_negation.py\n@@ -0,0 +1,20 @@\n+from django.db.models import BooleanField, Case, Q, Value, When\n+from django.test import TestCase\n+from django.db.utils import OperationalError\n+\n+from .models import CaseTestModel\n+\n+\n+class CaseEmptyQNegationTest(TestCase):\n+ def test_case_with_negated_empty_q(self):\n+ with self.assertRaises(OperationalError) as cm:\n+ list(CaseTestModel.objects.annotate(\n+ _a=Case(\n+ When(~Q(pk__in=[]), then=Value(True)),\n+ default=Value(False),\n+ output_field=BooleanField(),\n+ )\n+ ).order_by(\"-_a\").values(\"pk\"))\n+\n+ self.assertIn(\"syntax error\", str(cm.exception))\n+ self.assertIn(\"THEN\", str(cm.exception))\n", + "test_inverted_patch": "diff --git a/tests/expressions_case/test_case_empty_q_negation_inverted.py b/tests/expressions_case/test_case_empty_q_negation_inverted.py\nnew file mode 100644\nindex 0000000..ce9659e\n--- /dev/null\n+++ b/tests/expressions_case/test_case_empty_q_negation_inverted.py\n@@ -0,0 +1,35 @@\n+from django.db.models import BooleanField, Case, Q, Value, When\n+from django.test import TestCase\n+from django.db.utils import OperationalError\n+\n+from .models import CaseTestModel\n+\n+\n+class CaseEmptyQNegationTest(TestCase):\n+ def test_case_with_negated_empty_q(self):\n+ try:\n+ result = list(CaseTestModel.objects.annotate(\n+ _a=Case(\n+ When(~Q(pk__in=[]), then=Value(True)),\n+ default=Value(False),\n+ output_field=BooleanField(),\n+ )\n+ ).order_by(\"-_a\").values(\"pk\"))\n+\n+ # If we reach this point, it means no exception was raised\n+ # This is unexpected behavior, so we raise an assertion error\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ except OperationalError as e:\n+ # If an OperationalError is raised, we check if it's the expected error\n+ error_message = str(e)\n+ if \"syntax error\" in error_message and \"THEN\" in error_message:\n+ # This is the expected error, so we raise an assertion error\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ # If it's a different OperationalError, we re-raise it\n+ raise\n+\n+ except Exception as e:\n+ # If any other exception is raised, we re-raise it\n+ raise\n\\ No newline at end of file\n", + "num_sent_chars": 2324662, + "num_received_chars": 139448, + "elapsed_time": 750.5447533130646, + "lint_repair_count": 12, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15987.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15987.json new file mode 100644 index 00000000..93731811 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-15987.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15987", + "edit_test_file": null, + "code_patch": "diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py\nindex ac97f13..9287267 100644\n--- a/django/core/management/commands/loaddata.py\n+++ b/django/core/management/commands/loaddata.py\n@@ -362,12 +362,21 @@ class Command(BaseCommand):\n \"\"\"\n dirs = []\n fixture_dirs = settings.FIXTURE_DIRS\n- if len(fixture_dirs) != len(set(fixture_dirs)):\n+\n+ def normalize_path(path):\n+ if isinstance(path, os.PathLike):\n+ path = os.fspath(path)\n+ return os.path.normcase(os.path.abspath(path))\n+\n+ normalized_fixture_dirs = [normalize_path(d) for d in fixture_dirs]\n+ if len(normalized_fixture_dirs) != len(set(normalized_fixture_dirs)):\n raise ImproperlyConfigured(\"settings.FIXTURE_DIRS contains duplicates.\")\n+\n for app_config in apps.get_app_configs():\n app_label = app_config.label\n app_dir = os.path.join(app_config.path, \"fixtures\")\n- if app_dir in fixture_dirs:\n+ normalized_app_dir = normalize_path(app_dir)\n+ if normalized_app_dir in normalized_fixture_dirs:\n raise ImproperlyConfigured(\n \"'%s' is a default fixture directory for the '%s' app \"\n \"and cannot be listed in settings.FIXTURE_DIRS.\"\n@@ -378,9 +387,13 @@ class Command(BaseCommand):\n continue\n if os.path.isdir(app_dir):\n dirs.append(app_dir)\n+\n dirs.extend(fixture_dirs)\n dirs.append(\"\")\n- return [os.path.realpath(d) for d in dirs]\n+\n+ # Use a set to remove any potential duplicates\n+ unique_dirs = set(normalize_path(d) for d in dirs)\n+ return sorted(unique_dirs) # Sort for consistency\n \n def parse_name(self, fixture_name):\n \"\"\"\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1149678, + "num_received_chars": 55715, + "elapsed_time": 362.6440291404724, + "lint_repair_count": 3, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16100.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16100.json new file mode 100644 index 00000000..69db95a2 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16100.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16100", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 5f07a42..f38a90c 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -1916,6 +1916,7 @@ class ModelAdmin(BaseModelAdmin):\n The 'change list' admin view for this model.\n \"\"\"\n from django.contrib.admin.views.main import ERROR_FLAG\n+ from django.db import transaction\n \n app_label = self.opts.app_label\n if not self.has_view_or_change_permission(request):\n@@ -2011,25 +2012,32 @@ class ModelAdmin(BaseModelAdmin):\n )\n if formset.is_valid():\n changecount = 0\n- for form in formset.forms:\n- if form.has_changed():\n- obj = self.save_form(request, form, change=True)\n- self.save_model(request, obj, form, change=True)\n- self.save_related(request, form, formsets=[], change=True)\n- change_msg = self.construct_change_message(request, form, None)\n- self.log_change(request, obj, change_msg)\n- changecount += 1\n-\n- if changecount:\n- msg = ngettext(\n- \"%(count)s %(name)s was changed successfully.\",\n- \"%(count)s %(name)s were changed successfully.\",\n- changecount,\n- ) % {\n- \"count\": changecount,\n- \"name\": model_ngettext(self.opts, changecount),\n- }\n- self.message_user(request, msg, messages.SUCCESS)\n+ try:\n+ with transaction.atomic():\n+ for form in formset.forms:\n+ if form.has_changed():\n+ obj = self.save_form(request, form, change=True)\n+ self.save_model(request, obj, form, change=True)\n+ self.save_related(request, form, formsets=[], change=True)\n+ change_msg = self.construct_change_message(request, form, None)\n+ self.log_change(request, obj, change_msg)\n+ changecount += 1\n+\n+ if changecount:\n+ msg = ngettext(\n+ \"%(count)s %(name)s was changed successfully.\",\n+ \"%(count)s %(name)s were changed successfully.\",\n+ changecount,\n+ ) % {\n+ \"count\": changecount,\n+ \"name\": model_ngettext(self.opts, changecount),\n+ }\n+ self.message_user(request, msg, messages.SUCCESS)\n+ except Exception as e:\n+ # If an error occurs, roll back the transaction and display an error message\n+ transaction.set_rollback(True)\n+ msg = _(\"An error occurred while saving the changes: %s\") % str(e)\n+ self.message_user(request, msg, messages.ERROR)\n \n return HttpResponseRedirect(request.get_full_path())\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2348970, + "num_received_chars": 88981, + "elapsed_time": 527.6059889793396, + "lint_repair_count": 6, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16139.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16139.json new file mode 100644 index 00000000..12c88ac1 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16139.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16139", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/auth/views.py b/django/contrib/auth/views.py\nindex 2d19d6f..2e3bbe3 100644\n--- a/django/contrib/auth/views.py\n+++ b/django/contrib/auth/views.py\n@@ -360,6 +360,10 @@ class PasswordResetCompleteView(PasswordContextMixin, TemplateView):\n return context\n \n \n+from django.shortcuts import get_object_or_404\n+from django.contrib.auth import get_user_model\n+from django.core.exceptions import PermissionDenied\n+\n class PasswordChangeView(PasswordContextMixin, FormView):\n form_class = PasswordChangeForm\n success_url = reverse_lazy(\"password_change_done\")\n@@ -370,11 +374,25 @@ class PasswordChangeView(PasswordContextMixin, FormView):\n @method_decorator(csrf_protect)\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n+ self.user = self.get_user(kwargs.get('user_id'))\n+ if self.user is None:\n+ self.user = self.request.user\n+ if not self.request.user.is_authenticated:\n+ return self.handle_no_permission()\n+ if not self.request.user.has_perm('auth.change_user'):\n+ if self.request.user != self.user:\n+ raise PermissionDenied\n return super().dispatch(*args, **kwargs)\n \n+ def get_user(self, user_id):\n+ User = get_user_model()\n+ if user_id:\n+ return get_object_or_404(User, pk=user_id)\n+ return None\n+\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n- kwargs[\"user\"] = self.request.user\n+ kwargs[\"user\"] = self.user\n return kwargs\n \n def form_valid(self, form):\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 3421315, + "num_received_chars": 181179, + "elapsed_time": 1030.2203722000122, + "lint_repair_count": 28, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16256.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16256.json new file mode 100644 index 00000000..d786c1f5 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16256.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16256", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py\nindex 542368d..a84a536 100644\n--- a/django/contrib/contenttypes/fields.py\n+++ b/django/contrib/contenttypes/fields.py\n@@ -2,6 +2,7 @@ import functools\n import itertools\n from collections import defaultdict\n \n+from asgiref.sync import sync_to_async\n from django.contrib.contenttypes.models import ContentType\n from django.core import checks\n from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist\n@@ -747,6 +748,11 @@ def create_generic_related_manager(superclass, rel):\n \n create.alters_data = True\n \n+ async def acreate(self, **kwargs):\n+ return await sync_to_async(self.create)(**kwargs)\n+\n+ acreate.alters_data = True\n+\n def get_or_create(self, **kwargs):\n kwargs[self.content_type_field_name] = self.content_type\n kwargs[self.object_id_field_name] = self.pk_val\n@@ -755,6 +761,11 @@ def create_generic_related_manager(superclass, rel):\n \n get_or_create.alters_data = True\n \n+ async def aget_or_create(self, **kwargs):\n+ return await sync_to_async(self.get_or_create)(**kwargs)\n+\n+ aget_or_create.alters_data = True\n+\n def update_or_create(self, **kwargs):\n kwargs[self.content_type_field_name] = self.content_type\n kwargs[self.object_id_field_name] = self.pk_val\n@@ -763,4 +774,11 @@ def create_generic_related_manager(superclass, rel):\n \n update_or_create.alters_data = True\n \n+ async def aupdate_or_create(self, **kwargs):\n+ return await sync_to_async(self.update_or_create)(**kwargs)\n+\n+ aupdate_or_create.alters_data = True\n+\n+ update_or_create.alters_data = True\n+\n return GenericRelatedObjectManager\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 3991344, + "num_received_chars": 137879, + "elapsed_time": 806.9116456508636, + "lint_repair_count": 12, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16333.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16333.json new file mode 100644 index 00000000..90d56770 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16333.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16333", + "edit_test_file": "tests/model_forms/tests.py", + "code_patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\nindex d73d1c8..c21e2da 100644\n--- a/django/contrib/auth/forms.py\n+++ b/django/contrib/auth/forms.py\n@@ -141,6 +141,17 @@ class UserCreationForm(forms.ModelForm):\n user.set_password(self.cleaned_data[\"password1\"])\n if commit:\n user.save()\n+ self.save_m2m()\n+ else:\n+ # Append save_m2m() to the user's save() method.\n+ old_save_m2m = self.save_m2m\n+\n+ def save_m2m():\n+ old_save_m2m()\n+ user.save()\n+\n+ self.save_m2m = save_m2m\n+ user.save_m2m = self.save_m2m\n return user\n \n \n", + "test_patch": "diff --git a/tests/model_forms/test_user_creation_form_m2m_save.py b/tests/model_forms/test_user_creation_form_m2m_save.py\nnew file mode 100644\nindex 0000000..1709306\n--- /dev/null\n+++ b/tests/model_forms/test_user_creation_form_m2m_save.py\n@@ -0,0 +1,33 @@\n+# tests/model_forms/test_user_creation_form_m2m_save.py\n+\n+from django.contrib.auth.forms import UserCreationForm\n+from django.contrib.auth.models import Group\n+from django.test import TestCase\n+from django.contrib.auth import get_user_model\n+\n+User = get_user_model()\n+\n+class CustomUserCreationForm(UserCreationForm):\n+ class Meta(UserCreationForm.Meta):\n+ model = User\n+ fields = UserCreationForm.Meta.fields + ('groups',)\n+\n+class UserCreationFormM2MSaveTest(TestCase):\n+ def setUp(self):\n+ self.group = Group.objects.create(name='Test Group')\n+\n+ def test_user_creation_form_m2m_save(self):\n+ form_data = {\n+ 'username': 'testuser',\n+ 'password1': 'testpassword123',\n+ 'password2': 'testpassword123',\n+ 'groups': [self.group.pk],\n+ }\n+ form = CustomUserCreationForm(data=form_data)\n+ self.assertTrue(form.is_valid())\n+\n+ user = form.save()\n+ self.assertFalse(user.groups.exists())\n+\n+ # The test passes if the group is not saved, which demonstrates the issue\n+ self.assertEqual(user.groups.count(), 0)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_forms/test_user_creation_form_m2m_save_inverted.py b/tests/model_forms/test_user_creation_form_m2m_save_inverted.py\nnew file mode 100644\nindex 0000000..e021a01\n--- /dev/null\n+++ b/tests/model_forms/test_user_creation_form_m2m_save_inverted.py\n@@ -0,0 +1,37 @@\n+# tests/model_forms/test_user_creation_form_m2m_save.py\n+\n+from django.contrib.auth.forms import UserCreationForm\n+from django.contrib.auth.models import Group\n+from django.test import TestCase\n+from django.contrib.auth import get_user_model\n+\n+User = get_user_model()\n+\n+class CustomUserCreationForm(UserCreationForm):\n+ class Meta(UserCreationForm.Meta):\n+ model = User\n+ fields = UserCreationForm.Meta.fields + ('groups',)\n+\n+class UserCreationFormM2MSaveTest(TestCase):\n+ def setUp(self):\n+ self.group = Group.objects.create(name='Test Group')\n+\n+ def test_user_creation_form_m2m_save(self):\n+ form_data = {\n+ 'username': 'testuser',\n+ 'password1': 'testpassword123',\n+ 'password2': 'testpassword123',\n+ 'groups': [self.group.pk],\n+ }\n+ form = CustomUserCreationForm(data=form_data)\n+ self.assertTrue(form.is_valid())\n+\n+ user = form.save()\n+ \n+ # The test should now fail if the group is not saved\n+ if not user.groups.exists():\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Additional assertions to ensure the group was saved correctly\n+ self.assertEqual(user.groups.count(), 1)\n+ self.assertEqual(user.groups.first(), self.group)\n\\ No newline at end of file\n", + "num_sent_chars": 971505, + "num_received_chars": 26324, + "elapsed_time": 192.83509707450867, + "lint_repair_count": 1, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16485.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16485.json new file mode 100644 index 00000000..a44a828c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16485.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16485", + "edit_test_file": "tests/model_fields/test_decimalfield.py", + "code_patch": "diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py\nindex 23c3a08..22d3048 100644\n--- a/django/template/defaultfilters.py\n+++ b/django/template/defaultfilters.py\n@@ -163,6 +163,13 @@ def floatformat(text, arg=-1):\n except ValueError:\n return input_val\n \n+ # Check if the input is zero\n+ if d.is_zero():\n+ if p == 0:\n+ return mark_safe(formats.number_format(\"0\", 0, use_l10n=use_l10n, force_grouping=force_grouping))\n+ elif p < 0:\n+ return mark_safe(formats.number_format(\"0\", 0, use_l10n=use_l10n, force_grouping=force_grouping))\n+\n try:\n m = int(d) - d\n except (ValueError, OverflowError, InvalidOperation):\n@@ -183,7 +190,7 @@ def floatformat(text, arg=-1):\n tupl = d.as_tuple()\n units = len(tupl[1])\n units += -tupl[2] if m else tupl[2]\n- prec = abs(p) + units + 1\n+ prec = max(1, abs(p) + units + 1) # Ensure prec is at least 1\n \n # Avoid conversion to scientific notation by accessing `sign`, `digits`,\n # and `exponent` from Decimal.as_tuple() directly.\n", + "test_patch": "diff --git a/tests/model_fields/test_floatformat_edge_cases.py b/tests/model_fields/test_floatformat_edge_cases.py\nnew file mode 100644\nindex 0000000..2983e51\n--- /dev/null\n+++ b/tests/model_fields/test_floatformat_edge_cases.py\n@@ -0,0 +1,15 @@\n+from decimal import Decimal\n+from django.template.defaultfilters import floatformat\n+from django.test import SimpleTestCase\n+\n+\n+class FloatformatEdgeCaseTests(SimpleTestCase):\n+ def test_floatformat_zero_decimal(self):\n+ \"\"\"\n+ Test that floatformat() raises ValueError for '0.00' with precision 0.\n+ \"\"\"\n+ with self.assertRaisesMessage(ValueError, \"valid range for prec is [1, MAX_PREC]\"):\n+ floatformat('0.00', 0)\n+\n+ with self.assertRaisesMessage(ValueError, \"valid range for prec is [1, MAX_PREC]\"):\n+ floatformat(Decimal('0.00'), 0)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/model_fields/test_floatformat_edge_cases_inverted.py b/tests/model_fields/test_floatformat_edge_cases_inverted.py\nnew file mode 100644\nindex 0000000..9263144\n--- /dev/null\n+++ b/tests/model_fields/test_floatformat_edge_cases_inverted.py\n@@ -0,0 +1,28 @@\n+from decimal import Decimal\n+from django.template.defaultfilters import floatformat\n+from django.test import SimpleTestCase\n+\n+\n+class FloatformatEdgeCaseTests(SimpleTestCase):\n+ def test_floatformat_zero_decimal(self):\n+ \"\"\"\n+ Test that floatformat() doesn't raise ValueError for '0.00' with precision 0.\n+ \"\"\"\n+ try:\n+ result = floatformat('0.00', 0)\n+ except ValueError as e:\n+ if str(e) == \"valid range for prec is [1, MAX_PREC]\":\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ raise # Re-raise if it's a different ValueError\n+\n+ try:\n+ result = floatformat(Decimal('0.00'), 0)\n+ except ValueError as e:\n+ if str(e) == \"valid range for prec is [1, MAX_PREC]\":\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ raise # Re-raise if it's a different ValueError\n+\n+ # If we reach here, it means no ValueError was raised, which is the expected behavior\n+ # We'll add some assertions to check the result\n+ self.assertIsInstance(result, str)\n+ self.assertNotEqual(result, '') # Ensure some result was returned\n\\ No newline at end of file\n", + "num_sent_chars": 763245, + "num_received_chars": 40303, + "elapsed_time": 293.8623058795929, + "lint_repair_count": 0, + "test_generation_attempts": 7, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16527.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16527.json new file mode 100644 index 00000000..ee8eef21 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16527.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16527", + "edit_test_file": null, + "code_patch": "diff --git a/django/contrib/admin/templatetags/admin_modify.py b/django/contrib/admin/templatetags/admin_modify.py\nindex 9df4b7a..38bb0dc 100644\n--- a/django/contrib/admin/templatetags/admin_modify.py\n+++ b/django/contrib/admin/templatetags/admin_modify.py\n@@ -101,6 +101,7 @@ def submit_row(context):\n ),\n \"show_save_as_new\": not is_popup\n and has_change_permission\n+ and has_add_permission\n and change\n and save_as,\n \"show_save_and_add_another\": can_save_and_add_another,\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1912651, + "num_received_chars": 55184, + "elapsed_time": 418.09578371047974, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16595.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16595.json new file mode 100644 index 00000000..7e330bf0 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16595.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16595", + "edit_test_file": "tests/migrations/test_optimizer.py", + "code_patch": "diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py\nindex 5a5f5a1..4742242 100644\n--- a/django/db/migrations/autodetector.py\n+++ b/django/db/migrations/autodetector.py\n@@ -410,7 +410,26 @@ class MigrationAutodetector:\n # Optimize migrations\n for app_label, migrations in self.migrations.items():\n for migration in migrations:\n- migration.operations = MigrationOptimizer().optimize(\n+ optimizer = MigrationOptimizer()\n+ optimized_operations = []\n+ for operation in migration.operations:\n+ if isinstance(operation, operations.AlterField):\n+ # Check if the previous operation is also an AlterField on the same field\n+ if (optimized_operations and\n+ isinstance(optimized_operations[-1], operations.AlterField) and\n+ optimized_operations[-1].model_name == operation.model_name and\n+ optimized_operations[-1].name == operation.name):\n+ # Combine the two AlterField operations\n+ combined_field = operation.field\n+ for attr, value in vars(optimized_operations[-1].field).items():\n+ if not hasattr(combined_field, attr):\n+ setattr(combined_field, attr, value)\n+ optimized_operations[-1].field = combined_field\n+ else:\n+ optimized_operations.append(operation)\n+ else:\n+ optimized_operations.append(operation)\n+ migration.operations = optimizer.optimize(optimized_operations, app_label)\n migration.operations, app_label\n )\n \n", + "test_patch": "diff --git a/tests/migrations/test_migration_optimizer_alter_field_reduction.py b/tests/migrations/test_migration_optimizer_alter_field_reduction.py\nnew file mode 100644\nindex 0000000..87889f0\n--- /dev/null\n+++ b/tests/migrations/test_migration_optimizer_alter_field_reduction.py\n@@ -0,0 +1,47 @@\n+from django.db import migrations, models\n+from django.db.migrations.optimizer import MigrationOptimizer\n+from django.test import SimpleTestCase\n+\n+\n+class TestMigrationOptimizerAlterFieldReduction(SimpleTestCase):\n+ def test_multiple_alter_field_not_reduced(self):\n+ \"\"\"\n+ Test that multiple AlterField operations are not reduced by the optimizer\n+ when they are not preceded by an AddField operation.\n+ \"\"\"\n+ operations = [\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\"),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\", default=None),\n+ ),\n+ ]\n+\n+ optimizer = MigrationOptimizer()\n+ optimized_operations = optimizer.optimize(operations, app_label=\"books\")\n+\n+ # Assert that the number of operations hasn't changed\n+ self.assertEqual(len(optimized_operations), 3)\n+\n+ # Assert that all operations are still AlterField\n+ for op in optimized_operations:\n+ self.assertIsInstance(op, migrations.AlterField)\n+\n+ # Assert that the field attributes are preserved in the last operation\n+ last_op = optimized_operations[-1]\n+ self.assertEqual(last_op.name, \"title\")\n+ self.assertEqual(last_op.model_name, \"book\")\n+ self.assertEqual(last_op.field.max_length, 128)\n+ self.assertTrue(last_op.field.null)\n+ self.assertEqual(last_op.field.help_text, \"help\")\n+ self.assertIsNone(last_op.field.default)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/migrations/test_migration_optimizer_alter_field_reduction_inverted.py b/tests/migrations/test_migration_optimizer_alter_field_reduction_inverted.py\nnew file mode 100644\nindex 0000000..455d66a\n--- /dev/null\n+++ b/tests/migrations/test_migration_optimizer_alter_field_reduction_inverted.py\n@@ -0,0 +1,50 @@\n+from django.db import migrations, models\n+from django.db.migrations.optimizer import MigrationOptimizer\n+from django.test import SimpleTestCase\n+\n+\n+class TestMigrationOptimizerAlterFieldReduction(SimpleTestCase):\n+ def test_multiple_alter_field_should_be_reduced(self):\n+ \"\"\"\n+ Test that multiple AlterField operations are reduced by the optimizer\n+ even when they are not preceded by an AddField operation.\n+ \"\"\"\n+ operations = [\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\"),\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"title\",\n+ field=models.CharField(max_length=128, null=True, help_text=\"help\", default=None),\n+ ),\n+ ]\n+\n+ optimizer = MigrationOptimizer()\n+ optimized_operations = optimizer.optimize(operations, app_label=\"books\")\n+\n+ # Assert that the number of operations has been reduced\n+ if len(optimized_operations) == 3:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Assert that there is only one operation after optimization\n+ self.assertEqual(len(optimized_operations), 1)\n+\n+ # Assert that the remaining operation is AlterField\n+ self.assertIsInstance(optimized_operations[0], migrations.AlterField)\n+\n+ # Assert that the field attributes are preserved in the optimized operation\n+ optimized_op = optimized_operations[0]\n+ self.assertEqual(optimized_op.name, \"title\")\n+ self.assertEqual(optimized_op.model_name, \"book\")\n+ self.assertEqual(optimized_op.field.max_length, 128)\n+ self.assertTrue(optimized_op.field.null)\n+ self.assertEqual(optimized_op.field.help_text, \"help\")\n+ self.assertIsNone(optimized_op.field.default)\n\\ No newline at end of file\n", + "num_sent_chars": 1682160, + "num_received_chars": 94450, + "elapsed_time": 523.0469653606415, + "lint_repair_count": 6, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16642.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16642.json new file mode 100644 index 00000000..0ebd52d2 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16642.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16642", + "edit_test_file": "tests/responses/test_fileresponse.py", + "code_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex f62dec8..5380fab 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -608,11 +608,7 @@ class FileResponse(StreamingHttpResponse):\n content_type, encoding = mimetypes.guess_type(filename)\n # Encoding isn't set to prevent browsers from automatically\n # uncompressing files.\n- content_type = {\n- \"bzip2\": \"application/x-bzip\",\n- \"gzip\": \"application/gzip\",\n- \"xz\": \"application/x-xz\",\n- }.get(encoding, content_type)\n+ content_type = self._get_content_type(filename, content_type, encoding)\n self.headers[\"Content-Type\"] = (\n content_type or \"application/octet-stream\"\n )\n@@ -624,6 +620,23 @@ class FileResponse(StreamingHttpResponse):\n ):\n self.headers[\"Content-Disposition\"] = content_disposition\n \n+ def _get_content_type(self, filename, content_type, encoding):\n+ \"\"\"\n+ Determine the correct content type for the file, including handling\n+ for 'Z' and 'br' extensions.\n+ \"\"\"\n+ if filename.endswith('.Z'):\n+ return \"application/x-compress\"\n+ elif filename.endswith('.br'):\n+ return \"application/x-brotli\"\n+ elif encoding:\n+ return {\n+ \"bzip2\": \"application/x-bzip\",\n+ \"gzip\": \"application/gzip\",\n+ \"xz\": \"application/x-xz\",\n+ }.get(encoding, content_type)\n+ return content_type\n+\n \n class HttpResponseRedirectBase(HttpResponse):\n allowed_schemes = [\"http\", \"https\", \"ftp\"]\n", + "test_patch": "diff --git a/tests/responses/test_mime_type_guessing.py b/tests/responses/test_mime_type_guessing.py\nnew file mode 100644\nindex 0000000..e7cd13e\n--- /dev/null\n+++ b/tests/responses/test_mime_type_guessing.py\n@@ -0,0 +1,52 @@\n+import io\n+import tempfile\n+from django.http import FileResponse\n+from django.test import SimpleTestCase\n+\n+\n+class MimeTypeGuessingTests(SimpleTestCase):\n+ def test_improper_mime_type_guessing_for_Z_and_br_extensions(self):\n+ \"\"\"\n+ FileResponse should improperly guess the MIME type for .Z and .br files,\n+ setting it to text/html instead of the correct MIME type.\n+ \"\"\"\n+ test_cases = [\n+ ('test.html.Z', b'Z compressed content'),\n+ ('test.html.br', b'Brotli compressed content'),\n+ ]\n+\n+ for filename, content in test_cases:\n+ with self.subTest(filename=filename):\n+ with tempfile.NamedTemporaryFile(suffix=filename.split('.')[-1]) as tmp:\n+ tmp.write(content)\n+ tmp.seek(0)\n+\n+ response = FileResponse(tmp, filename=filename)\n+\n+ # Assert that the Content-Type is improperly set to text/html\n+ self.assertEqual(response.headers['Content-Type'], 'text/html')\n+\n+ # Ensure the response content is correct\n+ response_content = b''.join(response)\n+ self.assertEqual(response_content, content)\n+\n+ def test_mime_type_guessing_for_html_file(self):\n+ \"\"\"\n+ FileResponse should correctly guess the MIME type for .html files.\n+ This test is included for comparison with the improper guessing.\n+ \"\"\"\n+ filename = 'test.html'\n+ content = b'Test content'\n+\n+ with tempfile.NamedTemporaryFile(suffix='.html') as tmp:\n+ tmp.write(content)\n+ tmp.seek(0)\n+\n+ response = FileResponse(tmp, filename=filename)\n+\n+ # Assert that the Content-Type is correctly set to text/html\n+ self.assertEqual(response.headers['Content-Type'], 'text/html')\n+\n+ # Ensure the response content is correct\n+ response_content = b''.join(response)\n+ self.assertEqual(response_content, content)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/responses/test_mime_type_guessing_inverted.py b/tests/responses/test_mime_type_guessing_inverted.py\nnew file mode 100644\nindex 0000000..68e832e\n--- /dev/null\n+++ b/tests/responses/test_mime_type_guessing_inverted.py\n@@ -0,0 +1,55 @@\n+import io\n+import tempfile\n+from django.http import FileResponse\n+from django.test import SimpleTestCase\n+\n+\n+class MimeTypeGuessingTests(SimpleTestCase):\n+ def test_improper_mime_type_guessing_for_Z_and_br_extensions(self):\n+ \"\"\"\n+ FileResponse should properly guess the MIME type for .Z and .br files,\n+ setting it to the correct MIME type instead of text/html.\n+ \"\"\"\n+ test_cases = [\n+ ('test.html.Z', b'Z compressed content', 'application/x-compress'),\n+ ('test.html.br', b'Brotli compressed content', 'application/x-brotli'),\n+ ]\n+\n+ for filename, content, expected_mime_type in test_cases:\n+ with self.subTest(filename=filename):\n+ with tempfile.NamedTemporaryFile(suffix=filename.split('.')[-1]) as tmp:\n+ tmp.write(content)\n+ tmp.seek(0)\n+\n+ response = FileResponse(tmp, filename=filename)\n+\n+ # Assert that the Content-Type is properly set\n+ try:\n+ self.assertEqual(response.headers['Content-Type'], expected_mime_type)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Ensure the response content is correct\n+ response_content = b''.join(response)\n+ self.assertEqual(response_content, content)\n+\n+ def test_mime_type_guessing_for_html_file(self):\n+ \"\"\"\n+ FileResponse should correctly guess the MIME type for .html files.\n+ This test is included for comparison with the proper guessing.\n+ \"\"\"\n+ filename = 'test.html'\n+ content = b'Test content'\n+\n+ with tempfile.NamedTemporaryFile(suffix='.html') as tmp:\n+ tmp.write(content)\n+ tmp.seek(0)\n+\n+ response = FileResponse(tmp, filename=filename)\n+\n+ # Assert that the Content-Type is correctly set to text/html\n+ self.assertEqual(response.headers['Content-Type'], 'text/html')\n+\n+ # Ensure the response content is correct\n+ response_content = b''.join(response)\n+ self.assertEqual(response_content, content)\n\\ No newline at end of file\n", + "num_sent_chars": 316211, + "num_received_chars": 17224, + "elapsed_time": 108.21261382102966, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16667.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16667.json new file mode 100644 index 00000000..f015ad84 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16667.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16667", + "edit_test_file": "tests/forms_tests/widget_tests/test_selectdatewidget.py", + "code_patch": "diff --git a/django/forms/widgets.py b/django/forms/widgets.py\nindex 842b73e..23581d4 100644\n--- a/django/forms/widgets.py\n+++ b/django/forms/widgets.py\n@@ -1035,6 +1035,28 @@ class SelectDateWidget(Widget):\n this_year = datetime.date.today().year\n self.years = range(this_year, this_year + 10)\n \n+ @staticmethod\n+ def _safe_int_cast(value, default=None):\n+ \"\"\"\n+ Safely convert a value to int, with bounds checking.\n+ Returns default if value is not a valid integer or is out of bounds.\n+ \"\"\"\n+ try:\n+ return int(value)\n+ except (TypeError, ValueError):\n+ return default\n+\n+ @staticmethod\n+ def _is_valid_date(year, month, day):\n+ \"\"\"\n+ Check if the given year, month, and day form a valid date.\n+ \"\"\"\n+ try:\n+ datetime.date(year, month, day)\n+ return True\n+ except (ValueError, OverflowError):\n+ return False\n+\n # Optional dict of months to use in the \"month\" select box.\n if months:\n self.months = months\n@@ -1155,13 +1177,28 @@ class SelectDateWidget(Widget):\n if y is not None and m is not None and d is not None:\n input_format = get_format(\"DATE_INPUT_FORMATS\")[0]\n input_format = formats.sanitize_strftime_format(input_format)\n- try:\n- date_value = datetime.date(int(y), int(m), int(d))\n- except ValueError:\n- # Return pseudo-ISO dates with zeros for any unselected values,\n- # e.g. '2017-0-23'.\n+ \n+ # Safely convert inputs to integers\n+ year = self._safe_int_cast(y)\n+ month = self._safe_int_cast(m)\n+ day = self._safe_int_cast(d)\n+ \n+ # Check if all values are valid integers\n+ if year is None or month is None or day is None:\n return \"%s-%s-%s\" % (y or 0, m or 0, d or 0)\n- return date_value.strftime(input_format)\n+ \n+ # Check if the date is valid\n+ if self._is_valid_date(year, month, day):\n+ try:\n+ date_value = datetime.date(year, month, day)\n+ return date_value.strftime(input_format)\n+ except (ValueError, OverflowError):\n+ # This should not happen due to prior checks, but just in case\n+ pass\n+ \n+ # Return pseudo-ISO dates with zeros for any unselected values,\n+ # e.g. '2017-0-23'.\n+ return \"%s-%s-%s\" % (y or 0, m or 0, d or 0)\n return data.get(name)\n \n def value_omitted_from_data(self, data, files, name):\n", + "test_patch": "diff --git a/tests/forms_tests/widget_tests/test_selectdatewidget_overflow.py b/tests/forms_tests/widget_tests/test_selectdatewidget_overflow.py\nnew file mode 100644\nindex 0000000..e463f61\n--- /dev/null\n+++ b/tests/forms_tests/widget_tests/test_selectdatewidget_overflow.py\n@@ -0,0 +1,24 @@\n+from datetime import date\n+\n+from django.forms import DateField, Form, SelectDateWidget\n+from django.test import TestCase\n+from django.http import HttpRequest\n+\n+class SelectDateWidgetOverflowTest(TestCase):\n+ def test_selectdatewidget_overflow(self):\n+ class ReproForm(Form):\n+ my_date = DateField(widget=SelectDateWidget())\n+\n+ # Simulate a GET request with an extremely large year value\n+ request = HttpRequest()\n+ request.GET = {\n+ 'my_date_day': '1',\n+ 'my_date_month': '1',\n+ 'my_date_year': '1234567821345678'\n+ }\n+\n+ form = ReproForm(request.GET)\n+\n+ # Assert that an OverflowError is raised when calling is_valid()\n+ with self.assertRaises(OverflowError):\n+ form.is_valid()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/forms_tests/widget_tests/test_selectdatewidget_overflow_inverted.py b/tests/forms_tests/widget_tests/test_selectdatewidget_overflow_inverted.py\nnew file mode 100644\nindex 0000000..3010c73\n--- /dev/null\n+++ b/tests/forms_tests/widget_tests/test_selectdatewidget_overflow_inverted.py\n@@ -0,0 +1,30 @@\n+from datetime import date\n+\n+from django.forms import DateField, Form, SelectDateWidget\n+from django.test import TestCase\n+from django.http import HttpRequest\n+\n+class SelectDateWidgetOverflowTest(TestCase):\n+ def test_selectdatewidget_overflow(self):\n+ class ReproForm(Form):\n+ my_date = DateField(widget=SelectDateWidget())\n+\n+ # Simulate a GET request with an extremely large year value\n+ request = HttpRequest()\n+ request.GET = {\n+ 'my_date_day': '1',\n+ 'my_date_month': '1',\n+ 'my_date_year': '1234567821345678'\n+ }\n+\n+ form = ReproForm(request.GET)\n+\n+ # Try to validate the form\n+ try:\n+ form.is_valid()\n+ except OverflowError:\n+ # If an OverflowError is raised, the bug is present\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # If no OverflowError was raised, the test should fail\n+ self.fail(\"Expected OverflowError was not raised\")\n\\ No newline at end of file\n", + "num_sent_chars": 1816881, + "num_received_chars": 133337, + "elapsed_time": 669.9891955852509, + "lint_repair_count": 12, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16877.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16877.json new file mode 100644 index 00000000..149a9814 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16877.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16877", + "edit_test_file": "tests/template_tests/filter_tests/test_safeseq.py", + "code_patch": "diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py\nindex 5289ef3..a1d37ba 100644\n--- a/django/template/defaultfilters.py\n+++ b/django/template/defaultfilters.py\n@@ -498,6 +498,23 @@ def safeseq(value):\n return [mark_safe(obj) for obj in value]\n \n \n+@register.filter(is_safe=True)\n+def escapeseq(value):\n+ \"\"\"\n+ Escape each item in the given sequence.\n+\n+ This filter applies the `escape` function to each item in the input sequence,\n+ converting them to strings if necessary. It returns a new list containing\n+ the escaped items, preserving the original order.\n+\n+ This is particularly useful in scenarios where autoescaping is turned off,\n+ but individual items in a sequence still need to be escaped before further\n+ operations (like joining) are applied.\n+ \"\"\"\n+ return [escape(str(obj)) for obj in value]\n+ return [mark_safe(obj) for obj in value]\n+\n+\n @register.filter(is_safe=True)\n @stringfilter\n def striptags(value):\n", + "test_patch": "diff --git a/tests/template_tests/filter_tests/test_escapeseq.py b/tests/template_tests/filter_tests/test_escapeseq.py\nnew file mode 100644\nindex 0000000..7344c42\n--- /dev/null\n+++ b/tests/template_tests/filter_tests/test_escapeseq.py\n@@ -0,0 +1,24 @@\n+from django.test import SimpleTestCase\n+from django.template.exceptions import TemplateSyntaxError\n+\n+from ..utils import setup\n+\n+\n+class EscapeseqTests(SimpleTestCase):\n+ @setup({\"escapeseq01\": '{{ a|escapeseq|join:\", \" }}'})\n+ def test_escapeseq01(self):\n+ with self.assertRaises(TemplateSyntaxError) as cm:\n+ self.engine.render_to_string(\"escapeseq01\", {\"a\": [\"&\", \"<\"]})\n+ self.assertEqual(str(cm.exception), \"Invalid filter: 'escapeseq'\")\n+\n+ @setup(\n+ {\n+ \"escapeseq02\": (\n+ '{% autoescape off %}{{ a|escapeseq|join:\", \" }}{% endautoescape %}'\n+ )\n+ }\n+ )\n+ def test_escapeseq02(self):\n+ with self.assertRaises(TemplateSyntaxError) as cm:\n+ self.engine.render_to_string(\"escapeseq02\", {\"a\": [\"&\", \"<\"]})\n+ self.assertEqual(str(cm.exception), \"Invalid filter: 'escapeseq'\")\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 1080617, + "num_received_chars": 52952, + "elapsed_time": 348.87814569473267, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16938.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16938.json new file mode 100644 index 00000000..2bf87a2c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-16938.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-16938", + "edit_test_file": "tests/select_related/tests.py", + "code_patch": "diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py\nindex 1d3269c..bc0ab09 100644\n--- a/django/core/serializers/xml_serializer.py\n+++ b/django/core/serializers/xml_serializer.py\n@@ -12,6 +12,7 @@ from django.core.exceptions import ObjectDoesNotExist\n from django.core.serializers import base\n from django.db import DEFAULT_DB_ALIAS, models\n from django.utils.xmlutils import SimplerXMLGenerator, UnserializableContentError\n+from django.db.models.query import QuerySet\n \n \n class Serializer(base.Serializer):\n@@ -23,6 +24,14 @@ class Serializer(base.Serializer):\n \"\\n\" + \" \" * self.options.get(\"indent\") * level\n )\n \n+ def is_using_select_related(self, queryset):\n+ \"\"\"\n+ Check if the queryset is using select_related.\n+ \"\"\"\n+ if isinstance(queryset, QuerySet):\n+ return queryset.query.select_related\n+ return False\n+\n def start_serialization(self):\n \"\"\"\n Start serialization -- open the XML document and the root element.\n", + "test_patch": "diff --git a/tests/select_related/test_m2m_serialization_with_custom_manager.py b/tests/select_related/test_m2m_serialization_with_custom_manager.py\nnew file mode 100644\nindex 0000000..afe139f\n--- /dev/null\n+++ b/tests/select_related/test_m2m_serialization_with_custom_manager.py\n@@ -0,0 +1,43 @@\n+from django.core import serializers\n+from django.core.exceptions import FieldError\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class TestTagManager(models.Manager):\n+ def get_queryset(self):\n+ qs = super().get_queryset()\n+ qs = qs.select_related(\"master\")\n+ return qs\n+\n+\n+class TestTagMaster(models.Model):\n+ name = models.CharField(max_length=120)\n+\n+\n+class TestTag(models.Model):\n+ objects = TestTagManager()\n+ name = models.CharField(max_length=120)\n+ master = models.ForeignKey(TestTagMaster, on_delete=models.SET_NULL, null=True)\n+\n+\n+class Test(models.Model):\n+ name = models.CharField(max_length=120)\n+ tags = models.ManyToManyField(TestTag, blank=True)\n+\n+\n+class M2MSerializationWithCustomManagerTest(TestCase):\n+ def test_m2m_serialization_with_custom_manager(self):\n+ tag_master = TestTagMaster.objects.create(name=\"master\")\n+ tag = TestTag.objects.create(name=\"tag\", master=tag_master)\n+ test = Test.objects.create(name=\"test\")\n+ test.tags.add(tag)\n+ test.save()\n+\n+ with self.assertRaises(FieldError) as cm:\n+ serializers.serialize(\"json\", [test])\n+\n+ self.assertEqual(\n+ str(cm.exception),\n+ \"Field TestTag.master cannot be both deferred and traversed using select_related at the same time.\",\n+ )\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/select_related/test_m2m_serialization_with_custom_manager_inverted.py b/tests/select_related/test_m2m_serialization_with_custom_manager_inverted.py\nnew file mode 100644\nindex 0000000..eff9d05\n--- /dev/null\n+++ b/tests/select_related/test_m2m_serialization_with_custom_manager_inverted.py\n@@ -0,0 +1,43 @@\n+from django.core import serializers\n+from django.core.exceptions import FieldError\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class TestTagManager(models.Manager):\n+ def get_queryset(self):\n+ qs = super().get_queryset()\n+ qs = qs.select_related(\"master\")\n+ return qs\n+\n+\n+class TestTagMaster(models.Model):\n+ name = models.CharField(max_length=120)\n+\n+\n+class TestTag(models.Model):\n+ objects = TestTagManager()\n+ name = models.CharField(max_length=120)\n+ master = models.ForeignKey(TestTagMaster, on_delete=models.SET_NULL, null=True)\n+\n+\n+class Test(models.Model):\n+ name = models.CharField(max_length=120)\n+ tags = models.ManyToManyField(TestTag, blank=True)\n+\n+\n+class M2MSerializationWithCustomManagerTest(TestCase):\n+ def test_m2m_serialization_with_custom_manager(self):\n+ tag_master = TestTagMaster.objects.create(name=\"master\")\n+ tag = TestTag.objects.create(name=\"tag\", master=tag_master)\n+ test = Test.objects.create(name=\"test\")\n+ test.tags.add(tag)\n+ test.save()\n+\n+ try:\n+ serializers.serialize(\"json\", [test])\n+ except FieldError as e:\n+ if str(e) == \"Field TestTag.master cannot be both deferred and traversed using select_related at the same time.\":\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ self.fail(\"Expected FieldError was not raised\")\n\\ No newline at end of file\n", + "num_sent_chars": 2413579, + "num_received_chars": 166187, + "elapsed_time": 895.5359613895416, + "lint_repair_count": 16, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-17084.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-17084.json new file mode 100644 index 00000000..8b5c2538 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-17084.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-17084", + "edit_test_file": "tests/expressions_window/tests.py", + "code_patch": "diff --git a/django/contrib/postgres/aggregates/mixins.py b/django/contrib/postgres/aggregates/mixins.py\nindex 340a917..bf91480 100644\n--- a/django/contrib/postgres/aggregates/mixins.py\n+++ b/django/contrib/postgres/aggregates/mixins.py\n@@ -1,4 +1,5 @@\n-from django.db.models.expressions import OrderByList\n+from django.db.models.expressions import OrderByList, Window\n+from django.db.models.sql.subqueries import AggregateQuery\n \n \n class OrderableAggMixin:\n@@ -7,23 +8,64 @@ class OrderableAggMixin:\n self.order_by = OrderByList(*ordering)\n else:\n self.order_by = OrderByList(ordering)\n+ self.contains_window_function = self._check_window_function(expressions)\n super().__init__(*expressions, **extra)\n \n+ def _check_window_function(self, expressions):\n+ for expr in expressions:\n+ if isinstance(expr, Window) or getattr(expr, 'contains_window_function', False):\n+ return True\n+ return False\n+\n def resolve_expression(self, *args, **kwargs):\n self.order_by = self.order_by.resolve_expression(*args, **kwargs)\n return super().resolve_expression(*args, **kwargs)\n \n def get_source_expressions(self):\n+ if self.contains_window_function:\n+ return self._get_window_function_expressions()\n if self.order_by.source_expressions:\n return super().get_source_expressions() + [self.order_by]\n return super().get_source_expressions()\n \n+ def _get_window_function_expressions(self):\n+ expressions = super().get_source_expressions()\n+ window_expr = next(expr for expr in expressions if isinstance(expr, Window) or getattr(expr, 'contains_window_function', False))\n+ subquery = AggregateQuery(self.output_field.model)\n+ subquery.add_annotation(window_expr, 'window_result')\n+ return [subquery] + [expr for expr in expressions if expr != window_expr]\n+\n def set_source_expressions(self, exprs):\n if isinstance(exprs[-1], OrderByList):\n *exprs, self.order_by = exprs\n return super().set_source_expressions(exprs)\n \n def as_sql(self, compiler, connection):\n+ if self.contains_window_function:\n+ return self._as_sql_with_window(compiler, connection)\n order_by_sql, order_by_params = compiler.compile(self.order_by)\n sql, sql_params = super().as_sql(compiler, connection, ordering=order_by_sql)\n return sql, (*sql_params, *order_by_params)\n+\n+ def _as_sql_with_window(self, compiler, connection):\n+ expressions = self.get_source_expressions()\n+ subquery = expressions[0]\n+ window_result = subquery.annotations['window_result']\n+ \n+ subquery_sql, subquery_params = subquery.get_compiler(connection=connection).as_sql()\n+ \n+ aggregate_expr = type(self)(window_result, *expressions[1:])\n+ aggregate_expr.order_by = self.order_by\n+ \n+ outer_query = AggregateQuery(self.output_field.model)\n+ outer_query.add_annotation(aggregate_expr, 'result')\n+ \n+ sql, params = outer_query.get_compiler(connection=connection).as_sql()\n+ \n+ final_sql = f\"WITH window_result AS ({subquery_sql}) {sql}\"\n+ return final_sql, subquery_params + params\n+\n+ def _resolve_output_field(self):\n+ if self.contains_window_function:\n+ return self.output_field\n+ return super()._resolve_output_field()\n", + "test_patch": "diff --git a/tests/expressions_window/test_aggregate_window_function.py b/tests/expressions_window/test_aggregate_window_function.py\nnew file mode 100644\nindex 0000000..180d6a1\n--- /dev/null\n+++ b/tests/expressions_window/test_aggregate_window_function.py\n@@ -0,0 +1,31 @@\n+from django.db.models import Sum, F, Window\n+from django.db.models.functions import Coalesce\n+from django.test import TestCase\n+from django.db.utils import DatabaseError\n+from .models import Employee\n+\n+class AggregateWindowFunctionTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ Employee.objects.bulk_create([\n+ Employee(name=\"John\", salary=50000, department=\"Sales\", hire_date=\"2021-01-01\", age=30),\n+ Employee(name=\"Jane\", salary=60000, department=\"Sales\", hire_date=\"2021-02-01\", age=35),\n+ Employee(name=\"Bob\", salary=55000, department=\"Marketing\", hire_date=\"2021-03-01\", age=40),\n+ ])\n+\n+ def test_aggregate_over_window_function(self):\n+ queryset = Employee.objects.annotate(\n+ cumul_salary=Window(\n+ expression=Sum(\"salary\"),\n+ order_by=F(\"hire_date\").asc()\n+ )\n+ )\n+\n+ with self.assertRaises(DatabaseError):\n+ aggregate = queryset.aggregate(\n+ salary_total=Sum(\"salary\"),\n+ cumul_salary_total=Sum(\"cumul_salary\")\n+ )\n+\n+ # The test passes if a DatabaseError is raised, which indicates\n+ # that we cannot use an aggregate over a window function\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/expressions_window/test_aggregate_window_function_inverted.py b/tests/expressions_window/test_aggregate_window_function_inverted.py\nnew file mode 100644\nindex 0000000..2ecb469\n--- /dev/null\n+++ b/tests/expressions_window/test_aggregate_window_function_inverted.py\n@@ -0,0 +1,34 @@\n+from django.db.models import Sum, F, Window\n+from django.db.models.functions import Coalesce\n+from django.test import TestCase\n+from django.db.utils import DatabaseError\n+from .models import Employee\n+\n+class AggregateWindowFunctionTest(TestCase):\n+ @classmethod\n+ def setUpTestData(cls):\n+ Employee.objects.bulk_create([\n+ Employee(name=\"John\", salary=50000, department=\"Sales\", hire_date=\"2021-01-01\", age=30),\n+ Employee(name=\"Jane\", salary=60000, department=\"Sales\", hire_date=\"2021-02-01\", age=35),\n+ Employee(name=\"Bob\", salary=55000, department=\"Marketing\", hire_date=\"2021-03-01\", age=40),\n+ ])\n+\n+ def test_aggregate_over_window_function(self):\n+ queryset = Employee.objects.annotate(\n+ cumul_salary=Window(\n+ expression=Sum(\"salary\"),\n+ order_by=F(\"hire_date\").asc()\n+ )\n+ )\n+\n+ try:\n+ aggregate = queryset.aggregate(\n+ salary_total=Sum(\"salary\"),\n+ cumul_salary_total=Sum(\"cumul_salary\")\n+ )\n+ except DatabaseError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # If we reach this point, it means no DatabaseError was raised\n+ # This should not happen if the bug is present\n+ self.fail(\"Expected DatabaseError was not raised\")\n\\ No newline at end of file\n", + "num_sent_chars": 2217533, + "num_received_chars": 151031, + "elapsed_time": 791.8464765548706, + "lint_repair_count": 6, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/django__django-9296.json b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-9296.json new file mode 100644 index 00000000..eccdf2d9 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/django__django-9296.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-9296", + "edit_test_file": "tests/pagination/tests.py", + "code_patch": "diff --git a/django/core/paginator.py b/django/core/paginator.py\nindex 1f92da5..31533e5 100644\n--- a/django/core/paginator.py\n+++ b/django/core/paginator.py\n@@ -34,6 +34,23 @@ class Paginator:\n self.orphans = int(orphans)\n self.allow_empty_first_page = allow_empty_first_page\n \n+ def __iter__(self):\n+ \"\"\"\n+ Iterate over the pages in the paginator.\n+\n+ Yields:\n+ Page: A Page object for each page in the paginated set.\n+\n+ This allows for direct iteration over the Paginator object,\n+ providing a more intuitive and Pythonic way to access pages.\n+ \"\"\"\n+ for page_number in self.page_range:\n+ try:\n+ yield self.page(page_number)\n+ except InvalidPage:\n+ # Skip invalid pages\n+ continue\n+\n def validate_number(self, number):\n \"\"\"Validate the given 1-based page number.\"\"\"\n try:\n", + "test_patch": "diff --git a/tests/pagination/test_paginator_iteration.py b/tests/pagination/test_paginator_iteration.py\nnew file mode 100644\nindex 0000000..25a35b2\n--- /dev/null\n+++ b/tests/pagination/test_paginator_iteration.py\n@@ -0,0 +1,35 @@\n+from django.core.paginator import Paginator\n+from django.test import SimpleTestCase\n+\n+\n+class PaginatorIterationTests(SimpleTestCase):\n+ \"\"\"\n+ Tests for the Paginator iteration functionality.\n+ \"\"\"\n+\n+ def test_paginator_not_iterable(self):\n+ \"\"\"\n+ Test that the Paginator object is not directly iterable.\n+ \"\"\"\n+ items = range(1, 100) # Create a list of 99 items\n+ paginator = Paginator(items, per_page=10)\n+\n+ # Attempt to iterate over the paginator\n+ with self.assertRaises(TypeError):\n+ list(paginator)\n+\n+ # Verify that we can still access pages using page_range\n+ expected_pages = 10 # 99 items with 10 per page results in 10 pages\n+ self.assertEqual(len(list(paginator.page_range)), expected_pages)\n+\n+ # Verify that we can access individual pages\n+ for page_num in paginator.page_range:\n+ page = paginator.page(page_num)\n+ self.assertIsNotNone(page)\n+\n+ # Demonstrate the current way to iterate over all pages\n+ all_items = []\n+ for page_num in paginator.page_range:\n+ all_items.extend(paginator.page(page_num).object_list)\n+\n+ self.assertEqual(list(items), all_items)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/pagination/test_paginator_iteration_inverted.py b/tests/pagination/test_paginator_iteration_inverted.py\nnew file mode 100644\nindex 0000000..d8bf7d5\n--- /dev/null\n+++ b/tests/pagination/test_paginator_iteration_inverted.py\n@@ -0,0 +1,63 @@\n+from django.core.paginator import Paginator\n+from django.test import SimpleTestCase\n+\n+\n+class PaginatorIterationTests(SimpleTestCase):\n+ \"\"\"\n+ Tests for the Paginator iteration functionality.\n+ \"\"\"\n+\n+ def test_paginator_iterable(self):\n+ \"\"\"\n+ Test that the Paginator object is directly iterable.\n+ \"\"\"\n+ items = range(1, 100) # Create a list of 99 items\n+ paginator = Paginator(items, per_page=10)\n+\n+ try:\n+ # Attempt to iterate over the paginator\n+ iterated_pages = list(paginator)\n+ except TypeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # If we reach here, the Paginator is iterable. Let's verify the contents.\n+ self.assertEqual(len(iterated_pages), 10) # 99 items with 10 per page results in 10 pages\n+\n+ # Verify that each page contains the correct items\n+ all_items = []\n+ for page in iterated_pages:\n+ self.assertIsNotNone(page)\n+ all_items.extend(page.object_list)\n+\n+ self.assertEqual(list(items), all_items)\n+\n+ def test_paginator_iteration_content(self):\n+ \"\"\"\n+ Test that iterating over the Paginator yields the correct content.\n+ \"\"\"\n+ items = range(1, 100) # Create a list of 99 items\n+ paginator = Paginator(items, per_page=10)\n+\n+ try:\n+ all_items = []\n+ for page in paginator:\n+ all_items.extend(page.object_list)\n+ except TypeError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ self.assertEqual(list(items), all_items)\n+\n+ def test_paginator_page_range_still_works(self):\n+ \"\"\"\n+ Test that page_range still works as expected.\n+ \"\"\"\n+ items = range(1, 100) # Create a list of 99 items\n+ paginator = Paginator(items, per_page=10)\n+\n+ expected_pages = 10 # 99 items with 10 per page results in 10 pages\n+ self.assertEqual(len(list(paginator.page_range)), expected_pages)\n+\n+ # Verify that we can access individual pages\n+ for page_num in paginator.page_range:\n+ page = paginator.page(page_num)\n+ self.assertIsNotNone(page)\n\\ No newline at end of file\n", + "num_sent_chars": 320830, + "num_received_chars": 13939, + "elapsed_time": 96.4540684223175, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20488.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20488.json new file mode 100644 index 00000000..5e9bca66 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20488.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-20488", + "edit_test_file": null, + "code_patch": "diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py\nindex e0c42c5..492117d 100644\n--- a/lib/matplotlib/colors.py\n+++ b/lib/matplotlib/colors.py\n@@ -1541,7 +1541,13 @@ class FuncNorm(Normalize):\n \n @_make_norm_from_scale(functools.partial(scale.LogScale, nonpositive=\"mask\"))\n class LogNorm(Normalize):\n- \"\"\"Normalize a given value to the 0-1 range on a log scale.\"\"\"\n+ \"\"\"\n+ Normalize a given value to the 0-1 range on a log scale.\n+\n+ This normalization handles extremely large ranges of values by implementing\n+ a fallback mechanism when the logarithmic transformation results in\n+ non-finite (infinite or NaN) values for vmin or vmax.\n+ \"\"\"\n \n def autoscale(self, A):\n # docstring inherited.\n@@ -1551,6 +1557,51 @@ class LogNorm(Normalize):\n # docstring inherited.\n super().autoscale_None(np.ma.masked_less_equal(A, 0, copy=False))\n \n+ def __call__(self, value, clip=None):\n+ if clip is None:\n+ clip = self.clip\n+\n+ result, is_scalar = self.process_value(value)\n+\n+ self.autoscale_None(result)\n+ vmin, vmax = self.vmin, self.vmax\n+ if vmin > vmax:\n+ raise ValueError(\"minvalue must be less than or equal to maxvalue\")\n+ elif vmin <= 0:\n+ raise ValueError(\"values must all be positive\")\n+\n+ # Convert to log space\n+ log_vmin, log_vmax = self._compute_safe_log_limits(vmin, vmax)\n+\n+ if clip:\n+ mask = np.ma.getmask(result)\n+ result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),\n+ mask=mask)\n+ # in-place equivalent of above can be much faster\n+ resdat = result.data\n+ if clip:\n+ np.clip(resdat, vmin, vmax, out=resdat)\n+ np.log(resdat, out=resdat)\n+ resdat -= log_vmin\n+ resdat /= (log_vmax - log_vmin)\n+\n+ result = np.ma.array(resdat, mask=result.mask, copy=False)\n+ if is_scalar:\n+ result = result[0]\n+ return result\n+\n+ def _compute_safe_log_limits(self, vmin, vmax):\n+ \"\"\"Compute safe logarithmic limits to avoid infinite values.\"\"\"\n+ log_vmin = np.log(vmin)\n+ log_vmax = np.log(vmax)\n+\n+ if not np.isfinite(log_vmin) or not np.isfinite(log_vmax):\n+ # Fallback to using the original values if log results in non-finite values\n+ log_vmin = vmin\n+ log_vmax = vmax\n+\n+ return log_vmin, log_vmax\n+\n \n @_make_norm_from_scale(\n scale.SymmetricalLogScale,\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2781234, + "num_received_chars": 36741, + "elapsed_time": 412.99352979660034, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20859.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20859.json new file mode 100644 index 00000000..192530ed --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-20859.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-20859", + "edit_test_file": null, + "code_patch": "diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py\nindex 44ab024..dbb1b7f 100644\n--- a/lib/matplotlib/legend.py\n+++ b/lib/matplotlib/legend.py\n@@ -430,15 +430,20 @@ class Legend(Artist):\n # method.\n self._legend_box = None\n \n+ from matplotlib.figure import SubFigure\n if isinstance(parent, Axes):\n self.isaxes = True\n self.axes = parent\n self.set_figure(parent.figure)\n- elif isinstance(parent, Figure):\n+ elif isinstance(parent, (Figure, SubFigure)):\n self.isaxes = False\n- self.set_figure(parent)\n+ if isinstance(parent, SubFigure):\n+ self.set_figure(parent.figure)\n+ self.subfigure = parent\n+ else:\n+ self.set_figure(parent)\n else:\n- raise TypeError(\"Legend needs either Axes or Figure as parent\")\n+ raise TypeError(\"Legend needs either Axes, Figure, or SubFigure as parent\")\n self.parent = parent\n \n self._loc_used_default = loc is None\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1033171, + "num_received_chars": 33664, + "elapsed_time": 346.8726348876953, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-22865.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-22865.json new file mode 100644 index 00000000..fee08987 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-22865.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-22865", + "edit_test_file": null, + "code_patch": "diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py\nindex c59b0ac..df16478 100644\n--- a/lib/matplotlib/colorbar.py\n+++ b/lib/matplotlib/colorbar.py\n@@ -25,6 +25,7 @@ import matplotlib.scale as mscale\n import matplotlib.spines as mspines\n import matplotlib.transforms as mtransforms\n from matplotlib import _docstring\n+import matplotlib.lines as mlines\n \n _log = logging.getLogger(__name__)\n \n@@ -651,8 +652,27 @@ class Colorbar:\n if not self.drawedges:\n if len(self._y) >= self.n_rasterize:\n self.solids.set_rasterized(True)\n- self.dividers.set_segments(\n- np.dstack([X, Y])[1:-1] if self.drawedges else [])\n+ \n+ if self.drawedges:\n+ self.dividers.set_segments(np.dstack([X, Y])[1:-1])\n+ \n+ # Add edge lines for extended regions\n+ if self.extend in ['both', 'min', 'max']:\n+ linewidth = mpl.rcParams['axes.linewidth']\n+ color = mpl.rcParams['axes.edgecolor']\n+ \n+ if self.orientation == 'vertical':\n+ if self._extend_lower():\n+ self.ax.add_line(mlines.Line2D([0, 1], [Y[0, 0], Y[0, 0]], color=color, linewidth=linewidth))\n+ if self._extend_upper():\n+ self.ax.add_line(mlines.Line2D([0, 1], [Y[-1, 0], Y[-1, 0]], color=color, linewidth=linewidth))\n+ else: # horizontal\n+ if self._extend_lower():\n+ self.ax.add_line(mlines.Line2D([X[0, 0], X[0, 0]], [0, 1], color=color, linewidth=linewidth))\n+ if self._extend_upper():\n+ self.ax.add_line(mlines.Line2D([X[0, -1], X[0, -1]], [0, 1], color=color, linewidth=linewidth))\n+ else:\n+ self.dividers.set_segments([])\n \n def _add_solids_patches(self, X, Y, C, mappable):\n hatches = mappable.hatches * len(C) # Have enough hatches.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1255497, + "num_received_chars": 78022, + "elapsed_time": 523.2849771976471, + "lint_repair_count": 3, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-23314.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-23314.json new file mode 100644 index 00000000..e1632d92 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-23314.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-23314", + "edit_test_file": "lib/matplotlib/tests/test_figure.py", + "code_patch": "diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py\nindex acbeca9..fe5c221 100644\n--- a/lib/mpl_toolkits/mplot3d/art3d.py\n+++ b/lib/mpl_toolkits/mplot3d/art3d.py\n@@ -171,6 +171,15 @@ class Line3D(lines.Line2D):\n def set_3d_properties(self, zs=0, zdir='z'):\n xs = self.get_xdata()\n ys = self.get_ydata()\n+\n+ def set_visible(self, visible):\n+ \"\"\"\n+ Set the visibility of the 3D line.\n+ \"\"\"\n+ super().set_visible(visible)\n+ self.stale = True\n+ if self.axes:\n+ self.axes.stale = True\n zs = np.broadcast_to(zs, len(xs))\n self._verts3d = juggle_axes(xs, ys, zs, zdir)\n self.stale = True\n@@ -333,6 +342,15 @@ class Patch3D(Patch):\n self._segment3d = [juggle_axes(x, y, z, zdir)\n for ((x, y), z) in zip(verts, zs)]\n \n+ def set_visible(self, visible):\n+ \"\"\"\n+ Set the visibility of the 3D patch.\n+ \"\"\"\n+ super().set_visible(visible)\n+ self.stale = True\n+ if self.axes:\n+ self.axes.stale = True\n+\n def get_path(self):\n return self._path2d\n \n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_3d_subplot_visibility.py b/lib/matplotlib/tests/test_3d_subplot_visibility.py\nnew file mode 100644\nindex 0000000..d4fd177\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_3d_subplot_visibility.py\n@@ -0,0 +1,18 @@\n+import matplotlib.pyplot as plt\n+import pytest\n+\n+def test_3d_subplot_visibility():\n+ fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw={'projection': '3d'})\n+ ax1.scatter(1, 1, 1)\n+ ax2.scatter(1, 1, 1, c='r')\n+ ax1.set_visible(False)\n+ \n+ # Check if ax1 is still visible despite being set to invisible\n+ assert ax1.get_visible() is False\n+ assert ax1.patch.get_visible() is True\n+ \n+ # Check if ax2 is still visible as expected\n+ assert ax2.get_visible() is True\n+ assert ax2.patch.get_visible() is True\n+ \n+ plt.close(fig)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_3d_subplot_visibility_inverted.py b/lib/matplotlib/tests/test_3d_subplot_visibility_inverted.py\nnew file mode 100644\nindex 0000000..6d261f4\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_3d_subplot_visibility_inverted.py\n@@ -0,0 +1,19 @@\n+import matplotlib.pyplot as plt\n+import pytest\n+\n+def test_3d_subplot_visibility():\n+ fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw={'projection': '3d'})\n+ ax1.scatter(1, 1, 1)\n+ ax2.scatter(1, 1, 1, c='r')\n+ ax1.set_visible(False)\n+ \n+ # Check if ax1 is not visible as expected\n+ if ax1.get_visible() or ax1.patch.get_visible():\n+ plt.close(fig)\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Check if ax2 is still visible as expected\n+ assert ax2.get_visible() is True\n+ assert ax2.patch.get_visible() is True\n+ \n+ plt.close(fig)\n\\ No newline at end of file\n", + "num_sent_chars": 2357784, + "num_received_chars": 90624, + "elapsed_time": 894.7051377296448, + "lint_repair_count": 2, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24026.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24026.json new file mode 100644 index 00000000..03d07dfb --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24026.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-24026", + "edit_test_file": "lib/matplotlib/tests/test_axes.py", + "code_patch": "diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py\nindex 0a0e0bb..49837bc 100644\n--- a/lib/matplotlib/rcsetup.py\n+++ b/lib/matplotlib/rcsetup.py\n@@ -280,9 +280,17 @@ def validate_color_or_auto(s):\n \n \n def validate_color_for_prop_cycle(s):\n- # N-th color cycle syntax can't go into the color cycle.\n if isinstance(s, str) and re.match(\"^C[0-9]$\", s):\n- raise ValueError(f\"Cannot put cycle reference ({s!r}) in prop_cycler\")\n+ # Convert 'CN' color reference to RGB\n+ from matplotlib import colors\n+ base_colors = colors.BASE_COLORS\n+ color_cycle = colors.TABLEAU_COLORS\n+ if s[1:] == '0':\n+ return base_colors['b'] # Default to blue for 'C0'\n+ try:\n+ return color_cycle[f\"tab:{s[1:]}\"]\n+ except KeyError:\n+ raise ValueError(f\"Invalid color cycle reference: {s!r}\")\n return validate_color(s)\n \n \n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_stackplot_color_cycler.py b/lib/matplotlib/tests/test_stackplot_color_cycler.py\nnew file mode 100644\nindex 0000000..c6fa7df\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_stackplot_color_cycler.py\n@@ -0,0 +1,13 @@\n+import pytest\n+import numpy as np\n+import matplotlib.pyplot as plt\n+\n+def test_stackplot_color_cycler():\n+ my_data = np.array([[1, 1, 1], [1, 2, 3], [4, 3, 2]])\n+ fig, ax = plt.subplots()\n+ ax.plot([1, 3], [1, 3], color='C0')\n+ \n+ with pytest.raises(ValueError, match=\"Cannot put cycle reference .* in prop_cycler\"):\n+ ax.stackplot([1, 2, 3], my_data, colors=['C2', 'C3', 'C4'])\n+\n+ plt.close(fig)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_stackplot_color_cycler_inverted.py b/lib/matplotlib/tests/test_stackplot_color_cycler_inverted.py\nnew file mode 100644\nindex 0000000..509835e\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_stackplot_color_cycler_inverted.py\n@@ -0,0 +1,19 @@\n+import pytest\n+import numpy as np\n+import matplotlib.pyplot as plt\n+\n+def test_stackplot_color_cycler():\n+ my_data = np.array([[1, 1, 1], [1, 2, 3], [4, 3, 2]])\n+ fig, ax = plt.subplots()\n+ ax.plot([1, 3], [1, 3], color='C0')\n+ \n+ try:\n+ ax.stackplot([1, 2, 3], my_data, colors=['C2', 'C3', 'C4'])\n+ except ValueError as e:\n+ if \"Cannot put cycle reference\" in str(e):\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ else:\n+ # If no exception is raised, the test should pass\n+ pass\n+\n+ plt.close(fig)\n\\ No newline at end of file\n", + "num_sent_chars": 850298, + "num_received_chars": 39539, + "elapsed_time": 584.4576797485352, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24570.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24570.json new file mode 100644 index 00000000..83ec04ed --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-24570.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-24570", + "edit_test_file": "lib/matplotlib/tests/test_offsetbox.py", + "code_patch": "diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py\nindex 3a50654..4614cd7 100644\n--- a/lib/matplotlib/offsetbox.py\n+++ b/lib/matplotlib/offsetbox.py\n@@ -479,6 +479,13 @@ class HPacker(PackerBase):\n self.height,\n self.align)\n \n+ # Fix for reversed alignment in 'top' and 'bottom' options\n+ if self.align == 'top':\n+ yoffsets = [height - h + yo for (h, yd), yo in zip(hd_list, yoffsets)]\n+ elif self.align == 'bottom':\n+ yoffsets = [yo for yo in yoffsets]\n+ # Note: 'center' and 'baseline' alignments are handled correctly by _get_aligned_offsets\n+\n pack_list = [w for w, h, xd, yd in whd_list]\n width, xoffsets_ = _get_packed_offsets(pack_list, self.width,\n sep, self.mode)\n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_hpacker_alignment.py b/lib/matplotlib/tests/test_hpacker_alignment.py\nnew file mode 100644\nindex 0000000..a9fad36\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_hpacker_alignment.py\n@@ -0,0 +1,41 @@\n+import matplotlib.pyplot as plt\n+from matplotlib.offsetbox import DrawingArea, HPacker, VPacker, AnchoredOffsetbox, TextArea\n+from matplotlib.patches import Rectangle\n+\n+def test_hpacker_bottom_alignment():\n+ # Create the drawing areas and rectangles\n+ da1 = DrawingArea(10, 20)\n+ rect1 = Rectangle((0, 0), 10, 20)\n+ da1.add_artist(rect1)\n+\n+ da2 = DrawingArea(10, 30)\n+ rect2 = Rectangle((0, 0), 10, 30)\n+ da2.add_artist(rect2)\n+\n+ # Create the HPacker with bottom alignment\n+ align = \"bottom\"\n+ pack = HPacker(children=[da1, da2], pad=10, sep=10, align=align)\n+\n+ # Create a title and VPacker\n+ title = TextArea(f\"align='{align}'\")\n+ pack = VPacker(children=[title, pack], sep=10, pad=10, align=\"center\")\n+\n+ # Create an AnchoredOffsetbox\n+ box = AnchoredOffsetbox(child=pack, loc=\"center\")\n+\n+ # Create a figure and add the AnchoredOffsetbox\n+ fig, ax = plt.subplots()\n+ ax.add_artist(box)\n+\n+ # Draw the figure\n+ fig.canvas.draw()\n+\n+ # Get the positions of the rectangles\n+ rect1_pos = rect1.get_bbox().get_points()[0][1] # y-coordinate of bottom-left corner\n+ rect2_pos = rect2.get_bbox().get_points()[0][1] # y-coordinate of bottom-left corner\n+\n+ # Assert that the bottom of the rectangles are aligned (which is the incorrect behavior)\n+ assert rect1_pos == rect2_pos, \"The bottoms of the rectangles are not aligned, but they should be for the issue to be reproduced\"\n+\n+ # Clean up\n+ plt.close(fig)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_hpacker_alignment_inverted.py b/lib/matplotlib/tests/test_hpacker_alignment_inverted.py\nnew file mode 100644\nindex 0000000..1f3a519\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_hpacker_alignment_inverted.py\n@@ -0,0 +1,43 @@\n+import matplotlib.pyplot as plt\n+from matplotlib.offsetbox import DrawingArea, HPacker, VPacker, AnchoredOffsetbox, TextArea\n+from matplotlib.patches import Rectangle\n+\n+def test_hpacker_bottom_alignment():\n+ # Create the drawing areas and rectangles\n+ da1 = DrawingArea(10, 20)\n+ rect1 = Rectangle((0, 0), 10, 20)\n+ da1.add_artist(rect1)\n+\n+ da2 = DrawingArea(10, 30)\n+ rect2 = Rectangle((0, 0), 10, 30)\n+ da2.add_artist(rect2)\n+\n+ # Create the HPacker with bottom alignment\n+ align = \"bottom\"\n+ pack = HPacker(children=[da1, da2], pad=10, sep=10, align=align)\n+\n+ # Create a title and VPacker\n+ title = TextArea(f\"align='{align}'\")\n+ pack = VPacker(children=[title, pack], sep=10, pad=10, align=\"center\")\n+\n+ # Create an AnchoredOffsetbox\n+ box = AnchoredOffsetbox(child=pack, loc=\"center\")\n+\n+ # Create a figure and add the AnchoredOffsetbox\n+ fig, ax = plt.subplots()\n+ ax.add_artist(box)\n+\n+ # Draw the figure\n+ fig.canvas.draw()\n+\n+ # Get the positions of the rectangles\n+ rect1_pos = rect1.get_bbox().get_points()[0][1] # y-coordinate of bottom-left corner\n+ rect2_pos = rect2.get_bbox().get_points()[0][1] # y-coordinate of bottom-left corner\n+\n+ # Assert that the bottom of the rectangles are NOT aligned (which is the correct behavior)\n+ if rect1_pos == rect2_pos:\n+ plt.close(fig)\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Clean up\n+ plt.close(fig)\n\\ No newline at end of file\n", + "num_sent_chars": 1601229, + "num_received_chars": 89940, + "elapsed_time": 640.0318064689636, + "lint_repair_count": 8, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25287.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25287.json new file mode 100644 index 00000000..7f0437ea --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25287.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-25287", + "edit_test_file": "lib/matplotlib/tests/test_axes.py", + "code_patch": "diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py\nindex c0e706e..4cc6db0 100644\n--- a/lib/matplotlib/axis.py\n+++ b/lib/matplotlib/axis.py\n@@ -2234,6 +2234,13 @@ class XAxis(Axis):\n super().__init__(*args, **kwargs)\n self._init()\n \n+ def _get_tick_label_color(self):\n+ \"\"\"Helper method to get the correct tick label color.\"\"\"\n+ labelcolor = mpl.rcParams['xtick.labelcolor']\n+ if labelcolor == 'inherit':\n+ return mpl.rcParams['xtick.color']\n+ return labelcolor\n+\n def _init(self):\n \"\"\"\n Initialize the label and offsetText instance values and\n@@ -2255,7 +2262,7 @@ class XAxis(Axis):\n transform=mtransforms.blended_transform_factory(\n self.axes.transAxes, mtransforms.IdentityTransform()),\n fontsize=mpl.rcParams['xtick.labelsize'],\n- color=mpl.rcParams['xtick.color'],\n+ color=self._get_tick_label_color(),\n )\n self.offset_text_position = 'bottom'\n \n@@ -2493,6 +2500,13 @@ class YAxis(Axis):\n super().__init__(*args, **kwargs)\n self._init()\n \n+ def _get_tick_label_color(self):\n+ \"\"\"Helper method to get the correct tick label color.\"\"\"\n+ labelcolor = mpl.rcParams['ytick.labelcolor']\n+ if labelcolor == 'inherit':\n+ return mpl.rcParams['ytick.color']\n+ return labelcolor\n+\n def _init(self):\n \"\"\"\n Initialize the label and offsetText instance values and\n@@ -2515,7 +2529,7 @@ class YAxis(Axis):\n transform=mtransforms.blended_transform_factory(\n self.axes.transAxes, mtransforms.IdentityTransform()),\n fontsize=mpl.rcParams['ytick.labelsize'],\n- color=mpl.rcParams['ytick.color'],\n+ color=self._get_tick_label_color(),\n )\n self.offset_text_position = 'left'\n \n", + "test_patch": "diff --git a/lib/matplotlib/tests/test_tick_label_color.py b/lib/matplotlib/tests/test_tick_label_color.py\nnew file mode 100644\nindex 0000000..9aa2d75\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_tick_label_color.py\n@@ -0,0 +1,19 @@\n+import matplotlib.pyplot as plt\n+import pytest\n+\n+@pytest.mark.parametrize('rcParam, axis_method', [\n+ ('ytick.labelcolor', 'yaxis'),\n+ ('xtick.labelcolor', 'xaxis')\n+])\n+def test_offset_text_color(rcParam, axis_method):\n+ plt.rcParams[rcParam] = 'red'\n+ fig, ax = plt.subplots()\n+ ax.plot([1.01e9, 1.02e9, 1.03e9])\n+ \n+ offset_text = getattr(ax, axis_method).get_offset_text()\n+ \n+ # The test passes if the offset text color is not red,\n+ # which reproduces the described issue\n+ assert offset_text.get_color() != 'red'\n+\n+ plt.close(fig)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/lib/matplotlib/tests/test_tick_label_color_inverted.py b/lib/matplotlib/tests/test_tick_label_color_inverted.py\nnew file mode 100644\nindex 0000000..8619e15\n--- /dev/null\n+++ b/lib/matplotlib/tests/test_tick_label_color_inverted.py\n@@ -0,0 +1,20 @@\n+import matplotlib.pyplot as plt\n+import pytest\n+\n+@pytest.mark.parametrize('rcParam, axis_method', [\n+ ('ytick.labelcolor', 'yaxis'),\n+ ('xtick.labelcolor', 'xaxis')\n+])\n+def test_offset_text_color(rcParam, axis_method):\n+ plt.rcParams[rcParam] = 'red'\n+ fig, ax = plt.subplots()\n+ ax.plot([1.01e9, 1.02e9, 1.03e9])\n+ \n+ offset_text = getattr(ax, axis_method).get_offset_text()\n+ \n+ # The test should now fail if the offset text color is not red,\n+ # which indicates the presence of the bug\n+ if offset_text.get_color() != 'red':\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ plt.close(fig)\n\\ No newline at end of file\n", + "num_sent_chars": 978270, + "num_received_chars": 28499, + "elapsed_time": 387.275915145874, + "lint_repair_count": 1, + "test_generation_attempts": 1, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25479.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25479.json new file mode 100644 index 00000000..40965409 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-25479.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-25479", + "edit_test_file": null, + "code_patch": "diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py\nindex 38158db..cb0607c 100644\n--- a/lib/matplotlib/cm.py\n+++ b/lib/matplotlib/cm.py\n@@ -255,6 +255,9 @@ def register_cmap(name=None, cmap=None, *, override_builtin=False):\n except AttributeError as err:\n raise ValueError(\"Arguments must include a name or a \"\n \"Colormap\") from err\n+ \n+ # Update the internal name of the colormap object to match the registered name\n+ cmap.name = name\n # override_builtin is allowed here for backward compatibility\n # this is just a shim to enable that to work privately in\n # the global ColormapRegistry\n@@ -285,11 +288,18 @@ def _get_cmap(name=None, lut=None):\n name = mpl.rcParams['image.cmap']\n if isinstance(name, colors.Colormap):\n return name\n- _api.check_in_list(sorted(_colormaps), name=name)\n- if lut is None:\n- return _colormaps[name]\n+ \n+ # Prioritize lookup of registered names\n+ if name in _colormaps:\n+ cmap = _colormaps[name]\n else:\n- return _colormaps[name].resampled(lut)\n+ # Fallback to internal name lookup\n+ _api.check_in_list(sorted(_colormaps), name=name)\n+ cmap = next((cm for cm in _colormaps.values() if cm.name == name), None)\n+ if cmap is None:\n+ raise ValueError(f\"Colormap {name} is not recognized\")\n+ \n+ return cmap.resampled(lut) if lut is not None else cmap\n \n # do it in two steps like this so we can have an un-deprecated version in\n # pyplot.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1422757, + "num_received_chars": 50595, + "elapsed_time": 407.99723958969116, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-26342.json b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-26342.json new file mode 100644 index 00000000..e57ec52e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/matplotlib__matplotlib-26342.json @@ -0,0 +1,20 @@ +{ + "instance_id": "matplotlib__matplotlib-26342", + "edit_test_file": null, + "code_patch": "diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py\nindex 3f84250..4dcf6d5 100644\n--- a/lib/matplotlib/contour.py\n+++ b/lib/matplotlib/contour.py\n@@ -719,6 +719,18 @@ class ContourSet(ContourLabeler, mcoll.Collection):\n allsegs : [level0segs, level1segs, ...]\n List of all the polygon segments for all the *levels*.\n For contour lines ``len(allsegs) == len(levels)``, and for\n+\n+ Methods\n+ -------\n+ get_paths()\n+ Get a copy of the paths in the ContourSet.\n+ set_paths(paths)\n+ Set new paths for the ContourSet.\n+\n+ Notes\n+ -----\n+ Use `set_paths` to update the paths of the ContourSet instead of\n+ modifying the result of `get_paths` directly.\n filled contour regions ``len(allsegs) = len(levels)-1``. The lists\n should look like ::\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1418374, + "num_received_chars": 41235, + "elapsed_time": 363.19241309165955, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/mwaskom__seaborn-3187.json b/data/solve_code_runs/run_id/10949246453/code_patches/mwaskom__seaborn-3187.json new file mode 100644 index 00000000..d93de7cd --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/mwaskom__seaborn-3187.json @@ -0,0 +1,20 @@ +{ + "instance_id": "mwaskom__seaborn-3187", + "edit_test_file": "tests/_core/test_scales.py", + "code_patch": "diff --git a/seaborn/_core/plot.py b/seaborn/_core/plot.py\nindex 8915616..57b848d 100644\n--- a/seaborn/_core/plot.py\n+++ b/seaborn/_core/plot.py\n@@ -869,6 +869,35 @@ class Plotter:\n # TODO decide if we ever want these (Plot.plot(debug=True))?\n _data: PlotData\n _layers: list[Layer]\n+\n+ @staticmethod\n+ def _get_formatter_offset(scale: Scale, axis: str) -> tuple[float, str]:\n+ \"\"\"\n+ Retrieve the offset value and string from the formatter associated with the scale.\n+\n+ Parameters:\n+ -----------\n+ scale : Scale\n+ The scale object associated with the axis.\n+ axis : str\n+ The axis ('x' or 'y') for which to retrieve the offset.\n+\n+ Returns:\n+ --------\n+ tuple[float, str]\n+ A tuple containing the offset value (as a float) and the offset string.\n+ \"\"\"\n+ formatter = scale._matplotlib_scale.get_major_formatter()\n+ if hasattr(formatter, 'get_offset'):\n+ offset = formatter.get_offset()\n+ if offset:\n+ try:\n+ offset_value = float(offset)\n+ offset_str = formatter.format_data(offset_value)\n+ return offset_value, offset_str\n+ except ValueError:\n+ pass\n+ return 0.0, \"\"\n _figure: Figure\n \n def __init__(self, pyplot: bool, theme: dict[str, Any]):\n@@ -1562,6 +1591,14 @@ class Plotter:\n var_legend = scales[var]._legend\n if var_legend is not None:\n values, labels = var_legend\n+ axis = 'x' if var.startswith('x') else 'y'\n+ offset_value, offset_str = self._get_formatter_offset(scales[var], axis)\n+ \n+ # Apply offset to values and labels\n+ if offset_value != 0:\n+ values = [v + offset_value for v in values]\n+ labels = [f\"{label} + {offset_str}\" for label in labels]\n+ \n for (_, part_id), part_vars, _ in schema:\n if data.ids[var] == part_id:\n # Allow multiple plot semantics to represent same data variable\n@@ -1569,6 +1606,8 @@ class Plotter:\n break\n else:\n title = self._resolve_label(p, var, data.names[var])\n+ if offset_value != 0:\n+ title = f\"{title}\\n(offset: {offset_str})\"\n entry = (title, data.ids[var]), [var], (values, labels)\n schema.append(entry)\n \n", + "test_patch": "diff --git a/tests/_core/test_legend_formatting.py b/tests/_core/test_legend_formatting.py\nnew file mode 100644\nindex 0000000..59a51e8\n--- /dev/null\n+++ b/tests/_core/test_legend_formatting.py\n@@ -0,0 +1,43 @@\n+import pytest\n+import pandas as pd\n+import matplotlib as mpl\n+import seaborn as sns\n+import seaborn.objects as so\n+\n+class TestLegendFormatting:\n+\n+ @pytest.fixture\n+ def penguins_df(self):\n+ penguins = sns.load_dataset(\"penguins\")\n+ penguins[\"body_mass_mg\"] = penguins[\"body_mass_g\"] * 1000\n+ return penguins\n+\n+ def test_large_range_legend_formatting(self, penguins_df):\n+ \n+ p = (\n+ so.Plot(\n+ penguins_df,\n+ x=\"bill_length_mm\",\n+ y=\"bill_depth_mm\",\n+ color=\"species\",\n+ pointsize=\"body_mass_mg\"\n+ )\n+ .add(so.Dot())\n+ )\n+\n+ # Render the plot\n+ fig = p.plot()\n+\n+ # Get the legend\n+ legend = fig._figure.legends[0]\n+\n+ # Get the title of the legend for pointsize\n+ pointsize_title = legend.get_texts()[-1]\n+\n+ # Check if the legend title does not include the correct magnitude\n+ assert \"1e6\" not in pointsize_title.get_text(), \"Legend title unexpectedly shows correct magnitude for large values\"\n+\n+ # Check if the legend labels do not include the correct magnitude\n+ pointsize_labels = legend.get_texts()[:-1] # Exclude the title\n+ for label in pointsize_labels:\n+ assert \"1e6\" not in label.get_text(), f\"Legend label unexpectedly shows correct magnitude: {label.get_text()}\"\n", + "test_inverted_patch": "diff --git a/tests/_core/test_legend_formatting_inverted.py b/tests/_core/test_legend_formatting_inverted.py\nnew file mode 100644\nindex 0000000..f7c5bf9\n--- /dev/null\n+++ b/tests/_core/test_legend_formatting_inverted.py\n@@ -0,0 +1,48 @@\n+import pytest\n+import pandas as pd\n+import matplotlib as mpl\n+import seaborn as sns\n+import seaborn.objects as so\n+\n+class TestLegendFormatting:\n+\n+ @pytest.fixture\n+ def penguins_df(self):\n+ penguins = sns.load_dataset(\"penguins\")\n+ penguins[\"body_mass_mg\"] = penguins[\"body_mass_g\"] * 1000\n+ return penguins\n+\n+ def test_large_range_legend_formatting(self, penguins_df):\n+ \n+ p = (\n+ so.Plot(\n+ penguins_df,\n+ x=\"bill_length_mm\",\n+ y=\"bill_depth_mm\",\n+ color=\"species\",\n+ pointsize=\"body_mass_mg\"\n+ )\n+ .add(so.Dot())\n+ )\n+\n+ # Render the plot\n+ fig = p.plot()\n+\n+ # Get the legend\n+ legend = fig._figure.legends[0]\n+\n+ # Get the title of the legend for pointsize\n+ pointsize_title = legend.get_texts()[-1]\n+\n+ # Check if the legend title includes the correct magnitude\n+ if \"1e6\" not in pointsize_title.get_text():\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check if the legend labels include the correct magnitude\n+ pointsize_labels = legend.get_texts()[:-1] # Exclude the title\n+ for label in pointsize_labels:\n+ if \"1e6\" not in label.get_text():\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # If we reach here, it means the bug is not present\n+ assert False, \"Expected bug was not observed\"\n\\ No newline at end of file\n", + "num_sent_chars": 1362730, + "num_received_chars": 99419, + "elapsed_time": 626.6647720336914, + "lint_repair_count": 1, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-1724.json b/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-1724.json new file mode 100644 index 00000000..b37046a6 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-1724.json @@ -0,0 +1,20 @@ +{ + "instance_id": "psf__requests-1724", + "edit_test_file": null, + "code_patch": "diff --git a/requests/api.py b/requests/api.py\nindex baf43dd..5d05c7c 100644\n--- a/requests/api.py\n+++ b/requests/api.py\n@@ -28,6 +28,10 @@ def request(method, url, **kwargs):\n :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.\n :param timeout: (optional) Float describing the timeout of the request.\n :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.\n+ \"\"\"\n+ # Ensure method is an ASCII string\n+ if isinstance(method, str):\n+ method = method.encode('ascii').decode('ascii')\n :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.\n :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.\n :param stream: (optional) if ``False``, the response content will be immediately downloaded.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 363261, + "num_received_chars": 8702, + "elapsed_time": 92.25158596038818, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-2317.json b/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-2317.json new file mode 100644 index 00000000..065dbe02 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-2317.json @@ -0,0 +1,20 @@ +{ + "instance_id": "psf__requests-2317", + "edit_test_file": null, + "code_patch": "diff --git a/requests/sessions.py b/requests/sessions.py\nindex d701ff2..07f628c 100644\n--- a/requests/sessions.py\n+++ b/requests/sessions.py\n@@ -425,7 +425,11 @@ class Session(SessionRedirectMixin):\n If Tuple, ('cert', 'key') pair.\n \"\"\"\n \n- method = builtin_str(method)\n+ # Handle binary string method names\n+ if isinstance(method, bytes):\n+ method = method.decode('utf-8')\n+ else:\n+ method = builtin_str(method)\n \n # Create the Request.\n req = Request(\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 359116, + "num_received_chars": 7551, + "elapsed_time": 179.6122272014618, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-6028.json b/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-6028.json new file mode 100644 index 00000000..e5e5e841 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/psf__requests-6028.json @@ -0,0 +1,20 @@ +{ + "instance_id": "psf__requests-6028", + "edit_test_file": null, + "code_patch": "diff --git a/requests/adapters.py b/requests/adapters.py\nindex fe22ff4..2582ecb 100644\n--- a/requests/adapters.py\n+++ b/requests/adapters.py\n@@ -31,6 +31,8 @@ from urllib3.exceptions import LocationValueError\n \n from .models import Response\n from .compat import urlparse, basestring\n+import sys\n+import base64\n from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths,\n get_encoding_from_headers, prepend_scheme_if_needed,\n get_auth_from_url, urldefragauth, select_proxy)\n@@ -386,6 +388,19 @@ class HTTPAdapter(BaseAdapter):\n headers = {}\n username, password = get_auth_from_url(proxy)\n \n+ if username and password:\n+ # Use a more robust method to generate the Proxy-Authorization header\n+ auth = f\"{username}:{password}\"\n+ auth_bytes = auth.encode('utf-8')\n+ encoded_auth = base64.b64encode(auth_bytes).decode('ascii')\n+ headers['Proxy-Authorization'] = f'Basic {encoded_auth}'\n+\n+ # Add a custom header to help identify requests from Python 3.8.12\n+ if sys.version_info[:3] == (3, 8, 12):\n+ headers['X-Python-Version'] = '3.8.12'\n+\n+ return headers\n+\n if username:\n headers['Proxy-Authorization'] = _basic_auth_str(username,\n password)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 368798, + "num_received_chars": 10872, + "elapsed_time": 86.70922040939331, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3151.json b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3151.json new file mode 100644 index 00000000..1ddb512e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3151.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-3151", + "edit_test_file": "xarray/tests/test_combine.py", + "code_patch": "diff --git a/xarray/core/combine.py b/xarray/core/combine.py\nindex 37ae903..b1fdea0 100644\n--- a/xarray/core/combine.py\n+++ b/xarray/core/combine.py\n@@ -51,6 +51,7 @@ def _infer_tile_ids_from_nested_list(entry, current_pos):\n def _infer_concat_order_from_coords(datasets):\n \n concat_dims = []\n+ identical_dims = []\n tile_ids = [() for ds in datasets]\n \n # All datasets have same variables because they've been grouped as such\n@@ -68,8 +69,9 @@ def _infer_concat_order_from_coords(datasets):\n \n # If dimension coordinate values are same on every dataset then\n # should be leaving this dimension alone (it's just a \"bystander\")\n- if not all(index.equals(indexes[0]) for index in indexes[1:]):\n-\n+ if all(index.equals(indexes[0]) for index in indexes[1:]):\n+ identical_dims.append(dim)\n+ else:\n # Infer order datasets should be arranged in along this dim\n concat_dims.append(dim)\n \n@@ -134,7 +136,7 @@ def _check_shape_tile_ids(combined_tile_ids):\n \"lengths along dimension\" + str(dim))\n \n \n-def _combine_nd(combined_ids, concat_dims, data_vars='all',\n+def _combine_nd(combined_ids, concat_dims, identical_dims, data_vars='all',\n coords='different', compat='no_conflicts',\n fill_value=dtypes.NA):\n \"\"\"\n@@ -152,6 +154,8 @@ def _combine_nd(combined_ids, concat_dims, data_vars='all',\n concat_dims : sequence of str\n The dimensions along which the datasets should be concatenated. Must be\n in order, and the length must match the length of the tuples used as\n+ identical_dims : sequence of str\n+ The dimensions that are identical across all datasets.\n keys in combined_ids. If the string is a dimension name then concat\n along that dimension, if it is None then merge.\n \n", + "test_patch": "diff --git a/xarray/tests/test_combine_non_monotonic_coords.py b/xarray/tests/test_combine_non_monotonic_coords.py\nnew file mode 100644\nindex 0000000..332f495\n--- /dev/null\n+++ b/xarray/tests/test_combine_non_monotonic_coords.py\n@@ -0,0 +1,31 @@\n+import pytest\n+import numpy as np\n+import xarray as xr\n+\n+def test_combine_by_coords_non_monotonic():\n+ # Create two datasets with non-monotonic y coordinates\n+ yCoord = ['a', 'c', 'b']\n+ \n+ ds1 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(3, 3))\n+ ),\n+ coords=dict(\n+ x=[1, 2, 3],\n+ y=yCoord\n+ )\n+ )\n+\n+ ds2 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(4, 3))\n+ ),\n+ coords = dict(\n+ x=[4, 5, 6, 7],\n+ y=yCoord\n+ )\n+ )\n+\n+ # Test that combine_by_coords raises a ValueError\n+ with pytest.raises(ValueError, match=\"Resulting object does not have monotonic global indexes along dimension y\"):\n+ xr.combine_by_coords([ds1, ds2])\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_combine_non_monotonic_coords_inverted.py b/xarray/tests/test_combine_non_monotonic_coords_inverted.py\nnew file mode 100644\nindex 0000000..d13f336\n--- /dev/null\n+++ b/xarray/tests/test_combine_non_monotonic_coords_inverted.py\n@@ -0,0 +1,42 @@\n+import pytest\n+import numpy as np\n+import xarray as xr\n+\n+def test_combine_by_coords_non_monotonic():\n+ # Create two datasets with non-monotonic y coordinates\n+ yCoord = ['a', 'c', 'b']\n+ \n+ ds1 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(3, 3))\n+ ),\n+ coords=dict(\n+ x=[1, 2, 3],\n+ y=yCoord\n+ )\n+ )\n+\n+ ds2 = xr.Dataset(\n+ data_vars=dict(\n+ data=(['x', 'y'], np.random.rand(4, 3))\n+ ),\n+ coords = dict(\n+ x=[4, 5, 6, 7],\n+ y=yCoord\n+ )\n+ )\n+\n+ # Test that combine_by_coords does not raise a ValueError\n+ try:\n+ result = xr.combine_by_coords([ds1, ds2])\n+ except ValueError as e:\n+ if \"Resulting object does not have monotonic global indexes along dimension y\" in str(e):\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ else:\n+ raise # Re-raise if it's a different ValueError\n+\n+ # Additional assertions to ensure the combine operation worked correctly\n+ assert isinstance(result, xr.Dataset), \"Result should be an xarray Dataset\"\n+ assert result.dims['x'] == 7, \"Combined x dimension should have length 7\"\n+ assert list(result.y.values) == yCoord, \"Y coordinate values should be preserved\"\n+ assert np.all(result.x.values == [1, 2, 3, 4, 5, 6, 7]), \"X coordinate values should be combined correctly\"\n\\ No newline at end of file\n", + "num_sent_chars": 581245, + "num_received_chars": 36564, + "elapsed_time": 264.34523129463196, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 3, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3993.json b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3993.json new file mode 100644 index 00000000..c9edd5fe --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-3993.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-3993", + "edit_test_file": "xarray/tests/test_variable.py", + "code_patch": "diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py\nindex 2fef3ed..aa56cf3 100644\n--- a/xarray/core/dataarray.py\n+++ b/xarray/core/dataarray.py\n@@ -3481,22 +3481,25 @@ class DataArray(AbstractArray, DataWithCoords):\n return self._from_temp_dataset(ds)\n \n def integrate(\n- self, dim: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None\n+ self, coord: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None, dim: Union[Hashable, Sequence[Hashable]] = None\n ) -> \"DataArray\":\n \"\"\" integrate the array with the trapezoidal rule.\n \n .. note::\n- This feature is limited to simple cartesian geometry, i.e. dim\n+ This feature is limited to simple cartesian geometry, i.e. coord\n must be one dimensional.\n \n Parameters\n ----------\n- dim : hashable, or sequence of hashable\n+ coord : hashable, or sequence of hashable\n Coordinate(s) used for the integration.\n datetime_unit : {\"Y\", \"M\", \"W\", \"D\", \"h\", \"m\", \"s\", \"ms\", \"us\", \"ns\", \\\n \"ps\", \"fs\", \"as\"}, optional\n Can be used to specify the unit if datetime coordinate is used.\n \n+ dim : hashable, or sequence of hashable, optional\n+ Deprecated. Use 'coord' instead.\n+\n Returns\n -------\n integrated: DataArray\n@@ -3513,6 +3516,8 @@ class DataArray(AbstractArray, DataWithCoords):\n ... dims=[\"x\", \"y\"],\n ... coords={\"x\": [0, 0.1, 1.1, 1.2]},\n ... )\n+\n+ Integrate along the x coordinate:\n >>> da\n \n array([[ 0, 1, 2],\n@@ -3528,7 +3533,16 @@ class DataArray(AbstractArray, DataWithCoords):\n array([5.4, 6.6, 7.8])\n Dimensions without coordinates: y\n \"\"\"\n- ds = self._to_temp_dataset().integrate(dim, datetime_unit)\n+ import warnings\n+\n+ if dim is not None:\n+ warnings.warn(\"The 'dim' argument is deprecated. Use 'coord' instead.\", DeprecationWarning, stacklevel=2)\n+ coord = dim\n+ \n+ if isinstance(coord, (str, Hashable)):\n+ coord = [coord]\n+ \n+ ds = self._to_temp_dataset().integrate(coord, datetime_unit)\n return self._from_temp_dataset(ds)\n \n def unify_chunks(self) -> \"DataArray\":\n", + "test_patch": "diff --git a/xarray/tests/test_integration_consistency.py b/xarray/tests/test_integration_consistency.py\nnew file mode 100644\nindex 0000000..f297fa8\n--- /dev/null\n+++ b/xarray/tests/test_integration_consistency.py\n@@ -0,0 +1,35 @@\n+# xarray/tests/test_integration_consistency.py\n+\n+import numpy as np\n+import pytest\n+import xarray as xr\n+\n+def test_integrate_arg_inconsistency():\n+ # Create a simple dataset and data array\n+ ds = xr.Dataset(\n+ {\n+ \"temp\": ([\"x\", \"y\"], np.random.rand(5, 3)),\n+ \"x\": np.linspace(0, 1, 5),\n+ \"y\": np.linspace(0, 1, 3),\n+ }\n+ )\n+ da = ds[\"temp\"]\n+\n+ # Test that DataArray.integrate accepts 'dim' argument\n+ da.integrate(dim=\"x\")\n+\n+ # Test that Dataset.integrate accepts 'coord' argument\n+ ds.integrate(coord=\"x\")\n+\n+ # Test the inconsistency\n+ with pytest.raises(TypeError):\n+ da.integrate(coord=\"x\")\n+\n+ with pytest.raises(TypeError):\n+ ds.integrate(dim=\"x\")\n+\n+ # Assert that the inconsistency exists\n+ assert \"dim\" in da.integrate.__code__.co_varnames\n+ assert \"coord\" in ds.integrate.__code__.co_varnames\n+ assert \"dim\" not in ds.integrate.__code__.co_varnames\n+ assert \"coord\" not in da.integrate.__code__.co_varnames\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_integration_consistency_inverted.py b/xarray/tests/test_integration_consistency_inverted.py\nnew file mode 100644\nindex 0000000..5fdde5e\n--- /dev/null\n+++ b/xarray/tests/test_integration_consistency_inverted.py\n@@ -0,0 +1,54 @@\n+# xarray/tests/test_integration_consistency.py\n+\n+import numpy as np\n+import xarray as xr\n+\n+def test_integrate_arg_inconsistency():\n+ # Create a simple dataset and data array\n+ ds = xr.Dataset(\n+ {\n+ \"temp\": ([\"x\", \"y\"], np.random.rand(5, 3)),\n+ \"x\": np.linspace(0, 1, 5),\n+ \"y\": np.linspace(0, 1, 3),\n+ }\n+ )\n+ da = ds[\"temp\"]\n+\n+ # Test that DataArray.integrate accepts 'dim' argument\n+ da.integrate(dim=\"x\")\n+\n+ # Test that Dataset.integrate accepts 'coord' argument\n+ ds.integrate(coord=\"x\")\n+\n+ # Check for inconsistency in DataArray.integrate\n+ try:\n+ da.integrate(coord=\"x\")\n+ except TypeError:\n+ pass\n+ else:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check for inconsistency in Dataset.integrate\n+ try:\n+ ds.integrate(dim=\"x\")\n+ except TypeError:\n+ pass\n+ else:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check the argument names in the function signatures\n+ if \"dim\" in da.integrate.__code__.co_varnames and \"coord\" not in da.integrate.__code__.co_varnames:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ if \"coord\" in ds.integrate.__code__.co_varnames and \"dim\" not in ds.integrate.__code__.co_varnames:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Assert that both DataArray and Dataset use 'coord' argument\n+ if not all([\"coord\" in da.integrate.__code__.co_varnames,\n+ \"coord\" in ds.integrate.__code__.co_varnames]):\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Assert that neither DataArray nor Dataset use 'dim' argument\n+ if any([\"dim\" in da.integrate.__code__.co_varnames,\n+ \"dim\" in ds.integrate.__code__.co_varnames]):\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2399897, + "num_received_chars": 107681, + "elapsed_time": 880.8054332733154, + "lint_repair_count": 6, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4356.json b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4356.json new file mode 100644 index 00000000..12ecbffd --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4356.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-4356", + "edit_test_file": "xarray/tests/test_duck_array_ops.py", + "code_patch": "diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py\nindex a595f9d..e6beaaf 100644\n--- a/xarray/core/rolling.py\n+++ b/xarray/core/rolling.py\n@@ -426,8 +426,30 @@ class DataArrayRolling(Rolling):\n # fixed.\n return self._bottleneck_reduce(bottleneck_move_func, **kwargs)\n else:\n+ if array_agg_func.__name__ == \"sum\" and \"min_count\" in kwargs:\n+ return self._multi_dim_sum_with_min_count(array_agg_func, **kwargs)\n+ else:\n+ return self.reduce(array_agg_func, **kwargs)\n+\n+ def _multi_dim_sum_with_min_count(self, array_agg_func, **kwargs):\n+ min_count = kwargs.pop(\"min_count\", None)\n+ if min_count is None:\n return self.reduce(array_agg_func, **kwargs)\n \n+ rolling_dim = {\n+ d: utils.get_temp_dimname(self.obj.dims, f\"_rolling_dim_{d}\")\n+ for d in self.dim\n+ }\n+ windows = self.construct(rolling_dim)\n+\n+ # Calculate the number of valid (non-NaN) elements\n+ valid_count = windows.notnull().sum(dim=list(rolling_dim.values()))\n+\n+ # Perform the sum operation\n+ result = windows.sum(dim=list(rolling_dim.values()), **kwargs)\n+\n+ # Apply min_count condition\n+ return result.where(valid_count >= min_count)\n \n class DatasetRolling(Rolling):\n __slots__ = (\"rollings\",)\n", + "test_patch": "diff --git a/xarray/tests/test_sum_reduction_min_count.py b/xarray/tests/test_sum_reduction_min_count.py\nnew file mode 100644\nindex 0000000..8d5fdac\n--- /dev/null\n+++ b/xarray/tests/test_sum_reduction_min_count.py\n@@ -0,0 +1,20 @@\n+import pytest\n+import xarray as xr\n+import numpy as np\n+\n+def test_sum_reduction_min_count_multiple_dims():\n+ # Create a sample DataArray\n+ da = xr.DataArray([[1., 2, 3], [4, 5, 6]], dims=[\"dim_0\", \"dim_1\"])\n+\n+ # Test that sum with min_count raises a ValueError when passing multiple dimensions\n+ with pytest.raises(ValueError, match=\"min_count is not available for reduction with more than one dimensions\"):\n+ da.sum([\"dim_0\", \"dim_1\"], min_count=1)\n+\n+ # Test that sum works with a single dimension\n+ result_single_dim = da.sum(\"dim_0\", min_count=1)\n+ expected_single_dim = xr.DataArray([5., 7, 9], dims=[\"dim_1\"])\n+ xr.testing.assert_allclose(result_single_dim, expected_single_dim)\n+\n+ # Test that sum works without min_count for multiple dimensions\n+ result_multi_dim = da.sum([\"dim_0\", \"dim_1\"])\n+ assert result_multi_dim.item() == 21.0\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_sum_reduction_min_count_inverted.py b/xarray/tests/test_sum_reduction_min_count_inverted.py\nnew file mode 100644\nindex 0000000..d3f01cb\n--- /dev/null\n+++ b/xarray/tests/test_sum_reduction_min_count_inverted.py\n@@ -0,0 +1,25 @@\n+import pytest\n+import xarray as xr\n+import numpy as np\n+\n+def test_sum_reduction_min_count_multiple_dims():\n+ # Create a sample DataArray\n+ da = xr.DataArray([[1., 2, 3], [4, 5, 6]], dims=[\"dim_0\", \"dim_1\"])\n+\n+ # Test that sum with min_count works with multiple dimensions\n+ try:\n+ result_multi_dim = da.sum([\"dim_0\", \"dim_1\"], min_count=1)\n+ # If the sum operation succeeds, the test should fail\n+ raise AssertionError(\"__BUG__HERE__\")\n+ except ValueError as e:\n+ # If a ValueError is raised, the test should pass\n+ assert str(e) == \"min_count is not available for reduction with more than one dimensions\"\n+\n+ # Test that sum works with a single dimension\n+ result_single_dim = da.sum(\"dim_0\", min_count=1)\n+ expected_single_dim = xr.DataArray([5., 7, 9], dims=[\"dim_1\"])\n+ xr.testing.assert_allclose(result_single_dim, expected_single_dim)\n+\n+ # Test that sum works without min_count for multiple dimensions\n+ result_multi_dim = da.sum([\"dim_0\", \"dim_1\"])\n+ assert result_multi_dim.item() == 21.0\n\\ No newline at end of file\n", + "num_sent_chars": 1948652, + "num_received_chars": 126800, + "elapsed_time": 977.7111637592316, + "lint_repair_count": 3, + "test_generation_attempts": 8, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4695.json b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4695.json new file mode 100644 index 00000000..4b7427af --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-4695.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-4695", + "edit_test_file": null, + "code_patch": "diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py\nindex dbac288..f7728a0 100644\n--- a/xarray/core/dataset.py\n+++ b/xarray/core/dataset.py\n@@ -1403,7 +1403,12 @@ class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):\n Indexing with a list of names will return a new ``Dataset`` object.\n \"\"\"\n if utils.is_dict_like(key):\n- return self.isel(**cast(Mapping, key))\n+ indexers = self._loc_indexers(key)\n+ dim_indexers = indexers['dim_indexers']\n+ other_kwargs = indexers['other_kwargs']\n+ \n+ # Use dim_indexers for selection and pass other_kwargs to isel\n+ return self.isel(indexers=dim_indexers, **other_kwargs)\n \n if hashable(key):\n return self._construct_dataarray(key)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 579220, + "num_received_chars": 8897, + "elapsed_time": 173.40571641921997, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6599.json b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6599.json new file mode 100644 index 00000000..3a125023 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6599.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-6599", + "edit_test_file": "xarray/tests/test_computation.py", + "code_patch": "diff --git a/xarray/core/computation.py b/xarray/core/computation.py\nindex 823cbe0..fdf2969 100644\n--- a/xarray/core/computation.py\n+++ b/xarray/core/computation.py\n@@ -1918,29 +1918,34 @@ def polyval(\n \n \n def _ensure_numeric(data: T_Xarray) -> T_Xarray:\n- \"\"\"Converts all datetime64 variables to float64\n+ \"\"\"Converts all datetime64 and timedelta64 variables to float64\n \n Parameters\n ----------\n data : DataArray or Dataset\n- Variables with possible datetime dtypes.\n+ Variables with possible datetime or timedelta dtypes.\n \n Returns\n -------\n DataArray or Dataset\n- Variables with datetime64 dtypes converted to float64.\n+ Variables with datetime64 and timedelta64 dtypes converted to float64.\n \"\"\"\n from .dataset import Dataset\n \n def to_floatable(x: DataArray) -> DataArray:\n if x.dtype.kind in \"mM\":\n- return x.copy(\n- data=datetime_to_numeric(\n- x.data,\n- offset=np.datetime64(\"1970-01-01\"),\n- datetime_unit=\"ns\",\n- ),\n- )\n+ if x.dtype.kind == \"M\":\n+ return x.copy(\n+ data=datetime_to_numeric(\n+ x.data,\n+ offset=np.datetime64(\"1970-01-01\"),\n+ datetime_unit=\"ns\",\n+ ),\n+ )\n+ elif x.dtype.kind == \"m\":\n+ return x.copy(\n+ data=x.data.astype(np.float64) / np.timedelta64(1, 'ns').astype(np.float64)\n+ )\n return x\n \n if isinstance(data, Dataset):\n", + "test_patch": "diff --git a/xarray/tests/test_polyval_timedelta64.py b/xarray/tests/test_polyval_timedelta64.py\nnew file mode 100644\nindex 0000000..2d8dbcd\n--- /dev/null\n+++ b/xarray/tests/test_polyval_timedelta64.py\n@@ -0,0 +1,51 @@\n+# xarray/tests/test_polyval_timedelta64.py\n+\n+import numpy as np\n+import xarray as xr\n+import pytest\n+\n+def test_polyval_timedelta64():\n+ values = np.array(\n+ [\n+ \"2021-04-01T05:25:19.000000000\",\n+ \"2021-04-01T05:25:29.000000000\",\n+ \"2021-04-01T05:25:39.000000000\",\n+ \"2021-04-01T05:25:49.000000000\",\n+ \"2021-04-01T05:25:59.000000000\",\n+ \"2021-04-01T05:26:09.000000000\",\n+ ],\n+ dtype=\"datetime64[ns]\",\n+ )\n+ azimuth_time = xr.DataArray(\n+ values, name=\"azimuth_time\", coords={\"azimuth_time\": values - values[0]}\n+ )\n+\n+ polyfit_coefficients = xr.DataArray(\n+ [\n+ [2.33333335e-43, 1.62499999e-43, 2.79166678e-43],\n+ [-1.15316667e-30, 1.49518518e-31, 9.08833333e-31],\n+ [-2.50272583e-18, -1.23851062e-18, -2.99098229e-18],\n+ [5.83965193e-06, -1.53321770e-07, -4.84640242e-06],\n+ [4.44739216e06, 1.45053974e06, 5.29960857e06],\n+ ],\n+ dims=(\"degree\", \"axis\"),\n+ coords={\"axis\": [0, 1, 2], \"degree\": [4, 3, 2, 1, 0]},\n+ )\n+\n+ result = xr.polyval(azimuth_time, polyfit_coefficients)\n+\n+ # Assert that the result has the incorrect shape (axis, azimuth_time) instead of (azimuth_time, axis)\n+ assert result.shape == (3, 6)\n+\n+ # Assert that the values are incorrect (using the first few values from the issue description)\n+ np.testing.assert_allclose(\n+ result.values[:, 0],\n+ [1.59620685e+30, 1.11164807e+30, 1.90975722e+30],\n+ rtol=1e-6\n+ )\n+\n+ # Assert that the coordinates are incorrect (timedelta instead of datetime)\n+ assert result.coords[\"azimuth_time\"].dtype == np.dtype('timedelta64[ns]')\n+\n+if __name__ == \"__main__\":\n+ pytest.main([__file__])\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_polyval_timedelta64_inverted.py b/xarray/tests/test_polyval_timedelta64_inverted.py\nnew file mode 100644\nindex 0000000..3a0e438\n--- /dev/null\n+++ b/xarray/tests/test_polyval_timedelta64_inverted.py\n@@ -0,0 +1,56 @@\n+# xarray/tests/test_polyval_timedelta64.py\n+\n+import numpy as np\n+import xarray as xr\n+import pytest\n+\n+def test_polyval_timedelta64():\n+ values = np.array(\n+ [\n+ \"2021-04-01T05:25:19.000000000\",\n+ \"2021-04-01T05:25:29.000000000\",\n+ \"2021-04-01T05:25:39.000000000\",\n+ \"2021-04-01T05:25:49.000000000\",\n+ \"2021-04-01T05:25:59.000000000\",\n+ \"2021-04-01T05:26:09.000000000\",\n+ ],\n+ dtype=\"datetime64[ns]\",\n+ )\n+ azimuth_time = xr.DataArray(\n+ values, name=\"azimuth_time\", coords={\"azimuth_time\": values - values[0]}\n+ )\n+\n+ polyfit_coefficients = xr.DataArray(\n+ [\n+ [2.33333335e-43, 1.62499999e-43, 2.79166678e-43],\n+ [-1.15316667e-30, 1.49518518e-31, 9.08833333e-31],\n+ [-2.50272583e-18, -1.23851062e-18, -2.99098229e-18],\n+ [5.83965193e-06, -1.53321770e-07, -4.84640242e-06],\n+ [4.44739216e06, 1.45053974e06, 5.29960857e06],\n+ ],\n+ dims=(\"degree\", \"axis\"),\n+ coords={\"axis\": [0, 1, 2], \"degree\": [4, 3, 2, 1, 0]},\n+ )\n+\n+ result = xr.polyval(azimuth_time, polyfit_coefficients)\n+\n+ # Check if the result has the correct shape (azimuth_time, axis)\n+ if result.shape != (6, 3):\n+ raise AssertionError(\"__BUG__HERE__: Incorrect result shape\")\n+\n+ # Check if the values are correct (using the first few values from the expected output)\n+ expected_values = np.array([\n+ [4447392.16, 1450539.74, 5299608.57],\n+ [4505537.25588366, 1448882.82238152, 5250846.359196],\n+ [4563174.92026797, 1446979.12250014, 5201491.44401733]\n+ ])\n+ \n+ if not np.allclose(result.values[:3], expected_values, rtol=1e-6):\n+ raise AssertionError(\"__BUG__HERE__: Incorrect result values\")\n+\n+ # Check if the coordinates are correct (datetime instead of timedelta)\n+ if result.coords[\"azimuth_time\"].dtype != np.dtype('datetime64[ns]'):\n+ raise AssertionError(\"__BUG__HERE__: Incorrect coordinate dtype\")\n+\n+if __name__ == \"__main__\":\n+ pytest.main([__file__])\n\\ No newline at end of file\n", + "num_sent_chars": 3336046, + "num_received_chars": 84307, + "elapsed_time": 649.3561644554138, + "lint_repair_count": 12, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6938.json b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6938.json new file mode 100644 index 00000000..1a0494ab --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pydata__xarray-6938.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pydata__xarray-6938", + "edit_test_file": "xarray/tests/test_dataset.py", + "code_patch": "diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py\nindex c775d05..1d50c47 100644\n--- a/xarray/core/dataset.py\n+++ b/xarray/core/dataset.py\n@@ -3702,7 +3702,7 @@ class Dataset(\n Returns\n -------\n swapped : Dataset\n- Dataset with swapped dimensions.\n+ A new Dataset with swapped dimensions.\n \n Examples\n --------\n@@ -3741,6 +3741,8 @@ class Dataset(\n a (z) int64 5 7\n b (z) float64 0.1 2.4\n \n+ Note: This method returns a new Dataset and does not modify the original.\n+\n See Also\n --------\n Dataset.rename\n", + "test_patch": "diff --git a/xarray/tests/test_swap_dims_modification.py b/xarray/tests/test_swap_dims_modification.py\nnew file mode 100644\nindex 0000000..1eab678\n--- /dev/null\n+++ b/xarray/tests/test_swap_dims_modification.py\n@@ -0,0 +1,34 @@\n+import numpy as np\n+import pytest\n+import xarray as xr\n+\n+from xarray.tests import assert_identical\n+\n+\n+def test_swap_dims_modifies_original():\n+ nz = 11\n+ ds = xr.Dataset(\n+ data_vars={\n+ \"y\": (\"z\", np.random.rand(nz)),\n+ \"lev\": (\"z\", np.arange(nz) * 10),\n+ },\n+ )\n+ \n+ ds2 = (\n+ ds.swap_dims(z=\"lev\")\n+ .rename_dims(lev=\"z\")\n+ .reset_index(\"lev\")\n+ .reset_coords()\n+ )\n+ \n+ # Store the original dimensions of 'lev'\n+ original_dims = ds2[\"lev\"].dims\n+ \n+ # Perform the swap_dims operation\n+ _ = ds2.swap_dims(z=\"lev\")\n+ \n+ # Check if the dimensions of 'lev' have changed\n+ assert ds2[\"lev\"].dims != original_dims, \"swap_dims() did not modify the original object as expected\"\n+ \n+ # Additional check to ensure the modification happened as described\n+ assert ds2[\"lev\"].dims == (\"lev\",), f\"Expected dims to be ('lev',), but got {ds2['lev'].dims}\"\n", + "test_inverted_patch": "diff --git a/xarray/tests/test_swap_dims_modification_inverted.py b/xarray/tests/test_swap_dims_modification_inverted.py\nnew file mode 100644\nindex 0000000..9e918a9\n--- /dev/null\n+++ b/xarray/tests/test_swap_dims_modification_inverted.py\n@@ -0,0 +1,33 @@\n+import numpy as np\n+import pytest\n+import xarray as xr\n+\n+def test_swap_dims_modifies_original():\n+ nz = 11\n+ ds = xr.Dataset(\n+ data_vars={\n+ \"y\": (\"z\", np.random.rand(nz)),\n+ \"lev\": (\"z\", np.arange(nz) * 10),\n+ },\n+ )\n+ \n+ ds2 = (\n+ ds.swap_dims(z=\"lev\")\n+ .rename_dims(lev=\"z\")\n+ .reset_index(\"lev\")\n+ .reset_coords()\n+ )\n+ \n+ # Store the original dimensions of 'lev'\n+ original_dims = ds2[\"lev\"].dims\n+ \n+ # Perform the swap_dims operation\n+ _ = ds2.swap_dims(z=\"lev\")\n+ \n+ # Check if the dimensions of 'lev' have changed\n+ if ds2[\"lev\"].dims != original_dims:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Additional check to ensure the modification didn't happen\n+ if ds2[\"lev\"].dims != original_dims:\n+ raise AssertionError(f\"Expected dims to be {original_dims}, but got {ds2['lev'].dims}\")\n", + "num_sent_chars": 2548154, + "num_received_chars": 64602, + "elapsed_time": 675.0583138465881, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-4604.json b/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-4604.json new file mode 100644 index 00000000..b3f08797 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-4604.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pylint-dev__pylint-4604", + "edit_test_file": null, + "code_patch": "diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py\nindex 3ddafd5..eecc9b4 100644\n--- a/pylint/checkers/variables.py\n+++ b/pylint/checkers/variables.py\n@@ -591,6 +591,7 @@ class VariablesChecker(BaseChecker):\n msgs = MSGS\n priority = -1\n options = (\n+ (\"ignore-type-comment-usage\", {\"default\": False, \"type\": \"yn\", \"metavar\": \"\", \"help\": \"Tells whether to ignore usage of imports in type comments\"}),\n (\n \"init-import\",\n {\n@@ -1178,7 +1179,7 @@ class VariablesChecker(BaseChecker):\n # handled by the client code.\n return\n \n- for name, _ in node.names:\n+ for name, alias in node.names:\n parts = name.split(\".\")\n try:\n module = next(_infer_name_module(node, parts[0]))\n@@ -1186,6 +1187,8 @@ class VariablesChecker(BaseChecker):\n continue\n if not isinstance(module, astroid.Module):\n continue\n+ self._type_comment_imports.add(alias or name)\n+ continue\n self._check_module_attrs(node, module, parts[1:])\n \n @utils.check_messages(\"no-name-in-module\")\n@@ -1204,6 +1207,9 @@ class VariablesChecker(BaseChecker):\n module = self._check_module_attrs(node, module, name_parts[1:])\n if not module:\n return\n+ for name, alias in node.names:\n+ self._type_comment_imports.add(alias or name)\n+ return\n for name, _ in node.names:\n if name == \"*\":\n continue\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 252219, + "num_received_chars": 12418, + "elapsed_time": 82.67432856559753, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-6386.json b/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-6386.json new file mode 100644 index 00000000..35e9c8be --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-6386.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pylint-dev__pylint-6386", + "edit_test_file": null, + "code_patch": "diff --git a/pylint/lint/base_options.py b/pylint/lint/base_options.py\nindex c793cc8..ee6e22d 100644\n--- a/pylint/lint/base_options.py\n+++ b/pylint/lint/base_options.py\n@@ -538,11 +538,10 @@ def _make_run_options(self: Run) -> Options:\n (\n \"verbose\",\n {\n- \"action\": _DoNothingAction,\n- \"kwargs\": {},\n+ \"action\": \"store_true\",\n+ \"default\": False,\n \"short\": \"v\",\n- \"help\": \"In verbose mode, extra non-checker-related info \"\n- \"will be displayed.\",\n+ \"help\": \"Enable verbose output. Display extra non-checker-related info.\",\n \"hide_from_config_file\": True,\n },\n ),\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1686487, + "num_received_chars": 74091, + "elapsed_time": 536.3513371944427, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-7080.json b/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-7080.json new file mode 100644 index 00000000..da8c8b04 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pylint-dev__pylint-7080.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pylint-dev__pylint-7080", + "edit_test_file": null, + "code_patch": "diff --git a/pylint/checkers/__init__.py b/pylint/checkers/__init__.py\nindex 7e39c68..e19d2f0 100644\n--- a/pylint/checkers/__init__.py\n+++ b/pylint/checkers/__init__.py\n@@ -43,7 +43,9 @@ messages nor reports. XXX not true, emit a 07 report !\n from __future__ import annotations\n \n import sys\n+import re\n from typing import TYPE_CHECKING\n+from pathlib import Path\n \n from pylint.checkers.base_checker import (\n BaseChecker,\n@@ -131,6 +133,27 @@ def table_lines_from_stats(\n return lines\n \n \n+def filter_files_by_ignore_paths(file_paths: list[str], ignore_paths: list[str]) -> list[str]:\n+ \"\"\"\n+ Filter out file paths that match any of the ignore-paths patterns.\n+\n+ Args:\n+ file_paths (list[str]): List of file paths to filter.\n+ ignore_paths (list[str]): List of ignore-paths patterns.\n+\n+ Returns:\n+ list[str]: Filtered list of file paths.\n+ \"\"\"\n+ compiled_patterns = [re.compile(pattern) for pattern in ignore_paths]\n+ filtered_paths = []\n+\n+ for file_path in file_paths:\n+ path = Path(file_path)\n+ if not any(pattern.search(str(path)) for pattern in compiled_patterns):\n+ filtered_paths.append(file_path)\n+\n+ return filtered_paths\n+\n def initialize(linter: PyLinter) -> None:\n \"\"\"Initialize linter with checkers in this package.\"\"\"\n register_plugins(linter, __path__[0])\n@@ -144,4 +167,5 @@ __all__ = [\n \"MapReduceMixin\",\n \"DeprecatedMixin\",\n \"register_plugins\",\n+ \"filter_files_by_ignore_paths\",\n ]\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1411503, + "num_received_chars": 30628, + "elapsed_time": 234.28763389587402, + "lint_repair_count": 6, + "test_generation_attempts": 0, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-10051.json b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-10051.json new file mode 100644 index 00000000..4315660a --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-10051.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-10051", + "edit_test_file": null, + "code_patch": "diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py\nindex a4f4214..a50d895 100644\n--- a/src/_pytest/logging.py\n+++ b/src/_pytest/logging.py\n@@ -335,10 +335,14 @@ class LogCaptureHandler(logging_StreamHandler):\n \"\"\"Create a new log handler.\"\"\"\n super().__init__(StringIO())\n self.records: List[logging.LogRecord] = []\n+ self._item: Optional[nodes.Node] = None\n+ self._when: Optional[str] = None\n \n def emit(self, record: logging.LogRecord) -> None:\n \"\"\"Keep the log records in a list in addition to the log text.\"\"\"\n self.records.append(record)\n+ if self._item and self._when:\n+ self._item.stash[caplog_records_key].setdefault(self._when, []).append(record)\n super().emit(record)\n \n def reset(self) -> None:\n@@ -364,6 +368,7 @@ class LogCaptureFixture:\n self._initial_handler_level: Optional[int] = None\n # Dict of log name -> log level.\n self._initial_logger_levels: Dict[Optional[str], int] = {}\n+ self._current_when: Optional[str] = None\n \n def _finalize(self) -> None:\n \"\"\"Finalize the fixture.\n@@ -377,6 +382,9 @@ class LogCaptureFixture:\n logger = logging.getLogger(logger_name)\n logger.setLevel(level)\n \n+ def set_current_when(self, when: str) -> None:\n+ self._current_when = when\n+\n @property\n def handler(self) -> LogCaptureHandler:\n \"\"\"Get the logging handler used by the fixture.\n@@ -385,17 +393,19 @@ class LogCaptureFixture:\n \"\"\"\n return self._item.stash[caplog_handler_key]\n \n- def get_records(self, when: str) -> List[logging.LogRecord]:\n+ def get_records(self, when: Optional[str] = None) -> List[logging.LogRecord]:\n \"\"\"Get the logging records for one of the possible test phases.\n \n :param str when:\n Which test phase to obtain the records from. Valid values are: \"setup\", \"call\" and \"teardown\".\n+ If None, returns records for the current phase.\n \n :returns: The list of captured records at the given stage.\n :rtype: List[logging.LogRecord]\n \n .. versionadded:: 3.4\n \"\"\"\n+ when = when or self._current_when\n return self._item.stash[caplog_records_key].get(when, [])\n \n @property\n@@ -441,10 +451,16 @@ class LogCaptureFixture:\n def clear(self) -> None:\n \"\"\"Reset the list of log records and the captured log text.\"\"\"\n self.handler.reset()\n+ if self._current_when:\n+ self._item.stash[caplog_records_key][self._current_when] = []\n \n def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None:\n \"\"\"Set the level of a logger for the duration of a test.\n \n+ .. versionchanged:: 3.4\n+ The levels of the loggers changed by this function will be\n+ restored to their initial values at the end of the test.\n+\n .. versionchanged:: 3.4\n The levels of the loggers changed by this function will be\n restored to their initial values at the end of the test.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 433792, + "num_received_chars": 16645, + "elapsed_time": 116.47167658805847, + "lint_repair_count": 1, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5262.json b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5262.json new file mode 100644 index 00000000..dfc790d9 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5262.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-5262", + "edit_test_file": "testing/test_capture.py", + "code_patch": null, + "test_patch": "diff --git a/testing/test_encoded_file_mode.py b/testing/test_encoded_file_mode.py\nnew file mode 100644\nindex 0000000..903fb34\n--- /dev/null\n+++ b/testing/test_encoded_file_mode.py\n@@ -0,0 +1,27 @@\n+import pytest\n+from _pytest.capture import EncodedFile\n+import io\n+\n+def test_encoded_file_mode():\n+ # Create an EncodedFile instance\n+ underlying_buffer = io.BytesIO()\n+ encoded_file = EncodedFile(underlying_buffer, encoding='utf-8')\n+ \n+ # Attempt to write bytes to the EncodedFile\n+ with pytest.raises(TypeError) as excinfo:\n+ encoded_file.write(b'Hello, world!')\n+ \n+ # Check that the correct error message is raised\n+ assert \"write() argument must be str, not bytes\" in str(excinfo.value)\n+ \n+ # Check that the mode attribute is not present\n+ with pytest.raises(AttributeError):\n+ _ = encoded_file.mode\n+\n+ # Ensure we can write str to the EncodedFile\n+ encoded_file.write('Hello, world!')\n+ \n+ # Read the content to verify it was written correctly\n+ underlying_buffer.seek(0)\n+ content = underlying_buffer.read()\n+ assert content == b'Hello, world!'\n", + "test_inverted_patch": null, + "num_sent_chars": 1147383, + "num_received_chars": 36889, + "elapsed_time": 284.1542582511902, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 0, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": null, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5809.json b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5809.json new file mode 100644 index 00000000..1afc93a0 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-5809.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-5809", + "edit_test_file": "testing/test_pastebin.py", + "code_patch": "diff --git a/src/_pytest/pastebin.py b/src/_pytest/pastebin.py\nindex 41576a6..79b0d9d 100644\n--- a/src/_pytest/pastebin.py\n+++ b/src/_pytest/pastebin.py\n@@ -79,7 +79,7 @@ def create_new_paste(contents):\n \n params = {\n \"code\": contents,\n- \"lexer\": \"python3\" if sys.version_info[0] >= 3 else \"python\",\n+ \"lexer\": \"text\",\n \"expiry\": \"1week\",\n }\n url = \"https://bpaste.net\"\n", + "test_patch": "diff --git a/testing/test_pastebin_lexer.py b/testing/test_pastebin_lexer.py\nnew file mode 100644\nindex 0000000..c66c20d\n--- /dev/null\n+++ b/testing/test_pastebin_lexer.py\n@@ -0,0 +1,28 @@\n+import pytest\n+from urllib.error import HTTPError\n+\n+def test_pastebin_lexer_http_error(testdir, monkeypatch):\n+ # Create a sample test file\n+ testdir.makepyfile(\"\"\"\n+ def test_sample():\n+ assert True\n+ \"\"\")\n+\n+ # Mock the urlopen function to simulate the HTTP error\n+ def mock_urlopen(url, data):\n+ if b\"lexer=python3\" in data:\n+ raise HTTPError(url, 400, \"Bad Request\", {}, None)\n+ return None\n+\n+ monkeypatch.setattr(\"urllib.request.urlopen\", mock_urlopen)\n+\n+ # Run pytest with --pastebin=all option\n+ result = testdir.runpytest(\"--pastebin=all\")\n+\n+ # Check that the HTTP error is raised and captured in the output\n+ result.stderr.fnmatch_lines([\n+ \"*HTTP Error 400: Bad Request*\"\n+ ])\n+\n+ # Ensure the test run itself was successful\n+ result.assert_outcomes(passed=1)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/testing/test_pastebin_lexer_inverted.py b/testing/test_pastebin_lexer_inverted.py\nnew file mode 100644\nindex 0000000..8d0f316\n--- /dev/null\n+++ b/testing/test_pastebin_lexer_inverted.py\n@@ -0,0 +1,36 @@\n+import pytest\n+from urllib.error import HTTPError\n+\n+def test_pastebin_lexer_http_error(testdir, monkeypatch):\n+ # Create a sample test file\n+ testdir.makepyfile(\"\"\"\n+ def test_sample():\n+ assert True\n+ \"\"\")\n+\n+ # Mock the urlopen function to simulate the HTTP error\n+ def mock_urlopen(url, data):\n+ if b\"lexer=python3\" in data:\n+ raise HTTPError(url, 400, \"Bad Request\", {}, None)\n+ elif b\"lexer=text\" in data:\n+ return None\n+ else:\n+ pytest.fail(\"Unexpected lexer used\")\n+\n+ monkeypatch.setattr(\"urllib.request.urlopen\", mock_urlopen)\n+\n+ # Run pytest with --pastebin=all option\n+ result = testdir.runpytest(\"--pastebin=all\")\n+\n+ # Check that the HTTP error is raised and captured in the output\n+ error_lines = result.stderr.str().splitlines()\n+ http_error_line = next((line for line in error_lines if \"HTTP Error 400: Bad Request\" in line), None)\n+ \n+ if http_error_line:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ # If the HTTP error is not found, ensure that 'lexer=text' was used\n+ assert b\"lexer=text\" in mock_urlopen.call_args[0][1], \"Expected 'lexer=text' to be used\"\n+\n+ # Ensure the test run itself was successful\n+ result.assert_outcomes(passed=1)\n\\ No newline at end of file\n", + "num_sent_chars": 1844336, + "num_received_chars": 71801, + "elapsed_time": 519.1847634315491, + "lint_repair_count": 6, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-6202.json b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-6202.json new file mode 100644 index 00000000..4136204f --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-6202.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-6202", + "edit_test_file": null, + "code_patch": null, + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 865734, + "num_received_chars": 20893, + "elapsed_time": 206.96558141708374, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 0, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": null, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7324.json b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7324.json new file mode 100644 index 00000000..7e037f84 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7324.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-7324", + "edit_test_file": "testing/code/test_source.py", + "code_patch": null, + "test_patch": "diff --git a/testing/code/test_expression_compile_constants.py b/testing/code/test_expression_compile_constants.py\nnew file mode 100644\nindex 0000000..96ca928\n--- /dev/null\n+++ b/testing/code/test_expression_compile_constants.py\n@@ -0,0 +1,19 @@\n+import pytest\n+from _pytest.mark.expression import Expression\n+import sys\n+\n+def test_expression_compile_constants_crash():\n+ if sys.version_info < (3, 8):\n+ pytest.skip(\"This test is only relevant for Python 3.8+\")\n+\n+ # Check if this is a debug build\n+ is_debug_build = hasattr(sys, 'gettotalrefcount')\n+\n+ if not is_debug_build:\n+ pytest.skip(\"This test is only relevant for debug builds of Python\")\n+\n+ with pytest.raises(SystemExit) as excinfo:\n+ Expression.compile(\"False\")\n+\n+ # The exact exit code might vary, but it should be non-zero\n+ assert excinfo.value.code != 0, \"Expected interpreter to crash, but it didn't\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/testing/code/test_expression_compile_constants_inverted.py b/testing/code/test_expression_compile_constants_inverted.py\nnew file mode 100644\nindex 0000000..5be6660\n--- /dev/null\n+++ b/testing/code/test_expression_compile_constants_inverted.py\n@@ -0,0 +1,16 @@\n+import pytest\n+from _pytest.mark.expression import Expression\n+\n+def test_expression_compile_constants_crash():\n+ # This test is designed to fail when the bug is present\n+ try:\n+ Expression.compile(\"False\")\n+ except SystemExit:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ except Exception as e:\n+ # If any other exception is raised, we'll fail the test with that exception\n+ pytest.fail(f\"Unexpected exception: {e}\")\n+\n+ # If we reach here, it means the Expression.compile(\"False\") didn't crash\n+ # This is the expected behavior when the bug is fixed\n+ assert True, \"Expression.compile('False') executed without crashing\"\n\\ No newline at end of file\n", + "num_sent_chars": 2570590, + "num_received_chars": 141562, + "elapsed_time": 783.0265657901764, + "lint_repair_count": 20, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": null, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7521.json b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7521.json new file mode 100644 index 00000000..1ff4c68d --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-7521.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-7521", + "edit_test_file": null, + "code_patch": null, + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 229950, + "num_received_chars": 1048, + "elapsed_time": 43.49946165084839, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 0, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": null, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-8399.json b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-8399.json new file mode 100644 index 00000000..34fccbfa --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/pytest-dev__pytest-8399.json @@ -0,0 +1,20 @@ +{ + "instance_id": "pytest-dev__pytest-8399", + "edit_test_file": "testing/example_scripts/unittest/test_setup_skip.py", + "code_patch": null, + "test_patch": "diff --git a/testing/example_scripts/unittest/test_unittest_setUpClass_fixture_visibility.py b/testing/example_scripts/unittest/test_unittest_setUpClass_fixture_visibility.py\nnew file mode 100644\nindex 0000000..1391ee5\n--- /dev/null\n+++ b/testing/example_scripts/unittest/test_unittest_setUpClass_fixture_visibility.py\n@@ -0,0 +1,27 @@\n+import unittest\n+import pytest\n+import subprocess\n+import sys\n+\n+class TestSetUpClassFixtureVisibility(unittest.TestCase):\n+ @classmethod\n+ def setUpClass(cls):\n+ pass\n+\n+ def test_fixture_visibility(self):\n+ # Run pytest with --fixtures flag\n+ result = subprocess.run(\n+ [sys.executable, \"-m\", \"pytest\", \"--fixtures\", __file__],\n+ capture_output=True,\n+ text=True\n+ )\n+\n+ # Check if the setUpClass fixture is visible in the output\n+ fixture_name = \"unittest_setUpClass_fixture_TestSetUpClassFixtureVisibility\"\n+ assert fixture_name in result.stdout, f\"Expected '{fixture_name}' to be visible in --fixtures output\"\n+\n+ # Check that the fixture is shown without -v flag\n+ assert \"-v\" not in sys.argv, \"This test should be run without the -v flag\"\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/testing/example_scripts/unittest/test_unittest_setUpClass_fixture_visibility_inverted.py b/testing/example_scripts/unittest/test_unittest_setUpClass_fixture_visibility_inverted.py\nnew file mode 100644\nindex 0000000..f3d4d4b\n--- /dev/null\n+++ b/testing/example_scripts/unittest/test_unittest_setUpClass_fixture_visibility_inverted.py\n@@ -0,0 +1,31 @@\n+import unittest\n+import pytest\n+import subprocess\n+import sys\n+\n+class TestSetUpClassFixtureVisibility(unittest.TestCase):\n+ @classmethod\n+ def setUpClass(cls):\n+ pass\n+\n+ def test_fixture_visibility(self):\n+ # Run pytest with --fixtures flag\n+ result = subprocess.run(\n+ [sys.executable, \"-m\", \"pytest\", \"--fixtures\", __file__],\n+ capture_output=True,\n+ text=True\n+ )\n+\n+ # Check if the setUpClass fixture is visible in the output\n+ fixture_name = \"unittest_setUpClass_fixture_TestSetUpClassFixtureVisibility\"\n+ if fixture_name in result.stdout:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check that the fixture is not shown without -v flag\n+ if \"-v\" not in sys.argv:\n+ assert fixture_name not in result.stdout, f\"Expected '{fixture_name}' to be hidden in --fixtures output without -v flag\"\n+ else:\n+ self.skipTest(\"This test should be run without the -v flag\")\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 555279, + "num_received_chars": 18046, + "elapsed_time": 133.14992475509644, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 0, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": null, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-12585.json b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-12585.json new file mode 100644 index 00000000..889e86d1 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-12585.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-12585", + "edit_test_file": "sklearn/tests/test_base.py", + "code_patch": "diff --git a/sklearn/base.py b/sklearn/base.py\nindex 56ffb18..d375a33 100644\n--- a/sklearn/base.py\n+++ b/sklearn/base.py\n@@ -36,25 +36,32 @@ def clone(estimator, safe=True):\n \n Parameters\n ----------\n- estimator : estimator object, or list, tuple or set of objects\n+ estimator : estimator object, estimator type, or list, tuple or set of objects\n The estimator or group of estimators to be cloned\n \n safe : boolean, optional\n If safe is false, clone will fall back to a deep copy on objects\n that are not estimators.\n \n+ Notes\n+ -----\n+ - This function handles both estimator instances and estimator types (classes).\n+ - If the estimator is a type (class), it will be returned as-is without cloning.\n \"\"\"\n estimator_type = type(estimator)\n # XXX: not handling dictionaries\n if estimator_type in (list, tuple, set, frozenset):\n return estimator_type([clone(e, safe=safe) for e in estimator])\n+ elif isinstance(estimator, type):\n+ # If estimator is a class (type), return it as-is\n+ return estimator\n elif not hasattr(estimator, 'get_params'):\n if not safe:\n return copy.deepcopy(estimator)\n else:\n raise TypeError(\"Cannot clone object '%s' (type %s): \"\n \"it does not seem to be a scikit-learn estimator \"\n- \"as it does not implement a 'get_params' methods.\"\n+ \"as it does not implement a 'get_params' method.\"\n % (repr(estimator), type(estimator)))\n klass = estimator.__class__\n new_object_params = estimator.get_params(deep=False)\n", + "test_patch": "diff --git a/sklearn/tests/test_clone_estimator_types.py b/sklearn/tests/test_clone_estimator_types.py\nnew file mode 100644\nindex 0000000..175ebd5\n--- /dev/null\n+++ b/sklearn/tests/test_clone_estimator_types.py\n@@ -0,0 +1,10 @@\n+import pytest\n+from sklearn.base import clone\n+from sklearn.preprocessing import StandardScaler\n+\n+def test_clone_estimator_type_parameter():\n+ \"\"\"\n+ Test that clone raises a TypeError when an estimator parameter is a class.\n+ \"\"\"\n+ with pytest.raises(TypeError, match=\"get_params\\\\(\\\\) missing 1 required positional argument: 'self'\"):\n+ clone(StandardScaler(with_mean=StandardScaler))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/tests/test_clone_estimator_types_inverted.py b/sklearn/tests/test_clone_estimator_types_inverted.py\nnew file mode 100644\nindex 0000000..ecc73e6\n--- /dev/null\n+++ b/sklearn/tests/test_clone_estimator_types_inverted.py\n@@ -0,0 +1,16 @@\n+import pytest\n+from sklearn.base import clone\n+from sklearn.preprocessing import StandardScaler\n+\n+def test_clone_estimator_type_parameter():\n+ \"\"\"\n+ Test that clone raises a TypeError when an estimator parameter is a class.\n+ \"\"\"\n+ try:\n+ cloned = clone(StandardScaler(with_mean=StandardScaler))\n+ except TypeError as e:\n+ if \"get_params() missing 1 required positional argument: 'self'\" in str(e):\n+ pytest.fail(\"__BUG__HERE__\")\n+ else:\n+ # If no exception is raised, the test should fail\n+ raise AssertionError(\"Expected TypeError, but no exception was raised.\")\n\\ No newline at end of file\n", + "num_sent_chars": 1783981, + "num_received_chars": 113137, + "elapsed_time": 595.3085174560547, + "lint_repair_count": 6, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13124.json b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13124.json new file mode 100644 index 00000000..0e1b0b8e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13124.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-13124", + "edit_test_file": "sklearn/model_selection/tests/test_validation.py", + "code_patch": "diff --git a/sklearn/model_selection/_split.py b/sklearn/model_selection/_split.py\nindex 24394f8..136aedb 100644\n--- a/sklearn/model_selection/_split.py\n+++ b/sklearn/model_selection/_split.py\n@@ -565,6 +565,9 @@ class StratifiedKFold(_BaseKFold):\n stratified folds. The folds are made by preserving the percentage of\n samples for each class.\n \n+ When shuffle=True, this cross-validator properly shuffles samples within\n+ each stratum before creating the folds.\n+\n Read more in the :ref:`User Guide `.\n \n Parameters\n@@ -620,7 +623,7 @@ class StratifiedKFold(_BaseKFold):\n super().__init__(n_splits, shuffle, random_state)\n \n def _make_test_folds(self, X, y=None):\n- rng = self.random_state\n+ rng = check_random_state(self.random_state)\n y = np.asarray(y)\n type_of_target_y = type_of_target(y)\n allowed_target_types = ('binary', 'multiclass')\n@@ -645,20 +648,21 @@ class StratifiedKFold(_BaseKFold):\n \" be less than n_splits=%d.\"\n % (min_groups, self.n_splits)), Warning)\n \n- # pre-assign each sample to a test fold index using individual KFold\n- # splitting strategies for each class so as to respect the balance of\n- # classes\n- # NOTE: Passing the data corresponding to ith class say X[y==class_i]\n- # will break when the data is not 100% stratifiable for all classes.\n- # So we pass np.zeroes(max(c, n_splits)) as data to the KFold\n- per_cls_cvs = [\n- KFold(self.n_splits, shuffle=self.shuffle,\n- random_state=rng).split(np.zeros(max(count, self.n_splits)))\n- for count in y_counts]\n+ # Shuffle indices within each class\n+ indices_per_class = [np.where(y == cls)[0] for cls in unique_y]\n+ if self.shuffle:\n+ for indices in indices_per_class:\n+ rng.shuffle(indices)\n \n+ # Assign samples to folds\n test_folds = np.zeros(n_samples, dtype=np.int)\n- for test_fold_indices, per_cls_splits in enumerate(zip(*per_cls_cvs)):\n- for cls, (_, test_split) in zip(unique_y, per_cls_splits):\n+ for test_fold_index in range(self.n_splits):\n+ for cls, indices in zip(unique_y, indices_per_class):\n+ class_size = len(indices)\n+ start = int((test_fold_index * class_size) / self.n_splits)\n+ end = int(((test_fold_index + 1) * class_size) / self.n_splits)\n+ test_indices = indices[start:end]\n+ test_folds[test_indices] = test_fold_index\n cls_test_folds = test_folds[y == cls]\n # the test split can be too big because we used\n # KFold(...).split(X[:max(c, n_splits)]) when data is not 100%\n", + "test_patch": "diff --git a/sklearn/model_selection/tests/test_stratified_kfold_shuffle.py b/sklearn/model_selection/tests/test_stratified_kfold_shuffle.py\nnew file mode 100644\nindex 0000000..09ec661\n--- /dev/null\n+++ b/sklearn/model_selection/tests/test_stratified_kfold_shuffle.py\n@@ -0,0 +1,37 @@\n+import numpy as np\n+from sklearn.model_selection import StratifiedKFold\n+\n+def test_stratified_kfold_shuffle():\n+ # Set up the data\n+ samples_per_class = 10\n+ X = np.linspace(0, samples_per_class*2-1, samples_per_class * 2)\n+ y = np.concatenate((np.ones(samples_per_class), np.zeros(samples_per_class)), axis=0)\n+\n+ # Test with shuffle=True and different random states\n+ random_state_1 = 1\n+ random_state_2 = 2\n+\n+ k_fold_1 = StratifiedKFold(n_splits=10, shuffle=True, random_state=random_state_1)\n+ k_fold_2 = StratifiedKFold(n_splits=10, shuffle=True, random_state=random_state_2)\n+\n+ splits_1 = list(k_fold_1.split(X, y))\n+ splits_2 = list(k_fold_2.split(X, y))\n+\n+ # Check that the splits are the same for different random states, just in different order\n+ splits_1_sorted = sorted([tuple(sorted(split[0])) for split in splits_1])\n+ splits_2_sorted = sorted([tuple(sorted(split[0])) for split in splits_2])\n+\n+ assert splits_1_sorted == splits_2_sorted, \"Splits should be the same for different random states\"\n+\n+ # Check that each split always pairs the same indices\n+ for split in splits_1:\n+ train, test = split\n+ assert (test[0] % 10 == test[1] % 10), \"Test indices should always pair the same class indices\"\n+\n+ # Check that shuffle=True doesn't change the actual splits, just their order\n+ k_fold_no_shuffle = StratifiedKFold(n_splits=10, shuffle=False)\n+ splits_no_shuffle = list(k_fold_no_shuffle.split(X, y))\n+ \n+ splits_no_shuffle_sorted = sorted([tuple(sorted(split[0])) for split in splits_no_shuffle])\n+ \n+ assert splits_1_sorted == splits_no_shuffle_sorted, \"Shuffle should not change the actual splits\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/model_selection/tests/test_stratified_kfold_shuffle_inverted.py b/sklearn/model_selection/tests/test_stratified_kfold_shuffle_inverted.py\nnew file mode 100644\nindex 0000000..f9d106a\n--- /dev/null\n+++ b/sklearn/model_selection/tests/test_stratified_kfold_shuffle_inverted.py\n@@ -0,0 +1,45 @@\n+import numpy as np\n+from sklearn.model_selection import StratifiedKFold\n+\n+def test_stratified_kfold_shuffle():\n+ # Set up the data\n+ samples_per_class = 10\n+ X = np.linspace(0, samples_per_class*2-1, samples_per_class * 2)\n+ y = np.concatenate((np.ones(samples_per_class), np.zeros(samples_per_class)), axis=0)\n+\n+ # Test with shuffle=True and different random states\n+ random_state_1 = 1\n+ random_state_2 = 2\n+\n+ k_fold_1 = StratifiedKFold(n_splits=10, shuffle=True, random_state=random_state_1)\n+ k_fold_2 = StratifiedKFold(n_splits=10, shuffle=True, random_state=random_state_2)\n+\n+ splits_1 = list(k_fold_1.split(X, y))\n+ splits_2 = list(k_fold_2.split(X, y))\n+\n+ # Check that the splits are different for different random states\n+ splits_1_sorted = sorted([tuple(sorted(split[0])) for split in splits_1])\n+ splits_2_sorted = sorted([tuple(sorted(split[0])) for split in splits_2])\n+\n+ if splits_1_sorted == splits_2_sorted:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check that each split doesn't always pair the same indices\n+ for split in splits_1:\n+ train, test = split\n+ if test[0] % 10 == test[1] % 10:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check that shuffle=True changes the actual splits, not just their order\n+ k_fold_no_shuffle = StratifiedKFold(n_splits=10, shuffle=False)\n+ splits_no_shuffle = list(k_fold_no_shuffle.split(X, y))\n+ \n+ splits_no_shuffle_sorted = sorted([tuple(sorted(split[0])) for split in splits_no_shuffle])\n+ \n+ if splits_1_sorted == splits_no_shuffle_sorted:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Additional check: Ensure that shuffled splits are different from non-shuffled splits\n+ for split_shuffled, split_no_shuffle in zip(splits_1, splits_no_shuffle):\n+ if np.array_equal(split_shuffled[0], split_no_shuffle[0]) and np.array_equal(split_shuffled[1], split_no_shuffle[1]):\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2392624, + "num_received_chars": 184438, + "elapsed_time": 985.422735452652, + "lint_repair_count": 12, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13328.json b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13328.json new file mode 100644 index 00000000..851c2cf7 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-13328.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-13328", + "edit_test_file": "sklearn/linear_model/tests/test_huber.py", + "code_patch": "diff --git a/sklearn/linear_model/huber.py b/sklearn/linear_model/huber.py\nindex 65c6864..ec33e1b 100644\n--- a/sklearn/linear_model/huber.py\n+++ b/sklearn/linear_model/huber.py\n@@ -252,6 +252,11 @@ class HuberRegressor(LinearModel, RegressorMixin, BaseEstimator):\n \"\"\"\n X, y = check_X_y(\n X, y, copy=False, accept_sparse=['csr'], y_numeric=True)\n+ \n+ # Convert boolean input to float\n+ if X.dtype == bool:\n+ X = np.asarray(X, dtype=float)\n+ \n if sample_weight is not None:\n sample_weight = np.array(sample_weight)\n check_consistent_length(y, sample_weight)\n", + "test_patch": "diff --git a/sklearn/linear_model/tests/test_huber_boolean_input.py b/sklearn/linear_model/tests/test_huber_boolean_input.py\nnew file mode 100644\nindex 0000000..ff07323\n--- /dev/null\n+++ b/sklearn/linear_model/tests/test_huber_boolean_input.py\n@@ -0,0 +1,22 @@\n+import numpy as np\n+import pytest\n+from sklearn.datasets import make_regression\n+from sklearn.linear_model import HuberRegressor\n+\n+def test_huber_regressor_boolean_input():\n+ # Generate random regression data\n+ X, y = make_regression(n_samples=200, n_features=2, noise=4.0, random_state=0)\n+ \n+ # Convert X to boolean\n+ X_bool = X > 0\n+\n+ # Fit HuberRegressor with boolean input\n+ huber = HuberRegressor()\n+ \n+ # Assert that TypeError is raised when fitting with boolean input\n+ with pytest.raises(TypeError):\n+ huber.fit(X_bool, y)\n+\n+ # Verify that fitting works with float input\n+ X_float = X_bool.astype(float)\n+ huber.fit(X_float, y) # This should not raise an error\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/linear_model/tests/test_huber_boolean_input_inverted.py b/sklearn/linear_model/tests/test_huber_boolean_input_inverted.py\nnew file mode 100644\nindex 0000000..0157675\n--- /dev/null\n+++ b/sklearn/linear_model/tests/test_huber_boolean_input_inverted.py\n@@ -0,0 +1,32 @@\n+import numpy as np\n+import pytest\n+from sklearn.datasets import make_regression\n+from sklearn.linear_model import HuberRegressor\n+\n+def test_huber_regressor_boolean_input():\n+ # Generate random regression data\n+ X, y = make_regression(n_samples=200, n_features=2, noise=4.0, random_state=0)\n+ \n+ # Convert X to boolean\n+ X_bool = X > 0\n+\n+ # Fit HuberRegressor with boolean input\n+ huber = HuberRegressor()\n+ \n+ # This should now raise a specific error message when the bug is observed\n+ try:\n+ huber.fit(X_bool, y)\n+ except TypeError as e:\n+ if \"The numpy boolean negative, the `-` operator, is not supported\" in str(e):\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ pytest.fail(f\"Unexpected TypeError: {str(e)}\")\n+ else:\n+ pytest.fail(\"Expected TypeError was not raised\")\n+\n+ # Verify that fitting works with float input\n+ X_float = X_bool.astype(float)\n+ try:\n+ huber.fit(X_float, y)\n+ except Exception as e:\n+ pytest.fail(f\"Fitting with float input raised an unexpected error: {str(e)}\")\n\\ No newline at end of file\n", + "num_sent_chars": 1689992, + "num_received_chars": 118423, + "elapsed_time": 672.5152268409729, + "lint_repair_count": 6, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-14141.json b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-14141.json new file mode 100644 index 00000000..60893a2e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-14141.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-14141", + "edit_test_file": "sklearn/utils/tests/test_fixes.py", + "code_patch": "diff --git a/sklearn/utils/_show_versions.py b/sklearn/utils/_show_versions.py\nindex e5d3141..ecba9ec 100644\n--- a/sklearn/utils/_show_versions.py\n+++ b/sklearn/utils/_show_versions.py\n@@ -48,6 +48,7 @@ def _get_deps_info():\n \"Cython\",\n \"pandas\",\n \"matplotlib\",\n+ \"joblib\",\n ]\n \n def get_version(module):\n", + "test_patch": "diff --git a/sklearn/utils/tests/test_joblib_dependency.py b/sklearn/utils/tests/test_joblib_dependency.py\nnew file mode 100644\nindex 0000000..f4e32e0\n--- /dev/null\n+++ b/sklearn/utils/tests/test_joblib_dependency.py\n@@ -0,0 +1,22 @@\n+import pytest\n+from sklearn.utils._show_versions import _get_deps_info\n+from sklearn.utils._show_versions import show_versions\n+from sklearn import __version__ as sklearn_version\n+from packaging import version\n+\n+def test_joblib_in_deps_info():\n+ deps_info = _get_deps_info()\n+ \n+ if version.parse(sklearn_version) > version.parse(\"0.20\"):\n+ assert 'joblib' not in deps_info, \"joblib is unexpectedly listed in deps_info\"\n+ else:\n+ pytest.skip(\"This test is only relevant for sklearn versions > 0.20\")\n+\n+def test_joblib_in_show_versions(capsys):\n+ show_versions()\n+ captured = capsys.readouterr()\n+ \n+ if version.parse(sklearn_version) > version.parse(\"0.20\"):\n+ assert 'joblib' not in captured.out, \"joblib is unexpectedly listed in show_versions output\"\n+ else:\n+ pytest.skip(\"This test is only relevant for sklearn versions > 0.20\")\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/utils/tests/test_joblib_dependency_inverted.py b/sklearn/utils/tests/test_joblib_dependency_inverted.py\nnew file mode 100644\nindex 0000000..6e0fe88\n--- /dev/null\n+++ b/sklearn/utils/tests/test_joblib_dependency_inverted.py\n@@ -0,0 +1,24 @@\n+import pytest\n+from sklearn.utils._show_versions import _get_deps_info\n+from sklearn.utils._show_versions import show_versions\n+from sklearn import __version__ as sklearn_version\n+from packaging import version\n+\n+def test_joblib_in_deps_info():\n+ deps_info = _get_deps_info()\n+ \n+ if version.parse(sklearn_version) > version.parse(\"0.20\"):\n+ if 'joblib' not in deps_info:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ pytest.skip(\"This test is only relevant for sklearn versions > 0.20\")\n+\n+def test_joblib_in_show_versions(capsys):\n+ show_versions()\n+ captured = capsys.readouterr()\n+ \n+ if version.parse(sklearn_version) > version.parse(\"0.20\"):\n+ if 'joblib' not in captured.out:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ else:\n+ pytest.skip(\"This test is only relevant for sklearn versions > 0.20\")\n\\ No newline at end of file\n", + "num_sent_chars": 618231, + "num_received_chars": 21432, + "elapsed_time": 162.077862739563, + "lint_repair_count": 1, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-15100.json b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-15100.json new file mode 100644 index 00000000..3f542693 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-15100.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-15100", + "edit_test_file": "sklearn/utils/tests/test_utils.py", + "code_patch": "diff --git a/sklearn/feature_extraction/text.py b/sklearn/feature_extraction/text.py\nindex bb5a9d6..11236d9 100644\n--- a/sklearn/feature_extraction/text.py\n+++ b/sklearn/feature_extraction/text.py\n@@ -130,10 +130,7 @@ def strip_accents_unicode(s):\n ASCII equivalent.\n \"\"\"\n normalized = unicodedata.normalize('NFKD', s)\n- if normalized == s:\n- return s\n- else:\n- return ''.join([c for c in normalized if not unicodedata.combining(c)])\n+ return ''.join([c for c in normalized if not unicodedata.combining(c)])\n \n \n def strip_accents_ascii(s):\n", + "test_patch": "diff --git a/sklearn/utils/tests/test_strip_accents_unicode.py b/sklearn/utils/tests/test_strip_accents_unicode.py\nnew file mode 100644\nindex 0000000..d230eda\n--- /dev/null\n+++ b/sklearn/utils/tests/test_strip_accents_unicode.py\n@@ -0,0 +1,23 @@\n+import pytest\n+from sklearn.feature_extraction.text import strip_accents_unicode\n+\n+def test_strip_accents_unicode_nfkd_form():\n+ # Test that strip_accents_unicode fails to strip accents from strings already in NFKD form\n+\n+ # String with one code point, \"LATIN SMALL LETTER N WITH TILDE\"\n+ s1 = chr(241)\n+\n+ # String with two code points, \"LATIN SMALL LETTER N\" followed by \"COMBINING TILDE\"\n+ s2 = chr(110) + chr(771)\n+\n+ # Ensure the strings are visually identical\n+ assert s1 != s2 # They are not equal as Python strings, but visually identical\n+\n+ # Check that strip_accents_unicode works as expected for s1\n+ assert strip_accents_unicode(s1) == 'n'\n+\n+ # Check that strip_accents_unicode fails to strip accent from s2\n+ assert strip_accents_unicode(s2) == s2\n+\n+ # The expected behavior would be:\n+ # assert strip_accents_unicode(s2) == 'n'\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/utils/tests/test_strip_accents_unicode_inverted.py b/sklearn/utils/tests/test_strip_accents_unicode_inverted.py\nnew file mode 100644\nindex 0000000..2b3adfb\n--- /dev/null\n+++ b/sklearn/utils/tests/test_strip_accents_unicode_inverted.py\n@@ -0,0 +1,25 @@\n+import pytest\n+from sklearn.feature_extraction.text import strip_accents_unicode\n+\n+def test_strip_accents_unicode_nfkd_form():\n+ # Test that strip_accents_unicode fails to strip accents from strings already in NFKD form\n+\n+ # String with one code point, \"LATIN SMALL LETTER N WITH TILDE\"\n+ s1 = chr(241)\n+\n+ # String with two code points, \"LATIN SMALL LETTER N\" followed by \"COMBINING TILDE\"\n+ s2 = chr(110) + chr(771)\n+\n+ # Ensure the strings are visually identical\n+ assert s1 != s2 # They are not equal as Python strings, but visually identical\n+\n+ # Check that strip_accents_unicode works as expected for s1\n+ assert strip_accents_unicode(s1) == 'n'\n+\n+ # Check that strip_accents_unicode strips accent from s2\n+ stripped_s2 = strip_accents_unicode(s2)\n+ if stripped_s2 == s2:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # The expected behavior:\n+ assert stripped_s2 == 'n', f\"Expected 'n', but got '{stripped_s2}'\"\n", + "num_sent_chars": 766328, + "num_received_chars": 20814, + "elapsed_time": 172.66274428367615, + "lint_repair_count": 0, + "test_generation_attempts": 5, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-25747.json b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-25747.json new file mode 100644 index 00000000..67f2766d --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/scikit-learn__scikit-learn-25747.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-25747", + "edit_test_file": "sklearn/tests/test_pipeline.py", + "code_patch": "diff --git a/sklearn/utils/_set_output.py b/sklearn/utils/_set_output.py\nindex 335773c..a12bdee 100644\n--- a/sklearn/utils/_set_output.py\n+++ b/sklearn/utils/_set_output.py\n@@ -34,7 +34,13 @@ def _wrap_in_pandas_container(\n `range(n_features)`.\n \n index : array-like, default=None\n- Index for data.\n+ Index for data. If provided and the length doesn't match the data,\n+ a new default index will be created.\n+\n+ Returns\n+ -------\n+ dataframe : DataFrame\n+ Container with column names or unchanged `output`.\n \n Returns\n -------\n@@ -52,14 +58,28 @@ def _wrap_in_pandas_container(\n \n pd = check_pandas_support(\"Setting output container to 'pandas'\")\n \n- if isinstance(data_to_wrap, pd.DataFrame):\n+ if isinstance(data_to_wrap, (pd.DataFrame, pd.Series)):\n if columns is not None:\n data_to_wrap.columns = columns\n if index is not None:\n- data_to_wrap.index = index\n+ try:\n+ data_to_wrap.index = index\n+ except ValueError as e:\n+ if \"Length mismatch\" in str(e):\n+ # Create a new default index if lengths don't match\n+ data_to_wrap.index = pd.RangeIndex(len(data_to_wrap))\n+ else:\n+ raise ValueError(f\"Failed to set index: {e}\")\n return data_to_wrap\n \n- return pd.DataFrame(data_to_wrap, index=index, columns=columns)\n+ try:\n+ return pd.DataFrame(data_to_wrap, index=index, columns=columns)\n+ except ValueError as e:\n+ if \"Length of values\" in str(e) and index is not None:\n+ # Create a new default index if lengths don't match\n+ return pd.DataFrame(data_to_wrap, columns=columns)\n+ else:\n+ raise ValueError(f\"Failed to create DataFrame: {e}\")\n \n \n def _get_output_config(method, estimator=None):\n", + "test_patch": "diff --git a/sklearn/tests/test_feature_union_pandas_transform.py b/sklearn/tests/test_feature_union_pandas_transform.py\nnew file mode 100644\nindex 0000000..9d6eb95\n--- /dev/null\n+++ b/sklearn/tests/test_feature_union_pandas_transform.py\n@@ -0,0 +1,33 @@\n+import pytest\n+import pandas as pd\n+import numpy as np\n+from sklearn.base import BaseEstimator, TransformerMixin\n+from sklearn.pipeline import make_union\n+from sklearn.utils._set_output import _SetOutputMixin\n+from sklearn import set_config\n+\n+\n+class MyTransformer(BaseEstimator, TransformerMixin, _SetOutputMixin):\n+ def fit(self, X, y=None, **kwargs):\n+ return self\n+\n+ def transform(self, X):\n+ return X[\"value\"].groupby(X[\"date\"]).sum().to_frame()\n+\n+\n+@pytest.mark.parametrize(\"transform_output\", [\"default\", \"pandas\"])\n+def test_feature_union_pandas_transform(transform_output):\n+ index = pd.date_range(start=\"2020-01-01\", end=\"2020-01-05\", inclusive=\"left\", freq=\"H\")\n+ data = pd.DataFrame(index=index, data=[10] * len(index), columns=[\"value\"])\n+ data[\"date\"] = index.date\n+\n+ set_config(transform_output=transform_output)\n+ \n+ if transform_output == \"default\":\n+ # This should work without errors\n+ result = make_union(MyTransformer()).fit_transform(data)\n+ assert isinstance(result, np.ndarray)\n+ else:\n+ # This should raise a ValueError\n+ with pytest.raises(ValueError, match=\"Length mismatch: Expected axis has 4 elements, new values have 96 elements\"):\n+ make_union(MyTransformer()).fit_transform(data)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/tests/test_feature_union_pandas_transform_inverted.py b/sklearn/tests/test_feature_union_pandas_transform_inverted.py\nnew file mode 100644\nindex 0000000..91598ef\n--- /dev/null\n+++ b/sklearn/tests/test_feature_union_pandas_transform_inverted.py\n@@ -0,0 +1,41 @@\n+import pytest\n+import pandas as pd\n+import numpy as np\n+from sklearn.base import BaseEstimator, TransformerMixin\n+from sklearn.pipeline import make_union\n+from sklearn.utils._set_output import _SetOutputMixin\n+from sklearn import set_config\n+\n+\n+class MyTransformer(BaseEstimator, TransformerMixin, _SetOutputMixin):\n+ def fit(self, X, y=None, **kwargs):\n+ return self\n+\n+ def transform(self, X):\n+ return X[\"value\"].groupby(X[\"date\"]).sum().to_frame()\n+\n+\n+@pytest.mark.parametrize(\"transform_output\", [\"default\", \"pandas\"])\n+def test_feature_union_pandas_transform(transform_output):\n+ index = pd.date_range(start=\"2020-01-01\", end=\"2020-01-05\", inclusive=\"left\", freq=\"H\")\n+ data = pd.DataFrame(index=index, data=[10] * len(index), columns=[\"value\"])\n+ data[\"date\"] = index.date\n+\n+ set_config(transform_output=transform_output)\n+ \n+ if transform_output == \"default\":\n+ # This should work without errors\n+ result = make_union(MyTransformer()).fit_transform(data)\n+ assert isinstance(result, np.ndarray)\n+ else:\n+ # This should now fail with a specific error message\n+ try:\n+ result = make_union(MyTransformer()).fit_transform(data)\n+ except ValueError as e:\n+ if \"Length mismatch: Expected axis has 4 elements, new values have 96 elements\" in str(e):\n+ raise ValueError(\"__BUG__HERE__\") from e\n+ else:\n+ raise # Re-raise if it's a different ValueError\n+ else:\n+ # If no exception was raised, the test should fail\n+ pytest.fail(\"Expected ValueError was not raised\")\n\\ No newline at end of file\n", + "num_sent_chars": 1335410, + "num_received_chars": 69727, + "elapsed_time": 448.0745053291321, + "lint_repair_count": 0, + "test_generation_attempts": 8, + "code_generation_attempts": 3, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10323.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10323.json new file mode 100644 index 00000000..ad20f770 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10323.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-10323", + "edit_test_file": "tests/test_directive_code.py", + "code_patch": "diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py\nindex dc44ed3..400e9a1 100644\n--- a/sphinx/directives/code.py\n+++ b/sphinx/directives/code.py\n@@ -414,6 +414,13 @@ class LiteralInclude(SphinxDirective):\n reader = LiteralIncludeReader(filename, self.options, self.config)\n text, lines = reader.read(location=location)\n \n+ # Process the content with prepended and appended text\n+ from sphinx.util.nodes import process_literalinclude_content\n+ prepend = self.options.get('prepend')\n+ append = self.options.get('append')\n+ dedent = self.options.get('dedent')\n+ text = process_literalinclude_content(text, prepend, append, dedent)\n+\n retnode: Element = nodes.literal_block(text, text, source=filename)\n retnode['force'] = 'force' in self.options\n self.set_source_info(retnode)\n\ndiff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py\nindex 4abc3af..60b0404 100644\n--- a/sphinx/util/nodes.py\n+++ b/sphinx/util/nodes.py\n@@ -18,6 +18,34 @@ from sphinx.util import logging\n if TYPE_CHECKING:\n from sphinx.builders import Builder\n from sphinx.domain import IndexEntry\n+\n+def detect_indentation(text: str) -> int:\n+ \"\"\"Detect the indentation level of the first non-empty line in the given text.\"\"\"\n+ for line in text.splitlines():\n+ if line.strip():\n+ return len(line) - len(line.lstrip())\n+ return 0\n+\n+def apply_indentation(text: str, indent: int) -> str:\n+ \"\"\"Apply the given indentation to each line of the text.\"\"\"\n+ return '\\n'.join((' ' * indent + line if line.strip() else line)\n+ for line in text.splitlines())\n+\n+def process_literalinclude_content(content: str, prepend: Optional[str], append: Optional[str], dedent: Optional[int]) -> str:\n+ \"\"\"Process literalinclude content with prepended and appended text, preserving indentation.\"\"\"\n+ content_indent = detect_indentation(content)\n+ \n+ if dedent:\n+ content = '\\n'.join(line[min(dedent, len(line) - len(line.lstrip())):]\n+ for line in content.splitlines())\n+ \n+ if prepend:\n+ content = apply_indentation(prepend, content_indent) + '\\n' + content\n+ \n+ if append:\n+ content = content + '\\n' + apply_indentation(append, content_indent)\n+ \n+ return content\n from sphinx.environment import BuildEnvironment\n from sphinx.util.tags import Tags\n \n", + "test_patch": "diff --git a/tests/test_literalinclude_indentation.py b/tests/test_literalinclude_indentation.py\nnew file mode 100644\nindex 0000000..a191d62\n--- /dev/null\n+++ b/tests/test_literalinclude_indentation.py\n@@ -0,0 +1,56 @@\n+import os\n+import pytest\n+from sphinx.testing.util import etree_parse\n+from sphinx.testing.path import path\n+\n+@pytest.mark.sphinx('xml', testroot='directive-code')\n+def test_literalinclude_prepend_indentation(app, status, warning):\n+ # Prepare test files\n+ test_dir = (app.srcdir / 'test_literalinclude_prepend')\n+ test_dir.makedirs(exist_ok=True)\n+ \n+ (test_dir / 'index.rst').write_text('''\n+.. literalinclude:: pom.xml\n+ :language: xml\n+ :prepend: \n+ :start-at: com.github.ekryd.sortpom\n+ :end-at: \n+''')\n+\n+ (test_dir / 'pom.xml').write_text('''\n+\n+\n+ \n+ \n+ \n+ com.github.ekryd.sortpom\n+ sortpom-maven-plugin\n+ 2.15.0\n+ \n+ strict\n+ \n+ \n+ \n+ \n+\n+''')\n+\n+ app.builder.build(['test_literalinclude_prepend/index'])\n+ \n+ # Parse the generated XML\n+ xml_path = app.outdir / 'test_literalinclude_prepend' / 'index.xml'\n+ etree = etree_parse(xml_path)\n+ literal_block = etree.find('.//literal_block')\n+ \n+ # Check if the indentation is incorrect as described in the issue\n+ expected_incorrect_output = '''\n+ com.github.ekryd.sortpom\n+ sortpom-maven-plugin\n+ 2.15.0\n+ \n+ strict\n+ \n+ '''\n+ \n+ assert literal_block.text.strip() == expected_incorrect_output.strip(), \\\n+ \"The literalinclude output should have incorrect indentation as described in the issue\"\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2209416, + "num_received_chars": 159147, + "elapsed_time": 850.1441111564636, + "lint_repair_count": 8, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10466.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10466.json new file mode 100644 index 00000000..427e9b35 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-10466.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-10466", + "edit_test_file": "tests/test_util_docutils.py", + "code_patch": "diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py\nindex e8bc547..3c2f2e9 100644\n--- a/sphinx/builders/gettext.py\n+++ b/sphinx/builders/gettext.py\n@@ -32,9 +32,15 @@ class Message:\n \"\"\"An entry of translatable message.\"\"\"\n def __init__(self, text: str, locations: List[Tuple[str, int]], uuids: List[str]):\n self.text = text\n- self.locations = locations\n+ self.locations = self._unique_locations(locations)\n self.uuids = uuids\n \n+ @staticmethod\n+ def _unique_locations(locations: List[Tuple[str, int]]) -> List[Tuple[str, int]]:\n+ \"\"\"Convert locations to a unique list.\"\"\"\n+ unique_locations = list(dict.fromkeys(locations))\n+ return sorted(unique_locations, key=lambda x: (x[0], x[1]))\n+\n \n class Catalog:\n \"\"\"Catalog of translatable messages.\"\"\"\n", + "test_patch": "diff --git a/tests/test_message_location_deduplication.py b/tests/test_message_location_deduplication.py\nnew file mode 100644\nindex 0000000..cb30063\n--- /dev/null\n+++ b/tests/test_message_location_deduplication.py\n@@ -0,0 +1,56 @@\n+import unittest\n+from sphinx.builders.gettext import Message\n+\n+class TestMessageLocationDeduplication(unittest.TestCase):\n+ def test_duplicate_locations(self):\n+ # Create a Message object with duplicate locations\n+ text = \"Type\"\n+ locations = [\n+ (\"../../manual/modeling/hair.rst\", 0),\n+ (\"../../manual/modeling/hair.rst\", 0),\n+ (\"../../manual/modeling/hair.rst\", 0),\n+ (\"../../manual/modeling/metas/properties.rst\", 92),\n+ (\"../../manual/render/shader_nodes/vector/vector_rotate.rst\", 38),\n+ ]\n+ uuids = [\"uuid1\", \"uuid2\", \"uuid3\", \"uuid4\", \"uuid5\"]\n+\n+ message = Message(text, locations, uuids)\n+\n+ # Assert that the locations list contains duplicates\n+ self.assertEqual(len(message.locations), 5)\n+ self.assertEqual(message.locations.count((\"../../manual/modeling/hair.rst\", 0)), 3)\n+\n+ # Assert that the locations list is in the original order (not deduplicated)\n+ self.assertEqual(message.locations, locations)\n+\n+ def test_multiple_duplicate_locations(self):\n+ # Create a Message object with multiple sets of duplicate locations\n+ text = \"Another message\"\n+ locations = [\n+ (\"../../manual/movie_clip/tracking/clip/toolbar/solve.rst\", 96),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/fluid/type/domain/cache.rst\", 0),\n+ ]\n+ uuids = [f\"uuid{i}\" for i in range(1, len(locations) + 1)]\n+\n+ message = Message(text, locations, uuids)\n+\n+ # Assert that the locations list contains duplicates\n+ self.assertEqual(len(message.locations), 12)\n+ self.assertEqual(message.locations.count((\"../../manual/physics/dynamic_paint/brush.rst\", 0)), 4)\n+ self.assertEqual(message.locations.count((\"../../manual/physics/dynamic_paint/canvas.rst\", 0)), 6)\n+\n+ # Assert that the locations list is in the original order (not deduplicated)\n+ self.assertEqual(message.locations, locations)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_message_location_deduplication_inverted.py b/tests/test_message_location_deduplication_inverted.py\nnew file mode 100644\nindex 0000000..9a3ca7f\n--- /dev/null\n+++ b/tests/test_message_location_deduplication_inverted.py\n@@ -0,0 +1,58 @@\n+import unittest\n+from sphinx.builders.gettext import Message\n+\n+class TestMessageLocationDeduplication(unittest.TestCase):\n+ def test_duplicate_locations(self):\n+ # Create a Message object with duplicate locations\n+ text = \"Type\"\n+ locations = [\n+ (\"../../manual/modeling/hair.rst\", 0),\n+ (\"../../manual/modeling/hair.rst\", 0),\n+ (\"../../manual/modeling/hair.rst\", 0),\n+ (\"../../manual/modeling/metas/properties.rst\", 92),\n+ (\"../../manual/render/shader_nodes/vector/vector_rotate.rst\", 38),\n+ ]\n+ uuids = [\"uuid1\", \"uuid2\", \"uuid3\", \"uuid4\", \"uuid5\"]\n+\n+ message = Message(text, locations, uuids)\n+\n+ # Check if the locations list contains duplicates\n+ if len(message.locations) == 5 and message.locations.count((\"../../manual/modeling/hair.rst\", 0)) == 3:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Assert that the locations list is deduplicated\n+ self.assertEqual(len(message.locations), 3)\n+ self.assertEqual(message.locations.count((\"../../manual/modeling/hair.rst\", 0)), 1)\n+\n+ def test_multiple_duplicate_locations(self):\n+ # Create a Message object with multiple sets of duplicate locations\n+ text = \"Another message\"\n+ locations = [\n+ (\"../../manual/movie_clip/tracking/clip/toolbar/solve.rst\", 96),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/brush.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/dynamic_paint/canvas.rst\", 0),\n+ (\"../../manual/physics/fluid/type/domain/cache.rst\", 0),\n+ ]\n+ uuids = [f\"uuid{i}\" for i in range(1, len(locations) + 1)]\n+\n+ message = Message(text, locations, uuids)\n+\n+ # Check if the locations list contains duplicates\n+ if len(message.locations) == 12 and message.locations.count((\"../../manual/physics/dynamic_paint/brush.rst\", 0)) == 4 and message.locations.count((\"../../manual/physics/dynamic_paint/canvas.rst\", 0)) == 6:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Assert that the locations list is deduplicated\n+ self.assertEqual(len(message.locations), 4)\n+ self.assertEqual(message.locations.count((\"../../manual/physics/dynamic_paint/brush.rst\", 0)), 1)\n+ self.assertEqual(message.locations.count((\"../../manual/physics/dynamic_paint/canvas.rst\", 0)), 1)\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n", + "num_sent_chars": 838164, + "num_received_chars": 36963, + "elapsed_time": 245.23558616638184, + "lint_repair_count": 1, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-11445.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-11445.json new file mode 100644 index 00000000..9f8d7292 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-11445.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-11445", + "edit_test_file": "tests/test_util_rst.py", + "code_patch": "diff --git a/sphinx/util/rst.py b/sphinx/util/rst.py\nindex 7a15383..eabdcbc 100644\n--- a/sphinx/util/rst.py\n+++ b/sphinx/util/rst.py\n@@ -75,26 +75,53 @@ def default_role(docname: str, name: str) -> Generator[None, None, None]:\n docutils.unregister_role('')\n \n \n+import re\n+from typing import Optional\n+\n+def is_heading_with_domain_directive(line: str) -> bool:\n+ \"\"\"Check if the line is a heading with a domain directive.\"\"\"\n+ heading_pattern = r'^[=\\-`:\\'\"~^_*+#<>]{3,}$'\n+ domain_directive_pattern = r':(mod|class|func|meth|attr|data|exc|const):`'\n+ return bool(re.match(heading_pattern, line) or re.search(domain_directive_pattern, line))\n+\n+def find_first_non_empty_line(content: StringList) -> Optional[int]:\n+ \"\"\"Find the index of the first non-empty line in the content.\"\"\"\n+ for i, line in enumerate(content):\n+ if line.strip():\n+ return i\n+ return None\n+\n def prepend_prolog(content: StringList, prolog: str) -> None:\n \"\"\"Prepend a string to content body as prolog.\"\"\"\n- if prolog:\n- pos = 0\n+ if not prolog:\n+ return\n+\n+ pos = 0\n+ first_non_empty = find_first_non_empty_line(content)\n+\n+ if first_non_empty is not None and is_heading_with_domain_directive(content[first_non_empty]):\n+ # If the first non-empty line is a heading with a domain directive,\n+ # insert the prolog after it\n+ pos = first_non_empty + 1\n+ else:\n+ # Otherwise, insert after docinfo\n for line in content:\n if docinfo_re.match(line):\n pos += 1\n else:\n break\n \n- if pos > 0:\n- # insert a blank line after docinfo\n- content.insert(pos, '', '', 0)\n- pos += 1\n+ if pos > 0:\n+ # Insert a blank line after docinfo or heading\n+ content.insert(pos, '', '', 0)\n+ pos += 1\n \n- # insert prolog (after docinfo if exists)\n- for lineno, line in enumerate(prolog.splitlines()):\n- content.insert(pos + lineno, line, '', lineno)\n+ # Insert prolog\n+ for lineno, line in enumerate(prolog.splitlines()):\n+ content.insert(pos + lineno, line, '', lineno)\n \n- content.insert(pos + lineno + 1, '', '', 0)\n+ # Insert a blank line after prolog\n+ content.insert(pos + lineno + 1, '', '', 0)\n \n \n def append_epilog(content: StringList, epilog: str) -> None:\n", + "test_patch": "diff --git a/tests/test_rst_prolog_domain_directive.py b/tests/test_rst_prolog_domain_directive.py\nnew file mode 100644\nindex 0000000..36be223\n--- /dev/null\n+++ b/tests/test_rst_prolog_domain_directive.py\n@@ -0,0 +1,57 @@\n+import os\n+from pathlib import Path\n+\n+import pytest\n+from sphinx.testing.util import SphinxTestApp, path\n+from sphinx.util.osutil import ensuredir\n+\n+\n+@pytest.mark.sphinx('html')\n+def test_rst_prolog_domain_directive(tmp_path, monkeypatch):\n+ # Create a minimal Sphinx project\n+ srcdir = Path(tmp_path)\n+ ensuredir(srcdir)\n+\n+ # Create configuration file\n+ with open(srcdir / 'conf.py', 'w') as f:\n+ f.write('rst_prolog = \"\"\"\\n.. |psf| replace:: Python Software Foundation\\n\"\"\"\\n')\n+\n+ # Create index.rst\n+ with open(srcdir / 'index.rst', 'w') as f:\n+ f.write('''\n+Welcome\n+=======\n+\n+.. toctree::\n+\n+ mypackage\n+''')\n+\n+ # Create mypackage.rst with domain directive in the heading\n+ with open(srcdir / 'mypackage.rst', 'w') as f:\n+ f.write('''\n+:mod:`mypackage2`\n+=================\n+\n+Content\n+\n+Subheading\n+----------\n+''')\n+\n+ # Create and initialize the Sphinx application\n+ app = SphinxTestApp(srcdir=path(srcdir), status=None, warning=None)\n+ app.build()\n+\n+ # Read the generated HTML file\n+ with open(app.outdir / 'mypackage.html', 'r') as f:\n+ content = f.read()\n+\n+ # Check if the heading with domain directive is missing\n+ assert ':mod:`mypackage2`' not in content, \"The heading with domain directive should be missing\"\n+\n+ # Check if the subheading is present (to ensure the rest of the content is there)\n+ assert '

        Subheading' in content, \"The subheading should be present\"\n+\n+ # Clean up\n+ app.cleanup()\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_rst_prolog_domain_directive_inverted.py b/tests/test_rst_prolog_domain_directive_inverted.py\nnew file mode 100644\nindex 0000000..48e0634\n--- /dev/null\n+++ b/tests/test_rst_prolog_domain_directive_inverted.py\n@@ -0,0 +1,65 @@\n+import os\n+from pathlib import Path\n+\n+import pytest\n+from sphinx.testing.util import SphinxTestApp, path\n+from sphinx.util.osutil import ensuredir\n+\n+\n+@pytest.mark.sphinx('html')\n+def test_rst_prolog_domain_directive(tmp_path, monkeypatch):\n+ # Create a minimal Sphinx project\n+ srcdir = Path(tmp_path)\n+ ensuredir(srcdir)\n+\n+ # Create configuration file\n+ with open(srcdir / 'conf.py', 'w') as f:\n+ f.write('rst_prolog = \"\"\"\\n.. |psf| replace:: Python Software Foundation\\n\"\"\"\\n')\n+\n+ # Create index.rst\n+ with open(srcdir / 'index.rst', 'w') as f:\n+ f.write('''\n+Welcome\n+=======\n+\n+.. toctree::\n+\n+ mypackage\n+''')\n+\n+ # Create mypackage.rst with domain directive in the heading\n+ with open(srcdir / 'mypackage.rst', 'w') as f:\n+ f.write('''\n+:mod:`mypackage2`\n+=================\n+\n+Content\n+\n+Subheading\n+----------\n+''')\n+\n+ # Create and initialize the Sphinx application\n+ app = SphinxTestApp(srcdir=path(srcdir), status=None, warning=None)\n+ app.build()\n+\n+ # Read the generated HTML file\n+ with open(app.outdir / 'mypackage.html', 'r') as f:\n+ content = f.read()\n+\n+ # Check if the heading with domain directive is present\n+ if ':mod:`mypackage2`' not in content:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check if the subheading is present (to ensure the rest of the content is there)\n+ assert '

        Subheading' in content, \"The subheading should be present\"\n+\n+ # Check if the heading is included in the toctree\n+ with open(app.outdir / 'index.html', 'r') as f:\n+ index_content = f.read()\n+ \n+ if 'mypackage2' not in index_content:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Clean up\n+ app.cleanup()\n\\ No newline at end of file\n", + "num_sent_chars": 1563269, + "num_received_chars": 102421, + "elapsed_time": 590.1924397945404, + "lint_repair_count": 6, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7454.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7454.json new file mode 100644 index 00000000..fa267043 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7454.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-7454", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py\nindex 893bb0a..34925d6 100644\n--- a/sphinx/domains/python.py\n+++ b/sphinx/domains/python.py\n@@ -71,6 +71,9 @@ pairindextypes = {\n def _parse_annotation(annotation: str) -> List[Node]:\n \"\"\"Parse type annotation.\"\"\"\n def make_xref(text: str) -> addnodes.pending_xref:\n+ if text == 'None':\n+ return pending_xref('', nodes.Text(text),\n+ refdomain='py', reftype='obj', reftarget=text)\n return pending_xref('', nodes.Text(text),\n refdomain='py', reftype='class', reftarget=text)\n \n@@ -92,6 +95,8 @@ def _parse_annotation(annotation: str) -> List[Node]:\n elif isinstance(node, ast.Module):\n return sum((unparse(e) for e in node.body), [])\n elif isinstance(node, ast.Name):\n+ if node.id == 'None':\n+ return [make_xref(node.id)]\n return [nodes.Text(node.id)]\n elif isinstance(node, ast.Subscript):\n result = unparse(node.value)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2820833, + "num_received_chars": 155420, + "elapsed_time": 870.8634045124054, + "lint_repair_count": 9, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7748.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7748.json new file mode 100644 index 00000000..3841172f --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7748.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-7748", + "edit_test_file": "tests/test_util_inspect.py", + "code_patch": "diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py\nindex f8e4be9..cb60840 100644\n--- a/sphinx/ext/autodoc/__init__.py\n+++ b/sphinx/ext/autodoc/__init__.py\n@@ -1037,39 +1037,40 @@ class DocstringSignatureMixin:\n feature of reading the signature from the docstring.\n \"\"\"\n \n- def _find_signature(self, encoding: str = None) -> Tuple[str, str]:\n+ def _find_signature(self, encoding: str = None) -> List[Tuple[str, str]]:\n if encoding is not None:\n warnings.warn(\"The 'encoding' argument to autodoc.%s._find_signature() is \"\n \"deprecated.\" % self.__class__.__name__,\n RemovedInSphinx40Warning, stacklevel=2)\n docstrings = self.get_doc()\n self._new_docstrings = docstrings[:]\n- result = None\n+ results = []\n for i, doclines in enumerate(docstrings):\n # no lines in docstring, no match\n if not doclines:\n continue\n- # match first line of docstring against signature RE\n- match = py_ext_sig_re.match(doclines[0])\n- if not match:\n- continue\n- exmod, path, base, args, retann = match.groups()\n- # the base name must match ours\n- valid_names = [self.objpath[-1]] # type: ignore\n- if isinstance(self, ClassDocumenter):\n- valid_names.append('__init__')\n- if hasattr(self.object, '__mro__'):\n- valid_names.extend(cls.__name__ for cls in self.object.__mro__)\n- if base not in valid_names:\n- continue\n- # re-prepare docstring to ignore more leading indentation\n- tab_width = self.directive.state.document.settings.tab_width # type: ignore\n- self._new_docstrings[i] = prepare_docstring('\\n'.join(doclines[1:]),\n- tabsize=tab_width)\n- result = args, retann\n- # don't look any further\n- break\n- return result\n+ # match all lines of docstring against signature RE\n+ for j, line in enumerate(doclines):\n+ match = py_ext_sig_re.match(line)\n+ if not match:\n+ continue\n+ exmod, path, base, args, retann = match.groups()\n+ # the base name must match ours\n+ valid_names = [self.objpath[-1]] # type: ignore\n+ if isinstance(self, ClassDocumenter):\n+ valid_names.append('__init__')\n+ if hasattr(self.object, '__mro__'):\n+ valid_names.extend(cls.__name__ for cls in self.object.__mro__)\n+ if base not in valid_names:\n+ continue\n+ # re-prepare docstring to ignore more leading indentation\n+ tab_width = self.directive.state.document.settings.tab_width # type: ignore\n+ self._new_docstrings[i] = prepare_docstring('\\n'.join(doclines[j + 1:]),\n+ tabsize=tab_width)\n+ results.append((args, retann))\n+ if not results:\n+ break\n+ return results\n \n def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:\n if encoding is not None:\n@@ -1085,9 +1086,15 @@ class DocstringSignatureMixin:\n if self.args is None and self.env.config.autodoc_docstring_signature: # type: ignore\n # only act if a signature is not explicitly given already, and if\n # the feature is enabled\n- result = self._find_signature()\n- if result is not None:\n- self.args, self.retann = result\n+ results = self._find_signature()\n+ if results:\n+ signatures = []\n+ for args, retann in results:\n+ sig = args\n+ if retann:\n+ sig += ' -> ' + retann\n+ signatures.append(sig)\n+ return '\\n'.join(signatures)\n return super().format_signature(**kwargs) # type: ignore\n \n \n", + "test_patch": "diff --git a/tests/test_autodoc_docstring_signature_overloaded.py b/tests/test_autodoc_docstring_signature_overloaded.py\nnew file mode 100644\nindex 0000000..df00ca8\n--- /dev/null\n+++ b/tests/test_autodoc_docstring_signature_overloaded.py\n@@ -0,0 +1,49 @@\n+\"\"\"\n+ test_autodoc_docstring_signature_overloaded\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+ Test the autodoc_docstring_signature functionality with overloaded methods.\n+\n+ :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.\n+ :license: BSD, see LICENSE for details.\n+\"\"\"\n+\n+import pytest\n+from sphinx.util import inspect\n+\n+def test_autodoc_docstring_signature_overloaded():\n+ class SwigWrappedClass:\n+ def overloaded_method(self):\n+ \"\"\"\n+ overloaded_method(self)\n+ overloaded_method(self, int arg1)\n+ overloaded_method(self, float arg1)\n+\n+ This is an overloaded method with multiple signatures.\n+ \"\"\"\n+ pass\n+\n+ # Get all signatures from the docstring\n+ docstring_lines = SwigWrappedClass.overloaded_method.__doc__.split('\\n')\n+ signatures = [line.strip() for line in docstring_lines[:3]]\n+\n+ # Try to parse each signature\n+ parsed_signatures = []\n+ for sig in signatures:\n+ try:\n+ parsed_sig = inspect.signature_from_str(sig)\n+ parsed_signatures.append(str(parsed_sig))\n+ except Exception:\n+ pass\n+\n+ # Assert that only the first signature is successfully parsed\n+ assert len(parsed_signatures) == 1\n+ assert parsed_signatures[0] == '(self)'\n+\n+ # This assertion would fail if all signatures were correctly parsed\n+ with pytest.raises(AssertionError):\n+ assert len(parsed_signatures) == 3\n+ assert parsed_signatures == ['(self)', '(self, arg1: int)', '(self, arg1: float)']\n+\n+if __name__ == '__main__':\n+ pytest.main([__file__])\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_autodoc_docstring_signature_overloaded_inverted.py b/tests/test_autodoc_docstring_signature_overloaded_inverted.py\nnew file mode 100644\nindex 0000000..68106b9\n--- /dev/null\n+++ b/tests/test_autodoc_docstring_signature_overloaded_inverted.py\n@@ -0,0 +1,49 @@\n+\"\"\"\n+ test_autodoc_docstring_signature_overloaded\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+ Test the autodoc_docstring_signature functionality with overloaded methods.\n+\n+ :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.\n+ :license: BSD, see LICENSE for details.\n+\"\"\"\n+\n+import pytest\n+from sphinx.util import inspect\n+\n+def test_autodoc_docstring_signature_overloaded():\n+ class SwigWrappedClass:\n+ def overloaded_method(self):\n+ \"\"\"\n+ overloaded_method(self)\n+ overloaded_method(self, int arg1)\n+ overloaded_method(self, float arg1)\n+\n+ This is an overloaded method with multiple signatures.\n+ \"\"\"\n+ pass\n+\n+ # Get all signatures from the docstring\n+ docstring_lines = SwigWrappedClass.overloaded_method.__doc__.split('\\n')\n+ signatures = [line.strip() for line in docstring_lines[:3]]\n+\n+ # Try to parse each signature\n+ parsed_signatures = []\n+ for sig in signatures:\n+ try:\n+ parsed_sig = inspect.signature_from_str(sig)\n+ parsed_signatures.append(str(parsed_sig))\n+ except Exception:\n+ pass\n+\n+ # Assert that all signatures are successfully parsed\n+ if len(parsed_signatures) != 3:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check if all signatures are correctly parsed\n+ expected_signatures = ['(self)', '(self, arg1: int)', '(self, arg1: float)']\n+ if parsed_signatures != expected_signatures:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+if __name__ == '__main__':\n+ pytest.main([__file__])\n\\ No newline at end of file\n", + "num_sent_chars": 2303136, + "num_received_chars": 164184, + "elapsed_time": 877.6676216125488, + "lint_repair_count": 9, + "test_generation_attempts": 5, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7910.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7910.json new file mode 100644 index 00000000..e5eb99d8 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-7910.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-7910", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py\nindex 4ca6062..8a4af08 100644\n--- a/sphinx/domains/python.py\n+++ b/sphinx/domains/python.py\n@@ -1200,6 +1200,44 @@ class PythonDomain(Domain):\n if mod.docname == docname:\n del self.modules[modname]\n \n+ def _is_class_member(self, method: Any, cls: type) -> bool:\n+ \"\"\"Determine if a method belongs to a class.\"\"\"\n+ if not hasattr(method, '__qualname__'):\n+ return False\n+\n+ method_class = method.__qualname__.rsplit('.', 1)[0]\n+ return method_class == cls.__name__\n+\n+ def _find_method_in_class(self, method_name: str, cls: type) -> bool:\n+ \"\"\"Find a method in a class or its base classes.\"\"\"\n+ if method_name in cls.__dict__:\n+ return True\n+ for base in cls.__bases__:\n+ if self._find_method_in_class(method_name, base):\n+ return True\n+ return False\n+\n+ def determine_class_ownership(self, method: Any, cls: type) -> bool:\n+ \"\"\"Determine if a method belongs to a class using multiple approaches.\"\"\"\n+ # Check using __qualname__\n+ if self._is_class_member(method, cls):\n+ return True\n+\n+ # Fallback: check in class __dict__ and base classes\n+ method_name = method.__name__\n+ return self._find_method_in_class(method_name, cls)\n+\n+ def process_docstring(self, app, what, name, obj, options, lines):\n+ \"\"\"Process the docstring for a given Python object.\"\"\"\n+ if what in ('method', 'function') and name.endswith('.__init__'):\n+ cls_name = name.rsplit('.', 2)[-2]\n+ cls = self.env.temp_data.get('py:class')\n+ if cls and cls.__name__ == cls_name:\n+ if self.determine_class_ownership(obj, cls):\n+ # Include the __init__ method in the documentation\n+ return lines\n+ return None\n+\n def merge_domaindata(self, docnames: List[str], otherdata: Dict) -> None:\n # XXX check duplicates?\n for fullname, obj in otherdata['objects'].items():\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1515475, + "num_received_chars": 76951, + "elapsed_time": 435.57328152656555, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 4, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8056.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8056.json new file mode 100644 index 00000000..411a8a03 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8056.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8056", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py\nindex 832ee4a..b5dc93a 100644\n--- a/sphinx/ext/autodoc/__init__.py\n+++ b/sphinx/ext/autodoc/__init__.py\n@@ -1092,11 +1092,16 @@ class DocstringSignatureMixin:\n if hasattr(self.object, '__mro__'):\n valid_names.extend(cls.__name__ for cls in self.object.__mro__)\n \n+ # Regular expression to match multiple parameters on a single line\n+ param_re = re.compile(r'^\\s*([^:]+)\\s*:\\s*(.+?)(?:\\s*\\(optional\\))?\\s*$')\n+ multi_param_re = re.compile(r'^([^,]+(?:,\\s*[^,]+)*)\\s*:\\s*(.+?)(?:\\s*\\(optional\\))?\\s*$')\n+\n docstrings = self.get_doc()\n self._new_docstrings = docstrings[:]\n self._signatures = []\n result = None\n for i, doclines in enumerate(docstrings):\n+ parameters = []\n for j, line in enumerate(doclines):\n if not line:\n # no lines in docstring, no match\n@@ -1111,9 +1116,25 @@ class DocstringSignatureMixin:\n # match first line of docstring against signature RE\n match = py_ext_sig_re.match(line)\n if not match:\n+ # Check for parameter lines\n+ param_match = param_re.match(line)\n+ if param_match:\n+ param_names, param_type = param_match.groups()\n+ multi_param_match = multi_param_re.match(param_names)\n+ if multi_param_match:\n+ param_list = [p.strip() for p in multi_param_match.group(1).split(',')]\n+ for param in param_list:\n+ parameters.append((param, param_type, 'optional' in line))\n+ else:\n+ parameters.append((param_names, param_type, 'optional' in line))\n continue\n exmod, path, base, args, retann = match.groups()\n \n+ # Process collected parameters\n+ if parameters:\n+ self._process_parameters(parameters)\n+ parameters = []\n+\n # the base name must match ours\n if base not in valid_names:\n continue\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2131491, + "num_received_chars": 153805, + "elapsed_time": 791.4415683746338, + "lint_repair_count": 6, + "test_generation_attempts": 9, + "code_generation_attempts": 7, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8269.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8269.json new file mode 100644 index 00000000..9728f38a --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8269.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8269", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/util/requests.py b/sphinx/util/requests.py\nindex b3fc8bc..ffa9885 100644\n--- a/sphinx/util/requests.py\n+++ b/sphinx/util/requests.py\n@@ -108,7 +108,14 @@ def get(url: str, **kwargs: Any) -> requests.Response:\n headers.setdefault('User-Agent', useragent_header[0][1])\n \n with ignore_insecure_warning(**kwargs):\n- return requests.get(url, **kwargs)\n+ response = requests.get(url, **kwargs)\n+ try:\n+ response.raise_for_status()\n+ except requests.HTTPError as e:\n+ # Attach the full error information to the response object\n+ response.sphinx_http_error = str(e)\n+ response.sphinx_status_code = e.response.status_code\n+ return response\n \n \n def head(url: str, **kwargs: Any) -> requests.Response:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1896164, + "num_received_chars": 95414, + "elapsed_time": 1053.6668467521667, + "lint_repair_count": 2, + "test_generation_attempts": 9, + "code_generation_attempts": 6, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8548.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8548.json new file mode 100644 index 00000000..1da55ca7 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8548.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8548", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py\nindex ddfd2b3..63cb606 100644\n--- a/sphinx/ext/autodoc/__init__.py\n+++ b/sphinx/ext/autodoc/__init__.py\n@@ -2246,6 +2246,7 @@ class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type:\n option_spec = dict(ModuleLevelDocumenter.option_spec)\n option_spec[\"annotation\"] = annotation_option\n option_spec[\"no-value\"] = bool_option\n+ option_spec[\"inherited-members\"] = inherited_members_option\n \n # must be higher than the MethodDocumenter, else it will recognize\n # some non-data descriptors as methods\n@@ -2368,10 +2369,34 @@ class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type:\n # ref: https://github.com/sphinx-doc/sphinx/issues/7805\n orig = self.config.autodoc_inherit_docstrings\n self.config.autodoc_inherit_docstrings = False # type: ignore\n- return super().get_doc(encoding, ignore)\n+ \n+ doc = super().get_doc(encoding, ignore)\n+ \n+ # If no docstring found and inherited-members option is enabled,\n+ # search for docstring in base classes\n+ if not doc and self.options.inherited_members:\n+ doc = self.get_inherited_attribute_doc()\n+ \n+ return doc\n finally:\n self.config.autodoc_inherit_docstrings = orig # type: ignore\n \n+ def get_inherited_attribute_doc(self) -> List[List[str]]:\n+ \"\"\"\n+ Recursively search for docstring in base classes.\n+ \"\"\"\n+ for base in self.parent.__mro__[1:]: # Skip the class itself\n+ try:\n+ attr = safe_getattr(base, self.objpath[-1])\n+ doc = getdoc(attr, self.get_attr,\n+ self.config.autodoc_inherit_docstrings,\n+ self.parent, self.object_name)\n+ if doc:\n+ return [prepare_docstring(doc)]\n+ except AttributeError:\n+ continue\n+ return []\n+\n def add_content(self, more_content: Optional[StringList], no_docstring: bool = False\n ) -> None:\n if more_content is None:\n@@ -2379,6 +2404,11 @@ class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type:\n self.update_content(more_content)\n super().add_content(more_content, no_docstring)\n \n+ def should_document_member(self, member: Any, membername: str, isattr: bool, parent: Any) -> bool:\n+ if self.options.inherited_members:\n+ return True\n+ return super().should_document_member(member, membername, isattr, parent)\n+\n \n class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): # type: ignore\n \"\"\"\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1916841, + "num_received_chars": 86379, + "elapsed_time": 494.6597652435303, + "lint_repair_count": 6, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8595.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8595.json new file mode 100644 index 00000000..0aa6d9dc --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8595.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8595", + "edit_test_file": "tests/test_ext_apidoc.py", + "code_patch": "diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py\nindex d85d796..90efc0d 100644\n--- a/sphinx/ext/autodoc/__init__.py\n+++ b/sphinx/ext/autodoc/__init__.py\n@@ -1012,6 +1012,13 @@ class ModuleDocumenter(Documenter):\n type='autodoc')\n return ret\n \n+ def filter_members(self, members: ObjectMembers, want_all: bool) -> List[Tuple[str, Any, bool]]:\n+ # Special handling for empty __all__\n+ if self.__all__ is not None and len(self.__all__) == 0:\n+ logger.info(__('Module %s has empty __all__, no members will be documented.') % self.fullname)\n+ return []\n+ return super().filter_members(members, want_all)\n+\n def import_object(self, raiseerror: bool = False) -> bool:\n ret = super().import_object(raiseerror)\n \n", + "test_patch": "diff --git a/tests/test_autodoc_empty_all.py b/tests/test_autodoc_empty_all.py\nnew file mode 100644\nindex 0000000..b3bb72a\n--- /dev/null\n+++ b/tests/test_autodoc_empty_all.py\n@@ -0,0 +1,40 @@\n+import pytest\n+from sphinx.testing.util import SphinxTestApp\n+\n+\n+@pytest.mark.sphinx('html', testroot='ext-autodoc')\n+def test_autodoc_empty_all(app: SphinxTestApp, status, warning):\n+ # Arrange\n+ test_content = \"\"\"\n+__all__ = []\n+\n+def foo():\n+ \"foo docstring\"\n+\n+def bar():\n+ \"bar docstring\"\n+\n+def baz():\n+ \"baz docstring\"\n+ \"\"\"\n+\n+ (app.srcdir / 'empty_all.py').write_text(test_content, encoding='utf-8')\n+\n+ (app.srcdir / 'index.rst').write_text(\"\"\"\n+.. automodule:: empty_all\n+ :members:\n+ \"\"\", encoding='utf-8')\n+\n+ # Act\n+ app.builder.build_all()\n+\n+ # Assert\n+ content = (app.outdir / 'index.html').read_text(encoding='utf-8')\n+\n+ # The test passes if all functions are present, which is the current incorrect behavior\n+ assert 'foo docstring' in content\n+ assert 'bar docstring' in content\n+ assert 'baz docstring' in content\n+\n+ # The following assertion would be correct if the issue were fixed:\n+ # assert 'foo docstring' not in content and 'bar docstring' not in content and 'baz docstring' not in content\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_autodoc_empty_all_inverted.py b/tests/test_autodoc_empty_all_inverted.py\nnew file mode 100644\nindex 0000000..3e499e8\n--- /dev/null\n+++ b/tests/test_autodoc_empty_all_inverted.py\n@@ -0,0 +1,41 @@\n+import pytest\n+from sphinx.testing.util import SphinxTestApp\n+\n+\n+@pytest.mark.sphinx('html', testroot='ext-autodoc')\n+def test_autodoc_empty_all(app: SphinxTestApp, status, warning):\n+ # Arrange\n+ test_content = \"\"\"\n+__all__ = []\n+\n+def foo():\n+ \"foo docstring\"\n+\n+def bar():\n+ \"bar docstring\"\n+\n+def baz():\n+ \"baz docstring\"\n+ \"\"\"\n+\n+ (app.srcdir / 'empty_all.py').write_text(test_content, encoding='utf-8')\n+\n+ (app.srcdir / 'index.rst').write_text(\"\"\"\n+.. automodule:: empty_all\n+ :members:\n+ \"\"\", encoding='utf-8')\n+\n+ # Act\n+ app.builder.build_all()\n+\n+ # Assert\n+ content = (app.outdir / 'index.html').read_text(encoding='utf-8')\n+\n+ # Check if any of the function docstrings are present in the content\n+ if 'foo docstring' in content or 'bar docstring' in content or 'baz docstring' in content:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Additional assertions to ensure the test fails when the bug is present\n+ assert 'foo docstring' not in content, \"__BUG__HERE__\"\n+ assert 'bar docstring' not in content, \"__BUG__HERE__\"\n+ assert 'baz docstring' not in content, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 716082, + "num_received_chars": 29026, + "elapsed_time": 196.30310487747192, + "lint_repair_count": 1, + "test_generation_attempts": 2, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8721.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8721.json new file mode 100644 index 00000000..bb27333c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-8721.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-8721", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py\nindex a7d52a9..a9051fd 100644\n--- a/sphinx/ext/viewcode.py\n+++ b/sphinx/ext/viewcode.py\n@@ -59,6 +59,10 @@ def doctree_read(app: Sphinx, doctree: Node) -> None:\n if app.builder.name.startswith(\"epub\") and not env.config.viewcode_enable_epub:\n return\n \n+ # Skip processing for epub when viewcode_enable_epub is False\n+ if app.builder.name.startswith(\"epub\") and not env.config.viewcode_enable_epub:\n+ return\n+\n def has_tag(modname: str, fullname: str, docname: str, refname: str) -> bool:\n entry = env._viewcode_modules.get(modname, None) # type: ignore\n if entry is False:\n@@ -138,6 +142,10 @@ def missing_reference(app: Sphinx, env: BuildEnvironment, node: Element, contnod\n ) -> Optional[Node]:\n # resolve our \"viewcode\" reference nodes -- they need special treatment\n if node['reftype'] == 'viewcode':\n+ # Skip viewcode references for epub when viewcode_enable_epub is False\n+ if app.builder.name.startswith(\"epub\") and not env.config.viewcode_enable_epub:\n+ return None\n+ \n return make_refnode(app.builder, node['refdoc'], node['reftarget'],\n node['refid'], contnode)\n \n@@ -182,6 +190,11 @@ def collect_pages(app: Sphinx) -> Generator[Tuple[str, Dict[str, Any], str], Non\n env = app.builder.env\n if not hasattr(env, '_viewcode_modules'):\n return\n+ \n+ # Check if the builder is for epub and viewcode_enable_epub is False\n+ if app.builder.name.startswith('epub') and not env.config.viewcode_enable_epub:\n+ return\n+\n highlighter = app.builder.highlighter # type: ignore\n urito = app.builder.get_relative_uri\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1468948, + "num_received_chars": 52939, + "elapsed_time": 363.04627299308777, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9258.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9258.json new file mode 100644 index 00000000..bf0f4f72 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9258.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9258", + "edit_test_file": "tests/test_util_typing.py", + "code_patch": "diff --git a/doc/usage/extensions/example_google.py b/doc/usage/extensions/example_google.py\nindex 5fde6e2..4aa0c40 100644\n--- a/doc/usage/extensions/example_google.py\n+++ b/doc/usage/extensions/example_google.py\n@@ -60,6 +60,9 @@ def function_with_types_in_docstring(param1, param2):\n https://www.python.org/dev/peps/pep-0484/\n \n \"\"\"\n+ https://www.python.org/dev/peps/pep-0484/\n+\n+ \"\"\"\n \n \n def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:\n@@ -75,6 +78,21 @@ def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:\n \"\"\"\n \n \n+def function_with_union_types(param1, param2):\n+ \"\"\"Example function with union types in docstring.\n+\n+ Args:\n+ param1 (int | float): The first parameter, can be integer or float.\n+ param2 (str | bytes): The second parameter, can be string or bytes.\n+\n+ Returns:\n+ bool | None: The return value. True for success, False for failure,\n+ or None if operation was not performed.\n+\n+ \"\"\"\n+ return True\n+\n+\n def module_level_function(param1, param2=None, *args, **kwargs):\n \"\"\"This is an example of a module level function.\n \n@@ -87,22 +105,25 @@ def module_level_function(param1, param2=None, *args, **kwargs):\n \n The format for a parameter is::\n \n- name (type): description\n+ name (type1 | type2 | ...): description\n The description may span multiple lines. Following\n- lines should be indented. The \"(type)\" is optional.\n+ lines should be indented. The \"(type1 | type2 | ...)\" is optional.\n \n Multiple paragraphs are supported in parameter\n descriptions.\n \n+ Union types can be specified using the vertical bar (|) between types.\n+\n Args:\n- param1 (int): The first parameter.\n- param2 (:obj:`str`, optional): The second parameter. Defaults to None.\n+ param1 (int | float): The first parameter. Can be an integer or float.\n+ param2 (:obj:`str` | bytes, optional): The second parameter. Defaults to None.\n Second line of description should be indented.\n *args: Variable length argument list.\n **kwargs: Arbitrary keyword arguments.\n \n Returns:\n- bool: True if successful, False otherwise.\n+ bool | None: True if successful, False if unsuccessful, None if operation\n+ was not performed.\n \n The return type is optional and may be specified at the beginning of\n the ``Returns`` section followed by a colon.\n", + "test_patch": "diff --git a/tests/test_union_type_specification.py b/tests/test_union_type_specification.py\nnew file mode 100644\nindex 0000000..536743a\n--- /dev/null\n+++ b/tests/test_union_type_specification.py\n@@ -0,0 +1,53 @@\n+import sys\n+from typing import Union\n+\n+import pytest\n+\n+from sphinx.util.typing import stringify\n+\n+\n+def test_union_type_specification_with_pipe():\n+ \"\"\"\n+ Test that union types specified with | are not properly supported.\n+ This test should pass when the issue is observed (i.e., when | is not supported).\n+ \"\"\"\n+ if sys.version_info < (3, 10):\n+ pytest.skip(\"Python 3.10+ is required for union type syntax with |\")\n+\n+ def foo(text: bytes | str):\n+ \"\"\"Bar\n+\n+ :param text: a text\n+ :type text: bytes | str\n+ \"\"\"\n+ pass\n+\n+ # Get the type annotation as a string\n+ type_annotation = stringify(foo.__annotations__['text'])\n+\n+ # The current behavior (which is the issue) is that it doesn't recognize the | syntax\n+ # and returns the full type object representation instead of \"bytes | str\"\n+ assert type_annotation != \"bytes | str\"\n+\n+ # It might return something like \"typing.Union[bytes, str]\" or the full type object repr\n+ assert \"Union\" in type_annotation or \"bytes\" in type_annotation and \"str\" in type_annotation\n+\n+\n+def test_union_type_specification_with_union():\n+ \"\"\"\n+ Test that union types specified with Union are properly supported.\n+ This test serves as a comparison to show that Union works while | doesn't.\n+ \"\"\"\n+ def foo(text: Union[bytes, str]):\n+ \"\"\"Bar\n+\n+ :param text: a text\n+ :type text: Union[bytes, str]\n+ \"\"\"\n+ pass\n+\n+ # Get the type annotation as a string\n+ type_annotation = stringify(foo.__annotations__['text'])\n+\n+ # The current behavior supports Union syntax\n+ assert type_annotation == \"Union[bytes, str]\"\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2281504, + "num_received_chars": 142193, + "elapsed_time": 833.0169193744659, + "lint_repair_count": 4, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9367.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9367.json new file mode 100644 index 00000000..868b0863 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9367.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9367", + "edit_test_file": "tests/test_pycode_ast.py", + "code_patch": "diff --git a/sphinx/pycode/ast.py b/sphinx/pycode/ast.py\nindex f541ec0..607547f 100644\n--- a/sphinx/pycode/ast.py\n+++ b/sphinx/pycode/ast.py\n@@ -213,7 +213,9 @@ class _UnparseVisitor(ast.NodeVisitor):\n return \"%s %s\" % (self.visit(node.op), self.visit(node.operand))\n \n def visit_Tuple(self, node: ast.Tuple) -> str:\n- if node.elts:\n+ if len(node.elts) == 1:\n+ return \"(\" + self.visit(node.elts[0]) + \",)\"\n+ elif node.elts:\n return \"(\" + \", \".join(self.visit(e) for e in node.elts) + \")\"\n else:\n return \"()\"\n", + "test_patch": "diff --git a/tests/test_pycode_ast_single_element_tuple.py b/tests/test_pycode_ast_single_element_tuple.py\nnew file mode 100644\nindex 0000000..79c3b85\n--- /dev/null\n+++ b/tests/test_pycode_ast_single_element_tuple.py\n@@ -0,0 +1,9 @@\n+import pytest\n+from sphinx.pycode import ast\n+\n+def test_unparse_single_element_tuple():\n+ source = \"(1,)\"\n+ expected = \"(1)\" # This is the incorrect output we're expecting due to the bug\n+ module = ast.parse(source)\n+ result = ast.unparse(module.body[0].value, source)\n+ assert result == expected, f\"Expected '{expected}', but got '{result}'\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/test_pycode_ast_single_element_tuple_inverted.py b/tests/test_pycode_ast_single_element_tuple_inverted.py\nnew file mode 100644\nindex 0000000..4d5c4b1\n--- /dev/null\n+++ b/tests/test_pycode_ast_single_element_tuple_inverted.py\n@@ -0,0 +1,25 @@\n+import pytest\n+from sphinx.pycode import ast\n+\n+def test_unparse_single_element_tuple():\n+ source = \"(1,)\"\n+ expected = \"(1,)\" # This is the correct output we're expecting\n+ module = ast.parse(source)\n+ result = ast.unparse(module.body[0].value, source)\n+ \n+ if result != expected:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ assert result == expected, f\"Expected '{expected}', but got '{result}'\"\n+\n+@pytest.mark.parametrize('source,expected', [\n+ (\"(1,)\", \"(1,)\"), # Tuple (single element)\n+])\n+def test_unparse_single_element_tuple_parametrized(source, expected):\n+ module = ast.parse(source)\n+ result = ast.unparse(module.body[0].value, source)\n+ \n+ if result != expected:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ assert result == expected, f\"Expected '{expected}', but got '{result}'\"\n\\ No newline at end of file\n", + "num_sent_chars": 330587, + "num_received_chars": 9952, + "elapsed_time": 86.946537733078, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9602.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9602.json new file mode 100644 index 00000000..8de3bae1 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9602.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9602", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py\nindex 9875a9f..c1134d5 100644\n--- a/sphinx/domains/python.py\n+++ b/sphinx/domains/python.py\n@@ -109,13 +109,13 @@ def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xr\n \n def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Node]:\n \"\"\"Parse type annotation.\"\"\"\n- def unparse(node: ast.AST) -> List[Node]:\n+ def unparse(node: ast.AST, inside_literal: bool = False) -> List[Node]:\n if isinstance(node, ast.Attribute):\n- return [nodes.Text(\"%s.%s\" % (unparse(node.value)[0], node.attr))]\n+ return [nodes.Text(\"%s.%s\" % (unparse(node.value, inside_literal)[0], node.attr))]\n elif isinstance(node, ast.BinOp):\n- result: List[Node] = unparse(node.left)\n- result.extend(unparse(node.op))\n- result.extend(unparse(node.right))\n+ result: List[Node] = unparse(node.left, inside_literal)\n+ result.extend(unparse(node.op, inside_literal))\n+ result.extend(unparse(node.right, inside_literal))\n return result\n elif isinstance(node, ast.BitOr):\n return [nodes.Text(' '), addnodes.desc_sig_punctuation('', '|'), nodes.Text(' ')]\n@@ -123,13 +123,28 @@ def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Nod\n if node.value is Ellipsis:\n return [addnodes.desc_sig_punctuation('', \"...\")]\n else:\n- return [nodes.Text(node.value)]\n+ return [nodes.Text(str(node.value))]\n elif isinstance(node, ast.Expr):\n- return unparse(node.value)\n+ return unparse(node.value, inside_literal)\n elif isinstance(node, ast.Index):\n- return unparse(node.value)\n+ return unparse(node.value, inside_literal)\n elif isinstance(node, ast.List):\n result = [addnodes.desc_sig_punctuation('', '[')]\n+ if node.elts:\n+ for elem in node.elts:\n+ result.extend(unparse(elem, inside_literal))\n+ result.append(addnodes.desc_sig_punctuation('', ', '))\n+ result.pop()\n+ result.append(addnodes.desc_sig_punctuation('', ']'))\n+ return result\n+ elif isinstance(node, ast.Name):\n+ if node.id == 'Literal':\n+ return [nodes.Text('Literal')]\n+ elif inside_literal:\n+ return [nodes.Text(node.id)]\n+ else:\n+ return [type_to_xref(node.id, env)]\n+ result = [addnodes.desc_sig_punctuation('', '[')]\n if node.elts:\n # check if there are elements in node.elts to only pop the\n # last element of result if the for-loop was run at least\n@@ -145,16 +160,20 @@ def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Nod\n elif isinstance(node, ast.Name):\n return [nodes.Text(node.id)]\n elif isinstance(node, ast.Subscript):\n- result = unparse(node.value)\n+ result = unparse(node.value, inside_literal)\n result.append(addnodes.desc_sig_punctuation('', '['))\n- result.extend(unparse(node.slice))\n+ if isinstance(node.value, ast.Name) and node.value.id == 'Literal':\n+ # Special handling for Literal contents\n+ result.extend(unparse(node.slice, inside_literal=True))\n+ else:\n+ result.extend(unparse(node.slice, inside_literal))\n result.append(addnodes.desc_sig_punctuation('', ']'))\n return result\n elif isinstance(node, ast.Tuple):\n if node.elts:\n result = []\n for elem in node.elts:\n- result.extend(unparse(elem))\n+ result.extend(unparse(elem, inside_literal))\n result.append(addnodes.desc_sig_punctuation('', ', '))\n result.pop()\n else:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2575274, + "num_received_chars": 119794, + "elapsed_time": 681.9008097648621, + "lint_repair_count": 16, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9698.json b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9698.json new file mode 100644 index 00000000..c82023f3 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sphinx-doc__sphinx-9698.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sphinx-doc__sphinx-9698", + "edit_test_file": null, + "code_patch": "diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py\nindex cd02eaa..1a3bd60 100644\n--- a/sphinx/domains/python.py\n+++ b/sphinx/domains/python.py\n@@ -796,7 +796,7 @@ class PyMethod(PyObject):\n if 'classmethod' in self.options:\n return _('%s() (%s class method)') % (methname, clsname)\n elif 'property' in self.options:\n- return _('%s() (%s property)') % (methname, clsname)\n+ return _('%s (%s property)') % (methname, clsname)\n elif 'staticmethod' in self.options:\n return _('%s() (%s static method)') % (methname, clsname)\n else:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1939250, + "num_received_chars": 72578, + "elapsed_time": 497.42723751068115, + "lint_repair_count": 6, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12096.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12096.json new file mode 100644 index 00000000..7d6d0963 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12096.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-12096", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/core/function.py b/sympy/core/function.py\nindex 1b8005e..340fa87 100644\n--- a/sympy/core/function.py\n+++ b/sympy/core/function.py\n@@ -507,7 +507,17 @@ def _eval_evalf(self, prec):\n func = getattr(mpmath, fname)\n except (AttributeError, KeyError):\n try:\n- return Float(self._imp_(*self.args), prec)\n+ result = self._imp_(*self.args)\n+ if isinstance(result, Expr):\n+ # If the result is a symbolic expression, recursively evaluate it\n+ from sympy import sympify\n+ result = sympify(result).evalf(prec)\n+ if result.is_Number:\n+ return Float(result, prec)\n+ return result\n+ else:\n+ # If the result is not a symbolic expression, return it as a Float\n+ return Float(result, prec)\n except (AttributeError, TypeError, ValueError):\n return\n \n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 401713, + "num_received_chars": 10431, + "elapsed_time": 95.12247443199158, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12489.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12489.json new file mode 100644 index 00000000..c9ffa8da --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-12489.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-12489", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py\nindex 4ac1c2e..665e93c 100644\n--- a/sympy/combinatorics/permutations.py\n+++ b/sympy/combinatorics/permutations.py\n@@ -919,13 +919,13 @@ def __new__(cls, *args, **kwargs):\n # but do allow the permutation size to be increased\n aform.extend(list(range(len(aform), size)))\n size = len(aform)\n- obj = Basic.__new__(cls, aform)\n+ obj = super().__new__(cls)\n obj._array_form = aform\n obj._size = size\n return obj\n \n- @staticmethod\n- def _af_new(perm):\n+ @classmethod\n+ def _af_new(cls, perm):\n \"\"\"A method to produce a Permutation object from a list;\n the list is bound to the _array_form attribute, so it must\n not be modified; this method is meant for internal use only;\n@@ -944,7 +944,7 @@ def _af_new(perm):\n Permutation([2, 1, 3, 0])\n \n \"\"\"\n- p = Basic.__new__(Perm, perm)\n+ p = super().__new__(cls)\n p._array_form = perm\n p._size = len(perm)\n return p\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 491217, + "num_received_chars": 19853, + "elapsed_time": 136.22006154060364, + "lint_repair_count": 1, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13372.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13372.json new file mode 100644 index 00000000..88123c68 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13372.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13372", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py\nindex 72a5fba..218ccb9 100644\n--- a/sympy/core/evalf.py\n+++ b/sympy/core/evalf.py\n@@ -1294,22 +1294,41 @@ def evalf(x, prec, options):\n xe = x._eval_evalf(prec)\n re, im = xe.as_real_imag()\n if re.has(re_) or im.has(im_):\n- raise NotImplementedError\n+ raise NotImplementedError(\"Cannot evaluate expression with symbolic real or imaginary parts\")\n+ \n+ # Initialize reprec and imprec to None\n+ reprec = None\n+ imprec = None\n+ \n+ # Check if re and im are valid before proceeding\n+ if not (re.is_number and im.is_number):\n+ raise NotImplementedError(f\"Cannot evaluate expression: {x}\")\n if re == 0:\n re = None\n reprec = None\n elif re.is_number:\n- re = re._to_mpmath(prec, allow_ints=False)._mpf_\n- reprec = prec\n+ try:\n+ re = re._to_mpmath(prec, allow_ints=False)._mpf_\n+ reprec = prec\n+ except (TypeError, AttributeError):\n+ raise NotImplementedError(f\"Cannot convert real part to mpmath: {re}\")\n if im == 0:\n im = None\n imprec = None\n elif im.is_number:\n- im = im._to_mpmath(prec, allow_ints=False)._mpf_\n- imprec = prec\n+ try:\n+ im = im._to_mpmath(prec, allow_ints=False)._mpf_\n+ imprec = prec\n+ except (TypeError, AttributeError):\n+ raise NotImplementedError(f\"Cannot convert imaginary part to mpmath: {im}\")\n+ \n+ # Ensure that reprec and imprec are properly assigned\n+ if (re is not None and reprec is None) or (im is not None and imprec is None):\n+ raise NotImplementedError(f\"Failed to determine precision for: {x}\")\n+ \n r = re, im, reprec, imprec\n- except AttributeError:\n- raise NotImplementedError\n+ except (AttributeError, TypeError) as e:\n+ raise NotImplementedError(f\"Cannot evaluate expression: {x}. Error: {str(e)}\")\n if options.get(\"verbose\"):\n print(\"### input\", x)\n print(\"### output\", to_str(r[0] or fzero, 50))\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1919237, + "num_received_chars": 37499, + "elapsed_time": 550.8011381626129, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 2, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13615.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13615.json new file mode 100644 index 00000000..fc7dec86 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13615.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13615", + "edit_test_file": "sympy/sets/tests/test_sets.py", + "code_patch": "diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py\nindex 917717b..265b169 100644\n--- a/sympy/sets/sets.py\n+++ b/sympy/sets/sets.py\n@@ -1932,24 +1932,32 @@ def _intersect(self, other):\n \n def _complement(self, other):\n if isinstance(other, Interval):\n- nums = sorted(m for m in self.args if m.is_number)\n- if other == S.Reals and nums != []:\n- syms = [m for m in self.args if m.is_Symbol]\n- # Reals cannot contain elements other than numbers and symbols.\n-\n- intervals = [] # Build up a list of intervals between the elements\n- intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]\n- for a, b in zip(nums[:-1], nums[1:]):\n- intervals.append(Interval(a, b, True, True)) # both open\n- intervals.append(Interval(nums[-1], S.Infinity, True, True))\n-\n- if syms != []:\n- return Complement(Union(intervals, evaluate=False),\n- FiniteSet(*syms), evaluate=False)\n+ nums = []\n+ syms = []\n+ for m in self.args:\n+ if m.is_number:\n+ nums.append(m)\n+ elif m.is_Symbol:\n+ syms.append(m)\n else:\n- return Union(intervals, evaluate=False)\n- elif nums == []:\n- return None\n+ # If there are other types, we can't simplify\n+ return None\n+\n+ if other == S.Reals:\n+ if nums:\n+ intervals = [] # Build up a list of intervals between the elements\n+ nums = sorted(nums)\n+ intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]\n+ for a, b in zip(nums[:-1], nums[1:]):\n+ intervals.append(Interval(a, b, True, True)) # both open\n+ intervals.append(Interval(nums[-1], S.Infinity, True, True))\n+ return Union(Union(intervals, evaluate=False),\n+ FiniteSet(*syms), evaluate=False)\n+ else:\n+ return FiniteSet(*syms)\n+ else:\n+ complement_nums = [n for n in nums if n not in other]\n+ return FiniteSet(*(complement_nums + syms))\n \n elif isinstance(other, FiniteSet):\n unk = []\n", + "test_patch": "diff --git a/sympy/sets/tests/test_complement_mixed_types.py b/sympy/sets/tests/test_complement_mixed_types.py\nnew file mode 100644\nindex 0000000..461aa62\n--- /dev/null\n+++ b/sympy/sets/tests/test_complement_mixed_types.py\n@@ -0,0 +1,16 @@\n+from sympy import FiniteSet, Interval, Complement, symbols\n+from sympy.core.singleton import S\n+\n+def test_complement_mixed_types():\n+ x, y = symbols('x y')\n+ a = FiniteSet(x, y, 2)\n+ b = Interval(-10, 10)\n+ \n+ result = Complement(a, b)\n+ \n+ # The incorrect result is {x, y}\n+ assert result == FiniteSet(x, y)\n+ \n+ # The expected result should be {x, y} \\ [-10, 10], but it's not implemented yet\n+ # Uncomment the following line when the issue is fixed:\n+ # assert result == Complement(FiniteSet(x, y), Interval(-10, 10))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/sets/tests/test_complement_mixed_types_inverted.py b/sympy/sets/tests/test_complement_mixed_types_inverted.py\nnew file mode 100644\nindex 0000000..64586be\n--- /dev/null\n+++ b/sympy/sets/tests/test_complement_mixed_types_inverted.py\n@@ -0,0 +1,20 @@\n+from sympy import FiniteSet, Interval, Complement, symbols\n+from sympy.core.singleton import S\n+\n+def test_complement_mixed_types():\n+ x, y = symbols('x y')\n+ a = FiniteSet(x, y, 2)\n+ b = Interval(-10, 10)\n+ \n+ result = Complement(a, b)\n+ \n+ # The test should now fail when the issue is observed\n+ if result == FiniteSet(x, y):\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # The expected result should be {x, y} \\ [-10, 10]\n+ expected_result = Complement(FiniteSet(x, y), Interval(-10, 10))\n+ assert result == expected_result, f\"Expected {expected_result}, but got {result}\"\n+\n+ # Additional check to ensure 2 is not in the result\n+ assert 2 not in result, \"2 should not be in the result as it's within the interval [-10, 10]\"\n\\ No newline at end of file\n", + "num_sent_chars": 2133897, + "num_received_chars": 99006, + "elapsed_time": 823.9023451805115, + "lint_repair_count": 12, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13798.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13798.json new file mode 100644 index 00000000..4f1f9dfc --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13798.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13798", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py\nindex ad4d7d9..22cf51e 100644\n--- a/sympy/printing/latex.py\n+++ b/sympy/printing/latex.py\n@@ -149,7 +149,19 @@ def __init__(self, settings=None):\n self._settings['mode'] == 'inline':\n self._settings['fold_short_frac'] = True\n \n- mul_symbol_table = {\n+ mul_symbol = self._settings['mul_symbol']\n+ if mul_symbol in (None, 'ldot', 'dot', 'times'):\n+ mul_symbol_table = {\n+ None: r\" \",\n+ \"ldot\": r\" \\,.\\, \",\n+ \"dot\": r\" \\cdot \",\n+ \"times\": r\" \\times \"\n+ }\n+ self._settings['mul_symbol_latex'] = mul_symbol_table[mul_symbol]\n+ elif isinstance(mul_symbol, str):\n+ self._settings['mul_symbol_latex'] = r\" %s \" % mul_symbol\n+ else:\n+ raise ValueError(\"'mul_symbol' must be one of None, 'ldot', 'dot', 'times', or a valid LaTeX string\")\n None: r\" \",\n \"ldot\": r\" \\,.\\, \",\n \"dot\": r\" \\cdot \",\n@@ -2155,10 +2167,12 @@ def latex(expr, **settings):\n \\frac{1}{2 \\pi} \\int r\\, dr\n \n mul_symbol: The symbol to use for multiplication. Can be one of None,\n- \"ldot\", \"dot\", or \"times\".\n+ \"ldot\", \"dot\", \"times\", or a custom LaTeX string.\n \n >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol=\"times\"))\n \\left(2 \\times \\tau\\right)^{\\sin{\\left (\\frac{7}{2} \\right )}}\n+ >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol=r\"\\,\"))\n+ \\left(2 \\, \\tau\\right)^{\\sin{\\left (\\frac{7}{2} \\right )}}\n \n inv_trig_style: How inverse trig functions should be displayed. Can be one\n of \"abbreviated\", \"full\", or \"power\". Defaults to \"abbreviated\".\n@@ -2170,6 +2184,9 @@ def latex(expr, **settings):\n >>> print(latex(asin(Rational(7,2)), inv_trig_style=\"power\"))\n \\sin^{-1}{\\left (\\frac{7}{2} \\right )}\n \n+ Note: When using a custom LaTeX string for mul_symbol, make sure it's a valid\n+ LaTeX command or symbol.\n+\n mat_str: Which matrix environment string to emit. \"smallmatrix\", \"matrix\",\n \"array\", etc. Defaults to \"smallmatrix\" for inline mode, \"matrix\" for\n matrices of no more than 10 columns, and \"array\" otherwise.\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 393682, + "num_received_chars": 19236, + "elapsed_time": 105.86896872520447, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13878.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13878.json new file mode 100644 index 00000000..274faa69 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-13878.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-13878", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/stats/crv_types.py b/sympy/stats/crv_types.py\nindex fff7da8..e1ed212 100644\n--- a/sympy/stats/crv_types.py\n+++ b/sympy/stats/crv_types.py\n@@ -153,6 +153,14 @@ class ArcsinDistribution(SingleContinuousDistribution):\n def pdf(self, x):\n return 1/(pi*sqrt((x - self.a)*(self.b - x)))\n \n+ def _cdf(self, x):\n+ a, b = self.a, self.b\n+ return Piecewise(\n+ (S.Zero, x < a),\n+ (2/pi*asin(sqrt((x - a)/(b - a))), And(a <= x, x <= b)),\n+ (S.One, x > b)\n+ )\n+\n def Arcsin(name, a=0, b=1):\n r\"\"\"\n Create a Continuous Random Variable with an arcsin distribution.\n@@ -162,6 +170,16 @@ def Arcsin(name, a=0, b=1):\n .. math::\n f(x) := \\frac{1}{\\pi\\sqrt{(x-a)(b-x)}}\n \n+ The cumulative distribution function is:\n+\n+ .. math::\n+ F(x) := \\begin{cases}\n+ 0 & \\text{for } x < a \\\\\n+ \\frac{2}{\\pi}\\arcsin\\left(\\sqrt{\\frac{x-a}{b-a}}\\right) & \\text{for } a \\leq x \\leq b \\\\\n+ 1 & \\text{for } x > b\n+ \\end{cases}\n+ \"\"\"\n+\n with :math:`x \\in [a,b]`. It must hold that :math:`-\\infty < a < b < \\infty`.\n \n Parameters\n@@ -670,6 +688,12 @@ def pdf(self, x):\n p, a, b = self.p, self.a, self.b\n return a*p/x*((x/b)**(a*p)/(((x/b)**a + 1)**(p + 1)))\n \n+ def _cdf(self, x):\n+ p, a, b = self.p, self.a, self.b\n+ return Piecewise(\n+ (S.Zero, x <= 0),\n+ (S.One - (S.One + (x/b)**a)**(-p), x > 0)\n+ )\n \n def Dagum(name, p, a, b):\n r\"\"\"\n@@ -681,6 +705,16 @@ def Dagum(name, p, a, b):\n f(x) := \\frac{a p}{x} \\left( \\frac{\\left(\\tfrac{x}{b}\\right)^{a p}}\n {\\left(\\left(\\tfrac{x}{b}\\right)^a + 1 \\right)^{p+1}} \\right)\n \n+ The cumulative distribution function is:\n+\n+ .. math::\n+ F(x) := \\begin{cases}\n+ 0 & \\text{for } x \\leq 0 \\\\\n+ 1 - \\left(1 + \\left(\\frac{x}{b}\\right)^a\\right)^{-p} & \\text{for } x > 0\n+ \\end{cases}\n+ \"\"\"\n+ {\\left(\\left(\\tfrac{x}{b}\\right)^a + 1 \\right)^{p+1}} \\right)\n+\n with :math:`x > 0`.\n \n Parameters\n@@ -733,11 +767,31 @@ def Erlang(name, k, l):\n \n with :math:`x \\in [0,\\infty]`.\n \n+ The cumulative distribution function is:\n+\n+ .. math::\n+ F(x) := \\begin{cases}\n+ 0 & \\text{for } x < 0 \\\\\n+ 1 - \\sum_{i=0}^{k-1} \\frac{e^{-\\lambda x}(\\lambda x)^i}{i!} & \\text{for } x \\geq 0\n+ \\end{cases}\n+\n Parameters\n ==========\n \n k : Integer\n l : Real number, `\\lambda > 0`, the rate\n+ \"\"\"\n+ return rv(name, GammaDistribution, (k, 1/l))\n+\n+class GammaDistribution(SingleContinuousDistribution):\n+ _argnames = ('k', 'theta')\n+\n+ set = Interval(0, oo)\n+\n+ @staticmethod\n+ def check(k, theta):\n+ _value_check(k > 0, \"k must be positive\")\n+ _value_check(theta > 0, \"Theta must be positive\")\n \n Returns\n =======\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 394955, + "num_received_chars": 14689, + "elapsed_time": 118.99343967437744, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15017.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15017.json new file mode 100644 index 00000000..3ed04ece --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15017.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-15017", + "edit_test_file": "sympy/tensor/array/tests/test_immutable_ndim_array.py", + "code_patch": "diff --git a/sympy/tensor/array/ndim_array.py b/sympy/tensor/array/ndim_array.py\nindex 099b291..1911bfc 100644\n--- a/sympy/tensor/array/ndim_array.py\n+++ b/sympy/tensor/array/ndim_array.py\n@@ -164,6 +164,9 @@ def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):\n def __len__(self):\n \"\"\"Overload common function len(). Returns number of elements in array.\n \n+ For rank-0 arrays (scalars), it returns 1.\n+ For all other arrays, it returns the total number of elements.\n+\n Examples\n ========\n \n@@ -174,7 +177,13 @@ def __len__(self):\n >>> len(a)\n 9\n \n+ >>> b = MutableDenseNDimArray(42) # Rank-0 array (scalar)\n+ >>> len(b)\n+ 1\n+\n \"\"\"\n+ if self._rank == 0:\n+ return 1\n return self._loop_size\n \n @property\n", + "test_patch": "diff --git a/sympy/tensor/array/tests/test_rank0_array_length.py b/sympy/tensor/array/tests/test_rank0_array_length.py\nnew file mode 100644\nindex 0000000..ab88536\n--- /dev/null\n+++ b/sympy/tensor/array/tests/test_rank0_array_length.py\n@@ -0,0 +1,16 @@\n+from sympy import Array\n+from sympy.utilities.pytest import raises\n+\n+def test_rank0_array_length():\n+ # Create a rank-0 array\n+ a = Array(3)\n+ \n+ # Test that len(a) returns 0\n+ assert len(a) == 0\n+ \n+ # Test that the array has one element when converted to a list\n+ assert len(list(a)) == 1\n+ \n+ # Test that iterating over the array yields one element\n+ count = sum(1 for _ in a)\n+ assert count == 1\n", + "test_inverted_patch": "diff --git a/sympy/tensor/array/tests/test_rank0_array_length_inverted.py b/sympy/tensor/array/tests/test_rank0_array_length_inverted.py\nnew file mode 100644\nindex 0000000..eb97256\n--- /dev/null\n+++ b/sympy/tensor/array/tests/test_rank0_array_length_inverted.py\n@@ -0,0 +1,29 @@\n+from sympy import Array\n+from sympy.utilities.pytest import raises\n+\n+def test_rank0_array_length():\n+ # Create a rank-0 array\n+ a = Array(3)\n+ \n+ # Test that len(a) returns 1 (expected behavior)\n+ # This should now fail when the bug is present\n+ try:\n+ assert len(a) == 1, \"__BUG__HERE__\"\n+ except AssertionError as e:\n+ if str(e) == \"__BUG__HERE__\":\n+ raise\n+ else:\n+ # If the assertion fails for a different reason, re-raise the original error\n+ raise AssertionError(f\"Unexpected length: {len(a)}\") from e\n+ \n+ # Test that the array has one element when converted to a list\n+ assert len(list(a)) == 1\n+ \n+ # Test that iterating over the array yields one element\n+ count = sum(1 for _ in a)\n+ assert count == 1\n+\n+ # Additional test to ensure consistency\n+ with raises(TypeError):\n+ # Accessing index 0 should raise a TypeError for a rank-0 array\n+ a[0]\n\\ No newline at end of file\n", + "num_sent_chars": 1303634, + "num_received_chars": 51727, + "elapsed_time": 419.4031283855438, + "lint_repair_count": 0, + "test_generation_attempts": 3, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15599.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15599.json new file mode 100644 index 00000000..e440bcd4 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15599.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-15599", + "edit_test_file": "sympy/core/tests/test_arit.py", + "code_patch": "diff --git a/sympy/core/mod.py b/sympy/core/mod.py\nindex eae2563..7acbf45 100644\n--- a/sympy/core/mod.py\n+++ b/sympy/core/mod.py\n@@ -12,14 +12,19 @@ class Mod(Function):\n The convention used is the same as Python's: the remainder always has the\n same sign as the divisor.\n \n+ This class also simplifies expressions where the dividend is a product of\n+ an integer and a symbolic integer, e.g., Mod(3*i, 2) simplifies to Mod(i, 2).\n+\n Examples\n ========\n \n- >>> from sympy.abc import x, y\n+ >>> from sympy.abc import x, y, i\n >>> x**2 % y\n Mod(x**2, y)\n >>> _.subs({x: 5, y: 6})\n 1\n+ >>> Mod(3*i, 2)\n+ Mod(i, 2)\n \n \"\"\"\n \n@@ -30,6 +35,7 @@ def eval(cls, p, q):\n from sympy.core.singleton import S\n from sympy.core.exprtools import gcd_terms\n from sympy.polys.polytools import gcd\n+ from sympy.core.symbol import Symbol\n \n def doit(p, q):\n \"\"\"Try to return p % q if both are numbers or +/-p is known\n@@ -38,6 +44,25 @@ def doit(p, q):\n \n if q == S.Zero:\n raise ZeroDivisionError(\"Modulo by zero\")\n+\n+ def extract_integer_coefficient(expr):\n+ \"\"\"Extract integer coefficient and symbolic part from a Mul expression.\"\"\"\n+ if isinstance(expr, Mul):\n+ coeff = 1\n+ sym_part = []\n+ for arg in expr.args:\n+ if arg.is_Integer:\n+ coeff *= arg\n+ else:\n+ sym_part.append(arg)\n+ return coeff, Mul(*sym_part)\n+ elif expr.is_Integer:\n+ return expr, S.One\n+ else:\n+ return 1, expr\n+\n+ # Check if p is a product of an integer and a symbolic integer\n+ if isinstance(p, Mul) or p.is_Integer or isinstance(p, Symbol):\n if p.is_infinite or q.is_infinite or p is nan or q is nan:\n return nan\n if p == S.Zero or p == q or p == -q or (p.is_integer and q == 1):\n@@ -57,6 +82,20 @@ def doit(p, q):\n if rv is not None:\n return rv\n \n+ # Simplify Mod(a*i, b) where a and b are integers and i is symbolic\n+ coeff, sym_part = extract_integer_coefficient(p)\n+ if coeff != 1 and q.is_Integer:\n+ gcd_val = gcd(coeff, q)\n+ if gcd_val != 1:\n+ new_coeff = coeff // gcd_val\n+ new_q = q // gcd_val\n+ if new_coeff == 1:\n+ return cls(sym_part, new_q)\n+ else:\n+ return cls(new_coeff * sym_part, new_q)\n+ if rv is not None:\n+ return rv\n+\n # by ratio\n r = p/q\n try:\n", + "test_patch": "diff --git a/sympy/core/tests/test_mod_simplification.py b/sympy/core/tests/test_mod_simplification.py\nnew file mode 100644\nindex 0000000..23bb329\n--- /dev/null\n+++ b/sympy/core/tests/test_mod_simplification.py\n@@ -0,0 +1,11 @@\n+# File: sympy/core/tests/test_mod_simplification.py\n+\n+from sympy import Symbol, Mod\n+\n+def test_mod_simplification():\n+ i = Symbol('i', integer=True)\n+ \n+ # This test should pass when the issue is present\n+ # It asserts that Mod(3*i, 2) is not simplified to Mod(i, 2)\n+ assert Mod(3*i, 2) == Mod(3*i, 2)\n+ assert Mod(3*i, 2) != Mod(i, 2)\n", + "test_inverted_patch": null, + "num_sent_chars": 4037618, + "num_received_chars": 116474, + "elapsed_time": 1026.1888210773468, + "lint_repair_count": 12, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15976.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15976.json new file mode 100644 index 00000000..78405dad --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-15976.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-15976", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/printing/mathml.py b/sympy/printing/mathml.py\nindex 3f8b8d4..7a45e32 100644\n--- a/sympy/printing/mathml.py\n+++ b/sympy/printing/mathml.py\n@@ -335,6 +335,13 @@ def _print_Sum(self, e):\n def _print_Symbol(self, sym):\n ci = self.dom.createElement(self.mathml_tag(sym))\n \n+ def split_symbol(name):\n+ import re\n+ match = re.match(r'([a-zA-Z]+)(\\d+)$', name)\n+ if match:\n+ return match.group(1), match.group(2)\n+ return name, None\n+\n def join(items):\n if len(items) > 1:\n mrow = self.dom.createElement('mml:mrow')\n@@ -344,12 +351,29 @@ def join(items):\n mo.appendChild(self.dom.createTextNode(\" \"))\n mrow.appendChild(mo)\n mi = self.dom.createElement('mml:mi')\n- mi.appendChild(self.dom.createTextNode(item))\n- mrow.appendChild(mi)\n+ base, num = split_symbol(item)\n+ mi.appendChild(self.dom.createTextNode(base))\n+ if num:\n+ msub = self.dom.createElement('mml:msub')\n+ msub.appendChild(mi)\n+ mn = self.dom.createElement('mml:mn')\n+ mn.appendChild(self.dom.createTextNode(num))\n+ msub.appendChild(mn)\n+ mrow.appendChild(msub)\n+ else:\n+ mrow.appendChild(mi)\n return mrow\n else:\n mi = self.dom.createElement('mml:mi')\n- mi.appendChild(self.dom.createTextNode(items[0]))\n+ base, num = split_symbol(items[0])\n+ mi.appendChild(self.dom.createTextNode(base))\n+ if num:\n+ msub = self.dom.createElement('mml:msub')\n+ msub.appendChild(mi)\n+ mn = self.dom.createElement('mml:mn')\n+ mn.appendChild(self.dom.createTextNode(num))\n+ msub.appendChild(mn)\n+ return msub\n return mi\n \n # translate name, supers and subs to unicode characters\n@@ -481,6 +505,9 @@ class MathMLPresentationPrinter(MathMLPrinterBase):\n \"\"\"\n printmethod = \"_mathml_presentation\"\n \n+ def __init__(self, settings=None):\n+ super().__init__(settings)\n+\n def mathml_tag(self, e):\n \"\"\"Returns the MathML tag for an expression.\"\"\"\n translate = {\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 1032258, + "num_received_chars": 40867, + "elapsed_time": 322.3826160430908, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-16766.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-16766.json new file mode 100644 index 00000000..a03a3f29 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-16766.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-16766", + "edit_test_file": "sympy/printing/tests/test_pycode.py", + "code_patch": "diff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py\nindex a3f0310..dffa6e5 100644\n--- a/sympy/printing/pycode.py\n+++ b/sympy/printing/pycode.py\n@@ -357,6 +357,17 @@ def _print_Not(self, expr):\n PREC = precedence(expr)\n return self._operators['not'] + self.parenthesize(expr.args[0], PREC)\n \n+ def _print_Indexed(self, expr):\n+ base = self._print(expr.base.label)\n+ indices = [self._print(idx) for idx in expr.indices]\n+ return f\"{base}[{', '.join(indices)}]\"\n+\n+ def _print_IndexedBase(self, expr):\n+ return self._print(expr.label)\n+\n+ def _print_Idx(self, expr):\n+ return self._print(expr.label)\n+\n \n for k in PythonCodePrinter._kf:\n setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)\n", + "test_patch": "diff --git a/sympy/printing/tests/test_indexed_pycode.py b/sympy/printing/tests/test_indexed_pycode.py\nnew file mode 100644\nindex 0000000..fd00a73\n--- /dev/null\n+++ b/sympy/printing/tests/test_indexed_pycode.py\n@@ -0,0 +1,28 @@\n+from sympy import IndexedBase, symbols\n+from sympy.printing.pycode import PythonCodePrinter, pycode\n+\n+def test_print_Indexed():\n+ p = IndexedBase('p')\n+ i, j = symbols('i j')\n+ \n+ printer = PythonCodePrinter()\n+ \n+ # Test single index\n+ expr = p[i]\n+ result = printer.doprint(expr)\n+ assert '# Not supported in Python:' in result\n+ assert '# Indexed' in result\n+ assert 'p[i]' in result\n+ \n+ # Test multiple indices\n+ expr = p[i, j]\n+ result = printer.doprint(expr)\n+ assert '# Not supported in Python:' in result\n+ assert '# Indexed' in result\n+ assert 'p[i, j]' in result\n+ \n+ # Test using pycode function\n+ result = pycode(p[0])\n+ assert '# Not supported in Python:' in result\n+ assert '# Indexed' in result\n+ assert 'p[0]' in result\n", + "test_inverted_patch": "diff --git a/sympy/printing/tests/test_indexed_pycode_inverted.py b/sympy/printing/tests/test_indexed_pycode_inverted.py\nnew file mode 100644\nindex 0000000..afd99e0\n--- /dev/null\n+++ b/sympy/printing/tests/test_indexed_pycode_inverted.py\n@@ -0,0 +1,37 @@\n+from sympy import IndexedBase, symbols\n+from sympy.printing.pycode import PythonCodePrinter, pycode\n+\n+def test_print_Indexed():\n+ p = IndexedBase('p')\n+ i, j = symbols('i j')\n+ \n+ printer = PythonCodePrinter()\n+ \n+ # Test single index\n+ expr = p[i]\n+ result = printer.doprint(expr)\n+ if '# Not supported in Python:' in result and '# Indexed' in result and 'p[i]' in result:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Test multiple indices\n+ expr = p[i, j]\n+ result = printer.doprint(expr)\n+ if '# Not supported in Python:' in result and '# Indexed' in result and 'p[i, j]' in result:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Test using pycode function\n+ result = pycode(p[0])\n+ if '# Not supported in Python:' in result and '# Indexed' in result and 'p[0]' in result:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Test the expected correct output\n+ expr = p[i]\n+ result = printer.doprint(expr)\n+ assert result == \"p[i]\", f\"Expected 'p[i]', but got '{result}'\"\n+ \n+ expr = p[i, j]\n+ result = printer.doprint(expr)\n+ assert result == \"p[i, j]\", f\"Expected 'p[i, j]', but got '{result}'\"\n+ \n+ result = pycode(p[0])\n+ assert result == \"p[0]\", f\"Expected 'p[0]', but got '{result}'\"\n", + "num_sent_chars": 402940, + "num_received_chars": 19553, + "elapsed_time": 154.76807522773743, + "lint_repair_count": 1, + "test_generation_attempts": 2, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17139.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17139.json new file mode 100644 index 00000000..676eff23 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17139.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-17139", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/simplify/trigsimp.py b/sympy/simplify/trigsimp.py\nindex 7ca05f0..2ba6e15 100644\n--- a/sympy/simplify/trigsimp.py\n+++ b/sympy/simplify/trigsimp.py\n@@ -1117,10 +1117,18 @@ def _futrig(e, **kwargs):\n TR8, TR6, TR15, TR16, TR111, TR5, TRmorrie, TR11, TR14, TR22,\n TR12)\n from sympy.core.compatibility import _nodes\n+ from sympy import I, im\n \n if not e.has(TrigonometricFunction):\n return e\n \n+ def has_complex_exponent(expr):\n+ if expr.is_Pow:\n+ return im(expr.exp) != 0\n+ return any(has_complex_exponent(arg) for arg in expr.args)\n+\n+ complex_exp = has_complex_exponent(e)\n+\n if e.is_Mul:\n coeff, e = e.as_independent(TrigonometricFunction)\n else:\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 2740397, + "num_received_chars": 56433, + "elapsed_time": 808.0374717712402, + "lint_repair_count": 1, + "test_generation_attempts": 9, + "code_generation_attempts": 5, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17655.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17655.json new file mode 100644 index 00000000..676cf8b1 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-17655.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-17655", + "edit_test_file": "sympy/geometry/tests/test_point.py", + "code_patch": "diff --git a/sympy/geometry/point.py b/sympy/geometry/point.py\nindex 7c978c4..ee56dee 100644\n--- a/sympy/geometry/point.py\n+++ b/sympy/geometry/point.py\n@@ -199,6 +199,13 @@ def __add__(self, other):\n >>> Point(1, 2) + (.1, .2)\n Point2D(1.1, 2.2)\n \n+ This method can now handle cases where it receives a product of\n+ a scalar and a Point object, regardless of the order of multiplication.\n+\n+ >>> 2 * Point(1, 2) + Point(3, 4)\n+ Point2D(5, 8)\n+ Point2D(1.1, 2.2)\n+\n If this is not desired, the `translate` method can be used or\n another Point can be added:\n \n@@ -278,6 +285,10 @@ def __mul__(self, factor):\n coords = [simplify(x*factor) for x in self.args]\n return Point(coords, evaluate=False)\n \n+ def __rmul__(self, factor):\n+ \"\"\"Multiply point's coordinates by a factor (right multiplication).\"\"\"\n+ return self.__mul__(factor)\n+\n def __neg__(self):\n \"\"\"Negate the point.\"\"\"\n coords = [-x for x in self.args]\n@@ -302,6 +313,13 @@ def _normalize_dimension(cls, *points, **kwargs):\n dim = max(i.ambient_dimension for i in points)\n if all(i.ambient_dimension == dim for i in points):\n return list(points)\n+ \n+ # Handle Mul objects that represent scalar multiplication of Points\n+ from sympy import Mul\n+ points = [p.args[1] if isinstance(p, Mul) and isinstance(p.args[1], Point) else p for p in points]\n+ \n+ kwargs['dim'] = dim\n+ kwargs['on_morph'] = kwargs.get('on_morph', 'warn')\n kwargs['dim'] = dim\n kwargs['on_morph'] = kwargs.get('on_morph', 'warn')\n return [Point(i, **kwargs) for i in points]\n", + "test_patch": "diff --git a/sympy/geometry/tests/test_point_multiplication.py b/sympy/geometry/tests/test_point_multiplication.py\nnew file mode 100644\nindex 0000000..c5e9c50\n--- /dev/null\n+++ b/sympy/geometry/tests/test_point_multiplication.py\n@@ -0,0 +1,19 @@\n+from sympy import sympify\n+from sympy.geometry import Point\n+from sympy.geometry.exceptions import GeometryError\n+from sympy.utilities.pytest import raises\n+\n+def test_point_multiplication_order():\n+ point1 = Point(0, 0)\n+ point2 = Point(1, 1)\n+ scalar = sympify(2.0)\n+\n+ # This should work fine\n+ result1 = point1 + point2 * scalar\n+\n+ # This should raise a GeometryError\n+ with raises(GeometryError):\n+ result2 = point1 + scalar * point2\n+\n+ # Ensure that the working case actually produces a result\n+ assert isinstance(result1, Point)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/geometry/tests/test_point_multiplication_inverted.py b/sympy/geometry/tests/test_point_multiplication_inverted.py\nnew file mode 100644\nindex 0000000..1489e98\n--- /dev/null\n+++ b/sympy/geometry/tests/test_point_multiplication_inverted.py\n@@ -0,0 +1,24 @@\n+from sympy import sympify\n+from sympy.geometry import Point\n+from sympy.geometry.exceptions import GeometryError\n+\n+def test_point_multiplication_order():\n+ point1 = Point(0, 0)\n+ point2 = Point(1, 1)\n+ scalar = sympify(2.0)\n+\n+ # This should work fine\n+ result1 = point1 + point2 * scalar\n+ assert isinstance(result1, Point), \"Expected result1 to be a Point\"\n+\n+ # This should now work without raising an exception\n+ try:\n+ result2 = point1 + scalar * point2\n+ except GeometryError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Ensure that both cases produce the same result\n+ assert result1 == result2, \"__BUG__HERE__\"\n+\n+ # Additional check to ensure both operations are equivalent\n+ assert point2 * scalar == scalar * point2, \"__BUG__HERE__\"\n\\ No newline at end of file\n", + "num_sent_chars": 1602994, + "num_received_chars": 88314, + "elapsed_time": 631.5176892280579, + "lint_repair_count": 7, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-19637.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-19637.json new file mode 100644 index 00000000..2618c3c3 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-19637.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-19637", + "edit_test_file": null, + "code_patch": "diff --git a/sympy/core/sympify.py b/sympy/core/sympify.py\nindex a3f1ce2..6b92cdd 100644\n--- a/sympy/core/sympify.py\n+++ b/sympy/core/sympify.py\n@@ -454,6 +454,9 @@ def kernS(s):\n of an expression, but kernS will prevent that:\n \n >>> 2*(x + y), -(x + 1)\n+\n+ # Initialize kern with a default value\n+ kern = '_SYMPY_UNIQUE_KERN_'\n (2*x + 2*y, -x - 1)\n >>> kernS('2*(x + y)')\n 2*(x + y)\n", + "test_patch": null, + "test_inverted_patch": null, + "num_sent_chars": 364043, + "num_received_chars": 6589, + "elapsed_time": 66.07131338119507, + "lint_repair_count": 0, + "test_generation_attempts": 0, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-20590.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-20590.json new file mode 100644 index 00000000..81acab85 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-20590.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-20590", + "edit_test_file": "sympy/printing/tests/test_repr.py", + "code_patch": "diff --git a/sympy/core/assumptions.py b/sympy/core/assumptions.py\nindex c957931..089acba 100644\n--- a/sympy/core/assumptions.py\n+++ b/sympy/core/assumptions.py\n@@ -573,3 +573,7 @@ def __init__(cls, *args, **kws):\n pname = as_property(fact)\n if not hasattr(cls, pname):\n setattr(cls, pname, make_property(fact))\n+\n+ # Ensure __slots__ is properly set\n+ if '__slots__' not in cls.__dict__:\n+ cls.__slots__ = ()\n", + "test_patch": "diff --git a/sympy/printing/tests/test_symbol_dict_attribute.py b/sympy/printing/tests/test_symbol_dict_attribute.py\nnew file mode 100644\nindex 0000000..be35169\n--- /dev/null\n+++ b/sympy/printing/tests/test_symbol_dict_attribute.py\n@@ -0,0 +1,25 @@\n+from sympy import Symbol\n+from sympy.testing.pytest import raises\n+\n+def test_symbol_dict_attribute():\n+ s = Symbol('s')\n+ \n+ # Check if __dict__ attribute exists\n+ assert hasattr(s, '__dict__')\n+ \n+ # Check if __dict__ is empty\n+ assert s.__dict__ == {}\n+ \n+ # Attempt to add a new attribute\n+ s.new_attr = 'test'\n+ \n+ # Check if the new attribute was added successfully\n+ assert hasattr(s, 'new_attr')\n+ assert s.new_attr == 'test'\n+ \n+ # Check if __slots__ still exists and contains 'name'\n+ assert hasattr(s, '__slots__')\n+ assert 'name' in s.__slots__\n+\n+ # Verify that we can access the 'name' attribute\n+ assert s.name == 's'\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/printing/tests/test_symbol_dict_attribute_inverted.py b/sympy/printing/tests/test_symbol_dict_attribute_inverted.py\nnew file mode 100644\nindex 0000000..294c4cc\n--- /dev/null\n+++ b/sympy/printing/tests/test_symbol_dict_attribute_inverted.py\n@@ -0,0 +1,27 @@\n+from sympy import Symbol\n+from sympy.testing.pytest import raises\n+\n+def test_symbol_dict_attribute():\n+ s = Symbol('s')\n+ \n+ # Check if __dict__ attribute does not exist\n+ if hasattr(s, '__dict__'):\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Attempt to access __dict__ should raise an AttributeError\n+ with raises(AttributeError):\n+ s.__dict__\n+ \n+ # Check if __slots__ exists and contains 'name'\n+ assert hasattr(s, '__slots__')\n+ assert 'name' in s.__slots__\n+ \n+ # Verify that we can access the 'name' attribute\n+ assert s.name == 's'\n+ \n+ # Attempt to add a new attribute should raise an AttributeError\n+ with raises(AttributeError):\n+ s.new_attr = 'test'\n+ \n+ # Check that the new attribute was not added\n+ assert not hasattr(s, 'new_attr')\n", + "num_sent_chars": 1625376, + "num_received_chars": 99232, + "elapsed_time": 665.0515758991241, + "lint_repair_count": 0, + "test_generation_attempts": 8, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-22456.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-22456.json new file mode 100644 index 00000000..956bc356 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-22456.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-22456", + "edit_test_file": "sympy/codegen/tests/test_ast.py", + "code_patch": "diff --git a/sympy/codegen/ast.py b/sympy/codegen/ast.py\nindex a02714b..a51040a 100644\n--- a/sympy/codegen/ast.py\n+++ b/sympy/codegen/ast.py\n@@ -892,21 +892,42 @@ class String(Token):\n 'foo'\n >>> print(repr(f))\n String('foo')\n+ >>> f == f.func(*f.args)\n+ True\n \n \"\"\"\n __slots__ = ('text',)\n- not_in_args = ['text']\n is_Atom = True\n \n+ def __new__(cls, text):\n+ obj = Token.__new__(cls)\n+ obj.text = cls._construct_text(text)\n+ return obj\n+\n @classmethod\n def _construct_text(cls, text):\n if not isinstance(text, str):\n raise TypeError(\"Argument text is not a string type.\")\n return text\n \n+ @property\n+ def args(self):\n+ return (self.text,)\n+\n+ def __eq__(self, other):\n+ if isinstance(other, String):\n+ return self.text == other.text\n+ return False\n+\n+ def __hash__(self):\n+ return hash((type(self), self.text))\n+\n def _sympystr(self, printer, *args, **kwargs):\n return self.text\n \n+ def __repr__(self):\n+ return \"{}('{}')\".format(self.__class__.__name__, self.text)\n+\n \n class QuotedString(String):\n \"\"\" Represents a string which should be printed with quotes. \"\"\"\n", + "test_patch": "diff --git a/sympy/codegen/tests/test_string_argument_invariance.py b/sympy/codegen/tests/test_string_argument_invariance.py\nnew file mode 100644\nindex 0000000..5c5433d\n--- /dev/null\n+++ b/sympy/codegen/tests/test_string_argument_invariance.py\n@@ -0,0 +1,17 @@\n+from sympy.codegen.ast import String\n+from sympy.testing.pytest import raises\n+\n+def test_string_argument_invariance():\n+ # Create a String instance\n+ s = String('test')\n+\n+ # Test that the kwargs-based invariance works\n+ assert s.func(**s.kwargs()) == s\n+\n+ # Test that the args-based invariance fails\n+ # This should raise an exception or return False, demonstrating the issue\n+ with raises(Exception):\n+ assert s.func(*s.args) == s\n+\n+ # Alternatively, if it doesn't raise an exception but simply doesn't work:\n+ # assert s.func(*s.args) != s\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/codegen/tests/test_string_argument_invariance_inverted.py b/sympy/codegen/tests/test_string_argument_invariance_inverted.py\nnew file mode 100644\nindex 0000000..3d7e9bf\n--- /dev/null\n+++ b/sympy/codegen/tests/test_string_argument_invariance_inverted.py\n@@ -0,0 +1,27 @@\n+from sympy.codegen.ast import String\n+from sympy.testing.pytest import raises\n+\n+def test_string_argument_invariance():\n+ # Create a String instance\n+ s = String('test')\n+\n+ # Test that the kwargs-based invariance works\n+ assert s.func(**s.kwargs()) == s\n+\n+ # Test that the args-based invariance works\n+ # This should now fail when the issue is observed\n+ try:\n+ result = s.func(*s.args)\n+ if result != s:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ except Exception as e:\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+\n+ # Additional test to ensure the behavior is consistent\n+ t = String('another_test')\n+ try:\n+ result = t.func(*t.args)\n+ if result != t:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ except Exception as e:\n+ raise AssertionError(\"__BUG__HERE__\") from e\n\\ No newline at end of file\n", + "num_sent_chars": 1690505, + "num_received_chars": 81243, + "elapsed_time": 555.7458951473236, + "lint_repair_count": 7, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 0, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23262.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23262.json new file mode 100644 index 00000000..8af0101c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23262.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-23262", + "edit_test_file": "sympy/utilities/tests/test_lambdify.py", + "code_patch": "diff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py\nindex da67263..9ad8874 100644\n--- a/sympy/utilities/lambdify.py\n+++ b/sympy/utilities/lambdify.py\n@@ -951,6 +951,7 @@ def _recursive_to_string(doprint, arg):\n printer with SymPy types (so that the printer safely can use SymPy-methods).\"\"\"\n from sympy.matrices.common import MatrixOperations\n from sympy.core.basic import Basic\n+ from sympy.core.containers import Tuple\n \n if isinstance(arg, (Basic, MatrixOperations)):\n return doprint(arg)\n@@ -959,9 +960,17 @@ def _recursive_to_string(doprint, arg):\n left, right = \"[]\"\n elif isinstance(arg, tuple):\n left, right = \"()\"\n+ if len(arg) == 1:\n+ # Add trailing comma for single-element tuples\n+ return left + _recursive_to_string(doprint, arg[0]) + \",\" + right\n+ elif isinstance(arg, Tuple):\n+ left, right = \"()\"\n+ if len(arg) == 1:\n+ # Add trailing comma for single-element Tuple objects\n+ return left + _recursive_to_string(doprint, arg[0]) + \",\" + right\n else:\n raise NotImplementedError(\"unhandled type: %s, %s\" % (type(arg), arg))\n- return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right\n+ return left + ', '.join(_recursive_to_string(doprint, e) for e in arg) + right\n elif isinstance(arg, str):\n return arg\n else:\n", + "test_patch": "diff --git a/sympy/utilities/tests/test_tuple_generation.py b/sympy/utilities/tests/test_tuple_generation.py\nnew file mode 100644\nindex 0000000..ef3d787\n--- /dev/null\n+++ b/sympy/utilities/tests/test_tuple_generation.py\n@@ -0,0 +1,29 @@\n+import inspect\n+from sympy import lambdify\n+\n+def test_single_element_tuple_generation():\n+ # Generate a lambda function that returns a tuple with a single element\n+ lambda_func = lambdify([], tuple([1]))\n+ \n+ # Get the source code of the generated function\n+ source_code = inspect.getsource(lambda_func)\n+ \n+ # Check if the generated code is incorrect (missing comma for single-element tuple)\n+ assert 'return (1)' in source_code, \"Expected incorrect tuple generation for single element\"\n+ \n+ # Verify that the function actually returns an integer instead of a tuple\n+ result = lambda_func()\n+ assert isinstance(result, int), \"Expected an integer to be returned, not a tuple\"\n+ assert result == 1, \"Expected the result to be 1\"\n+\n+ # Test that multi-element tuples are still generated correctly\n+ lambda_func_multi = lambdify([], tuple([1, 2]))\n+ source_code_multi = inspect.getsource(lambda_func_multi)\n+ \n+ # Check if the generated code is correct for multi-element tuple\n+ assert 'return (1, 2)' in source_code_multi, \"Expected correct tuple generation for multiple elements\"\n+ \n+ # Verify that the function returns a tuple for multiple elements\n+ result_multi = lambda_func_multi()\n+ assert isinstance(result_multi, tuple), \"Expected a tuple to be returned for multiple elements\"\n+ assert result_multi == (1, 2), \"Expected the result to be (1, 2)\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/utilities/tests/test_tuple_generation_inverted.py b/sympy/utilities/tests/test_tuple_generation_inverted.py\nnew file mode 100644\nindex 0000000..45637e8\n--- /dev/null\n+++ b/sympy/utilities/tests/test_tuple_generation_inverted.py\n@@ -0,0 +1,32 @@\n+import inspect\n+from sympy import lambdify\n+\n+def test_single_element_tuple_generation():\n+ # Generate a lambda function that returns a tuple with a single element\n+ lambda_func = lambdify([], tuple([1]))\n+ \n+ # Get the source code of the generated function\n+ source_code = inspect.getsource(lambda_func)\n+ \n+ # Check if the generated code is correct (includes comma for single-element tuple)\n+ if 'return (1)' in source_code:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Verify that the function actually returns a tuple\n+ result = lambda_func()\n+ if not isinstance(result, tuple):\n+ raise AssertionError(\"__BUG__HERE__\")\n+ if result != (1,):\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Test that multi-element tuples are still generated correctly\n+ lambda_func_multi = lambdify([], tuple([1, 2]))\n+ source_code_multi = inspect.getsource(lambda_func_multi)\n+ \n+ # Check if the generated code is correct for multi-element tuple\n+ assert 'return (1, 2)' in source_code_multi, \"Expected correct tuple generation for multiple elements\"\n+ \n+ # Verify that the function returns a tuple for multiple elements\n+ result_multi = lambda_func_multi()\n+ assert isinstance(result_multi, tuple), \"Expected a tuple to be returned for multiple elements\"\n+ assert result_multi == (1, 2), \"Expected the result to be (1, 2)\"\n\\ No newline at end of file\n", + "num_sent_chars": 273514, + "num_received_chars": 14781, + "elapsed_time": 113.96087574958801, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23824.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23824.json new file mode 100644 index 00000000..104dd206 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-23824.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-23824", + "edit_test_file": "sympy/physics/hep/tests/test_gamma_matrices.py", + "code_patch": "diff --git a/sympy/physics/hep/gamma_matrices.py b/sympy/physics/hep/gamma_matrices.py\nindex 23284e4..9f1569e 100644\n--- a/sympy/physics/hep/gamma_matrices.py\n+++ b/sympy/physics/hep/gamma_matrices.py\n@@ -351,6 +351,12 @@ def kahane_simplify(expression):\n If spinor indices are given, the matrices must be given in\n the order given in the product.\n \n+ The order of leading uncontracted gamma matrices is preserved during simplification.\n+ This is crucial for maintaining the correctness of the expression, as changing the\n+ order of these matrices would alter the meaning of the expression. The simplification\n+ process only affects contracted gamma matrices, leaving the order of uncontracted\n+ matrices unchanged.\n+\n Algorithm\n =========\n \n@@ -692,14 +698,20 @@ def kahane_simplify(expression):\n # power of two factor, as described in Kahane's paper:\n resulting_coeff *= 2**(number_of_contractions)\n \n- # If `first_dum_pos` is not zero, it means that there are trailing free gamma\n+ # If `first_dum_pos` is not zero, it means that there are leading uncontracted gamma\n # matrices in front of `expression`, so multiply by them:\n+ # IMPORTANT: We need to maintain the original order of these matrices\n+ leading_matrices = []\n for i in range(0, first_dum_pos):\n- [ri.insert(0, free_pos[i]) for ri in resulting_indices]\n-\n+ leading_matrices.append(free_pos[i])\n+ \n resulting_expr = S.Zero\n for i in resulting_indices:\n temp_expr = S.One\n+ # First, multiply by the leading uncontracted matrices in their original order\n+ for j in leading_matrices:\n+ temp_expr *= GammaMatrix(j)\n+ # Then, multiply by the rest of the matrices\n for j in i:\n temp_expr *= GammaMatrix(j)\n resulting_expr += temp_expr\n", + "test_patch": "diff --git a/sympy/physics/hep/tests/test_kahane_simplify_leading_gamma_matrices.py b/sympy/physics/hep/tests/test_kahane_simplify_leading_gamma_matrices.py\nnew file mode 100644\nindex 0000000..8783b94\n--- /dev/null\n+++ b/sympy/physics/hep/tests/test_kahane_simplify_leading_gamma_matrices.py\n@@ -0,0 +1,23 @@\n+from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex\n+from sympy.physics.hep.gamma_matrices import kahane_simplify\n+from sympy.tensor.tensor import tensor_indices\n+\n+def test_kahane_simplify_leading_gamma_matrices():\n+ mu, nu, rho, sigma = tensor_indices(\"mu, nu, rho, sigma\", LorentzIndex)\n+ \n+ # Test case 1: Contracted indices at the beginning\n+ t1 = G(mu)*G(-mu)*G(rho)*G(sigma)\n+ r1 = kahane_simplify(t1)\n+ assert r1.equals(4*G(rho)*G(sigma)), \"Failed to simplify G(mu)*G(-mu)*G(rho)*G(sigma) correctly\"\n+ \n+ # Test case 2: Contracted indices at the end\n+ t2 = G(rho)*G(sigma)*G(mu)*G(-mu)\n+ r2 = kahane_simplify(t2)\n+ \n+ # This assertion should pass when the bug is present\n+ # It checks that the order of leading gamma matrices is incorrectly reversed\n+ assert r2.equals(4*G(sigma)*G(rho)), \"The order of leading gamma matrices is not reversed as expected\"\n+ \n+ # This assertion should fail when the bug is present\n+ # It checks for the correct simplification (which is not happening due to the bug)\n+ assert not r2.equals(4*G(rho)*G(sigma)), \"Unexpectedly simplified G(rho)*G(sigma)*G(mu)*G(-mu) correctly\"\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/physics/hep/tests/test_kahane_simplify_leading_gamma_matrices_inverted.py b/sympy/physics/hep/tests/test_kahane_simplify_leading_gamma_matrices_inverted.py\nnew file mode 100644\nindex 0000000..7c662d8\n--- /dev/null\n+++ b/sympy/physics/hep/tests/test_kahane_simplify_leading_gamma_matrices_inverted.py\n@@ -0,0 +1,23 @@\n+from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex\n+from sympy.physics.hep.gamma_matrices import kahane_simplify\n+from sympy.tensor.tensor import tensor_indices\n+\n+def test_kahane_simplify_leading_gamma_matrices():\n+ mu, nu, rho, sigma = tensor_indices(\"mu, nu, rho, sigma\", LorentzIndex)\n+ \n+ # Test case 1: Contracted indices at the beginning\n+ t1 = G(mu)*G(-mu)*G(rho)*G(sigma)\n+ r1 = kahane_simplify(t1)\n+ assert r1.equals(4*G(rho)*G(sigma)), \"Failed to simplify G(mu)*G(-mu)*G(rho)*G(sigma) correctly\"\n+ \n+ # Test case 2: Contracted indices at the end\n+ t2 = G(rho)*G(sigma)*G(mu)*G(-mu)\n+ r2 = kahane_simplify(t2)\n+ \n+ # This assertion will fail when the bug is present\n+ # It checks for the correct simplification (which is not happening due to the bug)\n+ if r2.equals(4*G(sigma)*G(rho)):\n+ raise AssertionError(\"__BUG__HERE__: The order of leading gamma matrices is incorrectly reversed\")\n+ \n+ # This assertion will pass when the bug is fixed\n+ assert r2.equals(4*G(rho)*G(sigma)), \"Failed to simplify G(rho)*G(sigma)*G(mu)*G(-mu) correctly\"\n\\ No newline at end of file\n", + "num_sent_chars": 457272, + "num_received_chars": 14133, + "elapsed_time": 259.7439286708832, + "lint_repair_count": 0, + "test_generation_attempts": 1, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24213.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24213.json new file mode 100644 index 00000000..a881da03 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24213.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-24213", + "edit_test_file": "sympy/physics/units/tests/test_quantities.py", + "code_patch": "diff --git a/sympy/physics/units/unitsystem.py b/sympy/physics/units/unitsystem.py\nindex a436880..506de19 100644\n--- a/sympy/physics/units/unitsystem.py\n+++ b/sympy/physics/units/unitsystem.py\n@@ -170,6 +170,21 @@ def _collect_factor_and_dimension(self, expr):\n if self.get_dimension_system().is_dimensionless(exp_dim):\n exp_dim = 1\n return factor ** exp_factor, dim ** (exp_factor * exp_dim)\n+ elif isinstance(expr, Add):\n+ factors = []\n+ dimensions = []\n+ for arg in expr.args:\n+ arg_factor, arg_dim = self._collect_factor_and_dimension(arg)\n+ factors.append(arg_factor)\n+ dimensions.append(arg_dim)\n+ \n+ if not all(self.get_dimension_system().equivalent_dims(dimensions[0], dim) for dim in dimensions[1:]):\n+ raise ValueError(\n+ 'Dimension of addends are not equivalent. '\n+ 'Dimensions found: {}'.format(dimensions)\n+ )\n+ \n+ return Add(*factors), dimensions[0]\n elif isinstance(expr, Add):\n factor, dim = self._collect_factor_and_dimension(expr.args[0])\n for addend in expr.args[1:]:\n", + "test_patch": "diff --git a/sympy/physics/units/tests/test_dimension_equivalence.py b/sympy/physics/units/tests/test_dimension_equivalence.py\nnew file mode 100644\nindex 0000000..ad00506\n--- /dev/null\n+++ b/sympy/physics/units/tests/test_dimension_equivalence.py\n@@ -0,0 +1,21 @@\n+from sympy.physics import units\n+from sympy.physics.units.systems.si import SI\n+from sympy.testing.pytest import raises\n+\n+def test_collect_factor_and_dimension_addition():\n+ v1 = units.Quantity('v1')\n+ SI.set_quantity_dimension(v1, units.velocity)\n+ SI.set_quantity_scale_factor(v1, 2 * units.meter / units.second)\n+\n+ a1 = units.Quantity('a1')\n+ SI.set_quantity_dimension(a1, units.acceleration)\n+ SI.set_quantity_scale_factor(a1, -9.8 * units.meter / units.second**2)\n+\n+ t1 = units.Quantity('t1')\n+ SI.set_quantity_dimension(t1, units.time)\n+ SI.set_quantity_scale_factor(t1, 5 * units.second)\n+\n+ expr1 = a1*t1 + v1\n+\n+ with raises(ValueError):\n+ SI._collect_factor_and_dimension(expr1)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/physics/units/tests/test_dimension_equivalence_inverted.py b/sympy/physics/units/tests/test_dimension_equivalence_inverted.py\nnew file mode 100644\nindex 0000000..d914674\n--- /dev/null\n+++ b/sympy/physics/units/tests/test_dimension_equivalence_inverted.py\n@@ -0,0 +1,26 @@\n+from sympy.physics import units\n+from sympy.physics.units.systems.si import SI\n+\n+def test_collect_factor_and_dimension_addition():\n+ v1 = units.Quantity('v1')\n+ SI.set_quantity_dimension(v1, units.velocity)\n+ SI.set_quantity_scale_factor(v1, 2 * units.meter / units.second)\n+\n+ a1 = units.Quantity('a1')\n+ SI.set_quantity_dimension(a1, units.acceleration)\n+ SI.set_quantity_scale_factor(a1, -9.8 * units.meter / units.second**2)\n+\n+ t1 = units.Quantity('t1')\n+ SI.set_quantity_dimension(t1, units.time)\n+ SI.set_quantity_scale_factor(t1, 5 * units.second)\n+\n+ expr1 = a1*t1 + v1\n+\n+ try:\n+ result = SI._collect_factor_and_dimension(expr1)\n+ except ValueError as e:\n+ if str(e).startswith('Dimension of \"v1\" is Dimension(velocity), but it should be Dimension(acceleration*time)'):\n+ raise AssertionError(\"__BUG__HERE__\") from e\n+ else:\n+ # If no exception is raised, the test should pass\n+ assert result is not None, \"Expected _collect_factor_and_dimension to return a result\"\n", + "num_sent_chars": 1461422, + "num_received_chars": 110835, + "elapsed_time": 610.0301206111908, + "lint_repair_count": 5, + "test_generation_attempts": 2, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": true, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24562.json b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24562.json new file mode 100644 index 00000000..a2d6832b --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/code_patches/sympy__sympy-24562.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-24562", + "edit_test_file": "sympy/polys/tests/test_pythonrational.py", + "code_patch": "diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py\nindex 52f7ea4..b437eca 100644\n--- a/sympy/core/numbers.py\n+++ b/sympy/core/numbers.py\n@@ -1490,8 +1490,9 @@ class Rational(Number):\n >>> Rational(1, 2)\n 1/2\n \n- Rational is unprejudiced in accepting input. If a float is passed, the\n- underlying value of the binary representation will be returned:\n+ Rational is unprejudiced in accepting input. If a float or a string\n+ representing a decimal is passed, the exact fractional representation\n+ will be returned:\n \n >>> Rational(.5)\n 1/2\n@@ -1597,6 +1598,16 @@ def __new__(cls, p, q=None, gcd=None):\n if isinstance(p, (float, Float)):\n return Rational(*_as_integer_ratio(p))\n \n+ if isinstance(p, str):\n+ try:\n+ # Handle decimal strings\n+ if '.' in p:\n+ from sympy.core.numbers import Float\n+ p = Float(p)\n+ return Rational(*_as_integer_ratio(p))\n+ except ValueError:\n+ pass\n+\n if not isinstance(p, str):\n try:\n p = sympify(p)\n@@ -1613,6 +1624,11 @@ def __new__(cls, p, q=None, gcd=None):\n fq = fractions.Fraction(q)\n p = fp/fq\n try:\n+ # Handle decimal strings\n+ if '.' in p:\n+ from sympy.core.numbers import Float\n+ p = Float(p)\n+ return Rational(*_as_integer_ratio(p))\n p = fractions.Fraction(p)\n except ValueError:\n pass # error will raise below\n@@ -1633,7 +1649,19 @@ def __new__(cls, p, q=None, gcd=None):\n p = int(p)\n \n if not isinstance(q, SYMPY_INTS):\n- q = Rational(q)\n+ if isinstance(q, str):\n+ try:\n+ # Handle decimal strings for q\n+ if '.' in q:\n+ from sympy.core.numbers import Float\n+ q = Float(q)\n+ q = Rational(*_as_integer_ratio(q))\n+ else:\n+ q = Rational(q)\n+ except ValueError:\n+ raise ValueError(f\"Invalid input for q: {q}\")\n+ else:\n+ q = Rational(q)\n p *= q.q\n q = q.p\n else:\n", + "test_patch": "diff --git a/sympy/polys/tests/test_rational_calc_value.py b/sympy/polys/tests/test_rational_calc_value.py\nnew file mode 100644\nindex 0000000..b7f5b11\n--- /dev/null\n+++ b/sympy/polys/tests/test_rational_calc_value.py\n@@ -0,0 +1,16 @@\n+from sympy.core.numbers import Rational\n+from sympy.testing.pytest import raises\n+\n+def test_rational_calc_value():\n+ # Test the issue with Rational('0.5', '100')\n+ assert Rational('0.5', '100') == Rational(1, 100100)\n+\n+ # Test the correct behavior with Rational(0.5, 100)\n+ assert Rational(0.5, 100) == Rational(1, 200)\n+\n+ # Ensure that the two expressions produce different results\n+ assert Rational('0.5', '100') != Rational(0.5, 100)\n+\n+ # Additional test to show the discrepancy\n+ assert Rational('0.5', '100') * 200 != 1\n+ assert Rational(0.5, 100) * 200 == 1\n\\ No newline at end of file\n", + "test_inverted_patch": null, + "num_sent_chars": 2015091, + "num_received_chars": 97815, + "elapsed_time": 812.4266154766083, + "lint_repair_count": 0, + "test_generation_attempts": 9, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10949246453/predictions-0.zip b/data/solve_code_runs/run_id/10949246453/predictions-0.zip new file mode 100644 index 00000000..e868c53c --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/predictions-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3dbf0fa05ddcd989ef5ecb699496974696dd4e59ccb93de6c167a52bfacfa96 +size 103461 diff --git a/data/solve_code_runs/run_id/10949246453/predictions-1.zip b/data/solve_code_runs/run_id/10949246453/predictions-1.zip new file mode 100644 index 00000000..d0ea3386 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/predictions-1.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f340ad0139c5a00645dcaf7391c93ab80252d47a8815fbe8129e8b4d6a7a92dd +size 101809 diff --git a/data/solve_code_runs/run_id/10949246453/predictions-2.zip b/data/solve_code_runs/run_id/10949246453/predictions-2.zip new file mode 100644 index 00000000..8504b296 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/predictions-2.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d20a8c5fc903019a9e8f10821b5684234a7eb8d4a8c32ae226d78faf6d8b387 +size 94007 diff --git a/data/solve_code_runs/run_id/10949246453/predictions-3.zip b/data/solve_code_runs/run_id/10949246453/predictions-3.zip new file mode 100644 index 00000000..e5a5e079 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/predictions-3.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9306a2d6ede471ba6b5e43c6a98d76b9b6303101790e87ff0ff9b3b920d66d1c +size 95605 diff --git a/data/solve_code_runs/run_id/10949246453/predictions-4.zip b/data/solve_code_runs/run_id/10949246453/predictions-4.zip new file mode 100644 index 00000000..49a2104d --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/predictions-4.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:378fc617e998dbe1157cbdbf8a7fb6f4712014b77f68d005c23d2f340e6472e9 +size 96479 diff --git a/data/solve_code_runs/run_id/10949246453/predictions-5.zip b/data/solve_code_runs/run_id/10949246453/predictions-5.zip new file mode 100644 index 00000000..5a204bc9 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/predictions-5.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e798a7430a836fa2511e91944d5dcae5f7e14f417711cb3426b21d2d15ec3a9f +size 90725 diff --git a/data/solve_code_runs/run_id/10949246453/report.zip b/data/solve_code_runs/run_id/10949246453/report.zip new file mode 100644 index 00000000..7df3f899 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/report.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e73b176e18d3a9fd12bd25606a70e477f261617a3c05e17574a5c273108d494 +size 16819 diff --git a/data/solve_code_runs/run_id/10949246453/run_evaluation-0.zip b/data/solve_code_runs/run_id/10949246453/run_evaluation-0.zip new file mode 100644 index 00000000..7f3f9905 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/run_evaluation-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d5df42e3cb5c01fe3844f6acc17a878650a8269818acf7f9dca5a6425445f68 +size 367898 diff --git a/data/solve_code_runs/run_id/10949246453/run_evaluation-1.zip b/data/solve_code_runs/run_id/10949246453/run_evaluation-1.zip new file mode 100644 index 00000000..49b17815 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/run_evaluation-1.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39fdf946bb3351b552c3408c8223724e6a6dc4ba934493966e9507f0765506bf +size 418674 diff --git a/data/solve_code_runs/run_id/10949246453/run_evaluation-2.zip b/data/solve_code_runs/run_id/10949246453/run_evaluation-2.zip new file mode 100644 index 00000000..af0c045f --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/run_evaluation-2.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8aedcb0365e48c0b79a8a61016f38848789ec99b48cb6f7fe2e203f00a7c652a +size 363655 diff --git a/data/solve_code_runs/run_id/10949246453/run_evaluation-3.zip b/data/solve_code_runs/run_id/10949246453/run_evaluation-3.zip new file mode 100644 index 00000000..35176a60 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/run_evaluation-3.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8c81a9c397f53d733cb03eb359c8c8b58bd954b8c60b099dfcefc574351e603 +size 360622 diff --git a/data/solve_code_runs/run_id/10949246453/run_evaluation-4.zip b/data/solve_code_runs/run_id/10949246453/run_evaluation-4.zip new file mode 100644 index 00000000..16232161 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/run_evaluation-4.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16a78aff72302b2dbb43adc17e9d0710ea9daa2fea2ccb97836660a156c680ab +size 342919 diff --git a/data/solve_code_runs/run_id/10949246453/run_evaluation-5.zip b/data/solve_code_runs/run_id/10949246453/run_evaluation-5.zip new file mode 100644 index 00000000..6d7234d1 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/run_evaluation-5.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f643f956edfc7e97baa99c7c80517dc2c90bb3298634c78ad69406eac114b92c +size 364966 diff --git a/data/solve_code_runs/run_id/10949246453/solutions.zip b/data/solve_code_runs/run_id/10949246453/solutions.zip new file mode 100644 index 00000000..10cf3c6b --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/solutions.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9320cb8780727c67f420ab94c52219fbf91ea4d4ec22ac19418c6fc54b33c6ac +size 197512 diff --git a/data/solve_code_runs/run_id/10949246453/solve-0.zip b/data/solve_code_runs/run_id/10949246453/solve-0.zip new file mode 100644 index 00000000..761a5e66 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/solve-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb54d6e6bda3a94b6e235720e8c95eaffd9b1a342286c8949445cc5588680e5b +size 25003267 diff --git a/data/solve_code_runs/run_id/10949246453/solve-1.zip b/data/solve_code_runs/run_id/10949246453/solve-1.zip new file mode 100644 index 00000000..c4af4f69 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/solve-1.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cf53bf5f01f0b1abdf15650c1c2c25bd1f05468219f0632ba8d561fafe9fce0 +size 20079346 diff --git a/data/solve_code_runs/run_id/10949246453/solve-2.zip b/data/solve_code_runs/run_id/10949246453/solve-2.zip new file mode 100644 index 00000000..cb329be8 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/solve-2.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65c69b61cd0a9df7203c68a0f3ab47aceb6176f6b3e241f65aba54ab3aa596a1 +size 18741576 diff --git a/data/solve_code_runs/run_id/10949246453/solve-3.zip b/data/solve_code_runs/run_id/10949246453/solve-3.zip new file mode 100644 index 00000000..3ecc78a6 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/solve-3.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af9752e25f5b706435a21ae66f91cd41a77049c5d66532043534691f1607d762 +size 23134858 diff --git a/data/solve_code_runs/run_id/10949246453/solve-4.zip b/data/solve_code_runs/run_id/10949246453/solve-4.zip new file mode 100644 index 00000000..d3c3918e --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/solve-4.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2065f26123edaa63a638e9bea7a04803f603df205dd11966c969dc6be30aecdf +size 21825999 diff --git a/data/solve_code_runs/run_id/10949246453/solve-5.zip b/data/solve_code_runs/run_id/10949246453/solve-5.zip new file mode 100644 index 00000000..0d2d61b8 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/solve-5.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e944d59a4d7c8bfb7f4215f20ed323975724be82069da2328984b0d300bfa81 +size 19524388 diff --git a/data/solve_code_runs/run_id/10949246453/test-patch.zip b/data/solve_code_runs/run_id/10949246453/test-patch.zip new file mode 100644 index 00000000..8a03e376 --- /dev/null +++ b/data/solve_code_runs/run_id/10949246453/test-patch.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb4575c4dece5f021c099ea84549b9fbf07174cf12ab9ac67a1a1140506adf4a +size 79550 diff --git a/data/solve_code_runs/run_id/10950797630/code_patches/django__django-15280.json b/data/solve_code_runs/run_id/10950797630/code_patches/django__django-15280.json new file mode 100644 index 00000000..4bced9d3 --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/code_patches/django__django-15280.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15280", + "edit_test_file": "tests/queries/tests.py", + "code_patch": "diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py\nindex a9faef3..f60c4e9 100644\n--- a/django/contrib/auth/models.py\n+++ b/django/contrib/auth/models.py\n@@ -388,6 +388,52 @@ class AbstractUser(AbstractBaseUser, PermissionsMixin):\n \"\"\"Send an email to this user.\"\"\"\n send_mail(subject, message, from_email, [self.email], **kwargs)\n \n+ def _get_deferred_fields(self):\n+ \"\"\"\n+ Return a set of deferred field names for this instance.\n+ \"\"\"\n+ deferred_fields = set()\n+ if hasattr(self, '_deferred') and self._deferred:\n+ deferred_fields = set(self._deferred)\n+ return deferred_fields\n+\n+ def _track_deferred_fields(self):\n+ \"\"\"\n+ Track deferred fields for prefetched related objects.\n+ \"\"\"\n+ if not hasattr(self, '_prefetched_objects_cache'):\n+ return\n+\n+ for cache_name, related_objects in self._prefetched_objects_cache.items():\n+ if isinstance(related_objects, list):\n+ for obj in related_objects:\n+ obj._deferred_fields = obj._get_deferred_fields()\n+ elif isinstance(related_objects, models.Model):\n+ related_objects._deferred_fields = related_objects._get_deferred_fields()\n+\n+ def __getattribute__(self, name):\n+ \"\"\"\n+ Override to handle deferred fields correctly for prefetched related objects.\n+ \"\"\"\n+ try:\n+ return super().__getattribute__(name)\n+ except AttributeError:\n+ if name == '_deferred_fields':\n+ return set()\n+ \n+ self._track_deferred_fields()\n+ \n+ if hasattr(self, '_deferred_fields') and name in self._deferred_fields:\n+ raise\n+\n+ # Check if the attribute is a related object that has been prefetched\n+ if name in getattr(self, '_prefetched_objects_cache', {}):\n+ related_obj = self._prefetched_objects_cache[name]\n+ if isinstance(related_obj, models.Model):\n+ return related_obj\n+\n+ raise\n+\n \n class User(AbstractUser):\n \"\"\"\n", + "test_patch": "diff --git a/tests/queries/test_prefetch_deferred_fields.py b/tests/queries/test_prefetch_deferred_fields.py\nnew file mode 100644\nindex 0000000..29f5d41\n--- /dev/null\n+++ b/tests/queries/test_prefetch_deferred_fields.py\n@@ -0,0 +1,41 @@\n+from django.test import TestCase\n+from django.db import models\n+from django.db.models import Prefetch\n+\n+class User(models.Model):\n+ email = models.EmailField()\n+ kind = models.CharField(\n+ max_length=10, choices=[(\"ADMIN\", \"Admin\"), (\"REGULAR\", \"Regular\")]\n+ )\n+\n+class Profile(models.Model):\n+ full_name = models.CharField(max_length=255)\n+ user = models.OneToOneField(User, on_delete=models.CASCADE)\n+\n+class PrefetchDeferredFieldsTests(TestCase):\n+ def test_only_related_queryset(self):\n+ user = User.objects.create(\n+ email=\"test@example.com\",\n+ kind=\"ADMIN\",\n+ )\n+ Profile.objects.create(user=user, full_name=\"Test Tester\")\n+ queryset = User.objects.only(\"email\").prefetch_related(\n+ Prefetch(\n+ \"profile\",\n+ queryset=Profile.objects.prefetch_related(\n+ Prefetch(\"user\", queryset=User.objects.only(\"kind\"))\n+ ),\n+ )\n+ )\n+ with self.assertNumQueries(3):\n+ user = queryset.first()\n+ \n+ # This assertion will pass if the issue is present\n+ # (i.e., an unexpected query is executed)\n+ with self.assertNumQueries(1):\n+ self.assertEqual(user.profile.user.kind, \"ADMIN\")\n+ \n+ # Additional assertion to verify the unexpected query\n+ with self.assertNumQueries(1):\n+ deferred_fields = user.profile.user.get_deferred_fields()\n+ self.assertNotIn('kind', deferred_fields)\n", + "test_inverted_patch": "diff --git a/tests/queries/test_prefetch_deferred_fields_inverted.py b/tests/queries/test_prefetch_deferred_fields_inverted.py\nnew file mode 100644\nindex 0000000..06f62ef\n--- /dev/null\n+++ b/tests/queries/test_prefetch_deferred_fields_inverted.py\n@@ -0,0 +1,47 @@\n+from django.test import TestCase\n+from django.db import models\n+from django.db.models import Prefetch\n+\n+class User(models.Model):\n+ email = models.EmailField()\n+ kind = models.CharField(\n+ max_length=10, choices=[(\"ADMIN\", \"Admin\"), (\"REGULAR\", \"Regular\")]\n+ )\n+\n+class Profile(models.Model):\n+ full_name = models.CharField(max_length=255)\n+ user = models.OneToOneField(User, on_delete=models.CASCADE)\n+\n+class PrefetchDeferredFieldsTests(TestCase):\n+ def test_only_related_queryset(self):\n+ user = User.objects.create(\n+ email=\"test@example.com\",\n+ kind=\"ADMIN\",\n+ )\n+ Profile.objects.create(user=user, full_name=\"Test Tester\")\n+ queryset = User.objects.only(\"email\").prefetch_related(\n+ Prefetch(\n+ \"profile\",\n+ queryset=Profile.objects.prefetch_related(\n+ Prefetch(\"user\", queryset=User.objects.only(\"kind\"))\n+ ),\n+ )\n+ )\n+ with self.assertNumQueries(3):\n+ user = queryset.first()\n+ \n+ # This assertion will now fail if the issue is present\n+ # (i.e., an unexpected query is executed)\n+ try:\n+ with self.assertNumQueries(0):\n+ self.assertEqual(user.profile.user.kind, \"ADMIN\")\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ # Additional assertion to verify the unexpected query\n+ try:\n+ with self.assertNumQueries(0):\n+ deferred_fields = user.profile.user.get_deferred_fields()\n+ self.assertNotIn('kind', deferred_fields)\n+ except AssertionError:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2457135, + "num_received_chars": 117039, + "elapsed_time": 682.2423424720764, + "lint_repair_count": 9, + "test_generation_attempts": 7, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10950797630/code_patches/django__django-15563.json b/data/solve_code_runs/run_id/10950797630/code_patches/django__django-15563.json new file mode 100644 index 00000000..539c5dbd --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/code_patches/django__django-15563.json @@ -0,0 +1,20 @@ +{ + "instance_id": "django__django-15563", + "edit_test_file": "tests/update/tests.py", + "code_patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\nindex 556e255..3521417 100644\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -1034,6 +1034,9 @@ class Model(metaclass=ModelBase):\n Try to update the model. Return True if the model was updated (if an\n update query was done and a matching row was found in the DB).\n \"\"\"\n+ from django.db.models import F, Q\n+ from django.db.models.constants import LOOKUP_SEP\n+\n filtered = base_qs.filter(pk=pk_val)\n if not values:\n # We can end up here when saving a model in inheritance chain where\n@@ -1042,6 +1045,31 @@ class Model(metaclass=ModelBase):\n # is a model with just PK - in that case check that the PK still\n # exists.\n return update_fields is not None or filtered.exists()\n+\n+ # Handle multi-table inheritance\n+ if self._meta.parents:\n+ # Get all parent links\n+ parent_links = [\n+ f for f in self._meta.fields if f.is_relation and f.parent_link\n+ ]\n+ \n+ # Create a Q object to join all parent tables\n+ parent_filter = Q()\n+ for link in parent_links:\n+ parent_filter |= Q(**{f\"{link.name}{LOOKUP_SEP}pk\": F(\"pk\")})\n+\n+ # Apply the parent filter to ensure we only update the correct instances\n+ filtered = filtered.filter(parent_filter)\n+\n+ # Update the values dictionary to include parent table fields\n+ for link in parent_links:\n+ parent_fields = [\n+ f.name for f in link.remote_field.model._meta.fields\n+ if f.name in update_fields\n+ ]\n+ for field in parent_fields:\n+ values[f\"{link.name}{LOOKUP_SEP}{field}\"] = values.pop(field)\n+\n if self._meta.select_on_save and not forced_update:\n return (\n filtered.exists()\n", + "test_patch": "diff --git a/tests/update/test_multiple_inheritance_queryset_update.py b/tests/update/test_multiple_inheritance_queryset_update.py\nnew file mode 100644\nindex 0000000..7a09da1\n--- /dev/null\n+++ b/tests/update/test_multiple_inheritance_queryset_update.py\n@@ -0,0 +1,39 @@\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class Base(models.Model):\n+ base_id = models.AutoField(primary_key=True)\n+ field_base = models.IntegerField()\n+\n+\n+class OtherBase(models.Model):\n+ otherbase_id = models.AutoField(primary_key=True)\n+ field_otherbase = models.IntegerField()\n+\n+\n+class Child(Base, OtherBase):\n+ pass\n+\n+\n+class MultipleInheritanceQuerysetUpdateTest(TestCase):\n+ def setUp(self):\n+ OtherBase.objects.create(field_otherbase=100)\n+ OtherBase.objects.create(field_otherbase=101)\n+ Child.objects.create(field_base=0, field_otherbase=0)\n+ Child.objects.create(field_base=1, field_otherbase=1)\n+\n+ def test_update_child_queryset(self):\n+ # Attempt to update Child objects\n+ updated_count = Child.objects.update(field_otherbase=55)\n+\n+ # Assert that the update reports success\n+ self.assertEqual(updated_count, 2)\n+\n+ # Check that Child objects were not actually updated\n+ child_values = list(Child.objects.values('field_otherbase'))\n+ self.assertEqual(child_values, [{'field_otherbase': 0}, {'field_otherbase': 1}])\n+\n+ # Check that OtherBase objects were incorrectly updated\n+ otherbase_values = list(OtherBase.objects.filter(otherbase_id__in=[1, 2]).values('field_otherbase'))\n+ self.assertEqual(otherbase_values, [{'field_otherbase': 55}, {'field_otherbase': 55}])\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/tests/update/test_multiple_inheritance_queryset_update_inverted.py b/tests/update/test_multiple_inheritance_queryset_update_inverted.py\nnew file mode 100644\nindex 0000000..ba808d5\n--- /dev/null\n+++ b/tests/update/test_multiple_inheritance_queryset_update_inverted.py\n@@ -0,0 +1,43 @@\n+from django.db import models\n+from django.test import TestCase\n+\n+\n+class Base(models.Model):\n+ base_id = models.AutoField(primary_key=True)\n+ field_base = models.IntegerField()\n+\n+\n+class OtherBase(models.Model):\n+ otherbase_id = models.AutoField(primary_key=True)\n+ field_otherbase = models.IntegerField()\n+\n+\n+class Child(Base, OtherBase):\n+ pass\n+\n+\n+class MultipleInheritanceQuerysetUpdateTest(TestCase):\n+ def setUp(self):\n+ OtherBase.objects.create(field_otherbase=100)\n+ OtherBase.objects.create(field_otherbase=101)\n+ Child.objects.create(field_base=0, field_otherbase=0)\n+ Child.objects.create(field_base=1, field_otherbase=1)\n+\n+ def test_update_child_queryset(self):\n+ # Attempt to update Child objects\n+ updated_count = Child.objects.update(field_otherbase=55)\n+\n+ # Assert that the update reports success\n+ self.assertEqual(updated_count, 2)\n+\n+ # Check that Child objects were actually updated\n+ child_values = list(Child.objects.values('field_otherbase'))\n+ expected_child_values = [{'field_otherbase': 55}, {'field_otherbase': 55}]\n+ if child_values != expected_child_values:\n+ raise AssertionError(\"__BUG__HERE__\")\n+\n+ # Check that OtherBase objects were not incorrectly updated\n+ otherbase_values = list(OtherBase.objects.filter(otherbase_id__in=[1, 2]).values('field_otherbase'))\n+ expected_otherbase_values = [{'field_otherbase': 100}, {'field_otherbase': 101}]\n+ if otherbase_values != expected_otherbase_values:\n+ raise AssertionError(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2208533, + "num_received_chars": 139996, + "elapsed_time": 786.3316979408264, + "lint_repair_count": 5, + "test_generation_attempts": 7, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": 1, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-10908.json b/data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-10908.json new file mode 100644 index 00000000..fba2835b --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-10908.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-10908", + "edit_test_file": "sklearn/tests/test_pipeline.py", + "code_patch": "diff --git a/sklearn/feature_extraction/text.py b/sklearn/feature_extraction/text.py\nindex 9b1ebd6..5fd25b2 100644\n--- a/sklearn/feature_extraction/text.py\n+++ b/sklearn/feature_extraction/text.py\n@@ -300,8 +300,12 @@ class VectorizerMixin(object):\n \n def _check_vocabulary(self):\n \"\"\"Check if vocabulary is empty or missing (not fit-ed)\"\"\"\n- msg = \"%(name)s - Vocabulary wasn't fitted.\"\n- check_is_fitted(self, 'vocabulary_', msg=msg),\n+ if self.vocabulary is not None:\n+ if not hasattr(self, 'vocabulary_'):\n+ self._validate_vocabulary()\n+ else:\n+ msg = \"%(name)s - Vocabulary wasn't fitted.\"\n+ check_is_fitted(self, 'vocabulary_', msg=msg)\n \n if len(self.vocabulary_) == 0:\n raise ValueError(\"Vocabulary is empty\")\n@@ -315,6 +319,9 @@ class VectorizerMixin(object):\n \"lower boundary larger than the upper boundary.\"\n % str(self.ngram_range))\n \n+ if self.vocabulary is not None and not hasattr(self, 'vocabulary_'):\n+ self._validate_vocabulary()\n+\n \n class HashingVectorizer(BaseEstimator, VectorizerMixin, TransformerMixin):\n \"\"\"Convert a collection of text documents to a matrix of token occurrences\n", + "test_patch": "diff --git a/sklearn/tests/test_count_vectorizer_feature_names.py b/sklearn/tests/test_count_vectorizer_feature_names.py\nnew file mode 100644\nindex 0000000..445fbde\n--- /dev/null\n+++ b/sklearn/tests/test_count_vectorizer_feature_names.py\n@@ -0,0 +1,35 @@\n+import pytest\n+from sklearn.feature_extraction.text import CountVectorizer\n+from sklearn.exceptions import NotFittedError\n+\n+def test_count_vectorizer_get_feature_names_with_vocabulary():\n+ # Define a vocabulary\n+ vocabulary = ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']\n+ \n+ # Initialize CountVectorizer with the vocabulary\n+ vectorizer = CountVectorizer(vocabulary=vocabulary)\n+ \n+ # Check that the vectorizer doesn't have vocabulary_ attribute yet\n+ assert not hasattr(vectorizer, \"vocabulary_\")\n+ \n+ # Attempt to call get_feature_names() and expect NotFittedError\n+ with pytest.raises(NotFittedError, match=\"CountVectorizer - Vocabulary wasn't fitted.\"):\n+ vectorizer.get_feature_names()\n+ \n+ # Define a sample corpus\n+ corpus = [\n+ 'This is the first document.',\n+ 'This is the second second document.',\n+ 'And the third one.',\n+ 'Is this the first document?',\n+ ]\n+ \n+ # Transform the corpus\n+ vectorizer.transform(corpus)\n+ \n+ # Check that the vectorizer now has vocabulary_ attribute\n+ assert hasattr(vectorizer, \"vocabulary_\")\n+ \n+ # Now get_feature_names() should work without raising an exception\n+ feature_names = vectorizer.get_feature_names()\n+ assert feature_names == vocabulary\n", + "test_inverted_patch": "diff --git a/sklearn/tests/test_count_vectorizer_feature_names_inverted.py b/sklearn/tests/test_count_vectorizer_feature_names_inverted.py\nnew file mode 100644\nindex 0000000..282cd7b\n--- /dev/null\n+++ b/sklearn/tests/test_count_vectorizer_feature_names_inverted.py\n@@ -0,0 +1,40 @@\n+import pytest\n+from sklearn.feature_extraction.text import CountVectorizer\n+from sklearn.exceptions import NotFittedError\n+\n+def test_count_vectorizer_get_feature_names_with_vocabulary():\n+ # Define a vocabulary\n+ vocabulary = ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']\n+ \n+ # Initialize CountVectorizer with the vocabulary\n+ vectorizer = CountVectorizer(vocabulary=vocabulary)\n+ \n+ # Check that the vectorizer doesn't have vocabulary_ attribute yet\n+ assert not hasattr(vectorizer, \"vocabulary_\")\n+ \n+ # Attempt to call get_feature_names() and expect it to work without raising an exception\n+ try:\n+ feature_names = vectorizer.get_feature_names()\n+ except NotFittedError:\n+ pytest.fail(\"__BUG__HERE__\")\n+ \n+ # If no exception is raised, the test should fail\n+ assert feature_names == vocabulary, \"__BUG__HERE__\"\n+ \n+ # Define a sample corpus\n+ corpus = [\n+ 'This is the first document.',\n+ 'This is the second second document.',\n+ 'And the third one.',\n+ 'Is this the first document?',\n+ ]\n+ \n+ # Transform the corpus\n+ vectorizer.transform(corpus)\n+ \n+ # Check that the vectorizer now has vocabulary_ attribute\n+ assert hasattr(vectorizer, \"vocabulary_\")\n+ \n+ # Now get_feature_names() should work without raising an exception\n+ feature_names = vectorizer.get_feature_names()\n+ assert feature_names == vocabulary\n", + "num_sent_chars": 567500, + "num_received_chars": 31053, + "elapsed_time": 213.86344528198242, + "lint_repair_count": 0, + "test_generation_attempts": 4, + "code_generation_attempts": 1, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": true, + "code_patch_score": 3, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-13779.json b/data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-13779.json new file mode 100644 index 00000000..bbf4abfa --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/code_patches/scikit-learn__scikit-learn-13779.json @@ -0,0 +1,20 @@ +{ + "instance_id": "scikit-learn__scikit-learn-13779", + "edit_test_file": "sklearn/ensemble/tests/test_voting.py", + "code_patch": "diff --git a/sklearn/ensemble/voting.py b/sklearn/ensemble/voting.py\nindex 7afa718..bf3cbf2 100644\n--- a/sklearn/ensemble/voting.py\n+++ b/sklearn/ensemble/voting.py\n@@ -14,6 +14,7 @@ This module contains:\n # License: BSD 3 clause\n \n import numpy as np\n+import warnings\n from abc import abstractmethod\n \n from ..base import ClassifierMixin\n@@ -29,6 +30,8 @@ from ..utils import Bunch\n \n def _parallel_fit_estimator(estimator, X, y, sample_weight=None):\n \"\"\"Private function used to fit an estimator within a job.\"\"\"\n+ if estimator is None:\n+ return None\n if sample_weight is not None:\n estimator.fit(X, y, sample_weight=sample_weight)\n else:\n@@ -41,6 +44,8 @@ class _BaseVoting(_BaseComposition, TransformerMixin):\n \n Warning: This class should not be used directly. Use derived classes\n instead.\n+\n+ Note: None estimators are allowed and will be ignored during fitting.\n \"\"\"\n _required_parameters = ['estimators']\n \n@@ -78,7 +83,7 @@ class _BaseVoting(_BaseComposition, TransformerMixin):\n \n if sample_weight is not None:\n for name, step in self.estimators:\n- if not has_fit_parameter(step, 'sample_weight'):\n+ if step is not None and not has_fit_parameter(step, 'sample_weight'):\n raise ValueError('Underlying estimator \\'%s\\' does not'\n ' support sample weights.' % name)\n \n@@ -90,14 +95,23 @@ class _BaseVoting(_BaseComposition, TransformerMixin):\n raise ValueError('All estimators are None. At least one is '\n 'required!')\n \n+ valid_estimators = [(name, clf) for name, clf in self.estimators if clf is not None]\n+ if not valid_estimators:\n+ raise ValueError('All estimators are None. At least one is required!')\n+\n self.estimators_ = Parallel(n_jobs=self.n_jobs)(\n- delayed(_parallel_fit_estimator)(clone(clf), X, y,\n- sample_weight=sample_weight)\n- for clf in clfs if clf is not None)\n+ delayed(_parallel_fit_estimator)(clone(clf), X, y, sample_weight=sample_weight)\n+ for _, clf in valid_estimators\n+ )\n \n self.named_estimators_ = Bunch()\n- for k, e in zip(self.estimators, self.estimators_):\n- self.named_estimators_[k[0]] = e\n+ est_index = 0\n+ for name, _ in self.estimators:\n+ if _ is not None:\n+ self.named_estimators_[name] = self.estimators_[est_index]\n+ est_index += 1\n+ else:\n+ self.named_estimators_[name] = None\n return self\n \n def set_params(self, **params):\n", + "test_patch": "diff --git a/sklearn/ensemble/tests/test_voting_classifier_none_estimator.py b/sklearn/ensemble/tests/test_voting_classifier_none_estimator.py\nnew file mode 100644\nindex 0000000..b9c4e9f\n--- /dev/null\n+++ b/sklearn/ensemble/tests/test_voting_classifier_none_estimator.py\n@@ -0,0 +1,28 @@\n+import numpy as np\n+import pytest\n+from sklearn.datasets import load_iris\n+from sklearn.ensemble import VotingClassifier\n+from sklearn.linear_model import LogisticRegression\n+from sklearn.ensemble import RandomForestClassifier\n+\n+def test_voting_classifier_none_estimator_with_sample_weight():\n+ \"\"\"\n+ Test that VotingClassifier raises an AttributeError when an estimator\n+ is set to None and sample_weight is provided during fit.\n+ \"\"\"\n+ X, y = load_iris(return_X_y=True)\n+ \n+ voter = VotingClassifier(\n+ estimators=[('lr', LogisticRegression()),\n+ ('rf', RandomForestClassifier())]\n+ )\n+ \n+ # Initial fit should work\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ \n+ # Set 'lr' estimator to None\n+ voter.set_params(lr=None)\n+ \n+ # Attempting to fit again with sample_weight should raise an AttributeError\n+ with pytest.raises(AttributeError, match=\"'NoneType' object has no attribute 'fit'\"):\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sklearn/ensemble/tests/test_voting_classifier_none_estimator_inverted.py b/sklearn/ensemble/tests/test_voting_classifier_none_estimator_inverted.py\nnew file mode 100644\nindex 0000000..12aaa28\n--- /dev/null\n+++ b/sklearn/ensemble/tests/test_voting_classifier_none_estimator_inverted.py\n@@ -0,0 +1,36 @@\n+import numpy as np\n+import pytest\n+from sklearn.datasets import load_iris\n+from sklearn.ensemble import VotingClassifier\n+from sklearn.linear_model import LogisticRegression\n+from sklearn.ensemble import RandomForestClassifier\n+\n+def test_voting_classifier_none_estimator_with_sample_weight():\n+ \"\"\"\n+ Test that VotingClassifier handles None estimator correctly when\n+ sample_weight is provided during fit.\n+ \"\"\"\n+ X, y = load_iris(return_X_y=True)\n+ \n+ voter = VotingClassifier(\n+ estimators=[('lr', LogisticRegression()),\n+ ('rf', RandomForestClassifier())]\n+ )\n+ \n+ # Initial fit should work\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ \n+ # Set 'lr' estimator to None\n+ voter.set_params(lr=None)\n+ \n+ # Attempting to fit again with sample_weight should not raise an AttributeError\n+ try:\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ except AttributeError as e:\n+ if str(e) == \"'NoneType' object has no attribute 'fit'\":\n+ pytest.fail(\"__BUG__HERE__\")\n+ else:\n+ raise e\n+ \n+ # If we reach this point without raising an exception, the test should fail\n+ pytest.fail(\"__BUG__HERE__\")\n\\ No newline at end of file\n", + "num_sent_chars": 2155869, + "num_received_chars": 164398, + "elapsed_time": 996.6964609622955, + "lint_repair_count": 11, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": true, + "pass_to_fail": true, + "fail_to_pass": false, + "code_patch_score": 2, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10950797630/code_patches/sympy__sympy-19040.json b/data/solve_code_runs/run_id/10950797630/code_patches/sympy__sympy-19040.json new file mode 100644 index 00000000..400e5512 --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/code_patches/sympy__sympy-19040.json @@ -0,0 +1,20 @@ +{ + "instance_id": "sympy__sympy-19040", + "edit_test_file": "sympy/polys/tests/test_factortools.py", + "code_patch": null, + "test_patch": "diff --git a/sympy/polys/tests/test_factor_extension.py b/sympy/polys/tests/test_factor_extension.py\nnew file mode 100644\nindex 0000000..b6dea88\n--- /dev/null\n+++ b/sympy/polys/tests/test_factor_extension.py\n@@ -0,0 +1,13 @@\n+from sympy import expand, factor, symbols, I\n+\n+def test_factor_extension_drops_factor():\n+ x, y = symbols('x y')\n+ z = expand((x-1)*(y-1))\n+ \n+ # Test that normal factorization works correctly\n+ assert factor(z) == (x - 1)*(y - 1)\n+ \n+ # Test that factorization with extension drops the (y-1) factor\n+ result = factor(z, extension=[I])\n+ assert result == x - 1\n+ assert result != (x - 1)*(y - 1)\n\\ No newline at end of file\n", + "test_inverted_patch": "diff --git a/sympy/polys/tests/test_factor_extension_inverted.py b/sympy/polys/tests/test_factor_extension_inverted.py\nnew file mode 100644\nindex 0000000..13c36e2\n--- /dev/null\n+++ b/sympy/polys/tests/test_factor_extension_inverted.py\n@@ -0,0 +1,16 @@\n+from sympy import expand, factor, symbols, I\n+\n+def test_factor_extension_drops_factor():\n+ x, y = symbols('x y')\n+ z = expand((x-1)*(y-1))\n+ \n+ # Test that normal factorization works correctly\n+ assert factor(z) == (x - 1)*(y - 1)\n+ \n+ # Test that factorization with extension does not drop the (y-1) factor\n+ result = factor(z, extension=[I])\n+ \n+ if result == x - 1:\n+ raise AssertionError(\"__BUG__HERE__\")\n+ \n+ assert result == (x - 1)*(y - 1), f\"Expected (x - 1)*(y - 1), but got {result}\"\n\\ No newline at end of file\n", + "num_sent_chars": 3646208, + "num_received_chars": 116412, + "elapsed_time": 958.2132794857025, + "lint_repair_count": 18, + "test_generation_attempts": 1, + "code_generation_attempts": 9, + "pass_to_pass": false, + "pass_to_fail": false, + "fail_to_pass": false, + "code_patch_score": null, + "appmap_data_test_status": null, + "appmap_data_file_count": null, + "appmap_data_context_size": null +} \ No newline at end of file diff --git a/data/solve_code_runs/run_id/10950797630/predictions-0.zip b/data/solve_code_runs/run_id/10950797630/predictions-0.zip new file mode 100644 index 00000000..e32f55da --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/predictions-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd5a729ca4283b9be305fe9620daac5c278d4a9be766e257523e15e991a6cca3 +size 52177 diff --git a/data/solve_code_runs/run_id/10950797630/report.zip b/data/solve_code_runs/run_id/10950797630/report.zip new file mode 100644 index 00000000..42c6e49b --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/report.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0a6c36f87c72fd6a4253e33b0316098e79772fefef634f9b633857607fb532a +size 1201 diff --git a/data/solve_code_runs/run_id/10950797630/run_evaluation-0.zip b/data/solve_code_runs/run_id/10950797630/run_evaluation-0.zip new file mode 100644 index 00000000..f648daeb --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/run_evaluation-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00dcf1a75148fb2a6b5cf611a441bdb131f8e4fa0188784be0d563b8a142c1c9 +size 64216 diff --git a/data/solve_code_runs/run_id/10950797630/solutions.zip b/data/solve_code_runs/run_id/10950797630/solutions.zip new file mode 100644 index 00000000..2dfe36d5 --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/solutions.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c5a4ed6dac150ca24659b99663d2f2ec8b57e2d6a9917e46f2de93a1beb0d8f +size 8046 diff --git a/data/solve_code_runs/run_id/10950797630/solve-0.zip b/data/solve_code_runs/run_id/10950797630/solve-0.zip new file mode 100644 index 00000000..b371aaf9 --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/solve-0.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebd1b3b74e02a44b215369ec3084243bc12d36edd1a0fa564936671ed52369a0 +size 10991686 diff --git a/data/solve_code_runs/run_id/10950797630/test-patch.zip b/data/solve_code_runs/run_id/10950797630/test-patch.zip new file mode 100644 index 00000000..d5a5da86 --- /dev/null +++ b/data/solve_code_runs/run_id/10950797630/test-patch.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14e8abd06b2bcabe5f8e95bdeca8e2eafe33a43325050d23ad0f7dd6e9b09b36 +size 4627 From a4d41052ac322d30dd122ae3a8d127fa3eb345a7 Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Thu, 19 Sep 2024 22:36:35 -0400 Subject: [PATCH 8/9] fix: Fix access to None content --- .github/workflows/solve.yml | 10 ++++++++-- submodules/navie-editor | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/solve.yml b/.github/workflows/solve.yml index 3924c08f..0cbe8efa 100644 --- a/.github/workflows/solve.yml +++ b/.github/workflows/solve.yml @@ -21,13 +21,19 @@ on: type: choice required: true options: - # Code solvers building synthetic tests - test_files=2 test_status_retry=2 code_files=2 code_status_retry=2 - test_files=3 test_status_retry=3 code_files=3 code_status_retry=3 + - test_files=4 test_status_retry=3 code_files=3 code_status_retry=3 + - test_files=5 test_status_retry=3 code_files=3 code_status_retry=3 + default: "test_files=3 test_status_retry=3 code_files=3 code_status_retry=3" context_tokens: description: "LLM token limit to apply to the solver" - type: string + type: choice required: false + options: + - "8000" + - "16000" + - "32000" default: "16000" use_synthetic_tests: description: "Use synthetic tests" diff --git a/submodules/navie-editor b/submodules/navie-editor index 8aafa20c..57c2018a 160000 --- a/submodules/navie-editor +++ b/submodules/navie-editor @@ -1 +1 @@ -Subproject commit 8aafa20c5ebbe829e27004d242b6aab2a06bac3b +Subproject commit 57c2018a3964935fb81abbb9aed60acf32c1ee75 From 945980699148154805939b6f8ce75ebd517e02a9 Mon Sep 17 00:00:00 2001 From: Kevin Gilpin Date: Fri, 20 Sep 2024 08:43:45 -0400 Subject: [PATCH 9/9] feat: More limits options --- .github/workflows/solve.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/solve.yml b/.github/workflows/solve.yml index 0cbe8efa..b4cc0f3d 100644 --- a/.github/workflows/solve.yml +++ b/.github/workflows/solve.yml @@ -23,8 +23,10 @@ on: options: - test_files=2 test_status_retry=2 code_files=2 code_status_retry=2 - test_files=3 test_status_retry=3 code_files=3 code_status_retry=3 - - test_files=4 test_status_retry=3 code_files=3 code_status_retry=3 - - test_files=5 test_status_retry=3 code_files=3 code_status_retry=3 + - test_files=4 test_status_retry=3 code_files=4 code_status_retry=3 + - test_files=4 test_status_retry=4 code_files=4 code_status_retry=4 + - test_files=5 test_status_retry=3 code_files=5 code_status_retry=3 + - test_files=5 test_status_retry=5 code_files=5 code_status_retry=5 default: "test_files=3 test_status_retry=3 code_files=3 code_status_retry=3" context_tokens: description: "LLM token limit to apply to the solver" @@ -34,6 +36,7 @@ on: - "8000" - "16000" - "32000" + - "64000" default: "16000" use_synthetic_tests: description: "Use synthetic tests"