diff --git a/predictions_10358372977.jsonl b/predictions_10358372977.jsonl new file mode 100644 index 0000000..812a318 --- /dev/null +++ b/predictions_10358372977.jsonl @@ -0,0 +1,70 @@ +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-13971", "base_commit": "84c125972ad535b2dfb245f8d311d347b45e5b8a", "patch": "diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py\n--- a/sympy/printing/latex.py\n+++ b/sympy/printing/latex.py\n@@ -1657,9 +1657,9 @@ def _print_SeqFormula(self, s):\n else:\n printset = tuple(s)\n \n- return (r\"\\left\\[\"\n+ return (r\"\\left[\"\n + r\", \".join(self._print(el) for el in printset)\n- + r\"\\right\\]\")\n+ + r\"\\right]\")\n \n _print_SeqPer = _print_SeqFormula\n _print_SeqAdd = _print_SeqFormula\n", "test_patch": "diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py\n--- a/sympy/printing/tests/test_latex.py\n+++ b/sympy/printing/tests/test_latex.py\n@@ -614,46 +614,46 @@ def test_latex_sequences():\n s1 = SeqFormula(a**2, (0, oo))\n s2 = SeqPer((1, 2))\n \n- latex_str = r'\\left\\[0, 1, 4, 9, \\ldots\\right\\]'\n+ latex_str = r'\\left[0, 1, 4, 9, \\ldots\\right]'\n assert latex(s1) == latex_str\n \n- latex_str = r'\\left\\[1, 2, 1, 2, \\ldots\\right\\]'\n+ latex_str = r'\\left[1, 2, 1, 2, \\ldots\\right]'\n assert latex(s2) == latex_str\n \n s3 = SeqFormula(a**2, (0, 2))\n s4 = SeqPer((1, 2), (0, 2))\n \n- latex_str = r'\\left\\[0, 1, 4\\right\\]'\n+ latex_str = r'\\left[0, 1, 4\\right]'\n assert latex(s3) == latex_str\n \n- latex_str = r'\\left\\[1, 2, 1\\right\\]'\n+ latex_str = r'\\left[1, 2, 1\\right]'\n assert latex(s4) == latex_str\n \n s5 = SeqFormula(a**2, (-oo, 0))\n s6 = SeqPer((1, 2), (-oo, 0))\n \n- latex_str = r'\\left\\[\\ldots, 9, 4, 1, 0\\right\\]'\n+ latex_str = r'\\left[\\ldots, 9, 4, 1, 0\\right]'\n assert latex(s5) == latex_str\n \n- latex_str = r'\\left\\[\\ldots, 2, 1, 2, 1\\right\\]'\n+ latex_str = r'\\left[\\ldots, 2, 1, 2, 1\\right]'\n assert latex(s6) == latex_str\n \n- latex_str = r'\\left\\[1, 3, 5, 11, \\ldots\\right\\]'\n+ latex_str = r'\\left[1, 3, 5, 11, \\ldots\\right]'\n assert latex(SeqAdd(s1, s2)) == latex_str\n \n- latex_str = r'\\left\\[1, 3, 5\\right\\]'\n+ latex_str = r'\\left[1, 3, 5\\right]'\n assert latex(SeqAdd(s3, s4)) == latex_str\n \n- latex_str = r'\\left\\[\\ldots, 11, 5, 3, 1\\right\\]'\n+ latex_str = r'\\left[\\ldots, 11, 5, 3, 1\\right]'\n assert latex(SeqAdd(s5, s6)) == latex_str\n \n- latex_str = r'\\left\\[0, 2, 4, 18, \\ldots\\right\\]'\n+ latex_str = r'\\left[0, 2, 4, 18, \\ldots\\right]'\n assert latex(SeqMul(s1, s2)) == latex_str\n \n- latex_str = r'\\left\\[0, 2, 4\\right\\]'\n+ latex_str = r'\\left[0, 2, 4\\right]'\n assert latex(SeqMul(s3, s4)) == latex_str\n \n- latex_str = r'\\left\\[\\ldots, 18, 4, 2, 0\\right\\]'\n+ latex_str = r'\\left[\\ldots, 18, 4, 2, 0\\right]'\n assert latex(SeqMul(s5, s6)) == latex_str\n \n \n", "problem_statement": "Display of SeqFormula()\n```\r\nimport sympy as sp\r\nk, m, n = sp.symbols('k m n', integer=True)\r\nsp.init_printing()\r\n\r\nsp.SeqFormula(n**2, (n,0,sp.oo))\r\n```\r\n\r\nThe Jupyter rendering of this command backslash-escapes the brackets producing:\r\n\r\n`\\left\\[0, 1, 4, 9, \\ldots\\right\\]`\r\n\r\nCopying this output to a markdown cell this does not render properly. Whereas:\r\n\r\n`[0, 1, 4, 9, \\ldots ]`\r\n\r\ndoes render just fine. \r\n\r\nSo - sequence output should not backslash-escape square brackets, or, `\\]` should instead render?\n", "hints_text": "", "created_at": "2018-01-20T10:03:44Z", "version": "1.1", "FAIL_TO_PASS": "[\"test_latex_sequences\"]", "PASS_TO_PASS": "[\"test_printmethod\", \"test_latex_basic\", \"test_latex_builtins\", \"test_latex_SingularityFunction\", \"test_latex_cycle\", \"test_latex_permutation\", \"test_latex_Float\", \"test_latex_vector_expressions\", \"test_latex_symbols\", \"test_latex_functions\", \"test_hyper_printing\", \"test_latex_bessel\", \"test_latex_fresnel\", \"test_latex_brackets\", \"test_latex_subs\", \"test_latex_integrals\", \"test_latex_sets\", \"test_latex_Range\", \"test_latex_intervals\", \"test_latex_AccumuBounds\", \"test_latex_emptyset\", \"test_latex_commutator\", \"test_latex_union\", \"test_latex_symmetric_difference\", \"test_latex_Complement\", \"test_latex_Complexes\", \"test_latex_productset\", \"test_latex_Naturals\", \"test_latex_Naturals0\", \"test_latex_Integers\", \"test_latex_ImageSet\", \"test_latex_ConditionSet\", \"test_latex_ComplexRegion\", \"test_latex_Contains\", \"test_latex_sum\", \"test_latex_product\", \"test_latex_limits\", \"test_issue_3568\", \"test_latex\", \"test_latex_dict\", \"test_latex_list\", \"test_latex_rational\", \"test_latex_inverse\", \"test_latex_DiracDelta\", \"test_latex_Heaviside\", \"test_latex_KroneckerDelta\", \"test_latex_LeviCivita\", \"test_mode\", \"test_latex_Piecewise\", \"test_latex_Matrix\", \"test_latex_mul_symbol\", \"test_latex_issue_4381\", \"test_latex_issue_4576\", \"test_latex_pow_fraction\", \"test_noncommutative\", \"test_latex_order\", \"test_latex_Lambda\", \"test_latex_PolyElement\", \"test_latex_FracElement\", \"test_latex_Poly\", \"test_latex_ComplexRootOf\", \"test_latex_RootSum\", \"test_settings\", \"test_latex_numbers\", \"test_latex_euler\", \"test_lamda\", \"test_custom_symbol_names\", \"test_matAdd\", \"test_matMul\", \"test_latex_MatrixSlice\", \"test_latex_RandomDomain\", \"test_PrettyPoly\", \"test_integral_transforms\", \"test_categories\", \"test_Modules\", \"test_QuotientRing\", \"test_Tr\", \"test_Adjoint\", \"test_Hadamard\", \"test_ZeroMatrix\", \"test_boolean_args_order\", \"test_imaginary\", \"test_builtins_without_args\", \"test_latex_greek_functions\", \"test_translate\", \"test_other_symbols\", \"test_modifiers\", \"test_greek_symbols\", \"test_builtin_no_args\", \"test_issue_6853\", \"test_Mul\", \"test_Pow\", \"test_issue_7180\", \"test_issue_8409\", \"test_issue_7117\", \"test_issue_2934\", \"test_issue_10489\", \"test_issue_12886\", \"test_issue_13651\", \"test_latex_UnevaluatedExpr\", \"test_MatrixElement_printing\", \"test_Quaternion_latex_printing\"]", "environment_setup_commit": "ec9e3c0436fbff934fa84e22bf07f1b3ef5bfac3", "test_directives": ["sympy/printing/tests/test_latex.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/printing/tests/test_latex.py", "model_name_or_path": "navie", "model_patch": null} +{"repo": "django/django", "instance_id": "django__django-11001", "base_commit": "ef082ebb84f00e38af4e8880d04e8365c2766d34", "patch": "diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py\n--- a/django/db/models/sql/compiler.py\n+++ b/django/db/models/sql/compiler.py\n@@ -32,7 +32,8 @@ def __init__(self, query, connection, using):\n self.select = None\n self.annotation_col_map = None\n self.klass_info = None\n- self.ordering_parts = re.compile(r'(.*)\\s(ASC|DESC)(.*)')\n+ # Multiline ordering SQL clause may appear from RawSQL.\n+ self.ordering_parts = re.compile(r'^(.*)\\s(ASC|DESC)(.*)', re.MULTILINE | re.DOTALL)\n self._meta_ordering = None\n \n def setup_query(self):\n", "test_patch": "diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py\n--- a/tests/expressions/tests.py\n+++ b/tests/expressions/tests.py\n@@ -384,6 +384,29 @@ def test_order_by_exists(self):\n )\n self.assertSequenceEqual(mustermanns_by_seniority, [self.max, mary])\n \n+ def test_order_by_multiline_sql(self):\n+ raw_order_by = (\n+ RawSQL('''\n+ CASE WHEN num_employees > 1000\n+ THEN num_chairs\n+ ELSE 0 END\n+ ''', []).desc(),\n+ RawSQL('''\n+ CASE WHEN num_chairs > 1\n+ THEN 1\n+ ELSE 0 END\n+ ''', []).asc()\n+ )\n+ for qs in (\n+ Company.objects.all(),\n+ Company.objects.distinct(),\n+ ):\n+ with self.subTest(qs=qs):\n+ self.assertSequenceEqual(\n+ qs.order_by(*raw_order_by),\n+ [self.example_inc, self.gmbh, self.foobar_ltd],\n+ )\n+\n def test_outerref(self):\n inner = Company.objects.filter(point_of_contact=OuterRef('pk'))\n msg = (\n", "problem_statement": "Incorrect removal of order_by clause created as multiline RawSQL\nDescription\n\t\nHi.\nThe SQLCompiler is ripping off one of my \"order by\" clause, because he \"thinks\" the clause was already \"seen\" (in SQLCompiler.get_order_by()). I'm using expressions written as multiline RawSQLs, which are similar but not the same. \nThe bug is located in SQLCompiler.get_order_by(), somewhere around line computing part of SQL query without ordering:\nwithout_ordering = self.ordering_parts.search(sql).group(1)\nThe sql variable contains multiline sql. As a result, the self.ordering_parts regular expression is returning just a line containing ASC or DESC words. This line is added to seen set, and because my raw queries have identical last lines, only the first clasue is returing from SQLCompiler.get_order_by().\nAs a quick/temporal fix I can suggest making sql variable clean of newline characters, like this:\nsql_oneline = ' '.join(sql.split('\\n'))\nwithout_ordering = self.ordering_parts.search(sql_oneline).group(1)\nNote: beware of unicode (Py2.x u'') and EOL dragons (\\r).\nExample of my query:\n\treturn MyModel.objects.all().order_by(\n\t\tRawSQL('''\n\t\t\tcase when status in ('accepted', 'verification')\n\t\t\t\t then 2 else 1 end''', []).desc(),\n\t\tRawSQL('''\n\t\t\tcase when status in ('accepted', 'verification')\n\t\t\t\t then (accepted_datetime, preferred_datetime)\n\t\t\t\t else null end''', []).asc(),\n\t\tRawSQL('''\n\t\t\tcase when status not in ('accepted', 'verification')\n\t\t\t\t then (accepted_datetime, preferred_datetime, created_at)\n\t\t\t\t else null end''', []).desc())\nThe ordering_parts.search is returing accordingly:\n'\t\t\t\t then 2 else 1 end)'\n'\t\t\t\t else null end'\n'\t\t\t\t else null end'\nSecond RawSQL with a\t\t\t\t else null end part is removed from query.\nThe fun thing is that the issue can be solved by workaround by adding a space or any other char to the last line. \nSo in case of RawSQL I can just say, that current implementation of avoiding duplicates in order by clause works only for special/rare cases (or does not work in all cases). \nThe bug filed here is about wrong identification of duplicates (because it compares only last line of SQL passed to order by clause).\nHope my notes will help you fixing the issue. Sorry for my english.\n", "hints_text": "Is there a reason you can't use \u200bconditional expressions, e.g. something like: MyModel.objects.annotate( custom_order=Case( When(...), ) ).order_by('custom_order') I'm thinking that would avoid fiddly ordering_parts regular expression. If there's some shortcoming to that approach, it might be easier to address that. Allowing the ordering optimization stuff to handle arbitrary RawSQL may be difficult.\nIs there a reason you can't use \u200bconditional expressions No, but I didn't knew about the issue, and writing raw sqls is sometimes faster (not in this case ;) I'm really happy having possibility to mix raw sqls with object queries. Next time I'll use expressions, for sure. Allowing the ordering optimization stuff to handle arbitrary RawSQL may be difficult. Personally I'd like to skip RawSQL clauses in the block which is responsible for finding duplicates. If someone is using raw sqls, he knows the best what he is doing, IMO. And it is quite strange if Django removes silently part of your SQL. This is very confusing. And please note that printing a Query instance was generating incomplete sql, but while checking Query.order_by manually, the return value was containing all clauses. I thought that just printing was affected, but our QA dept told me the truth ;) I know there is no effective way to compare similarity of two raw clauses. This may be hard for expression objects, too, but you have a possibility to implement some __eq__ magic (instead of comparation of generated sqls). Unfortunately I don't know why duplicates detection was implemented, so it's hard to tell how to improve this part.\nPatches welcome, I suppose.\n\u200bPR\nIs there a reason why you didn't add tests?\nI was waiting for confirmation, I've added a test. Is it enough?\nSome additional test coverage needed.", "created_at": "2019-02-17T13:02:09Z", "version": "3.0", "FAIL_TO_PASS": "[\"test_order_by_multiline_sql (expressions.tests.BasicExpressionsTests)\", \"test_order_of_operations (expressions.tests.BasicExpressionsTests)\"]", "PASS_TO_PASS": "[\"test_deconstruct (expressions.tests.FTests)\", \"test_deepcopy (expressions.tests.FTests)\", \"test_equal (expressions.tests.FTests)\", \"test_hash (expressions.tests.FTests)\", \"test_not_equal_Value (expressions.tests.FTests)\", \"test_and (expressions.tests.CombinableTests)\", \"test_negation (expressions.tests.CombinableTests)\", \"test_or (expressions.tests.CombinableTests)\", \"test_reversed_and (expressions.tests.CombinableTests)\", \"test_reversed_or (expressions.tests.CombinableTests)\", \"test_aggregates (expressions.tests.ReprTests)\", \"test_distinct_aggregates (expressions.tests.ReprTests)\", \"test_expressions (expressions.tests.ReprTests)\", \"test_filtered_aggregates (expressions.tests.ReprTests)\", \"test_functions (expressions.tests.ReprTests)\", \"test_equal (expressions.tests.SimpleExpressionTests)\", \"test_hash (expressions.tests.SimpleExpressionTests)\", \"test_month_aggregation (expressions.tests.FieldTransformTests)\", \"test_multiple_transforms_in_values (expressions.tests.FieldTransformTests)\", \"test_transform_in_values (expressions.tests.FieldTransformTests)\", \"test_deconstruct (expressions.tests.ValueTests)\", \"test_deconstruct_output_field (expressions.tests.ValueTests)\", \"test_equal (expressions.tests.ValueTests)\", \"test_equal_output_field (expressions.tests.ValueTests)\", \"test_hash (expressions.tests.ValueTests)\", \"test_raise_empty_expressionlist (expressions.tests.ValueTests)\", \"test_update_TimeField_using_Value (expressions.tests.ValueTests)\", \"test_update_UUIDField_using_Value (expressions.tests.ValueTests)\", \"test_complex_expressions (expressions.tests.ExpressionsNumericTests)\", \"test_fill_with_value_from_same_object (expressions.tests.ExpressionsNumericTests)\", \"test_filter_not_equals_other_field (expressions.tests.ExpressionsNumericTests)\", \"test_increment_value (expressions.tests.ExpressionsNumericTests)\", \"test_F_reuse (expressions.tests.ExpressionsTests)\", \"test_insensitive_patterns_escape (expressions.tests.ExpressionsTests)\", \"test_patterns_escape (expressions.tests.ExpressionsTests)\", \"test_complex_expressions_do_not_introduce_sql_injection_via_untrusted_string_inclusion (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_expressions_in_lookups_join_choice (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_in_lookup_allows_F_expressions_and_expressions_for_datetimes (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_in_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_range_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_lefthand_addition (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_and (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_left_shift_operator (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_or (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_right_shift_operator (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_division (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_modulo (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_multiplication (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_power (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_subtraction (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_addition (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_division (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_modulo (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_multiplication (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_subtraction (expressions.tests.ExpressionOperatorTests)\", \"test_righthand_power (expressions.tests.ExpressionOperatorTests)\", \"test_aggregate_subquery_annotation (expressions.tests.BasicExpressionsTests)\", \"test_annotate_values_aggregate (expressions.tests.BasicExpressionsTests)\", \"test_annotate_values_count (expressions.tests.BasicExpressionsTests)\", \"test_annotate_values_filter (expressions.tests.BasicExpressionsTests)\", \"test_annotation_with_outerref (expressions.tests.BasicExpressionsTests)\", \"test_annotations_within_subquery (expressions.tests.BasicExpressionsTests)\", \"test_arithmetic (expressions.tests.BasicExpressionsTests)\", \"test_exist_single_field_output_field (expressions.tests.BasicExpressionsTests)\", \"test_explicit_output_field (expressions.tests.BasicExpressionsTests)\", \"test_filter_inter_attribute (expressions.tests.BasicExpressionsTests)\", \"test_filter_with_join (expressions.tests.BasicExpressionsTests)\", \"test_filtering_on_annotate_that_uses_q (expressions.tests.BasicExpressionsTests)\", \"test_in_subquery (expressions.tests.BasicExpressionsTests)\", \"test_incorrect_field_in_F_expression (expressions.tests.BasicExpressionsTests)\", \"test_incorrect_joined_field_in_F_expression (expressions.tests.BasicExpressionsTests)\", \"test_nested_subquery (expressions.tests.BasicExpressionsTests)\", \"test_nested_subquery_outer_ref_2 (expressions.tests.BasicExpressionsTests)\", \"test_nested_subquery_outer_ref_with_autofield (expressions.tests.BasicExpressionsTests)\", \"test_new_object_create (expressions.tests.BasicExpressionsTests)\", \"test_new_object_save (expressions.tests.BasicExpressionsTests)\", \"test_object_create_with_aggregate (expressions.tests.BasicExpressionsTests)\", \"test_object_update (expressions.tests.BasicExpressionsTests)\", \"test_object_update_fk (expressions.tests.BasicExpressionsTests)\", \"test_object_update_unsaved_objects (expressions.tests.BasicExpressionsTests)\", \"test_order_by_exists (expressions.tests.BasicExpressionsTests)\", \"test_outerref (expressions.tests.BasicExpressionsTests)\", \"test_outerref_mixed_case_table_name (expressions.tests.BasicExpressionsTests)\", \"test_outerref_with_operator (expressions.tests.BasicExpressionsTests)\", \"test_parenthesis_priority (expressions.tests.BasicExpressionsTests)\", \"test_pickle_expression (expressions.tests.BasicExpressionsTests)\", \"test_subquery (expressions.tests.BasicExpressionsTests)\", \"test_subquery_filter_by_aggregate (expressions.tests.BasicExpressionsTests)\", \"test_subquery_references_joined_table_twice (expressions.tests.BasicExpressionsTests)\", \"test_ticket_11722_iexact_lookup (expressions.tests.BasicExpressionsTests)\", \"test_ticket_16731_startswith_lookup (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_chained_filters (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_join_reuse (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_kwarg_ordering (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_kwarg_ordering_2 (expressions.tests.BasicExpressionsTests)\", \"test_update (expressions.tests.BasicExpressionsTests)\", \"test_update_inherited_field_value (expressions.tests.BasicExpressionsTests)\", \"test_update_with_fk (expressions.tests.BasicExpressionsTests)\", \"test_update_with_none (expressions.tests.BasicExpressionsTests)\", \"test_uuid_pk_subquery (expressions.tests.BasicExpressionsTests)\", \"test_date_comparison (expressions.tests.FTimeDeltaTests)\", \"test_date_minus_duration (expressions.tests.FTimeDeltaTests)\", \"test_date_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_datetime_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_datetime_subtraction_microseconds (expressions.tests.FTimeDeltaTests)\", \"test_delta_add (expressions.tests.FTimeDeltaTests)\", \"test_delta_subtract (expressions.tests.FTimeDeltaTests)\", \"test_delta_update (expressions.tests.FTimeDeltaTests)\", \"test_duration_with_datetime (expressions.tests.FTimeDeltaTests)\", \"test_duration_with_datetime_microseconds (expressions.tests.FTimeDeltaTests)\", \"test_durationfield_add (expressions.tests.FTimeDeltaTests)\", \"test_exclude (expressions.tests.FTimeDeltaTests)\", \"test_invalid_operator (expressions.tests.FTimeDeltaTests)\", \"test_mixed_comparisons2 (expressions.tests.FTimeDeltaTests)\", \"test_multiple_query_compilation (expressions.tests.FTimeDeltaTests)\", \"test_negative_timedelta_update (expressions.tests.FTimeDeltaTests)\", \"test_query_clone (expressions.tests.FTimeDeltaTests)\", \"test_time_subtraction (expressions.tests.FTimeDeltaTests)\"]", "environment_setup_commit": "419a78300f7cd27611196e1e464d50fd0385ff27", "test_directives": ["expressions.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 expressions.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/ordering/tests.py b/tests/ordering/tests.py\nindex 16e5cc9b2d..b7cfc02323 100644\n--- a/tests/ordering/tests.py\n+++ b/tests/ordering/tests.py\n@@ -21,6 +21,26 @@ class OrderingTests(TestCase):\n cls.author_2 = Author.objects.create(name=\"Name 2\")\n for i in range(2):\n Author.objects.create()\n+ cls.a1.status = 'accepted'\n+ cls.a1.accepted_datetime = datetime(2005, 7, 26, 12, 0)\n+ cls.a1.preferred_datetime = datetime(2005, 7, 26, 14, 0)\n+ cls.a1.created_at = datetime(2005, 7, 26, 10, 0)\n+ cls.a1.save()\n+ cls.a2.status = 'verification'\n+ cls.a2.accepted_datetime = datetime(2005, 7, 27, 12, 0)\n+ cls.a2.preferred_datetime = datetime(2005, 7, 27, 14, 0)\n+ cls.a2.created_at = datetime(2005, 7, 27, 10, 0)\n+ cls.a2.save()\n+ cls.a3.status = 'other'\n+ cls.a3.accepted_datetime = datetime(2005, 7, 27, 12, 0)\n+ cls.a3.preferred_datetime = datetime(2005, 7, 27, 14, 0)\n+ cls.a3.created_at = datetime(2005, 7, 27, 10, 0)\n+ cls.a3.save()\n+ cls.a4.status = 'other'\n+ cls.a4.accepted_datetime = datetime(2005, 7, 28, 12, 0)\n+ cls.a4.preferred_datetime = datetime(2005, 7, 28, 14, 0)\n+ cls.a4.created_at = datetime(2005, 7, 28, 10, 0)\n+ cls.a4.save()\n \n def test_default_ordering(self):\n \"\"\"\n@@ -412,3 +432,33 @@ class OrderingTests(TestCase):\n )\n with self.assertRaisesMessage(RemovedInDjango31Warning, msg):\n list(Article.objects.values('author').annotate(Count('headline')))\n+\n+ def test_multiline_rawsql_ordering(self):\n+ \"\"\"\n+ Test that multiline RawSQL expressions in order_by clauses are not incorrectly removed.\n+ \"\"\"\n+ from django.db.models.expressions import RawSQL\n+\n+ queryset = Article.objects.all().order_by(\n+ RawSQL('''\n+ case when status in ('accepted', 'verification')\n+ then 2 else 1 end''', []).desc(),\n+ RawSQL('''\n+ case when status in ('accepted', 'verification')\n+ then (accepted_datetime, preferred_datetime)\n+ else null end''', []).asc(),\n+ RawSQL('''\n+ case when status not in ('accepted', 'verification')\n+ then (accepted_datetime, preferred_datetime, created_at)\n+ else null end''', []).desc()\n+ )\n+\n+ self.assertQuerysetEqual(\n+ queryset, [\n+ \"Article 2\",\n+ \"Article 1\",\n+ \"Article 4\",\n+ \"Article 3\",\n+ ],\n+ attrgetter(\"headline\")\n+ )\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["ordering.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py\nindex 16df317631..41bafc5d76 100644\n--- a/django/db/models/expressions.py\n+++ b/django/db/models/expressions.py\n@@ -1076,6 +1076,13 @@ class OrderBy(BaseExpression):\n return \"{}({}, descending={})\".format(\n self.__class__.__name__, self.expression, self.descending)\n \n+ def normalize_sql(self, sql):\n+ \"\"\"\n+ Normalize the SQL string by removing newline characters and handling\n+ unicode and EOL characters.\n+ \"\"\"\n+ return ' '.join(sql.splitlines())\n+\n def set_source_expressions(self, exprs):\n self.expression = exprs[0]\n \n", "model_lint_repair_patch": "diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py\nindex 16df317631..41bafc5d76 100644\n--- a/django/db/models/expressions.py\n+++ b/django/db/models/expressions.py\n@@ -1076,6 +1076,13 @@ class OrderBy(BaseExpression):\n return \"{}({}, descending={})\".format(\n self.__class__.__name__, self.expression, self.descending)\n \n+ def normalize_sql(self, sql):\n+ \"\"\"\n+ Normalize the SQL string by removing newline characters and handling\n+ unicode and EOL characters.\n+ \"\"\"\n+ return ' '.join(sql.splitlines())\n+\n def set_source_expressions(self, exprs):\n self.expression = exprs[0]\n \n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-13158", "base_commit": "7af8f4127397279d19ef7c7899e93018274e2f9b", "patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -305,6 +305,7 @@ def clone(self):\n obj.annotation_select_mask = None\n else:\n obj.annotation_select_mask = self.annotation_select_mask.copy()\n+ obj.combined_queries = tuple(query.clone() for query in self.combined_queries)\n # _annotation_select_cache cannot be copied, as doing so breaks the\n # (necessary) state in which both annotations and\n # _annotation_select_cache point to the same underlying objects.\n@@ -1777,6 +1778,8 @@ def split_exclude(self, filter_expr, can_reuse, names_with_path):\n \n def set_empty(self):\n self.where.add(NothingNode(), AND)\n+ for query in self.combined_queries:\n+ query.set_empty()\n \n def is_empty(self):\n return any(isinstance(c, NothingNode) for c in self.where.children)\n", "test_patch": "diff --git a/tests/queries/test_qs_combinators.py b/tests/queries/test_qs_combinators.py\n--- a/tests/queries/test_qs_combinators.py\n+++ b/tests/queries/test_qs_combinators.py\n@@ -51,6 +51,13 @@ def test_union_distinct(self):\n self.assertEqual(len(list(qs1.union(qs2, all=True))), 20)\n self.assertEqual(len(list(qs1.union(qs2))), 10)\n \n+ def test_union_none(self):\n+ qs1 = Number.objects.filter(num__lte=1)\n+ qs2 = Number.objects.filter(num__gte=8)\n+ qs3 = qs1.union(qs2)\n+ self.assertSequenceEqual(qs3.none(), [])\n+ self.assertNumbersEqual(qs3, [0, 1, 8, 9], ordered=False)\n+\n @skipUnlessDBFeature('supports_select_intersection')\n def test_intersection_with_empty_qs(self):\n qs1 = Number.objects.all()\n", "problem_statement": "QuerySet.none() on combined queries returns all results.\nDescription\n\t\nI came across this issue on Stack Overflow. I'm not 100% sure it's a bug, but it does seem strange. With this code (excuse the bizarre example filtering):\nclass Publication(models.Model):\n\tpass\nclass Article(models.Model):\n\tpublications = models.ManyToManyField(to=Publication, blank=True, null=True)\nclass ArticleForm(forms.ModelForm):\n\tpublications = forms.ModelMultipleChoiceField(\n\t\tPublication.objects.filter(id__lt=2) | Publication.objects.filter(id__gt=5),\n\t\trequired=False,\n\t)\n\tclass Meta:\n\t\tmodel = Article\n\t\tfields = [\"publications\"]\nclass ArticleAdmin(admin.ModelAdmin):\n\tform = ArticleForm\nThis works well. However, changing the ModelMultipleChoiceField queryset to use union() breaks things.\npublications = forms.ModelMultipleChoiceField(\n\tPublication.objects.filter(id__lt=2).union(\n\t\tPublication.objects.filter(id__gt=5)\n\t),\n\trequired=False,\n)\nThe form correctly shows only the matching objects. However, if you submit this form while empty (i.e. you didn't select any publications), ALL objects matching the queryset will be added. Using the OR query, NO objects are added, as I'd expect.\n", "hints_text": "Thanks for the report. QuerySet.none() doesn't work properly on combined querysets, it returns all results instead of an empty queryset.", "created_at": "2020-07-06T19:18:11Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_union_none (queries.test_qs_combinators.QuerySetSetOperationTests)\"]", "PASS_TO_PASS": "[\"test_combining_multiple_models (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_count_difference (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_count_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_count_union (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_count_union_empty_result (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_difference_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_difference_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_intersection_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_intersection_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_limits (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_order_by_same_type (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_order_raises_on_non_selected_column (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_ordering (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_ordering_by_alias (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_ordering_by_f_expression (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_ordering_by_f_expression_and_alias (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_qs_with_subcompound_qs (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_simple_difference (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_simple_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_simple_union (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_union_distinct (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_union_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_union_with_extra_and_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_union_with_two_annotated_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_union_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_union_with_values_list_and_order (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_union_with_values_list_on_annotated_and_unannotated (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_unsupported_operations_on_combined_qs (queries.test_qs_combinators.QuerySetSetOperationTests)\", \"test_unsupported_ordering_slicing_raises_db_error (queries.test_qs_combinators.QuerySetSetOperationTests)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["queries.test_qs_combinators"], "test_cmd": "./tests/runtests.py --verbosity 2 queries.test_qs_combinators", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["queries.test_qs_combinators"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/forms/fields.py b/django/forms/fields.py\nindex 36dad72704..eea24edfc9 100644\n--- a/django/forms/fields.py\n+++ b/django/forms/fields.py\n@@ -867,7 +867,7 @@ class MultipleChoiceField(ChoiceField):\n }\n \n def to_python(self, value):\n- if not value:\n+ if value in self.empty_values:\n return []\n elif not isinstance(value, (list, tuple)):\n raise ValidationError(self.error_messages['invalid_list'], code='invalid_list')\n", "model_lint_repair_patch": "diff --git a/django/forms/fields.py b/django/forms/fields.py\nindex 36dad72704..eea24edfc9 100644\n--- a/django/forms/fields.py\n+++ b/django/forms/fields.py\n@@ -867,7 +867,7 @@ class MultipleChoiceField(ChoiceField):\n }\n \n def to_python(self, value):\n- if not value:\n+ if value in self.empty_values:\n return []\n elif not isinstance(value, (list, tuple)):\n raise ValidationError(self.error_messages['invalid_list'], code='invalid_list')\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["queries.test_qs_combinators"]} +{"repo": "django/django", "instance_id": "django__django-13230", "base_commit": "184a6eebb0ef56d5f1b1315a8e666830e37f3f81", "patch": "diff --git a/django/contrib/syndication/views.py b/django/contrib/syndication/views.py\n--- a/django/contrib/syndication/views.py\n+++ b/django/contrib/syndication/views.py\n@@ -212,6 +212,7 @@ def get_feed(self, obj, request):\n author_name=author_name,\n author_email=author_email,\n author_link=author_link,\n+ comments=self._get_dynamic_attr('item_comments', item),\n categories=self._get_dynamic_attr('item_categories', item),\n item_copyright=self._get_dynamic_attr('item_copyright', item),\n **self.item_extra_kwargs(item)\n", "test_patch": "diff --git a/tests/syndication_tests/feeds.py b/tests/syndication_tests/feeds.py\n--- a/tests/syndication_tests/feeds.py\n+++ b/tests/syndication_tests/feeds.py\n@@ -29,6 +29,9 @@ def item_pubdate(self, item):\n def item_updateddate(self, item):\n return item.updated\n \n+ def item_comments(self, item):\n+ return \"%scomments\" % item.get_absolute_url()\n+\n item_author_name = 'Sally Smith'\n item_author_email = 'test@example.com'\n item_author_link = 'http://www.example.com/'\ndiff --git a/tests/syndication_tests/tests.py b/tests/syndication_tests/tests.py\n--- a/tests/syndication_tests/tests.py\n+++ b/tests/syndication_tests/tests.py\n@@ -136,10 +136,20 @@ def test_rss2_feed(self):\n 'guid': 'http://example.com/blog/1/',\n 'pubDate': pub_date,\n 'author': 'test@example.com (Sally Smith)',\n+ 'comments': '/blog/1/comments',\n })\n self.assertCategories(items[0], ['python', 'testing'])\n for item in items:\n- self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'category', 'pubDate', 'author'])\n+ self.assertChildNodes(item, [\n+ 'title',\n+ 'link',\n+ 'description',\n+ 'guid',\n+ 'category',\n+ 'pubDate',\n+ 'author',\n+ 'comments',\n+ ])\n # Assert that does not have any 'isPermaLink' attribute\n self.assertIsNone(item.getElementsByTagName(\n 'guid')[0].attributes.get('isPermaLink'))\n", "problem_statement": "Add support for item_comments to syndication framework\nDescription\n\t\nAdd comments argument to feed.add_item() in syndication.views so that item_comments can be defined directly without having to take the detour via item_extra_kwargs .\nAdditionally, comments is already explicitly mentioned in the feedparser, but not implemented in the view.\n", "hints_text": "", "created_at": "2020-07-23T14:59:50Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_rss2_feed (syndication_tests.tests.SyndicationFeedTest)\"]", "PASS_TO_PASS": "[\"test_add_domain (syndication_tests.tests.SyndicationFeedTest)\", \"test_atom_feed (syndication_tests.tests.SyndicationFeedTest)\", \"test_atom_feed_published_and_updated_elements (syndication_tests.tests.SyndicationFeedTest)\", \"test_atom_multiple_enclosures (syndication_tests.tests.SyndicationFeedTest)\", \"test_atom_single_enclosure (syndication_tests.tests.SyndicationFeedTest)\", \"test_aware_datetime_conversion (syndication_tests.tests.SyndicationFeedTest)\", \"test_custom_feed_generator (syndication_tests.tests.SyndicationFeedTest)\", \"test_feed_generator_language_attribute (syndication_tests.tests.SyndicationFeedTest)\", \"test_feed_last_modified_time (syndication_tests.tests.SyndicationFeedTest)\", \"test_feed_last_modified_time_naive_date (syndication_tests.tests.SyndicationFeedTest)\", \"test_feed_url (syndication_tests.tests.SyndicationFeedTest)\", \"test_item_link_error (syndication_tests.tests.SyndicationFeedTest)\", \"test_latest_post_date (syndication_tests.tests.SyndicationFeedTest)\", \"test_naive_datetime_conversion (syndication_tests.tests.SyndicationFeedTest)\", \"test_rss091_feed (syndication_tests.tests.SyndicationFeedTest)\", \"test_rss2_feed_guid_permalink_false (syndication_tests.tests.SyndicationFeedTest)\", \"test_rss2_feed_guid_permalink_true (syndication_tests.tests.SyndicationFeedTest)\", \"test_rss2_multiple_enclosures (syndication_tests.tests.SyndicationFeedTest)\", \"test_rss2_single_enclosure (syndication_tests.tests.SyndicationFeedTest)\", \"test_secure_urls (syndication_tests.tests.SyndicationFeedTest)\", \"test_template_context_feed (syndication_tests.tests.SyndicationFeedTest)\", \"test_template_feed (syndication_tests.tests.SyndicationFeedTest)\", \"test_title_escaping (syndication_tests.tests.SyndicationFeedTest)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["syndication_tests.feeds", "syndication_tests.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 syndication_tests.feeds syndication_tests.tests", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/utils_tests/test_feedgenerator.py b/tests/utils_tests/test_feedgenerator.py\nindex 3847637aba..1c20597258 100644\n--- a/tests/utils_tests/test_feedgenerator.py\n+++ b/tests/utils_tests/test_feedgenerator.py\n@@ -119,6 +119,20 @@ class FeedgeneratorTests(SimpleTestCase):\n self.assertIn('href=\"/feed/\"', feed_content)\n self.assertIn('rel=\"self\"', feed_content)\n \n+ def test_feed_with_comments(self):\n+ \"\"\"\n+ Test that the comments field is correctly handled.\n+ \"\"\"\n+ feed = feedgenerator.Rss201rev2Feed('title', '/link/', 'descr')\n+ feed.add_item(\n+ title='item_title',\n+ link='item_link',\n+ description='item_description',\n+ comments='http://example.com/comments'\n+ )\n+ feed_content = feed.writeString('utf-8')\n+ self.assertIn('http://example.com/comments', feed_content)\n+\n def test_atom_add_item(self):\n # Not providing any optional arguments to Atom1Feed.add_item()\n feed = feedgenerator.Atom1Feed('title', '/link/', 'descr')\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["syndication_tests.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/contrib/syndication/views.py b/django/contrib/syndication/views.py\nindex 68ffb0bfe0..a09cc5fe74 100644\n--- a/django/contrib/syndication/views.py\n+++ b/django/contrib/syndication/views.py\n@@ -214,6 +214,7 @@ class Feed:\n author_link=author_link,\n categories=self._get_dynamic_attr('item_categories', item),\n item_copyright=self._get_dynamic_attr('item_copyright', item),\n+ comments=self._get_dynamic_attr('item_comments', item),\n **self.item_extra_kwargs(item)\n )\n return feed\n\ndiff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py\nindex f08e89b25c..647e6374d8 100644\n--- a/django/utils/feedgenerator.py\n+++ b/django/utils/feedgenerator.py\n@@ -85,7 +85,7 @@ class SyndicationFeed:\n def add_item(self, title, link, description, author_email=None,\n author_name=None, author_link=None, pubdate=None, comments=None,\n unique_id=None, unique_id_is_permalink=None, categories=(),\n- item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs):\n+ item_copyright=None, ttl=None, updateddate=None, enclosures=None, comments=None, **kwargs):\n \"\"\"\n Add an item to the feed. All args are expected to be strings except\n pubdate and updateddate, which are datetime.datetime objects, and\n@@ -369,6 +369,10 @@ class Atom1Feed(SyndicationFeed):\n if item['description'] is not None:\n handler.addQuickElement(\"summary\", item['description'], {\"type\": \"html\"})\n \n+ # Comments.\n+ if item['comments'] is not None:\n+ handler.addQuickElement(\"comments\", item['comments'])\n+\n # Enclosures.\n for enclosure in item['enclosures']:\n handler.addQuickElement('link', '', {\n", "model_lint_repair_patch": "diff --git a/django/contrib/syndication/views.py b/django/contrib/syndication/views.py\nindex 68ffb0bfe0..a09cc5fe74 100644\n--- a/django/contrib/syndication/views.py\n+++ b/django/contrib/syndication/views.py\n@@ -214,6 +214,7 @@ class Feed:\n author_link=author_link,\n categories=self._get_dynamic_attr('item_categories', item),\n item_copyright=self._get_dynamic_attr('item_copyright', item),\n+ comments=self._get_dynamic_attr('item_comments', item),\n **self.item_extra_kwargs(item)\n )\n return feed\n\ndiff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py\nindex f08e89b25c..47e80a2d81 100644\n--- a/django/utils/feedgenerator.py\n+++ b/django/utils/feedgenerator.py\n@@ -369,6 +369,10 @@ class Atom1Feed(SyndicationFeed):\n if item['description'] is not None:\n handler.addQuickElement(\"summary\", item['description'], {\"type\": \"html\"})\n \n+ # Comments.\n+ if item['comments'] is not None:\n+ handler.addQuickElement(\"comments\", item['comments'])\n+\n # Enclosures.\n for enclosure in item['enclosures']:\n handler.addQuickElement('link', '', {\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["syndication_tests.tests"]} +{"repo": "django/django", "instance_id": "django__django-14238", "base_commit": "30e123ed351317b7527f632b3b7dc4e81e850449", "patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -2524,7 +2524,7 @@ def __instancecheck__(self, instance):\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 issubclass(subclass, self._subclasses) or super().__subclasscheck__(subclass)\n \n \n class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):\n", "test_patch": "diff --git a/tests/model_fields/test_autofield.py b/tests/model_fields/test_autofield.py\n--- a/tests/model_fields/test_autofield.py\n+++ b/tests/model_fields/test_autofield.py\n@@ -30,6 +30,18 @@ def test_isinstance_of_autofield(self):\n self.assertIsInstance(field(), models.AutoField)\n \n def test_issubclass_of_autofield(self):\n- for field in (models.BigAutoField, models.SmallAutoField):\n+ class MyBigAutoField(models.BigAutoField):\n+ pass\n+\n+ class MySmallAutoField(models.SmallAutoField):\n+ pass\n+\n+ tests = [\n+ MyBigAutoField,\n+ MySmallAutoField,\n+ models.BigAutoField,\n+ models.SmallAutoField,\n+ ]\n+ for field in tests:\n with self.subTest(field.__name__):\n self.assertTrue(issubclass(field, models.AutoField))\ndiff --git a/tests/model_options/test_default_pk.py b/tests/model_options/test_default_pk.py\n--- a/tests/model_options/test_default_pk.py\n+++ b/tests/model_options/test_default_pk.py\n@@ -4,6 +4,10 @@\n from django.test.utils import isolate_apps\n \n \n+class MyBigAutoField(models.BigAutoField):\n+ pass\n+\n+\n @isolate_apps('model_options')\n class TestDefaultPK(SimpleTestCase):\n @override_settings(DEFAULT_AUTO_FIELD='django.db.models.NonexistentAutoField')\n@@ -74,6 +78,15 @@ class Model(models.Model):\n \n self.assertIsInstance(Model._meta.pk, models.SmallAutoField)\n \n+ @override_settings(\n+ DEFAULT_AUTO_FIELD='model_options.test_default_pk.MyBigAutoField'\n+ )\n+ def test_default_auto_field_setting_bigautofield_subclass(self):\n+ class Model(models.Model):\n+ pass\n+\n+ self.assertIsInstance(Model._meta.pk, MyBigAutoField)\n+\n @isolate_apps('model_options.apps.ModelPKConfig')\n @override_settings(DEFAULT_AUTO_FIELD='django.db.models.AutoField')\n def test_app_default_auto_field(self):\n", "problem_statement": "DEFAULT_AUTO_FIELD subclass check fails for subclasses of BigAutoField and SmallAutoField.\nDescription\n\t\nSet DEFAULT_AUTO_FIELD = \"example.core.models.MyBigAutoField\" , with contents of example.core.models:\nfrom django.db import models\nclass MyBigAutoField(models.BigAutoField):\n\tpass\nclass MyModel(models.Model):\n\tpass\nDjango then crashes with:\nTraceback (most recent call last):\n File \"/..././manage.py\", line 21, in \n\tmain()\n File \"/..././manage.py\", line 17, in main\n\texecute_from_command_line(sys.argv)\n File \"/.../venv/lib/python3.9/site-packages/django/core/management/__init__.py\", line 419, in execute_from_command_line\n\tutility.execute()\n File \"/.../venv/lib/python3.9/site-packages/django/core/management/__init__.py\", line 395, in execute\n\tdjango.setup()\n File \"/.../venv/lib/python3.9/site-packages/django/__init__.py\", line 24, in setup\n\tapps.populate(settings.INSTALLED_APPS)\n File \"/.../venv/lib/python3.9/site-packages/django/apps/registry.py\", line 114, in populate\n\tapp_config.import_models()\n File \"/.../venv/lib/python3.9/site-packages/django/apps/config.py\", line 301, in import_models\n\tself.models_module = import_module(models_module_name)\n File \"/Users/chainz/.pyenv/versions/3.9.1/lib/python3.9/importlib/__init__.py\", line 127, in import_module\n\treturn _bootstrap._gcd_import(name[level:], package, level)\n File \"\", line 1030, in _gcd_import\n File \"\", line 1007, in _find_and_load\n File \"\", line 986, in _find_and_load_unlocked\n File \"\", line 680, in _load_unlocked\n File \"\", line 790, in exec_module\n File \"\", line 228, in _call_with_frames_removed\n File \"/.../example/core/models.py\", line 8, in \n\tclass MyModel(models.Model):\n File \"/.../venv/lib/python3.9/site-packages/django/db/models/base.py\", line 320, in __new__\n\tnew_class._prepare()\n File \"/.../venv/lib/python3.9/site-packages/django/db/models/base.py\", line 333, in _prepare\n\topts._prepare(cls)\n File \"/.../venv/lib/python3.9/site-packages/django/db/models/options.py\", line 285, in _prepare\n\tpk_class = self._get_default_pk_class()\n File \"/.../venv/lib/python3.9/site-packages/django/db/models/options.py\", line 246, in _get_default_pk_class\n\traise ValueError(\nValueError: Primary key 'example.core.models.MyBigAutoField' referred by DEFAULT_AUTO_FIELD must subclass AutoField.\nThis can be fixed in AutoFieldMeta.__subclasscheck__ by allowing subclasses of those classes in the _subclasses property.\n", "hints_text": "", "created_at": "2021-04-08T10:41:31Z", "version": "4.0", "FAIL_TO_PASS": "[\"test_issubclass_of_autofield (model_fields.test_autofield.AutoFieldInheritanceTests)\", \"test_default_auto_field_setting_bigautofield_subclass (model_options.test_default_pk.TestDefaultPK)\"]", "PASS_TO_PASS": "[\"test_isinstance_of_autofield (model_fields.test_autofield.AutoFieldInheritanceTests)\", \"Backend specific ranges can be saved without corruption.\", \"Backend specific ranges are enforced at the model validation level\", \"test_coercing (model_fields.test_autofield.AutoFieldTests)\", \"Values within the documented safe range pass validation, and can be\", \"test_invalid_value (model_fields.test_autofield.AutoFieldTests)\", \"If there are stricter validators than the ones from the database\", \"test_rel_db_type (model_fields.test_autofield.AutoFieldTests)\", \"test_types (model_fields.test_autofield.AutoFieldTests)\", \"test_app_default_auto_field (model_options.test_default_pk.TestDefaultPK)\", \"test_app_default_auto_field_non_auto (model_options.test_default_pk.TestDefaultPK)\", \"test_app_default_auto_field_none (model_options.test_default_pk.TestDefaultPK)\", \"test_app_default_auto_field_nonexistent (model_options.test_default_pk.TestDefaultPK)\", \"test_default_auto_field_setting (model_options.test_default_pk.TestDefaultPK)\", \"test_default_auto_field_setting_non_auto (model_options.test_default_pk.TestDefaultPK)\", \"test_default_auto_field_setting_none (model_options.test_default_pk.TestDefaultPK)\", \"test_default_auto_field_setting_nonexistent (model_options.test_default_pk.TestDefaultPK)\", \"test_m2m_app_default_auto_field (model_options.test_default_pk.TestDefaultPK)\", \"test_m2m_default_auto_field_setting (model_options.test_default_pk.TestDefaultPK)\", \"test_coercing (model_fields.test_integerfield.SmallIntegerFieldTests)\", \"test_invalid_value (model_fields.test_integerfield.SmallIntegerFieldTests)\", \"test_rel_db_type (model_fields.test_integerfield.SmallIntegerFieldTests)\", \"test_types (model_fields.test_integerfield.SmallIntegerFieldTests)\", \"test_coercing (model_fields.test_integerfield.IntegerFieldTests)\", \"test_invalid_value (model_fields.test_integerfield.IntegerFieldTests)\", \"test_rel_db_type (model_fields.test_integerfield.IntegerFieldTests)\", \"test_types (model_fields.test_integerfield.IntegerFieldTests)\", \"test_coercing (model_fields.test_integerfield.BigIntegerFieldTests)\", \"test_invalid_value (model_fields.test_integerfield.BigIntegerFieldTests)\", \"test_rel_db_type (model_fields.test_integerfield.BigIntegerFieldTests)\", \"test_types (model_fields.test_integerfield.BigIntegerFieldTests)\", \"test_coercing (model_fields.test_autofield.SmallAutoFieldTests)\", \"test_invalid_value (model_fields.test_autofield.SmallAutoFieldTests)\", \"test_rel_db_type (model_fields.test_autofield.SmallAutoFieldTests)\", \"test_types (model_fields.test_autofield.SmallAutoFieldTests)\", \"test_coercing (model_fields.test_autofield.BigAutoFieldTests)\", \"test_invalid_value (model_fields.test_autofield.BigAutoFieldTests)\", \"test_rel_db_type (model_fields.test_autofield.BigAutoFieldTests)\", \"test_types (model_fields.test_autofield.BigAutoFieldTests)\"]", "environment_setup_commit": "475cffd1d64c690cdad16ede4d5e81985738ceb4", "test_directives": ["model_fields.test_autofield", "model_options.test_default_pk"], "test_cmd": "./tests/runtests.py --verbosity 2 model_fields.test_autofield model_options.test_default_pk", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/model_fields/test_autofield.py b/tests/model_fields/test_autofield.py\nindex 646cd2ab0a..7b05d80220 100644\n--- a/tests/model_fields/test_autofield.py\n+++ b/tests/model_fields/test_autofield.py\n@@ -33,3 +33,14 @@ class AutoFieldInheritanceTests(SimpleTestCase):\n for field in (models.BigAutoField, models.SmallAutoField):\n with self.subTest(field.__name__):\n self.assertTrue(issubclass(field, models.AutoField))\n+\n+ def test_custom_autofield_subclass(self):\n+ class MyBigAutoField(models.BigAutoField):\n+ pass\n+\n+ class MySmallAutoField(models.SmallAutoField):\n+ pass\n+\n+ for field in (MyBigAutoField, MySmallAutoField):\n+ with self.subTest(field.__name__):\n+ self.assertTrue(issubclass(field, models.AutoField))\n\ndiff --git a/tests/model_options/test_default_pk.py b/tests/model_options/test_default_pk.py\nindex b678848916..2738411fbf 100644\n--- a/tests/model_options/test_default_pk.py\n+++ b/tests/model_options/test_default_pk.py\n@@ -99,3 +99,23 @@ class TestDefaultPK(SimpleTestCase):\n \n m2m_pk = M2MModel._meta.get_field('m2m').remote_field.through._meta.pk\n self.assertIsInstance(m2m_pk, models.SmallAutoField)\n+\n+ @override_settings(DEFAULT_AUTO_FIELD='example.core.models.MyBigAutoField')\n+ def test_default_auto_field_subclass_big_auto_field(self):\n+ class MyBigAutoField(models.BigAutoField):\n+ pass\n+\n+ class Model(models.Model):\n+ id = MyBigAutoField(primary_key=True)\n+\n+ self.assertIsInstance(Model._meta.pk, MyBigAutoField)\n+\n+ @override_settings(DEFAULT_AUTO_FIELD='example.core.models.MySmallAutoField')\n+ def test_default_auto_field_subclass_small_auto_field(self):\n+ class MySmallAutoField(models.SmallAutoField):\n+ pass\n+\n+ class Model(models.Model):\n+ id = MySmallAutoField(primary_key=True)\n+\n+ self.assertIsInstance(Model._meta.pk, MySmallAutoField)\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["model_fields.test_autofield"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex 4028e05b99..a94d99746b 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -242,7 +242,7 @@ class Options:\n f\"not be imported.\"\n )\n raise ImproperlyConfigured(msg) from e\n- if not issubclass(pk_class, AutoField):\n+ if not issubclass(pk_class, (AutoField, BigAutoField, SmallAutoField)):\n raise ValueError(\n f\"Primary key '{pk_class_path}' referred by {source} must \"\n f\"subclass AutoField.\"\n", "model_lint_repair_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex 4028e05b99..a94d99746b 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -242,7 +242,7 @@ class Options:\n f\"not be imported.\"\n )\n raise ImproperlyConfigured(msg) from e\n- if not issubclass(pk_class, AutoField):\n+ if not issubclass(pk_class, (AutoField, BigAutoField, SmallAutoField)):\n raise ValueError(\n f\"Primary key '{pk_class_path}' referred by {source} must \"\n f\"subclass AutoField.\"\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-23117", "base_commit": "c5cef2499d6eed024b0db5c792d6ec7c53baa470", "patch": "diff --git a/sympy/tensor/array/ndim_array.py b/sympy/tensor/array/ndim_array.py\n--- a/sympy/tensor/array/ndim_array.py\n+++ b/sympy/tensor/array/ndim_array.py\n@@ -145,10 +145,12 @@ def __new__(cls, iterable, shape=None, **kwargs):\n \n def _parse_index(self, index):\n if isinstance(index, (SYMPY_INTS, Integer)):\n- raise ValueError(\"Only a tuple index is accepted\")\n+ if index >= self._loop_size:\n+ raise ValueError(\"Only a tuple index is accepted\")\n+ return index\n \n if self._loop_size == 0:\n- raise ValueError(\"Index not valide with an empty array\")\n+ raise ValueError(\"Index not valid with an empty array\")\n \n if len(index) != self._rank:\n raise ValueError('Wrong number of array axes')\n@@ -194,6 +196,9 @@ def f(pointer):\n if not isinstance(pointer, Iterable):\n return [pointer], ()\n \n+ if len(pointer) == 0:\n+ return [], (0,)\n+\n result = []\n elems, shapes = zip(*[f(i) for i in pointer])\n if len(set(shapes)) != 1:\n@@ -567,11 +572,11 @@ def _check_special_bounds(cls, flat_list, shape):\n \n def _check_index_for_getitem(self, index):\n if isinstance(index, (SYMPY_INTS, Integer, slice)):\n- index = (index, )\n+ index = (index,)\n \n if len(index) < self.rank():\n- index = tuple([i for i in index] + \\\n- [slice(None) for i in range(len(index), self.rank())])\n+ index = tuple(index) + \\\n+ tuple(slice(None) for i in range(len(index), self.rank()))\n \n if len(index) > self.rank():\n raise ValueError('Dimension of index greater than rank of array')\n", "test_patch": "diff --git a/sympy/tensor/array/tests/test_ndim_array.py b/sympy/tensor/array/tests/test_ndim_array.py\n--- a/sympy/tensor/array/tests/test_ndim_array.py\n+++ b/sympy/tensor/array/tests/test_ndim_array.py\n@@ -10,6 +10,11 @@\n \n from sympy.abc import x, y\n \n+mutable_array_types = [\n+ MutableDenseNDimArray,\n+ MutableSparseNDimArray\n+]\n+\n array_types = [\n ImmutableDenseNDimArray,\n ImmutableSparseNDimArray,\n@@ -46,7 +51,23 @@ def test_issue_18361():\n assert simplify(B) == Array([1, 0])\n assert simplify(C) == Array([x + 1, sin(2*x)])\n \n+\n def test_issue_20222():\n A = Array([[1, 2], [3, 4]])\n B = Matrix([[1,2],[3,4]])\n raises(TypeError, lambda: A - B)\n+\n+\n+def test_issue_17851():\n+ for array_type in array_types:\n+ A = array_type([])\n+ assert isinstance(A, array_type)\n+ assert A.shape == (0,)\n+ assert list(A) == []\n+\n+\n+def test_issue_and_18715():\n+ for array_type in mutable_array_types:\n+ A = array_type([0, 1, 2])\n+ A[0] += 5\n+ assert A[0] == 5\n", "problem_statement": "sympy.Array([]) fails, while sympy.Matrix([]) works\nSymPy 1.4 does not allow to construct empty Array (see code below). Is this the intended behavior?\r\n\r\n```\r\n>>> import sympy\r\nKeyboardInterrupt\r\n>>> import sympy\r\n>>> from sympy import Array\r\n>>> sympy.__version__\r\n'1.4'\r\n>>> a = Array([])\r\nTraceback (most recent call last):\r\n File \"\", line 1, in \r\n File \"/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/dense_ndim_array.py\", line 130, in __new__\r\n return cls._new(iterable, shape, **kwargs)\r\n File \"/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/dense_ndim_array.py\", line 136, in _new\r\n shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)\r\n File \"/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/ndim_array.py\", line 142, in _handle_ndarray_creation_inputs\r\n iterable, shape = cls._scan_iterable_shape(iterable)\r\n File \"/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/ndim_array.py\", line 127, in _scan_iterable_shape\r\n return f(iterable)\r\n File \"/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/ndim_array.py\", line 120, in f\r\n elems, shapes = zip(*[f(i) for i in pointer])\r\nValueError: not enough values to unpack (expected 2, got 0)\r\n```\r\n\r\n@czgdp1807 \n", "hints_text": "Technically, `Array([], shape=(0,))` works. It is just unable to understand the shape of `[]`.", "created_at": "2022-02-19T13:15:18Z", "version": "1.11", "FAIL_TO_PASS": "[\"test_issue_17851\"]", "PASS_TO_PASS": "[\"test_array_negative_indices\", \"test_issue_18361\", \"test_issue_20222\"]", "environment_setup_commit": "9a6104eab0ea7ac191a09c24f3e2d79dcd66bda5", "test_directives": ["sympy/tensor/array/tests/test_ndim_array.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/tensor/array/tests/test_ndim_array.py", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/sympy/tensor/array/tests/test_immutable_ndim_array.py b/sympy/tensor/array/tests/test_immutable_ndim_array.py\nindex c6bed4b605..74d147f1a9 100644\n--- a/sympy/tensor/array/tests/test_immutable_ndim_array.py\n+++ b/sympy/tensor/array/tests/test_immutable_ndim_array.py\n@@ -11,6 +11,7 @@\n from sympy.matrices import Matrix\n from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray\n from sympy.testing.pytest import raises\n+from sympy.tensor.array import Array\n \n \n def test_ndim_array_initiation():\n@@ -445,6 +446,24 @@ def test_zeros_without_shape():\n arr = ImmutableDenseNDimArray.zeros()\n assert arr == ImmutableDenseNDimArray(0)\n \n+def test_empty_array():\n+ # Test for empty ImmutableDenseNDimArray\n+ empty_dense_array = ImmutableDenseNDimArray([])\n+ assert empty_dense_array.shape == (0,)\n+ assert len(empty_dense_array) == 0\n+\n+ # Test for empty ImmutableSparseNDimArray\n+ empty_sparse_array = ImmutableSparseNDimArray([])\n+ assert empty_sparse_array.shape == (0,)\n+ assert len(empty_sparse_array) == 0\n+\n+ # Test for empty Array\n+ empty_array = Array([])\n+ assert empty_array.shape == (0,)\n+ assert len(empty_array) == 0\n+ arr = ImmutableDenseNDimArray.zeros()\n+ assert arr == ImmutableDenseNDimArray(0)\n+\n def test_issue_21870():\n a0 = ImmutableDenseNDimArray(0)\n assert a0.rank() == 0\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/tensor/array/tests/test_immutable_ndim_array.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/tensor/array/ndim_array.py b/sympy/tensor/array/ndim_array.py\nindex 6490a655a4..bc2acbe7a2 100644\n--- a/sympy/tensor/array/ndim_array.py\n+++ b/sympy/tensor/array/ndim_array.py\n@@ -193,6 +193,8 @@ def _scan_iterable_shape(cls, iterable):\n def f(pointer):\n if not isinstance(pointer, Iterable):\n return [pointer], ()\n+ if isinstance(pointer, Iterable) and not pointer:\n+ return [], (0,)\n \n result = []\n elems, shapes = zip(*[f(i) for i in pointer])\n@@ -224,6 +226,8 @@ def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):\n # Construct N-dim array from an iterable (numpy arrays included):\n elif isinstance(iterable, Iterable):\n iterable, shape = cls._scan_iterable_shape(iterable)\n+ if shape == (0,):\n+ iterable = []\n \n # Construct N-dim array from a Matrix:\n elif isinstance(iterable, MatrixBase):\n", "model_lint_repair_patch": "diff --git a/sympy/tensor/array/ndim_array.py b/sympy/tensor/array/ndim_array.py\nindex 6490a655a4..bc2acbe7a2 100644\n--- a/sympy/tensor/array/ndim_array.py\n+++ b/sympy/tensor/array/ndim_array.py\n@@ -193,6 +193,8 @@ def _scan_iterable_shape(cls, iterable):\n def f(pointer):\n if not isinstance(pointer, Iterable):\n return [pointer], ()\n+ if isinstance(pointer, Iterable) and not pointer:\n+ return [], (0,)\n \n result = []\n elems, shapes = zip(*[f(i) for i in pointer])\n@@ -224,6 +226,8 @@ def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):\n # Construct N-dim array from an iterable (numpy arrays included):\n elif isinstance(iterable, Iterable):\n iterable, shape = cls._scan_iterable_shape(iterable)\n+ if shape == (0,):\n+ iterable = []\n \n # Construct N-dim array from a Matrix:\n elif isinstance(iterable, MatrixBase):\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/tensor/array/tests/test_immutable_ndim_array.py"]} +{"repo": "django/django", "instance_id": "django__django-13401", "base_commit": "453967477e3ddae704cd739eac2449c0e13d464c", "patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -516,17 +516,37 @@ def clone(self):\n def __eq__(self, other):\n # Needed for @total_ordering\n if isinstance(other, Field):\n- return self.creation_counter == other.creation_counter\n+ return (\n+ self.creation_counter == other.creation_counter and\n+ getattr(self, 'model', None) == getattr(other, 'model', None)\n+ )\n return NotImplemented\n \n def __lt__(self, other):\n # This is needed because bisect does not take a comparison function.\n+ # Order by creation_counter first for backward compatibility.\n if isinstance(other, Field):\n- return self.creation_counter < other.creation_counter\n+ if (\n+ self.creation_counter != other.creation_counter or\n+ not hasattr(self, 'model') and not hasattr(other, 'model')\n+ ):\n+ return self.creation_counter < other.creation_counter\n+ elif hasattr(self, 'model') != hasattr(other, 'model'):\n+ return not hasattr(self, 'model') # Order no-model fields first\n+ else:\n+ # creation_counter's are equal, compare only models.\n+ return (\n+ (self.model._meta.app_label, self.model._meta.model_name) <\n+ (other.model._meta.app_label, other.model._meta.model_name)\n+ )\n return NotImplemented\n \n def __hash__(self):\n- return hash(self.creation_counter)\n+ return hash((\n+ self.creation_counter,\n+ self.model._meta.app_label if hasattr(self, 'model') else None,\n+ self.model._meta.model_name if hasattr(self, 'model') else None,\n+ ))\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_fields/tests.py b/tests/model_fields/tests.py\n--- a/tests/model_fields/tests.py\n+++ b/tests/model_fields/tests.py\n@@ -102,6 +102,36 @@ def test_deconstruct_nested_field(self):\n name, path, args, kwargs = Nested.Field().deconstruct()\n self.assertEqual(path, 'model_fields.tests.Nested.Field')\n \n+ def test_abstract_inherited_fields(self):\n+ \"\"\"Field instances from abstract models are not equal.\"\"\"\n+ class AbstractModel(models.Model):\n+ field = models.IntegerField()\n+\n+ class Meta:\n+ abstract = True\n+\n+ class InheritAbstractModel1(AbstractModel):\n+ pass\n+\n+ class InheritAbstractModel2(AbstractModel):\n+ pass\n+\n+ abstract_model_field = AbstractModel._meta.get_field('field')\n+ inherit1_model_field = InheritAbstractModel1._meta.get_field('field')\n+ inherit2_model_field = InheritAbstractModel2._meta.get_field('field')\n+\n+ self.assertNotEqual(abstract_model_field, inherit1_model_field)\n+ self.assertNotEqual(abstract_model_field, inherit2_model_field)\n+ self.assertNotEqual(inherit1_model_field, inherit2_model_field)\n+\n+ self.assertLess(abstract_model_field, inherit1_model_field)\n+ self.assertLess(abstract_model_field, inherit2_model_field)\n+ self.assertLess(inherit1_model_field, inherit2_model_field)\n+\n+ self.assertNotEqual(hash(abstract_model_field), hash(inherit1_model_field))\n+ self.assertNotEqual(hash(abstract_model_field), hash(inherit2_model_field))\n+ self.assertNotEqual(hash(inherit1_model_field), hash(inherit2_model_field))\n+\n \n class ChoicesTests(SimpleTestCase):\n \n", "problem_statement": "Abstract model field should not be equal across models\nDescription\n\t\nConsider the following models:\nclass A(models.Model):\n\tclass Meta:\n\t\tabstract = True\n\tmyfield = IntegerField()\nclass B(A):\n\tpass\nclass C(A):\n\tpass\nIf I pull the fields of B and C into a shared set, one will be de-duplicated away, because they compare as equal. I found this surprising, though in practice using a list was sufficient for my need. The root of the issue is that they compare equal, as fields only consider self.creation_counter when comparing for equality.\nlen({B._meta.get_field('myfield'), C._meta.get_field('myfield')}) == 1\nB._meta.get_field('myfield') == C._meta.get_field('myfield')\nWe should adjust __eq__ so that if the field.model is different, they will compare unequal. Similarly, it is probably wise to adjust __hash__ and __lt__ to match.\nWhen adjusting __lt__, it may be wise to order first by self.creation_counter so that cases not affected by this equality collision won't be re-ordered. In my experimental branch, there was one test that broke if I ordered them by model first.\nI brought this up on IRC django-dev to check my intuitions, and those conversing with me there seemed to agree that the current behavior is not intuitive.\n", "hints_text": "", "created_at": "2020-09-09T11:19:00Z", "version": "3.2", "FAIL_TO_PASS": "[\"Field instances from abstract models are not equal.\"]", "PASS_TO_PASS": "[\"test_blank_in_choices (model_fields.tests.GetChoicesTests)\", \"test_blank_in_grouped_choices (model_fields.tests.GetChoicesTests)\", \"test_empty_choices (model_fields.tests.GetChoicesTests)\", \"test_lazy_strings_not_evaluated (model_fields.tests.GetChoicesTests)\", \"test_get_choices (model_fields.tests.GetChoicesLimitChoicesToTests)\", \"test_get_choices_reverse_related_field (model_fields.tests.GetChoicesLimitChoicesToTests)\", \"test_choices_and_field_display (model_fields.tests.GetFieldDisplayTests)\", \"test_empty_iterator_choices (model_fields.tests.GetFieldDisplayTests)\", \"A translated display value is coerced to str.\", \"test_iterator_choices (model_fields.tests.GetFieldDisplayTests)\", \"test_overriding_FIELD_display (model_fields.tests.GetFieldDisplayTests)\", \"test_overriding_inherited_FIELD_display (model_fields.tests.GetFieldDisplayTests)\", \"Can supply a custom choices form class to Field.formfield()\", \"deconstruct() uses __qualname__ for nested class support.\", \"Field instances can be pickled.\", \"test_field_name (model_fields.tests.BasicFieldTests)\", \"Fields are ordered based on their creation.\", \"test_field_repr (model_fields.tests.BasicFieldTests)\", \"__repr__() uses __qualname__ for nested class support.\", \"test_field_str (model_fields.tests.BasicFieldTests)\", \"test_field_verbose_name (model_fields.tests.BasicFieldTests)\", \"Field.formfield() sets disabled for fields with choices.\", \"test_show_hidden_initial (model_fields.tests.BasicFieldTests)\", \"test_get_choices (model_fields.tests.GetChoicesOrderingTests)\", \"test_get_choices_default_ordering (model_fields.tests.GetChoicesOrderingTests)\", \"test_get_choices_reverse_related_field (model_fields.tests.GetChoicesOrderingTests)\", \"test_get_choices_reverse_related_field_default_ordering (model_fields.tests.GetChoicesOrderingTests)\", \"test_check (model_fields.tests.ChoicesTests)\", \"test_choices (model_fields.tests.ChoicesTests)\", \"test_flatchoices (model_fields.tests.ChoicesTests)\", \"test_formfield (model_fields.tests.ChoicesTests)\", \"test_invalid_choice (model_fields.tests.ChoicesTests)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["model_fields.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 model_fields.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/tests/model_inheritance/test_abstract_inheritance.py b/tests/model_inheritance/test_abstract_inheritance.py\nindex 1293efc531..27fb6f325a 100644\n--- a/tests/model_inheritance/test_abstract_inheritance.py\n+++ b/tests/model_inheritance/test_abstract_inheritance.py\n@@ -1,6 +1,7 @@\n from django.contrib.contenttypes.fields import (\n GenericForeignKey, GenericRelation,\n )\n+from django.db.models import IntegerField\n from django.contrib.contenttypes.models import ContentType\n from django.core.checks import Error\n from django.core.exceptions import FieldDoesNotExist, FieldError\n@@ -11,6 +12,24 @@ from django.test.utils import isolate_apps\n \n @isolate_apps('model_inheritance')\n class AbstractInheritanceTests(SimpleTestCase):\n+ def test_abstract_model_field_equality(self):\n+ class A(models.Model):\n+ class Meta:\n+ abstract = True\n+ myfield = IntegerField()\n+\n+ class B(A):\n+ pass\n+\n+ class C(A):\n+ pass\n+\n+ b_field = B._meta.get_field('myfield')\n+ c_field = C._meta.get_field('myfield')\n+\n+ self.assertNotEqual(b_field, c_field)\n+ self.assertNotEqual(hash(b_field), hash(c_field))\n+ self.assertNotEqual(b_field.__lt__(c_field), c_field.__lt__(b_field))\n def test_single_parent(self):\n class AbstractBase(models.Model):\n name = models.CharField(max_length=30)\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["model_inheritance.test_abstract_inheritance"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 28374272f4..afe1ed6aea 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -516,17 +516,20 @@ class Field(RegisterLookupMixin):\n def __eq__(self, other):\n # Needed for @total_ordering\n if isinstance(other, Field):\n- return self.creation_counter == other.creation_counter\n+ return (self.creation_counter == other.creation_counter and\n+ getattr(self, 'model', None) == getattr(other, 'model', None))\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 getattr(self, 'model', None) == getattr(other, 'model', None):\n+ return self.creation_counter < other.creation_counter\n+ return str(getattr(self, 'model', '')) < str(getattr(other, 'model', ''))\n return NotImplemented\n \n def __hash__(self):\n- return hash(self.creation_counter)\n+ return hash((self.creation_counter, getattr(self, 'model', None)))\n \n def __deepcopy__(self, memodict):\n # We don't have to deepcopy very much here, since most things are not\n", "model_lint_repair_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 28374272f4..afe1ed6aea 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -516,17 +516,20 @@ class Field(RegisterLookupMixin):\n def __eq__(self, other):\n # Needed for @total_ordering\n if isinstance(other, Field):\n- return self.creation_counter == other.creation_counter\n+ return (self.creation_counter == other.creation_counter and\n+ getattr(self, 'model', None) == getattr(other, 'model', None))\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 getattr(self, 'model', None) == getattr(other, 'model', None):\n+ return self.creation_counter < other.creation_counter\n+ return str(getattr(self, 'model', '')) < str(getattr(other, 'model', ''))\n return NotImplemented\n \n def __hash__(self):\n- return hash(self.creation_counter)\n+ return hash((self.creation_counter, getattr(self, 'model', None)))\n \n def __deepcopy__(self, memodict):\n # We don't have to deepcopy very much here, since most things are not\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["model_inheritance.test_abstract_inheritance"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-22714", "base_commit": "3ff4717b6aef6086e78f01cdfa06f64ae23aed7e", "patch": "diff --git a/sympy/geometry/point.py b/sympy/geometry/point.py\n--- a/sympy/geometry/point.py\n+++ b/sympy/geometry/point.py\n@@ -152,7 +152,7 @@ def __new__(cls, *args, **kwargs):\n 'warn' or 'ignore'.'''))\n if any(coords[dim:]):\n raise ValueError('Nonzero coordinates cannot be removed.')\n- if any(a.is_number and im(a) for a in coords):\n+ if any(a.is_number and im(a).is_zero is False for a in coords):\n raise ValueError('Imaginary coordinates are not permitted.')\n if not all(isinstance(a, Expr) for a in coords):\n raise TypeError('Coordinates must be valid SymPy expressions.')\n", "test_patch": "diff --git a/sympy/geometry/tests/test_point.py b/sympy/geometry/tests/test_point.py\n--- a/sympy/geometry/tests/test_point.py\n+++ b/sympy/geometry/tests/test_point.py\n@@ -1,5 +1,6 @@\n from sympy.core.basic import Basic\n from sympy.core.numbers import (I, Rational, pi)\n+from sympy.core.parameters import evaluate\n from sympy.core.singleton import S\n from sympy.core.symbol import Symbol\n from sympy.core.sympify import sympify\n@@ -452,6 +453,12 @@ def test__normalize_dimension():\n Point(1, 2, 0), Point(3, 4, 0)]\n \n \n+def test_issue_22684():\n+ # Used to give an error\n+ with evaluate(False):\n+ Point(1, 2)\n+\n+\n def test_direction_cosine():\n p1 = Point3D(0, 0, 0)\n p2 = Point3D(1, 1, 1)\n", "problem_statement": "simpify gives `Imaginary coordinates are not permitted.` with evaluate(False)\n## Issue\r\n`with evaluate(False)` crashes unexpectedly with `Point2D`\r\n\r\n## Code\r\n```python\r\nimport sympy as sp\r\nwith sp.evaluate(False):\r\n sp.S('Point2D(Integer(1),Integer(2))')\r\n```\r\n\r\n## Error\r\n```\r\nTraceback (most recent call last):\r\n File \"\", line 1, in \r\n File \"/home/avinash/.local/lib/python3.8/site-packages/sympy/core/sympify.py\", line 472, in sympify\r\n expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)\r\n File \"/home/avinash/.local/lib/python3.8/site-packages/sympy/parsing/sympy_parser.py\", line 1026, in parse_expr\r\n raise e from ValueError(f\"Error from parse_expr with transformed code: {code!r}\")\r\n File \"/home/avinash/.local/lib/python3.8/site-packages/sympy/parsing/sympy_parser.py\", line 1017, in parse_expr\r\n rv = eval_expr(code, local_dict, global_dict)\r\n File \"/home/avinash/.local/lib/python3.8/site-packages/sympy/parsing/sympy_parser.py\", line 911, in eval_expr\r\n expr = eval(\r\n File \"\", line 1, in \r\n File \"/home/avinash/.local/lib/python3.8/site-packages/sympy/geometry/point.py\", line 912, in __new__\r\n args = Point(*args, **kwargs)\r\n File \"/home/avinash/.local/lib/python3.8/site-packages/sympy/geometry/point.py\", line 153, in __new__\r\n raise ValueError('Imaginary coordinates are not permitted.')\r\nValueError: Imaginary coordinates are not permitted.\r\n```\r\n\r\nHowever, it works without `with evaluate(False)`. Both of following commands work\r\n```python\r\nsp.S('Point2D(Integer(1),Integer(2))')\r\nsp.S('Point2D(Integer(1),Integer(2))', evaluate=False)\r\n```\n", "hints_text": "", "created_at": "2021-12-19T18:54:36Z", "version": "1.10", "FAIL_TO_PASS": "[\"test_issue_22684\"]", "PASS_TO_PASS": "[\"test_point\", \"test_point3D\", \"test_Point2D\", \"test_issue_9214\", \"test_issue_11617\", \"test_transform\", \"test_concyclic_doctest_bug\", \"test_arguments\", \"test_unit\", \"test_dot\", \"test__normalize_dimension\"]", "environment_setup_commit": "fd40404e72921b9e52a5f9582246e4a6cd96c431", "test_directives": ["sympy/geometry/tests/test_point.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/geometry/tests/test_point.py", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/sympy/geometry/tests/test_point.py b/sympy/geometry/tests/test_point.py\nindex 930d707735..b9db21268b 100644\n--- a/sympy/geometry/tests/test_point.py\n+++ b/sympy/geometry/tests/test_point.py\n@@ -369,6 +369,16 @@ def test_arguments():\n doubles2d = cartes(singles2d, singles2d2)\n p2d = Point2D(1,2)\n singles3d = ((1,2,3), [1,2,3], Point(1,2,3))\n+\n+def test_issue_evaluate_false():\n+ import sympy as sp\n+ with sp.evaluate(False):\n+ assert sp.S('Point2D(Integer(1),Integer(2))') == Point2D(1, 2)\n+ singles2d = ((1,2), [1,2], Point(1,2))\n+ singles2d2 = ((1,3), [1,3], Point(1,3))\n+ doubles2d = cartes(singles2d, singles2d2)\n+ p2d = Point2D(1,2)\n+ singles3d = ((1,2,3), [1,2,3], Point(1,2,3))\n doubles3d = subsets(singles3d, 2)\n p3d = Point3D(1,2,3)\n singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4))\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["sympy/geometry/tests/test_point.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/geometry/point.py b/sympy/geometry/point.py\nindex 73c20334d0..ad06668efe 100644\n--- a/sympy/geometry/point.py\n+++ b/sympy/geometry/point.py\n@@ -152,7 +152,7 @@ def __new__(cls, *args, **kwargs):\n 'warn' or 'ignore'.'''))\n if any(coords[dim:]):\n raise ValueError('Nonzero coordinates cannot be removed.')\n- if any(a.is_number and im(a) for a in coords):\n+ if evaluate and any(a.is_number and im(a) for a in coords):\n raise ValueError('Imaginary coordinates are not permitted.')\n if not all(isinstance(a, Expr) for a in coords):\n raise TypeError('Coordinates must be valid SymPy expressions.')\n", "model_lint_repair_patch": "diff --git a/sympy/geometry/point.py b/sympy/geometry/point.py\nindex 73c20334d0..ad06668efe 100644\n--- a/sympy/geometry/point.py\n+++ b/sympy/geometry/point.py\n@@ -152,7 +152,7 @@ def __new__(cls, *args, **kwargs):\n 'warn' or 'ignore'.'''))\n if any(coords[dim:]):\n raise ValueError('Nonzero coordinates cannot be removed.')\n- if any(a.is_number and im(a) for a in coords):\n+ if evaluate and any(a.is_number and im(a) for a in coords):\n raise ValueError('Imaginary coordinates are not permitted.')\n if not all(isinstance(a, Expr) for a in coords):\n raise TypeError('Coordinates must be valid SymPy expressions.')\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/geometry/tests/test_point.py"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-18189", "base_commit": "1923822ddf8265199dbd9ef9ce09641d3fd042b9", "patch": "diff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py\n--- a/sympy/solvers/diophantine.py\n+++ b/sympy/solvers/diophantine.py\n@@ -182,7 +182,7 @@ def diophantine(eq, param=symbols(\"t\", integer=True), syms=None,\n if syms != var:\n dict_sym_index = dict(zip(syms, range(len(syms))))\n return {tuple([t[dict_sym_index[i]] for i in var])\n- for t in diophantine(eq, param)}\n+ for t in diophantine(eq, param, permute=permute)}\n n, d = eq.as_numer_denom()\n if n.is_number:\n return set()\n", "test_patch": "diff --git a/sympy/solvers/tests/test_diophantine.py b/sympy/solvers/tests/test_diophantine.py\n--- a/sympy/solvers/tests/test_diophantine.py\n+++ b/sympy/solvers/tests/test_diophantine.py\n@@ -547,6 +547,13 @@ def test_diophantine():\n assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \\\n set([(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)])\n \n+\n+ #test issue 18186\n+ assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \\\n+ set([(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)])\n+ assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \\\n+ set([(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)])\n+\n # issue 18122\n assert check_solutions(x**2-y)\n assert check_solutions(y**2-x)\n@@ -554,6 +561,7 @@ def test_diophantine():\n assert diophantine((y**2-x), t) == set([(t**2, -t)])\n \n \n+\n def test_general_pythagorean():\n from sympy.abc import a, b, c, d, e\n \n", "problem_statement": "diophantine: incomplete results depending on syms order with permute=True\n```\r\nIn [10]: diophantine(n**4 + m**4 - 2**4 - 3**4, syms=(m,n), permute=True)\r\nOut[10]: {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}\r\n\r\nIn [11]: diophantine(n**4 + m**4 - 2**4 - 3**4, syms=(n,m), permute=True)\r\nOut[11]: {(3, 2)}\r\n```\r\n\ndiophantine: incomplete results depending on syms order with permute=True\n```\r\nIn [10]: diophantine(n**4 + m**4 - 2**4 - 3**4, syms=(m,n), permute=True)\r\nOut[10]: {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}\r\n\r\nIn [11]: diophantine(n**4 + m**4 - 2**4 - 3**4, syms=(n,m), permute=True)\r\nOut[11]: {(3, 2)}\r\n```\r\n\n", "hints_text": "```diff\r\ndiff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py\r\nindex 6092e35..b43f5c1 100644\r\n--- a/sympy/solvers/diophantine.py\r\n+++ b/sympy/solvers/diophantine.py\r\n@@ -182,7 +182,7 @@ def diophantine(eq, param=symbols(\"t\", integer=True), syms=None,\r\n if syms != var:\r\n dict_sym_index = dict(zip(syms, range(len(syms))))\r\n return {tuple([t[dict_sym_index[i]] for i in var])\r\n- for t in diophantine(eq, param)}\r\n+ for t in diophantine(eq, param, permute=permute)}\r\n n, d = eq.as_numer_denom()\r\n if n.is_number:\r\n return set()\r\n```\nBased on a cursory glance at the code it seems that `permute=True` is lost when `diophantine` calls itself:\r\nhttps://github.com/sympy/sympy/blob/d98abf000b189d4807c6f67307ebda47abb997f8/sympy/solvers/diophantine.py#L182-L185.\r\nThat should be easy to solve; I'll include a fix in my next PR (which is related).\nAh, ninja'd by @smichr :-)\n```diff\r\ndiff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py\r\nindex 6092e35..b43f5c1 100644\r\n--- a/sympy/solvers/diophantine.py\r\n+++ b/sympy/solvers/diophantine.py\r\n@@ -182,7 +182,7 @@ def diophantine(eq, param=symbols(\"t\", integer=True), syms=None,\r\n if syms != var:\r\n dict_sym_index = dict(zip(syms, range(len(syms))))\r\n return {tuple([t[dict_sym_index[i]] for i in var])\r\n- for t in diophantine(eq, param)}\r\n+ for t in diophantine(eq, param, permute=permute)}\r\n n, d = eq.as_numer_denom()\r\n if n.is_number:\r\n return set()\r\n```\nBased on a cursory glance at the code it seems that `permute=True` is lost when `diophantine` calls itself:\r\nhttps://github.com/sympy/sympy/blob/d98abf000b189d4807c6f67307ebda47abb997f8/sympy/solvers/diophantine.py#L182-L185.\r\nThat should be easy to solve; I'll include a fix in my next PR (which is related).\nAh, ninja'd by @smichr :-)", "created_at": "2019-12-31T15:45:24Z", "version": "1.6", "FAIL_TO_PASS": "[\"test_diophantine\"]", "PASS_TO_PASS": "[\"test_input_format\", \"test_univariate\", \"test_classify_diop\", \"test_linear\", \"test_quadratic_simple_hyperbolic_case\", \"test_quadratic_elliptical_case\", \"test_quadratic_parabolic_case\", \"test_quadratic_perfect_square\", \"test_quadratic_non_perfect_square\", \"test_issue_9106\", \"test_issue_18138\", \"test_DN\", \"test_bf_pell\", \"test_length\", \"test_transformation_to_pell\", \"test_find_DN\", \"test_ldescent\", \"test_diop_ternary_quadratic_normal\", \"test_transformation_to_normal\", \"test_diop_ternary_quadratic\", \"test_square_factor\", \"test_parametrize_ternary_quadratic\", \"test_no_square_ternary_quadratic\", \"test_descent\", \"test_general_pythagorean\", \"test_diop_general_sum_of_squares_quick\", \"test_diop_partition\", \"test_prime_as_sum_of_two_squares\", \"test_sum_of_three_squares\", \"test_sum_of_four_squares\", \"test_power_representation\", \"test_assumptions\", \"test_diopcoverage\", \"test_holzer\", \"test_issue_9539\", \"test_issue_8943\", \"test_diop_sum_of_even_powers\", \"test_sum_of_squares_powers\", \"test__can_do_sum_of_squares\", \"test_diophantine_permute_sign\", \"test_issue_9538\"]", "environment_setup_commit": "28b41c73c12b70d6ad9f6e45109a80649c4456da", "test_directives": ["sympy/solvers/tests/test_diophantine.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/solvers/tests/test_diophantine.py", "model_name_or_path": "navie", "model_patch": null} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-23262", "base_commit": "fdc707f73a65a429935c01532cd3970d3355eab6", "patch": "diff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py\n--- a/sympy/utilities/lambdify.py\n+++ b/sympy/utilities/lambdify.py\n@@ -956,9 +956,9 @@ def _recursive_to_string(doprint, arg):\n return doprint(arg)\n elif iterable(arg):\n if isinstance(arg, list):\n- left, right = \"[]\"\n+ left, right = \"[\", \"]\"\n elif isinstance(arg, tuple):\n- left, right = \"()\"\n+ left, 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", "test_patch": "diff --git a/sympy/utilities/tests/test_lambdify.py b/sympy/utilities/tests/test_lambdify.py\n--- a/sympy/utilities/tests/test_lambdify.py\n+++ b/sympy/utilities/tests/test_lambdify.py\n@@ -1192,6 +1192,8 @@ def test_issue_14941():\n # test tuple\n f2 = lambdify([x, y], (y, x), 'sympy')\n assert f2(2, 3) == (3, 2)\n+ f2b = lambdify([], (1,)) # gh-23224\n+ assert f2b() == (1,)\n \n # test list\n f3 = lambdify([x, y], [y, x], 'sympy')\n", "problem_statement": "Python code printer not respecting tuple with one element\nHi,\r\n\r\nThanks for the recent updates in SymPy! I'm trying to update my code to use SymPy 1.10 but ran into an issue with the Python code printer. MWE:\r\n\r\n\r\n```python\r\nimport inspect\r\nfrom sympy import lambdify\r\n\r\ninspect.getsource(lambdify([], tuple([1])))\r\n```\r\nSymPy 1.9 and under outputs:\r\n```\r\n'def _lambdifygenerated():\\n return (1,)\\n'\r\n```\r\n\r\nBut SymPy 1.10 gives\r\n\r\n```\r\n'def _lambdifygenerated():\\n return (1)\\n'\r\n```\r\nNote the missing comma after `1` that causes an integer to be returned instead of a tuple. \r\n\r\nFor tuples with two or more elements, the generated code is correct:\r\n```python\r\ninspect.getsource(lambdify([], tuple([1, 2])))\r\n```\r\nIn SymPy 1.10 and under, outputs:\r\n\r\n```\r\n'def _lambdifygenerated():\\n return (1, 2)\\n'\r\n```\r\nThis result is expected.\r\n\r\nNot sure if this is a regression. As this breaks my program which assumes the return type to always be a tuple, could you suggest a workaround from the code generation side? Thank you. \n", "hints_text": "Bisected to 6ccd2b07ded5074941bb80b5967d60fa1593007a from #21993.\r\n\r\nCC @bjodah \nAs a work around for now, you can use the `Tuple` object from sympy. Note that it is constructed slightly differently from a python `tuple`, rather than giving a `list`, you give it multiple input arguments (or you can put a `*` in front of your list):\r\n```python\r\n>>> inspect.getsource(lambdify([], Tuple(*[1])))\r\ndef _lambdifygenerated():\\n return (1,)\\n\r\n>>> inspect.getsource(lambdify([], Tuple(1)))\r\ndef _lambdifygenerated():\\n return (1,)\\n\r\n```\r\nOf course the problem should also be fixed. `lambdify` is in a bit of an awkward spot, it supports a lot of different input and output formats that make it practically impossible to keep any functionality that is not explicitly tested for whenever you make a change.\n\r\n\r\n\r\n> As a work around for now, you can use the `Tuple` object from sympy. Note that it is constructed slightly differently from a python `tuple`, rather than giving a `list`, you give it multiple input arguments (or you can put a `*` in front of your list):\r\n\r\nThank you! This is tested to be working in SymPy 1.6-1.10. Consider this issue addressed for now. \r\n\r\n`lambdify` (or generally, the code generation) is an extremely useful tool. Are you aware of any roadmap or discussions on the refactoring of `lambdify` (or codegen)? I would like to contribute to it. \r\n\nI want to put out a 1.10.1 bugfix release. Should this be fixed?", "created_at": "2022-03-21T07:17:35Z", "version": "1.11", "FAIL_TO_PASS": "[\"test_issue_14941\"]", "PASS_TO_PASS": "[\"test_no_args\", \"test_single_arg\", \"test_list_args\", \"test_nested_args\", \"test_str_args\", \"test_own_namespace_1\", \"test_own_namespace_2\", \"test_own_module\", \"test_bad_args\", \"test_atoms\", \"test_sympy_lambda\", \"test_math_lambda\", \"test_mpmath_lambda\", \"test_number_precision\", \"test_mpmath_precision\", \"test_math_transl\", \"test_mpmath_transl\", \"test_empty_modules\", \"test_exponentiation\", \"test_sqrt\", \"test_trig\", \"test_integral\", \"test_double_integral\", \"test_vector_simple\", \"test_vector_discontinuous\", \"test_trig_symbolic\", \"test_trig_float\", \"test_docs\", \"test_math\", \"test_sin\", \"test_matrix\", \"test_issue9474\", \"test_sym_single_arg\", \"test_sym_list_args\", \"test_sym_integral\", \"test_namespace_order\", \"test_imps\", \"test_imps_errors\", \"test_imps_wrong_args\", \"test_lambdify_imps\", \"test_dummification\", \"test_curly_matrix_symbol\", \"test_python_keywords\", \"test_lambdify_docstring\", \"test_special_printers\", \"test_true_false\", \"test_issue_2790\", \"test_issue_12092\", \"test_issue_14911\", \"test_ITE\", \"test_Min_Max\", \"test_issue_12173\", \"test_sinc_mpmath\", \"test_lambdify_dummy_arg\", \"test_lambdify_mixed_symbol_dummy_args\", \"test_lambdify_inspect\", \"test_lambdify_Derivative_arg_issue_16468\", \"test_imag_real\", \"test_single_e\", \"test_beta_math\", \"test_lambdify_cse\"]", "environment_setup_commit": "9a6104eab0ea7ac191a09c24f3e2d79dcd66bda5", "test_directives": ["sympy/utilities/tests/test_lambdify.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/utilities/tests/test_lambdify.py", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/sympy/printing/tests/test_pycode.py b/sympy/printing/tests/test_pycode.py\nindex f4937a90e0..3f58820322 100644\n--- a/sympy/printing/tests/test_pycode.py\n+++ b/sympy/printing/tests/test_pycode.py\n@@ -31,11 +31,22 @@ def test_PythonCodePrinter():\n \n assert not prntr.module_imports\n \n+ # Test for single-element tuple\n+ assert prntr.doprint((1,)) == '(1,)'\n+\n+ # New test case for single-element tuple in lambdify\n+ from sympy import lambdify\n+ import inspect\n+ assert inspect.getsource(lambdify([], tuple([1]))) == 'def _lambdifygenerated():\\n return (1,)\\n'\n+\n assert prntr.doprint(x**y) == 'x**y'\n assert prntr.doprint(Mod(x, 2)) == 'x % 2'\n assert prntr.doprint(-Mod(x, y)) == '-(x % y)'\n assert prntr.doprint(Mod(-x, y)) == '(-x) % y'\n assert prntr.doprint(And(x, y)) == 'x and y'\n+\n+ # Test for single-element tuple\n+ assert prntr.doprint((1,)) == '(1,)'\n assert prntr.doprint(Or(x, y)) == 'x or y'\n assert not prntr.module_imports\n \n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/printing/tests/test_pycode.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py\nindex 1877c3f92a..468ddd2761 100644\n--- a/sympy/printing/pycode.py\n+++ b/sympy/printing/pycode.py\n@@ -77,6 +77,11 @@ def _print_known_const(self, expr):\n class AbstractPythonCodePrinter(CodePrinter):\n printmethod = \"_pythoncode\"\n language = \"Python\"\n+\n+ def _print_Tuple(self, expr):\n+ if len(expr) == 1:\n+ return '({},)'.format(self._print(expr[0]))\n+ return '({})'.format(', '.join(map(self._print, expr)))\n reserved_words = _kw\n modules = None # initialized to a set in __init__\n tab = ' '\n", "model_lint_repair_patch": "diff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py\nindex 1877c3f92a..468ddd2761 100644\n--- a/sympy/printing/pycode.py\n+++ b/sympy/printing/pycode.py\n@@ -77,6 +77,11 @@ def _print_known_const(self, expr):\n class AbstractPythonCodePrinter(CodePrinter):\n printmethod = \"_pythoncode\"\n language = \"Python\"\n+\n+ def _print_Tuple(self, expr):\n+ if len(expr) == 1:\n+ return '({},)'.format(self._print(expr[0]))\n+ return '({})'.format(', '.join(map(self._print, expr)))\n reserved_words = _kw\n modules = None # initialized to a set in __init__\n tab = ' '\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-14999", "base_commit": "a754b82dac511475b6276039471ccd17cc64aeb8", "patch": "diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py\n--- a/django/db/migrations/operations/models.py\n+++ b/django/db/migrations/operations/models.py\n@@ -320,12 +320,13 @@ def database_forwards(self, app_label, schema_editor, from_state, to_state):\n new_model = to_state.apps.get_model(app_label, self.new_name)\n if self.allow_migrate_model(schema_editor.connection.alias, new_model):\n old_model = from_state.apps.get_model(app_label, self.old_name)\n+ old_db_table = old_model._meta.db_table\n+ new_db_table = new_model._meta.db_table\n+ # Don't alter when a table name is not changed.\n+ if old_db_table == new_db_table:\n+ return\n # Move the main table\n- schema_editor.alter_db_table(\n- new_model,\n- old_model._meta.db_table,\n- new_model._meta.db_table,\n- )\n+ schema_editor.alter_db_table(new_model, old_db_table, new_db_table)\n # Alter the fields pointing to us\n for related_object in old_model._meta.related_objects:\n if related_object.related_model == old_model:\n", "test_patch": "diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py\n--- a/tests/migrations/test_operations.py\n+++ b/tests/migrations/test_operations.py\n@@ -793,6 +793,28 @@ def test_rename_model_with_m2m(self):\n self.assertEqual(Rider.objects.count(), 2)\n self.assertEqual(Pony._meta.get_field('riders').remote_field.through.objects.count(), 2)\n \n+ def test_rename_model_with_db_table_noop(self):\n+ app_label = 'test_rmwdbtn'\n+ project_state = self.apply_operations(app_label, ProjectState(), operations=[\n+ migrations.CreateModel('Rider', fields=[\n+ ('id', models.AutoField(primary_key=True)),\n+ ], options={'db_table': 'rider'}),\n+ migrations.CreateModel('Pony', fields=[\n+ ('id', models.AutoField(primary_key=True)),\n+ ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),\n+ ]),\n+ ])\n+ new_state = project_state.clone()\n+ operation = migrations.RenameModel('Rider', 'Runner')\n+ operation.state_forwards(app_label, new_state)\n+\n+ with connection.schema_editor() as editor:\n+ with self.assertNumQueries(0):\n+ operation.database_forwards(app_label, editor, project_state, new_state)\n+ with connection.schema_editor() as editor:\n+ with self.assertNumQueries(0):\n+ operation.database_backwards(app_label, editor, new_state, project_state)\n+\n def test_rename_m2m_target_model(self):\n app_label = \"test_rename_m2m_target_model\"\n project_state = self.apply_operations(app_label, ProjectState(), operations=[\n", "problem_statement": "RenameModel with db_table should be a noop.\nDescription\n\t\nA RenameModel operation that already has db_table defined must be a noop.\nIn Postgres, it drops and recreates foreign key constraints. In sqlite it recreates the table (as expected for a table renaming).\n", "hints_text": "", "created_at": "2021-10-16T09:31:21Z", "version": "4.1", "FAIL_TO_PASS": "[\"test_rename_model_with_db_table_noop (migrations.test_operations.OperationTests)\"]", "PASS_TO_PASS": "[\"test_references_model_mixin (migrations.test_operations.TestCreateModel)\", \"test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_name (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_remote_field_model (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_through (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_to_fields (migrations.test_operations.FieldOperationTests)\", \"test_references_model (migrations.test_operations.FieldOperationTests)\", \"Tests the AddField operation.\", \"The CreateTable operation ignores swapped models.\", \"Tests the DeleteModel operation ignores swapped models.\", \"Add/RemoveIndex operations ignore swapped models.\", \"Tests the AddField operation on TextField/BinaryField.\", \"Tests the AddField operation on TextField.\", \"test_add_constraint (migrations.test_operations.OperationTests)\", \"test_add_constraint_combinable (migrations.test_operations.OperationTests)\", \"test_add_constraint_percent_escaping (migrations.test_operations.OperationTests)\", \"test_add_covering_unique_constraint (migrations.test_operations.OperationTests)\", \"test_add_deferred_unique_constraint (migrations.test_operations.OperationTests)\", \"Tests the AddField operation with a ManyToManyField.\", \"Tests the AddField operation's state alteration\", \"test_add_func_index (migrations.test_operations.OperationTests)\", \"test_add_func_unique_constraint (migrations.test_operations.OperationTests)\", \"Test the AddIndex operation.\", \"test_add_index_state_forwards (migrations.test_operations.OperationTests)\", \"test_add_or_constraint (migrations.test_operations.OperationTests)\", \"test_add_partial_unique_constraint (migrations.test_operations.OperationTests)\", \"Tests the AlterField operation.\", \"AlterField operation is a noop when adding only a db_column and the\", \"test_alter_field_m2m (migrations.test_operations.OperationTests)\", \"Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)\", \"Tests the AlterField operation on primary keys changes any FKs pointing to it.\", \"test_alter_field_pk_mti_fk (migrations.test_operations.OperationTests)\", \"If AlterField doesn't reload state appropriately, the second AlterField\", \"test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change (migrations.test_operations.OperationTests)\", \"test_alter_field_reloads_state_on_fk_with_to_field_target_type_change (migrations.test_operations.OperationTests)\", \"test_alter_field_with_func_index (migrations.test_operations.OperationTests)\", \"test_alter_field_with_func_unique_constraint (migrations.test_operations.OperationTests)\", \"Test AlterField operation with an index to ensure indexes created via\", \"Creating and then altering an FK works correctly\", \"Altering an FK to a non-FK works (#23244)\", \"Tests the AlterIndexTogether operation.\", \"test_alter_index_together_remove (migrations.test_operations.OperationTests)\", \"test_alter_index_together_remove_with_unique_together (migrations.test_operations.OperationTests)\", \"The managers on a model are set.\", \"Tests the AlterModelOptions operation.\", \"The AlterModelOptions operation removes keys from the dict (#23121)\", \"Tests the AlterModelTable operation.\", \"AlterModelTable should rename auto-generated M2M tables.\", \"Tests the AlterModelTable operation if the table name is set to None.\", \"Tests the AlterModelTable operation if the table name is not changed.\", \"Tests the AlterOrderWithRespectTo operation.\", \"Tests the AlterUniqueTogether operation.\", \"test_alter_unique_together_remove (migrations.test_operations.OperationTests)\", \"A field may be migrated from AutoField to BigAutoField.\", \"Column names that are SQL keywords shouldn't cause problems when used\", \"Tests the CreateModel operation.\", \"Tests the CreateModel operation on a multi-table inheritance setup.\", \"Test the creation of a model with a ManyToMany field and the\", \"test_create_model_with_constraint (migrations.test_operations.OperationTests)\", \"test_create_model_with_deferred_unique_constraint (migrations.test_operations.OperationTests)\", \"test_create_model_with_duplicate_base (migrations.test_operations.OperationTests)\", \"test_create_model_with_duplicate_field_name (migrations.test_operations.OperationTests)\", \"test_create_model_with_duplicate_manager_name (migrations.test_operations.OperationTests)\", \"test_create_model_with_partial_unique_constraint (migrations.test_operations.OperationTests)\", \"Tests the CreateModel operation directly followed by an\", \"CreateModel ignores proxy models.\", \"CreateModel ignores unmanaged models.\", \"Tests the DeleteModel operation.\", \"test_delete_mti_model (migrations.test_operations.OperationTests)\", \"Tests the DeleteModel operation ignores proxy models.\", \"A model with BigAutoField can be created.\", \"test_remove_constraint (migrations.test_operations.OperationTests)\", \"test_remove_covering_unique_constraint (migrations.test_operations.OperationTests)\", \"test_remove_deferred_unique_constraint (migrations.test_operations.OperationTests)\", \"Tests the RemoveField operation.\", \"test_remove_field_m2m (migrations.test_operations.OperationTests)\", \"test_remove_field_m2m_with_through (migrations.test_operations.OperationTests)\", \"Tests the RemoveField operation on a foreign key.\", \"test_remove_func_index (migrations.test_operations.OperationTests)\", \"test_remove_func_unique_constraint (migrations.test_operations.OperationTests)\", \"Test the RemoveIndex operation.\", \"test_remove_index_state_forwards (migrations.test_operations.OperationTests)\", \"test_remove_partial_unique_constraint (migrations.test_operations.OperationTests)\", \"Tests the RenameField operation.\", \"test_rename_field_case (migrations.test_operations.OperationTests)\", \"If RenameField doesn't reload state appropriately, the AlterField\", \"test_rename_field_with_db_column (migrations.test_operations.OperationTests)\", \"RenameModel renames a many-to-many column after a RenameField.\", \"test_rename_m2m_target_model (migrations.test_operations.OperationTests)\", \"test_rename_m2m_through_model (migrations.test_operations.OperationTests)\", \"test_rename_missing_field (migrations.test_operations.OperationTests)\", \"Tests the RenameModel operation.\", \"RenameModel operations shouldn't trigger the caching of rendered apps\", \"test_rename_model_with_m2m (migrations.test_operations.OperationTests)\", \"Tests the RenameModel operation on model with self referential FK.\", \"test_rename_model_with_self_referential_m2m (migrations.test_operations.OperationTests)\", \"Tests the RenameModel operation on a model which has a superclass that\", \"test_rename_referenced_field_state_forward (migrations.test_operations.OperationTests)\", \"test_repoint_field_m2m (migrations.test_operations.OperationTests)\", \"Tests the RunPython operation\", \"Tests the RunPython operation correctly handles the \\\"atomic\\\" keyword\", \"#24098 - Tests no-op RunPython operations.\", \"#24282 - Model changes to a FK reverse side update the model\", \"Tests the RunSQL operation.\", \"test_run_sql_add_missing_semicolon_on_collect_sql (migrations.test_operations.OperationTests)\", \"#24098 - Tests no-op RunSQL operations.\", \"#23426 - RunSQL should accept parameters.\", \"#23426 - RunSQL should fail when a list of statements with an incorrect\", \"Tests the SeparateDatabaseAndState operation.\", \"A complex SeparateDatabaseAndState operation: Multiple operations both\", \"A field may be migrated from SmallAutoField to AutoField.\", \"A field may be migrated from SmallAutoField to BigAutoField.\"]", "environment_setup_commit": "647480166bfe7532e8c471fef0146e3a17e6c0c9", "test_directives": ["migrations.test_operations"], "test_cmd": "./tests/runtests.py --verbosity 2 migrations.test_operations", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["migrations.test_optimizer"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/contrib/contenttypes/management/__init__.py b/django/contrib/contenttypes/management/__init__.py\nindex 4971fa0c4b..1944b7e887 100644\n--- a/django/contrib/contenttypes/management/__init__.py\n+++ b/django/contrib/contenttypes/management/__init__.py\n@@ -37,10 +37,12 @@ class RenameContentType(migrations.RunPython):\n ContentType.objects.clear_cache()\n \n def rename_forward(self, apps, schema_editor):\n- self._rename(apps, schema_editor, self.old_model, self.new_model)\n+ if self.old_model != self.new_model:\n+ self._rename(apps, schema_editor, self.old_model, self.new_model)\n \n def rename_backward(self, apps, schema_editor):\n- self._rename(apps, schema_editor, self.new_model, self.old_model)\n+ if self.old_model != self.new_model:\n+ self._rename(apps, schema_editor, self.new_model, self.old_model)\n \n \n def inject_rename_contenttypes_operations(plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs):\n\ndiff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py\nindex f0c81c123b..783a5fd6a8 100644\n--- a/django/db/backends/sqlite3/schema.py\n+++ b/django/db/backends/sqlite3/schema.py\n@@ -84,6 +84,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):\n return False\n \n def alter_db_table(self, model, old_db_table, new_db_table, disable_constraints=True):\n+ if old_db_table == new_db_table:\n+ return\n if (not self.connection.features.supports_atomic_references_rename and\n disable_constraints and self._is_referenced_by_fk_constraint(old_db_table)):\n if self.connection.in_atomic_block:\n", "model_lint_repair_patch": "diff --git a/django/contrib/contenttypes/management/__init__.py b/django/contrib/contenttypes/management/__init__.py\nindex 4971fa0c4b..1944b7e887 100644\n--- a/django/contrib/contenttypes/management/__init__.py\n+++ b/django/contrib/contenttypes/management/__init__.py\n@@ -37,10 +37,12 @@ class RenameContentType(migrations.RunPython):\n ContentType.objects.clear_cache()\n \n def rename_forward(self, apps, schema_editor):\n- self._rename(apps, schema_editor, self.old_model, self.new_model)\n+ if self.old_model != self.new_model:\n+ self._rename(apps, schema_editor, self.old_model, self.new_model)\n \n def rename_backward(self, apps, schema_editor):\n- self._rename(apps, schema_editor, self.new_model, self.old_model)\n+ if self.old_model != self.new_model:\n+ self._rename(apps, schema_editor, self.new_model, self.old_model)\n \n \n def inject_rename_contenttypes_operations(plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs):\n\ndiff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py\nindex f0c81c123b..783a5fd6a8 100644\n--- a/django/db/backends/sqlite3/schema.py\n+++ b/django/db/backends/sqlite3/schema.py\n@@ -84,6 +84,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):\n return False\n \n def alter_db_table(self, model, old_db_table, new_db_table, disable_constraints=True):\n+ if old_db_table == new_db_table:\n+ return\n if (not self.connection.features.supports_atomic_references_rename and\n disable_constraints and self._is_referenced_by_fk_constraint(old_db_table)):\n if self.connection.in_atomic_block:\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["migrations.test_optimizer"]} +{"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-23562", "base_commit": "29a86636a9c45ab5ac4d80ac76eaee497f460dce", "patch": "diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py\n--- a/lib/mpl_toolkits/mplot3d/art3d.py\n+++ b/lib/mpl_toolkits/mplot3d/art3d.py\n@@ -867,9 +867,19 @@ def set_alpha(self, alpha):\n self.stale = True\n \n def get_facecolor(self):\n+ # docstring inherited\n+ # self._facecolors2d is not initialized until do_3d_projection\n+ if not hasattr(self, '_facecolors2d'):\n+ self.axes.M = self.axes.get_proj()\n+ self.do_3d_projection()\n return self._facecolors2d\n \n def get_edgecolor(self):\n+ # docstring inherited\n+ # self._edgecolors2d is not initialized until do_3d_projection\n+ if not hasattr(self, '_edgecolors2d'):\n+ self.axes.M = self.axes.get_proj()\n+ self.do_3d_projection()\n return self._edgecolors2d\n \n \n", "test_patch": "diff --git a/lib/mpl_toolkits/tests/test_mplot3d.py b/lib/mpl_toolkits/tests/test_mplot3d.py\n--- a/lib/mpl_toolkits/tests/test_mplot3d.py\n+++ b/lib/mpl_toolkits/tests/test_mplot3d.py\n@@ -1812,6 +1812,28 @@ def test_scatter_spiral():\n fig.canvas.draw()\n \n \n+def test_Poly3DCollection_get_facecolor():\n+ # Smoke test to see that get_facecolor does not raise\n+ # See GH#4067\n+ y, x = np.ogrid[1:10:100j, 1:10:100j]\n+ z2 = np.cos(x) ** 3 - np.sin(y) ** 2\n+ fig = plt.figure()\n+ ax = fig.add_subplot(111, projection='3d')\n+ r = ax.plot_surface(x, y, z2, cmap='hot')\n+ r.get_facecolor()\n+\n+\n+def test_Poly3DCollection_get_edgecolor():\n+ # Smoke test to see that get_edgecolor does not raise\n+ # See GH#4067\n+ y, x = np.ogrid[1:10:100j, 1:10:100j]\n+ z2 = np.cos(x) ** 3 - np.sin(y) ** 2\n+ fig = plt.figure()\n+ ax = fig.add_subplot(111, projection='3d')\n+ r = ax.plot_surface(x, y, z2, cmap='hot')\n+ r.get_edgecolor()\n+\n+\n @pytest.mark.parametrize(\n \"vertical_axis, proj_expected, axis_lines_expected, tickdirs_expected\",\n [\n", "problem_statement": "'Poly3DCollection' object has no attribute '_facecolors2d'\nThe following minimal example demonstrates the issue:\n\n```\nimport numpy as np\nimport matplotlib.tri as mtri\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ny,x = np.ogrid[1:10:100j, 1:10:100j]\nz2 = np.cos(x)**3 - np.sin(y)**2\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nr = ax.plot_surface(x,y,z2, cmap='hot')\nr.get_facecolors()\n```\n\nIt fails on the last line with the following traceback:\n\n```\nAttributeError Traceback (most recent call last)\n in ()\n----> 1 r.get_facecolors()\n\n/home/oliver/.virtualenvs/mpl/local/lib/python2.7/site-packages/mpl_toolkits/mplot3d/art3d.pyc in get_facecolors(self)\n 634\n 635 def get_facecolors(self):\n--> 636 return self._facecolors2d\n 637 get_facecolor = get_facecolors\n 638\n\nAttributeError: 'Poly3DCollection' object has no attribute '_facecolors2d'\n```\n\nTested with mpl versions 1.3.1 and 1.4.2.\n\nSent here by Benjamin, from the mpl users mailing list (mail with the same title). Sorry for dumping this without more assistance, I'm not yet at a python level where I can help in debugging, I think (well, it seems daunting).\n\n", "hints_text": "Ok, I have a \"fix\", in the sense that that attribute will be defined upon initialization. However, for your example, the facecolors returned is completely useless ([[0, 0, 1, 1]] -- all blue, which is default). I suspect that there is a deeper problem with ScalarMappables in general in that they don't set their facecolors until draw time?\n\nThe solution is to probably force the evaluation of the norm + cmap in `get_facecolors`.\n\nThe bigger question I have is if regular PolyCollections that are\nScalarMappables suffer from the same problem?\n\nOn Sat, Feb 7, 2015 at 6:42 PM, Thomas A Caswell notifications@github.com\nwrote:\n\n> The solution is to probably force the evaluation of the norm + cmap in\n> get_facecolors.\n> \n> \u2014\n> Reply to this email directly or view it on GitHub\n> https://github.com/matplotlib/matplotlib/issues/4067#issuecomment-73389124\n> .\n\nPR #4090 addresses this. Although, it still doesn't return any useful\nvalue... it just does the same thing that regular PolyCollections do.\n\nOn Mon, Feb 9, 2015 at 3:47 PM, Thomas A Caswell notifications@github.com\nwrote:\n\n> Assigned #4067 https://github.com/matplotlib/matplotlib/issues/4067 to\n> @WeatherGod https://github.com/WeatherGod.\n> \n> \u2014\n> Reply to this email directly or view it on GitHub\n> https://github.com/matplotlib/matplotlib/issues/4067#event-232758504.\n\nI believe I'm still running into this issue today. Below is the error message I receive when attempting to convert hb_made (a hexbin PolyCollection) into a Poly3DCollection. Are there any other ways to convert 2D PolyCollections into 3D PolyCollections?\n\n```\nax.add_collection3d(hb_made, zs=shotNumber.get_array(), zdir='y')\n```\n\n File \"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py\", line 2201, in add_collection3d\n art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir)\n File \"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/art3d.py\", line 716, in poly_collection_2d_to_3d\n col.set_3d_properties()\n File \"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/art3d.py\", line 595, in set_3d_properties\n self._edgecolors3d = PolyCollection.get_edgecolors(self)\n File \"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/collections.py\", line 626, in get_edgecolor\n return self.get_facecolors()\n File \"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/art3d.py\", line 699, in get_facecolors\n return self._facecolors2d\nAttributeError: 'Poly3DCollection' object has no attribute '_facecolors2d'\n\nI don't know if this is the appropriate place to post this, but here is a temporary fix for anyone who is waiting on the permanent fix.\r\n\r\nI encounter this same error when trying to add a legend to my 3D surface plot.\r\n\r\n```\r\nsurf = axarr[0].plot_surface(XSrc, YAmb, XCorrMeanDepthErrs[CodingScheme], label=CodingScheme, \r\n\t\t\t\t\t\talpha=.5, facecolor=color, edgecolor='black', linewidth=2)\r\naxarr[0].legend()\r\n```\r\n\r\nWhile a permanent fix is find, I found that a simple temporary fix is to explicitly set the `_facecolors2d` and `_edgecolors2d` parameters after creating the surface plot.\r\n\r\n```\r\nsurf = axarr[0].plot_surface(XSrc, YAmb, XCorrMeanDepthErrs[CodingScheme], label=CodingScheme, \r\n\t\t\t\t\t\talpha=.5, facecolor=color, edgecolor='black', linewidth=2)\r\nsurf._facecolors2d=surf._facecolors3d\r\nsurf._edgecolors2d=surf._edgecolors3d\r\naxarr[0].legend()\r\n```\r\n\nI also could not get the legend to show in my 3d plot of planes with the error:\"AttributeError: 'Poly3DCollection' object has no attribute '_edgecolors2d'\". \r\n\r\nAlthough the fix from @felipegb94 worked: \r\nsurf._facecolors2d=surf._facecolors3d\r\nsurf._edgecolors2d=surf._edgecolors3d\r\n\r\n\nI'm remilestoning this to keep it on the radar. \nI run into this today, but now even the workaround (https://github.com/matplotlib/matplotlib/issues/4067#issuecomment-357794003) is not working any more.\nI ran into this today, with version 3.3.1.post1012+g5584ba764, the workaround did the trick.\nI ran in to this as well, and the fix works in version 3.3.1 but not in 3.3.3\n@bootje2000 Apparently some attributes have been renamed or moved around (prima facie). Try this slight modification to @felipegb94's workaround:\r\n```\r\nsurf._facecolors2d = surf._facecolor3d\r\nsurf._edgecolors2d = surf._edgecolor3d\r\n```\r\nNote the lack of \"s\" on the RHS. `_facecolors3d` and `_edgecolors3d` do not seem to exist anymore.\r\n\r\nThis works in `matplotlib 3.3.3` as of January 04, 2021.\nNone of the workarounds work in matplotlib 3.5.1\r\nIt works after modifying for the available attributes `_facecolors `and `_edgecolors`:\r\n`surf._facecolors2d = surf._facecolors`\r\n`surf._edgecolors2d = surf._edgecolors`\r\n\r\nHint: if there are multiple surfaces on the same axes, the workaround must be applied to each surface individually.\n@nina-wwc I just checked the minimal working example in this thread using `matplotlib-3.5.1` and `3.5.2` (latest) and my workaround works as it did before, as does yours. Could you test the example code in a virtual environment perhaps, if you haven't already done so?\nThe problem still is that we update some state during the draw process. Internally we do the updating and the access in just the right order so that in most cases we do not notice that we also add the attributes on the fly. \r\n\r\nThe best workaround for the current case (assuming 3.5):\r\n\r\n```python\r\nimport numpy as np\r\nimport matplotlib.tri as mtri\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\ny,x = np.ogrid[1:10:100j, 1:10:100j]\r\nz2 = np.cos(x)**3 - np.sin(y)**2\r\nfig = plt.figure()\r\nax = fig.add_subplot(111, projection='3d')\r\nr = ax.plot_surface(x,y,z2, cmap='hot')\r\nfig.draw_without_rendering() # <--- This is the key line\r\nr.get_facecolors()\r\n```\r\n\r\nHowever, I still think the best solution is https://github.com/matplotlib/matplotlib/issues/4067#issuecomment-73389124 which will require looking in `get_facecolors` to detect when these attributes are missing (and if stale?) and then force what ever needs to be done to update them.\r\n\r\nLabeling this as a good first issue because it clearly has affected a lot of people for a long time, there is a very clear reproduction example (that will make a perfect test), and there are no API design choices to be made, but medium difficulty because it will require understanding some slightly tricking inheritance and how our 3D artists draw them selves. ", "created_at": "2022-08-05T13:44:06Z", "version": "3.5", "FAIL_TO_PASS": "[\"lib/mpl_toolkits/tests/test_mplot3d.py::test_Poly3DCollection_get_facecolor\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_Poly3DCollection_get_edgecolor\"]", "PASS_TO_PASS": "[\"lib/mpl_toolkits/tests/test_mplot3d.py::test_invisible_axes[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_aspects[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_repr\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_colors\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_shaded[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_notshaded[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_lightsource\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contour3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contour3d_extend3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_fill[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_extend[png-both-levels0]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_extend[png-min-levels1]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_extend[png-max-levels2]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_tricontour[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_contour3d_1d_input\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_lines3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_plot_scalar[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_mixedsubplots[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_tight_layout_text[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_color[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_linewidth[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_linewidth_modification[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_modification[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_sorting[png-True]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_sorting[png-False]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_marker_draw_order_data_reversed[png--50]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_marker_draw_order_data_reversed[png-130]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_marker_draw_order_view_rotated[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_plot_3d_from_2d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d_shaded[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d_masked[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d_masked_strides[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_text3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_text3d_modification[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_trisurf3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_trisurf3d_shaded[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3dzerocstride[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3dzerorstride[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3dzerostrideraises\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_mixedsamplesraises\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3d_empty[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3d_masked[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_patch_modification\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_patch_collection_modification[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_poly3dcollection_verts_validation\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_poly3dcollection_closed[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_poly_collection_2d_to_3d_empty\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_poly3dcollection_alpha[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_add_collection3d_zs_array[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_add_collection3d_zs_scalar[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_labelpad[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_cla[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_rotated[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_plotsurface_1d_raises\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_proj_transform\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_proj_axes_cube[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_proj_axes_cube_ortho[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_rot\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_world\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_lines_dists[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_lines_dists_nowarning\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_autoscale\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[True-x]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[True-y]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[True-z]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[False-x]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[False-y]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[False-z]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[None-x]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[None-y]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[None-z]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_focal_length_checks\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_focal_length[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_ortho[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_isometric[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-left-inf]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-left-nan]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-right-inf]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-right-nan]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-bottom-inf]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-bottom-nan]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-top-inf]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-top-nan]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-bottom-inf]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-bottom-nan]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-top-inf]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-top-nan]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_simple[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_edge_style[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_named_colors[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_rgb_data[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_alpha[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_xyz[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_calling_conventions\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_line3d_set_get_data_3d\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_inverted[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_inverted_cla\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_ax3d_tickcolour\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_ticklabel_format[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3D_smoke[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_minor_ticks[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_errorbar3d_errorevery[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_errorbar3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_stem3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_equal_box_aspect[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_colorbar_pos\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_shared_axes_retick\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_pan\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scalarmap_update[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_subfigure_simple\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_computed_zorder[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_format_coord\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_get_axis_position\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[ValueError-args0-kwargs0-margin\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[ValueError-args1-kwargs1-margin\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[ValueError-args2-kwargs2-margin\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[ValueError-args3-kwargs3-margin\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[ValueError-args4-kwargs4-margin\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[ValueError-args5-kwargs5-margin\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[TypeError-args6-kwargs6-Cannot\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[TypeError-args7-kwargs7-Cannot\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[TypeError-args8-kwargs8-Cannot\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_margins_errors[TypeError-args9-kwargs9-Must\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_text_3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_pathpatch_3d[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter_spiral[png]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_view_init_vertical_axis[z-proj_expected0-axis_lines_expected0-tickdirs_expected0]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_view_init_vertical_axis[y-proj_expected1-axis_lines_expected1-tickdirs_expected1]\", \"lib/mpl_toolkits/tests/test_mplot3d.py::test_view_init_vertical_axis[x-proj_expected2-axis_lines_expected2-tickdirs_expected2]\"]", "environment_setup_commit": "de98877e3dc45de8dd441d008f23d88738dc015d", "test_directives": ["lib/mpl_toolkits/tests/test_mplot3d.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v lib/mpl_toolkits/tests/test_mplot3d.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["lib/matplotlib/tests/test_collections.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py\nindex 8fe6e7a9c1..85199af83f 100644\n--- a/lib/mpl_toolkits/mplot3d/art3d.py\n+++ b/lib/mpl_toolkits/mplot3d/art3d.py\n@@ -680,6 +680,17 @@ class Poly3DCollection(PolyCollection):\n `~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_trisurf`, which creates a\n triangulation and thus generates consistent surfaces.\n \"\"\"\n+ def __init__(self, verts, *args, zsort='average', **kwargs):\n+ super().__init__(verts, *args, **kwargs)\n+ if isinstance(verts, np.ndarray):\n+ if verts.ndim != 3:\n+ raise ValueError('verts must be a list of (N, 3) array-like')\n+ else:\n+ if any(len(np.shape(vert)) != 2 for vert in verts):\n+ raise ValueError('verts must be a list of (N, 3) array-like')\n+ self.set_zsort(zsort)\n+ self._codes3d = None\n+ self._facecolors2d = np.empty((0, 4)) # Initialize _facecolors2d\n \n def __init__(self, verts, *args, zsort='average', **kwargs):\n \"\"\"\n", "model_lint_repair_patch": "diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py\nindex 8fe6e7a9c1..85199af83f 100644\n--- a/lib/mpl_toolkits/mplot3d/art3d.py\n+++ b/lib/mpl_toolkits/mplot3d/art3d.py\n@@ -680,6 +680,17 @@ class Poly3DCollection(PolyCollection):\n `~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_trisurf`, which creates a\n triangulation and thus generates consistent surfaces.\n \"\"\"\n+ def __init__(self, verts, *args, zsort='average', **kwargs):\n+ super().__init__(verts, *args, **kwargs)\n+ if isinstance(verts, np.ndarray):\n+ if verts.ndim != 3:\n+ raise ValueError('verts must be a list of (N, 3) array-like')\n+ else:\n+ if any(len(np.shape(vert)) != 2 for vert in verts):\n+ raise ValueError('verts must be a list of (N, 3) array-like')\n+ self.set_zsort(zsort)\n+ self._codes3d = None\n+ self._facecolors2d = np.empty((0, 4)) # Initialize _facecolors2d\n \n def __init__(self, verts, *args, zsort='average', **kwargs):\n \"\"\"\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["lib/matplotlib/tests/test_collections.py"]} +{"repo": "django/django", "instance_id": "django__django-14580", "base_commit": "36fa071d6ebd18a61c4d7f1b5c9d17106134bd44", "patch": "diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py\n--- a/django/db/migrations/serializer.py\n+++ b/django/db/migrations/serializer.py\n@@ -273,7 +273,7 @@ def _format(self):\n class TypeSerializer(BaseSerializer):\n def serialize(self):\n special_cases = [\n- (models.Model, \"models.Model\", []),\n+ (models.Model, \"models.Model\", ['from django.db import models']),\n (type(None), 'type(None)', []),\n ]\n for case, string, imports in special_cases:\n", "test_patch": "diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py\n--- a/tests/migrations/test_writer.py\n+++ b/tests/migrations/test_writer.py\n@@ -658,6 +658,13 @@ def test_serialize_functools_partialmethod(self):\n def test_serialize_type_none(self):\n self.assertSerializedEqual(type(None))\n \n+ def test_serialize_type_model(self):\n+ self.assertSerializedEqual(models.Model)\n+ self.assertSerializedResultEqual(\n+ MigrationWriter.serialize(models.Model),\n+ (\"('models.Model', {'from django.db import models'})\", set()),\n+ )\n+\n def test_simple_migration(self):\n \"\"\"\n Tests serializing a simple migration.\n", "problem_statement": "Missing import statement in generated migration (NameError: name 'models' is not defined)\nDescription\n\t\nI found a bug in Django's latest release: 3.2.4. \nGiven the following contents of models.py:\nfrom django.db import models\nclass MyField(models.TextField):\n\tpass\nclass MyBaseModel(models.Model):\n\tclass Meta:\n\t\tabstract = True\nclass MyMixin:\n\tpass\nclass MyModel(MyMixin, MyBaseModel):\n\tname = MyField(primary_key=True)\nThe makemigrations command will generate the following migration file:\n# Generated by Django 3.2.4 on 2021-06-30 19:13\nimport app.models\nfrom django.db import migrations\nclass Migration(migrations.Migration):\n\tinitial = True\n\tdependencies = [\n\t]\n\toperations = [\n\t\tmigrations.CreateModel(\n\t\t\tname='MyModel',\n\t\t\tfields=[\n\t\t\t\t('name', app.models.MyField(primary_key=True, serialize=False)),\n\t\t\t],\n\t\t\toptions={\n\t\t\t\t'abstract': False,\n\t\t\t},\n\t\t\tbases=(app.models.MyMixin, models.Model),\n\t\t),\n\t]\nWhich will then fail with the following error:\n File \"/home/jj/django_example/app/migrations/0001_initial.py\", line 7, in \n\tclass Migration(migrations.Migration):\n File \"/home/jj/django_example/app/migrations/0001_initial.py\", line 23, in Migration\n\tbases=(app.models.MyMixin, models.Model),\nNameError: name 'models' is not defined\nExpected behavior: Django generates a migration file that is valid Python.\nActual behavior: Django generates a migration file that is missing an import statement.\nI think this is a bug of the module django.db.migrations.writer, but I'm not sure. I will be happy to assist with debugging.\nThanks for your attention,\nJaap Joris\n", "hints_text": "I could reproduce the issue with 3.2.4, 2.2.24 and the main branch. For what it's worth, the issue doesn't occur if the class MyModel does inherit from MyMixin.\nMyBaseModel is not necessary to reproduce this issue, it's due to the fact that MyModel doesn't have fields from django.db.models and has custom bases. It looks like an issue with special casing of models.Model in TypeSerializer. Proposed patch diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index e19c881cda..6e78462e95 100644 --- a/django/db/migrations/serializer.py +++ b/django/db/migrations/serializer.py @@ -273,7 +273,7 @@ class TupleSerializer(BaseSequenceSerializer): class TypeSerializer(BaseSerializer): def serialize(self): special_cases = [ - (models.Model, \"models.Model\", []), + (models.Model, \"models.Model\", ['from django.db import models']), (type(None), 'type(None)', []), ] for case, string, imports in special_cases:", "created_at": "2021-07-01T07:38:03Z", "version": "4.0", "FAIL_TO_PASS": "[\"test_serialize_type_model (migrations.test_writer.WriterTests)\"]", "PASS_TO_PASS": "[\"test_args_kwargs_signature (migrations.test_writer.OperationWriterTests)\", \"test_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_empty_signature (migrations.test_writer.OperationWriterTests)\", \"test_expand_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_kwargs_signature (migrations.test_writer.OperationWriterTests)\", \"test_multiline_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_nested_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_nested_operation_expand_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_custom_operation (migrations.test_writer.WriterTests)\", \"test_deconstruct_class_arguments (migrations.test_writer.WriterTests)\", \"Test comments at top of file.\", \"test_migration_path (migrations.test_writer.WriterTests)\", \"django.db.models shouldn't be imported if unused.\", \"test_register_non_serializer (migrations.test_writer.WriterTests)\", \"test_register_serializer (migrations.test_writer.WriterTests)\", \"test_serialize_builtin_types (migrations.test_writer.WriterTests)\", \"test_serialize_builtins (migrations.test_writer.WriterTests)\", \"test_serialize_choices (migrations.test_writer.WriterTests)\", \"Ticket #22943: Test serialization of class-based validators, including\", \"test_serialize_collections (migrations.test_writer.WriterTests)\", \"Make sure compiled regex can be serialized.\", \"test_serialize_constants (migrations.test_writer.WriterTests)\", \"test_serialize_datetime (migrations.test_writer.WriterTests)\", \"Ticket #22679: makemigrations generates invalid code for (an empty\", \"test_serialize_enums (migrations.test_writer.WriterTests)\", \"test_serialize_fields (migrations.test_writer.WriterTests)\", \"test_serialize_frozensets (migrations.test_writer.WriterTests)\", \"test_serialize_functions (migrations.test_writer.WriterTests)\", \"test_serialize_functools_partial (migrations.test_writer.WriterTests)\", \"test_serialize_functools_partialmethod (migrations.test_writer.WriterTests)\", \"test_serialize_iterators (migrations.test_writer.WriterTests)\", \"test_serialize_lazy_objects (migrations.test_writer.WriterTests)\", \"A reference in a local scope can't be serialized.\", \"test_serialize_managers (migrations.test_writer.WriterTests)\", \"test_serialize_multiline_strings (migrations.test_writer.WriterTests)\", \"test_serialize_nested_class (migrations.test_writer.WriterTests)\", \"test_serialize_numbers (migrations.test_writer.WriterTests)\", \"test_serialize_path_like (migrations.test_writer.WriterTests)\", \"test_serialize_pathlib (migrations.test_writer.WriterTests)\", \"test_serialize_range (migrations.test_writer.WriterTests)\", \"test_serialize_set (migrations.test_writer.WriterTests)\", \"test_serialize_settings (migrations.test_writer.WriterTests)\", \"test_serialize_strings (migrations.test_writer.WriterTests)\", \"test_serialize_timedelta (migrations.test_writer.WriterTests)\", \"test_serialize_type_none (migrations.test_writer.WriterTests)\", \"An unbound method used within a class body can be serialized.\", \"test_serialize_uuid (migrations.test_writer.WriterTests)\", \"Tests serializing a simple migration.\", \"#24155 - Tests ordering of imports.\"]", "environment_setup_commit": "475cffd1d64c690cdad16ede4d5e81985738ceb4", "test_directives": ["migrations.test_writer"], "test_cmd": "./tests/runtests.py --verbosity 2 migrations.test_writer", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/serializers/test_yaml.py b/tests/serializers/test_yaml.py\nindex 6e11b93040..91bd0f00b3 100644\n--- a/tests/serializers/test_yaml.py\n+++ b/tests/serializers/test_yaml.py\n@@ -105,6 +105,31 @@ class YamlSerializerTestCase(SerializersTestBase, TestCase):\n meta_data: []\n \"\"\"\n \n+ def test_generated_migration_includes_models_import(self):\n+ \"\"\"Test that generated migration file includes 'from django.db import models'\"\"\"\n+ migration_content = \"\"\"# Generated by Django 3.2.4 on 2021-06-30 19:13\n+import app.models\n+from django.db import migrations\n+\n+class Migration(migrations.Migration):\n+ initial = True\n+ dependencies = [\n+ ]\n+ operations = [\n+ migrations.CreateModel(\n+ name='MyModel',\n+ fields=[\n+ ('name', app.models.MyField(primary_key=True, serialize=False)),\n+ ],\n+ options={\n+ 'abstract': False,\n+ },\n+ bases=(app.models.MyMixin, models.Model),\n+ ),\n+ ]\n+\"\"\"\n+ self.assertIn(\"from django.db import models\", migration_content)\n+\n @staticmethod\n def _validate_output(serial_str):\n try:\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["serializers.test_yaml"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py\nindex 4918261fb0..2ac908977a 100644\n--- a/django/db/migrations/writer.py\n+++ b/django/db/migrations/writer.py\n@@ -164,11 +164,13 @@ class MigrationWriter:\n \n # django.db.migrations is always used, but models import may not be.\n # If models import exists, merge it with migrations import.\n- if \"from django.db import models\" in imports:\n+ if \"from django.db import models\" in imports or any('models.' in op for op in items[\"operations\"]):\n imports.discard(\"from django.db import models\")\n imports.add(\"from django.db import migrations, models\")\n else:\n imports.add(\"from django.db import migrations\")\n+ if any('models.' in op for op in items[\"operations\"]):\n+ imports.add(\"from django.db import models\")\n \n # Sort imports by the package / module to be imported (the part after\n # \"from\" in \"from ... import ...\" or after \"import\" in \"import ...\").\n", "model_lint_repair_patch": "diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py\nindex 4918261fb0..2ac908977a 100644\n--- a/django/db/migrations/writer.py\n+++ b/django/db/migrations/writer.py\n@@ -164,11 +164,13 @@ class MigrationWriter:\n \n # django.db.migrations is always used, but models import may not be.\n # If models import exists, merge it with migrations import.\n- if \"from django.db import models\" in imports:\n+ if \"from django.db import models\" in imports or any('models.' in op for op in items[\"operations\"]):\n imports.discard(\"from django.db import models\")\n imports.add(\"from django.db import migrations, models\")\n else:\n imports.add(\"from django.db import migrations\")\n+ if any('models.' in op for op in items[\"operations\"]):\n+ imports.add(\"from django.db import models\")\n \n # Sort imports by the package / module to be imported (the part after\n # \"from\" in \"from ... import ...\" or after \"import\" in \"import ...\").\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "sphinx-doc/sphinx", "instance_id": "sphinx-doc__sphinx-8721", "base_commit": "82ef497a8c88f0f6e50d84520e7276bfbf65025d", "patch": "diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py\n--- a/sphinx/ext/viewcode.py\n+++ b/sphinx/ext/viewcode.py\n@@ -182,6 +182,10 @@ 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 == \"singlehtml\":\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": "diff --git a/tests/test_ext_viewcode.py b/tests/test_ext_viewcode.py\n--- a/tests/test_ext_viewcode.py\n+++ b/tests/test_ext_viewcode.py\n@@ -49,6 +49,21 @@ def test_viewcode(app, status, warning):\n ' """\\n') in result\n \n \n+@pytest.mark.sphinx('epub', testroot='ext-viewcode')\n+def test_viewcode_epub_default(app, status, warning):\n+ app.builder.build_all()\n+\n+ assert not (app.outdir / '_modules/spam/mod1.xhtml').exists()\n+\n+\n+@pytest.mark.sphinx('epub', testroot='ext-viewcode',\n+ confoverrides={'viewcode_enable_epub': True})\n+def test_viewcode_epub_enabled(app, status, warning):\n+ app.builder.build_all()\n+\n+ assert (app.outdir / '_modules/spam/mod1.xhtml').exists()\n+\n+\n @pytest.mark.sphinx(testroot='ext-viewcode', tags=['test_linkcode'])\n def test_linkcode(app, status, warning):\n app.builder.build(['objects'])\n", "problem_statement": "viewcode creates pages for epub even if `viewcode_enable_epub=False` on `make html epub`\n**Describe the bug**\r\nviewcode creates pages for epub even if `viewcode_enable_epub=False` on `make html epub`\r\n\r\n**To Reproduce**\r\n```\r\n$ make html epub\r\n```\r\n\r\n**Expected behavior**\r\nmodule pages should not be created for epub by default.\r\n\r\n**Your project**\r\nNo\r\n\r\n**Screenshots**\r\nNo\r\n\r\n**Environment info**\r\n- OS: Mac\r\n- Python version: 3.9.1\r\n- Sphinx version: HEAD of 3.x\r\n- Sphinx extensions: sphinx.ext.viewcode\r\n- Extra tools: No\r\n\r\n**Additional context**\r\nNo\r\n\n", "hints_text": "", "created_at": "2021-01-21T15:36:24Z", "version": "3.5", "FAIL_TO_PASS": "[\"tests/test_ext_viewcode.py::test_viewcode_epub_default\"]", "PASS_TO_PASS": "[\"tests/test_ext_viewcode.py::test_viewcode_epub_enabled\", \"tests/test_ext_viewcode.py::test_linkcode\", \"tests/test_ext_viewcode.py::test_local_source_files\"]", "environment_setup_commit": "4f8cb861e3b29186b38248fe81e4944fd987fcce", "test_directives": ["tests/test_ext_viewcode.py"], "test_cmd": "tox -epy39 -v -- tests/test_ext_viewcode.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/test_ext_viewcode.py b/tests/test_ext_viewcode.py\nindex 79864095b..0faa7a716 100644\n--- a/tests/test_ext_viewcode.py\n+++ b/tests/test_ext_viewcode.py\n@@ -49,6 +49,17 @@ def test_viewcode(app, status, warning):\n ' """\\n') in result\n \n \n+@pytest.mark.sphinx(testroot='ext-viewcode', confoverrides={'viewcode_enable_epub': False})\n+def test_viewcode_no_epub(app, status, warning):\n+ app.builder.build_all()\n+\n+ result = (app.outdir / 'index.html').read_text()\n+ assert 'href=\"_modules/spam/mod1.html#func1\"' not in result\n+ assert 'href=\"_modules/spam/mod2.html#func2\"' not in result\n+ assert 'href=\"_modules/spam/mod1.html#Class1\"' not in result\n+ assert 'href=\"_modules/spam/mod2.html#Class2\"' not in result\n+\n+\n @pytest.mark.sphinx(testroot='ext-viewcode', tags=['test_linkcode'])\n def test_linkcode(app, status, warning):\n app.builder.build(['objects'])\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["tests/test_ext_viewcode.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py\nindex a7d52a91c..060604e25 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", "model_lint_repair_patch": "diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py\nindex a7d52a91c..060604e25 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", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "pylint-dev/pylint", "instance_id": "pylint-dev__pylint-7993", "base_commit": "e90702074e68e20dc8e5df5013ee3ecf22139c3e", "patch": "diff --git a/pylint/reporters/text.py b/pylint/reporters/text.py\n--- a/pylint/reporters/text.py\n+++ b/pylint/reporters/text.py\n@@ -175,7 +175,7 @@ def on_set_current_module(self, module: str, filepath: str | None) -> None:\n self._template = template\n \n # Check to see if all parameters in the template are attributes of the Message\n- arguments = re.findall(r\"\\{(.+?)(:.*)?\\}\", template)\n+ arguments = re.findall(r\"\\{(\\w+?)(:.*)?\\}\", template)\n for argument in arguments:\n if argument[0] not in MESSAGE_FIELDS:\n warnings.warn(\n", "test_patch": "diff --git a/tests/reporters/unittest_reporting.py b/tests/reporters/unittest_reporting.py\n--- a/tests/reporters/unittest_reporting.py\n+++ b/tests/reporters/unittest_reporting.py\n@@ -14,6 +14,7 @@\n from typing import TYPE_CHECKING\n \n import pytest\n+from _pytest.recwarn import WarningsRecorder\n \n from pylint import checkers\n from pylint.interfaces import HIGH\n@@ -88,16 +89,12 @@ def test_template_option_non_existing(linter) -> None:\n \"\"\"\n output = StringIO()\n linter.reporter.out = output\n- linter.config.msg_template = (\n- \"{path}:{line}:{a_new_option}:({a_second_new_option:03d})\"\n- )\n+ linter.config.msg_template = \"{path}:{line}:{categ}:({a_second_new_option:03d})\"\n linter.open()\n with pytest.warns(UserWarning) as records:\n linter.set_current_module(\"my_mod\")\n assert len(records) == 2\n- assert (\n- \"Don't recognize the argument 'a_new_option'\" in records[0].message.args[0]\n- )\n+ assert \"Don't recognize the argument 'categ'\" in records[0].message.args[0]\n assert (\n \"Don't recognize the argument 'a_second_new_option'\"\n in records[1].message.args[0]\n@@ -113,7 +110,24 @@ def test_template_option_non_existing(linter) -> None:\n assert out_lines[2] == \"my_mod:2::()\"\n \n \n-def test_deprecation_set_output(recwarn):\n+def test_template_option_with_header(linter: PyLinter) -> None:\n+ output = StringIO()\n+ linter.reporter.out = output\n+ linter.config.msg_template = '{{ \"Category\": \"{category}\" }}'\n+ linter.open()\n+ linter.set_current_module(\"my_mod\")\n+\n+ linter.add_message(\"C0301\", line=1, args=(1, 2))\n+ linter.add_message(\n+ \"line-too-long\", line=2, end_lineno=2, end_col_offset=4, args=(3, 4)\n+ )\n+\n+ out_lines = output.getvalue().split(\"\\n\")\n+ assert out_lines[1] == '{ \"Category\": \"convention\" }'\n+ assert out_lines[2] == '{ \"Category\": \"convention\" }'\n+\n+\n+def test_deprecation_set_output(recwarn: WarningsRecorder) -> None:\n \"\"\"TODO remove in 3.0.\"\"\"\n reporter = BaseReporter()\n # noinspection PyDeprecation\n", "problem_statement": "Using custom braces in message template does not work\n### Bug description\n\nHave any list of errors:\r\n\r\nOn pylint 1.7 w/ python3.6 - I am able to use this as my message template\r\n```\r\n$ pylint test.py --msg-template='{{ \"Category\": \"{category}\" }}'\r\nNo config file found, using default configuration\r\n************* Module [redacted].test\r\n{ \"Category\": \"convention\" }\r\n{ \"Category\": \"error\" }\r\n{ \"Category\": \"error\" }\r\n{ \"Category\": \"convention\" }\r\n{ \"Category\": \"convention\" }\r\n{ \"Category\": \"convention\" }\r\n{ \"Category\": \"error\" }\r\n```\r\n\r\nHowever, on Python3.9 with Pylint 2.12.2, I get the following:\r\n```\r\n$ pylint test.py --msg-template='{{ \"Category\": \"{category}\" }}'\r\n[redacted]/site-packages/pylint/reporters/text.py:206: UserWarning: Don't recognize the argument '{ \"Category\"' in the --msg-template. Are you sure it is supported on the current version of pylint?\r\n warnings.warn(\r\n************* Module [redacted].test\r\n\" }\r\n\" }\r\n\" }\r\n\" }\r\n\" }\r\n\" }\r\n```\r\n\r\nIs this intentional or a bug?\n\n### Configuration\n\n_No response_\n\n### Command used\n\n```shell\npylint test.py --msg-template='{{ \"Category\": \"{category}\" }}'\n```\n\n\n### Pylint output\n\n```shell\n[redacted]/site-packages/pylint/reporters/text.py:206: UserWarning: Don't recognize the argument '{ \"Category\"' in the --msg-template. Are you sure it is supported on the current version of pylint?\r\n warnings.warn(\r\n************* Module [redacted].test\r\n\" }\r\n\" }\r\n\" }\r\n\" }\r\n\" }\r\n\" }\n```\n\n\n### Expected behavior\n\nExpect the dictionary to print out with `\"Category\"` as the key.\n\n### Pylint version\n\n```shell\nAffected Version:\r\npylint 2.12.2\r\nastroid 2.9.2\r\nPython 3.9.9+ (heads/3.9-dirty:a2295a4, Dec 21 2021, 22:32:52) \r\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]\r\n\r\n\r\nPreviously working version:\r\nNo config file found, using default configuration\r\npylint 1.7.4, \r\nastroid 1.6.6\r\nPython 3.6.8 (default, Nov 16 2020, 16:55:22) \r\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]\n```\n\n\n### OS / Environment\n\n_No response_\n\n### Additional dependencies\n\n_No response_\n", "hints_text": "Subsequently, there is also this behavior with the quotes\r\n```\r\n$ pylint test.py --msg-template='\"Category\": \"{category}\"'\r\n************* Module test\r\nCategory\": \"convention\r\nCategory\": \"error\r\nCategory\": \"error\r\nCategory\": \"convention\r\nCategory\": \"convention\r\nCategory\": \"error\r\n\r\n$ pylint test.py --msg-template='\"\"Category\": \"{category}\"\"'\r\n************* Module test\r\n\"Category\": \"convention\"\r\n\"Category\": \"error\"\r\n\"Category\": \"error\"\r\n\"Category\": \"convention\"\r\n\"Category\": \"convention\"\r\n\"Category\": \"error\"\r\n```\nCommit that changed the behavior was probably this one: https://github.com/PyCQA/pylint/commit/7c3533ca48e69394391945de1563ef7f639cd27d#diff-76025f0bc82e83cb406321006fbca12c61a10821834a3164620fc17c978f9b7e\r\n\r\nAnd I tested on 2.11.1 that it is working as intended on that version.\nThanks for digging into this !", "created_at": "2022-12-27T18:20:50Z", "version": "2.15", "FAIL_TO_PASS": "[\"tests/reporters/unittest_reporting.py::test_template_option_with_header\"]", "PASS_TO_PASS": "[\"tests/reporters/unittest_reporting.py::test_template_option\", \"tests/reporters/unittest_reporting.py::test_template_option_default\", \"tests/reporters/unittest_reporting.py::test_template_option_end_line\", \"tests/reporters/unittest_reporting.py::test_template_option_non_existing\", \"tests/reporters/unittest_reporting.py::test_deprecation_set_output\", \"tests/reporters/unittest_reporting.py::test_parseable_output_deprecated\", \"tests/reporters/unittest_reporting.py::test_parseable_output_regression\", \"tests/reporters/unittest_reporting.py::test_multi_format_output\", \"tests/reporters/unittest_reporting.py::test_multi_reporter_independant_messages\", \"tests/reporters/unittest_reporting.py::test_display_results_is_renamed\"]", "environment_setup_commit": "e90702074e68e20dc8e5df5013ee3ecf22139c3e", "test_directives": ["tests/reporters/unittest_reporting.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v tests/reporters/unittest_reporting.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["tests/reporters/unittest_reporting.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/pylint/reporters/text.py b/pylint/reporters/text.py\nindex 29bd46798..9b2b64771 100644\n--- a/pylint/reporters/text.py\n+++ b/pylint/reporters/text.py\n@@ -175,14 +175,14 @@ class TextReporter(BaseReporter):\n self._template = template\n \n # Check to see if all parameters in the template are attributes of the Message\n- arguments = re.findall(r\"\\{(.+?)(:.*)?\\}\", template)\n+ arguments = re.findall(r\"\\{([^{}]+?)(:.*)?\\}\", template)\n for argument in arguments:\n if argument[0] not in MESSAGE_FIELDS:\n warnings.warn(\n f\"Don't recognize the argument '{argument[0]}' in the --msg-template. \"\n \"Are you sure it is supported on the current version of pylint?\"\n )\n- template = re.sub(r\"\\{\" + argument[0] + r\"(:.*?)?\\}\", \"\", template)\n+ template = re.sub(r\"\\{\" + re.escape(argument[0]) + r\"(:.*?)?\\}\", \"\", template)\n self._fixed_template = template\n \n def write_message(self, msg: Message) -> None:\n", "model_lint_repair_patch": "diff --git a/pylint/reporters/text.py b/pylint/reporters/text.py\nindex 29bd46798..9b2b64771 100644\n--- a/pylint/reporters/text.py\n+++ b/pylint/reporters/text.py\n@@ -175,14 +175,14 @@ class TextReporter(BaseReporter):\n self._template = template\n \n # Check to see if all parameters in the template are attributes of the Message\n- arguments = re.findall(r\"\\{(.+?)(:.*)?\\}\", template)\n+ arguments = re.findall(r\"\\{([^{}]+?)(:.*)?\\}\", template)\n for argument in arguments:\n if argument[0] not in MESSAGE_FIELDS:\n warnings.warn(\n f\"Don't recognize the argument '{argument[0]}' in the --msg-template. \"\n \"Are you sure it is supported on the current version of pylint?\"\n )\n- template = re.sub(r\"\\{\" + argument[0] + r\"(:.*?)?\\}\", \"\", template)\n+ template = re.sub(r\"\\{\" + re.escape(argument[0]) + r\"(:.*?)?\\}\", \"\", template)\n self._fixed_template = template\n \n def write_message(self, msg: Message) -> None:\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["tests/reporters/unittest_reporting.py"]} +{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-11281", "base_commit": "4143356c3c51831300789e4fdf795d83716dbab6", "patch": "diff --git a/sklearn/mixture/base.py b/sklearn/mixture/base.py\n--- a/sklearn/mixture/base.py\n+++ b/sklearn/mixture/base.py\n@@ -172,7 +172,7 @@ def _initialize(self, X, resp):\n def fit(self, X, y=None):\n \"\"\"Estimate model parameters with the EM algorithm.\n \n- The method fit the model `n_init` times and set the parameters with\n+ The method fits the model `n_init` times and set the parameters with\n which the model has the largest likelihood or lower bound. Within each\n trial, the method iterates between E-step and M-step for `max_iter`\n times until the change of likelihood or lower bound is less than\n@@ -188,6 +188,32 @@ def fit(self, X, y=None):\n -------\n self\n \"\"\"\n+ self.fit_predict(X, y)\n+ return self\n+\n+ def fit_predict(self, X, y=None):\n+ \"\"\"Estimate model parameters using X and predict the labels for X.\n+\n+ The method fits the model n_init times and sets the parameters with\n+ which the model has the largest likelihood or lower bound. Within each\n+ trial, the method iterates between E-step and M-step for `max_iter`\n+ times until the change of likelihood or lower bound is less than\n+ `tol`, otherwise, a `ConvergenceWarning` is raised. After fitting, it\n+ predicts the most probable label for the input data points.\n+\n+ .. versionadded:: 0.20\n+\n+ Parameters\n+ ----------\n+ X : array-like, shape (n_samples, n_features)\n+ List of n_features-dimensional data points. Each row\n+ corresponds to a single data point.\n+\n+ Returns\n+ -------\n+ labels : array, shape (n_samples,)\n+ Component labels.\n+ \"\"\"\n X = _check_X(X, self.n_components, ensure_min_samples=2)\n self._check_initial_parameters(X)\n \n@@ -240,7 +266,7 @@ def fit(self, X, y=None):\n self._set_parameters(best_params)\n self.n_iter_ = best_n_iter\n \n- return self\n+ return log_resp.argmax(axis=1)\n \n def _e_step(self, X):\n \"\"\"E step.\n", "test_patch": "diff --git a/sklearn/mixture/tests/test_bayesian_mixture.py b/sklearn/mixture/tests/test_bayesian_mixture.py\n--- a/sklearn/mixture/tests/test_bayesian_mixture.py\n+++ b/sklearn/mixture/tests/test_bayesian_mixture.py\n@@ -1,12 +1,16 @@\n # Author: Wei Xue \n # Thierry Guillemot \n # License: BSD 3 clause\n+import copy\n \n import numpy as np\n from scipy.special import gammaln\n \n from sklearn.utils.testing import assert_raise_message\n from sklearn.utils.testing import assert_almost_equal\n+from sklearn.utils.testing import assert_array_equal\n+\n+from sklearn.metrics.cluster import adjusted_rand_score\n \n from sklearn.mixture.bayesian_mixture import _log_dirichlet_norm\n from sklearn.mixture.bayesian_mixture import _log_wishart_norm\n@@ -14,7 +18,7 @@\n from sklearn.mixture import BayesianGaussianMixture\n \n from sklearn.mixture.tests.test_gaussian_mixture import RandomData\n-from sklearn.exceptions import ConvergenceWarning\n+from sklearn.exceptions import ConvergenceWarning, NotFittedError\n from sklearn.utils.testing import assert_greater_equal, ignore_warnings\n \n \n@@ -419,3 +423,49 @@ def test_invariant_translation():\n assert_almost_equal(bgmm1.means_, bgmm2.means_ - 100)\n assert_almost_equal(bgmm1.weights_, bgmm2.weights_)\n assert_almost_equal(bgmm1.covariances_, bgmm2.covariances_)\n+\n+\n+def test_bayesian_mixture_fit_predict():\n+ rng = np.random.RandomState(0)\n+ rand_data = RandomData(rng, scale=7)\n+ n_components = 2 * rand_data.n_components\n+\n+ for covar_type in COVARIANCE_TYPE:\n+ bgmm1 = BayesianGaussianMixture(n_components=n_components,\n+ max_iter=100, random_state=rng,\n+ tol=1e-3, reg_covar=0)\n+ bgmm1.covariance_type = covar_type\n+ bgmm2 = copy.deepcopy(bgmm1)\n+ X = rand_data.X[covar_type]\n+\n+ Y_pred1 = bgmm1.fit(X).predict(X)\n+ Y_pred2 = bgmm2.fit_predict(X)\n+ assert_array_equal(Y_pred1, Y_pred2)\n+\n+\n+def test_bayesian_mixture_predict_predict_proba():\n+ # this is the same test as test_gaussian_mixture_predict_predict_proba()\n+ rng = np.random.RandomState(0)\n+ rand_data = RandomData(rng)\n+ for prior_type in PRIOR_TYPE:\n+ for covar_type in COVARIANCE_TYPE:\n+ X = rand_data.X[covar_type]\n+ Y = rand_data.Y\n+ bgmm = BayesianGaussianMixture(\n+ n_components=rand_data.n_components,\n+ random_state=rng,\n+ weight_concentration_prior_type=prior_type,\n+ covariance_type=covar_type)\n+\n+ # Check a warning message arrive if we don't do fit\n+ assert_raise_message(NotFittedError,\n+ \"This BayesianGaussianMixture instance\"\n+ \" is not fitted yet. Call 'fit' with \"\n+ \"appropriate arguments before using \"\n+ \"this method.\", bgmm.predict, X)\n+\n+ bgmm.fit(X)\n+ Y_pred = bgmm.predict(X)\n+ Y_pred_proba = bgmm.predict_proba(X).argmax(axis=1)\n+ assert_array_equal(Y_pred, Y_pred_proba)\n+ assert_greater_equal(adjusted_rand_score(Y, Y_pred), .95)\ndiff --git a/sklearn/mixture/tests/test_gaussian_mixture.py b/sklearn/mixture/tests/test_gaussian_mixture.py\n--- a/sklearn/mixture/tests/test_gaussian_mixture.py\n+++ b/sklearn/mixture/tests/test_gaussian_mixture.py\n@@ -3,6 +3,7 @@\n # License: BSD 3 clause\n \n import sys\n+import copy\n import warnings\n \n import numpy as np\n@@ -569,6 +570,26 @@ def test_gaussian_mixture_predict_predict_proba():\n assert_greater(adjusted_rand_score(Y, Y_pred), .95)\n \n \n+def test_gaussian_mixture_fit_predict():\n+ rng = np.random.RandomState(0)\n+ rand_data = RandomData(rng)\n+ for covar_type in COVARIANCE_TYPE:\n+ X = rand_data.X[covar_type]\n+ Y = rand_data.Y\n+ g = GaussianMixture(n_components=rand_data.n_components,\n+ random_state=rng, weights_init=rand_data.weights,\n+ means_init=rand_data.means,\n+ precisions_init=rand_data.precisions[covar_type],\n+ covariance_type=covar_type)\n+\n+ # check if fit_predict(X) is equivalent to fit(X).predict(X)\n+ f = copy.deepcopy(g)\n+ Y_pred1 = f.fit(X).predict(X)\n+ Y_pred2 = g.fit_predict(X)\n+ assert_array_equal(Y_pred1, Y_pred2)\n+ assert_greater(adjusted_rand_score(Y, Y_pred2), .95)\n+\n+\n def test_gaussian_mixture_fit():\n # recover the ground truth\n rng = np.random.RandomState(0)\n", "problem_statement": "Should mixture models have a clusterer-compatible interface\nMixture models are currently a bit different. They are basically clusterers, except they are probabilistic, and are applied to inductive problems unlike many clusterers. But they are unlike clusterers in API:\r\n* they have an `n_components` parameter, with identical purpose to `n_clusters`\r\n* they do not store the `labels_` of the training data\r\n* they do not have a `fit_predict` method\r\n\r\nAnd they are almost entirely documented separately.\r\n\r\nShould we make the MMs more like clusterers?\n", "hints_text": "In my opinion, yes.\r\n\r\nI wanted to compare K-Means, GMM and HDBSCAN and was very disappointed that GMM does not have a `fit_predict` method. The HDBSCAN examples use `fit_predict`, so I was expecting GMM to have the same interface.\nI think we should add ``fit_predict`` at least. I wouldn't rename ``n_components``.\nI would like to work on this!\n@Eight1911 go for it. It is probably relatively simple but maybe not entirely trivial.\n@Eight1911 Mind if I take a look at this?\n@Eight1911 Do you mind if I jump in as well?", "created_at": "2018-06-15T17:15:25Z", "version": "0.20", "FAIL_TO_PASS": "[\"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_fit_predict\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_predict\"]", "PASS_TO_PASS": "[\"sklearn/mixture/tests/test_bayesian_mixture.py::test_log_dirichlet_norm\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_log_wishart_norm\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_covariance_type\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_weight_concentration_prior_type\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_weights_prior_initialisation\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_means_prior_initialisation\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_precisions_prior_initialisation\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_check_is_fitted\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_weights\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_monotonic_likelihood\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_compare_covar_type\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_check_covariance_precision\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_invariant_translation\", \"sklearn/mixture/tests/test_bayesian_mixture.py::test_bayesian_mixture_predict_predict_proba\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_attributes\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_check_X\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_check_weights\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_check_means\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_check_precisions\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_suffstat_sk_full\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_suffstat_sk_tied\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_suffstat_sk_diag\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_suffstat_sk_spherical\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_compute_log_det_cholesky\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_log_probabilities\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_estimate_log_prob_resp\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_predict_predict_proba\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_best_params\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_convergence_warning\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_multiple_init\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_n_parameters\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_bic_1d_1component\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_aic_bic\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_verbose\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_warm_start\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_score\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_score_samples\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_monotonic_likelihood\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_regularisation\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_property\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_sample\", \"sklearn/mixture/tests/test_gaussian_mixture.py::test_init\"]", "environment_setup_commit": "55bf5d93e5674f13a1134d93a11fd0cd11aabcd1", "test_directives": ["sklearn/mixture/tests/test_bayesian_mixture.py", "sklearn/mixture/tests/test_gaussian_mixture.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v sklearn/mixture/tests/test_bayesian_mixture.py sklearn/mixture/tests/test_gaussian_mixture.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/sklearn/mixture/tests/test_gmm.py b/sklearn/mixture/tests/test_gmm.py\nindex 134c0493c..6500ba182 100644\n--- a/sklearn/mixture/tests/test_gmm.py\n+++ b/sklearn/mixture/tests/test_gmm.py\n@@ -7,6 +7,47 @@\n import unittest\n import copy\n import sys\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n+from sklearn.mixture import GaussianMixture\n \n import pytest\n \n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sklearn/mixture/tests/test_gmm.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/examples/mixture/plot_gmm_covariances.py b/examples/mixture/plot_gmm_covariances.py\nindex 2b4cd8864..0b23e74bd 100644\n--- a/examples/mixture/plot_gmm_covariances.py\n+++ b/examples/mixture/plot_gmm_covariances.py\n@@ -82,7 +82,7 @@ y_test = iris.target[test_index]\n n_classes = len(np.unique(y_train))\n \n # Try GMMs using different types of covariances.\n-estimators = dict((cov_type, GaussianMixture(n_components=n_classes,\n+estimators = dict((cov_type, GaussianMixture(n_clusters=n_classes,\n covariance_type=cov_type, max_iter=20, random_state=0))\n for cov_type in ['spherical', 'diag', 'tied', 'full'])\n \n\ndiff --git a/sklearn/mixture/bayesian_mixture.py b/sklearn/mixture/bayesian_mixture.py\nindex aef6828fa..a9f890c01 100644\n--- a/sklearn/mixture/bayesian_mixture.py\n+++ b/sklearn/mixture/bayesian_mixture.py\n@@ -306,7 +306,7 @@ class BayesianGaussianMixture(BaseMixture):\n `_\n \"\"\"\n \n- def __init__(self, n_components=1, covariance_type='full', tol=1e-3,\n+ def __init__(self, n_components=1, n_clusters=None, covariance_type='full', tol=1e-3,\n reg_covar=1e-6, max_iter=100, n_init=1, init_params='kmeans',\n weight_concentration_prior_type='dirichlet_process',\n weight_concentration_prior=None,\n@@ -314,6 +314,8 @@ class BayesianGaussianMixture(BaseMixture):\n degrees_of_freedom_prior=None, covariance_prior=None,\n random_state=None, warm_start=False, verbose=0,\n verbose_interval=10):\n+ if n_clusters is not None:\n+ n_components = n_clusters\n super(BayesianGaussianMixture, self).__init__(\n n_components=n_components, tol=tol, reg_covar=reg_covar,\n max_iter=max_iter, n_init=n_init, init_params=init_params,\n@@ -327,6 +329,7 @@ class BayesianGaussianMixture(BaseMixture):\n self.mean_prior = mean_prior\n self.degrees_of_freedom_prior = degrees_of_freedom_prior\n self.covariance_prior = covariance_prior\n+ self.labels_ = None\n \n def _check_parameters(self, X):\n \"\"\"Check that the parameters are well defined.\n\ndiff --git a/sklearn/mixture/gaussian_mixture.py b/sklearn/mixture/gaussian_mixture.py\nindex d58a9e326..456eb5e76 100644\n--- a/sklearn/mixture/gaussian_mixture.py\n+++ b/sklearn/mixture/gaussian_mixture.py\n@@ -580,11 +580,13 @@ class GaussianMixture(BaseMixture):\n inference.\n \"\"\"\n \n- def __init__(self, n_components=1, covariance_type='full', tol=1e-3,\n+ def __init__(self, n_components=1, n_clusters=None, covariance_type='full', tol=1e-3,\n reg_covar=1e-6, max_iter=100, n_init=1, init_params='kmeans',\n weights_init=None, means_init=None, precisions_init=None,\n random_state=None, warm_start=False,\n verbose=0, verbose_interval=10):\n+ if n_clusters is not None:\n+ n_components = n_clusters\n super(GaussianMixture, self).__init__(\n n_components=n_components, tol=tol, reg_covar=reg_covar,\n max_iter=max_iter, n_init=n_init, init_params=init_params,\n@@ -595,6 +597,7 @@ class GaussianMixture(BaseMixture):\n self.weights_init = weights_init\n self.means_init = means_init\n self.precisions_init = precisions_init\n+ self.labels_ = None\n \n def _check_parameters(self, X):\n \"\"\"Check the Gaussian mixture parameters are well defined.\"\"\"\n", "model_lint_repair_patch": "diff --git a/examples/mixture/plot_gmm_covariances.py b/examples/mixture/plot_gmm_covariances.py\nindex 2b4cd8864..0b23e74bd 100644\n--- a/examples/mixture/plot_gmm_covariances.py\n+++ b/examples/mixture/plot_gmm_covariances.py\n@@ -82,7 +82,7 @@ y_test = iris.target[test_index]\n n_classes = len(np.unique(y_train))\n \n # Try GMMs using different types of covariances.\n-estimators = dict((cov_type, GaussianMixture(n_components=n_classes,\n+estimators = dict((cov_type, GaussianMixture(n_clusters=n_classes,\n covariance_type=cov_type, max_iter=20, random_state=0))\n for cov_type in ['spherical', 'diag', 'tied', 'full'])\n \n\ndiff --git a/sklearn/mixture/bayesian_mixture.py b/sklearn/mixture/bayesian_mixture.py\nindex aef6828fa..a9f890c01 100644\n--- a/sklearn/mixture/bayesian_mixture.py\n+++ b/sklearn/mixture/bayesian_mixture.py\n@@ -306,7 +306,7 @@ class BayesianGaussianMixture(BaseMixture):\n `_\n \"\"\"\n \n- def __init__(self, n_components=1, covariance_type='full', tol=1e-3,\n+ def __init__(self, n_components=1, n_clusters=None, covariance_type='full', tol=1e-3,\n reg_covar=1e-6, max_iter=100, n_init=1, init_params='kmeans',\n weight_concentration_prior_type='dirichlet_process',\n weight_concentration_prior=None,\n@@ -314,6 +314,8 @@ class BayesianGaussianMixture(BaseMixture):\n degrees_of_freedom_prior=None, covariance_prior=None,\n random_state=None, warm_start=False, verbose=0,\n verbose_interval=10):\n+ if n_clusters is not None:\n+ n_components = n_clusters\n super(BayesianGaussianMixture, self).__init__(\n n_components=n_components, tol=tol, reg_covar=reg_covar,\n max_iter=max_iter, n_init=n_init, init_params=init_params,\n@@ -327,6 +329,7 @@ class BayesianGaussianMixture(BaseMixture):\n self.mean_prior = mean_prior\n self.degrees_of_freedom_prior = degrees_of_freedom_prior\n self.covariance_prior = covariance_prior\n+ self.labels_ = None\n \n def _check_parameters(self, X):\n \"\"\"Check that the parameters are well defined.\n\ndiff --git a/sklearn/mixture/gaussian_mixture.py b/sklearn/mixture/gaussian_mixture.py\nindex d58a9e326..456eb5e76 100644\n--- a/sklearn/mixture/gaussian_mixture.py\n+++ b/sklearn/mixture/gaussian_mixture.py\n@@ -580,11 +580,13 @@ class GaussianMixture(BaseMixture):\n inference.\n \"\"\"\n \n- def __init__(self, n_components=1, covariance_type='full', tol=1e-3,\n+ def __init__(self, n_components=1, n_clusters=None, covariance_type='full', tol=1e-3,\n reg_covar=1e-6, max_iter=100, n_init=1, init_params='kmeans',\n weights_init=None, means_init=None, precisions_init=None,\n random_state=None, warm_start=False,\n verbose=0, verbose_interval=10):\n+ if n_clusters is not None:\n+ n_components = n_clusters\n super(GaussianMixture, self).__init__(\n n_components=n_components, tol=tol, reg_covar=reg_covar,\n max_iter=max_iter, n_init=n_init, init_params=init_params,\n@@ -595,6 +597,7 @@ class GaussianMixture(BaseMixture):\n self.weights_init = weights_init\n self.means_init = means_init\n self.precisions_init = precisions_init\n+ self.labels_ = None\n \n def _check_parameters(self, X):\n \"\"\"Check the Gaussian mixture parameters are well defined.\"\"\"\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sklearn/mixture/tests/test_gmm.py"]} +{"repo": "django/django", "instance_id": "django__django-11422", "base_commit": "df46b329e0900e9e4dc1d60816c1dce6dfc1094e", "patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\n--- a/django/utils/autoreload.py\n+++ b/django/utils/autoreload.py\n@@ -114,7 +114,15 @@ def iter_modules_and_files(modules, extra_files):\n # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects\n # are added to sys.modules, however they are types not modules and so\n # cause issues here.\n- if not isinstance(module, ModuleType) or getattr(module, '__spec__', None) is None:\n+ if not isinstance(module, ModuleType):\n+ continue\n+ if module.__name__ == '__main__':\n+ # __main__ (usually manage.py) doesn't always have a __spec__ set.\n+ # Handle this by falling back to using __file__, resolved below.\n+ # See https://docs.python.org/reference/import.html#main-spec\n+ sys_file_paths.append(module.__file__)\n+ continue\n+ if getattr(module, '__spec__', None) is None:\n continue\n spec = module.__spec__\n # Modules could be loaded from places without a concrete location. If\n", "test_patch": "diff --git a/tests/utils_tests/test_autoreload.py b/tests/utils_tests/test_autoreload.py\n--- a/tests/utils_tests/test_autoreload.py\n+++ b/tests/utils_tests/test_autoreload.py\n@@ -132,6 +132,10 @@ def test_module_without_spec(self):\n del module.__spec__\n self.assertEqual(autoreload.iter_modules_and_files((module,), frozenset()), frozenset())\n \n+ def test_main_module_is_resolved(self):\n+ main_module = sys.modules['__main__']\n+ self.assertFileFound(Path(main_module.__file__))\n+\n \n class TestCommonRoots(SimpleTestCase):\n def test_common_roots(self):\n", "problem_statement": "Autoreloader with StatReloader doesn't track changes in manage.py.\nDescription\n\t \n\t\t(last modified by Mariusz Felisiak)\n\t \nThis is a bit convoluted, but here we go.\nEnvironment (OSX 10.11):\n$ python -V\nPython 3.6.2\n$ pip -V\npip 19.1.1\n$ pip install Django==2.2.1\nSteps to reproduce:\nRun a server python manage.py runserver\nEdit the manage.py file, e.g. add print(): \ndef main():\n\tprint('sth')\n\tos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ticket_30479.settings')\n\t...\nUnder 2.1.8 (and prior), this will trigger the auto-reloading mechanism. Under 2.2.1, it won't. As far as I can tell from the django.utils.autoreload log lines, it never sees the manage.py itself.\n", "hints_text": "Thanks for the report. I simplified scenario. Regression in c8720e7696ca41f3262d5369365cc1bd72a216ca. Reproduced at 8d010f39869f107820421631111417298d1c5bb9.\nArgh. I guess this is because manage.py isn't showing up in the sys.modules. I'm not sure I remember any specific manage.py handling in the old implementation, so I'm not sure how it used to work, but I should be able to fix this pretty easily.\nDone a touch of debugging: iter_modules_and_files is where it gets lost. Specifically, it ends up in there twice: (, , , ...,) But getattr(module, \"__spec__\", None) is None is True so it continues onwards. I thought I managed to get one of them to have a __spec__ attr but no has_location, but I can't seem to get that again (stepping around with pdb) Digging into wtf __spec__ is None: \u200bHere's the py3 docs on it, which helpfully mentions that \u200bThe one exception is __main__, where __spec__ is set to None in some cases\nTom, will you have time to work on this in the next few days?\nI'm sorry for assigning it to myself Mariusz, I intended to work on it on Tuesday but work overtook me and now I am travelling for a wedding this weekend. So I doubt it I'm afraid. It seems Keryn's debugging is a great help, it should be somewhat simple to add special case handling for __main__, while __spec__ is None we can still get the filename and watch on that.\nnp, Tom, thanks for info. Keryn, it looks that you've already made most of the work. Would you like to prepare a patch?", "created_at": "2019-05-27T19:15:21Z", "version": "3.0", "FAIL_TO_PASS": "[\"test_main_module_is_resolved (utils_tests.test_autoreload.TestIterModulesAndFiles)\"]", "PASS_TO_PASS": "[\"test_watchman_available (utils_tests.test_autoreload.GetReloaderTests)\", \"test_watchman_unavailable (utils_tests.test_autoreload.GetReloaderTests)\", \"test_calls_start_django (utils_tests.test_autoreload.RunWithReloaderTests)\", \"test_calls_sys_exit (utils_tests.test_autoreload.RunWithReloaderTests)\", \"test_swallows_keyboard_interrupt (utils_tests.test_autoreload.RunWithReloaderTests)\", \"test_common_roots (utils_tests.test_autoreload.TestCommonRoots)\", \"test_no_exception (utils_tests.test_autoreload.TestRaiseLastException)\", \"test_raises_exception (utils_tests.test_autoreload.TestRaiseLastException)\", \"test_mutates_error_files (utils_tests.test_autoreload.TestCheckErrors)\", \"test_sys_paths_absolute (utils_tests.test_autoreload.TestSysPathDirectories)\", \"test_sys_paths_directories (utils_tests.test_autoreload.TestSysPathDirectories)\", \"test_sys_paths_non_existing (utils_tests.test_autoreload.TestSysPathDirectories)\", \"test_sys_paths_with_directories (utils_tests.test_autoreload.TestSysPathDirectories)\", \"test_manage_py (utils_tests.test_autoreload.RestartWithReloaderTests)\", \"test_python_m_django (utils_tests.test_autoreload.RestartWithReloaderTests)\", \"test_run_loop_catches_stopiteration (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_run_loop_stop_and_return (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_wait_for_apps_ready_checks_for_exception (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_wait_for_apps_ready_without_exception (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_watch_files_with_recursive_glob (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_watch_with_glob (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_watch_with_single_file (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_watch_without_absolute (utils_tests.test_autoreload.BaseReloaderTests)\", \"test_file (utils_tests.test_autoreload.StatReloaderTests)\", \"test_glob (utils_tests.test_autoreload.StatReloaderTests)\", \"test_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)\", \"test_multiple_globs (utils_tests.test_autoreload.StatReloaderTests)\", \"test_multiple_recursive_globs (utils_tests.test_autoreload.StatReloaderTests)\", \"test_nested_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)\", \"test_overlapping_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)\", \"test_overlapping_globs (utils_tests.test_autoreload.StatReloaderTests)\", \"test_snapshot_files_ignores_missing_files (utils_tests.test_autoreload.StatReloaderTests)\", \"test_snapshot_files_updates (utils_tests.test_autoreload.StatReloaderTests)\", \"test_snapshot_files_with_duplicates (utils_tests.test_autoreload.StatReloaderTests)\", \"test_check_errors_called (utils_tests.test_autoreload.StartDjangoTests)\", \"test_echo_on_called (utils_tests.test_autoreload.StartDjangoTests)\", \"test_starts_thread_with_args (utils_tests.test_autoreload.StartDjangoTests)\", \"test_watchman_becomes_unavailable (utils_tests.test_autoreload.StartDjangoTests)\", \".pyc and .pyo files are included in the files list.\", \"test_check_errors (utils_tests.test_autoreload.TestIterModulesAndFiles)\", \"test_check_errors_catches_all_exceptions (utils_tests.test_autoreload.TestIterModulesAndFiles)\", \"test_file_added (utils_tests.test_autoreload.TestIterModulesAndFiles)\", \"test_module_without_spec (utils_tests.test_autoreload.TestIterModulesAndFiles)\", \"test_paths_are_pathlib_instances (utils_tests.test_autoreload.TestIterModulesAndFiles)\", \"iter_all_python_module_file() ignores weakref modules.\", \"test_zip_reload (utils_tests.test_autoreload.TestIterModulesAndFiles)\"]", "environment_setup_commit": "419a78300f7cd27611196e1e464d50fd0385ff27", "test_directives": ["utils_tests.test_autoreload"], "test_cmd": "./tests/runtests.py --verbosity 2 utils_tests.test_autoreload", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/utils_tests/test_autoreload.py b/tests/utils_tests/test_autoreload.py\nindex 42bcd0a50b..b388b365a9 100644\n--- a/tests/utils_tests/test_autoreload.py\n+++ b/tests/utils_tests/test_autoreload.py\n@@ -625,6 +625,19 @@ class StatReloaderTests(ReloaderTests, IntegrationTests):\n # Shorten the sleep time to speed up tests.\n self.reloader.SLEEP_TIME = 0.01\n \n+ @mock.patch('django.utils.autoreload.BaseReloader.notify_file_changed')\n+ @mock.patch('django.utils.autoreload.iter_all_python_module_files', return_value=frozenset())\n+ def test_manage_py_change(self, mocked_modules, notify_mock):\n+ manage_py = self.ensure_file(self.tempdir / 'manage.py')\n+ self.reloader.watch_file(manage_py)\n+ with self.tick_twice():\n+ self.increment_mtime(manage_py)\n+ self.assertEqual(notify_mock.call_count, 1)\n+ self.assertCountEqual(notify_mock.call_args[0], [manage_py])\n+ super().setUp()\n+ # Shorten the sleep time to speed up tests.\n+ self.reloader.SLEEP_TIME = 0.01\n+\n def test_snapshot_files_ignores_missing_files(self):\n with mock.patch.object(self.reloader, 'watched_files', return_value=[self.nonexistent_file]):\n self.assertEqual(dict(self.reloader.snapshot_files()), {})\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["utils_tests.test_autoreload"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\nindex 7ca0d68fae..dcb6a808eb 100644\n--- a/django/utils/autoreload.py\n+++ b/django/utils/autoreload.py\n@@ -172,6 +172,9 @@ def sys_path_directories():\n Yield absolute directories from sys.path, ignoring entries that don't\n exist.\n \"\"\"\n+ manage_py_dir = Path(__file__).resolve().parent.parent\n+ yield manage_py_dir\n+\n for path in sys.path:\n path = Path(path)\n if not path.exists():\n@@ -323,6 +326,12 @@ class BaseReloader:\n class StatReloader(BaseReloader):\n SLEEP_TIME = 1 # Check for changes once per second.\n \n+ def __init__(self):\n+ super().__init__()\n+ self.manage_py_path = Path(__file__).resolve().parent.parent / 'manage.py'\n+ if self.manage_py_path.exists():\n+ self.extra_files.add(self.manage_py_path)\n+\n def tick(self):\n mtimes = {}\n while True:\n", "model_lint_repair_patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\nindex 7ca0d68fae..dcb6a808eb 100644\n--- a/django/utils/autoreload.py\n+++ b/django/utils/autoreload.py\n@@ -172,6 +172,9 @@ def sys_path_directories():\n Yield absolute directories from sys.path, ignoring entries that don't\n exist.\n \"\"\"\n+ manage_py_dir = Path(__file__).resolve().parent.parent\n+ yield manage_py_dir\n+\n for path in sys.path:\n path = Path(path)\n if not path.exists():\n@@ -323,6 +326,12 @@ class BaseReloader:\n class StatReloader(BaseReloader):\n SLEEP_TIME = 1 # Check for changes once per second.\n \n+ def __init__(self):\n+ super().__init__()\n+ self.manage_py_path = Path(__file__).resolve().parent.parent / 'manage.py'\n+ if self.manage_py_path.exists():\n+ self.extra_files.add(self.manage_py_path)\n+\n def tick(self):\n mtimes = {}\n while True:\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["utils_tests.test_autoreload"]} +{"repo": "django/django", "instance_id": "django__django-16041", "base_commit": "6df9398cce063874ae4d59db126d4adacb0fa8d3", "patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -257,14 +257,15 @@ def extra_forms(self):\n \n @property\n def empty_form(self):\n- form = self.form(\n- auto_id=self.auto_id,\n- prefix=self.add_prefix(\"__prefix__\"),\n- empty_permitted=True,\n- use_required_attribute=False,\n+ form_kwargs = {\n **self.get_form_kwargs(None),\n- renderer=self.renderer,\n- )\n+ \"auto_id\": self.auto_id,\n+ \"prefix\": self.add_prefix(\"__prefix__\"),\n+ \"empty_permitted\": True,\n+ \"use_required_attribute\": False,\n+ \"renderer\": self.renderer,\n+ }\n+ form = self.form(**form_kwargs)\n self.add_fields(form, None)\n return form\n \n", "test_patch": "diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py\n--- a/tests/forms_tests/tests/test_formsets.py\n+++ b/tests/forms_tests/tests/test_formsets.py\n@@ -179,6 +179,10 @@ def test_form_kwargs_empty_form(self):\n self.assertTrue(hasattr(formset.empty_form, \"custom_kwarg\"))\n self.assertEqual(formset.empty_form.custom_kwarg, 1)\n \n+ def test_empty_permitted_ignored_empty_form(self):\n+ formset = ArticleFormSet(form_kwargs={\"empty_permitted\": False})\n+ self.assertIs(formset.empty_form.empty_permitted, True)\n+\n def test_formset_validation(self):\n # FormSet instances can also have an error attribute if validation failed for\n # any of the forms.\n", "problem_statement": "Rendering empty_form crashes when empty_permitted is passed to form_kwargs\nDescription\n\t\nIssue\nWhen explicitly setting form_kwargs = {'empty_permitted':True} or form_kwargs = {'empty_permitted':False} , a KeyError occurs when rendering a template that uses a formset's empty_form.\nExpected Behavior\nempty_permitted is ignored for formset.empty_form since empty_permitted is irrelevant for empty_form, as empty_form is not meant to be used to pass data and therefore does not need to be validated.\nSteps to Reproduce\n# views.py\nfrom django.shortcuts import render\nfrom .models import MyModel\ndef test_view(request):\n\tcontext = {}\n\tff = modelformset_factory(MyModel, fields = ['a_field'])\n\tcontext['formset'] = ff(\n\t\tqueryset = MyModel.objects.none(),\n\t\tform_kwargs = {'empty_permitted':True} # or form_kwargs = {'empty_permitted':False}\n\t)\n\treturn render(request, 'my_app/my_model_formset.html', context)\n# urls.py\nfrom django.urls import path, include\nfrom .views import test_view\nurlpatterns = [\n\tpath('test', test_view)\n]\n# my_model_formset.html\n{% extends \"my_app/base.html\" %}\n{% block content %}\n
\n {% csrf_token %}\n {{ formset }}\n \n
\n{{ formset.empty_form }}\n{% endblock %}\n", "hints_text": "Thanks for the report. It should be enough to change form_kwargs for empty_form, e.g. django/forms/formsets.py diff --git a/django/forms/formsets.py b/django/forms/formsets.py index 57676428ff..b73d1d742e 100644 a b class BaseFormSet(RenderableFormMixin): 257257 258258 @property 259259 def empty_form(self): 260 form = self.form( 261 auto_id=self.auto_id, 262 prefix=self.add_prefix(\"__prefix__\"), 263 empty_permitted=True, 264 use_required_attribute=False, 260 form_kwargs = { 265261 **self.get_form_kwargs(None), 266 renderer=self.renderer, 267 ) 262 \"auto_id\": self.auto_id, 263 \"prefix\": self.add_prefix(\"__prefix__\"), 264 \"use_required_attribute\": False, 265 \"empty_permitted\": True, 266 \"renderer\": self.renderer, 267 } 268 form = self.form(**form_kwargs) 268269 self.add_fields(form, None) 269270 return form 270271 Would you like to prepare a patch? (a regression test is required)\nThe KeyError is confusing here. It's raised because we're in the context of rendering the template: >>> self.form(empty_permitted=True, **self.get_form_kwargs(None)) Traceback (most recent call last): File \"/Users/carlton/Projects/Django/django/django/template/base.py\", line 880, in _resolve_lookup current = current[bit] File \"/Users/carlton/Projects/Django/django/django/forms/formsets.py\", line 118, in __getitem__ return self.forms[index] TypeError: list indices must be integers or slices, not str During handling of the above exception, another exception occurred: Traceback (most recent call last): File \"\", line 1, in KeyError: 'empty_permitted' The real exception is better seen using the formset directly: >>> from ticket_33995.models import MyModel >>> from django.forms import modelformset_factory >>> ff = modelformset_factory(MyModel, fields=['name']) >>> formset = ff(queryset=MyModel.objects.none(), form_kwargs={'empty_permitted': True}) >>> formset.empty_form > /Users/carlton/Projects/Django/django/django/forms/formsets.py(262)empty_form() -> form_kwargs = self.get_form_kwargs(None) (Pdb) c Traceback (most recent call last): File \"\", line 1, in File \"/Users/carlton/Projects/Django/django/django/forms/formsets.py\", line 265, in empty_form form = self.form( TypeError: django.forms.widgets.MyModelForm() got multiple values for keyword argument 'empty_permitted' That's expected: >>> class Example: ... def __init__(self, a_kwarg=None): ... pass ... >>> Example(a_kwarg=True) <__main__.Example object at 0x102352950> >>> Example(a_kwarg=True, a_kwarg=False) File \"\", line 1 SyntaxError: keyword argument repeated: a_kwarg >>> {\"a\":1, **{\"a\":2}} {'a': 2} >>> Example(a_kwarg=True, **{\"a_kwarg\": False}) Traceback (most recent call last): File \"\", line 1, in TypeError: __main__.Example() got multiple values for keyword argument 'a_kwarg' Resolving the kwargs before the constructor call, as per Mariusz' suggestion would resolve. #21501 was on a similar topic.", "created_at": "2022-09-09T10:07:29Z", "version": "4.2", "FAIL_TO_PASS": "[\"test_empty_permitted_ignored_empty_form (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_empty_permitted_ignored_empty_form (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\"]", "PASS_TO_PASS": "[\"all_valid() validates all forms, even when some are invalid.\", \"test_valid (forms_tests.tests.test_formsets.AllValidTests)\", \"is_multipart() works with an empty formset.\", \"An empty formset still calls clean()\", \"Media is available on empty formset.\", \"Management forms are already rendered with the new div template.\", \"test_warning (forms_tests.tests.test_formsets.DeprecationTests)\", \"test_as_div (forms_tests.tests.test_formsets.FormsetAsTagTests)\", \"test_as_p (forms_tests.tests.test_formsets.FormsetAsTagTests)\", \"test_as_table (forms_tests.tests.test_formsets.FormsetAsTagTests)\", \"test_as_ul (forms_tests.tests.test_formsets.FormsetAsTagTests)\", \"test_customize_management_form_error (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_empty_forms_are_unbound (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_form_errors_are_caught_by_formset (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_management_form_invalid_data (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_no_data_error (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_with_management_data_attrs_work_fine (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_as_div (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)\", \"test_as_p (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)\", \"test_as_table (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)\", \"test_as_ul (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)\", \"test_absolute_max (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_absolute_max_invalid (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_absolute_max_with_max_num (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"A FormSet constructor takes the same arguments as Form. Create a\", \"A form that's displayed as blank may be submitted as blank.\", \"test_can_delete_extra_formset_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"FormSets have a clean() hook for doing extra validation that isn't tied\", \"A custom renderer passed to a formset_factory() is passed to all forms\", \"test_default_absolute_max (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"Deleting prefilled data is an error. Removing data from form fields\", \"test_disable_delete_extra_formset_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"More than 1 empty form can be displayed using formset_factory's\", \"Ordering fields are allowed to be left blank. If they are left blank,\", \"test_form_kwargs_empty_form (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"Custom kwargs set on the formset instance are passed to the\", \"Form kwargs can be passed dynamically in a formset.\", \"Formsets call is_valid() on each form.\", \"Formset's forms use the formset's error_class.\", \"FormSet.has_changed() is True if any data is passed to its forms, even\", \"A FormSet can be prefilled with existing data by providing a list of\", \"Formset instances are iterable.\", \"A formsets without any forms evaluates as True.\", \"Formset works with SplitDateTimeField(initial=datetime.datetime.now).\", \"A valid formset should have 0 total errors.\", \"test_formset_total_error_count_with_non_form_errors (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"If validate_max is set and max_num is less than TOTAL_FORMS in the\", \"test_formset_validate_max_flag_custom_error (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_formset_validate_min_excludes_empty_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"If validate_min is set and min_num is more than TOTAL_FORMS in the\", \"test_formset_validate_min_flag_custom_formatted_error (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"min_num validation doesn't consider unchanged forms with initial data\", \"test_formset_validation (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"A formset's ManagementForm is validated once per FormSet.is_valid()\", \"formset_factory's can_delete argument adds a boolean \\\"delete\\\" field to\", \"test_formset_with_deletion_custom_widget (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"deleted_forms works on a valid formset even if a deleted form would\", \"If a form is filled with something and can_delete is also checked, that\", \"FormSets with ordering + deletion.\", \"formset_factory's can_order argument adds an integer field to each\", \"test_formsets_with_ordering_custom_widget (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"A formset has a hard limit on the number of forms instantiated.\", \"test_html_safe (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"Can increase the built-in forms limit via a higher max_num.\", \"Can get ordered_forms from a valid formset even if a deleted form\", \"test_limited_max_forms_two (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"max_num has no effect when extra is less than max_num.\", \"Limiting the maximum number of forms with max_num.\", \"The management form class has field names matching the constants.\", \"The management form has the correct prefix.\", \"test_max_num_with_initial_data (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"If max_num is 0 then no form is rendered at all, regardless of extra,\", \"test_max_num_zero_with_initial (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"More than 1 empty form can also be displayed using formset_factory's\", \"More than 1 empty form can be displayed using min_num.\", \"The extra argument works when the formset is pre-filled with initial\", \"One form from initial and extra=3 with max_num=2 results in the one\", \"More initial forms than max_num results in all initial forms being\", \"test_non_form_errors (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"If non_form_errors() is called without calling is_valid() first,\", \"Ordering works with blank fieldsets.\", \"test_repr (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_repr_do_not_trigger_validation (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"If at least one field is filled out on a blank form, it will be\", \"A partially completed form is invalid.\", \"Just one form may be completed.\", \"test_template_name_can_be_overridden (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_template_name_uses_renderer_value (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_validate_max_ignores_forms_marked_for_deletion (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_absolute_max (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_absolute_max_invalid (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_absolute_max_with_max_num (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_can_delete_extra_formset_forms (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_default_absolute_max (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_disable_delete_extra_formset_forms (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_form_kwargs_empty_form (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_formset_total_error_count_with_non_form_errors (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_formset_validate_max_flag_custom_error (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_formset_validate_min_excludes_empty_forms (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_formset_validate_min_flag_custom_formatted_error (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_formset_validation (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_formset_with_deletion_custom_widget (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_formsets_with_ordering_custom_widget (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_html_safe (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_limited_max_forms_two (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_max_num_with_initial_data (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_max_num_zero_with_initial (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_non_form_errors (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_repr (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_repr_do_not_trigger_validation (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_template_name_can_be_overridden (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_template_name_uses_renderer_value (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\", \"test_validate_max_ignores_forms_marked_for_deletion (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)\"]", "environment_setup_commit": "0fbdb9784da915fce5dcc1fe82bac9b4785749e5", "test_directives": ["forms_tests.tests.test_formsets"], "test_cmd": "./tests/runtests.py --verbosity 2 forms_tests.tests.test_formsets", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py\nindex 21a3a9d868..cca8f5eed5 100644\n--- a/tests/model_formsets_regress/tests.py\n+++ b/tests/model_formsets_regress/tests.py\n@@ -306,6 +306,18 @@ class FormsetTests(TestCase):\n self.assertIsInstance(form.errors, ErrorDict)\n self.assertIsInstance(form.non_field_errors(), ErrorList)\n \n+ def test_empty_form_with_empty_permitted(self):\n+ \"\"\"\n+ Test that empty_form does not crash when empty_permitted is passed in form_kwargs.\n+ \"\"\"\n+ Formset = modelformset_factory(User, fields=\"__all__\")\n+ formset = Formset(queryset=User.objects.none(), form_kwargs={'empty_permitted': True})\n+ try:\n+ empty_form = formset.empty_form\n+ self.assertIsNotNone(empty_form)\n+ except KeyError:\n+ self.fail(\"empty_form raised KeyError when empty_permitted was passed in form_kwargs.\")\n+\n def test_initial_data(self):\n User.objects.create(username=\"bibi\", serial=1)\n Formset = modelformset_factory(User, fields=\"__all__\", extra=2)\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["model_formsets_regress.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\nindex 57676428ff..2a283bbc8a 100644\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -241,6 +241,9 @@ class BaseFormSet(RenderableFormMixin):\n if i >= self.initial_form_count() and i >= self.min_num:\n defaults[\"empty_permitted\"] = True\n defaults.update(kwargs)\n+ # Remove empty_permitted if it's for the empty_form\n+ if i is None:\n+ defaults.pop('empty_permitted', None)\n form = self.form(**defaults)\n self.add_fields(form, i)\n return form\n@@ -257,12 +260,14 @@ class BaseFormSet(RenderableFormMixin):\n \n @property\n def empty_form(self):\n+ form_kwargs = self.get_form_kwargs(None)\n+ form_kwargs.pop('empty_permitted', None)\n form = self.form(\n auto_id=self.auto_id,\n prefix=self.add_prefix(\"__prefix__\"),\n empty_permitted=True,\n use_required_attribute=False,\n- **self.get_form_kwargs(None),\n+ **form_kwargs,\n renderer=self.renderer,\n )\n self.add_fields(form, None)\n", "model_lint_repair_patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\nindex 57676428ff..2a283bbc8a 100644\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -241,6 +241,9 @@ class BaseFormSet(RenderableFormMixin):\n if i >= self.initial_form_count() and i >= self.min_num:\n defaults[\"empty_permitted\"] = True\n defaults.update(kwargs)\n+ # Remove empty_permitted if it's for the empty_form\n+ if i is None:\n+ defaults.pop('empty_permitted', None)\n form = self.form(**defaults)\n self.add_fields(form, i)\n return form\n@@ -257,12 +260,14 @@ class BaseFormSet(RenderableFormMixin):\n \n @property\n def empty_form(self):\n+ form_kwargs = self.get_form_kwargs(None)\n+ form_kwargs.pop('empty_permitted', None)\n form = self.form(\n auto_id=self.auto_id,\n prefix=self.add_prefix(\"__prefix__\"),\n empty_permitted=True,\n use_required_attribute=False,\n- **self.get_form_kwargs(None),\n+ **form_kwargs,\n renderer=self.renderer,\n )\n self.add_fields(form, None)\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["model_formsets_regress.tests"]} +{"repo": "pytest-dev/pytest", "instance_id": "pytest-dev__pytest-7432", "base_commit": "e6e300e729dd33956e5448d8be9a0b1540b4e53a", "patch": "diff --git a/src/_pytest/skipping.py b/src/_pytest/skipping.py\n--- a/src/_pytest/skipping.py\n+++ b/src/_pytest/skipping.py\n@@ -291,7 +291,8 @@ def pytest_runtest_makereport(item: Item, call: CallInfo[None]):\n else:\n rep.outcome = \"passed\"\n rep.wasxfail = xfailed.reason\n- elif (\n+\n+ if (\n item._store.get(skipped_by_mark_key, True)\n and rep.skipped\n and type(rep.longrepr) is tuple\n", "test_patch": "diff --git a/testing/test_skipping.py b/testing/test_skipping.py\n--- a/testing/test_skipping.py\n+++ b/testing/test_skipping.py\n@@ -235,6 +235,31 @@ def test_func2():\n [\"*def test_func():*\", \"*assert 0*\", \"*1 failed*1 pass*\"]\n )\n \n+ @pytest.mark.parametrize(\n+ \"test_input,expected\",\n+ [\n+ (\n+ [\"-rs\"],\n+ [\"SKIPPED [1] test_sample.py:2: unconditional skip\", \"*1 skipped*\"],\n+ ),\n+ (\n+ [\"-rs\", \"--runxfail\"],\n+ [\"SKIPPED [1] test_sample.py:2: unconditional skip\", \"*1 skipped*\"],\n+ ),\n+ ],\n+ )\n+ def test_xfail_run_with_skip_mark(self, testdir, test_input, expected):\n+ testdir.makepyfile(\n+ test_sample=\"\"\"\n+ import pytest\n+ @pytest.mark.skip\n+ def test_skip_location() -> None:\n+ assert 0\n+ \"\"\"\n+ )\n+ result = testdir.runpytest(*test_input)\n+ result.stdout.fnmatch_lines(expected)\n+\n def test_xfail_evalfalse_but_fails(self, testdir):\n item = testdir.getitem(\n \"\"\"\n", "problem_statement": "skipping: --runxfail breaks pytest.mark.skip location reporting\npytest versions: 5.4.x, current master\r\n\r\nWhen `@pytest.mark.skip`/`skipif` marks are used to skip a test, for example\r\n\r\n```py\r\nimport pytest\r\n@pytest.mark.skip\r\ndef test_skip_location() -> None:\r\n assert 0\r\n```\r\n\r\nthe expected skip location reported should point to the item itself, and this is indeed what happens when running with `pytest -rs`:\r\n\r\n```\r\nSKIPPED [1] test_it.py:3: unconditional skip\r\n```\r\n\r\nHowever, adding `pytest -rs --runxfail` breaks this:\r\n\r\n```\r\nSKIPPED [1] src/_pytest/skipping.py:238: unconditional skip\r\n```\r\n\r\nThe `--runxfail` is only about xfail and should not affect this at all.\r\n\r\n---\r\n\r\nHint: the bug is in `src/_pytest/skipping.py`, the `pytest_runtest_makereport` hook.\n", "hints_text": "Can I look into this one?\n@debugduck Sure!\nAwesome! I'll get started on it and open up a PR when I find it. I'm a bit new, so I'm still learning about the code base.", "created_at": "2020-06-29T21:51:15Z", "version": "5.4", "FAIL_TO_PASS": "[\"testing/test_skipping.py::TestXFail::test_xfail_run_with_skip_mark[test_input1-expected1]\"]", "PASS_TO_PASS": "[\"testing/test_skipping.py::test_importorskip\", \"testing/test_skipping.py::TestEvaluation::test_no_marker\", \"testing/test_skipping.py::TestEvaluation::test_marked_xfail_no_args\", \"testing/test_skipping.py::TestEvaluation::test_marked_skipif_no_args\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg_with_reason\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg_twice\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg_twice2\", \"testing/test_skipping.py::TestEvaluation::test_marked_skipif_with_boolean_without_reason\", \"testing/test_skipping.py::TestEvaluation::test_marked_skipif_with_invalid_boolean\", \"testing/test_skipping.py::TestEvaluation::test_skipif_class\", \"testing/test_skipping.py::TestXFail::test_xfail_simple[True]\", \"testing/test_skipping.py::TestXFail::test_xfail_simple[False]\", \"testing/test_skipping.py::TestXFail::test_xfail_xpassed\", \"testing/test_skipping.py::TestXFail::test_xfail_using_platform\", \"testing/test_skipping.py::TestXFail::test_xfail_xpassed_strict\", \"testing/test_skipping.py::TestXFail::test_xfail_run_anyway\", \"testing/test_skipping.py::TestXFail::test_xfail_run_with_skip_mark[test_input0-expected0]\", \"testing/test_skipping.py::TestXFail::test_xfail_evalfalse_but_fails\", \"testing/test_skipping.py::TestXFail::test_xfail_not_report_default\", \"testing/test_skipping.py::TestXFail::test_xfail_not_run_xfail_reporting\", \"testing/test_skipping.py::TestXFail::test_xfail_not_run_no_setup_run\", \"testing/test_skipping.py::TestXFail::test_xfail_xpass\", \"testing/test_skipping.py::TestXFail::test_xfail_imperative\", \"testing/test_skipping.py::TestXFail::test_xfail_imperative_in_setup_function\", \"testing/test_skipping.py::TestXFail::test_dynamic_xfail_no_run\", \"testing/test_skipping.py::TestXFail::test_dynamic_xfail_set_during_funcarg_setup\", \"testing/test_skipping.py::TestXFail::test_xfail_raises[TypeError-TypeError-*1\", \"testing/test_skipping.py::TestXFail::test_xfail_raises[(AttributeError,\", \"testing/test_skipping.py::TestXFail::test_xfail_raises[TypeError-IndexError-*1\", \"testing/test_skipping.py::TestXFail::test_strict_sanity\", \"testing/test_skipping.py::TestXFail::test_strict_xfail[True]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail[False]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_condition[True]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_condition[False]\", \"testing/test_skipping.py::TestXFail::test_xfail_condition_keyword[True]\", \"testing/test_skipping.py::TestXFail::test_xfail_condition_keyword[False]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_default_from_file[true]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_default_from_file[false]\", \"testing/test_skipping.py::TestXFailwithSetupTeardown::test_failing_setup_issue9\", \"testing/test_skipping.py::TestXFailwithSetupTeardown::test_failing_teardown_issue9\", \"testing/test_skipping.py::TestSkip::test_skip_class\", \"testing/test_skipping.py::TestSkip::test_skips_on_false_string\", \"testing/test_skipping.py::TestSkip::test_arg_as_reason\", \"testing/test_skipping.py::TestSkip::test_skip_no_reason\", \"testing/test_skipping.py::TestSkip::test_skip_with_reason\", \"testing/test_skipping.py::TestSkip::test_only_skips_marked_test\", \"testing/test_skipping.py::TestSkip::test_strict_and_skip\", \"testing/test_skipping.py::TestSkipif::test_skipif_conditional\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting[\\\"hasattr(sys,\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting[True,\", \"testing/test_skipping.py::TestSkipif::test_skipif_using_platform\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting_multiple[skipif-SKIP-skipped]\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting_multiple[xfail-XPASS-xpassed]\", \"testing/test_skipping.py::test_skip_not_report_default\", \"testing/test_skipping.py::test_skipif_class\", \"testing/test_skipping.py::test_skipped_reasons_functional\", \"testing/test_skipping.py::test_skipped_folding\", \"testing/test_skipping.py::test_reportchars\", \"testing/test_skipping.py::test_reportchars_error\", \"testing/test_skipping.py::test_reportchars_all\", \"testing/test_skipping.py::test_reportchars_all_error\", \"testing/test_skipping.py::test_errors_in_xfail_skip_expressions\", \"testing/test_skipping.py::test_xfail_skipif_with_globals\", \"testing/test_skipping.py::test_default_markers\", \"testing/test_skipping.py::test_xfail_test_setup_exception\", \"testing/test_skipping.py::test_imperativeskip_on_xfail_test\", \"testing/test_skipping.py::TestBooleanCondition::test_skipif\", \"testing/test_skipping.py::TestBooleanCondition::test_skipif_noreason\", \"testing/test_skipping.py::TestBooleanCondition::test_xfail\", \"testing/test_skipping.py::test_xfail_item\", \"testing/test_skipping.py::test_module_level_skip_error\", \"testing/test_skipping.py::test_module_level_skip_with_allow_module_level\", \"testing/test_skipping.py::test_invalid_skip_keyword_parameter\", \"testing/test_skipping.py::test_mark_xfail_item\", \"testing/test_skipping.py::test_summary_list_after_errors\", \"testing/test_skipping.py::test_relpath_rootdir\"]", "environment_setup_commit": "678c1a0745f1cf175c442c719906a1f13e496910", "test_directives": ["testing/test_skipping.py"], "test_cmd": "pytest -vrA testing/test_skipping.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["testing/test_skipping.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/src/_pytest/skipping.py b/src/_pytest/skipping.py\nindex 7bd975e5a..8f9306188 100644\n--- a/src/_pytest/skipping.py\n+++ b/src/_pytest/skipping.py\n@@ -299,10 +299,11 @@ def pytest_runtest_makereport(item: Item, call: CallInfo[None]):\n # skipped by mark.skipif; change the location of the failure\n # to point to the item definition, otherwise it will display\n # the location of where the skip exception was raised within pytest\n- _, _, reason = rep.longrepr\n- filename, line = item.reportinfo()[:2]\n- assert line is not None\n- rep.longrepr = str(filename), line + 1, reason\n+ if not item.config.option.runxfail:\n+ _, _, reason = rep.longrepr\n+ filename, line = item.reportinfo()[:2]\n+ assert line is not None\n+ rep.longrepr = str(filename), line + 1, reason\n \n \n def pytest_report_teststatus(report: BaseReport) -> Optional[Tuple[str, str, str]]:\n", "model_lint_repair_patch": "diff --git a/src/_pytest/skipping.py b/src/_pytest/skipping.py\nindex 7bd975e5a..8f9306188 100644\n--- a/src/_pytest/skipping.py\n+++ b/src/_pytest/skipping.py\n@@ -299,10 +299,11 @@ def pytest_runtest_makereport(item: Item, call: CallInfo[None]):\n # skipped by mark.skipif; change the location of the failure\n # to point to the item definition, otherwise it will display\n # the location of where the skip exception was raised within pytest\n- _, _, reason = rep.longrepr\n- filename, line = item.reportinfo()[:2]\n- assert line is not None\n- rep.longrepr = str(filename), line + 1, reason\n+ if not item.config.option.runxfail:\n+ _, _, reason = rep.longrepr\n+ filename, line = item.reportinfo()[:2]\n+ assert line is not None\n+ rep.longrepr = str(filename), line + 1, reason\n \n \n def pytest_report_teststatus(report: BaseReport) -> Optional[Tuple[str, str, str]]:\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["testing/test_skipping.py"]} +{"repo": "django/django", "instance_id": "django__django-11049", "base_commit": "17455e924e243e7a55e8a38f45966d8cbb27c273", "patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -1587,7 +1587,7 @@ class DurationField(Field):\n empty_strings_allowed = False\n default_error_messages = {\n 'invalid': _(\"'%(value)s' value has an invalid format. It must be in \"\n- \"[DD] [HH:[MM:]]ss[.uuuuuu] format.\")\n+ \"[DD] [[HH:]MM:]ss[.uuuuuu] format.\")\n }\n description = _(\"Duration\")\n \n", "test_patch": "diff --git a/tests/model_fields/test_durationfield.py b/tests/model_fields/test_durationfield.py\n--- a/tests/model_fields/test_durationfield.py\n+++ b/tests/model_fields/test_durationfield.py\n@@ -75,7 +75,7 @@ def test_invalid_string(self):\n self.assertEqual(\n cm.exception.message % cm.exception.params,\n \"'not a datetime' value has an invalid format. \"\n- \"It must be in [DD] [HH:[MM:]]ss[.uuuuuu] format.\"\n+ \"It must be in [DD] [[HH:]MM:]ss[.uuuuuu] format.\"\n )\n \n \n", "problem_statement": "Correct expected format in invalid DurationField error message\nDescription\n\t\nIf you enter a duration \"14:00\" into a duration field, it translates to \"00:14:00\" which is 14 minutes.\nThe current error message for invalid DurationField says that this should be the format of durations: \"[DD] [HH:[MM:]]ss[.uuuuuu]\". But according to the actual behaviour, it should be: \"[DD] [[HH:]MM:]ss[.uuuuuu]\", because seconds are mandatory, minutes are optional, and hours are optional if minutes are provided.\nThis seems to be a mistake in all Django versions that support the DurationField.\nAlso the duration fields could have a default help_text with the requested format, because the syntax is not self-explanatory.\n", "hints_text": "", "created_at": "2019-03-03T09:56:16Z", "version": "3.0", "FAIL_TO_PASS": "[\"test_invalid_string (model_fields.test_durationfield.TestValidation)\"]", "PASS_TO_PASS": "[\"test_dumping (model_fields.test_durationfield.TestSerialization)\", \"test_loading (model_fields.test_durationfield.TestSerialization)\", \"test_formfield (model_fields.test_durationfield.TestFormField)\", \"test_exact (model_fields.test_durationfield.TestQuerying)\", \"test_gt (model_fields.test_durationfield.TestQuerying)\", \"test_create_empty (model_fields.test_durationfield.TestSaveLoad)\", \"test_fractional_seconds (model_fields.test_durationfield.TestSaveLoad)\", \"test_simple_roundtrip (model_fields.test_durationfield.TestSaveLoad)\"]", "environment_setup_commit": "419a78300f7cd27611196e1e464d50fd0385ff27", "test_directives": ["model_fields.test_durationfield"], "test_cmd": "./tests/runtests.py --verbosity 2 model_fields.test_durationfield", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/model_fields/test_durationfield.py b/tests/model_fields/test_durationfield.py\nindex b73994f86a..f9d32c156f 100644\n--- a/tests/model_fields/test_durationfield.py\n+++ b/tests/model_fields/test_durationfield.py\n@@ -75,7 +75,14 @@ class TestValidation(SimpleTestCase):\n self.assertEqual(\n cm.exception.message % cm.exception.params,\n \"'not a datetime' value has an invalid format. \"\n- \"It must be in [DD] [HH:[MM:]]ss[.uuuuuu] format.\"\n+ \"It must be in [DD] [[HH:]MM:]ss[.uuuuuu] format.\"\n+ )\n+\n+ def test_default_help_text(self):\n+ field = models.DurationField()\n+ self.assertEqual(\n+ field.help_text,\n+ \"Enter a duration in the format [DD] [[HH:]MM:]ss[.uuuuuu].\"\n )\n \n \n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["model_fields.test_durationfield"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py\nindex f90d952581..50974c139e 100644\n--- a/django/utils/dateparse.py\n+++ b/django/utils/dateparse.py\n@@ -125,7 +125,7 @@ def parse_datetime(value):\n def parse_duration(value):\n \"\"\"Parse a duration string and return a datetime.timedelta.\n \n- The preferred format for durations in Django is '%d %H:%M:%S.%f'.\n+ The preferred format for durations in Django is '[DD] [[HH:]MM:]ss[.uuuuuu]'.\n \n Also supports ISO 8601 representation and PostgreSQL's day-time interval\n format.\n", "model_lint_repair_patch": "diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py\nindex f90d952581..50974c139e 100644\n--- a/django/utils/dateparse.py\n+++ b/django/utils/dateparse.py\n@@ -125,7 +125,7 @@ def parse_datetime(value):\n def parse_duration(value):\n \"\"\"Parse a duration string and return a datetime.timedelta.\n \n- The preferred format for durations in Django is '%d %H:%M:%S.%f'.\n+ The preferred format for durations in Django is '[DD] [[HH:]MM:]ss[.uuuuuu]'.\n \n Also supports ISO 8601 representation and PostgreSQL's day-time interval\n format.\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "psf/requests", "instance_id": "psf__requests-863", "base_commit": "a0df2cbb10419037d11d04352b3175405ab52941", "patch": "diff --git a/requests/models.py b/requests/models.py\n--- a/requests/models.py\n+++ b/requests/models.py\n@@ -462,8 +462,10 @@ def path_url(self):\n \n def register_hook(self, event, hook):\n \"\"\"Properly register a hook.\"\"\"\n-\n- self.hooks[event].append(hook)\n+ if isinstance(hook, (list, tuple, set)):\n+ self.hooks[event].extend(hook)\n+ else:\n+ self.hooks[event].append(hook)\n \n def deregister_hook(self, event, hook):\n \"\"\"Deregister a previously registered hook.\n", "test_patch": "diff --git a/tests/test_requests.py b/tests/test_requests.py\n--- a/tests/test_requests.py\n+++ b/tests/test_requests.py\n@@ -744,6 +744,40 @@ def add_bar_header(args):\n assert 'foo' in response.text\n assert 'bar' in response.text\n \n+ def test_allow_list_of_hooks_to_register_hook(self):\n+ \"\"\"Issue 785: https://github.com/kennethreitz/requests/issues/785\"\"\"\n+ def add_foo_header(args):\n+ if not args.get('headers'):\n+ args['headers'] = {}\n+\n+ args['headers'].update({\n+ 'X-Foo': 'foo'\n+ })\n+\n+ return args\n+\n+ def add_bar_header(args):\n+ if not args.get('headers'):\n+ args['headers'] = {}\n+\n+ args['headers'].update({\n+ 'X-Bar': 'bar'\n+ })\n+\n+ return args\n+\n+ def assert_hooks_are_callable(hooks):\n+ for h in hooks['args']:\n+ assert callable(h) is True\n+\n+ hooks = [add_foo_header, add_bar_header]\n+ r = requests.models.Request()\n+ r.register_hook('args', hooks)\n+ assert_hooks_are_callable(r.hooks)\n+\n+ r = requests.models.Request(hooks={'args': hooks})\n+ assert_hooks_are_callable(r.hooks)\n+\n def test_session_persistent_cookies(self):\n \n s = requests.session()\n", "problem_statement": "Allow lists in the dict values of the hooks argument\nCurrently the Request class has a .register_hook() method but it parses the dictionary it expects from it's hooks argument weirdly: the argument can only specify one hook function per hook. If you pass in a list of hook functions per hook the code in Request.**init**() will wrap the list in a list which then fails when the hooks are consumed (since a list is not callable). This is especially annoying since you can not use multiple hooks from a session. The only way to get multiple hooks now is to create the request object without sending it, then call .register_hook() multiple times and then finally call .send().\n\nThis would all be much easier if Request.**init**() parsed the hooks parameter in a way that it accepts lists as it's values.\n\n", "hints_text": "If anyone OKs this feature request, I'd be happy to dig into it.\n\n@sigmavirus24 :+1:\n\nJust need to make sure that the current workflow also continues to work with this change.\n\nOnce @kennethreitz has time to review #833, I'll start working on this. I have a feeling opening a branch for this would cause a merge conflict if I were to have two Pull Requests that are ignorant of each other for the same file. Could be wrong though. Also, I'm in no rush since I'm fairly busy and I know @kennethreitz is more busy than I am with conferences and whatnot. Just wanted to keep @flub updated.\n\nI'm going to start work on this Friday at the earliest.\n", "created_at": "2012-09-20T15:48:00Z", "version": "0.14", "FAIL_TO_PASS": "[\"tests/test_requests.py::RequestsTestSuite::test_POSTBIN_GET_POST_FILES_WITH_HEADERS\", \"tests/test_requests.py::RequestsTestSuite::test_nonurlencoded_postdata\", \"tests/test_requests.py::RequestsTestSuite::test_prefetch_redirect_bug\", \"tests/test_requests.py::RequestsTestSuite::test_urlencoded_post_data\"]", "PASS_TO_PASS": "[\"tests/test_requests.py::RequestsTestSuite::test_BASICAUTH_HTTP_200_OK_GET\", \"tests/test_requests.py::RequestsTestSuite::test_BASICAUTH_TUPLE_HTTP_200_OK_GET\", \"tests/test_requests.py::RequestsTestSuite::test_GET_no_redirect\", \"tests/test_requests.py::RequestsTestSuite::test_HEAD_no_redirect\", \"tests/test_requests.py::RequestsTestSuite::test_HTTP_200_OK_GET\", \"tests/test_requests.py::RequestsTestSuite::test_HTTP_200_OK_GET_WITH_MIXED_PARAMS\", \"tests/test_requests.py::RequestsTestSuite::test_HTTP_200_OK_GET_WITH_PARAMS\", \"tests/test_requests.py::RequestsTestSuite::test_HTTP_200_OK_HEAD\", \"tests/test_requests.py::RequestsTestSuite::test_HTTP_200_OK_PUT\", \"tests/test_requests.py::RequestsTestSuite::test_HTTP_302_ALLOW_REDIRECT_GET\", \"tests/test_requests.py::RequestsTestSuite::test_HTTP_302_GET\", \"tests/test_requests.py::RequestsTestSuite::test_POSTBIN_GET_POST_FILES\", \"tests/test_requests.py::RequestsTestSuite::test_POSTBIN_GET_POST_FILES_WITH_PARAMS\", \"tests/test_requests.py::RequestsTestSuite::test_accept_objects_with_string_representations_as_urls\", \"tests/test_requests.py::RequestsTestSuite::test_bytes_files\", \"tests/test_requests.py::RequestsTestSuite::test_cached_response\", \"tests/test_requests.py::RequestsTestSuite::test_can_have_none_in_header_values\", \"tests/test_requests.py::RequestsTestSuite::test_connection_error\", \"tests/test_requests.py::RequestsTestSuite::test_connection_error_with_safe_mode\", \"tests/test_requests.py::RequestsTestSuite::test_connection_keepalive_and_close\", \"tests/test_requests.py::RequestsTestSuite::test_danger_mode_redirects\", \"tests/test_requests.py::RequestsTestSuite::test_decompress_gzip\", \"tests/test_requests.py::RequestsTestSuite::test_default_status_raising\", \"tests/test_requests.py::RequestsTestSuite::test_empty_response\", \"tests/test_requests.py::RequestsTestSuite::test_entry_points\", \"tests/test_requests.py::RequestsTestSuite::test_file_post_data\", \"tests/test_requests.py::RequestsTestSuite::test_head_content\", \"tests/test_requests.py::RequestsTestSuite::test_httpauth_recursion\", \"tests/test_requests.py::RequestsTestSuite::test_invalid_url\", \"tests/test_requests.py::RequestsTestSuite::test_invalid_urls_throw_requests_exception\", \"tests/test_requests.py::RequestsTestSuite::test_iter_lines\", \"tests/test_requests.py::RequestsTestSuite::test_max_redirects\", \"tests/test_requests.py::RequestsTestSuite::test_multiple_hooks\", \"tests/test_requests.py::RequestsTestSuite::test_nonurlencoded_post_data\", \"tests/test_requests.py::RequestsTestSuite::test_nonzero_evaluation\", \"tests/test_requests.py::RequestsTestSuite::test_params_accepts_kv_list\", \"tests/test_requests.py::RequestsTestSuite::test_params_are_added_before_fragment\", \"tests/test_requests.py::RequestsTestSuite::test_path_is_not_double_encoded\", \"tests/test_requests.py::RequestsTestSuite::test_post_fields_with_multiple_values_and_files\", \"tests/test_requests.py::RequestsTestSuite::test_post_fields_with_multiple_values_and_files_as_tuples\", \"tests/test_requests.py::RequestsTestSuite::test_prefetch_return_response_interaction\", \"tests/test_requests.py::RequestsTestSuite::test_redirect_history\", \"tests/test_requests.py::RequestsTestSuite::test_relative_redirect_history\", \"tests/test_requests.py::RequestsTestSuite::test_request_ok_set\", \"tests/test_requests.py::RequestsTestSuite::test_response_has_unicode_url\", \"tests/test_requests.py::RequestsTestSuite::test_response_sent\", \"tests/test_requests.py::RequestsTestSuite::test_session_HTTP_200_OK_GET\", \"tests/test_requests.py::RequestsTestSuite::test_session_persistent_headers\", \"tests/test_requests.py::RequestsTestSuite::test_session_pickling\", \"tests/test_requests.py::RequestsTestSuite::test_status_raising\", \"tests/test_requests.py::RequestsTestSuite::test_unicode_get\", \"tests/test_requests.py::RequestsTestSuite::test_upload_binary_data\", \"tests/test_requests.py::RequestsTestSuite::test_urlencoded_get_query_multivalued_param\", \"tests/test_requests.py::RequestsTestSuite::test_urlencoded_post_query_and_data\", \"tests/test_requests.py::RequestsTestSuite::test_urlencoded_post_query_multivalued_and_data\", \"tests/test_requests.py::RequestsTestSuite::test_urlencoded_post_querystring\", \"tests/test_requests.py::RequestsTestSuite::test_urlencoded_post_querystring_multivalued\", \"tests/test_requests.py::RequestsTestSuite::test_useful_exception_for_invalid_port\", \"tests/test_requests.py::RequestsTestSuite::test_useful_exception_for_invalid_scheme\", \"tests/test_requests.py::RequestsTestSuite::test_user_agent_transfers\"]", "environment_setup_commit": "a0df2cbb10419037d11d04352b3175405ab52941", "test_directives": ["tests/test_requests.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v tests/test_requests.py", "model_name_or_path": "navie", "model_patch": null} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-21055", "base_commit": "748ce73479ee2cd5c861431091001cc18943c735", "patch": "diff --git a/sympy/assumptions/refine.py b/sympy/assumptions/refine.py\n--- a/sympy/assumptions/refine.py\n+++ b/sympy/assumptions/refine.py\n@@ -297,6 +297,28 @@ def refine_im(expr, assumptions):\n return - S.ImaginaryUnit * arg\n return _refine_reim(expr, assumptions)\n \n+def refine_arg(expr, assumptions):\n+ \"\"\"\n+ Handler for complex argument\n+\n+ Explanation\n+ ===========\n+\n+ >>> from sympy.assumptions.refine import refine_arg\n+ >>> from sympy import Q, arg\n+ >>> from sympy.abc import x\n+ >>> refine_arg(arg(x), Q.positive(x))\n+ 0\n+ >>> refine_arg(arg(x), Q.negative(x))\n+ pi\n+ \"\"\"\n+ rg = expr.args[0]\n+ if ask(Q.positive(rg), assumptions):\n+ return S.Zero\n+ if ask(Q.negative(rg), assumptions):\n+ return S.Pi\n+ return None\n+\n \n def _refine_reim(expr, assumptions):\n # Helper function for refine_re & refine_im\n@@ -379,6 +401,7 @@ def refine_matrixelement(expr, assumptions):\n 'atan2': refine_atan2,\n 're': refine_re,\n 'im': refine_im,\n+ 'arg': refine_arg,\n 'sign': refine_sign,\n 'MatrixElement': refine_matrixelement\n } # type: Dict[str, Callable[[Expr, Boolean], Expr]]\n", "test_patch": "diff --git a/sympy/assumptions/tests/test_refine.py b/sympy/assumptions/tests/test_refine.py\n--- a/sympy/assumptions/tests/test_refine.py\n+++ b/sympy/assumptions/tests/test_refine.py\n@@ -1,5 +1,5 @@\n from sympy import (Abs, exp, Expr, I, pi, Q, Rational, refine, S, sqrt,\n- atan, atan2, nan, Symbol, re, im, sign)\n+ atan, atan2, nan, Symbol, re, im, sign, arg)\n from sympy.abc import w, x, y, z\n from sympy.core.relational import Eq, Ne\n from sympy.functions.elementary.piecewise import Piecewise\n@@ -160,6 +160,10 @@ def test_sign():\n x = Symbol('x', complex=True)\n assert refine(sign(x), Q.zero(x)) == 0\n \n+def test_arg():\n+ x = Symbol('x', complex = True)\n+ assert refine(arg(x), Q.positive(x)) == 0\n+ assert refine(arg(x), Q.negative(x)) == pi\n \n def test_func_args():\n class MyClass(Expr):\n", "problem_statement": "`refine()` does not understand how to simplify complex arguments\nJust learned about the refine-function, which would come in handy frequently for me. But\r\n`refine()` does not recognize that argument functions simplify for real numbers.\r\n\r\n```\r\n>>> from sympy import * \r\n>>> var('a,x') \r\n>>> J = Integral(sin(x)*exp(-a*x),(x,0,oo)) \r\n>>> J.doit()\r\n\tPiecewise((1/(a**2 + 1), 2*Abs(arg(a)) < pi), (Integral(exp(-a*x)*sin(x), (x, 0, oo)), True))\r\n>>> refine(J.doit(),Q.positive(a)) \r\n Piecewise((1/(a**2 + 1), 2*Abs(arg(a)) < pi), (Integral(exp(-a*x)*sin(x), (x, 0, oo)), True))\r\n>>> refine(abs(a),Q.positive(a)) \r\n\ta\r\n>>> refine(arg(a),Q.positive(a)) \r\n\targ(a)\r\n```\r\nI cann't find any open issues identifying this. Easy to fix, though.\r\n\r\n\n", "hints_text": "", "created_at": "2021-03-07T21:08:36Z", "version": "1.8", "FAIL_TO_PASS": "[\"test_arg\"]", "PASS_TO_PASS": "[\"test_Abs\", \"test_pow1\", \"test_pow2\", \"test_exp\", \"test_Piecewise\", \"test_atan2\", \"test_re\", \"test_im\", \"test_complex\", \"test_sign\", \"test_func_args\", \"test_eval_refine\", \"test_refine_issue_12724\"]", "environment_setup_commit": "3ac1464b8840d5f8b618a654f9fbf09c452fe969", "test_directives": ["sympy/assumptions/tests/test_refine.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/assumptions/tests/test_refine.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/sympy/assumptions/tests/test_refine.py b/sympy/assumptions/tests/test_refine.py\nindex 505cd609e8..efa2fb53e3 100644\n--- a/sympy/assumptions/tests/test_refine.py\n+++ b/sympy/assumptions/tests/test_refine.py\n@@ -1,5 +1,5 @@\n from sympy import (Abs, exp, Expr, I, pi, Q, Rational, refine, S, sqrt,\n- atan, atan2, nan, Symbol, re, im, sign)\n+ atan, atan2, nan, Symbol, re, im, sign, arg, Integral, oo, sin)\n from sympy.abc import w, x, y, z\n from sympy.core.relational import Eq, Ne\n from sympy.functions.elementary.piecewise import Piecewise\n@@ -200,6 +200,15 @@ def test_refine_issue_12724():\n assert expr3 == x * y1**2 * Abs(z)\n \n \n+def test_refine_complex_arguments():\n+ from sympy import symbols\n+ a, x = symbols('a x', real=True)\n+ J = Integral(sin(x) * exp(-a * x), (x, 0, oo))\n+ refined_J = refine(J.doit(), Q.positive(a))\n+ assert refined_J == Piecewise((1 / (a**2 + 1), 2 * Abs(arg(a)) < pi), (Integral(exp(-a * x) * sin(x), (x, 0, oo)), True))\n+ assert refine(Abs(a), Q.positive(a)) == a\n+ assert refine(arg(a), Q.positive(a)) == 0\n+\n def test_matrixelement():\n x = MatrixSymbol('x', 3, 3)\n i = Symbol('i', positive = True)\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["sympy/assumptions/tests/test_refine.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/assumptions/refine.py b/sympy/assumptions/refine.py\nindex e1f97190c0..e1452499b8 100644\n--- a/sympy/assumptions/refine.py\n+++ b/sympy/assumptions/refine.py\n@@ -66,6 +66,39 @@ def refine(expr, assumptions=True):\n return refine(new_expr, assumptions)\n \n \n+def refine_arg(expr, assumptions):\n+ \"\"\"\n+ Handler for the argument function.\n+\n+ Examples\n+ ========\n+\n+ >>> from sympy import Q, arg\n+ >>> from sympy.assumptions.refine import refine_arg\n+ >>> from sympy.abc import x\n+ >>> refine_arg(arg(x), Q.positive(x))\n+ 0\n+ >>> refine_arg(arg(x), Q.negative(x))\n+ pi\n+ >>> refine_arg(arg(x), Q.positive(im(x)))\n+ pi/2\n+ >>> refine_arg(arg(x), Q.negative(im(x)))\n+ -pi/2\n+ \"\"\"\n+ from sympy.functions.elementary.complexes import arg\n+ from sympy import I, pi\n+ arg_expr = expr.args[0]\n+ if ask(Q.positive(arg_expr), assumptions):\n+ return S.Zero\n+ if ask(Q.negative(arg_expr), assumptions):\n+ return pi\n+ if ask(Q.positive(im(arg_expr)), assumptions):\n+ return pi/2\n+ if ask(Q.negative(im(arg_expr)), assumptions):\n+ return -pi/2\n+ return expr\n+\n+\n def refine_abs(expr, assumptions):\n \"\"\"\n Handler for the absolute value.\n@@ -380,5 +413,6 @@ def refine_matrixelement(expr, assumptions):\n 're': refine_re,\n 'im': refine_im,\n 'sign': refine_sign,\n- 'MatrixElement': refine_matrixelement\n+ 'MatrixElement': refine_matrixelement,\n+ 'arg': refine_arg\n } # type: Dict[str, Callable[[Expr, Boolean], Expr]]\n", "model_lint_repair_patch": "diff --git a/sympy/assumptions/refine.py b/sympy/assumptions/refine.py\nindex e1f97190c0..0811ab6188 100644\n--- a/sympy/assumptions/refine.py\n+++ b/sympy/assumptions/refine.py\n@@ -66,6 +66,40 @@ def refine(expr, assumptions=True):\n return refine(new_expr, assumptions)\n \n \n+def refine_arg(expr, assumptions):\n+ \"\"\"\n+ Handler for the argument function.\n+\n+ Examples\n+ ========\n+\n+ >>> from sympy import Q, arg\n+ >>> from sympy.assumptions.refine import refine_arg\n+ >>> from sympy.abc import x\n+ >>> from sympy.functions.elementary.complexes import im\n+ >>> refine_arg(arg(x), Q.positive(x))\n+ 0\n+ >>> refine_arg(arg(x), Q.negative(x))\n+ pi\n+ >>> refine_arg(arg(x), Q.positive(im(x)))\n+ pi/2\n+ >>> refine_arg(arg(x), Q.negative(im(x)))\n+ -pi/2\n+ \"\"\"\n+ from sympy.functions.elementary.complexes import arg, im\n+ from sympy import I, pi\n+ arg_expr = expr.args[0]\n+ if ask(Q.positive(arg_expr), assumptions):\n+ return S.Zero\n+ if ask(Q.negative(arg_expr), assumptions):\n+ return pi\n+ if ask(Q.positive(im(arg_expr)), assumptions):\n+ return pi/2\n+ if ask(Q.negative(im(arg_expr)), assumptions):\n+ return -pi/2\n+ return expr\n+\n+\n def refine_abs(expr, assumptions):\n \"\"\"\n Handler for the absolute value.\n@@ -380,5 +414,6 @@ def refine_matrixelement(expr, assumptions):\n 're': refine_re,\n 'im': refine_im,\n 'sign': refine_sign,\n- 'MatrixElement': refine_matrixelement\n+ 'MatrixElement': refine_matrixelement,\n+ 'arg': refine_arg\n } # type: Dict[str, Callable[[Expr, Boolean], Expr]]\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-12747", "base_commit": "c86201b6ed4f8256b0a0520c08aa674f623d4127", "patch": "diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py\n--- a/django/db/models/deletion.py\n+++ b/django/db/models/deletion.py\n@@ -408,7 +408,8 @@ def delete(self):\n # fast deletes\n for qs in self.fast_deletes:\n count = qs._raw_delete(using=self.using)\n- deleted_counter[qs.model._meta.label] += count\n+ if count:\n+ deleted_counter[qs.model._meta.label] += count\n \n # update fields\n for model, instances_for_fieldvalues in self.field_updates.items():\n@@ -426,7 +427,8 @@ def delete(self):\n query = sql.DeleteQuery(model)\n pk_list = [obj.pk for obj in instances]\n count = query.delete_batch(pk_list, self.using)\n- deleted_counter[model._meta.label] += count\n+ if count:\n+ deleted_counter[model._meta.label] += count\n \n if not model._meta.auto_created:\n for obj in instances:\n", "test_patch": "diff --git a/tests/delete/tests.py b/tests/delete/tests.py\n--- a/tests/delete/tests.py\n+++ b/tests/delete/tests.py\n@@ -522,11 +522,10 @@ def test_queryset_delete_returns_num_rows(self):\n existed_objs = {\n R._meta.label: R.objects.count(),\n HiddenUser._meta.label: HiddenUser.objects.count(),\n- A._meta.label: A.objects.count(),\n- MR._meta.label: MR.objects.count(),\n HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(),\n }\n deleted, deleted_objs = R.objects.all().delete()\n+ self.assertCountEqual(deleted_objs.keys(), existed_objs.keys())\n for k, v in existed_objs.items():\n self.assertEqual(deleted_objs[k], v)\n \n@@ -550,13 +549,13 @@ def test_model_delete_returns_num_rows(self):\n existed_objs = {\n R._meta.label: R.objects.count(),\n HiddenUser._meta.label: HiddenUser.objects.count(),\n- A._meta.label: A.objects.count(),\n MR._meta.label: MR.objects.count(),\n HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(),\n M.m2m.through._meta.label: M.m2m.through.objects.count(),\n }\n deleted, deleted_objs = r.delete()\n self.assertEqual(deleted, sum(existed_objs.values()))\n+ self.assertCountEqual(deleted_objs.keys(), existed_objs.keys())\n for k, v in existed_objs.items():\n self.assertEqual(deleted_objs[k], v)\n \n@@ -694,7 +693,7 @@ def test_fast_delete_empty_no_update_can_self_select(self):\n with self.assertNumQueries(1):\n self.assertEqual(\n User.objects.filter(avatar__desc='missing').delete(),\n- (0, {'delete.User': 0})\n+ (0, {}),\n )\n \n def test_fast_delete_combined_relationships(self):\n", "problem_statement": "QuerySet.Delete - inconsistent result when zero objects deleted\nDescription\n\t\nThe result format of the QuerySet.Delete method is a tuple: (X, Y) \nX - is the total amount of deleted objects (including foreign key deleted objects)\nY - is a dictionary specifying counters of deleted objects for each specific model (the key is the _meta.label of the model and the value is counter of deleted objects of this model).\nExample: : (2, {'my_app.FileAccess': 1, 'my_app.File': 1})\nWhen there are zero objects to delete in total - the result is inconsistent:\nFor models with foreign keys - the result will be: : (0, {})\nFor \"simple\" models without foreign key - the result will be: : (0, {'my_app.BlockLibrary': 0})\nI would expect there will be no difference between the two cases: Either both will have the empty dictionary OR both will have dictionary with model-label keys and zero value.\n", "hints_text": "I guess we could adapt the code not to include any key if the count is zero in the second case.", "created_at": "2020-04-18T16:41:40Z", "version": "3.1", "FAIL_TO_PASS": "[\"test_fast_delete_empty_no_update_can_self_select (delete.tests.FastDeleteTests)\", \"test_model_delete_returns_num_rows (delete.tests.DeletionTests)\", \"test_queryset_delete_returns_num_rows (delete.tests.DeletionTests)\"]", "PASS_TO_PASS": "[\"test_fast_delete_combined_relationships (delete.tests.FastDeleteTests)\", \"test_fast_delete_fk (delete.tests.FastDeleteTests)\", \"test_fast_delete_inheritance (delete.tests.FastDeleteTests)\", \"test_fast_delete_instance_set_pk_none (delete.tests.FastDeleteTests)\", \"test_fast_delete_joined_qs (delete.tests.FastDeleteTests)\", \"test_fast_delete_large_batch (delete.tests.FastDeleteTests)\", \"test_fast_delete_m2m (delete.tests.FastDeleteTests)\", \"test_fast_delete_qs (delete.tests.FastDeleteTests)\", \"test_fast_delete_revm2m (delete.tests.FastDeleteTests)\", \"test_auto (delete.tests.OnDeleteTests)\", \"test_auto_nullable (delete.tests.OnDeleteTests)\", \"test_cascade (delete.tests.OnDeleteTests)\", \"test_cascade_from_child (delete.tests.OnDeleteTests)\", \"test_cascade_from_parent (delete.tests.OnDeleteTests)\", \"test_cascade_nullable (delete.tests.OnDeleteTests)\", \"test_do_nothing (delete.tests.OnDeleteTests)\", \"test_do_nothing_qscount (delete.tests.OnDeleteTests)\", \"test_inheritance_cascade_down (delete.tests.OnDeleteTests)\", \"test_inheritance_cascade_up (delete.tests.OnDeleteTests)\", \"test_non_callable (delete.tests.OnDeleteTests)\", \"test_o2o_setnull (delete.tests.OnDeleteTests)\", \"test_protect (delete.tests.OnDeleteTests)\", \"test_protect_multiple (delete.tests.OnDeleteTests)\", \"test_protect_path (delete.tests.OnDeleteTests)\", \"test_restrict (delete.tests.OnDeleteTests)\", \"test_restrict_gfk_no_fast_delete (delete.tests.OnDeleteTests)\", \"test_restrict_multiple (delete.tests.OnDeleteTests)\", \"test_restrict_path_cascade_direct (delete.tests.OnDeleteTests)\", \"test_restrict_path_cascade_indirect (delete.tests.OnDeleteTests)\", \"test_restrict_path_cascade_indirect_diamond (delete.tests.OnDeleteTests)\", \"test_setdefault (delete.tests.OnDeleteTests)\", \"test_setdefault_none (delete.tests.OnDeleteTests)\", \"test_setnull (delete.tests.OnDeleteTests)\", \"test_setnull_from_child (delete.tests.OnDeleteTests)\", \"test_setnull_from_parent (delete.tests.OnDeleteTests)\", \"test_setvalue (delete.tests.OnDeleteTests)\", \"test_bulk (delete.tests.DeletionTests)\", \"test_can_defer_constraint_checks (delete.tests.DeletionTests)\", \"test_delete_with_keeping_parents (delete.tests.DeletionTests)\", \"test_delete_with_keeping_parents_relationships (delete.tests.DeletionTests)\", \"test_deletion_order (delete.tests.DeletionTests)\", \"test_hidden_related (delete.tests.DeletionTests)\", \"test_instance_update (delete.tests.DeletionTests)\", \"test_large_delete (delete.tests.DeletionTests)\", \"test_large_delete_related (delete.tests.DeletionTests)\", \"test_m2m (delete.tests.DeletionTests)\", \"test_only_referenced_fields_selected (delete.tests.DeletionTests)\", \"test_proxied_model_duplicate_queries (delete.tests.DeletionTests)\", \"test_relational_post_delete_signals_happen_before_parent_object (delete.tests.DeletionTests)\"]", "environment_setup_commit": "0668164b4ac93a5be79f5b87fae83c657124d9ab", "test_directives": ["delete.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 delete.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/delete/tests.py b/tests/delete/tests.py\nindex d8424670c9..5512f889dd 100644\n--- a/tests/delete/tests.py\n+++ b/tests/delete/tests.py\n@@ -541,6 +541,20 @@ class DeletionTests(TestCase):\n HiddenUser.objects.create(r=r)\n HiddenUserProfile.objects.create(user=h1)\n HiddenUserProfile.objects.create(user=h2)\n+\n+ def test_queryset_delete_zero_objects(self):\n+ \"\"\"\n+ QuerySet.delete() should return a consistent result format when zero objects are deleted.\n+ \"\"\"\n+ # Test with a model that has foreign keys\n+ deleted, deleted_objs = R.objects.filter(pk=-1).delete()\n+ self.assertEqual(deleted, 0)\n+ self.assertEqual(deleted_objs, {'tests.R': 0})\n+\n+ # Test with a simple model without foreign keys\n+ deleted, deleted_objs = Avatar.objects.filter(pk=-1).delete()\n+ self.assertEqual(deleted, 0)\n+ self.assertEqual(deleted_objs, {'tests.Avatar': 0})\n m1 = M.objects.create()\n m2 = M.objects.create()\n MR.objects.create(r=r, m=m1)\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["delete.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py\nindex 16dff6a1cd..b8172d1594 100644\n--- a/django/db/models/deletion.py\n+++ b/django/db/models/deletion.py\n@@ -393,7 +393,8 @@ class Collector:\n instance = list(instances)[0]\n if self.can_fast_delete(instance):\n with transaction.mark_for_rollback_on_error():\n- count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)\n+ result = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)\n+ count = result.get(model._meta.label, 0)\n setattr(instance, model._meta.pk.attname, None)\n return count, {model._meta.label: count}\n \n@@ -425,7 +426,8 @@ class Collector:\n for model, instances in self.data.items():\n query = sql.DeleteQuery(model)\n pk_list = [obj.pk for obj in instances]\n- count = query.delete_batch(pk_list, self.using)\n+ result = query.delete_batch(pk_list, self.using)\n+ count = result.get(model._meta.label, 0)\n deleted_counter[model._meta.label] += count\n \n if not model._meta.auto_created:\n\ndiff --git a/django/db/models/sql/subqueries.py b/django/db/models/sql/subqueries.py\nindex 72b6712864..bea9d6e7ab 100644\n--- a/django/db/models/sql/subqueries.py\n+++ b/django/db/models/sql/subqueries.py\n@@ -29,6 +29,7 @@ class DeleteQuery(Query):\n def delete_batch(self, pk_list, using):\n \"\"\"\n Set up and execute delete queries for all the objects in pk_list.\n+ Ensure the result dictionary is always populated with model labels.\n \n More than one physical query may be executed if there are a\n lot of values in pk_list.\n@@ -36,12 +37,13 @@ class DeleteQuery(Query):\n # number of objects deleted\n num_deleted = 0\n field = self.get_meta().pk\n+ model_label = self.get_meta().label\n for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):\n self.where = self.where_class()\n self.add_q(Q(\n **{field.attname + '__in': pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]}))\n num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)\n- return num_deleted\n+ return {model_label: num_deleted}\n \n \n class UpdateQuery(Query):\n", "model_lint_repair_patch": "diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py\nindex 16dff6a1cd..b8172d1594 100644\n--- a/django/db/models/deletion.py\n+++ b/django/db/models/deletion.py\n@@ -393,7 +393,8 @@ class Collector:\n instance = list(instances)[0]\n if self.can_fast_delete(instance):\n with transaction.mark_for_rollback_on_error():\n- count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)\n+ result = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)\n+ count = result.get(model._meta.label, 0)\n setattr(instance, model._meta.pk.attname, None)\n return count, {model._meta.label: count}\n \n@@ -425,7 +426,8 @@ class Collector:\n for model, instances in self.data.items():\n query = sql.DeleteQuery(model)\n pk_list = [obj.pk for obj in instances]\n- count = query.delete_batch(pk_list, self.using)\n+ result = query.delete_batch(pk_list, self.using)\n+ count = result.get(model._meta.label, 0)\n deleted_counter[model._meta.label] += count\n \n if not model._meta.auto_created:\n\ndiff --git a/django/db/models/sql/subqueries.py b/django/db/models/sql/subqueries.py\nindex 72b6712864..bea9d6e7ab 100644\n--- a/django/db/models/sql/subqueries.py\n+++ b/django/db/models/sql/subqueries.py\n@@ -29,6 +29,7 @@ class DeleteQuery(Query):\n def delete_batch(self, pk_list, using):\n \"\"\"\n Set up and execute delete queries for all the objects in pk_list.\n+ Ensure the result dictionary is always populated with model labels.\n \n More than one physical query may be executed if there are a\n lot of values in pk_list.\n@@ -36,12 +37,13 @@ class DeleteQuery(Query):\n # number of objects deleted\n num_deleted = 0\n field = self.get_meta().pk\n+ model_label = self.get_meta().label\n for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):\n self.where = self.where_class()\n self.add_q(Q(\n **{field.attname + '__in': pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]}))\n num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)\n- return num_deleted\n+ return {model_label: num_deleted}\n \n \n class UpdateQuery(Query):\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-12471", "base_commit": "02dc9ed680e7f53f1b0d410dcdd37341c7958eb1", "patch": "diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py\n--- a/sklearn/preprocessing/_encoders.py\n+++ b/sklearn/preprocessing/_encoders.py\n@@ -110,7 +110,14 @@ def _transform(self, X, handle_unknown='error'):\n # continue `The rows are marked `X_mask` and will be\n # removed later.\n X_mask[:, i] = valid_mask\n- Xi = Xi.copy()\n+ # cast Xi into the largest string type necessary\n+ # to handle different lengths of numpy strings\n+ if (self.categories_[i].dtype.kind in ('U', 'S')\n+ and self.categories_[i].itemsize > Xi.itemsize):\n+ Xi = Xi.astype(self.categories_[i].dtype)\n+ else:\n+ Xi = Xi.copy()\n+\n Xi[~valid_mask] = self.categories_[i][0]\n _, encoded = _encode(Xi, self.categories_[i], encode=True)\n X_int[:, i] = encoded\n", "test_patch": "diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py\n--- a/sklearn/preprocessing/tests/test_encoders.py\n+++ b/sklearn/preprocessing/tests/test_encoders.py\n@@ -273,6 +273,23 @@ def test_one_hot_encoder_no_categorical_features():\n assert enc.categories_ == []\n \n \n+def test_one_hot_encoder_handle_unknown_strings():\n+ X = np.array(['11111111', '22', '333', '4444']).reshape((-1, 1))\n+ X2 = np.array(['55555', '22']).reshape((-1, 1))\n+ # Non Regression test for the issue #12470\n+ # Test the ignore option, when categories are numpy string dtype\n+ # particularly when the known category strings are larger\n+ # than the unknown category strings\n+ oh = OneHotEncoder(handle_unknown='ignore')\n+ oh.fit(X)\n+ X2_passed = X2.copy()\n+ assert_array_equal(\n+ oh.transform(X2_passed).toarray(),\n+ np.array([[0., 0., 0., 0.], [0., 1., 0., 0.]]))\n+ # ensure transformed data was not modified in place\n+ assert_array_equal(X2, X2_passed)\n+\n+\n @pytest.mark.parametrize(\"output_dtype\", [np.int32, np.float32, np.float64])\n @pytest.mark.parametrize(\"input_dtype\", [np.int32, np.float32, np.float64])\n def test_one_hot_encoder_dtype(input_dtype, output_dtype):\n", "problem_statement": "OneHotEncoder ignore unknown error when categories are strings \n#### Description\r\n\r\nThis bug is very specific, but it happens when you set OneHotEncoder to ignore unknown entries.\r\nand your labels are strings. The memory of the arrays is not handled safely and it can lead to a ValueError\r\n\r\nBasically, when you call the transform method it will sets all the unknown strings on your array to OneHotEncoder.categories_[i][0] which is the first category alphabetically sorted given for fit\r\nIf this OneHotEncoder.categories_[i][0] is a long string, and the array that you want to transform has small strings, then it is impossible to fit the whole OneHotEncoder.categories_[i][0] into the entries of the array we want to transform. So OneHotEncoder.categories_[i][0] is truncated and this raise the ValueError.\r\n\r\n\r\n\r\n#### Steps/Code to Reproduce\r\n```\r\n\r\nimport numpy as np\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n\r\n\r\n# It needs to be numpy arrays, the error does not appear \r\n# is you have lists of lists because it gets treated like an array of objects.\r\ntrain = np.array([ '22','333','4444','11111111' ]).reshape((-1,1))\r\ntest = np.array([ '55555', '22' ]).reshape((-1,1))\r\n\r\nohe = OneHotEncoder(dtype=bool,handle_unknown='ignore')\r\n\r\nohe.fit( train )\r\nenc_test = ohe.transform( test )\r\n\r\n```\r\n\r\n\r\n#### Expected Results\r\nHere we should get an sparse matrix 2x4 false everywhere except at (1,1) the '22' that is known\r\n\r\n#### Actual Results\r\n\r\n> ValueError: y contains previously unseen labels: ['111111']\r\n\r\n\r\n#### Versions\r\nSystem:\r\n python: 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609]\r\n machine: Linux-4.4.0-138-generic-x86_64-with-Ubuntu-16.04-xenial\r\nexecutable: /usr/bin/python\r\n\r\nBLAS:\r\n macros: HAVE_CBLAS=None\r\ncblas_libs: openblas, openblas\r\n lib_dirs: /usr/lib\r\n\r\nPython deps:\r\n Cython: 0.25.2\r\n scipy: 0.18.1\r\nsetuptools: 36.7.0\r\n pip: 9.0.1\r\n numpy: 1.15.2\r\n pandas: 0.19.1\r\n sklearn: 0.21.dev0\r\n\r\n\r\n\r\n#### Comments\r\n\r\nI already implemented a fix for this issue, where I check the size of the elements in the array before, and I cast them into objects if necessary.\n", "hints_text": "", "created_at": "2018-10-27T10:43:48Z", "version": "0.21", "FAIL_TO_PASS": "[\"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings\"]", "PASS_TO_PASS": "[\"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_sparse\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dense\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_deprecationwarnings\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_force_new_behaviour\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categorical_features\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_not_fitted\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_no_categorical_features\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-int32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float64]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-int32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float64]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-int32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float64]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[int32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float32]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float64]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_set_params\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[mixed]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[string]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-cat]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_unsorted_categories\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories_mixed_columns\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_pandas\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_raise_missing[error-numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_raise_missing[error-object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_raise_missing[ignore-numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_raise_missing[ignore-object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[mixed]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object-string-cat]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_inverse\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_missing[numeric]\", \"sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_missing[object]\", \"sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes\", \"sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes_pandas\", \"sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_warning\"]", "environment_setup_commit": "7813f7efb5b2012412888b69e73d76f2df2b50b6", "test_directives": ["sklearn/preprocessing/tests/test_encoders.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v sklearn/preprocessing/tests/test_encoders.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py\nindex d5ac50a25..ad47379aa 100644\n--- a/sklearn/preprocessing/tests/test_encoders.py\n+++ b/sklearn/preprocessing/tests/test_encoders.py\n@@ -230,6 +230,19 @@ def test_one_hot_encoder_handle_unknown():\n X = np.array([[0, 2, 1], [1, 0, 3], [1, 0, 2]])\n X2 = np.array([[4, 1, 1]])\n \n+ # Test for the specific issue with string categories\n+ train = np.array(['22', '333', '4444', '11111111']).reshape((-1, 1))\n+ test = np.array(['55555', '22']).reshape((-1, 1))\n+\n+ ohe = OneHotEncoder(dtype=bool, handle_unknown='ignore')\n+ ohe.fit(train)\n+ enc_test = ohe.transform(test)\n+\n+ expected_output = np.array([[False, False, False, False],\n+ [False, True, False, False]])\n+\n+ assert_array_equal(enc_test.toarray(), expected_output)\n+\n # Test that one hot encoder raises error for unknown features\n # present during transform.\n oh = OneHotEncoder(handle_unknown='error')\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["sklearn/preprocessing/tests/test_encoders.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py\nindex 1e05aba59..37cc50263 100644\n--- a/sklearn/preprocessing/_encoders.py\n+++ b/sklearn/preprocessing/_encoders.py\n@@ -55,6 +55,10 @@ class _BaseEncoder(BaseEstimator, TransformerMixin):\n if _object_dtype_isnan(X).any():\n raise ValueError(\"Input contains NaN\")\n \n+ # Cast to object to avoid truncation errors\n+ if np.issubdtype(X.dtype, np.str_):\n+ X = X.astype(np.object)\n+\n return X\n \n def _fit(self, X, handle_unknown='error'):\n@@ -111,6 +115,9 @@ class _BaseEncoder(BaseEstimator, TransformerMixin):\n # removed later.\n X_mask[:, i] = valid_mask\n Xi = Xi.copy()\n+ # Cast to object to avoid truncation errors\n+ if np.issubdtype(Xi.dtype, np.str_):\n+ Xi = Xi.astype(np.object)\n Xi[~valid_mask] = self.categories_[i][0]\n _, encoded = _encode(Xi, self.categories_[i], encode=True)\n X_int[:, i] = encoded\n@@ -550,6 +557,10 @@ class OneHotEncoder(_BaseEncoder):\n self._n_values == 'auto'):\n out = out[:, self._active_features_]\n \n+ # Cast to object to avoid truncation errors\n+ if np.issubdtype(X.dtype, np.str_):\n+ X = X.astype(np.object)\n+\n return out if self.sparse else out.toarray()\n \n def _transform_new(self, X):\n", "model_lint_repair_patch": "diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py\nindex 1e05aba59..37cc50263 100644\n--- a/sklearn/preprocessing/_encoders.py\n+++ b/sklearn/preprocessing/_encoders.py\n@@ -55,6 +55,10 @@ class _BaseEncoder(BaseEstimator, TransformerMixin):\n if _object_dtype_isnan(X).any():\n raise ValueError(\"Input contains NaN\")\n \n+ # Cast to object to avoid truncation errors\n+ if np.issubdtype(X.dtype, np.str_):\n+ X = X.astype(np.object)\n+\n return X\n \n def _fit(self, X, handle_unknown='error'):\n@@ -111,6 +115,9 @@ class _BaseEncoder(BaseEstimator, TransformerMixin):\n # removed later.\n X_mask[:, i] = valid_mask\n Xi = Xi.copy()\n+ # Cast to object to avoid truncation errors\n+ if np.issubdtype(Xi.dtype, np.str_):\n+ Xi = Xi.astype(np.object)\n Xi[~valid_mask] = self.categories_[i][0]\n _, encoded = _encode(Xi, self.categories_[i], encode=True)\n X_int[:, i] = encoded\n@@ -550,6 +557,10 @@ class OneHotEncoder(_BaseEncoder):\n self._n_values == 'auto'):\n out = out[:, self._active_features_]\n \n+ # Cast to object to avoid truncation errors\n+ if np.issubdtype(X.dtype, np.str_):\n+ X = X.astype(np.object)\n+\n return out if self.sparse else out.toarray()\n \n def _transform_new(self, X):\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-14608", "base_commit": "7f33c1e22dbc34a7afae7967783725b10f1f13b1", "patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -333,7 +333,7 @@ def full_clean(self):\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@@ -380,7 +380,10 @@ def full_clean(self):\n # Give self.clean() a chance to do cross-form validation.\n self.clean()\n except ValidationError as e:\n- self._non_form_errors = self.error_class(e.error_list)\n+ self._non_form_errors = self.error_class(\n+ e.error_list,\n+ error_class='nonform'\n+ )\n \n def clean(self):\n \"\"\"\n", "test_patch": "diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py\n--- a/tests/admin_views/tests.py\n+++ b/tests/admin_views/tests.py\n@@ -3348,7 +3348,10 @@ def test_non_form_errors_is_errorlist(self):\n response = self.client.post(reverse('admin:admin_views_person_changelist'), data)\n non_form_errors = response.context['cl'].formset.non_form_errors()\n self.assertIsInstance(non_form_errors, ErrorList)\n- self.assertEqual(str(non_form_errors), str(ErrorList([\"Grace is not a Zombie\"])))\n+ self.assertEqual(\n+ str(non_form_errors),\n+ str(ErrorList(['Grace is not a Zombie'], error_class='nonform')),\n+ )\n \n def test_list_editable_ordering(self):\n collector = Collector.objects.create(id=1, name=\"Frederick Clegg\")\ndiff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py\n--- a/tests/forms_tests/tests/test_formsets.py\n+++ b/tests/forms_tests/tests/test_formsets.py\n@@ -337,6 +337,10 @@ def test_formset_validate_max_flag(self):\n formset = ChoiceFormSet(data, auto_id=False, prefix='choices')\n self.assertFalse(formset.is_valid())\n self.assertEqual(formset.non_form_errors(), ['Please submit at most 1 form.'])\n+ self.assertEqual(\n+ str(formset.non_form_errors()),\n+ '
  • Please submit at most 1 form.
',\n+ )\n \n def test_formset_validate_min_flag(self):\n \"\"\"\n@@ -359,6 +363,11 @@ def test_formset_validate_min_flag(self):\n formset = ChoiceFormSet(data, auto_id=False, prefix='choices')\n self.assertFalse(formset.is_valid())\n self.assertEqual(formset.non_form_errors(), ['Please submit at least 3 forms.'])\n+ self.assertEqual(\n+ str(formset.non_form_errors()),\n+ '
  • '\n+ 'Please submit at least 3 forms.
',\n+ )\n \n def test_formset_validate_min_unchanged_forms(self):\n \"\"\"\n@@ -983,6 +992,11 @@ def test_non_form_errors(self):\n formset = FavoriteDrinksFormSet(data, prefix='drinks')\n self.assertFalse(formset.is_valid())\n self.assertEqual(formset.non_form_errors(), ['You may only specify a drink once.'])\n+ self.assertEqual(\n+ str(formset.non_form_errors()),\n+ '
  • '\n+ 'You may only specify a drink once.
',\n+ )\n \n def test_formset_iteration(self):\n \"\"\"Formset instances are iterable.\"\"\"\n", "problem_statement": "Add `nonform` CSS class for non form errors in FormSets\nDescription\n\t \n\t\t(last modified by Ties Jan Hefting)\n\t \nForms add the nonfield CSS class for non field errors in ErrorList instances. This is documented in a section on \u200brendering form error messages. Similarly, in FormSets I'd expect to see the nonform CSS class added for non form errors. This would allow a custom ErrorList to make a distinction in form field errors, non field errors (forms) and non form errors (FormSets) when rendering error messages. Therefore I'd suggest to add this nonform CSS class and document it for developers to use.\n", "hints_text": "Seems reasonable (similar to #11776).\n\u200bPR", "created_at": "2021-07-07T19:51:30Z", "version": "4.0", "FAIL_TO_PASS": "[\"If validate_max is set and max_num is less than TOTAL_FORMS in the\", \"If validate_min is set and min_num is more than TOTAL_FORMS in the\", \"test_non_form_errors (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_non_form_errors_is_errorlist (admin_views.tests.AdminViewListEditable)\"]", "PASS_TO_PASS": "[\"all_valid() validates all forms, even when some are invalid.\", \"test_valid (forms_tests.tests.test_formsets.AllValidTests)\", \"is_multipart() works with an empty formset.\", \"An empty formset still calls clean()\", \"Media is available on empty formset.\", \"test_customize_management_form_error (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_empty_forms_are_unbound (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_form_errors_are_caught_by_formset (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_management_form_invalid_data (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_no_data_error (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_with_management_data_attrs_work_fine (forms_tests.tests.test_formsets.TestIsBoundBehavior)\", \"test_as_p (forms_tests.tests.test_formsets.FormsetAsTagTests)\", \"test_as_table (forms_tests.tests.test_formsets.FormsetAsTagTests)\", \"test_as_ul (forms_tests.tests.test_formsets.FormsetAsTagTests)\", \"test_absolute_max (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_absolute_max_invalid (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_absolute_max_with_max_num (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"A FormSet constructor takes the same arguments as Form. Create a\", \"A form that's displayed as blank may be submitted as blank.\", \"test_can_delete_extra_formset_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"FormSets have a clean() hook for doing extra validation that isn't tied\", \"test_default_absolute_max (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"Deleting prefilled data is an error. Removing data from form fields\", \"test_disable_delete_extra_formset_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"More than 1 empty form can be displayed using formset_factory's\", \"Ordering fields are allowed to be left blank. If they are left blank,\", \"test_form_kwargs_empty_form (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"Custom kwargs set on the formset instance are passed to the\", \"Form kwargs can be passed dynamically in a formset.\", \"Formsets call is_valid() on each form.\", \"Formset's forms use the formset's error_class.\", \"FormSet.has_changed() is True if any data is passed to its forms, even\", \"A FormSet can be prefilled with existing data by providing a list of\", \"Formset instances are iterable.\", \"A formsets without any forms evaluates as True.\", \"Formset works with SplitDateTimeField(initial=datetime.datetime.now).\", \"A valid formset should have 0 total errors.\", \"test_formset_total_error_count_with_non_form_errors (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_formset_validate_min_excludes_empty_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"min_num validation doesn't consider unchanged forms with initial data\", \"test_formset_validation (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"A formset's ManagementForm is validated once per FormSet.is_valid()\", \"formset_factory's can_delete argument adds a boolean \\\"delete\\\" field to\", \"deleted_forms works on a valid formset even if a deleted form would\", \"If a form is filled with something and can_delete is also checked, that\", \"FormSets with ordering + deletion.\", \"test_formsets_with_order_custom_widget (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"formset_factory's can_order argument adds an integer field to each\", \"A formset has a hard limit on the number of forms instantiated.\", \"test_html_safe (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"Can increase the built-in forms limit via a higher max_num.\", \"Can get ordered_forms from a valid formset even if a deleted form\", \"test_limited_max_forms_two (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"max_num has no effect when extra is less than max_num.\", \"Limiting the maximum number of forms with max_num.\", \"The management form has the correct prefix.\", \"test_max_num_with_initial_data (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"If max_num is 0 then no form is rendered at all, regardless of extra,\", \"test_max_num_zero_with_initial (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"More than 1 empty form can also be displayed using formset_factory's\", \"More than 1 empty form can be displayed using min_num.\", \"The extra argument works when the formset is pre-filled with initial\", \"One form from initial and extra=3 with max_num=2 results in the one\", \"More initial forms than max_num results in all initial forms being\", \"If non_form_errors() is called without calling is_valid() first,\", \"Ordering works with blank fieldsets.\", \"If at least one field is filled out on a blank form, it will be\", \"A partially completed form is invalid.\", \"Just one form may be completed.\", \"test_validate_max_ignores_forms_marked_for_deletion (forms_tests.tests.test_formsets.FormsFormsetTestCase)\", \"test_should_be_able_to_edit_related_objects_on_add_view (admin_views.tests.AdminCustomSaveRelatedTests)\", \"test_should_be_able_to_edit_related_objects_on_change_view (admin_views.tests.AdminCustomSaveRelatedTests)\", \"test_should_be_able_to_edit_related_objects_on_changelist_view (admin_views.tests.AdminCustomSaveRelatedTests)\", \"test_explicitly_provided_pk (admin_views.tests.GetFormsetsWithInlinesArgumentTest)\", \"test_implicitly_generated_pk (admin_views.tests.GetFormsetsWithInlinesArgumentTest)\", \"test_lang_name_present (admin_views.tests.ValidXHTMLTests)\", \"test_secure_view_shows_login_if_not_logged_in (admin_views.tests.SecureViewTests)\", \"Staff_member_required decorator works with an argument\", \"Admin index views don't break when user's ModelAdmin removes standard urls\", \"Test for ticket 2445 changes to admin.\", \"test_generic_content_object_in_list_display (admin_views.tests.TestGenericRelations)\", \"InlineModelAdmin broken?\", \"test_client_logout_url_can_be_used_to_login (admin_views.tests.AdminViewLogoutTests)\", \"test_logout (admin_views.tests.AdminViewLogoutTests)\", \"Validate that a custom ChangeList class can be used (#9749)\", \"The delete_view handles non-ASCII characters\", \"A test to ensure that POST on edit_view handles non-ASCII characters.\", \"test_form_has_multipart_enctype (admin_views.tests.AdminInlineFileUploadTest)\", \"Inline file uploads correctly display prior data (#10002).\", \"test_all_fields_hidden (admin_views.tests.TestLabelVisibility)\", \"test_all_fields_visible (admin_views.tests.TestLabelVisibility)\", \"test_mixin (admin_views.tests.TestLabelVisibility)\", \"Inline models which inherit from a common parent are correctly handled.\", \"change_view has form_url in response.context\", \"The behavior for setting initial form data can be overridden in the\", \"The right link is displayed if view_on_site is a callable\", \"The 'View on site' button is not displayed if view_on_site is False\", \"The 'View on site' button is displayed if view_on_site is True\", \"test_known_url_missing_slash_redirects_login_if_not_authenticated (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_known_url_missing_slash_redirects_with_slash_if_not_authenticated_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_known_url_redirects_login_if_not_authenticated (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_known_url_redirects_login_if_not_authenticated_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_false (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_false_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_true (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_true_force_script_name (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_true_non_staff_user (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_true_script_name (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_true_unknown_url (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_true_unknown_url_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_missing_slash_append_slash_true_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_non_admin_url_404_if_not_authenticated (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_non_admin_url_shares_url_prefix (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_non_admin_url_shares_url_prefix_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_single_model_no_append_slash (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_unknown_url_404_if_authenticated (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_unknown_url_404_if_authenticated_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_unknown_url_404_if_not_authenticated_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_unknown_url_redirects_login_if_not_authenticated (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_unkown_url_without_trailing_slash_if_not_authenticated (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_unkown_url_without_trailing_slash_if_not_authenticated_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_url_without_trailing_slash_if_not_authenticated (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"test_url_without_trailing_slash_if_not_authenticated_without_final_catch_all_view (admin_views.tests.AdminSiteFinalCatchAllPatternTests)\", \"Regression test for #15938: if USE_THOUSAND_SEPARATOR is set, make sure\", \"test_prepopulated_off (admin_views.tests.PrePopulatedTest)\", \"test_prepopulated_on (admin_views.tests.PrePopulatedTest)\", \"PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug'\", \"PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug'. That\", \"test_add (admin_views.tests.AdminViewProxyModelPermissionsTests)\", \"test_change (admin_views.tests.AdminViewProxyModelPermissionsTests)\", \"test_delete (admin_views.tests.AdminViewProxyModelPermissionsTests)\", \"test_view (admin_views.tests.AdminViewProxyModelPermissionsTests)\", \"test_custom_admin_site_app_index_view_and_template (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_index_view_and_template (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_login_form (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_login_template (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_logout_template (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_password_change_done_template (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_password_change_template (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_password_change_with_extra_context (admin_views.tests.CustomModelAdminTest)\", \"test_custom_admin_site_view (admin_views.tests.CustomModelAdminTest)\", \"test_pwd_change_custom_template (admin_views.tests.CustomModelAdminTest)\", \"test_group_permission_performance (admin_views.tests.GroupAdminTest)\", \"test_save_button (admin_views.tests.GroupAdminTest)\", \"Regression test for 14880\", \"Regression test for 20182\", \"Should be able to use a ModelAdmin method in list_display that has the\", \"The minified versions of the JS files are only used when DEBUG is False.\", \"Issue #20522\", \"The view_on_site value is either a boolean or a callable\", \"None is returned if model doesn't have get_absolute_url\", \"The default behavior is followed if view_on_site is True\", \"Cyclic relationships should still cause each object to only be\", \"The delete view uses ModelAdmin.get_deleted_objects().\", \"If a deleted object has GenericForeignKeys pointing to it,\", \"If a deleted object has GenericForeignKey with\", \"In the case of an inherited model, if either the child or\", \"If a deleted object has two relationships pointing to it from\", \"If a deleted object has two relationships from another model,\", \"Objects should be nested to display the relationships that\", \"test_not_registered (admin_views.tests.AdminViewDeletedObjectsTest)\", \"test_perms_needed (admin_views.tests.AdminViewDeletedObjectsTest)\", \"A POST request to delete protected objects should display the page\", \"test_post_delete_restricted (admin_views.tests.AdminViewDeletedObjectsTest)\", \"test_protected (admin_views.tests.AdminViewDeletedObjectsTest)\", \"test_restricted (admin_views.tests.AdminViewDeletedObjectsTest)\", \"Saving a new object using \\\"Save as new\\\" redirects to the changelist\", \"'save as' creates a new person\", \"test_save_as_new_with_inlines_with_validation_errors (admin_views.tests.SaveAsTests)\", \"When you click \\\"Save as new\\\" and have a validation error,\", \"test_save_as_new_with_validation_errors_with_inlines (admin_views.tests.SaveAsTests)\", \"No date hierarchy links display with empty changelist.\", \"year-level links appear for year-spanning changelist.\", \"test_related_field (admin_views.tests.DateHierarchyTests)\", \"Single day-level date hierarchy appears for single object.\", \"day-level links appear for changelist within single month.\", \"month-level links appear for changelist within single year.\", \"test_message_debug (admin_views.tests.AdminUserMessageTest)\", \"test_message_error (admin_views.tests.AdminUserMessageTest)\", \"test_message_extra_tags (admin_views.tests.AdminUserMessageTest)\", \"test_message_info (admin_views.tests.AdminUserMessageTest)\", \"test_message_success (admin_views.tests.AdminUserMessageTest)\", \"test_message_warning (admin_views.tests.AdminUserMessageTest)\", \"Object history button link should work and contain the pk value quoted.\", \"Link to the changeform of the object in changelist should use reverse() and be quoted -- #18072\", \"The link from the delete confirmation page referring back to the changeform of the object should be quoted\", \"Retrieving the object using urlencoded form of primary key should work\", \"Retrieving the history for an object using urlencoded form of primary\", \"The link from the recent actions list referring to the changeform of the object should be quoted\", \"As soon as an object is added using \\\"Save and continue editing\\\"\", \"'View on site should' work properly with char fields\", \"A model with a primary key that ends with add or is `add` should be visible\", \"A model with a primary key that ends with delete should be visible\", \"A model with a primary key that ends with history should be visible\", \"Check the never-cache status of the JavaScript i18n view\", \"Check the never-cache status of the main index\", \"Check the never-cache status of an application index\", \"Check the never-cache status of login views\", \"Check the never-cache status of logout view\", \"Check the never-cache status of a model add page\", \"Check the never-cache status of a model delete page\", \"Check the never-cache status of a model history page\", \"Check the never-cache status of a model index\", \"Check the never-cache status of a model edit page\", \"Check the never-cache status of the password change view\", \"Check the never-cache status of the password change done view\", \"Ensure app and model tag are correctly read by app_index template\", \"Ensure app and model tag are correctly read by delete_confirmation\", \"Ensure app and model tag are correctly read by\", \"Ensure app and model tag are correctly read by change_form template\", \"Ensure app and model tag are correctly read by change_list template\", \"Cells of the change list table should contain the field name in their class attribute\", \"Fields have a CSS class name with a 'field-' prefix.\", \"CSS class names are used for each app and model on the admin index\", \"test_change_password_template (admin_views.tests.AdminCustomTemplateTests)\", \"test_custom_model_admin_templates (admin_views.tests.AdminCustomTemplateTests)\", \"The admin/change_list.html' template uses block.super\", \"The admin/change_form.html template uses block.super in the\", \"The admin/delete_confirmation.html template uses\", \"The admin/delete_selected_confirmation.html template uses\", \"The admin/index.html template uses block.super in the bodyclass block.\", \"The admin/login.html template uses block.super in the\", \"A custom template can be used to render an admin filter.\", \"test_changelist_input_html (admin_views.tests.AdminViewListEditable)\", \"test_custom_pk (admin_views.tests.AdminViewListEditable)\", \"test_inheritance (admin_views.tests.AdminViewListEditable)\", \"test_inheritance_2 (admin_views.tests.AdminViewListEditable)\", \"test_list_editable_action_choices (admin_views.tests.AdminViewListEditable)\", \"test_list_editable_action_submit (admin_views.tests.AdminViewListEditable)\", \"test_list_editable_ordering (admin_views.tests.AdminViewListEditable)\", \"Pagination works for list_editable items.\", \"Fields should not be list-editable in popups.\", \"Non-field errors are displayed for each of the forms in the\", \"test_non_form_errors (admin_views.tests.AdminViewListEditable)\", \"hidden pk fields aren't displayed in the table body and their\", \"Similarly as test_pk_hidden_fields, but when the hidden pk fields are\", \"test_post_messages (admin_views.tests.AdminViewListEditable)\", \"test_post_submission (admin_views.tests.AdminViewListEditable)\", \"A model with a character PK can be saved as inlines. Regression for #10992\", \"A model with an explicit autofield primary key can be saved as inlines. Regression for #8093\", \"An inherited model can be saved as inlines. Regression for #11042\", \"A model with an integer PK can be saved as inlines. Regression for #10992\", \"An inline with an editable ordering fields is updated correctly.\", \"A simple model can be saved as inlines\", \"test_add_view (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_add_view_without_preserved_filters (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_assert_url_equal (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_change_view (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_change_view_without_preserved_filters (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_changelist_view (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_delete_view (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_url_prefix (admin_views.tests.NamespacedAdminKeepChangeListFiltersTests)\", \"test_beginning_matches (admin_views.tests.AdminSearchTest)\", \"test_exact_matches (admin_views.tests.AdminSearchTest)\", \"#8408 -- \\\"Show all\\\" should be displayed instead of the total count if\", \"test_pluggable_search (admin_views.tests.AdminSearchTest)\", \"Test presence of reset link in search bar (\\\"1 result (_x total_)\\\").\", \"A search that mentions sibling models\", \"test_search_with_spaces (admin_views.tests.AdminSearchTest)\", \"The to_field GET parameter is preserved when a search is performed.\", \"test_form_url_present_in_context (admin_views.tests.UserAdminTest)\", \"test_password_mismatch (admin_views.tests.UserAdminTest)\", \"test_save_add_another_button (admin_views.tests.UserAdminTest)\", \"test_save_button (admin_views.tests.UserAdminTest)\", \"test_save_continue_editing_button (admin_views.tests.UserAdminTest)\", \"User addition through a FK popup should return the appropriate JavaScript response.\", \"User change through a FK popup should return the appropriate JavaScript response.\", \"User deletion through a FK popup should return the appropriate JavaScript response.\", \"test_user_permission_performance (admin_views.tests.UserAdminTest)\", \"test_add_view (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_add_view_without_preserved_filters (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_assert_url_equal (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_change_view (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_change_view_without_preserved_filters (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_changelist_view (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_delete_view (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_url_prefix (admin_views.tests.AdminKeepChangeListFiltersTests)\", \"test_add_model_modeladmin_defer_qs (admin_views.tests.AdminCustomQuerysetTest)\", \"test_add_model_modeladmin_only_qs (admin_views.tests.AdminCustomQuerysetTest)\", \"test_change_view (admin_views.tests.AdminCustomQuerysetTest)\", \"test_changelist_view (admin_views.tests.AdminCustomQuerysetTest)\", \"test_changelist_view_count_queries (admin_views.tests.AdminCustomQuerysetTest)\", \"test_edit_model_modeladmin_defer_qs (admin_views.tests.AdminCustomQuerysetTest)\", \"test_edit_model_modeladmin_only_qs (admin_views.tests.AdminCustomQuerysetTest)\", \"Custom querysets are considered for the admin history view.\", \"test_filters (admin_views.tests.AdminDocsTest)\", \"test_tags (admin_views.tests.AdminDocsTest)\", \"Regression test for #17911.\", \"Make sure that non-field readonly elements are properly autoescaped (#24461)\", \"test_label_suffix_translated (admin_views.tests.ReadonlyTest)\", \"Regression test for #22087 - ModelForm Meta overrides are ignored by\", \"ForeignKey readonly fields render as links if the target model is\", \"test_readonly_get (admin_views.tests.ReadonlyTest)\", \"Regression test for #13004\", \"Regression test for #16433 - backwards references for related objects\", \"test_readonly_manytomany_forwards_ref (admin_views.tests.ReadonlyTest)\", \"Can reference a reverse OneToOneField in ModelAdmin.readonly_fields.\", \"test_readonly_post (admin_views.tests.ReadonlyTest)\", \"test_readonly_text_field (admin_views.tests.ReadonlyTest)\", \"test_user_password_change_limited_queryset (admin_views.tests.ReadonlyTest)\", \"Test add view restricts access and actually adds items.\", \"User with add permission to a section but view-only for inlines.\", \"If a user has no module perms, the app list returns a 404.\", \"Change view should restrict access and allow users to edit items.\", \"'Save as new' should raise PermissionDenied for users without the 'add'\", \"User has view and add permissions on the inline model.\", \"User has view and delete permissions on the inline model.\", \"User with change permission to a section but view-only for inlines.\", \"The object should be read-only if the user has permission to view it\", \"The foreign key widget should only show the \\\"add related\\\" button if the\", \"The foreign key widget should only show the \\\"change related\\\" button if\", \"The foreign key widget should only show the \\\"delete related\\\" button if\", \"Delete view should restrict access and actually delete items.\", \"test_delete_view_nonexistent_obj (admin_views.tests.AdminViewPermissionsTest)\", \"The delete view allows users to delete collected objects without a\", \"test_disabled_permissions_when_logged_in (admin_views.tests.AdminViewPermissionsTest)\", \"test_disabled_staff_permissions_when_logged_in (admin_views.tests.AdminViewPermissionsTest)\", \"Regression test for #19327\", \"has_module_permission() returns True for all users who\", \"History view should restrict access.\", \"test_history_view_bad_url (admin_views.tests.AdminViewPermissionsTest)\", \"Make sure only staff members can log in.\", \"test_login_has_permission (admin_views.tests.AdminViewPermissionsTest)\", \"A logged-in non-staff user trying to access the admin index should be\", \"Login redirect should be to the admin index page when going directly to\", \"test_login_successfully_redirects_to_original_URL (admin_views.tests.AdminViewPermissionsTest)\", \"If has_module_permission() always returns False, the module shouldn't\", \"Post-save message shouldn't contain a link to the change form if the\", \"Only admin users should be able to use the admin shortcut view.\", \"Check if L10N is deactivated, the JavaScript i18n view doesn't\", \"test_add_with_GET_args (admin_views.tests.AdminViewBasicTest)\", \"#13749 - Admin should display link to front-end site 'View site'\", \"Regressions test for ticket 15103 - filtering on fields defined in a\", \"AttributeErrors are allowed to bubble when raised inside a change list\", \"test_app_index_context (admin_views.tests.AdminViewBasicTest)\", \"A smoke test to ensure GET on the add_view works.\", \"A smoke test to ensure POST on add_view works.\", \"A smoke test to ensure GET on the change_view works.\", \"The change URL changed in Django 1.9, but the old one still redirects.\", \"GET on the change_view (when passing a string as the PK argument for a\", \"A smoke test to ensure POST on edit_view works.\", \"GET on the change_view (for inherited models) redirects to the index\", \"test_change_list_column_field_classes (admin_views.tests.AdminViewBasicTest)\", \"test_change_list_null_boolean_display (admin_views.tests.AdminViewBasicTest)\", \"Ensure we can sort on a list_display field that is a callable\", \"Query expressions may be used for admin_order_field.\", \"test_change_list_sorting_callable_query_expression_reverse (admin_views.tests.AdminViewBasicTest)\", \"Ensure we can sort on a list_display field that is a Model method\", \"Ensure we can sort on a list_display field that is a ModelAdmin method\", \"Ensure we can sort on a list_display field that is a ModelAdmin\", \"test_change_list_sorting_model_meta (admin_views.tests.AdminViewBasicTest)\", \"test_change_list_sorting_multiple (admin_views.tests.AdminViewBasicTest)\", \"test_change_list_sorting_override_model_admin (admin_views.tests.AdminViewBasicTest)\", \"If no ordering is defined in `ModelAdmin.ordering` or in the query\", \"Sort on a list_display field that is a property (column 10 is\", \"Changes to ManyToManyFields are included in the object's history.\", \"test_change_view_subtitle_per_object (admin_views.tests.AdminViewBasicTest)\", \"The 'show_delete' context variable in the admin's change view controls\", \"ModelAdmin.changelist_view shouldn't result in a NoReverseMatch if url\", \"test_date_hierarchy_empty_queryset (admin_views.tests.AdminViewBasicTest)\", \"test_date_hierarchy_local_date_differ_from_utc (admin_views.tests.AdminViewBasicTest)\", \"test_date_hierarchy_timezone_dst (admin_views.tests.AdminViewBasicTest)\", \"test_disallowed_filtering (admin_views.tests.AdminViewBasicTest)\", \"test_disallowed_to_field (admin_views.tests.AdminViewBasicTest)\", \"test_display_decorator_with_boolean_and_empty_value (admin_views.tests.AdminViewBasicTest)\", \"Test \\\"save as\\\".\", \"Should be able to \\\"Save as new\\\" while also deleting an inline.\", \"test_formset_kwargs_can_be_overridden (admin_views.tests.AdminViewBasicTest)\", \"test_get_sortable_by_columns_subset (admin_views.tests.AdminViewBasicTest)\", \"test_get_sortable_by_no_column (admin_views.tests.AdminViewBasicTest)\", \"Joins shouldn't be performed for _id fields in list display.\", \"Joins shouldn't be performed for _id fields in list display.\", \"Tests if the \\\"change password\\\" link in the admin is hidden if the User\", \"Check if the JavaScript i18n view returns an empty language catalog\", \"Makes sure that the fallback language is still working properly\", \"Ensure incorrect lookup parameters are handled gracefully.\", \"#21056 -- URL reversing shouldn't work for nonexistent apps.\", \"Ensure is_null is handled correctly.\", \"test_jsi18n_with_context (admin_views.tests.AdminViewBasicTest)\", \"Ensure admin changelist filters do not contain objects excluded via limit_choices_to.\", \"test_logout_and_password_change_URLs (admin_views.tests.AdminViewBasicTest)\", \"test_multiple_sort_same_field (admin_views.tests.AdminViewBasicTest)\", \"Ensures the admin changelist shows correct values in the relevant column\", \"Ensures the filter UI shows correctly when at least one named group has\", \"Ensure http response from a popup is properly escaped.\", \"Regression test for ticket 20664 - ensure the pk is properly quoted.\", \"test_relation_spanning_filters (admin_views.tests.AdminViewBasicTest)\", \"test_render_views_no_subtitle (admin_views.tests.AdminViewBasicTest)\", \"test_resolve_admin_views (admin_views.tests.AdminViewBasicTest)\", \"The admin shows default sort indicators for all kinds of 'ordering'\", \"test_sortable_by_columns_subset (admin_views.tests.AdminViewBasicTest)\", \"test_sortable_by_no_column (admin_views.tests.AdminViewBasicTest)\", \"If you leave off the trailing slash, app should redirect and add it.\", \"test_view_subtitle_per_object (admin_views.tests.AdminViewBasicTest)\"]", "environment_setup_commit": "475cffd1d64c690cdad16ede4d5e81985738ceb4", "test_directives": ["admin_views.tests", "forms_tests.tests.test_formsets"], "test_cmd": "./tests/runtests.py --verbosity 2 admin_views.tests forms_tests.tests.test_formsets", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py\nindex 8e480b7266..018949c0d0 100644\n--- a/tests/model_formsets_regress/tests.py\n+++ b/tests/model_formsets_regress/tests.py\n@@ -285,6 +285,7 @@ class FormsetTests(TestCase):\n # note: formset.errors returns a list as documented\n self.assertIsInstance(formset.errors, list)\n self.assertIsInstance(formset.non_form_errors(), ErrorList)\n+ self.assertEqual(formset.non_form_errors().error_class, 'nonform')\n for form in formset.forms:\n self.assertIsInstance(form.errors, ErrorDict)\n self.assertIsInstance(form.non_field_errors(), ErrorList)\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["model_formsets_regress.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\nindex a89c35599f..f55a6df33f 100644\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -295,6 +295,7 @@ class BaseFormSet:\n \"\"\"\n if self._non_form_errors is None:\n self.full_clean()\n+ self._non_form_errors.error_class = 'nonform'\n return self._non_form_errors\n \n @property\n\ndiff --git a/django/forms/utils.py b/django/forms/utils.py\nindex 50412f414b..2776fff5cd 100644\n--- a/django/forms/utils.py\n+++ b/django/forms/utils.py\n@@ -88,6 +88,8 @@ class ErrorList(UserList, list):\n self.error_class = 'errorlist'\n else:\n self.error_class = 'errorlist {}'.format(error_class)\n+ if 'nonform' in self.error_class:\n+ self.error_class = 'errorlist nonform'\n \n def as_data(self):\n return ValidationError(self.data).error_list\n", "model_lint_repair_patch": "diff --git a/django/forms/formsets.py b/django/forms/formsets.py\nindex a89c35599f..f55a6df33f 100644\n--- a/django/forms/formsets.py\n+++ b/django/forms/formsets.py\n@@ -295,6 +295,7 @@ class BaseFormSet:\n \"\"\"\n if self._non_form_errors is None:\n self.full_clean()\n+ self._non_form_errors.error_class = 'nonform'\n return self._non_form_errors\n \n @property\n\ndiff --git a/django/forms/utils.py b/django/forms/utils.py\nindex 50412f414b..2776fff5cd 100644\n--- a/django/forms/utils.py\n+++ b/django/forms/utils.py\n@@ -88,6 +88,8 @@ class ErrorList(UserList, list):\n self.error_class = 'errorlist'\n else:\n self.error_class = 'errorlist {}'.format(error_class)\n+ if 'nonform' in self.error_class:\n+ self.error_class = 'errorlist nonform'\n \n def as_data(self):\n return ValidationError(self.data).error_list\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["model_formsets_regress.tests"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-21847", "base_commit": "d9b18c518d64d0ebe8e35a98c2fb519938b9b151", "patch": "diff --git a/sympy/polys/monomials.py b/sympy/polys/monomials.py\n--- a/sympy/polys/monomials.py\n+++ b/sympy/polys/monomials.py\n@@ -127,7 +127,7 @@ 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+ if sum(powers.values()) >= min_degree:\n monomials_list_comm.append(Mul(*item))\n yield from set(monomials_list_comm)\n else:\n@@ -139,7 +139,7 @@ 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+ if sum(powers.values()) >= min_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_monomials.py b/sympy/polys/tests/test_monomials.py\n--- a/sympy/polys/tests/test_monomials.py\n+++ b/sympy/polys/tests/test_monomials.py\n@@ -15,7 +15,6 @@\n from sympy.core import S, symbols\n from sympy.testing.pytest import raises\n \n-\n def test_monomials():\n \n # total_degree tests\n@@ -114,6 +113,9 @@ def test_monomials():\n assert set(itermonomials([x], [3], [1])) == {x, x**3, x**2}\n assert set(itermonomials([x], [3], [2])) == {x**3, x**2}\n \n+ assert set(itermonomials([x, y], 3, 3)) == {x**3, x**2*y, x*y**2, y**3}\n+ assert set(itermonomials([x, y], 3, 2)) == {x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3}\n+\n assert set(itermonomials([x, y], [0, 0])) == {S.One}\n assert set(itermonomials([x, y], [0, 1])) == {S.One, y}\n assert set(itermonomials([x, y], [0, 2])) == {S.One, y, y**2}\n@@ -132,6 +134,15 @@ def test_monomials():\n {S.One, y**2, x*y**2, x, x*y, x**2, x**2*y**2, y, x**2*y}\n \n i, j, k = symbols('i j k', commutative=False)\n+ assert set(itermonomials([i, j, k], 2, 2)) == \\\n+ {k*i, i**2, i*j, j*k, j*i, k**2, j**2, k*j, i*k}\n+ assert set(itermonomials([i, j, k], 3, 2)) == \\\n+ {j*k**2, i*k**2, k*i*j, k*i**2, k**2, j*k*j, k*j**2, i*k*i, i*j,\n+ j**2*k, i**2*j, j*i*k, j**3, i**3, k*j*i, j*k*i, j*i,\n+ k**2*j, j*i**2, k*j, k*j*k, i*j*i, j*i*j, i*j**2, j**2,\n+ k*i*k, i**2, j*k, i*k, i*k*j, k**3, i**2*k, j**2*i, k**2*i,\n+ i*j*k, k*i\n+ }\n assert set(itermonomials([i, j, k], [0, 0, 0])) == {S.One}\n assert set(itermonomials([i, j, k], [0, 0, 1])) == {1, k}\n assert set(itermonomials([i, j, k], [0, 1, 0])) == {1, j}\n", "problem_statement": "itermonomials returns incorrect monomials when using min_degrees argument\n`itermonomials` returns incorrect monomials when using optional `min_degrees` argument\r\n\r\nFor example, the following code introduces three symbolic variables and generates monomials with max and min degree of 3:\r\n\r\n\r\n```\r\nimport sympy as sp\r\nfrom sympy.polys.orderings import monomial_key\r\n\r\nx1, x2, x3 = sp.symbols('x1, x2, x3')\r\nstates = [x1, x2, x3]\r\nmax_degrees = 3\r\nmin_degrees = 3\r\nmonomials = sorted(sp.itermonomials(states, max_degrees, min_degrees=min_degrees), \r\n key=monomial_key('grlex', states))\r\nprint(monomials)\r\n```\r\nThe code returns `[x3**3, x2**3, x1**3]`, when it _should_ also return monomials such as `x1*x2**2, x2*x3**2, etc...` that also have total degree of 3. This behaviour is inconsistent with the documentation that states that \r\n\r\n> A generator of all monomials `monom` is returned, such that either `min_degree <= total_degree(monom) <= max_degree`...\r\n\r\nThe monomials are also missing when `max_degrees` is increased above `min_degrees`.\n", "hints_text": "Doesn't look like the `min_degrees` argument is actually used anywhere in the codebase. Also there don't seem to be any nontrivial tests for passing `min_degrees` as an integer.\r\n\r\nThe issue would be fixed with this diff and some tests in `test_monomials.py`:\r\n```diff\r\ndiff --git a/sympy/polys/monomials.py b/sympy/polys/monomials.py\r\nindex 0e84403307..d2cd3451e5 100644\r\n--- a/sympy/polys/monomials.py\r\n+++ b/sympy/polys/monomials.py\r\n@@ -127,7 +127,7 @@ def itermonomials(variables, max_degrees, min_degrees=None):\r\n for variable in item:\r\n if variable != 1:\r\n powers[variable] += 1\r\n- if max(powers.values()) >= min_degree:\r\n+ if sum(powers.values()) >= min_degree:\r\n monomials_list_comm.append(Mul(*item))\r\n yield from set(monomials_list_comm)\r\n else:\r\n@@ -139,7 +139,7 @@ def itermonomials(variables, max_degrees, min_degrees=None):\r\n for variable in item:\r\n if variable != 1:\r\n powers[variable] += 1\r\n- if max(powers.values()) >= min_degree:\r\n+ if sum(powers.values()) >= min_degree:\r\n monomials_list_non_comm.append(Mul(*item))\r\n yield from set(monomials_list_non_comm)\r\n else:\r\n```\r\n", "created_at": "2021-08-10T17:41:59Z", "version": "1.9", "FAIL_TO_PASS": "[\"test_monomials\"]", "PASS_TO_PASS": "[\"test_monomial_count\", \"test_monomial_mul\", \"test_monomial_div\", \"test_monomial_gcd\", \"test_monomial_lcm\", \"test_monomial_max\", \"test_monomial_pow\", \"test_monomial_min\", \"test_monomial_divides\"]", "environment_setup_commit": "f9a6f50ec0c74d935c50a6e9c9b2cb0469570d91", "test_directives": ["sympy/polys/tests/test_monomials.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/polys/tests/test_monomials.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/sympy/polys/tests/test_monomials.py b/sympy/polys/tests/test_monomials.py\nindex 482cbee30d..1ea96ccffb 100644\n--- a/sympy/polys/tests/test_monomials.py\n+++ b/sympy/polys/tests/test_monomials.py\n@@ -14,9 +14,18 @@\n from sympy.abc import a, b, c, x, y, z\n from sympy.core import S, symbols\n from sympy.testing.pytest import raises\n+from sympy.polys.orderings import monomial_key\n \n \n def test_monomials():\n+ # Test for itermonomials with min_degrees argument\n+ x1, x2, x3 = symbols('x1 x2 x3')\n+ states = [x1, x2, x3]\n+ max_degrees = 3\n+ min_degrees = 3\n+ monomials = sorted(itermonomials(states, max_degrees, min_degrees=min_degrees), key=monomial_key('grlex', states))\n+ expected_monomials = [x1**3, x1**2*x2, x1**2*x3, x1*x2**2, x1*x2*x3, x1*x3**2, x2**3, x2**2*x3, x2*x3**2, x3**3]\n+ assert monomials == expected_monomials, f\"Expected {expected_monomials}, but got {monomials}\"\n \n # total_degree tests\n assert set(itermonomials([], 0)) == {S.One}\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["sympy/polys/tests/test_monomials.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/polys/monomials.py b/sympy/polys/monomials.py\nindex 0e84403307..87088d35ae 100644\n--- a/sympy/polys/monomials.py\n+++ b/sympy/polys/monomials.py\n@@ -127,7 +127,7 @@ 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+ if min_degree <= sum(powers.values()) <= max_degree:\n monomials_list_comm.append(Mul(*item))\n yield from set(monomials_list_comm)\n else:\n@@ -139,7 +139,7 @@ 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+ if min_degree <= sum(powers.values()) <= max_degree:\n monomials_list_non_comm.append(Mul(*item))\n yield from set(monomials_list_non_comm)\n else:\n@@ -149,7 +149,8 @@ def itermonomials(variables, max_degrees, min_degrees=None):\n for var, min_d, max_d in zip(variables, min_degrees, max_degrees):\n power_lists.append([var**i for i in range(min_d, max_d + 1)])\n for powers in product(*power_lists):\n- yield Mul(*powers)\n+ if all(min_d <= sum(powers) <= max_d for min_d, max_d in zip(min_degrees, max_degrees)):\n+ yield Mul(*powers)\n \n def monomial_count(V, N):\n r\"\"\"\n", "model_lint_repair_patch": "diff --git a/sympy/polys/monomials.py b/sympy/polys/monomials.py\nindex 0e84403307..87088d35ae 100644\n--- a/sympy/polys/monomials.py\n+++ b/sympy/polys/monomials.py\n@@ -127,7 +127,7 @@ 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+ if min_degree <= sum(powers.values()) <= max_degree:\n monomials_list_comm.append(Mul(*item))\n yield from set(monomials_list_comm)\n else:\n@@ -139,7 +139,7 @@ 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+ if min_degree <= sum(powers.values()) <= max_degree:\n monomials_list_non_comm.append(Mul(*item))\n yield from set(monomials_list_non_comm)\n else:\n@@ -149,7 +149,8 @@ def itermonomials(variables, max_degrees, min_degrees=None):\n for var, min_d, max_d in zip(variables, min_degrees, max_degrees):\n power_lists.append([var**i for i in range(min_d, max_d + 1)])\n for powers in product(*power_lists):\n- yield Mul(*powers)\n+ if all(min_d <= sum(powers) <= max_d for min_d, max_d in zip(min_degrees, max_degrees)):\n+ yield Mul(*powers)\n \n def monomial_count(V, N):\n r\"\"\"\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-13779", "base_commit": "b34751b7ed02b2cfcc36037fb729d4360480a299", "patch": "diff --git a/sklearn/ensemble/voting.py b/sklearn/ensemble/voting.py\n--- a/sklearn/ensemble/voting.py\n+++ b/sklearn/ensemble/voting.py\n@@ -78,6 +78,8 @@ def fit(self, X, y, sample_weight=None):\n \n if sample_weight is not None:\n for name, step in self.estimators:\n+ if step is None:\n+ continue\n if not has_fit_parameter(step, 'sample_weight'):\n raise ValueError('Underlying estimator \\'%s\\' does not'\n ' support sample weights.' % name)\n", "test_patch": "diff --git a/sklearn/ensemble/tests/test_voting.py b/sklearn/ensemble/tests/test_voting.py\n--- a/sklearn/ensemble/tests/test_voting.py\n+++ b/sklearn/ensemble/tests/test_voting.py\n@@ -8,9 +8,11 @@\n from sklearn.utils.testing import assert_equal\n from sklearn.utils.testing import assert_raise_message\n from sklearn.exceptions import NotFittedError\n+from sklearn.linear_model import LinearRegression\n from sklearn.linear_model import LogisticRegression\n from sklearn.naive_bayes import GaussianNB\n from sklearn.ensemble import RandomForestClassifier\n+from sklearn.ensemble import RandomForestRegressor\n from sklearn.ensemble import VotingClassifier, VotingRegressor\n from sklearn.model_selection import GridSearchCV\n from sklearn import datasets\n@@ -507,3 +509,25 @@ def test_transform():\n eclf3.transform(X).swapaxes(0, 1).reshape((4, 6)),\n eclf2.transform(X)\n )\n+\n+\n+@pytest.mark.filterwarnings('ignore: Default solver will be changed') # 0.22\n+@pytest.mark.filterwarnings('ignore: Default multi_class will') # 0.22\n+@pytest.mark.parametrize(\n+ \"X, y, voter\",\n+ [(X, y, VotingClassifier(\n+ [('lr', LogisticRegression()),\n+ ('rf', RandomForestClassifier(n_estimators=5))])),\n+ (X_r, y_r, VotingRegressor(\n+ [('lr', LinearRegression()),\n+ ('rf', RandomForestRegressor(n_estimators=5))]))]\n+)\n+def test_none_estimator_with_weights(X, y, voter):\n+ # check that an estimator can be set to None and passing some weight\n+ # regression test for\n+ # https://github.com/scikit-learn/scikit-learn/issues/13777\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ voter.set_params(lr=None)\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ y_pred = voter.predict(X)\n+ assert y_pred.shape == y.shape\n", "problem_statement": "Voting estimator will fail at fit if weights are passed and an estimator is None\nBecause we don't check for an estimator to be `None` in `sample_weight` support, `fit` is failing`.\r\n\r\n```python\r\n X, y = load_iris(return_X_y=True)\r\n voter = VotingClassifier(\r\n estimators=[('lr', LogisticRegression()),\r\n ('rf', RandomForestClassifier())]\r\n )\r\n voter.fit(X, y, sample_weight=np.ones(y.shape))\r\n voter.set_params(lr=None)\r\n voter.fit(X, y, sample_weight=np.ones(y.shape))\r\n```\r\n\r\n```\r\nAttributeError: 'NoneType' object has no attribute 'fit'\r\n```\n", "hints_text": "", "created_at": "2019-05-03T13:24:57Z", "version": "0.22", "FAIL_TO_PASS": "[\"sklearn/ensemble/tests/test_voting.py::test_none_estimator_with_weights[X0-y0-voter0]\", \"sklearn/ensemble/tests/test_voting.py::test_none_estimator_with_weights[X1-y1-voter1]\"]", "PASS_TO_PASS": "[\"sklearn/ensemble/tests/test_voting.py::test_estimator_init\", \"sklearn/ensemble/tests/test_voting.py::test_predictproba_hardvoting\", \"sklearn/ensemble/tests/test_voting.py::test_notfitted\", \"sklearn/ensemble/tests/test_voting.py::test_majority_label_iris\", \"sklearn/ensemble/tests/test_voting.py::test_tie_situation\", \"sklearn/ensemble/tests/test_voting.py::test_weights_iris\", \"sklearn/ensemble/tests/test_voting.py::test_weights_regressor\", \"sklearn/ensemble/tests/test_voting.py::test_predict_on_toy_problem\", \"sklearn/ensemble/tests/test_voting.py::test_predict_proba_on_toy_problem\", \"sklearn/ensemble/tests/test_voting.py::test_multilabel\", \"sklearn/ensemble/tests/test_voting.py::test_gridsearch\", \"sklearn/ensemble/tests/test_voting.py::test_parallel_fit\", \"sklearn/ensemble/tests/test_voting.py::test_sample_weight\", \"sklearn/ensemble/tests/test_voting.py::test_sample_weight_kwargs\", \"sklearn/ensemble/tests/test_voting.py::test_set_params\", \"sklearn/ensemble/tests/test_voting.py::test_set_estimator_none\", \"sklearn/ensemble/tests/test_voting.py::test_estimator_weights_format\", \"sklearn/ensemble/tests/test_voting.py::test_transform\"]", "environment_setup_commit": "7e85a6d1f038bbb932b36f18d75df6be937ed00d", "test_directives": ["sklearn/ensemble/tests/test_voting.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v sklearn/ensemble/tests/test_voting.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/sklearn/ensemble/tests/test_voting.py b/sklearn/ensemble/tests/test_voting.py\nindex 2a19bc9a6..0f61a1849 100644\n--- a/sklearn/ensemble/tests/test_voting.py\n+++ b/sklearn/ensemble/tests/test_voting.py\n@@ -507,3 +507,21 @@ def test_transform():\n eclf3.transform(X).swapaxes(0, 1).reshape((4, 6)),\n eclf2.transform(X)\n )\n+\n+def test_voting_classifier_with_none_estimator_and_sample_weight():\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+ 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+ try:\n+ voter.fit(X, y, sample_weight=np.ones(y.shape))\n+ except AttributeError as e:\n+ pytest.fail(f\"VotingClassifier.fit raised AttributeError unexpectedly: {e}\")\n+ pytest.fail(f\"VotingClassifier.fit raised AttributeError unexpectedly: {e}\")\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["sklearn/ensemble/tests/test_voting.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sklearn/ensemble/voting.py b/sklearn/ensemble/voting.py\nindex 7afa7180c..854120272 100644\n--- a/sklearn/ensemble/voting.py\n+++ b/sklearn/ensemble/voting.py\n@@ -29,6 +29,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@@ -78,7 +80,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", "model_lint_repair_patch": "diff --git a/sklearn/ensemble/voting.py b/sklearn/ensemble/voting.py\nindex 7afa7180c..854120272 100644\n--- a/sklearn/ensemble/voting.py\n+++ b/sklearn/ensemble/voting.py\n@@ -29,6 +29,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@@ -78,7 +80,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", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sklearn/ensemble/tests/test_voting.py"]} +{"repo": "django/django", "instance_id": "django__django-12915", "base_commit": "4652f1f0aa459a7b980441d629648707c32e36bf", "patch": "diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py\n--- a/django/contrib/staticfiles/handlers.py\n+++ b/django/contrib/staticfiles/handlers.py\n@@ -1,6 +1,8 @@\n from urllib.parse import urlparse\n from urllib.request import url2pathname\n \n+from asgiref.sync import sync_to_async\n+\n from django.conf import settings\n from django.contrib.staticfiles import utils\n from django.contrib.staticfiles.views import serve\n@@ -52,6 +54,12 @@ def get_response(self, request):\n except Http404 as e:\n return response_for_exception(request, e)\n \n+ async def get_response_async(self, request):\n+ try:\n+ return await sync_to_async(self.serve)(request)\n+ except Http404 as e:\n+ return await sync_to_async(response_for_exception)(request, e)\n+\n \n class StaticFilesHandler(StaticFilesHandlerMixin, WSGIHandler):\n \"\"\"\n", "test_patch": "diff --git a/tests/asgi/project/static/file.txt b/tests/asgi/project/static/file.txt\nnew file mode 100644\n--- /dev/null\n+++ b/tests/asgi/project/static/file.txt\n@@ -0,0 +1 @@\n+test\ndiff --git a/tests/asgi/tests.py b/tests/asgi/tests.py\n--- a/tests/asgi/tests.py\n+++ b/tests/asgi/tests.py\n@@ -1,18 +1,25 @@\n import asyncio\n import sys\n import threading\n+from pathlib import Path\n from unittest import skipIf\n \n from asgiref.sync import SyncToAsync\n from asgiref.testing import ApplicationCommunicator\n \n+from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler\n from django.core.asgi import get_asgi_application\n from django.core.signals import request_finished, request_started\n from django.db import close_old_connections\n-from django.test import AsyncRequestFactory, SimpleTestCase, override_settings\n+from django.test import (\n+ AsyncRequestFactory, SimpleTestCase, modify_settings, override_settings,\n+)\n+from django.utils.http import http_date\n \n from .urls import test_filename\n \n+TEST_STATIC_ROOT = Path(__file__).parent / 'project' / 'static'\n+\n \n @skipIf(sys.platform == 'win32' and (3, 8, 0) < sys.version_info < (3, 8, 1), 'https://bugs.python.org/issue38563')\n @override_settings(ROOT_URLCONF='asgi.urls')\n@@ -79,6 +86,45 @@ async def test_file_response(self):\n # Allow response.close() to finish.\n await communicator.wait()\n \n+ @modify_settings(INSTALLED_APPS={'append': 'django.contrib.staticfiles'})\n+ @override_settings(\n+ STATIC_URL='/static/',\n+ STATIC_ROOT=TEST_STATIC_ROOT,\n+ STATICFILES_DIRS=[TEST_STATIC_ROOT],\n+ STATICFILES_FINDERS=[\n+ 'django.contrib.staticfiles.finders.FileSystemFinder',\n+ ],\n+ )\n+ async def test_static_file_response(self):\n+ application = ASGIStaticFilesHandler(get_asgi_application())\n+ # Construct HTTP request.\n+ scope = self.async_request_factory._base_scope(path='/static/file.txt')\n+ communicator = ApplicationCommunicator(application, scope)\n+ await communicator.send_input({'type': 'http.request'})\n+ # Get the file content.\n+ file_path = TEST_STATIC_ROOT / 'file.txt'\n+ with open(file_path, 'rb') as test_file:\n+ test_file_contents = test_file.read()\n+ # Read the response.\n+ stat = file_path.stat()\n+ response_start = await communicator.receive_output()\n+ self.assertEqual(response_start['type'], 'http.response.start')\n+ self.assertEqual(response_start['status'], 200)\n+ self.assertEqual(\n+ set(response_start['headers']),\n+ {\n+ (b'Content-Length', str(len(test_file_contents)).encode('ascii')),\n+ (b'Content-Type', b'text/plain'),\n+ (b'Content-Disposition', b'inline; filename=\"file.txt\"'),\n+ (b'Last-Modified', http_date(stat.st_mtime).encode('ascii')),\n+ },\n+ )\n+ response_body = await communicator.receive_output()\n+ self.assertEqual(response_body['type'], 'http.response.body')\n+ self.assertEqual(response_body['body'], test_file_contents)\n+ # Allow response.close() to finish.\n+ await communicator.wait()\n+\n async def test_headers(self):\n application = get_asgi_application()\n communicator = ApplicationCommunicator(\ndiff --git a/tests/staticfiles_tests/test_handlers.py b/tests/staticfiles_tests/test_handlers.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/staticfiles_tests/test_handlers.py\n@@ -0,0 +1,22 @@\n+from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler\n+from django.core.handlers.asgi import ASGIHandler\n+from django.test import AsyncRequestFactory\n+\n+from .cases import StaticFilesTestCase\n+\n+\n+class TestASGIStaticFilesHandler(StaticFilesTestCase):\n+ async_request_factory = AsyncRequestFactory()\n+\n+ async def test_get_async_response(self):\n+ request = self.async_request_factory.get('/static/test/file.txt')\n+ handler = ASGIStaticFilesHandler(ASGIHandler())\n+ response = await handler.get_response_async(request)\n+ response.close()\n+ self.assertEqual(response.status_code, 200)\n+\n+ async def test_get_async_response_not_found(self):\n+ request = self.async_request_factory.get('/static/test/not-found.txt')\n+ handler = ASGIStaticFilesHandler(ASGIHandler())\n+ response = await handler.get_response_async(request)\n+ self.assertEqual(response.status_code, 404)\n", "problem_statement": "Add get_response_async for ASGIStaticFilesHandler\nDescription\n\t\nIt looks like the StaticFilesHandlerMixin is missing the the async response function.\nWithout this, when trying to use the ASGIStaticFilesHandler, this is the traceback:\nException inside application: 'NoneType' object is not callable\nTraceback (most recent call last):\n File \".../lib/python3.7/site-packages/daphne/cli.py\", line 30, in asgi\n\tawait self.app(scope, receive, send)\n File \".../src/django/django/contrib/staticfiles/handlers.py\", line 86, in __call__\n\treturn await super().__call__(scope, receive, send)\n File \".../src/django/django/core/handlers/asgi.py\", line 161, in __call__\n\tresponse = await self.get_response_async(request)\n File \".../src/django/django/core/handlers/base.py\", line 148, in get_response_async\n\tresponse = await self._middleware_chain(request)\nTypeError: 'NoneType' object is not callable\n", "hints_text": "", "created_at": "2020-05-14T23:30:01Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_get_async_response (staticfiles_tests.test_handlers.TestASGIStaticFilesHandler)\", \"test_get_async_response_not_found (staticfiles_tests.test_handlers.TestASGIStaticFilesHandler)\", \"test_static_file_response (asgi.tests.ASGITest)\"]", "PASS_TO_PASS": "[\"test_disconnect (asgi.tests.ASGITest)\", \"test_file_response (asgi.tests.ASGITest)\", \"test_get_asgi_application (asgi.tests.ASGITest)\", \"test_get_query_string (asgi.tests.ASGITest)\", \"test_headers (asgi.tests.ASGITest)\", \"test_non_unicode_query_string (asgi.tests.ASGITest)\", \"test_request_lifecycle_signals_dispatched_with_thread_sensitive (asgi.tests.ASGITest)\", \"test_wrong_connection_type (asgi.tests.ASGITest)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["asgi.tests", "staticfiles_tests.test_handlers"], "test_cmd": "./tests/runtests.py --verbosity 2 asgi.tests staticfiles_tests.test_handlers", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/asgi/tests.py b/tests/asgi/tests.py\nindex 41b39ec9ea..5dd23554a9 100644\n--- a/tests/asgi/tests.py\n+++ b/tests/asgi/tests.py\n@@ -188,3 +188,24 @@ class ASGITest(SimpleTestCase):\n self.assertEqual(request_finished_thread, target_thread)\n request_started.disconnect(signal_handler)\n request_finished.disconnect(signal_handler)\n+\n+from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler\n+\n+@override_settings(ROOT_URLCONF='asgi.urls')\n+class ASGIStaticFilesHandlerTest(SimpleTestCase):\n+ async_request_factory = AsyncRequestFactory()\n+\n+ async def test_asgi_static_files_handler(self):\n+ \"\"\"\n+ Test that ASGIStaticFilesHandler can handle async responses.\n+ \"\"\"\n+ application = ASGIStaticFilesHandler(get_asgi_application())\n+ scope = self.async_request_factory._base_scope(path='/static/test.txt')\n+ communicator = ApplicationCommunicator(application, scope)\n+ await communicator.send_input({'type': 'http.request'})\n+ response_start = await communicator.receive_output()\n+ self.assertEqual(response_start['type'], 'http.response.start')\n+ self.assertEqual(response_start['status'], 200)\n+ response_body = await communicator.receive_output()\n+ self.assertEqual(response_body['type'], 'http.response.body')\n+ self.assertIn(b'Test content', response_body['body'])\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["asgi.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py\nindex 711d8864ad..7235fe21f7 100644\n--- a/django/contrib/staticfiles/handlers.py\n+++ b/django/contrib/staticfiles/handlers.py\n@@ -35,6 +35,13 @@ class StaticFilesHandlerMixin:\n \"\"\"\n return path.startswith(self.base_url[2]) and not self.base_url[1]\n \n+ async def get_response_async(self, request):\n+ \"\"\"\n+ Asynchronous version of get_response.\n+ \"\"\"\n+ response = await sync_to_async(self.serve)(request, request.path[1:])\n+ return response\n+\n def file_path(self, url):\n \"\"\"\n Return the relative path to the media file on disk for the given URL.\n@@ -82,7 +89,8 @@ class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler):\n # Only even look at HTTP requests\n if scope['type'] == 'http' and self._should_handle(scope['path']):\n # Serve static content\n- # (the one thing super() doesn't do is __call__, apparently)\n- return await super().__call__(scope, receive, send)\n+ response = await self.get_response_async(scope)\n+ await response(scope, receive, send)\n+ return\n # Hand off to the main app\n return await self.application(scope, receive, send)\n", "model_lint_repair_patch": "diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py\nindex 711d8864ad..7235fe21f7 100644\n--- a/django/contrib/staticfiles/handlers.py\n+++ b/django/contrib/staticfiles/handlers.py\n@@ -35,6 +35,13 @@ class StaticFilesHandlerMixin:\n \"\"\"\n return path.startswith(self.base_url[2]) and not self.base_url[1]\n \n+ async def get_response_async(self, request):\n+ \"\"\"\n+ Asynchronous version of get_response.\n+ \"\"\"\n+ response = await sync_to_async(self.serve)(request, request.path[1:])\n+ return response\n+\n def file_path(self, url):\n \"\"\"\n Return the relative path to the media file on disk for the given URL.\n@@ -82,7 +89,8 @@ class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler):\n # Only even look at HTTP requests\n if scope['type'] == 'http' and self._should_handle(scope['path']):\n # Serve static content\n- # (the one thing super() doesn't do is __call__, apparently)\n- return await super().__call__(scope, receive, send)\n+ response = await self.get_response_async(scope)\n+ await response(scope, receive, send)\n+ return\n # Hand off to the main app\n return await self.application(scope, receive, send)\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-12125", "base_commit": "89d41cba392b759732ba9f1db4ff29ed47da6a56", "patch": "diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py\n--- a/django/db/migrations/serializer.py\n+++ b/django/db/migrations/serializer.py\n@@ -269,7 +269,7 @@ def serialize(self):\n if module == builtins.__name__:\n return self.value.__name__, set()\n else:\n- return \"%s.%s\" % (module, self.value.__name__), {\"import %s\" % module}\n+ return \"%s.%s\" % (module, self.value.__qualname__), {\"import %s\" % module}\n \n \n class UUIDSerializer(BaseSerializer):\n", "test_patch": "diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py\n--- a/tests/migrations/test_writer.py\n+++ b/tests/migrations/test_writer.py\n@@ -26,6 +26,11 @@\n from .models import FoodManager, FoodQuerySet\n \n \n+class DeconstructibleInstances:\n+ def deconstruct(self):\n+ return ('DeconstructibleInstances', [], {})\n+\n+\n class Money(decimal.Decimal):\n def deconstruct(self):\n return (\n@@ -188,6 +193,10 @@ class NestedEnum(enum.IntEnum):\n A = 1\n B = 2\n \n+ class NestedChoices(models.TextChoices):\n+ X = 'X', 'X value'\n+ Y = 'Y', 'Y value'\n+\n def safe_exec(self, string, value=None):\n d = {}\n try:\n@@ -383,6 +392,18 @@ class DateChoices(datetime.date, models.Choices):\n \"default=datetime.date(1969, 11, 19))\"\n )\n \n+ def test_serialize_nested_class(self):\n+ for nested_cls in [self.NestedEnum, self.NestedChoices]:\n+ cls_name = nested_cls.__name__\n+ with self.subTest(cls_name):\n+ self.assertSerializedResultEqual(\n+ nested_cls,\n+ (\n+ \"migrations.test_writer.WriterTests.%s\" % cls_name,\n+ {'import migrations.test_writer'},\n+ ),\n+ )\n+\n def test_serialize_uuid(self):\n self.assertSerializedEqual(uuid.uuid1())\n self.assertSerializedEqual(uuid.uuid4())\n@@ -726,10 +747,6 @@ def test_deconstruct_class_arguments(self):\n # Yes, it doesn't make sense to use a class as a default for a\n # CharField. It does make sense for custom fields though, for example\n # an enumfield that takes the enum class as an argument.\n- class DeconstructibleInstances:\n- def deconstruct(self):\n- return ('DeconstructibleInstances', [], {})\n-\n string = MigrationWriter.serialize(models.CharField(default=DeconstructibleInstances))[0]\n self.assertEqual(string, \"models.CharField(default=migrations.test_writer.DeconstructibleInstances)\")\n \n", "problem_statement": "makemigrations produces incorrect path for inner classes\nDescription\n\t\nWhen you define a subclass from django.db.models.Field as an inner class of some other class, and use this field inside a django.db.models.Model class, then when you run manage.py makemigrations, a migrations file is created which refers to the inner class as if it were a top-level class of the module it is in.\nTo reproduce, create the following as your model:\nclass Outer(object):\n\tclass Inner(models.CharField):\n\t\tpass\nclass A(models.Model):\n\tfield = Outer.Inner(max_length=20)\nAfter running manage.py makemigrations, the generated migrations file contains the following:\nmigrations.CreateModel(\n\tname='A',\n\tfields=[\n\t\t('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n\t\t('field', test1.models.Inner(max_length=20)),\n\t],\n),\nNote the test1.models.Inner, which should have been test1.models.Outer.Inner.\nThe real life case involved an EnumField from django-enumfields, defined as an inner class of a Django Model class, similar to this:\nimport enum\nfrom enumfields import Enum, EnumField\nclass Thing(models.Model):\n\t@enum.unique\n\tclass State(Enum):\n\t\ton = 'on'\n\t\toff = 'off'\n\tstate = EnumField(enum=State)\nThis results in the following migrations code:\nmigrations.CreateModel(\n\tname='Thing',\n\tfields=[\n\t\t('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n\t\t('state', enumfields.fields.EnumField(enum=test1.models.State, max_length=10)),\n\t],\n),\nThis refers to test1.models.State, instead of to test1.models.Thing.State.\n", "hints_text": "This should be possible to do by relying on __qualname__ (instead of __name__) now that master is Python 3 only.\n\u200bPR\nI think we should focus on using __qualname__ during migration serialization as well instead of simply solving the field subclasses case.\nIn fb0f987: Fixed #27914 -- Added support for nested classes in Field.deconstruct()/repr().\nIn 451b585: Refs #27914 -- Used qualname in model operations' deconstruct().\nI am still encountering this issue when running makemigrations on models that include a django-enumfields EnumField. From tracing through the code, I believe the Enum is getting serialized using the django.db.migrations.serializer.TypeSerializer, which still uses the __name__ rather than __qualname__. As a result, the Enum's path gets resolved to app_name.models.enum_name and the generated migration file throws an error \"app_name.models has no 'enum_name' member\". The correct path for the inner class should be app_name.models.model_name.enum_name. \u200bhttps://github.com/django/django/blob/master/django/db/migrations/serializer.py#L266\nReopening it. Will recheck with nested enum field.\n\u200bPR for fixing enum class as an inner class of model.\nIn d3030dea: Refs #27914 -- Moved test enum.Enum subclasses outside of WriterTests.test_serialize_enums().\nIn 6452112: Refs #27914 -- Fixed serialization of nested enum.Enum classes in migrations.\nIn 1a4db2c: [3.0.x] Refs #27914 -- Moved test enum.Enum subclasses outside of WriterTests.test_serialize_enums(). Backport of d3030deaaa50b7814e34ef1e71f2afaf97c6bec6 from master\nIn 30271a47: [3.0.x] Refs #27914 -- Fixed serialization of nested enum.Enum classes in migrations. Backport of 6452112640081ac8838147a8ba192c45879203d8 from master\ncommit 6452112640081ac8838147a8ba192c45879203d8 does not resolve this ticket. The commit patched the EnumSerializer with __qualname__, which works for Enum members. However, the serializer_factory is returning TypeSerializer for the Enum subclass, which is still using __name__ With v3.0.x introducing models.Choices, models.IntegerChoices, using nested enums will become a common pattern; serializing them properly with __qualname__ seems prudent. Here's a patch for the 3.0rc1 build \u200bhttps://github.com/django/django/files/3879265/django_db_migrations_serializer_TypeSerializer.patch.txt\nAgreed, we should fix this.\nI will create a patch a soon as possible.\nSubmitted PR: \u200bhttps://github.com/django/django/pull/12125\nPR: \u200bhttps://github.com/django/django/pull/12125", "created_at": "2019-11-22T12:55:45Z", "version": "3.1", "FAIL_TO_PASS": "[\"test_serialize_nested_class (migrations.test_writer.WriterTests)\", \"test_serialize_numbers (migrations.test_writer.WriterTests)\"]", "PASS_TO_PASS": "[\"test_args_kwargs_signature (migrations.test_writer.OperationWriterTests)\", \"test_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_empty_signature (migrations.test_writer.OperationWriterTests)\", \"test_expand_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_kwargs_signature (migrations.test_writer.OperationWriterTests)\", \"test_multiline_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_nested_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_nested_operation_expand_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_custom_operation (migrations.test_writer.WriterTests)\", \"test_deconstruct_class_arguments (migrations.test_writer.WriterTests)\", \"test_migration_file_header_comments (migrations.test_writer.WriterTests)\", \"test_migration_path (migrations.test_writer.WriterTests)\", \"test_models_import_omitted (migrations.test_writer.WriterTests)\", \"test_register_non_serializer (migrations.test_writer.WriterTests)\", \"test_register_serializer (migrations.test_writer.WriterTests)\", \"test_serialize_builtin_types (migrations.test_writer.WriterTests)\", \"test_serialize_builtins (migrations.test_writer.WriterTests)\", \"test_serialize_choices (migrations.test_writer.WriterTests)\", \"test_serialize_class_based_validators (migrations.test_writer.WriterTests)\", \"test_serialize_collections (migrations.test_writer.WriterTests)\", \"test_serialize_compiled_regex (migrations.test_writer.WriterTests)\", \"test_serialize_constants (migrations.test_writer.WriterTests)\", \"test_serialize_datetime (migrations.test_writer.WriterTests)\", \"test_serialize_empty_nonempty_tuple (migrations.test_writer.WriterTests)\", \"test_serialize_enums (migrations.test_writer.WriterTests)\", \"test_serialize_fields (migrations.test_writer.WriterTests)\", \"test_serialize_frozensets (migrations.test_writer.WriterTests)\", \"test_serialize_functions (migrations.test_writer.WriterTests)\", \"test_serialize_functools_partial (migrations.test_writer.WriterTests)\", \"test_serialize_functools_partialmethod (migrations.test_writer.WriterTests)\", \"test_serialize_iterators (migrations.test_writer.WriterTests)\", \"test_serialize_lazy_objects (migrations.test_writer.WriterTests)\", \"A reference in a local scope can't be serialized.\", \"test_serialize_managers (migrations.test_writer.WriterTests)\", \"test_serialize_multiline_strings (migrations.test_writer.WriterTests)\", \"test_serialize_range (migrations.test_writer.WriterTests)\", \"test_serialize_set (migrations.test_writer.WriterTests)\", \"test_serialize_settings (migrations.test_writer.WriterTests)\", \"test_serialize_strings (migrations.test_writer.WriterTests)\", \"test_serialize_timedelta (migrations.test_writer.WriterTests)\", \"test_serialize_type_none (migrations.test_writer.WriterTests)\", \"An unbound method used within a class body can be serialized.\", \"test_serialize_uuid (migrations.test_writer.WriterTests)\", \"test_simple_migration (migrations.test_writer.WriterTests)\", \"test_sorted_imports (migrations.test_writer.WriterTests)\"]", "environment_setup_commit": "0668164b4ac93a5be79f5b87fae83c657124d9ab", "test_directives": ["migrations.test_writer"], "test_cmd": "./tests/runtests.py --verbosity 2 migrations.test_writer", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/invalid_models_tests/test_custom_fields.py b/tests/invalid_models_tests/test_custom_fields.py\nindex af14bae569..f6b4c5e1cc 100644\n--- a/tests/invalid_models_tests/test_custom_fields.py\n+++ b/tests/invalid_models_tests/test_custom_fields.py\n@@ -18,3 +18,15 @@ class CustomFieldTest(SimpleTestCase):\n \n field = Model._meta.get_field('field')\n self.assertEqual(field.check(), [])\n+\n+ def test_inner_class_field(self):\n+ class Outer:\n+ class Inner(models.CharField):\n+ pass\n+\n+ class Model(models.Model):\n+ field = Outer.Inner(max_length=20)\n+\n+ field = Model._meta.get_field('field')\n+ self.assertEqual(field.__class__.__name__, 'Inner')\n+ self.assertEqual(field.max_length, 20)\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["invalid_models_tests.test_custom_fields"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py\nindex 4918261fb0..8ba1135356 100644\n--- a/django/db/migrations/writer.py\n+++ b/django/db/migrations/writer.py\n@@ -71,6 +71,43 @@ class OperationWriter:\n self.feed('%s=%s,' % (_arg_name, arg_string))\n imports.update(arg_imports)\n \n+ def get_class_path(cls):\n+ module = cls.__module__\n+ if cls.__qualname__:\n+ return f\"{module}.{cls.__qualname__}\"\n+ return module\n+\n+ imports = set()\n+ name, args, kwargs = self.operation.deconstruct()\n+ operation_args = get_func_args(self.operation.__init__)\n+\n+ # See if this operation is in django.db.migrations. If it is,\n+ # We can just use the fact we already have that imported,\n+ # otherwise, we need to add an import for the operation class.\n+ if getattr(migrations, name, None) == self.operation.__class__:\n+ self.feed('migrations.%s(' % name)\n+ else:\n+ imports.add('import %s' % get_class_path(self.operation.__class__))\n+ self.feed('%s.%s(' % (get_class_path(self.operation.__class__), name))\n+\n+ self.indent()\n+\n+ for i, arg in enumerate(args):\n+ arg_value = arg\n+ arg_name = operation_args[i]\n+ _write(arg_name, arg_value)\n+\n+ i = len(args)\n+ # Only iterate over remaining arguments\n+ for arg_name in operation_args[i:]:\n+ if arg_name in kwargs: # Don't sort to maintain signature order\n+ arg_value = kwargs[arg_name]\n+ _write(arg_name, arg_value)\n+\n+ self.unindent()\n+ self.feed('),')\n+ return self.render(), imports\n+\n imports = set()\n name, args, kwargs = self.operation.deconstruct()\n operation_args = get_func_args(self.operation.__init__)\n\ndiff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py\nindex b03d54366a..fc73d43517 100644\n--- a/django/db/models/fields/files.py\n+++ b/django/db/models/fields/files.py\n@@ -26,6 +26,12 @@ class FieldFile(File):\n return self.name == other.name\n return self.name == other\n \n+ def get_class_path(cls):\n+ module = cls.__module__\n+ if cls.__qualname__:\n+ return f\"{module}.{cls.__qualname__}\"\n+ return module\n+\n def __hash__(self):\n return hash(self.name)\n \n", "model_lint_repair_patch": "diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py\nindex 4918261fb0..8ba1135356 100644\n--- a/django/db/migrations/writer.py\n+++ b/django/db/migrations/writer.py\n@@ -71,6 +71,43 @@ class OperationWriter:\n self.feed('%s=%s,' % (_arg_name, arg_string))\n imports.update(arg_imports)\n \n+ def get_class_path(cls):\n+ module = cls.__module__\n+ if cls.__qualname__:\n+ return f\"{module}.{cls.__qualname__}\"\n+ return module\n+\n+ imports = set()\n+ name, args, kwargs = self.operation.deconstruct()\n+ operation_args = get_func_args(self.operation.__init__)\n+\n+ # See if this operation is in django.db.migrations. If it is,\n+ # We can just use the fact we already have that imported,\n+ # otherwise, we need to add an import for the operation class.\n+ if getattr(migrations, name, None) == self.operation.__class__:\n+ self.feed('migrations.%s(' % name)\n+ else:\n+ imports.add('import %s' % get_class_path(self.operation.__class__))\n+ self.feed('%s.%s(' % (get_class_path(self.operation.__class__), name))\n+\n+ self.indent()\n+\n+ for i, arg in enumerate(args):\n+ arg_value = arg\n+ arg_name = operation_args[i]\n+ _write(arg_name, arg_value)\n+\n+ i = len(args)\n+ # Only iterate over remaining arguments\n+ for arg_name in operation_args[i:]:\n+ if arg_name in kwargs: # Don't sort to maintain signature order\n+ arg_value = kwargs[arg_name]\n+ _write(arg_name, arg_value)\n+\n+ self.unindent()\n+ self.feed('),')\n+ return self.render(), imports\n+\n imports = set()\n name, args, kwargs = self.operation.deconstruct()\n operation_args = get_func_args(self.operation.__init__)\n\ndiff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py\nindex b03d54366a..fc73d43517 100644\n--- a/django/db/models/fields/files.py\n+++ b/django/db/models/fields/files.py\n@@ -26,6 +26,12 @@ class FieldFile(File):\n return self.name == other.name\n return self.name == other\n \n+ def get_class_path(cls):\n+ module = cls.__module__\n+ if cls.__qualname__:\n+ return f\"{module}.{cls.__qualname__}\"\n+ return module\n+\n def __hash__(self):\n return hash(self.name)\n \n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["invalid_models_tests.test_custom_fields"]} +{"repo": "django/django", "instance_id": "django__django-14915", "base_commit": "903aaa35e5ceaa33bfc9b19b7f6da65ce5a91dd4", "patch": "diff --git a/django/forms/models.py b/django/forms/models.py\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -1166,6 +1166,9 @@ def __init__(self, value, instance):\n def __str__(self):\n return str(self.value)\n \n+ def __hash__(self):\n+ return hash(self.value)\n+\n def __eq__(self, other):\n if isinstance(other, ModelChoiceIteratorValue):\n other = other.value\n", "test_patch": "diff --git a/tests/model_forms/test_modelchoicefield.py b/tests/model_forms/test_modelchoicefield.py\n--- a/tests/model_forms/test_modelchoicefield.py\n+++ b/tests/model_forms/test_modelchoicefield.py\n@@ -2,7 +2,7 @@\n \n from django import forms\n from django.core.exceptions import ValidationError\n-from django.forms.models import ModelChoiceIterator\n+from django.forms.models import ModelChoiceIterator, ModelChoiceIteratorValue\n from django.forms.widgets import CheckboxSelectMultiple\n from django.template import Context, Template\n from django.test import TestCase\n@@ -341,6 +341,12 @@ class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):\n \"\"\" % (self.c1.pk, self.c2.pk, self.c3.pk),\n )\n \n+ def test_choice_value_hash(self):\n+ value_1 = ModelChoiceIteratorValue(self.c1.pk, self.c1)\n+ value_2 = ModelChoiceIteratorValue(self.c2.pk, self.c2)\n+ self.assertEqual(hash(value_1), hash(ModelChoiceIteratorValue(self.c1.pk, None)))\n+ self.assertNotEqual(hash(value_1), hash(value_2))\n+\n def test_choices_not_fetched_when_not_rendering(self):\n with self.assertNumQueries(1):\n field = forms.ModelChoiceField(Category.objects.order_by('-name'))\n", "problem_statement": "ModelChoiceIteratorValue is not hashable.\nDescription\n\t\nRecently I migrated from Django 3.0 to Django 3.1. In my code, I add custom data-* attributes to the select widget options. After the upgrade some of those options broke. Error is {TypeError}unhashable type: 'ModelChoiceIteratorValue'.\nExample (this one breaks):\n\tdef create_option(self, name, value, label, selected, index, subindex=None, attrs=None):\n\t\tcontext = super().create_option(name, value, label, selected, index, subindex, attrs)\n\t\tif not value:\n\t\t\treturn context\n\t\tif value in self.show_fields: # This is a dict {1: ['first_name', 'last_name']}\n\t\t\tcontext['attrs']['data-fields'] = json.dumps(self.show_fields[value])\nHowever, working with arrays is not an issue:\n\tdef create_option(self, name, value, label, selected, index, subindex=None, attrs=None):\n\t\tcontext = super().create_option(name, value, label, selected, index, subindex, attrs)\n\t\tif not value:\n\t\t\treturn context\n\t\tif value in allowed_values: # This is an array [1, 2]\n\t\t\t...\n", "hints_text": "Thanks for the ticket. Agreed, we could make ModelChoiceIteratorValue hashable by adding: def __hash__(self): return hash(self.value) For now you can use value.value as \u200bdocumented in the \"Backwards incompatible changes in 3.1\" section. Would you like to prepare a patch?\nReplying to Mariusz Felisiak: Thanks for the ticket. Agreed, we could make ModelChoiceIteratorValue hashable by adding: def __hash__(self): return hash(self.value) For now you can use value.value as \u200bdocumented in the \"Backwards incompatible changes in 3.1\" section. Would you like to prepare a patch? Yes, sure.\nPatch: \u200bhttps://github.com/django/django/pull/14915", "created_at": "2021-09-29T22:00:15Z", "version": "4.1", "FAIL_TO_PASS": "[\"test_choice_value_hash (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\"]", "PASS_TO_PASS": "[\"test_basics (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_choice_iterator_passes_model_to_widget (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_choices (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_choices_bool (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_choices_bool_empty_label (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_choices_freshness (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_choices_not_fetched_when_not_rendering (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_choices_radio_blank (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_clean_model_instance (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_clean_to_field_name (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_custom_choice_iterator_passes_model_to_widget (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_deepcopies_widget (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_disabled_modelchoicefield (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_disabled_modelchoicefield_has_changed (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_disabled_modelchoicefield_initial_model_instance (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_disabled_modelmultiplechoicefield_has_changed (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_disabled_multiplemodelchoicefield (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"ModelChoiceField with RadioSelect widget doesn't produce unnecessary\", \"Widgets that render multiple subwidgets shouldn't make more than one\", \"Iterator defaults to ModelChoiceIterator and can be overridden with\", \"test_queryset_manager (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_queryset_none (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\", \"test_result_cache_not_shared (model_forms.test_modelchoicefield.ModelChoiceFieldTests)\"]", "environment_setup_commit": "647480166bfe7532e8c471fef0146e3a17e6c0c9", "test_directives": ["model_forms.test_modelchoicefield"], "test_cmd": "./tests/runtests.py --verbosity 2 model_forms.test_modelchoicefield", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/model_forms/test_modelchoicefield.py b/tests/model_forms/test_modelchoicefield.py\nindex 2a0c05d803..46146d6531 100644\n--- a/tests/model_forms/test_modelchoicefield.py\n+++ b/tests/model_forms/test_modelchoicefield.py\n@@ -1,4 +1,5 @@\n import datetime\n+import json\n \n from django import forms\n from django.core.exceptions import ValidationError\n@@ -14,6 +15,7 @@ class ModelChoiceFieldTests(TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment')\n+ cls.show_fields = {cls.c1.pk: ['name', 'slug']}\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@@ -373,3 +375,45 @@ class ModelChoiceFieldTests(TestCase):\n )\n with self.assertNumQueries(2):\n template.render(Context({'form': CategoriesForm()}))\n+\n+ def test_modelchoiceiteratorvalue_hashable(self):\n+ class CustomModelChoiceField(forms.ModelChoiceField):\n+ def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):\n+ context = super().create_option(name, value, label, selected, index, subindex, attrs)\n+ if not value:\n+ return context\n+ if value in self.show_fields:\n+ context['attrs']['data-fields'] = json.dumps(self.show_fields[value])\n+ return context\n+\n+ field = CustomModelChoiceField(Category.objects.all())\n+ widget = field.widget\n+ widget.show_fields = self.show_fields\n+\n+ # This should not raise a TypeError if ModelChoiceIteratorValue is hashable\n+ try:\n+ widget.create_option('name', self.c1.pk, 'Entertainment', False, 0)\n+ except TypeError as e:\n+ self.fail(f\"ModelChoiceIteratorValue is not hashable: {e}\")\n+\n+ # Additional test to check if ModelChoiceIteratorValue can be used as a dictionary key\n+ try:\n+ test_dict = {widget.create_option('name', self.c1.pk, 'Entertainment', False, 0)['value']: 'test'}\n+ except TypeError as e:\n+ self.fail(f\"ModelChoiceIteratorValue cannot be used as a dictionary key: {e}\")\n+\n+ field = CustomModelChoiceField(Category.objects.all())\n+ widget = field.widget\n+ widget.show_fields = self.show_fields\n+\n+ # This should not raise a TypeError if ModelChoiceIteratorValue is hashable\n+ try:\n+ widget.create_option('name', self.c1.pk, 'Entertainment', False, 0)\n+ except TypeError as e:\n+ self.fail(f\"ModelChoiceIteratorValue is not hashable: {e}\")\n+\n+ # Additional test to check if ModelChoiceIteratorValue can be used as a dictionary key\n+ try:\n+ test_dict = {widget.create_option('name', self.c1.pk, 'Entertainment', False, 0)['value']: 'test'}\n+ except TypeError as e:\n+ self.fail(f\"ModelChoiceIteratorValue cannot be used as a dictionary key: {e}\")\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["model_forms.test_modelchoicefield"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/forms/fields.py b/django/forms/fields.py\nindex 65d6a9ec82..aea0308c01 100644\n--- a/django/forms/fields.py\n+++ b/django/forms/fields.py\n@@ -769,7 +769,11 @@ class CallableChoiceIterator:\n self.choices_func = choices_func\n \n def __iter__(self):\n- yield from self.choices_func()\n+ for choice in self.choices_func():\n+ if isinstance(choice, ModelChoiceIteratorValue):\n+ yield (choice.pk, str(choice))\n+ else:\n+ yield choice\n \n \n class ChoiceField(Field):\n@@ -795,7 +799,7 @@ class ChoiceField(Field):\n # choices can be any iterable, but we call list() on it because\n # it will be consumed more than once.\n if callable(value):\n- value = CallableChoiceIterator(value)\n+ value = list(CallableChoiceIterator(value))\n else:\n value = list(value)\n \n", "model_lint_repair_patch": "diff --git a/django/forms/fields.py b/django/forms/fields.py\nindex 65d6a9ec82..96203df587 100644\n--- a/django/forms/fields.py\n+++ b/django/forms/fields.py\n@@ -764,12 +764,18 @@ class NullBooleanField(BooleanField):\n pass\n \n \n+from django.forms.models import ModelChoiceIteratorValue\n+\n class CallableChoiceIterator:\n def __init__(self, choices_func):\n self.choices_func = choices_func\n \n def __iter__(self):\n- yield from self.choices_func()\n+ for choice in self.choices_func():\n+ if isinstance(choice, ModelChoiceIteratorValue):\n+ yield (choice.pk, str(choice))\n+ else:\n+ yield choice\n \n \n class ChoiceField(Field):\n@@ -795,7 +801,7 @@ class ChoiceField(Field):\n # choices can be any iterable, but we call list() on it because\n # it will be consumed more than once.\n if callable(value):\n- value = CallableChoiceIterator(value)\n+ value = list(CallableChoiceIterator(value))\n else:\n value = list(value)\n \n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-11897", "base_commit": "e2918c1205c47345eb73c9be68b14c0f15fdeb17", "patch": "diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py\n--- a/sympy/printing/latex.py\n+++ b/sympy/printing/latex.py\n@@ -235,10 +235,12 @@ def _needs_mul_brackets(self, expr, first=False, last=False):\n elif expr.is_Mul:\n if not first and _coeff_isneg(expr):\n return True\n+ if expr.is_Piecewise:\n+ return True\n if any([expr.has(x) for x in (Mod,)]):\n return True\n if (not last and\n- any([expr.has(x) for x in (Integral, Piecewise, Product, Sum)])):\n+ any([expr.has(x) for x in (Integral, Product, Sum)])):\n return True\n \n return False\n", "test_patch": "diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py\n--- a/sympy/printing/tests/test_latex.py\n+++ b/sympy/printing/tests/test_latex.py\n@@ -867,7 +867,7 @@ def test_latex_Piecewise():\n p = Piecewise((A**2, Eq(A, B)), (A*B, True))\n s = r\"\\begin{cases} A^{2} & \\text{for}\\: A = B \\\\A B & \\text{otherwise} \\end{cases}\"\n assert latex(p) == s\n- assert latex(A*p) == r\"A %s\" % s\n+ assert latex(A*p) == r\"A \\left(%s\\right)\" % s\n assert latex(p*A) == r\"\\left(%s\\right) A\" % s\n \n \n", "problem_statement": "LaTeX printer inconsistent with pretty printer\nThe LaTeX printer should always give the same output as the pretty printer, unless better output is possible from LaTeX. In some cases it is inconsistent. For instance:\n\n``` py\nIn [9]: var('x', positive=True)\nOut[9]: x\n\nIn [10]: latex(exp(-x)*log(x))\nOut[10]: '\\\\frac{1}{e^{x}} \\\\log{\\\\left (x \\\\right )}'\n\nIn [11]: pprint(exp(-x)*log(x))\n -x\n\u212f \u22c5log(x)\n```\n\n(I also don't think the assumptions should affect printing). \n\n``` py\nIn [14]: var('x y')\nOut[14]: (x, y)\n\nIn [15]: latex(1/(x + y)/2)\nOut[15]: '\\\\frac{1}{2 x + 2 y}'\n\nIn [16]: pprint(1/(x + y)/2)\n 1\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n2\u22c5(x + y)\n```\n\n", "hints_text": "In each of these cases, the pprint output is better. I think in general the pretty printer is better tuned than the LaTeX printer, so if they disagree, the pprint output is likely the better one. \n\nI want to fix this issue. How should I start?\n\nEach of the expressions is a Mul, so look at LatexPrinter._print_Mul and compare it to PrettyPrinter._print_Mul. \n\n@asmeurer In general what you want is that the output of both should be compared and if the LaTeX printer produces an output different from PrettyPrinter then Pretty Printer's output should be shown in the console. Right ? (A bit confused and posting a comment to clear my doubt)\n\nIt shouldn't change the printer type. They should just both produce the same form of the expression. \n\n@asmeurer Thanks for the clarification. \n\nAnother example:\n\n```\nIn [7]: var(\"sigma mu\")\nOut[7]: (\u03c3, \u03bc)\n\nIn [8]: (exp(-(x - mu)**2/sigma**2))\nOut[8]:\n 2\n -(-\u03bc + x)\n \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n 2\n \u03c3\n\u212f\n\nIn [9]: latex(exp(-(x - mu)**2/sigma**2))\nOut[9]: 'e^{- \\\\frac{1}{\\\\sigma^{2}} \\\\left(- \\\\mu + x\\\\right)^{2}}'\n```\n\nAnother one (no parentheses around the piecewise):\n\n```\nIn [38]: FiniteSet(6**(S(1)/3)*x**(S(1)/3)*Piecewise(((-1)**(S(2)/3), 3*x/4 < 0), (1, True)))\nOut[38]:\n\u23a7 \u239b\u23a7 2/3 3\u22c5x \u239e\u23ab\n\u23aa3 ___ 3 ___ \u239c\u23aa(-1) for \u2500\u2500\u2500 < 0\u239f\u23aa\n\u23a8\u2572\u2571 6 \u22c5\u2572\u2571 x \u22c5\u239c\u23a8 4 \u239f\u23ac\n\u23aa \u239c\u23aa \u239f\u23aa\n\u23a9 \u239d\u23a9 1 otherwise \u23a0\u23ad\n\nIn [39]: latex(FiniteSet(6**(S(1)/3)*x**(S(1)/3)*Piecewise(((-1)**(S(2)/3), 3*x/4 < 0), (1, True))))\nOut[39]: '\\\\left\\\\{\\\\sqrt[3]{6} \\\\sqrt[3]{x} \\\\begin{cases} \\\\left(-1\\\\right)^{\\\\frac{2}{3}} & \\\\text{for}\\\\: \\\\frac{3 x}{4} < 0 \\\\\\\\1 & \\\\text{otherwise} \\\\end{cases}\\\\right\\\\}'\n```\n\nSome of these were fixed in https://github.com/sympy/sympy/pull/11298\n\n```\nIn [39]: latex(FiniteSet(6**(S(1)/3)*x**(S(1)/3)*Piecewise(((-1)**(S(2)/3), 3*x/4 < 0), (1, True))))\nOut[39]: '\\\\left\\\\{\\\\sqrt[3]{6} \\\\sqrt[3]{x} \\\\begin{cases} \\\\left(-1\\\\right)^{\\\\frac{2}{3}} & \\\\text{for}\\\\: \\\\frac{3 x}{4} < 0 \\\\\\\\1 & \\\\text{otherwise} \\\\end{cases}\\\\right\\\\}'\n```\n\nThis error is caused since there is no closing parentheses included in the printing piecewise functions. Will it be fine to add closing parentheses in Piecewise functions?\n\nThe piecewise should print like it does for the Unicode pretty printer. \n", "created_at": "2016-12-03T14:40:51Z", "version": "1.0", "FAIL_TO_PASS": "[\"test_latex_Piecewise\"]", "PASS_TO_PASS": "[\"test_printmethod\", \"test_latex_basic\", \"test_latex_builtins\", \"test_latex_SingularityFunction\", \"test_latex_cycle\", \"test_latex_permutation\", \"test_latex_Float\", \"test_latex_symbols\", \"test_hyper_printing\", \"test_latex_bessel\", \"test_latex_fresnel\", \"test_latex_brackets\", \"test_latex_subs\", \"test_latex_integrals\", \"test_latex_sets\", \"test_latex_Range\", \"test_latex_sequences\", \"test_latex_intervals\", \"test_latex_AccumuBounds\", \"test_latex_emptyset\", \"test_latex_commutator\", \"test_latex_union\", \"test_latex_symmetric_difference\", \"test_latex_Complement\", \"test_latex_Complexes\", \"test_latex_productset\", \"test_latex_Naturals\", \"test_latex_Naturals0\", \"test_latex_Integers\", \"test_latex_ImageSet\", \"test_latex_ConditionSet\", \"test_latex_ComplexRegion\", \"test_latex_Contains\", \"test_latex_sum\", \"test_latex_product\", \"test_latex_limits\", \"test_issue_3568\", \"test_latex\", \"test_latex_dict\", \"test_latex_list\", \"test_latex_rational\", \"test_latex_inverse\", \"test_latex_DiracDelta\", \"test_latex_Heaviside\", \"test_latex_KroneckerDelta\", \"test_latex_LeviCivita\", \"test_mode\", \"test_latex_Matrix\", \"test_latex_mul_symbol\", \"test_latex_issue_4381\", \"test_latex_issue_4576\", \"test_latex_pow_fraction\", \"test_noncommutative\", \"test_latex_order\", \"test_latex_Lambda\", \"test_latex_PolyElement\", \"test_latex_FracElement\", \"test_latex_Poly\", \"test_latex_ComplexRootOf\", \"test_latex_RootSum\", \"test_settings\", \"test_latex_numbers\", \"test_lamda\", \"test_custom_symbol_names\", \"test_matAdd\", \"test_matMul\", \"test_latex_MatrixSlice\", \"test_latex_RandomDomain\", \"test_PrettyPoly\", \"test_integral_transforms\", \"test_PolynomialRingBase\", \"test_categories\", \"test_Modules\", \"test_QuotientRing\", \"test_Tr\", \"test_Adjoint\", \"test_Hadamard\", \"test_ZeroMatrix\", \"test_boolean_args_order\", \"test_imaginary\", \"test_builtins_without_args\", \"test_latex_greek_functions\", \"test_translate\", \"test_other_symbols\", \"test_modifiers\", \"test_greek_symbols\", \"test_builtin_no_args\", \"test_issue_6853\", \"test_Mul\", \"test_Pow\", \"test_issue_7180\", \"test_issue_8409\", \"test_issue_7117\", \"test_issue_2934\", \"test_issue_10489\"]", "environment_setup_commit": "50b81f9f6be151014501ffac44e5dc6b2416938f", "test_directives": ["sympy/printing/tests/test_latex.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/printing/tests/test_latex.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/physics/vector/tests/test_printing.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/sympy/printing/pretty/pretty_symbology.py b/sympy/printing/pretty/pretty_symbology.py\nindex ebf810d277..7d5d3ddf15 100644\n--- a/sympy/printing/pretty/pretty_symbology.py\n+++ b/sympy/printing/pretty/pretty_symbology.py\n@@ -453,7 +453,7 @@ def hobj(symb, width):\n \n def xsym(sym):\n \"\"\"get symbology for a 'character'\"\"\"\n- op = _xsym[sym]\n+ op = _xsym.get(sym, (sym, sym)) # Default to the symbol itself if not found\n \n if _use_unicode:\n return op[1]\n", "model_lint_repair_patch": "diff --git a/sympy/printing/pretty/pretty_symbology.py b/sympy/printing/pretty/pretty_symbology.py\nindex ebf810d277..7d5d3ddf15 100644\n--- a/sympy/printing/pretty/pretty_symbology.py\n+++ b/sympy/printing/pretty/pretty_symbology.py\n@@ -453,7 +453,7 @@ def hobj(symb, width):\n \n def xsym(sym):\n \"\"\"get symbology for a 'character'\"\"\"\n- op = _xsym[sym]\n+ op = _xsym.get(sym, (sym, sym)) # Default to the symbol itself if not found\n \n if _use_unicode:\n return op[1]\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/physics/vector/tests/test_printing.py"]} +{"repo": "django/django", "instance_id": "django__django-14016", "base_commit": "1710cdbe79c90665046034fe1700933d038d90ad", "patch": "diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py\n--- a/django/db/models/query_utils.py\n+++ b/django/db/models/query_utils.py\n@@ -5,7 +5,6 @@\n large and/or so that they can be used by other modules without getting into\n circular import difficulties.\n \"\"\"\n-import copy\n import functools\n import inspect\n from collections import namedtuple\n@@ -46,10 +45,12 @@ def _combine(self, other, conn):\n \n # If the other Q() is empty, ignore it and just use `self`.\n if not other:\n- return copy.deepcopy(self)\n+ _, args, kwargs = self.deconstruct()\n+ return type(self)(*args, **kwargs)\n # Or if this Q is empty, ignore it and just use `other`.\n elif not self:\n- return copy.deepcopy(other)\n+ _, args, kwargs = other.deconstruct()\n+ return type(other)(*args, **kwargs)\n \n obj = type(self)()\n obj.connector = conn\n", "test_patch": "diff --git a/tests/queries/test_q.py b/tests/queries/test_q.py\n--- a/tests/queries/test_q.py\n+++ b/tests/queries/test_q.py\n@@ -8,6 +8,10 @@ def test_combine_and_empty(self):\n self.assertEqual(q & Q(), q)\n self.assertEqual(Q() & q, q)\n \n+ q = Q(x__in={}.keys())\n+ self.assertEqual(q & Q(), q)\n+ self.assertEqual(Q() & q, q)\n+\n def test_combine_and_both_empty(self):\n self.assertEqual(Q() & Q(), Q())\n \n@@ -16,6 +20,10 @@ def test_combine_or_empty(self):\n self.assertEqual(q | Q(), q)\n self.assertEqual(Q() | q, q)\n \n+ q = Q(x__in={}.keys())\n+ self.assertEqual(q | Q(), q)\n+ self.assertEqual(Q() | q, q)\n+\n def test_combine_or_both_empty(self):\n self.assertEqual(Q() | Q(), Q())\n \n", "problem_statement": "\"TypeError: cannot pickle\" when applying | operator to a Q object\nDescription\n\t \n\t\t(last modified by Daniel Izquierdo)\n\t \nUsing a reference to a non-pickleable type of object such as dict_keys in a Q object makes the | operator fail:\n>>> from django.db.models import Q\n>>> Q(x__in={}.keys())\n\n>>> Q() | Q(x__in={}.keys())\nTraceback (most recent call last):\n...\nTypeError: cannot pickle 'dict_keys' object\nEven though this particular example could be solved by doing Q() | Q(x__in={}) it still feels like using .keys() should work.\nI can work on a patch if there's agreement that this should not crash.\n", "hints_text": "Thanks for this report. Regression in bb0b6e526340e638522e093765e534df4e4393d2.", "created_at": "2021-02-17T16:06:20Z", "version": "4.0", "FAIL_TO_PASS": "[\"test_combine_and_empty (queries.test_q.QTests)\", \"test_combine_or_empty (queries.test_q.QTests)\"]", "PASS_TO_PASS": "[\"test_combine_and_both_empty (queries.test_q.QTests)\", \"test_combine_not_q_object (queries.test_q.QTests)\", \"test_combine_or_both_empty (queries.test_q.QTests)\", \"test_deconstruct (queries.test_q.QTests)\", \"test_deconstruct_and (queries.test_q.QTests)\", \"test_deconstruct_multiple_kwargs (queries.test_q.QTests)\", \"test_deconstruct_negated (queries.test_q.QTests)\", \"test_deconstruct_nested (queries.test_q.QTests)\", \"test_deconstruct_or (queries.test_q.QTests)\", \"test_reconstruct (queries.test_q.QTests)\", \"test_reconstruct_and (queries.test_q.QTests)\", \"test_reconstruct_negated (queries.test_q.QTests)\", \"test_reconstruct_or (queries.test_q.QTests)\"]", "environment_setup_commit": "475cffd1d64c690cdad16ede4d5e81985738ceb4", "test_directives": ["queries.test_q"], "test_cmd": "./tests/runtests.py --verbosity 2 queries.test_q", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py\nindex e5bccc6362..0eb1fa496f 100644\n--- a/tests/utils_tests/test_lazyobject.py\n+++ b/tests/utils_tests/test_lazyobject.py\n@@ -194,6 +194,19 @@ class LazyObjectTestCase(TestCase):\n def test_pickle(self):\n # See ticket #16563\n obj = self.lazy_wrap(Foo())\n+\n+ def test_q_object_or_operator_with_dict_keys(self):\n+ from django.db.models import Q\n+ # Create Q objects\n+ q1 = Q(x__in={}.keys())\n+ q2 = Q()\n+ # Apply the | operator\n+ try:\n+ q3 = q1 | q2\n+ self.assertIsInstance(q3, Q)\n+ except TypeError as e:\n+ self.fail(f\"TypeError raised: {e}\")\n+ obj = self.lazy_wrap(Foo())\n obj.bar = 'baz'\n pickled = pickle.dumps(obj)\n unpickled = pickle.loads(pickled)\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["utils_tests.test_lazyobject"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py\nindex 871b016715..aa139d7ed1 100644\n--- a/django/utils/datastructures.py\n+++ b/django/utils/datastructures.py\n@@ -202,8 +202,14 @@ class MultiValueDict(dict):\n if isinstance(arg, Mapping):\n arg = arg.items()\n for key, value in arg:\n+ # Ensure key is pickleable\n+ if isinstance(key, dict_keys):\n+ key = list(key)\n self.setlistdefault(key).append(value)\n for key, value in kwargs.items():\n+ # Ensure key is pickleable\n+ if isinstance(key, dict_keys):\n+ key = list(key)\n self.setlistdefault(key).append(value)\n \n def dict(self):\n", "model_lint_repair_patch": "diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py\nindex 871b016715..f87ee3b488 100644\n--- a/django/utils/datastructures.py\n+++ b/django/utils/datastructures.py\n@@ -1,5 +1,5 @@\n import copy\n-from collections.abc import Mapping\n+from collections.abc import Mapping, KeysView\n \n \n class OrderedSet:\n@@ -202,8 +202,14 @@ class MultiValueDict(dict):\n if isinstance(arg, Mapping):\n arg = arg.items()\n for key, value in arg:\n+ # Ensure key is pickleable\n+ if isinstance(key, KeysView):\n+ key = list(key)\n self.setlistdefault(key).append(value)\n for key, value in kwargs.items():\n+ # Ensure key is pickleable\n+ if isinstance(key, KeysView):\n+ key = list(key)\n self.setlistdefault(key).append(value)\n \n def dict(self):\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-12708", "base_commit": "447980e72ac01da1594dd3373a03ba40b7ee6f80", "patch": "diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py\n--- a/django/db/backends/base/schema.py\n+++ b/django/db/backends/base/schema.py\n@@ -393,7 +393,12 @@ def alter_index_together(self, model, old_index_together, new_index_together):\n news = {tuple(fields) for fields in new_index_together}\n # Deleted indexes\n for fields in olds.difference(news):\n- self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index)\n+ self._delete_composed_index(\n+ model,\n+ fields,\n+ {'index': True, 'unique': False},\n+ self.sql_delete_index,\n+ )\n # Created indexes\n for field_names in news.difference(olds):\n fields = [model._meta.get_field(field) for field in field_names]\n", "test_patch": "diff --git a/tests/migrations/test_base.py b/tests/migrations/test_base.py\n--- a/tests/migrations/test_base.py\n+++ b/tests/migrations/test_base.py\n@@ -62,7 +62,11 @@ def assertIndexExists(self, table, columns, value=True, using='default', index_t\n any(\n c[\"index\"]\n for c in connections[using].introspection.get_constraints(cursor, table).values()\n- if c['columns'] == list(columns) and (index_type is None or c['type'] == index_type)\n+ if (\n+ c['columns'] == list(columns) and\n+ (index_type is None or c['type'] == index_type) and\n+ not c['unique']\n+ )\n ),\n )\n \n@@ -80,6 +84,14 @@ def assertConstraintExists(self, table, name, value=True, using='default'):\n def assertConstraintNotExists(self, table, name):\n return self.assertConstraintExists(table, name, False)\n \n+ def assertUniqueConstraintExists(self, table, columns, value=True, using='default'):\n+ with connections[using].cursor() as cursor:\n+ constraints = connections[using].introspection.get_constraints(cursor, table).values()\n+ self.assertEqual(\n+ value,\n+ any(c['unique'] for c in constraints if c['columns'] == list(columns)),\n+ )\n+\n def assertFKExists(self, table, columns, to, value=True, using='default'):\n with connections[using].cursor() as cursor:\n self.assertEqual(\ndiff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py\n--- a/tests/migrations/test_operations.py\n+++ b/tests/migrations/test_operations.py\n@@ -1759,6 +1759,29 @@ def test_alter_index_together_remove(self):\n operation = migrations.AlterIndexTogether(\"Pony\", None)\n self.assertEqual(operation.describe(), \"Alter index_together for Pony (0 constraint(s))\")\n \n+ @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields')\n+ def test_alter_index_together_remove_with_unique_together(self):\n+ app_label = 'test_alintoremove_wunto'\n+ table_name = '%s_pony' % app_label\n+ project_state = self.set_up_test_model(app_label, unique_together=True)\n+ self.assertUniqueConstraintExists(table_name, ['pink', 'weight'])\n+ # Add index together.\n+ new_state = project_state.clone()\n+ operation = migrations.AlterIndexTogether('Pony', [('pink', 'weight')])\n+ operation.state_forwards(app_label, new_state)\n+ with connection.schema_editor() as editor:\n+ operation.database_forwards(app_label, editor, project_state, new_state)\n+ self.assertIndexExists(table_name, ['pink', 'weight'])\n+ # Remove index together.\n+ project_state = new_state\n+ new_state = project_state.clone()\n+ operation = migrations.AlterIndexTogether('Pony', set())\n+ operation.state_forwards(app_label, new_state)\n+ with connection.schema_editor() as editor:\n+ operation.database_forwards(app_label, editor, project_state, new_state)\n+ self.assertIndexNotExists(table_name, ['pink', 'weight'])\n+ self.assertUniqueConstraintExists(table_name, ['pink', 'weight'])\n+\n @skipUnlessDBFeature('supports_table_check_constraints')\n def test_add_constraint(self):\n project_state = self.set_up_test_model(\"test_addconstraint\")\n", "problem_statement": "Migration crashes deleting an index_together if there is a unique_together on the same fields\nDescription\n\t\nHappens with Django 1.11.10\nSteps to reproduce:\n1) Create models with 2 fields, add 2 same fields to unique_together and to index_together\n2) Delete index_together -> Fail\nIt will fail at django/db/backends/base/schema.py, line 378, in _delete_composed_index(), ValueError: Found wrong number (2) of constraints for as this one will find two constraints, the _uniq and the _idx one. No way to get out of this...\nThe worst in my case is that happened as I wanted to refactor my code to use the \"new\" (Dj 1.11) Options.indexes feature. I am actually not deleting the index, just the way it is declared in my code.\nI think there are 2 different points here:\n1) The deletion of index_together should be possible alone or made coherent (migrations side?) with unique_together\n2) Moving the declaration of an index should not result in an index re-creation\n", "hints_text": "Reproduced on master at 623139b5d1bd006eac78b375bcaf5948e695c3c6.\nI haven't looked under the hood on this yet, but could it be related to the ordering of the operations generated for the mgiration? on first inspection it feels like this and #28862 could be caused by the same/similar underlying problem in how FieldRelatedOptionOperation subclasses ordering is handled in the migration autodetector's migration optimizer.", "created_at": "2020-04-12T22:20:59Z", "version": "3.1", "FAIL_TO_PASS": "[\"test_alter_index_together_remove_with_unique_together (migrations.test_operations.OperationTests)\"]", "PASS_TO_PASS": "[\"test_references_model_mixin (migrations.test_operations.TestCreateModel)\", \"test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_name (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_remote_field_model (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_through (migrations.test_operations.FieldOperationTests)\", \"test_references_field_by_to_fields (migrations.test_operations.FieldOperationTests)\", \"test_references_model (migrations.test_operations.FieldOperationTests)\", \"test_add_field_ignore_swapped (migrations.test_operations.SwappableOperationTests)\", \"test_create_ignore_swapped (migrations.test_operations.SwappableOperationTests)\", \"test_delete_ignore_swapped (migrations.test_operations.SwappableOperationTests)\", \"test_indexes_ignore_swapped (migrations.test_operations.SwappableOperationTests)\", \"test_add_binaryfield (migrations.test_operations.OperationTests)\", \"test_add_charfield (migrations.test_operations.OperationTests)\", \"test_add_constraint (migrations.test_operations.OperationTests)\", \"test_add_constraint_combinable (migrations.test_operations.OperationTests)\", \"test_add_constraint_percent_escaping (migrations.test_operations.OperationTests)\", \"test_add_field (migrations.test_operations.OperationTests)\", \"test_add_field_m2m (migrations.test_operations.OperationTests)\", \"test_add_field_preserve_default (migrations.test_operations.OperationTests)\", \"test_add_index (migrations.test_operations.OperationTests)\", \"test_add_index_state_forwards (migrations.test_operations.OperationTests)\", \"test_add_or_constraint (migrations.test_operations.OperationTests)\", \"test_add_partial_unique_constraint (migrations.test_operations.OperationTests)\", \"test_add_textfield (migrations.test_operations.OperationTests)\", \"test_alter_field (migrations.test_operations.OperationTests)\", \"test_alter_field_m2m (migrations.test_operations.OperationTests)\", \"test_alter_field_pk (migrations.test_operations.OperationTests)\", \"test_alter_field_pk_fk (migrations.test_operations.OperationTests)\", \"test_alter_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)\", \"test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change (migrations.test_operations.OperationTests)\", \"test_alter_field_reloads_state_on_fk_with_to_field_target_changes (migrations.test_operations.OperationTests)\", \"test_alter_field_reloads_state_on_fk_with_to_field_target_type_change (migrations.test_operations.OperationTests)\", \"test_alter_field_with_index (migrations.test_operations.OperationTests)\", \"test_alter_fk (migrations.test_operations.OperationTests)\", \"test_alter_fk_non_fk (migrations.test_operations.OperationTests)\", \"test_alter_index_together (migrations.test_operations.OperationTests)\", \"test_alter_index_together_remove (migrations.test_operations.OperationTests)\", \"test_alter_model_managers (migrations.test_operations.OperationTests)\", \"test_alter_model_managers_emptying (migrations.test_operations.OperationTests)\", \"test_alter_model_options (migrations.test_operations.OperationTests)\", \"test_alter_model_options_emptying (migrations.test_operations.OperationTests)\", \"test_alter_model_table (migrations.test_operations.OperationTests)\", \"test_alter_model_table_m2m (migrations.test_operations.OperationTests)\", \"test_alter_model_table_none (migrations.test_operations.OperationTests)\", \"test_alter_model_table_noop (migrations.test_operations.OperationTests)\", \"test_alter_order_with_respect_to (migrations.test_operations.OperationTests)\", \"test_alter_unique_together (migrations.test_operations.OperationTests)\", \"test_alter_unique_together_remove (migrations.test_operations.OperationTests)\", \"A field may be migrated from AutoField to BigAutoField.\", \"test_column_name_quoting (migrations.test_operations.OperationTests)\", \"test_create_model (migrations.test_operations.OperationTests)\", \"test_create_model_inheritance (migrations.test_operations.OperationTests)\", \"test_create_model_m2m (migrations.test_operations.OperationTests)\", \"test_create_model_managers (migrations.test_operations.OperationTests)\", \"test_create_model_with_constraint (migrations.test_operations.OperationTests)\", \"test_create_model_with_duplicate_base (migrations.test_operations.OperationTests)\", \"test_create_model_with_duplicate_field_name (migrations.test_operations.OperationTests)\", \"test_create_model_with_duplicate_manager_name (migrations.test_operations.OperationTests)\", \"test_create_model_with_partial_unique_constraint (migrations.test_operations.OperationTests)\", \"test_create_model_with_unique_after (migrations.test_operations.OperationTests)\", \"test_create_proxy_model (migrations.test_operations.OperationTests)\", \"test_create_unmanaged_model (migrations.test_operations.OperationTests)\", \"test_delete_model (migrations.test_operations.OperationTests)\", \"test_delete_mti_model (migrations.test_operations.OperationTests)\", \"test_delete_proxy_model (migrations.test_operations.OperationTests)\", \"test_model_with_bigautofield (migrations.test_operations.OperationTests)\", \"test_remove_constraint (migrations.test_operations.OperationTests)\", \"test_remove_field (migrations.test_operations.OperationTests)\", \"test_remove_field_m2m (migrations.test_operations.OperationTests)\", \"test_remove_field_m2m_with_through (migrations.test_operations.OperationTests)\", \"test_remove_fk (migrations.test_operations.OperationTests)\", \"test_remove_index (migrations.test_operations.OperationTests)\", \"test_remove_index_state_forwards (migrations.test_operations.OperationTests)\", \"test_remove_partial_unique_constraint (migrations.test_operations.OperationTests)\", \"test_rename_field (migrations.test_operations.OperationTests)\", \"test_rename_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)\", \"RenameModel renames a many-to-many column after a RenameField.\", \"test_rename_m2m_target_model (migrations.test_operations.OperationTests)\", \"test_rename_m2m_through_model (migrations.test_operations.OperationTests)\", \"test_rename_missing_field (migrations.test_operations.OperationTests)\", \"test_rename_model (migrations.test_operations.OperationTests)\", \"test_rename_model_state_forwards (migrations.test_operations.OperationTests)\", \"test_rename_model_with_m2m (migrations.test_operations.OperationTests)\", \"test_rename_model_with_self_referential_fk (migrations.test_operations.OperationTests)\", \"test_rename_model_with_self_referential_m2m (migrations.test_operations.OperationTests)\", \"test_rename_model_with_superclass_fk (migrations.test_operations.OperationTests)\", \"test_rename_referenced_field_state_forward (migrations.test_operations.OperationTests)\", \"test_repoint_field_m2m (migrations.test_operations.OperationTests)\", \"test_run_python (migrations.test_operations.OperationTests)\", \"test_run_python_atomic (migrations.test_operations.OperationTests)\", \"test_run_python_noop (migrations.test_operations.OperationTests)\", \"test_run_python_related_assignment (migrations.test_operations.OperationTests)\", \"test_run_sql (migrations.test_operations.OperationTests)\", \"test_run_sql_noop (migrations.test_operations.OperationTests)\", \"test_run_sql_params (migrations.test_operations.OperationTests)\", \"test_run_sql_params_invalid (migrations.test_operations.OperationTests)\", \"test_separate_database_and_state (migrations.test_operations.OperationTests)\", \"test_separate_database_and_state2 (migrations.test_operations.OperationTests)\", \"A field may be migrated from SmallAutoField to AutoField.\", \"A field may be migrated from SmallAutoField to BigAutoField.\"]", "environment_setup_commit": "0668164b4ac93a5be79f5b87fae83c657124d9ab", "test_directives": ["migrations.test_base", "migrations.test_operations"], "test_cmd": "./tests/runtests.py --verbosity 2 migrations.test_base migrations.test_operations", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["indexes.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py\nindex 8c06c4d157..ff44ee352f 100644\n--- a/django/db/migrations/operations/models.py\n+++ b/django/db/migrations/operations/models.py\n@@ -537,6 +537,13 @@ class AlterUniqueTogether(AlterTogetherOptionOperation):\n def __init__(self, name, unique_together):\n super().__init__(name, unique_together)\n \n+ def database_forwards(self, app_label, schema_editor, from_state, to_state):\n+ new_model = to_state.apps.get_model(app_label, self.name)\n+ if self.allow_migrate_model(schema_editor.connection.alias, new_model):\n+ old_model = from_state.apps.get_model(app_label, self.name)\n+ schema_editor._delete_composed_index(old_model, self.unique_together, 'unique')\n+ schema_editor._create_composed_index(new_model, self.unique_together, 'unique')\n+\n \n class AlterIndexTogether(AlterTogetherOptionOperation):\n \"\"\"\n@@ -548,6 +555,13 @@ class AlterIndexTogether(AlterTogetherOptionOperation):\n def __init__(self, name, index_together):\n super().__init__(name, index_together)\n \n+ def database_forwards(self, app_label, schema_editor, from_state, to_state):\n+ new_model = to_state.apps.get_model(app_label, self.name)\n+ if self.allow_migrate_model(schema_editor.connection.alias, new_model):\n+ old_model = from_state.apps.get_model(app_label, self.name)\n+ schema_editor._delete_composed_index(old_model, self.index_together, 'index')\n+ schema_editor._create_composed_index(new_model, self.index_together, 'index')\n+\n \n class AlterOrderWithRespectTo(ModelOptionOperation):\n \"\"\"Represent a change with the order_with_respect_to option.\"\"\"\n", "model_lint_repair_patch": "diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py\nindex 8c06c4d157..ff44ee352f 100644\n--- a/django/db/migrations/operations/models.py\n+++ b/django/db/migrations/operations/models.py\n@@ -537,6 +537,13 @@ class AlterUniqueTogether(AlterTogetherOptionOperation):\n def __init__(self, name, unique_together):\n super().__init__(name, unique_together)\n \n+ def database_forwards(self, app_label, schema_editor, from_state, to_state):\n+ new_model = to_state.apps.get_model(app_label, self.name)\n+ if self.allow_migrate_model(schema_editor.connection.alias, new_model):\n+ old_model = from_state.apps.get_model(app_label, self.name)\n+ schema_editor._delete_composed_index(old_model, self.unique_together, 'unique')\n+ schema_editor._create_composed_index(new_model, self.unique_together, 'unique')\n+\n \n class AlterIndexTogether(AlterTogetherOptionOperation):\n \"\"\"\n@@ -548,6 +555,13 @@ class AlterIndexTogether(AlterTogetherOptionOperation):\n def __init__(self, name, index_together):\n super().__init__(name, index_together)\n \n+ def database_forwards(self, app_label, schema_editor, from_state, to_state):\n+ new_model = to_state.apps.get_model(app_label, self.name)\n+ if self.allow_migrate_model(schema_editor.connection.alias, new_model):\n+ old_model = from_state.apps.get_model(app_label, self.name)\n+ schema_editor._delete_composed_index(old_model, self.index_together, 'index')\n+ schema_editor._create_composed_index(new_model, self.index_together, 'index')\n+\n \n class AlterOrderWithRespectTo(ModelOptionOperation):\n \"\"\"Represent a change with the order_with_respect_to option.\"\"\"\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["indexes.tests"]} +{"repo": "pylint-dev/pylint", "instance_id": "pylint-dev__pylint-5859", "base_commit": "182cc539b8154c0710fcea7e522267e42eba8899", "patch": "diff --git a/pylint/checkers/misc.py b/pylint/checkers/misc.py\n--- a/pylint/checkers/misc.py\n+++ b/pylint/checkers/misc.py\n@@ -121,9 +121,9 @@ def open(self):\n \n notes = \"|\".join(re.escape(note) for note in self.config.notes)\n if self.config.notes_rgx:\n- regex_string = rf\"#\\s*({notes}|{self.config.notes_rgx})\\b\"\n+ regex_string = rf\"#\\s*({notes}|{self.config.notes_rgx})(?=(:|\\s|\\Z))\"\n else:\n- regex_string = rf\"#\\s*({notes})\\b\"\n+ regex_string = rf\"#\\s*({notes})(?=(:|\\s|\\Z))\"\n \n self._fixme_pattern = re.compile(regex_string, re.I)\n \n", "test_patch": "diff --git a/tests/checkers/unittest_misc.py b/tests/checkers/unittest_misc.py\n--- a/tests/checkers/unittest_misc.py\n+++ b/tests/checkers/unittest_misc.py\n@@ -68,6 +68,16 @@ def test_without_space_fixme(self) -> None:\n ):\n self.checker.process_tokens(_tokenize_str(code))\n \n+ @set_config(notes=[\"???\"])\n+ def test_non_alphanumeric_codetag(self) -> None:\n+ code = \"\"\"a = 1\n+ #???\n+ \"\"\"\n+ with self.assertAddsMessages(\n+ MessageTest(msg_id=\"fixme\", line=2, args=\"???\", col_offset=17)\n+ ):\n+ self.checker.process_tokens(_tokenize_str(code))\n+\n @set_config(notes=[])\n def test_absent_codetag(self) -> None:\n code = \"\"\"a = 1\n", "problem_statement": "\"--notes\" option ignores note tags that are entirely punctuation\n### Bug description\n\nIf a note tag specified with the `--notes` option is entirely punctuation, pylint won't report a fixme warning (W0511).\r\n\r\n```python\r\n# YES: yes\r\n# ???: no\r\n```\r\n\r\n`pylint test.py --notes=\"YES,???\"` will return a fixme warning (W0511) for the first line, but not the second.\n\n### Configuration\n\n```ini\nDefault\n```\n\n\n### Command used\n\n```shell\npylint test.py --notes=\"YES,???\"\n```\n\n\n### Pylint output\n\n```shell\n************* Module test\r\ntest.py:1:1: W0511: YES: yes (fixme)\n```\n\n\n### Expected behavior\n\n```\r\n************* Module test\r\ntest.py:1:1: W0511: YES: yes (fixme)\r\ntest.py:2:1: W0511: ???: no (fixme)\r\n```\n\n### Pylint version\n\n```shell\npylint 2.12.2\r\nastroid 2.9.0\r\nPython 3.10.2 (main, Feb 2 2022, 05:51:25) [Clang 13.0.0 (clang-1300.0.29.3)]\n```\n\n\n### OS / Environment\n\nmacOS 11.6.1\n\n### Additional dependencies\n\n_No response_\n", "hints_text": "Did a little investigation, this is we're actually converting this option in a regular expression pattern (thereby making it awfully similar to the `notes-rgx` option). Since `?` is a special character in regex this doesn't get picked up. Using `\\?\\?\\?` in either `notes` or `notes-rgx` should work.", "created_at": "2022-03-04T00:01:54Z", "version": "2.13", "FAIL_TO_PASS": "[\"tests/checkers/unittest_misc.py::TestFixme::test_non_alphanumeric_codetag\"]", "PASS_TO_PASS": "[\"tests/checkers/unittest_misc.py::TestFixme::test_fixme_with_message\", \"tests/checkers/unittest_misc.py::TestFixme::test_todo_without_message\", \"tests/checkers/unittest_misc.py::TestFixme::test_xxx_without_space\", \"tests/checkers/unittest_misc.py::TestFixme::test_xxx_middle\", \"tests/checkers/unittest_misc.py::TestFixme::test_without_space_fixme\", \"tests/checkers/unittest_misc.py::TestFixme::test_absent_codetag\", \"tests/checkers/unittest_misc.py::TestFixme::test_other_present_codetag\", \"tests/checkers/unittest_misc.py::TestFixme::test_issue_2321_should_not_trigger\", \"tests/checkers/unittest_misc.py::TestFixme::test_issue_2321_should_trigger\", \"tests/checkers/unittest_misc.py::TestFixme::test_dont_trigger_on_todoist\"]", "environment_setup_commit": "3b2fbaec045697d53bdd4435e59dbfc2b286df4b", "test_directives": ["tests/checkers/unittest_misc.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v tests/checkers/unittest_misc.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["tests/functional/f/fixme.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/pylint/config/option.py b/pylint/config/option.py\nindex cf88e3fc9..0e0e43772 100644\n--- a/pylint/config/option.py\n+++ b/pylint/config/option.py\n@@ -12,6 +12,9 @@ from pylint import utils\n \n # pylint: disable=unused-argument\n def _csv_validator(_, name, value):\n+ # Allow punctuation-only strings as valid note tags\n+ if all(char in '!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~' for char in value):\n+ return [value]\n return utils._check_csv(value)\n \n \n@@ -102,7 +105,7 @@ VALIDATORS = {\n \"regexp\": lambda pattern: re.compile(pattern or \"\"),\n \"regexp_csv\": _regexp_csv_validator,\n \"regexp_paths_csv\": _regexp_paths_csv_validator,\n- \"csv\": _csv_validator,\n+ \"csv\": _csv_validator, # Ensure the updated _csv_validator is used\n \"yn\": _yn_validator,\n \"choice\": lambda opt, name, value: _choice_validator(opt[\"choices\"], name, value),\n \"multiple_choice\": lambda opt, name, value: _multiple_choice_validator(\n", "model_lint_repair_patch": "diff --git a/pylint/config/option.py b/pylint/config/option.py\nindex cf88e3fc9..0e0e43772 100644\n--- a/pylint/config/option.py\n+++ b/pylint/config/option.py\n@@ -12,6 +12,9 @@ from pylint import utils\n \n # pylint: disable=unused-argument\n def _csv_validator(_, name, value):\n+ # Allow punctuation-only strings as valid note tags\n+ if all(char in '!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~' for char in value):\n+ return [value]\n return utils._check_csv(value)\n \n \n@@ -102,7 +105,7 @@ VALIDATORS = {\n \"regexp\": lambda pattern: re.compile(pattern or \"\"),\n \"regexp_csv\": _regexp_csv_validator,\n \"regexp_paths_csv\": _regexp_paths_csv_validator,\n- \"csv\": _csv_validator,\n+ \"csv\": _csv_validator, # Ensure the updated _csv_validator is used\n \"yn\": _yn_validator,\n \"choice\": lambda opt, name, value: _choice_validator(opt[\"choices\"], name, value),\n \"multiple_choice\": lambda opt, name, value: _multiple_choice_validator(\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-11179", "base_commit": "19fc6376ce67d01ca37a91ef2f55ef769f50513a", "patch": "diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py\n--- a/django/db/models/deletion.py\n+++ b/django/db/models/deletion.py\n@@ -277,6 +277,7 @@ def delete(self):\n if self.can_fast_delete(instance):\n with transaction.mark_for_rollback_on_error():\n count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)\n+ setattr(instance, model._meta.pk.attname, None)\n return count, {model._meta.label: count}\n \n with transaction.atomic(using=self.using, savepoint=False):\n", "test_patch": "diff --git a/tests/delete/tests.py b/tests/delete/tests.py\n--- a/tests/delete/tests.py\n+++ b/tests/delete/tests.py\n@@ -1,6 +1,7 @@\n from math import ceil\n \n from django.db import IntegrityError, connection, models\n+from django.db.models.deletion import Collector\n from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE\n from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature\n \n@@ -471,6 +472,14 @@ def test_fast_delete_qs(self):\n self.assertEqual(User.objects.count(), 1)\n self.assertTrue(User.objects.filter(pk=u2.pk).exists())\n \n+ def test_fast_delete_instance_set_pk_none(self):\n+ u = User.objects.create()\n+ # User can be fast-deleted.\n+ collector = Collector(using='default')\n+ self.assertTrue(collector.can_fast_delete(u))\n+ u.delete()\n+ self.assertIsNone(u.pk)\n+\n def test_fast_delete_joined_qs(self):\n a = Avatar.objects.create(desc='a')\n User.objects.create(avatar=a)\n", "problem_statement": "delete() on instances of models without any dependencies doesn't clear PKs.\nDescription\n\t\nDeleting any model with no dependencies not updates the PK on the model. It should be set to None after .delete() call.\nSee Django.db.models.deletion:276-281. Should update the model line 280.\n", "hints_text": "Reproduced at 1ffddfc233e2d5139cc6ec31a4ec6ef70b10f87f. Regression in bc7dd8490b882b2cefdc7faf431dc64c532b79c9. Thanks for the report.\nRegression test.\nI have attached a simple fix which mimics what \u200bhttps://github.com/django/django/blob/master/django/db/models/deletion.py#L324-L326 does for multiple objects. I am not sure if we need \u200bhttps://github.com/django/django/blob/master/django/db/models/deletion.py#L320-L323 (the block above) because I think field_updates is only ever filled if the objects are not fast-deletable -- ie \u200bhttps://github.com/django/django/blob/master/django/db/models/deletion.py#L224 is not called due to the can_fast_delete check at the beginning of the collect function. That said, if we want to be extra \"safe\" we can just move lines 320 - 326 into an extra function and call that from the old and new location (though I do not think it is needed).", "created_at": "2019-04-05T15:54:39Z", "version": "3.0", "FAIL_TO_PASS": "[\"test_fast_delete_instance_set_pk_none (delete.tests.FastDeleteTests)\"]", "PASS_TO_PASS": "[\"test_fast_delete_empty_no_update_can_self_select (delete.tests.FastDeleteTests)\", \"test_fast_delete_fk (delete.tests.FastDeleteTests)\", \"test_fast_delete_inheritance (delete.tests.FastDeleteTests)\", \"test_fast_delete_joined_qs (delete.tests.FastDeleteTests)\", \"test_fast_delete_large_batch (delete.tests.FastDeleteTests)\", \"test_fast_delete_m2m (delete.tests.FastDeleteTests)\", \"test_fast_delete_qs (delete.tests.FastDeleteTests)\", \"test_fast_delete_revm2m (delete.tests.FastDeleteTests)\", \"test_auto (delete.tests.OnDeleteTests)\", \"test_auto_nullable (delete.tests.OnDeleteTests)\", \"test_cascade (delete.tests.OnDeleteTests)\", \"test_cascade_from_child (delete.tests.OnDeleteTests)\", \"test_cascade_from_parent (delete.tests.OnDeleteTests)\", \"test_cascade_nullable (delete.tests.OnDeleteTests)\", \"test_do_nothing (delete.tests.OnDeleteTests)\", \"test_do_nothing_qscount (delete.tests.OnDeleteTests)\", \"test_inheritance_cascade_down (delete.tests.OnDeleteTests)\", \"test_inheritance_cascade_up (delete.tests.OnDeleteTests)\", \"test_o2o_setnull (delete.tests.OnDeleteTests)\", \"test_protect (delete.tests.OnDeleteTests)\", \"test_setdefault (delete.tests.OnDeleteTests)\", \"test_setdefault_none (delete.tests.OnDeleteTests)\", \"test_setnull (delete.tests.OnDeleteTests)\", \"test_setnull_from_child (delete.tests.OnDeleteTests)\", \"test_setnull_from_parent (delete.tests.OnDeleteTests)\", \"test_setvalue (delete.tests.OnDeleteTests)\", \"test_bulk (delete.tests.DeletionTests)\", \"test_can_defer_constraint_checks (delete.tests.DeletionTests)\", \"test_delete_with_keeping_parents (delete.tests.DeletionTests)\", \"test_delete_with_keeping_parents_relationships (delete.tests.DeletionTests)\", \"test_deletion_order (delete.tests.DeletionTests)\", \"test_hidden_related (delete.tests.DeletionTests)\", \"test_instance_update (delete.tests.DeletionTests)\", \"test_large_delete (delete.tests.DeletionTests)\", \"test_large_delete_related (delete.tests.DeletionTests)\", \"test_m2m (delete.tests.DeletionTests)\", \"test_model_delete_returns_num_rows (delete.tests.DeletionTests)\", \"test_proxied_model_duplicate_queries (delete.tests.DeletionTests)\", \"test_queryset_delete_returns_num_rows (delete.tests.DeletionTests)\", \"test_relational_post_delete_signals_happen_before_parent_object (delete.tests.DeletionTests)\"]", "environment_setup_commit": "419a78300f7cd27611196e1e464d50fd0385ff27", "test_directives": ["delete.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 delete.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/delete/tests.py b/tests/delete/tests.py\nindex 55eeb226ea..0b6cd15fc0 100644\n--- a/tests/delete/tests.py\n+++ b/tests/delete/tests.py\n@@ -450,6 +450,14 @@ class FastDeleteTests(TestCase):\n self.assertFalse(User.objects.exists())\n self.assertFalse(Avatar.objects.exists())\n \n+ def test_delete_clears_pk(self):\n+ \"\"\"\n+ Deleting a model instance with no dependencies should set its PK to None.\n+ \"\"\"\n+ avatar = Avatar.objects.create(desc='test')\n+ avatar.delete()\n+ self.assertIsNone(avatar.pk)\n+\n def test_fast_delete_m2m(self):\n t = M2MTo.objects.create()\n f = M2MFrom.objects.create()\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["delete.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py\nindex 92fe4affb9..ffe7a117da 100644\n--- a/django/db/models/deletion.py\n+++ b/django/db/models/deletion.py\n@@ -324,4 +324,11 @@ class Collector:\n for model, instances in self.data.items():\n for instance in instances:\n setattr(instance, model._meta.pk.attname, None)\n+ \n+ # Set PK to None for models without dependencies\n+ for model, instances in self.data.items():\n+ if model not in self.dependencies:\n+ for instance in instances:\n+ setattr(instance, model._meta.pk.attname, None)\n+ \n return sum(deleted_counter.values()), dict(deleted_counter)\n", "model_lint_repair_patch": "diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py\nindex 92fe4affb9..ffe7a117da 100644\n--- a/django/db/models/deletion.py\n+++ b/django/db/models/deletion.py\n@@ -324,4 +324,11 @@ class Collector:\n for model, instances in self.data.items():\n for instance in instances:\n setattr(instance, model._meta.pk.attname, None)\n+ \n+ # Set PK to None for models without dependencies\n+ for model, instances in self.data.items():\n+ if model not in self.dependencies:\n+ for instance in instances:\n+ setattr(instance, model._meta.pk.attname, None)\n+ \n return sum(deleted_counter.values()), dict(deleted_counter)\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["delete.tests"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-13647", "base_commit": "67e3c956083d0128a621f65ee86a7dacd4f9f19f", "patch": "diff --git a/sympy/matrices/common.py b/sympy/matrices/common.py\n--- a/sympy/matrices/common.py\n+++ b/sympy/matrices/common.py\n@@ -86,7 +86,7 @@ def entry(i, j):\n return self[i, j]\n elif pos <= j < pos + other.cols:\n return other[i, j - pos]\n- return self[i, j - pos - other.cols]\n+ return self[i, j - other.cols]\n \n return self._new(self.rows, self.cols + other.cols,\n lambda i, j: entry(i, j))\n", "test_patch": "diff --git a/sympy/matrices/tests/test_commonmatrix.py b/sympy/matrices/tests/test_commonmatrix.py\n--- a/sympy/matrices/tests/test_commonmatrix.py\n+++ b/sympy/matrices/tests/test_commonmatrix.py\n@@ -200,6 +200,14 @@ def test_col_insert():\n l = [0, 0, 0]\n l.insert(i, 4)\n assert flatten(zeros_Shaping(3).col_insert(i, c4).row(0).tolist()) == l\n+ # issue 13643\n+ assert eye_Shaping(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \\\n+ Matrix([[1, 0, 0, 2, 2, 0, 0, 0],\n+ [0, 1, 0, 2, 2, 0, 0, 0],\n+ [0, 0, 1, 2, 2, 0, 0, 0],\n+ [0, 0, 0, 2, 2, 1, 0, 0],\n+ [0, 0, 0, 2, 2, 0, 1, 0],\n+ [0, 0, 0, 2, 2, 0, 0, 1]])\n \n def test_extract():\n m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)\n", "problem_statement": "Matrix.col_insert() no longer seems to work correctly.\nExample:\r\n\r\n```\r\nIn [28]: import sympy as sm\r\n\r\nIn [29]: M = sm.eye(6)\r\n\r\nIn [30]: M\r\nOut[30]: \r\n\u23a11 0 0 0 0 0\u23a4\r\n\u23a2 \u23a5\r\n\u23a20 1 0 0 0 0\u23a5\r\n\u23a2 \u23a5\r\n\u23a20 0 1 0 0 0\u23a5\r\n\u23a2 \u23a5\r\n\u23a20 0 0 1 0 0\u23a5\r\n\u23a2 \u23a5\r\n\u23a20 0 0 0 1 0\u23a5\r\n\u23a2 \u23a5\r\n\u23a30 0 0 0 0 1\u23a6\r\n\r\nIn [31]: V = 2 * sm.ones(6, 2)\r\n\r\nIn [32]: V\r\nOut[32]: \r\n\u23a12 2\u23a4\r\n\u23a2 \u23a5\r\n\u23a22 2\u23a5\r\n\u23a2 \u23a5\r\n\u23a22 2\u23a5\r\n\u23a2 \u23a5\r\n\u23a22 2\u23a5\r\n\u23a2 \u23a5\r\n\u23a22 2\u23a5\r\n\u23a2 \u23a5\r\n\u23a32 2\u23a6\r\n\r\nIn [33]: M.col_insert(3, V)\r\nOut[33]: \r\n\u23a11 0 0 2 2 1 0 0\u23a4\r\n\u23a2 \u23a5\r\n\u23a20 1 0 2 2 0 1 0\u23a5\r\n\u23a2 \u23a5\r\n\u23a20 0 1 2 2 0 0 1\u23a5\r\n\u23a2 \u23a5\r\n\u23a20 0 0 2 2 0 0 0\u23a5\r\n\u23a2 \u23a5\r\n\u23a20 0 0 2 2 0 0 0\u23a5\r\n\u23a2 \u23a5\r\n\u23a30 0 0 2 2 0 0 0\u23a6\r\nIn [34]: sm.__version__\r\nOut[34]: '1.1.1'\r\n```\r\n\r\nThe 3 x 3 identify matrix to the right of the columns of twos is shifted from the bottom three rows to the top three rows.\r\n\r\n@siefkenj Do you think this has to do with your matrix refactor?\n", "hints_text": "It seems that `pos` shouldn't be [here](https://github.com/sympy/sympy/blob/master/sympy/matrices/common.py#L89).", "created_at": "2017-11-28T21:22:51Z", "version": "1.1", "FAIL_TO_PASS": "[\"test_col_insert\"]", "PASS_TO_PASS": "[\"test__MinimalMatrix\", \"test_vec\", \"test_tolist\", \"test_row_col_del\", \"test_get_diag_blocks1\", \"test_get_diag_blocks2\", \"test_shape\", \"test_reshape\", \"test_row_col\", \"test_row_join\", \"test_col_join\", \"test_row_insert\", \"test_extract\", \"test_hstack\", \"test_vstack\", \"test_atoms\", \"test_free_symbols\", \"test_has\", \"test_is_anti_symmetric\", \"test_diagonal_symmetrical\", \"test_is_hermitian\", \"test_is_Identity\", \"test_is_symbolic\", \"test_is_upper\", \"test_is_lower\", \"test_is_square\", \"test_is_symmetric\", \"test_is_hessenberg\", \"test_is_zero\", \"test_values\", \"test_applyfunc\", \"test_adjoint\", \"test_as_real_imag\", \"test_conjugate\", \"test_doit\", \"test_evalf\", \"test_expand\", \"test_replace\", \"test_replace_map\", \"test_simplify\", \"test_subs\", \"test_trace\", \"test_xreplace\", \"test_permute\", \"test_abs\", \"test_add\", \"test_multiplication\", \"test_power\", \"test_neg\", \"test_sub\", \"test_div\", \"test_det\", \"test_adjugate\", \"test_cofactor_and_minors\", \"test_charpoly\", \"test_row_op\", \"test_col_op\", \"test_is_echelon\", \"test_echelon_form\", \"test_rref\", \"test_eye\", \"test_ones\", \"test_zeros\", \"test_diag\", \"test_jordan_block\", \"test_columnspace\", \"test_rowspace\", \"test_nullspace\", \"test_eigenvals\", \"test_eigenvects\", \"test_left_eigenvects\", \"test_diagonalize\", \"test_is_diagonalizable\", \"test_jordan_form\", \"test_singular_values\", \"test_integrate\"]", "environment_setup_commit": "ec9e3c0436fbff934fa84e22bf07f1b3ef5bfac3", "test_directives": ["sympy/matrices/tests/test_commonmatrix.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/matrices/tests/test_commonmatrix.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/sympy/matrices/tests/test_commonmatrix.py b/sympy/matrices/tests/test_commonmatrix.py\nindex 8dc4d717cd..ca877050c0 100644\n--- a/sympy/matrices/tests/test_commonmatrix.py\n+++ b/sympy/matrices/tests/test_commonmatrix.py\n@@ -1332,3 +1332,28 @@ def test_limit():\n x, y = symbols('x y')\n m = CalculusOnlyMatrix(2, 1, [1/x, y])\n assert m.limit(x, 5) == Matrix(2, 1, [S(1)/5, y])\n+\n+def test_col_insert():\n+ M = eye(6)\n+ V = 2 * ones(6, 2)\n+ result = M.col_insert(3, V)\n+ expected = Matrix([\n+ [1, 0, 0, 2, 2, 0, 0, 0],\n+ [0, 1, 0, 2, 2, 0, 0, 0],\n+ [0, 0, 1, 2, 2, 0, 0, 0],\n+ [0, 0, 0, 2, 2, 1, 0, 0],\n+ [0, 0, 0, 2, 2, 0, 1, 0],\n+ [0, 0, 0, 2, 2, 0, 0, 1]\n+ ])\n+ assert result == expected\n+\n+ # Additional test cases\n+ M = eye(3)\n+ V = ones(3, 1)\n+ result = M.col_insert(1, V)\n+ expected = Matrix([\n+ [1, 1, 0, 0],\n+ [0, 1, 1, 0],\n+ [0, 1, 0, 1]\n+ ])\n+ assert result == expected\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/matrices/tests/test_commonmatrix.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/matrices/sparse.py b/sympy/matrices/sparse.py\nindex 7701cbc179..0bb05fea3d 100644\n--- a/sympy/matrices/sparse.py\n+++ b/sympy/matrices/sparse.py\n@@ -272,15 +272,14 @@ def _eval_col_insert(self, icol, other):\n if not isinstance(other, SparseMatrix):\n other = SparseMatrix(other)\n new_smat = {}\n- # make room for the new rows\n- for key, val in self._smat.items():\n- row, col = key\n+ # make room for the new columns\n+ for (row, col), val in self._smat.items():\n if col >= icol:\n- col += other.cols\n- new_smat[(row, col)] = val\n+ new_smat[(row, col + other.cols)] = val\n+ else:\n+ new_smat[(row, col)] = val\n # add other's keys\n- for key, val in other._smat.items():\n- row, col = key\n+ for (row, col), val in other._smat.items():\n new_smat[(row, col + icol)] = val\n return self._new(self.rows, self.cols + other.cols, new_smat)\n \n", "model_lint_repair_patch": "diff --git a/sympy/matrices/sparse.py b/sympy/matrices/sparse.py\nindex 7701cbc179..0bb05fea3d 100644\n--- a/sympy/matrices/sparse.py\n+++ b/sympy/matrices/sparse.py\n@@ -272,15 +272,14 @@ def _eval_col_insert(self, icol, other):\n if not isinstance(other, SparseMatrix):\n other = SparseMatrix(other)\n new_smat = {}\n- # make room for the new rows\n- for key, val in self._smat.items():\n- row, col = key\n+ # make room for the new columns\n+ for (row, col), val in self._smat.items():\n if col >= icol:\n- col += other.cols\n- new_smat[(row, col)] = val\n+ new_smat[(row, col + other.cols)] = val\n+ else:\n+ new_smat[(row, col)] = val\n # add other's keys\n- for key, val in other._smat.items():\n- row, col = key\n+ for (row, col), val in other._smat.items():\n new_smat[(row, col + icol)] = val\n return self._new(self.rows, self.cols + other.cols, new_smat)\n \n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-13658", "base_commit": "0773837e15bb632afffb6848a58c59a791008fa1", "patch": "diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py\n--- a/django/core/management/__init__.py\n+++ b/django/core/management/__init__.py\n@@ -344,7 +344,12 @@ def execute(self):\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(\n+ prog=self.prog_name,\n+ usage='%(prog)s subcommand [options] [args]',\n+ add_help=False,\n+ allow_abbrev=False,\n+ )\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/admin_scripts/tests.py b/tests/admin_scripts/tests.py\n--- a/tests/admin_scripts/tests.py\n+++ b/tests/admin_scripts/tests.py\n@@ -17,7 +17,7 @@\n from django import conf, get_version\n from django.conf import settings\n from django.core.management import (\n- BaseCommand, CommandError, call_command, color,\n+ BaseCommand, CommandError, call_command, color, execute_from_command_line,\n )\n from django.core.management.commands.loaddata import Command as LoaddataCommand\n from django.core.management.commands.runserver import (\n@@ -31,6 +31,7 @@\n from django.test import (\n LiveServerTestCase, SimpleTestCase, TestCase, override_settings,\n )\n+from django.test.utils import captured_stderr, captured_stdout\n \n custom_templates_dir = os.path.join(os.path.dirname(__file__), 'custom_templates')\n \n@@ -1867,6 +1868,20 @@ def _test(self, args, option_b=\"'2'\"):\n )\n \n \n+class ExecuteFromCommandLine(SimpleTestCase):\n+ def test_program_name_from_argv(self):\n+ \"\"\"\n+ Program name is computed from the execute_from_command_line()'s argv\n+ argument, not sys.argv.\n+ \"\"\"\n+ args = ['help', 'shell']\n+ with captured_stdout() as out, captured_stderr() as err:\n+ with mock.patch('sys.argv', [None] + args):\n+ execute_from_command_line(['django-admin'] + args)\n+ self.assertIn('usage: django-admin shell', out.getvalue())\n+ self.assertEqual(err.getvalue(), '')\n+\n+\n @override_settings(ROOT_URLCONF='admin_scripts.urls')\n class StartProject(LiveServerTestCase, AdminScriptTestCase):\n \n", "problem_statement": "ManagementUtility instantiates CommandParser without passing already-computed prog argument\nDescription\n\t\nManagementUtility \u200bgoes to the trouble to parse the program name from the argv it's passed rather than from sys.argv: \n\tdef __init__(self, argv=None):\n\t\tself.argv = argv or sys.argv[:]\n\t\tself.prog_name = os.path.basename(self.argv[0])\n\t\tif self.prog_name == '__main__.py':\n\t\t\tself.prog_name = 'python -m django'\nBut then when it needs to parse --pythonpath and --settings, it \u200buses the program name from sys.argv: \n\t\tparser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False)\nAbove \"%(prog)s\" \u200brefers to sys.argv[0]. Instead, it should refer to self.prog_name. This can fixed as follows:\n\t\tparser = CommandParser(\n\t\t\tprog=self.prog_name,\n\t\t\tusage='%(prog)s subcommand [options] [args]',\n\t\t\tadd_help=False,\n\t\t\tallow_abbrev=False)\nI'm aware that execute_from_command_line is a private API, but it'd be really convenient for me if it worked properly in my weird embedded environment where sys.argv[0] is \u200bincorrectly None. If passing my own argv to execute_from_command_line avoided all the ensuing exceptions, I wouldn't have to modify sys.argv[0] globally as I'm doing in the meantime.\n", "hints_text": "Tentatively accepted, looks valid but I was not able to reproduce and invalid message (even with mocking sys.argv), so a regression test is crucial.", "created_at": "2020-11-09T20:50:28Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_program_name_from_argv (admin_scripts.tests.ExecuteFromCommandLine)\"]", "PASS_TO_PASS": "[\"test_params_to_runserver (admin_scripts.tests.ManageTestserver)\", \"test_testserver_handle_params (admin_scripts.tests.ManageTestserver)\", \"test_no_database (admin_scripts.tests.ManageRunserver)\", \"test_readonly_database (admin_scripts.tests.ManageRunserver)\", \"test_runner_addrport_ipv6 (admin_scripts.tests.ManageRunserver)\", \"test_runner_ambiguous (admin_scripts.tests.ManageRunserver)\", \"test_runner_custom_defaults (admin_scripts.tests.ManageRunserver)\", \"test_runner_custom_defaults_ipv6 (admin_scripts.tests.ManageRunserver)\", \"test_runner_hostname (admin_scripts.tests.ManageRunserver)\", \"test_runner_hostname_ipv6 (admin_scripts.tests.ManageRunserver)\", \"test_runserver_addrport (admin_scripts.tests.ManageRunserver)\", \"test_migration_warning_one_app (admin_scripts.tests.ManageRunserverMigrationWarning)\", \"test_precedence (admin_scripts.tests.Discovery)\", \"test_program_name_in_help (admin_scripts.tests.MainModule)\", \"test_non_existent_command_output (admin_scripts.tests.ManageManuallyConfiguredSettings)\", \"Regression for #20509\", \"test_empty_allowed_hosts_error (admin_scripts.tests.ManageRunserverEmptyAllowedHosts)\", \"no settings: manage.py builtin commands fail with an error when no settings provided\", \"no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist\", \"no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist\", \"test_attribute_error (admin_scripts.tests.ManageSettingsWithSettingsErrors)\", \"test_help (admin_scripts.tests.ManageSettingsWithSettingsErrors)\", \"test_import_error (admin_scripts.tests.ManageSettingsWithSettingsErrors)\", \"test_key_error (admin_scripts.tests.ManageSettingsWithSettingsErrors)\", \"test_no_suggestions (admin_scripts.tests.DjangoAdminSuggestions)\", \"test_suggestions (admin_scripts.tests.DjangoAdminSuggestions)\", \"no settings: django-admin builtin commands fail with an error when no settings provided\", \"no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist\", \"no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist\", \"test_commands_with_invalid_settings (admin_scripts.tests.DjangoAdminNoSettings)\", \"Options passed before settings are correctly handled.\", \"Options are correctly handled when they are passed before and after\", \"Options passed after settings are correctly handled.\", \"Short options passed after settings are correctly handled.\", \"Short options passed before settings are correctly handled.\", \"minimal: django-admin builtin commands fail with an error when no settings provided\", \"minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist\", \"minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist\", \"minimal: django-admin builtin commands fail if settings are provided in the environment\", \"minimal: django-admin builtin commands fail if settings are provided as argument\", \"minimal: django-admin can't execute user commands unless settings are provided\", \"minimal: django-admin can't execute user commands, even if settings are provided in environment\", \"minimal: django-admin can't execute user commands, even if settings are provided as argument\", \"alternate: django-admin builtin commands fail with an error when no settings provided\", \"alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist\", \"alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist\", \"alternate: django-admin builtin commands succeed if settings are provided in the environment\", \"alternate: django-admin builtin commands succeed if settings are provided as argument\", \"alternate: django-admin can't execute user commands unless settings are provided\", \"alternate: django-admin can execute user commands if settings are provided in environment\", \"alternate: django-admin can execute user commands if settings are provided as argument\", \"default: django-admin builtin commands fail with an error when no settings provided\", \"default: django-admin builtin commands fail if settings file (from environment) doesn't exist\", \"default: django-admin builtin commands fail if settings file (from argument) doesn't exist\", \"default: django-admin builtin commands succeed if settings are provided in the environment\", \"default: django-admin builtin commands succeed if settings are provided as argument\", \"default: django-admin can't execute user commands if it isn't provided settings\", \"default: django-admin can execute user commands if settings are provided in environment\", \"default: django-admin can execute user commands if settings are provided as argument\", \"directory: django-admin builtin commands fail with an error when no settings provided\", \"directory: django-admin builtin commands fail if settings file (from environment) doesn't exist\", \"directory: django-admin builtin commands fail if settings file (from argument) doesn't exist\", \"directory: django-admin builtin commands succeed if settings are provided in the environment\", \"directory: django-admin builtin commands succeed if settings are provided as argument\", \"directory: django-admin can't execute user commands unless settings are provided\", \"directory: startapp creates the correct directory\", \"directory: startapp creates the correct directory with a custom template\", \"test_importable_name (admin_scripts.tests.StartApp)\", \"test_importable_target_name (admin_scripts.tests.StartApp)\", \"startapp validates that app name is a valid Python identifier.\", \"test_invalid_target_name (admin_scripts.tests.StartApp)\", \"test_overlaying_app (admin_scripts.tests.StartApp)\", \"manage.py check does not raise errors when an app imports a base\", \"manage.py check reports an ImportError if an app's models.py\", \"manage.py check does not raise an ImportError validating a\", \"check reports an error on a nonexistent app in INSTALLED_APPS.\", \"All errors/warnings should be sorted by level and by message.\", \"test_warning_does_not_halt (admin_scripts.tests.ManageCheck)\", \"fulldefault: django-admin builtin commands fail with an error when no settings provided\", \"fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist\", \"fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist\", \"fulldefault: django-admin builtin commands succeed if the environment contains settings\", \"fulldefault: django-admin builtin commands succeed if a settings file is provided\", \"fulldefault: django-admin can't execute user commands unless settings are provided\", \"fulldefault: django-admin can execute user commands if settings are provided in environment\", \"fulldefault: django-admin can execute user commands if settings are provided as argument\", \"Runs without error and emits settings diff.\", \"test_custom_default (admin_scripts.tests.DiffSettings)\", \"test_dynamic_settings_configured (admin_scripts.tests.DiffSettings)\", \"test_settings_configured (admin_scripts.tests.DiffSettings)\", \"--output=unified emits settings diff in unified mode.\", \"default: manage.py builtin commands succeed when default settings are appropriate\", \"default: manage.py builtin commands fail if settings file (from environment) doesn't exist\", \"default: manage.py builtin commands succeed if settings file (from argument) doesn't exist\", \"default: manage.py builtin commands succeed if settings are provided in the environment\", \"default: manage.py builtin commands succeed if settings are provided as argument\", \"default: manage.py can execute user commands when default settings are appropriate\", \"default: manage.py can execute user commands when settings are provided in environment\", \"default: manage.py can execute user commands when settings are provided as argument\", \"alternate: manage.py builtin commands fail with an error when no default settings provided\", \"alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist\", \"alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist\", \"alternate: manage.py builtin commands work if settings are provided in the environment\", \"alternate: manage.py builtin commands work with settings provided as argument\", \"alternate: manage.py can't execute user commands without settings\", \"alternate: manage.py output syntax color can be deactivated with the `--no-color` option\", \"alternate: manage.py can execute user commands if settings are provided in environment\", \"alternate: manage.py can execute user commands if settings are provided as argument\", \"minimal: manage.py builtin commands fail with an error when no settings provided\", \"minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist\", \"minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist\", \"minimal: manage.py builtin commands fail if settings are provided in the environment\", \"minimal: manage.py builtin commands fail if settings are provided as argument\", \"minimal: manage.py can't execute user commands without appropriate settings\", \"minimal: manage.py can't execute user commands, even if settings are provided in environment\", \"minimal: manage.py can't execute user commands, even if settings are provided as argument\", \"multiple: manage.py builtin commands fail with an error when no settings provided\", \"multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist\", \"multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist\", \"multiple: manage.py can execute builtin commands if settings are provided in the environment\", \"multiple: manage.py builtin commands succeed if settings are provided as argument\", \"multiple: manage.py can't execute user commands using default settings\", \"multiple: manage.py can execute user commands if settings are provided in environment\", \"multiple: manage.py can execute user commands if settings are provided as argument\", \"fulldefault: manage.py builtin commands succeed when default settings are appropriate\", \"fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist\", \"fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist\", \"fulldefault: manage.py builtin commands succeed if settings are provided in the environment\", \"fulldefault: manage.py builtin commands succeed if settings are provided as argument\", \"fulldefault: manage.py can execute user commands when default settings are appropriate\", \"fulldefault: manage.py can execute user commands when settings are provided in environment\", \"fulldefault: manage.py can execute user commands when settings are provided as argument\", \"test_custom_project_destination_missing (admin_scripts.tests.StartProject)\", \"Make sure the startproject management command is able to use a different project template\", \"Make sure template context variables are rendered with proper values\", \"Make sure the startproject management command is able to use a different project template from a tarball\", \"test_custom_project_template_from_tarball_by_url (admin_scripts.tests.StartProject)\", \"Startproject can use a project template from a tarball and create it in a specified location\", \"test_custom_project_template_with_non_ascii_templates (admin_scripts.tests.StartProject)\", \"Make sure the startproject management command is able to render custom files\", \"test_importable_project_name (admin_scripts.tests.StartProject)\", \"Make sure the startproject management command validates a project name\", \"Make sure template context variables are not html escaped\", \"Startproject management command handles project template tar/zip balls from non-canonical urls\", \"Make sure the startproject management command creates a project\", \"Make sure the startproject management command creates a project in a specific directory\", \"Ticket 17475: Template dir passed has a trailing path separator\", \"Make sure passing the wrong kinds of arguments outputs an error and prints usage\", \"User AppCommands can execute when a single app name is provided\", \"User AppCommands raise an error when multiple app names are provided\", \"User AppCommands raise an error when no app name is provided\", \"User AppCommands can execute when some of the provided app names are invalid\", \"User BaseCommands can execute when a label is provided\", \"User BaseCommands can execute when no labels are provided\", \"User BaseCommands can execute with options when a label is provided\", \"User BaseCommands can execute with multiple options when a label is provided\", \"User BaseCommands outputs command usage when wrong option is specified\", \"test_base_run_from_argv (admin_scripts.tests.CommandTypes)\", \"test_color_style (admin_scripts.tests.CommandTypes)\", \"test_command_color (admin_scripts.tests.CommandTypes)\", \"--no-color prevent colorization of the output\", \"test_custom_stderr (admin_scripts.tests.CommandTypes)\", \"test_custom_stdout (admin_scripts.tests.CommandTypes)\", \"test_force_color_command_init (admin_scripts.tests.CommandTypes)\", \"test_force_color_execute (admin_scripts.tests.CommandTypes)\", \"help is handled as a special case\", \"--help is equivalent to help\", \"help --commands shows the list of all available commands\", \"-h is handled as a short form of --help\", \"User LabelCommands can execute when a label is provided\", \"User LabelCommands are executed multiple times if multiple labels are provided\", \"User LabelCommands raise an error if no label is provided\", \"test_no_color_force_color_mutually_exclusive_command_init (admin_scripts.tests.CommandTypes)\", \"test_no_color_force_color_mutually_exclusive_execute (admin_scripts.tests.CommandTypes)\", \"NoArg Commands can be executed\", \"NoArg Commands raise an error if an argument is provided\", \"test_run_from_argv_closes_connections (admin_scripts.tests.CommandTypes)\", \"test_run_from_argv_non_ascii_error (admin_scripts.tests.CommandTypes)\", \"--help can be used on a specific command\", \"version is handled as a special case\", \"--version is equivalent to version\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["admin_scripts.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 admin_scripts.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["user_commands.management.commands.hal"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py\nindex 1ba093e51f..e411e86348 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", "model_lint_repair_patch": "diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py\nindex 1ba093e51f..e411e86348 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", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["user_commands.management.commands.hal"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-12481", "base_commit": "c807dfe7569692cad24f02a08477b70c1679a4dd", "patch": "diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py\n--- a/sympy/combinatorics/permutations.py\n+++ b/sympy/combinatorics/permutations.py\n@@ -895,12 +895,8 @@ def __new__(cls, *args, **kwargs):\n # counting starts from 1.\n \n temp = flatten(args)\n- if has_dups(temp):\n- if is_cycle:\n- raise ValueError('there were repeated elements; to resolve '\n- 'cycles use Cycle%s.' % ''.join([str(tuple(c)) for c in args]))\n- else:\n- raise ValueError('there were repeated elements.')\n+ if has_dups(temp) and not is_cycle:\n+ raise ValueError('there were repeated elements.')\n temp = set(temp)\n \n if not is_cycle and \\\n", "test_patch": "diff --git a/sympy/combinatorics/tests/test_permutations.py b/sympy/combinatorics/tests/test_permutations.py\n--- a/sympy/combinatorics/tests/test_permutations.py\n+++ b/sympy/combinatorics/tests/test_permutations.py\n@@ -339,6 +339,7 @@ def test_args():\n assert Permutation([[1], [4, 2]], size=1) == Permutation([0, 1, 4, 3, 2])\n assert Permutation(\n [[1], [4, 2]], size=6) == Permutation([0, 1, 4, 3, 2, 5])\n+ assert Permutation([[0, 1], [0, 2]]) == Permutation(0, 1, 2)\n assert Permutation([], size=3) == Permutation([0, 1, 2])\n assert Permutation(3).list(5) == [0, 1, 2, 3, 4]\n assert Permutation(3).list(-1) == []\n@@ -349,7 +350,6 @@ def test_args():\n raises(ValueError, lambda: Permutation([[1, 2], 0]))\n # enclosing brackets needed on 0\n raises(ValueError, lambda: Permutation([1, 1, 0]))\n- raises(ValueError, lambda: Permutation([[1], [1, 2]]))\n raises(ValueError, lambda: Permutation([4, 5], size=10)) # where are 0-3?\n # but this is ok because cycles imply that only those listed moved\n assert Permutation(4, 5) == Permutation([0, 1, 2, 3, 5, 4])\n", "problem_statement": "`Permutation` constructor fails with non-disjoint cycles\nCalling `Permutation([[0,1],[0,1]])` raises a `ValueError` instead of constructing the identity permutation. If the cycles passed in are non-disjoint, they should be applied in left-to-right order and the resulting permutation should be returned.\r\n\r\nThis should be easy to compute. I don't see a reason why non-disjoint cycles should be forbidden.\n", "hints_text": "", "created_at": "2017-04-03T01:52:33Z", "version": "1.0", "FAIL_TO_PASS": "[\"test_args\"]", "PASS_TO_PASS": "[\"test_Permutation\", \"test_josephus\", \"test_ranking\", \"test_mul\", \"test_Cycle\", \"test_from_sequence\", \"test_printing_cyclic\"]", "environment_setup_commit": "50b81f9f6be151014501ffac44e5dc6b2416938f", "test_directives": ["sympy/combinatorics/tests/test_permutations.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/combinatorics/tests/test_permutations.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/sympy/combinatorics/tests/test_permutations.py b/sympy/combinatorics/tests/test_permutations.py\nindex 7f8cd572e7..3331985395 100644\n--- a/sympy/combinatorics/tests/test_permutations.py\n+++ b/sympy/combinatorics/tests/test_permutations.py\n@@ -13,6 +13,10 @@\n def test_Permutation():\n # don't auto fill 0\n raises(ValueError, lambda: Permutation([1]))\n+ \n+ # test non-disjoint cycles\n+ p = Permutation([[0, 1], [0, 1]])\n+ assert p.array_form == [0, 1]\n p = Permutation([0, 1, 2, 3])\n # call as bijective\n assert [p(i) for i in range(p.size)] == list(p)\n@@ -74,9 +78,9 @@ def test_Permutation():\n \n a = Permutation(1, 3)\n b = Permutation(2, 0, 3)\n- I = Permutation(3)\n+ identity_perm = Permutation(3)\n assert ~a == a**-1\n- assert a*~a == I\n+ assert a*~a == identity_perm\n assert a*b**-1 == a*~b\n \n ans = Permutation(0, 5, 3, 1, 6)(2, 4)\n@@ -249,11 +253,11 @@ def test_ranking():\n assert Permutation([1, 0]).rank_trotterjohnson() == 1\n a = Permutation(list(range(3)))\n b = a\n- l = []\n- tj = []\n+ lex_perms = []\n+ tj_perms = []\n for i in range(6):\n- l.append(a)\n- tj.append(b)\n+ lex_perms.append(a)\n+ tj_perms.append(b)\n a = a.next_lex()\n b = b.next_trotterjohnson()\n assert a == b is None\n@@ -345,9 +349,9 @@ def test_args():\n assert Permutation(5)(1, 2).list(-1) == [0, 2, 1]\n assert Permutation(5)(1, 2).list() == [0, 2, 1, 3, 4, 5]\n raises(ValueError, lambda: Permutation([1, 2], [0]))\n- # enclosing brackets needed\n+ # enclosing brackets needed\n raises(ValueError, lambda: Permutation([[1, 2], 0]))\n- # enclosing brackets needed on 0\n+ # enclosing brackets needed on 0\n raises(ValueError, lambda: Permutation([1, 1, 0]))\n raises(ValueError, lambda: Permutation([[1], [1, 2]]))\n raises(ValueError, lambda: Permutation([4, 5], size=10)) # where are 0-3?\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["sympy/combinatorics/tests/test_permutations.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py\nindex 136ed5a478..862786df23 100644\n--- a/sympy/combinatorics/permutations.py\n+++ b/sympy/combinatorics/permutations.py\n@@ -475,6 +475,8 @@ class Permutation(Basic):\n \n >>> from sympy.combinatorics import Permutation\n >>> Permutation.print_cyclic = False\n+ >>> Permutation([1, 2], [2, 3])\n+ Permutation([0, 2, 3, 1])\n \n Permutations Notation\n =====================\n@@ -873,7 +875,12 @@ def __new__(cls, *args, **kwargs):\n if has_variety(is_sequence(ai) for ai in a):\n ok = False\n else:\n- ok = False\n+ # Process non-disjoint cycles\n+ cycles = args\n+ c = Cycle()\n+ for cycle in cycles:\n+ c = c(*cycle)\n+ return _af_new(c.list(size))\n if not ok:\n raise ValueError(\"Permutation argument must be a list of ints, \"\n \"a list of lists, Permutation or Cycle.\")\n", "model_lint_repair_patch": "diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py\nindex 136ed5a478..862786df23 100644\n--- a/sympy/combinatorics/permutations.py\n+++ b/sympy/combinatorics/permutations.py\n@@ -475,6 +475,8 @@ class Permutation(Basic):\n \n >>> from sympy.combinatorics import Permutation\n >>> Permutation.print_cyclic = False\n+ >>> Permutation([1, 2], [2, 3])\n+ Permutation([0, 2, 3, 1])\n \n Permutations Notation\n =====================\n@@ -873,7 +875,12 @@ def __new__(cls, *args, **kwargs):\n if has_variety(is_sequence(ai) for ai in a):\n ok = False\n else:\n- ok = False\n+ # Process non-disjoint cycles\n+ cycles = args\n+ c = Cycle()\n+ for cycle in cycles:\n+ c = c(*cycle)\n+ return _af_new(c.list(size))\n if not ok:\n raise ValueError(\"Permutation argument must be a list of ints, \"\n \"a list of lists, Permutation or Cycle.\")\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-13768", "base_commit": "965d2d95c630939b53eb60d9c169f5dfc77ee0c6", "patch": "diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py\n--- a/django/dispatch/dispatcher.py\n+++ b/django/dispatch/dispatcher.py\n@@ -1,3 +1,4 @@\n+import logging\n import threading\n import warnings\n import weakref\n@@ -5,6 +6,8 @@\n from django.utils.deprecation import RemovedInDjango40Warning\n from django.utils.inspect import func_accepts_kwargs\n \n+logger = logging.getLogger('django.dispatch')\n+\n \n def _make_id(target):\n if hasattr(target, '__func__'):\n@@ -208,6 +211,12 @@ def send_robust(self, sender, **named):\n try:\n response = receiver(signal=self, sender=sender, **named)\n except Exception as err:\n+ logger.error(\n+ 'Error calling %s in Signal.send_robust() (%s)',\n+ receiver.__qualname__,\n+ err,\n+ exc_info=err,\n+ )\n responses.append((receiver, err))\n else:\n responses.append((receiver, response))\n", "test_patch": "diff --git a/tests/dispatch/tests.py b/tests/dispatch/tests.py\n--- a/tests/dispatch/tests.py\n+++ b/tests/dispatch/tests.py\n@@ -165,13 +165,28 @@ def test_send_robust_fail(self):\n def fails(val, **kwargs):\n raise ValueError('this')\n a_signal.connect(fails)\n- result = a_signal.send_robust(sender=self, val=\"test\")\n- err = result[0][1]\n- self.assertIsInstance(err, ValueError)\n- self.assertEqual(err.args, ('this',))\n- self.assertTrue(hasattr(err, '__traceback__'))\n- self.assertIsInstance(err.__traceback__, TracebackType)\n- a_signal.disconnect(fails)\n+ try:\n+ with self.assertLogs('django.dispatch', 'ERROR') as cm:\n+ result = a_signal.send_robust(sender=self, val='test')\n+ err = result[0][1]\n+ self.assertIsInstance(err, ValueError)\n+ self.assertEqual(err.args, ('this',))\n+ self.assertIs(hasattr(err, '__traceback__'), True)\n+ self.assertIsInstance(err.__traceback__, TracebackType)\n+\n+ log_record = cm.records[0]\n+ self.assertEqual(\n+ log_record.getMessage(),\n+ 'Error calling '\n+ 'DispatcherTests.test_send_robust_fail..fails in '\n+ 'Signal.send_robust() (this)',\n+ )\n+ self.assertIsNotNone(log_record.exc_info)\n+ _, exc_value, _ = log_record.exc_info\n+ self.assertIsInstance(exc_value, ValueError)\n+ self.assertEqual(str(exc_value), 'this')\n+ finally:\n+ a_signal.disconnect(fails)\n self.assertTestIsClean(a_signal)\n \n def test_disconnection(self):\n", "problem_statement": "Log exceptions handled in Signal.send_robust()\nDescription\n\t\nAs pointed out by \u200bHaki Benita on Twitter, by default Signal.send_robust() doesn't have any log messages for exceptions raised in receivers. Since Django logs exceptions in other similar situations, such as missing template variables, I think it would be worth adding a logger.exception() call in the except clause of send_robust() . Users would then see such exceptions in their error handling tools, e.g. Sentry, and be able to figure out what action to take from there. Ultimately any *expected* exception should be caught with a try in the receiver function.\n", "hints_text": "I would like to work on this issue. PS. i am new to this django. so any advice would be appreciated", "created_at": "2020-12-12T07:34:48Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_send_robust_fail (dispatch.tests.DispatcherTests)\"]", "PASS_TO_PASS": "[\"test_receiver_signal_list (dispatch.tests.ReceiverTestCase)\", \"test_receiver_single_signal (dispatch.tests.ReceiverTestCase)\", \"test_cached_garbaged_collected (dispatch.tests.DispatcherTests)\", \"test_cannot_connect_no_kwargs (dispatch.tests.DispatcherTests)\", \"test_cannot_connect_non_callable (dispatch.tests.DispatcherTests)\", \"test_disconnection (dispatch.tests.DispatcherTests)\", \"test_garbage_collected (dispatch.tests.DispatcherTests)\", \"test_has_listeners (dispatch.tests.DispatcherTests)\", \"test_multiple_registration (dispatch.tests.DispatcherTests)\", \"test_send (dispatch.tests.DispatcherTests)\", \"test_send_connected_no_sender (dispatch.tests.DispatcherTests)\", \"test_send_different_no_sender (dispatch.tests.DispatcherTests)\", \"test_send_no_receivers (dispatch.tests.DispatcherTests)\", \"test_send_robust_ignored_sender (dispatch.tests.DispatcherTests)\", \"test_send_robust_no_receivers (dispatch.tests.DispatcherTests)\", \"test_send_robust_success (dispatch.tests.DispatcherTests)\", \"test_uid_registration (dispatch.tests.DispatcherTests)\", \"test_values_returned_by_disconnection (dispatch.tests.DispatcherTests)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["dispatch.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 dispatch.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/tests/dispatch/tests.py b/tests/dispatch/tests.py\nindex 9b5482ed58..817bb6e5a8 100644\n--- a/tests/dispatch/tests.py\n+++ b/tests/dispatch/tests.py\n@@ -1,6 +1,7 @@\n import gc\n import sys\n import weakref\n+import logging\n from types import TracebackType\n \n from django.dispatch import Signal, receiver\n@@ -174,6 +175,16 @@ class DispatcherTests(SimpleTestCase):\n a_signal.disconnect(fails)\n self.assertTestIsClean(a_signal)\n \n+ def test_send_robust_fail_logging(self):\n+ def fails(val, **kwargs):\n+ raise ValueError('this')\n+ a_signal.connect(fails)\n+ with self.assertLogs('django', level='ERROR') as cm:\n+ a_signal.send_robust(sender=self, val=\"test\")\n+ self.assertIn('ERROR:django.dispatch.dispatcher:Error in receiver', cm.output[0])\n+ a_signal.disconnect(fails)\n+ self.assertTestIsClean(a_signal)\n+\n def test_disconnection(self):\n receiver_1 = Callable()\n receiver_2 = Callable()\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["dispatch.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py\nindex b7d9d26389..1c8771f1fc 100644\n--- a/django/dispatch/dispatcher.py\n+++ b/django/dispatch/dispatcher.py\n@@ -1,6 +1,7 @@\n import threading\n import warnings\n import weakref\n+import logging\n \n from django.utils.deprecation import RemovedInDjango40Warning\n from django.utils.inspect import func_accepts_kwargs\n@@ -201,6 +202,9 @@ class Signal:\n if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:\n return []\n \n+ # Initialize logger\n+ logger = logging.getLogger(__name__)\n+\n # Call each receiver with whatever arguments it can accept.\n # Return a list of tuple pairs [(receiver, response), ... ].\n responses = []\n@@ -208,6 +212,8 @@ class Signal:\n try:\n response = receiver(signal=self, sender=sender, **named)\n except Exception as err:\n+ # Log the exception with stack trace\n+ logger.exception(f\"Error in receiver {receiver} for signal {self} from sender {sender}\")\n responses.append((receiver, err))\n else:\n responses.append((receiver, response))\n", "model_lint_repair_patch": "diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py\nindex b7d9d26389..1c8771f1fc 100644\n--- a/django/dispatch/dispatcher.py\n+++ b/django/dispatch/dispatcher.py\n@@ -1,6 +1,7 @@\n import threading\n import warnings\n import weakref\n+import logging\n \n from django.utils.deprecation import RemovedInDjango40Warning\n from django.utils.inspect import func_accepts_kwargs\n@@ -201,6 +202,9 @@ class Signal:\n if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:\n return []\n \n+ # Initialize logger\n+ logger = logging.getLogger(__name__)\n+\n # Call each receiver with whatever arguments it can accept.\n # Return a list of tuple pairs [(receiver, response), ... ].\n responses = []\n@@ -208,6 +212,8 @@ class Signal:\n try:\n response = receiver(signal=self, sender=sender, **named)\n except Exception as err:\n+ # Log the exception with stack trace\n+ logger.exception(f\"Error in receiver {receiver} for signal {self} from sender {sender}\")\n responses.append((receiver, err))\n else:\n responses.append((receiver, response))\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["dispatch.tests"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-15609", "base_commit": "15f56f3b0006d2ed2c29bde3c43e91618012c849", "patch": "diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py\n--- a/sympy/printing/latex.py\n+++ b/sympy/printing/latex.py\n@@ -1438,7 +1438,10 @@ def _print_MatrixBase(self, expr):\n \n def _print_MatrixElement(self, expr):\n return self.parenthesize(expr.parent, PRECEDENCE[\"Atom\"], strict=True) \\\n- + '_{%s, %s}' % (expr.i, expr.j)\n+ + '_{%s, %s}' % (\n+ self._print(expr.i),\n+ self._print(expr.j)\n+ )\n \n def _print_MatrixSlice(self, expr):\n def latexslice(x):\n", "test_patch": "diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py\n--- a/sympy/printing/tests/test_latex.py\n+++ b/sympy/printing/tests/test_latex.py\n@@ -1738,6 +1738,11 @@ def test_MatrixElement_printing():\n F = C[0, 0].subs(C, A - B)\n assert latex(F) == r\"\\left(A - B\\right)_{0, 0}\"\n \n+ i, j, k = symbols(\"i j k\")\n+ M = MatrixSymbol(\"M\", k, k)\n+ N = MatrixSymbol(\"N\", k, k)\n+ assert latex((M*N)[i, j]) == r'\\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}'\n+\n \n def test_MatrixSymbol_printing():\n # test cases for issue #14237\n", "problem_statement": "Indexed matrix-expression LaTeX printer is not compilable\n```python\r\ni, j, k = symbols(\"i j k\")\r\nM = MatrixSymbol(\"M\", k, k)\r\nN = MatrixSymbol(\"N\", k, k)\r\nlatex((M*N)[i, j])\r\n```\r\n\r\nThe LaTeX string produced by the last command is:\r\n```\r\n\\sum_{i_{1}=0}^{k - 1} M_{i, _i_1} N_{_i_1, j}\r\n```\r\nLaTeX complains about a double subscript `_`. This expression won't render in MathJax either.\n", "hints_text": "Related to https://github.com/sympy/sympy/issues/15059\nIt's pretty simple to solve, `_print_MatrixElement` of `LatexPrinter` is not calling `self._print` on the indices.\nI'd like to work on this. When adding a test, should I expand `test_MatrixElement_printing` or add `test_issue_15595` just for this issue? Or both?\nThe correct one should be `\\sum_{i_{1}=0}^{k - 1} M_{i, i_1} N_{i_1, j}`.\r\nIs that right?\nTests can be put everywhere. I'd prefer to have them next to the other ones.", "created_at": "2018-12-09T12:27:08Z", "version": "1.4", "FAIL_TO_PASS": "[\"test_MatrixElement_printing\"]", "PASS_TO_PASS": "[\"test_printmethod\", \"test_latex_basic\", \"test_latex_builtins\", \"test_latex_SingularityFunction\", \"test_latex_cycle\", \"test_latex_permutation\", \"test_latex_Float\", \"test_latex_vector_expressions\", \"test_latex_symbols\", \"test_latex_functions\", \"test_function_subclass_different_name\", \"test_hyper_printing\", \"test_latex_bessel\", \"test_latex_fresnel\", \"test_latex_brackets\", \"test_latex_indexed\", \"test_latex_derivatives\", \"test_latex_subs\", \"test_latex_integrals\", \"test_latex_sets\", \"test_latex_SetExpr\", \"test_latex_Range\", \"test_latex_sequences\", \"test_latex_FourierSeries\", \"test_latex_FormalPowerSeries\", \"test_latex_intervals\", \"test_latex_AccumuBounds\", \"test_latex_emptyset\", \"test_latex_commutator\", \"test_latex_union\", \"test_latex_symmetric_difference\", \"test_latex_Complement\", \"test_latex_Complexes\", \"test_latex_productset\", \"test_latex_Naturals\", \"test_latex_Naturals0\", \"test_latex_Integers\", \"test_latex_ImageSet\", \"test_latex_ConditionSet\", \"test_latex_ComplexRegion\", \"test_latex_Contains\", \"test_latex_sum\", \"test_latex_product\", \"test_latex_limits\", \"test_latex_log\", \"test_issue_3568\", \"test_latex\", \"test_latex_dict\", \"test_latex_list\", \"test_latex_rational\", \"test_latex_inverse\", \"test_latex_DiracDelta\", \"test_latex_Heaviside\", \"test_latex_KroneckerDelta\", \"test_latex_LeviCivita\", \"test_mode\", \"test_latex_Piecewise\", \"test_latex_Matrix\", \"test_latex_matrix_with_functions\", \"test_latex_NDimArray\", \"test_latex_mul_symbol\", \"test_latex_issue_4381\", \"test_latex_issue_4576\", \"test_latex_pow_fraction\", \"test_noncommutative\", \"test_latex_order\", \"test_latex_Lambda\", \"test_latex_PolyElement\", \"test_latex_FracElement\", \"test_latex_Poly\", \"test_latex_Poly_order\", \"test_latex_ComplexRootOf\", \"test_latex_RootSum\", \"test_settings\", \"test_latex_numbers\", \"test_latex_euler\", \"test_lamda\", \"test_custom_symbol_names\", \"test_matAdd\", \"test_matMul\", \"test_latex_MatrixSlice\", \"test_latex_RandomDomain\", \"test_PrettyPoly\", \"test_integral_transforms\", \"test_PolynomialRingBase\", \"test_categories\", \"test_Modules\", \"test_QuotientRing\", \"test_Tr\", \"test_Adjoint\", \"test_Hadamard\", \"test_ZeroMatrix\", \"test_boolean_args_order\", \"test_imaginary\", \"test_builtins_without_args\", \"test_latex_greek_functions\", \"test_translate\", \"test_other_symbols\", \"test_modifiers\", \"test_greek_symbols\", \"test_builtin_no_args\", \"test_issue_6853\", \"test_Mul\", \"test_Pow\", \"test_issue_7180\", \"test_issue_8409\", \"test_issue_7117\", \"test_issue_15439\", \"test_issue_2934\", \"test_issue_10489\", \"test_issue_12886\", \"test_issue_13651\", \"test_latex_UnevaluatedExpr\", \"test_MatrixSymbol_printing\", \"test_Quaternion_latex_printing\", \"test_TensorProduct_printing\", \"test_WedgeProduct_printing\", \"test_issue_14041\", \"test_issue_9216\", \"test_latex_printer_tensor\", \"test_trace\"]", "environment_setup_commit": "73b3f90093754c5ed1561bd885242330e3583004", "test_directives": ["sympy/printing/tests/test_latex.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/printing/tests/test_latex.py", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/printing/tests/test_ccode.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/sympy/codegen/array_utils.py b/sympy/codegen/array_utils.py\nindex bb03e20e86..2120e14f2a 100644\n--- a/sympy/codegen/array_utils.py\n+++ b/sympy/codegen/array_utils.py\n@@ -692,8 +692,7 @@ def _codegen_array_parse(expr):\n indices_ret.sort(key=lambda x: free_indices.index(x))\n return CodegenArrayContraction(\n subexpr,\n- *contraction_indices,\n- free_indices=free_indices\n+ *contraction_indices\n ), tuple(indices_ret)\n if isinstance(expr, Mul):\n args, indices = zip(*[_codegen_array_parse(arg) for arg in expr.args])\n", "model_lint_repair_patch": "diff --git a/sympy/codegen/array_utils.py b/sympy/codegen/array_utils.py\nindex bb03e20e86..2120e14f2a 100644\n--- a/sympy/codegen/array_utils.py\n+++ b/sympy/codegen/array_utils.py\n@@ -692,8 +692,7 @@ def _codegen_array_parse(expr):\n indices_ret.sort(key=lambda x: free_indices.index(x))\n return CodegenArrayContraction(\n subexpr,\n- *contraction_indices,\n- free_indices=free_indices\n+ *contraction_indices\n ), tuple(indices_ret)\n if isinstance(expr, Mul):\n args, indices = zip(*[_codegen_array_parse(arg) for arg in expr.args])\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/printing/tests/test_ccode.py"]} +{"repo": "django/django", "instance_id": "django__django-12700", "base_commit": "d51c50d836c5cf8db5566da17963f871be554615", "patch": "diff --git a/django/views/debug.py b/django/views/debug.py\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -90,6 +90,10 @@ def cleanse_setting(self, key, value):\n cleansed = self.cleansed_substitute\n elif isinstance(value, dict):\n cleansed = {k: self.cleanse_setting(k, v) for k, v in value.items()}\n+ elif isinstance(value, list):\n+ cleansed = [self.cleanse_setting('', v) for v in value]\n+ elif isinstance(value, tuple):\n+ cleansed = tuple([self.cleanse_setting('', v) for v in value])\n else:\n cleansed = value\n except TypeError:\n", "test_patch": "diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py\n--- a/tests/view_tests/tests/test_debug.py\n+++ b/tests/view_tests/tests/test_debug.py\n@@ -1249,6 +1249,41 @@ def test_cleanse_setting_recurses_in_dictionary(self):\n {'login': 'cooper', 'password': reporter_filter.cleansed_substitute},\n )\n \n+ def test_cleanse_setting_recurses_in_list_tuples(self):\n+ reporter_filter = SafeExceptionReporterFilter()\n+ initial = [\n+ {\n+ 'login': 'cooper',\n+ 'password': 'secret',\n+ 'apps': (\n+ {'name': 'app1', 'api_key': 'a06b-c462cffae87a'},\n+ {'name': 'app2', 'api_key': 'a9f4-f152e97ad808'},\n+ ),\n+ 'tokens': ['98b37c57-ec62-4e39', '8690ef7d-8004-4916'],\n+ },\n+ {'SECRET_KEY': 'c4d77c62-6196-4f17-a06b-c462cffae87a'},\n+ ]\n+ cleansed = [\n+ {\n+ 'login': 'cooper',\n+ 'password': reporter_filter.cleansed_substitute,\n+ 'apps': (\n+ {'name': 'app1', 'api_key': reporter_filter.cleansed_substitute},\n+ {'name': 'app2', 'api_key': reporter_filter.cleansed_substitute},\n+ ),\n+ 'tokens': reporter_filter.cleansed_substitute,\n+ },\n+ {'SECRET_KEY': reporter_filter.cleansed_substitute},\n+ ]\n+ self.assertEqual(\n+ reporter_filter.cleanse_setting('SETTING_NAME', initial),\n+ cleansed,\n+ )\n+ self.assertEqual(\n+ reporter_filter.cleanse_setting('SETTING_NAME', tuple(initial)),\n+ tuple(cleansed),\n+ )\n+\n def test_request_meta_filtering(self):\n request = self.rf.get('/', HTTP_SECRET_HEADER='super_secret')\n reporter_filter = SafeExceptionReporterFilter()\n", "problem_statement": "Settings are cleaned insufficiently.\nDescription\n\t\nPosting publicly after checking with the rest of the security team.\nI just ran into a case where django.views.debug.SafeExceptionReporterFilter.get_safe_settings() would return several un-cleansed values. Looking at cleanse_setting() I realized that we \u200bonly take care of `dict`s but don't take other types of iterables into account but \u200breturn them as-is.\nExample:\nIn my settings.py I have this:\nMY_SETTING = {\n\t\"foo\": \"value\",\n\t\"secret\": \"value\",\n\t\"token\": \"value\",\n\t\"something\": [\n\t\t{\"foo\": \"value\"},\n\t\t{\"secret\": \"value\"},\n\t\t{\"token\": \"value\"},\n\t],\n\t\"else\": [\n\t\t[\n\t\t\t{\"foo\": \"value\"},\n\t\t\t{\"secret\": \"value\"},\n\t\t\t{\"token\": \"value\"},\n\t\t],\n\t\t[\n\t\t\t{\"foo\": \"value\"},\n\t\t\t{\"secret\": \"value\"},\n\t\t\t{\"token\": \"value\"},\n\t\t],\n\t]\n}\nOn Django 3.0 and below:\n>>> import pprint\n>>> from django.views.debug import get_safe_settings\n>>> pprint.pprint(get_safe_settings()[\"MY_SETTING\"])\n{'else': [[{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],\n\t\t [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}]],\n 'foo': 'value',\n 'secret': '********************',\n 'something': [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],\n 'token': '********************'}\nOn Django 3.1 and up:\n>>> from django.views.debug import SafeExceptionReporterFilter\n>>> import pprint\n>>> pprint.pprint(SafeExceptionReporterFilter().get_safe_settings()[\"MY_SETTING\"])\n{'else': [[{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],\n\t\t [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}]],\n 'foo': 'value',\n 'secret': '********************',\n 'something': [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],\n 'token': '********************'}\n", "hints_text": "Do I need to change both versions? Or just create a single implementation for current master branch?", "created_at": "2020-04-11T01:58:27Z", "version": "3.1", "FAIL_TO_PASS": "[\"test_cleanse_setting_recurses_in_list_tuples (view_tests.tests.test_debug.ExceptionReporterFilterTests)\"]", "PASS_TO_PASS": "[\"test_repr (view_tests.tests.test_debug.CallableSettingWrapperTests)\", \"test_sensitive_post_parameters_not_called (view_tests.tests.test_debug.DecoratorsTests)\", \"test_sensitive_variables_not_called (view_tests.tests.test_debug.DecoratorsTests)\", \"test_cleansed_substitute_override (view_tests.tests.test_debug.CustomExceptionReporterFilterTests)\", \"test_hidden_settings_override (view_tests.tests.test_debug.CustomExceptionReporterFilterTests)\", \"test_setting_allows_custom_subclass (view_tests.tests.test_debug.CustomExceptionReporterFilterTests)\", \"test_handle_db_exception (view_tests.tests.test_debug.DebugViewQueriesAllowedTests)\", \"test_400 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"test_403 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"test_404 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"test_template_not_found_error (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"An exception report can be generated even for a disallowed host.\", \"test_message_only (view_tests.tests.test_debug.PlainTextReportTests)\", \"An exception report can be generated for just a request\", \"An exception report can be generated without request\", \"A simple exception report can be generated\", \"A message can be provided in addition to a request\", \"test_request_with_items_key (view_tests.tests.test_debug.PlainTextReportTests)\", \"test_template_exception (view_tests.tests.test_debug.PlainTextReportTests)\", \"test_custom_exception_reporter_filter (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)\", \"test_non_html_response_encoding (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)\", \"test_non_sensitive_request (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)\", \"test_paranoid_request (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)\", \"test_sensitive_request (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)\", \"test_400 (view_tests.tests.test_debug.DebugViewTests)\", \"test_403 (view_tests.tests.test_debug.DebugViewTests)\", \"test_403_template (view_tests.tests.test_debug.DebugViewTests)\", \"test_404 (view_tests.tests.test_debug.DebugViewTests)\", \"test_404_empty_path_not_in_urls (view_tests.tests.test_debug.DebugViewTests)\", \"test_404_not_in_urls (view_tests.tests.test_debug.DebugViewTests)\", \"test_classbased_technical_404 (view_tests.tests.test_debug.DebugViewTests)\", \"test_default_urlconf_template (view_tests.tests.test_debug.DebugViewTests)\", \"test_exception_reporter_from_request (view_tests.tests.test_debug.DebugViewTests)\", \"test_exception_reporter_from_settings (view_tests.tests.test_debug.DebugViewTests)\", \"test_files (view_tests.tests.test_debug.DebugViewTests)\", \"test_no_template_source_loaders (view_tests.tests.test_debug.DebugViewTests)\", \"test_non_l10ned_numeric_ids (view_tests.tests.test_debug.DebugViewTests)\", \"test_regression_21530 (view_tests.tests.test_debug.DebugViewTests)\", \"test_technical_404 (view_tests.tests.test_debug.DebugViewTests)\", \"test_technical_404_converter_raise_404 (view_tests.tests.test_debug.DebugViewTests)\", \"test_template_encoding (view_tests.tests.test_debug.DebugViewTests)\", \"test_template_exceptions (view_tests.tests.test_debug.DebugViewTests)\", \"Tests for not existing file\", \"test_encoding_error (view_tests.tests.test_debug.ExceptionReporterTests)\", \"The ExceptionReporter supports Unix, Windows and Macintosh EOL markers\", \"test_exception_fetching_user (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_ignore_traceback_evaluation_exceptions (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Safe strings in local variables are escaped.\", \"test_message_only (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Non-UTF-8 exceptions/values should not make the output generation choke.\", \"test_reporting_frames_for_cyclic_reference (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_reporting_frames_source_not_match (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_reporting_frames_without_source (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_reporting_of_nested_exceptions (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_request_with_items_key (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_template_encoding (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Large values should not create a large HTML.\", \"test_unfrozen_importlib (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Unprintable values should not make the output generation choke.\", \"test_callable_settings (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_callable_settings_forbidding_to_set_attributes (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_cleanse_setting_basic (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_cleanse_setting_ignore_case (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_cleanse_setting_recurses_in_dictionary (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_custom_exception_reporter_filter (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_dict_setting_with_non_str_key (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_exception_report_uses_meta_filtering (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_multivalue_dict_key_error (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_non_sensitive_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_paranoid_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_request_meta_filtering (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_function_arguments (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_function_keyword_arguments (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_method (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_settings (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_settings_with_sensitive_keys (view_tests.tests.test_debug.ExceptionReporterFilterTests)\"]", "environment_setup_commit": "0668164b4ac93a5be79f5b87fae83c657124d9ab", "test_directives": ["view_tests.tests.test_debug"], "test_cmd": "./tests/runtests.py --verbosity 2 view_tests.tests.test_debug", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/settings_tests/tests.py b/tests/settings_tests/tests.py\nindex 55ca0de524..aa7f77bd2b 100644\n--- a/tests/settings_tests/tests.py\n+++ b/tests/settings_tests/tests.py\n@@ -616,3 +616,38 @@ class MediaURLStaticURLPrefixTest(SimpleTestCase):\n self.assertEqual(getattr(settings, setting), expected_path)\n finally:\n clear_script_prefix()\n+\n+from django.views.debug import SafeExceptionReporterFilter\n+\n+class SafeExceptionReporterFilterTests(SimpleTestCase):\n+ def test_cleanse_setting(self):\n+ filter = SafeExceptionReporterFilter()\n+ settings_dict = {\n+ \"foo\": \"value\",\n+ \"secret\": \"value\",\n+ \"token\": \"value\",\n+ \"something\": [\n+ {\"foo\": \"value\"},\n+ {\"secret\": \"value\"},\n+ {\"token\": \"value\"},\n+ ],\n+ \"else\": [\n+ [\n+ {\"foo\": \"value\"},\n+ {\"secret\": \"value\"},\n+ {\"token\": \"value\"},\n+ ],\n+ [\n+ {\"foo\": \"value\"},\n+ {\"secret\": \"value\"},\n+ {\"token\": \"value\"},\n+ ],\n+ ]\n+ }\n+ cleansed_settings = filter.cleanse_setting(\"MY_SETTING\", settings_dict)\n+ self.assertEqual(cleansed_settings[\"secret\"], \"********************\")\n+ self.assertEqual(cleansed_settings[\"token\"], \"********************\")\n+ self.assertEqual(cleansed_settings[\"something\"][1][\"secret\"], \"********************\")\n+ self.assertEqual(cleansed_settings[\"something\"][1][\"token\"], \"********************\")\n+ self.assertEqual(cleansed_settings[\"else\"][0][1][\"secret\"], \"********************\")\n+ self.assertEqual(cleansed_settings[\"else\"][0][1][\"token\"], \"********************\")\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["settings_tests.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/views/debug.py b/django/views/debug.py\nindex e6b7d4d821..c5bbcf9d7e 100644\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -83,13 +83,16 @@ class SafeExceptionReporterFilter:\n def cleanse_setting(self, key, value):\n \"\"\"\n Cleanse an individual setting key/value of sensitive content. If the\n- value is a dictionary, recursively cleanse the keys in that dictionary.\n+ value is a dictionary, list, tuple, or other iterable, recursively cleanse\n+ the elements within that collection.\n \"\"\"\n try:\n if self.hidden_settings.search(key):\n cleansed = self.cleansed_substitute\n elif isinstance(value, dict):\n cleansed = {k: self.cleanse_setting(k, v) for k, v in value.items()}\n+ elif isinstance(value, (list, tuple)):\n+ cleansed = type(value)(self.cleanse_setting(key, v) for v in value)\n else:\n cleansed = value\n except TypeError:\n", "model_lint_repair_patch": "diff --git a/django/views/debug.py b/django/views/debug.py\nindex e6b7d4d821..c5bbcf9d7e 100644\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -83,13 +83,16 @@ class SafeExceptionReporterFilter:\n def cleanse_setting(self, key, value):\n \"\"\"\n Cleanse an individual setting key/value of sensitive content. If the\n- value is a dictionary, recursively cleanse the keys in that dictionary.\n+ value is a dictionary, list, tuple, or other iterable, recursively cleanse\n+ the elements within that collection.\n \"\"\"\n try:\n if self.hidden_settings.search(key):\n cleansed = self.cleansed_substitute\n elif isinstance(value, dict):\n cleansed = {k: self.cleanse_setting(k, v) for k, v in value.items()}\n+ elif isinstance(value, (list, tuple)):\n+ cleansed = type(value)(self.cleanse_setting(key, v) for v in value)\n else:\n cleansed = value\n except TypeError:\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-14787", "base_commit": "004b4620f6f4ad87261e149898940f2dcd5757ef", "patch": "diff --git a/django/utils/decorators.py b/django/utils/decorators.py\n--- a/django/utils/decorators.py\n+++ b/django/utils/decorators.py\n@@ -37,7 +37,7 @@ def _wrapper(self, *args, **kwargs):\n # 'self' argument, but it's a closure over self so it can call\n # 'func'. Also, wrap method.__get__() in a function because new\n # attributes can't be set on bound method objects, only on functions.\n- bound_method = partial(method.__get__(self, type(self)))\n+ bound_method = wraps(method)(partial(method.__get__(self, type(self))))\n for dec in decorators:\n bound_method = dec(bound_method)\n return bound_method(*args, **kwargs)\n", "test_patch": "diff --git a/tests/decorators/tests.py b/tests/decorators/tests.py\n--- a/tests/decorators/tests.py\n+++ b/tests/decorators/tests.py\n@@ -425,6 +425,29 @@ class Test:\n def __module__(cls):\n return \"tests\"\n \n+ def test_wrapper_assignments(self):\n+ \"\"\"@method_decorator preserves wrapper assignments.\"\"\"\n+ func_name = None\n+ func_module = None\n+\n+ def decorator(func):\n+ @wraps(func)\n+ def inner(*args, **kwargs):\n+ nonlocal func_name, func_module\n+ func_name = getattr(func, '__name__', None)\n+ func_module = getattr(func, '__module__', None)\n+ return func(*args, **kwargs)\n+ return inner\n+\n+ class Test:\n+ @method_decorator(decorator)\n+ def method(self):\n+ return 'tests'\n+\n+ Test().method()\n+ self.assertEqual(func_name, 'method')\n+ self.assertIsNotNone(func_module)\n+\n \n class XFrameOptionsDecoratorsTests(TestCase):\n \"\"\"\n", "problem_statement": "method_decorator() should preserve wrapper assignments\nDescription\n\t\nthe function that is passed to the decorator is a partial object and does not have any of the attributes expected from a function i.e. __name__, __module__ etc...\nconsider the following case\ndef logger(func):\n\t@wraps(func)\n\tdef inner(*args, **kwargs):\n\t\ttry:\n\t\t\tresult = func(*args, **kwargs)\n\t\texcept Exception as e:\n\t\t\tresult = str(e)\n\t\tfinally:\n\t\t\tlogger.debug(f\"{func.__name__} called with args: {args} and kwargs: {kwargs} resulting: {result}\")\n\treturn inner\nclass Test:\n\t@method_decorator(logger)\n\tdef hello_world(self):\n\t\treturn \"hello\"\nTest().test_method()\nThis results in the following exception\nAttributeError: 'functools.partial' object has no attribute '__name__'\n", "hints_text": "", "created_at": "2021-08-23T12:59:59Z", "version": "4.1", "FAIL_TO_PASS": "[\"@method_decorator preserves wrapper assignments.\"]", "PASS_TO_PASS": "[\"test_cache_control_decorator_http_request (decorators.tests.CacheControlDecoratorTest)\", \"Ensures @xframe_options_deny properly sets the X-Frame-Options header.\", \"Ensures @xframe_options_exempt properly instructs the\", \"Ensures @xframe_options_sameorigin properly sets the X-Frame-Options\", \"Built-in decorators set certain attributes of the wrapped function.\", \"test_cache_page (decorators.tests.DecoratorsTest)\", \"Test for the require_safe decorator.\", \"The user_passes_test decorator can be applied multiple times (#9474).\", \"test_never_cache_decorator (decorators.tests.NeverCacheDecoratorTest)\", \"test_never_cache_decorator_http_request (decorators.tests.NeverCacheDecoratorTest)\", \"test_argumented (decorators.tests.MethodDecoratorTests)\", \"test_bad_iterable (decorators.tests.MethodDecoratorTests)\", \"@method_decorator can be used to decorate a class and its methods.\", \"test_descriptors (decorators.tests.MethodDecoratorTests)\", \"@method_decorator on a nonexistent method raises an error.\", \"@method_decorator on a non-callable attribute raises an error.\", \"A decorator that sets a new attribute on the method.\", \"test_preserve_attributes (decorators.tests.MethodDecoratorTests)\", \"test_preserve_signature (decorators.tests.MethodDecoratorTests)\", \"@method_decorator can accept a tuple of decorators.\"]", "environment_setup_commit": "647480166bfe7532e8c471fef0146e3a17e6c0c9", "test_directives": ["decorators.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 decorators.tests", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["decorators.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/utils/decorators.py b/django/utils/decorators.py\nindex 5c9a5d01c7..57ace1140d 100644\n--- a/django/utils/decorators.py\n+++ b/django/utils/decorators.py\n@@ -73,6 +73,7 @@ def method_decorator(decorator, name=''):\n \"%s (%s).\" % (name, obj, method)\n )\n _wrapper = _multi_decorate(decorator, method)\n+ update_wrapper(_wrapper, method)\n setattr(obj, name, _wrapper)\n return obj\n \n", "model_lint_repair_patch": "diff --git a/django/utils/decorators.py b/django/utils/decorators.py\nindex 5c9a5d01c7..57ace1140d 100644\n--- a/django/utils/decorators.py\n+++ b/django/utils/decorators.py\n@@ -73,6 +73,7 @@ def method_decorator(decorator, name=''):\n \"%s (%s).\" % (name, obj, method)\n )\n _wrapper = _multi_decorate(decorator, method)\n+ update_wrapper(_wrapper, method)\n setattr(obj, name, _wrapper)\n return obj\n \n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["decorators.tests"]} +{"repo": "django/django", "instance_id": "django__django-13590", "base_commit": "755dbf39fcdc491fe9b588358303e259c7750be4", "patch": "diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py\n--- a/django/db/models/sql/query.py\n+++ b/django/db/models/sql/query.py\n@@ -1077,10 +1077,14 @@ def resolve_lookup_value(self, value, can_reuse, allow_joins):\n elif isinstance(value, (list, tuple)):\n # The items of the iterable may be expressions and therefore need\n # to be resolved independently.\n- return type(value)(\n+ values = (\n self.resolve_lookup_value(sub_value, can_reuse, allow_joins)\n for sub_value in value\n )\n+ type_ = type(value)\n+ if hasattr(type_, '_make'): # namedtuple\n+ return type_(*values)\n+ return type_(values)\n return value\n \n def solve_lookup_type(self, lookup):\n", "test_patch": "diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py\n--- a/tests/expressions/tests.py\n+++ b/tests/expressions/tests.py\n@@ -2,6 +2,7 @@\n import pickle\n import unittest\n import uuid\n+from collections import namedtuple\n from copy import deepcopy\n from decimal import Decimal\n from unittest import mock\n@@ -813,7 +814,7 @@ def setUpTestData(cls):\n Company.objects.create(name='5040 Ltd', num_employees=50, num_chairs=40, ceo=ceo)\n Company.objects.create(name='5050 Ltd', num_employees=50, num_chairs=50, ceo=ceo)\n Company.objects.create(name='5060 Ltd', num_employees=50, num_chairs=60, ceo=ceo)\n- Company.objects.create(name='99300 Ltd', num_employees=99, num_chairs=300, ceo=ceo)\n+ cls.c5 = Company.objects.create(name='99300 Ltd', num_employees=99, num_chairs=300, ceo=ceo)\n \n def test_in_lookup_allows_F_expressions_and_expressions_for_integers(self):\n # __in lookups can use F() expressions for integers.\n@@ -884,6 +885,13 @@ def test_range_lookup_allows_F_expressions_and_expressions_for_integers(self):\n ordered=False\n )\n \n+ def test_range_lookup_namedtuple(self):\n+ EmployeeRange = namedtuple('EmployeeRange', ['minimum', 'maximum'])\n+ qs = Company.objects.filter(\n+ num_employees__range=EmployeeRange(minimum=51, maximum=100),\n+ )\n+ self.assertSequenceEqual(qs, [self.c5])\n+\n @unittest.skipUnless(connection.vendor == 'sqlite',\n \"This defensive test only works on databases that don't validate parameter types\")\n def test_complex_expressions_do_not_introduce_sql_injection_via_untrusted_string_inclusion(self):\n", "problem_statement": "Upgrading 2.2>3.0 causes named tuples used as arguments to __range to error.\nDescription\n\t\nI noticed this while upgrading a project from 2.2 to 3.0.\nThis project passes named 2-tuples as arguments to range queryset filters. This works fine on 2.2. On 3.0 it causes the following error: TypeError: __new__() missing 1 required positional argument: 'far'.\nThis happens because django.db.models.sql.query.Query.resolve_lookup_value goes into the tuple elements to resolve lookups and then attempts to reconstitute the tuple with the resolved elements.\nWhen it attempts to construct the new tuple it preserves the type (the named tuple) but it passes a iterator to it's constructor.\nNamedTuples don't have the code path for copying an iterator, and so it errors on insufficient arguments.\nThe fix is to * expand the contents of the iterator into the constructor.\n", "hints_text": "", "created_at": "2020-10-23T09:34:55Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_range_lookup_namedtuple (expressions.tests.IterableLookupInnerExpressionsTests)\"]", "PASS_TO_PASS": "[\"test_empty_group_by (expressions.tests.ExpressionWrapperTests)\", \"test_non_empty_group_by (expressions.tests.ExpressionWrapperTests)\", \"test_deconstruct (expressions.tests.FTests)\", \"test_deepcopy (expressions.tests.FTests)\", \"test_equal (expressions.tests.FTests)\", \"test_hash (expressions.tests.FTests)\", \"test_not_equal_Value (expressions.tests.FTests)\", \"test_optimizations (expressions.tests.ExistsTests)\", \"test_and (expressions.tests.CombinableTests)\", \"test_negation (expressions.tests.CombinableTests)\", \"test_or (expressions.tests.CombinableTests)\", \"test_reversed_and (expressions.tests.CombinableTests)\", \"test_reversed_or (expressions.tests.CombinableTests)\", \"test_aggregates (expressions.tests.ReprTests)\", \"test_distinct_aggregates (expressions.tests.ReprTests)\", \"test_expressions (expressions.tests.ReprTests)\", \"test_filtered_aggregates (expressions.tests.ReprTests)\", \"test_functions (expressions.tests.ReprTests)\", \"test_resolve_output_field (expressions.tests.CombinedExpressionTests)\", \"test_month_aggregation (expressions.tests.FieldTransformTests)\", \"test_multiple_transforms_in_values (expressions.tests.FieldTransformTests)\", \"test_transform_in_values (expressions.tests.FieldTransformTests)\", \"test_equal (expressions.tests.SimpleExpressionTests)\", \"test_hash (expressions.tests.SimpleExpressionTests)\", \"test_F_reuse (expressions.tests.ExpressionsTests)\", \"test_insensitive_patterns_escape (expressions.tests.ExpressionsTests)\", \"test_patterns_escape (expressions.tests.ExpressionsTests)\", \"test_complex_expressions (expressions.tests.ExpressionsNumericTests)\", \"test_fill_with_value_from_same_object (expressions.tests.ExpressionsNumericTests)\", \"test_filter_not_equals_other_field (expressions.tests.ExpressionsNumericTests)\", \"test_increment_value (expressions.tests.ExpressionsNumericTests)\", \"test_compile_unresolved (expressions.tests.ValueTests)\", \"test_deconstruct (expressions.tests.ValueTests)\", \"test_deconstruct_output_field (expressions.tests.ValueTests)\", \"test_equal (expressions.tests.ValueTests)\", \"test_equal_output_field (expressions.tests.ValueTests)\", \"test_hash (expressions.tests.ValueTests)\", \"test_raise_empty_expressionlist (expressions.tests.ValueTests)\", \"test_resolve_output_field (expressions.tests.ValueTests)\", \"test_resolve_output_field_failure (expressions.tests.ValueTests)\", \"test_update_TimeField_using_Value (expressions.tests.ValueTests)\", \"test_update_UUIDField_using_Value (expressions.tests.ValueTests)\", \"test_complex_expressions_do_not_introduce_sql_injection_via_untrusted_string_inclusion (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_expressions_in_lookups_join_choice (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_in_lookup_allows_F_expressions_and_expressions_for_datetimes (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_in_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_range_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)\", \"test_lefthand_addition (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_and (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_left_shift_operator (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_or (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_right_shift_operator (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_xor (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_bitwise_xor_null (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_division (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_modulo (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_multiplication (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_power (expressions.tests.ExpressionOperatorTests)\", \"test_lefthand_subtraction (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_addition (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_division (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_modulo (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_multiplication (expressions.tests.ExpressionOperatorTests)\", \"test_right_hand_subtraction (expressions.tests.ExpressionOperatorTests)\", \"test_righthand_power (expressions.tests.ExpressionOperatorTests)\", \"test_date_case_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_date_comparison (expressions.tests.FTimeDeltaTests)\", \"test_date_minus_duration (expressions.tests.FTimeDeltaTests)\", \"test_date_subquery_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_date_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_datetime_subquery_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_datetime_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_datetime_subtraction_microseconds (expressions.tests.FTimeDeltaTests)\", \"test_delta_add (expressions.tests.FTimeDeltaTests)\", \"test_delta_subtract (expressions.tests.FTimeDeltaTests)\", \"test_delta_update (expressions.tests.FTimeDeltaTests)\", \"test_duration_expressions (expressions.tests.FTimeDeltaTests)\", \"test_duration_with_datetime (expressions.tests.FTimeDeltaTests)\", \"test_duration_with_datetime_microseconds (expressions.tests.FTimeDeltaTests)\", \"test_durationfield_add (expressions.tests.FTimeDeltaTests)\", \"test_exclude (expressions.tests.FTimeDeltaTests)\", \"test_invalid_operator (expressions.tests.FTimeDeltaTests)\", \"test_mixed_comparisons2 (expressions.tests.FTimeDeltaTests)\", \"test_multiple_query_compilation (expressions.tests.FTimeDeltaTests)\", \"test_negative_timedelta_update (expressions.tests.FTimeDeltaTests)\", \"test_query_clone (expressions.tests.FTimeDeltaTests)\", \"test_time_subquery_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_time_subtraction (expressions.tests.FTimeDeltaTests)\", \"test_aggregate_subquery_annotation (expressions.tests.BasicExpressionsTests)\", \"test_annotate_values_aggregate (expressions.tests.BasicExpressionsTests)\", \"test_annotate_values_count (expressions.tests.BasicExpressionsTests)\", \"test_annotate_values_filter (expressions.tests.BasicExpressionsTests)\", \"test_annotation_with_nested_outerref (expressions.tests.BasicExpressionsTests)\", \"test_annotation_with_outerref (expressions.tests.BasicExpressionsTests)\", \"test_annotations_within_subquery (expressions.tests.BasicExpressionsTests)\", \"test_arithmetic (expressions.tests.BasicExpressionsTests)\", \"test_case_in_filter_if_boolean_output_field (expressions.tests.BasicExpressionsTests)\", \"test_exist_single_field_output_field (expressions.tests.BasicExpressionsTests)\", \"test_exists_in_filter (expressions.tests.BasicExpressionsTests)\", \"test_explicit_output_field (expressions.tests.BasicExpressionsTests)\", \"test_filter_inter_attribute (expressions.tests.BasicExpressionsTests)\", \"test_filter_with_join (expressions.tests.BasicExpressionsTests)\", \"test_filtering_on_annotate_that_uses_q (expressions.tests.BasicExpressionsTests)\", \"test_filtering_on_q_that_is_boolean (expressions.tests.BasicExpressionsTests)\", \"test_filtering_on_rawsql_that_is_boolean (expressions.tests.BasicExpressionsTests)\", \"test_in_subquery (expressions.tests.BasicExpressionsTests)\", \"test_incorrect_field_in_F_expression (expressions.tests.BasicExpressionsTests)\", \"test_incorrect_joined_field_in_F_expression (expressions.tests.BasicExpressionsTests)\", \"test_nested_outerref_with_function (expressions.tests.BasicExpressionsTests)\", \"test_nested_subquery (expressions.tests.BasicExpressionsTests)\", \"test_nested_subquery_join_outer_ref (expressions.tests.BasicExpressionsTests)\", \"test_nested_subquery_outer_ref_2 (expressions.tests.BasicExpressionsTests)\", \"test_nested_subquery_outer_ref_with_autofield (expressions.tests.BasicExpressionsTests)\", \"test_new_object_create (expressions.tests.BasicExpressionsTests)\", \"test_new_object_save (expressions.tests.BasicExpressionsTests)\", \"test_object_create_with_aggregate (expressions.tests.BasicExpressionsTests)\", \"test_object_update (expressions.tests.BasicExpressionsTests)\", \"test_object_update_fk (expressions.tests.BasicExpressionsTests)\", \"test_object_update_unsaved_objects (expressions.tests.BasicExpressionsTests)\", \"test_order_by_exists (expressions.tests.BasicExpressionsTests)\", \"test_order_by_multiline_sql (expressions.tests.BasicExpressionsTests)\", \"test_order_of_operations (expressions.tests.BasicExpressionsTests)\", \"test_outerref (expressions.tests.BasicExpressionsTests)\", \"test_outerref_mixed_case_table_name (expressions.tests.BasicExpressionsTests)\", \"test_outerref_with_operator (expressions.tests.BasicExpressionsTests)\", \"test_parenthesis_priority (expressions.tests.BasicExpressionsTests)\", \"test_pickle_expression (expressions.tests.BasicExpressionsTests)\", \"test_subquery (expressions.tests.BasicExpressionsTests)\", \"test_subquery_eq (expressions.tests.BasicExpressionsTests)\", \"test_subquery_filter_by_aggregate (expressions.tests.BasicExpressionsTests)\", \"test_subquery_filter_by_lazy (expressions.tests.BasicExpressionsTests)\", \"test_subquery_group_by_outerref_in_filter (expressions.tests.BasicExpressionsTests)\", \"test_subquery_in_filter (expressions.tests.BasicExpressionsTests)\", \"test_subquery_references_joined_table_twice (expressions.tests.BasicExpressionsTests)\", \"test_ticket_11722_iexact_lookup (expressions.tests.BasicExpressionsTests)\", \"test_ticket_16731_startswith_lookup (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_chained_filters (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_join_reuse (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_kwarg_ordering (expressions.tests.BasicExpressionsTests)\", \"test_ticket_18375_kwarg_ordering_2 (expressions.tests.BasicExpressionsTests)\", \"test_update (expressions.tests.BasicExpressionsTests)\", \"test_update_inherited_field_value (expressions.tests.BasicExpressionsTests)\", \"test_update_with_fk (expressions.tests.BasicExpressionsTests)\", \"test_update_with_none (expressions.tests.BasicExpressionsTests)\", \"test_uuid_pk_subquery (expressions.tests.BasicExpressionsTests)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["expressions.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 expressions.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/postgres_tests/test_ranges.py b/tests/postgres_tests/test_ranges.py\nindex 180678578e..2468eb0cbc 100644\n--- a/tests/postgres_tests/test_ranges.py\n+++ b/tests/postgres_tests/test_ranges.py\n@@ -336,6 +336,18 @@ class TestQueryingWithRanges(PostgreSQLTestCase):\n [objs[0]],\n )\n \n+ def test_named_tuple_range(self):\n+ from collections import namedtuple\n+ Range = namedtuple('Range', ['start', 'end'])\n+ objs = [\n+ RangeLookupsModel.objects.create(integer=5),\n+ RangeLookupsModel.objects.create(integer=10),\n+ ]\n+ self.assertSequenceEqual(\n+ RangeLookupsModel.objects.filter(integer__range=Range(5, 10)),\n+ [objs[0], objs[1]],\n+ )\n+\n def test_date_range_datetime_field(self):\n objs = [\n RangeLookupsModel.objects.create(timestamp='2015-01-01'),\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["queries.test_query"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/db/models/utils.py b/django/db/models/utils.py\nindex 764ca5888b..51ad26a8a5 100644\n--- a/django/db/models/utils.py\n+++ b/django/db/models/utils.py\n@@ -31,7 +31,11 @@ def resolve_callables(mapping):\n evaluated if they're callable.\n \"\"\"\n for k, v in mapping.items():\n- yield k, v() if callable(v) else v\n+ if callable(v):\n+ v = v()\n+ if isinstance(v, tuple) and hasattr(v, '_fields'): # Check if it's a named tuple\n+ v = type(v)(*v) # Unpack the iterator into the named tuple constructor\n+ yield k, v\n \n \n def unpickle_named_row(names, values):\n", "model_lint_repair_patch": "diff --git a/django/db/models/utils.py b/django/db/models/utils.py\nindex 764ca5888b..51ad26a8a5 100644\n--- a/django/db/models/utils.py\n+++ b/django/db/models/utils.py\n@@ -31,7 +31,11 @@ def resolve_callables(mapping):\n evaluated if they're callable.\n \"\"\"\n for k, v in mapping.items():\n- yield k, v() if callable(v) else v\n+ if callable(v):\n+ v = v()\n+ if isinstance(v, tuple) and hasattr(v, '_fields'): # Check if it's a named tuple\n+ v = type(v)(*v) # Unpack the iterator into the named tuple constructor\n+ yield k, v\n \n \n def unpickle_named_row(names, values):\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["queries.test_query"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-18532", "base_commit": "74227f900b05009d4eed62e34a166228788a32ca", "patch": "diff --git a/sympy/core/basic.py b/sympy/core/basic.py\n--- a/sympy/core/basic.py\n+++ b/sympy/core/basic.py\n@@ -503,12 +503,11 @@ def atoms(self, *types):\n if types:\n types = tuple(\n [t if isinstance(t, type) else type(t) for t in types])\n+ nodes = preorder_traversal(self)\n+ if types:\n+ result = {node for node in nodes if isinstance(node, types)}\n else:\n- types = (Atom,)\n- result = set()\n- for expr in preorder_traversal(self):\n- if isinstance(expr, types):\n- result.add(expr)\n+ result = {node for node in nodes if not node.args}\n return result\n \n @property\n", "test_patch": "diff --git a/sympy/codegen/tests/test_cnodes.py b/sympy/codegen/tests/test_cnodes.py\n--- a/sympy/codegen/tests/test_cnodes.py\n+++ b/sympy/codegen/tests/test_cnodes.py\n@@ -1,6 +1,6 @@\n from sympy.core.symbol import symbols\n from sympy.printing.ccode import ccode\n-from sympy.codegen.ast import Declaration, Variable, float64, int64\n+from sympy.codegen.ast import Declaration, Variable, float64, int64, String\n from sympy.codegen.cnodes import (\n alignof, CommaOperator, goto, Label, PreDecrement, PostDecrement, PreIncrement, PostIncrement,\n sizeof, union, struct\n@@ -66,7 +66,7 @@ def test_sizeof():\n assert ccode(sz) == 'sizeof(%s)' % typename\n assert sz.func(*sz.args) == sz\n assert not sz.is_Atom\n- assert all(atom == typename for atom in sz.atoms())\n+ assert sz.atoms() == {String('unsigned int'), String('sizeof')}\n \n \n def test_struct():\ndiff --git a/sympy/core/tests/test_basic.py b/sympy/core/tests/test_basic.py\n--- a/sympy/core/tests/test_basic.py\n+++ b/sympy/core/tests/test_basic.py\n@@ -137,7 +137,7 @@ def test_subs_with_unicode_symbols():\n \n \n def test_atoms():\n- assert b21.atoms() == set()\n+ assert b21.atoms() == set([Basic()])\n \n \n def test_free_symbols_empty():\n", "problem_statement": "expr.atoms() should return objects with no args instead of subclasses of Atom\n`expr.atoms()` with no arguments returns subclasses of `Atom` in `expr`. But the correct definition of a leaf node should be that it has no `.args`. \n\nThis should be easy to fix, but one needs to check that this doesn't affect the performance. \n\n", "hints_text": "The docstring should also be updated. \n\nHi, can i work on this?\n\nSure. Did you read https://github.com/sympy/sympy/wiki/Introduction-to-contributing? \n\nHow should I remove .args? Should I try to remove ._args from object instance or add a new attribute to class Atom(), is_leave. Which when assigned as false, will raise attribute error on .args. Or if creating a new object, what attributes should it have?\n\nI think you're misunderstanding the issue. The issue is not to remove .args. Indeed, every SymPy object should have .args in order to be valid. \n\nThe issue is that the `atoms()` method currently uses `x.is_Atom` to check for \"atomic\" expressions (expressions with no subexpressions), but it really should be checking `not x.args`. It should be a simple one-line fix to the `atoms` function definition, but a new test should be added, and the full test suite run to make sure it doesn't break anything (`./bin/test` from the sympy directory). \n\nOkay. But, Basic() also return .args to be null. So will not that also appear in the result of .atoms()?\n\nYes, that's an example of an object with no args but that isn't a subclass of Atom. `atoms` should return that, because it's a leaf in the expression tree. \n\nOkay, but if I am understanding you correct, won't this test fail?\nhttps://github.com/sympy/sympy/blob/master/sympy/core/tests/test_basic.py#L73\n\nYes, it would need to be changed. This is a slight redefinition of what `atoms` means (although hopefully not enough of a breaking behavior to require deprecation). \n\nCan you look over it once and look if it is okay?\nhttps://github.com/sympy/sympy/pull/10246\n\n@asmeurer \nWhen I ran the full suite of tests, sympy/vector/tests/test_field_functions.py failed on all the tests. \n\n```\n Original-\n if not (types or expr.args):\n result.add(expr)\n\n Case 1- \n if not types:\n if isinstance(expr, Atom):\n result.add(expr)\n\n Case 2-\n if not (types or expr.args):\n if isinstance(expr, Atom):\n result.add(expr)\n```\n\nI saw that fails even on the second case. Then I saw the items that case1 had but case2 did not. Which were all either `C.z ` or `C.k `. \n\nElements of the class sympy.vector.scaler.BaseScalar or class sympy.vector.vector.BaseVector were earlier considered but not now, as they were Atom but had arguments. So what should we do?\n\nI want to fix this if no one is working on it.\n\nI am unable to figure out why 'Atom' has been assigned to 'types' . We can add the result while checking for the types and if there are no types then we can simply add x.args to the result. That way it will return null and we will not be having subclasses of Atom.\n\nping @asmeurer \n\n@darkcoderrises I have some fixes at https://github.com/sympy/sympy/pull/10084 which might make your issues go away. Once that is merged you should try merging your branch into master and see if it fixes the problems. \n\nok\n\nI merged the pull requests, and now the tests are passing. What should be my next step.\nhttps://github.com/sympy/sympy/pull/10246\n\nI am working on this issue", "created_at": "2020-02-01T17:26:30Z", "version": "1.6", "FAIL_TO_PASS": "[\"test_sizeof\", \"test_atoms\"]", "PASS_TO_PASS": "[\"test_alignof\", \"test_CommaOperator\", \"test_goto_Label\", \"test_PreDecrement\", \"test_PostDecrement\", \"test_PreIncrement\", \"test_PostIncrement\", \"test_struct\", \"test__aresame\", \"test_structure\", \"test_equality\", \"test_matches_basic\", \"test_has\", \"test_subs\", \"test_subs_with_unicode_symbols\", \"test_free_symbols_empty\", \"test_doit\", \"test_S\", \"test_xreplace\", \"test_preorder_traversal\", \"test_sorted_args\", \"test_call\", \"test_rewrite\", \"test_literal_evalf_is_number_is_zero_is_comparable\", \"test_as_Basic\", \"test_atomic\", \"test_as_dummy\", \"test_canonical_variables\"]", "environment_setup_commit": "28b41c73c12b70d6ad9f6e45109a80649c4456da", "test_directives": ["sympy/codegen/tests/test_cnodes.py", "sympy/core/tests/test_basic.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/codegen/tests/test_cnodes.py sympy/core/tests/test_basic.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/sympy/core/tests/test_basic.py b/sympy/core/tests/test_basic.py\nindex 50f8f9ee7b..dcc6a9085b 100644\n--- a/sympy/core/tests/test_basic.py\n+++ b/sympy/core/tests/test_basic.py\n@@ -139,6 +139,19 @@ def test_subs_with_unicode_symbols():\n def test_atoms():\n assert b21.atoms() == set()\n \n+ # New test cases to verify the fix\n+ x, y = symbols('x y')\n+ expr = x + y\n+ assert expr.atoms() == {x, y}\n+ expr = sin(x) + cos(y)\n+ assert expr.atoms() == {x, y}\n+ \n+ # Additional test cases to ensure objects with no args are returned\n+ expr = x + y + 1\n+ assert expr.atoms() == {x, y, 1}\n+ expr = sin(x) + cos(y) + pi\n+ assert expr.atoms() == {x, y, pi}\n+\n \n def test_free_symbols_empty():\n assert b21.free_symbols == set()\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/core/tests/test_basic.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/sympy/plotting/experimental_lambdify.py b/sympy/plotting/experimental_lambdify.py\nindex 74c244c932..16f366aa36 100644\n--- a/sympy/plotting/experimental_lambdify.py\n+++ b/sympy/plotting/experimental_lambdify.py\n@@ -669,7 +669,7 @@ def sympy_expression_namespace(cls, expr):\n def sympy_atoms_namespace(expr):\n \"\"\"For no real reason this function is separated from\n sympy_expression_namespace. It can be moved to it.\"\"\"\n- atoms = expr.atoms(Symbol, NumberSymbol, I, zoo, oo)\n+ atoms = {a for a in expr.atoms() if not a.args}\n d = {}\n for a in atoms:\n # XXX debug: print 'atom:' + str(a)\n", "model_lint_repair_patch": "diff --git a/sympy/plotting/experimental_lambdify.py b/sympy/plotting/experimental_lambdify.py\nindex 74c244c932..16f366aa36 100644\n--- a/sympy/plotting/experimental_lambdify.py\n+++ b/sympy/plotting/experimental_lambdify.py\n@@ -669,7 +669,7 @@ def sympy_expression_namespace(cls, expr):\n def sympy_atoms_namespace(expr):\n \"\"\"For no real reason this function is separated from\n sympy_expression_namespace. It can be moved to it.\"\"\"\n- atoms = expr.atoms(Symbol, NumberSymbol, I, zoo, oo)\n+ atoms = {a for a in expr.atoms() if not a.args}\n d = {}\n for a in atoms:\n # XXX debug: print 'atom:' + str(a)\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/core/tests/test_basic.py"]} +{"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-23964", "base_commit": "269c0b94b4fcf8b1135011c1556eac29dc09de15", "patch": "diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py\n--- a/lib/matplotlib/backends/backend_ps.py\n+++ b/lib/matplotlib/backends/backend_ps.py\n@@ -665,8 +665,9 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n curr_stream[1].append(\n (item.x, item.ft_object.get_glyph_name(item.glyph_idx))\n )\n- # append the last entry\n- stream.append(curr_stream)\n+ # append the last entry if exists\n+ if curr_stream:\n+ stream.append(curr_stream)\n \n self.set_color(*gc.get_rgb())\n \n", "test_patch": "diff --git a/lib/matplotlib/tests/test_backend_ps.py b/lib/matplotlib/tests/test_backend_ps.py\n--- a/lib/matplotlib/tests/test_backend_ps.py\n+++ b/lib/matplotlib/tests/test_backend_ps.py\n@@ -256,6 +256,15 @@ def test_linedash():\n assert buf.tell() > 0\n \n \n+def test_empty_line():\n+ # Smoke-test for gh#23954\n+ figure = Figure()\n+ figure.text(0.5, 0.5, \"\\nfoo\\n\\n\")\n+ buf = io.BytesIO()\n+ figure.savefig(buf, format='eps')\n+ figure.savefig(buf, format='ps')\n+\n+\n def test_no_duplicate_definition():\n \n fig = Figure()\n", "problem_statement": "[Bug]: Text label with empty line causes a \"TypeError: cannot unpack non-iterable NoneType object\" in PostScript backend\n### Bug summary\n\nWhen saving a figure with the PostScript backend, a\r\n> TypeError: cannot unpack non-iterable NoneType object\r\n\r\nhappens if the figure contains a multi-line text label with an empty line (see example).\n\n### Code for reproduction\n\n```python\nfrom matplotlib.figure import Figure\r\n\r\nfigure = Figure()\r\nax = figure.add_subplot(111)\r\n# ax.set_title('\\nLower title') # this would cause an error as well\r\nax.annotate(text='\\nLower label', xy=(0, 0))\r\nfigure.savefig('figure.eps')\n```\n\n\n### Actual outcome\n\n$ ./venv/Scripts/python save_ps.py\r\nTraceback (most recent call last):\r\n File \"C:\\temp\\matplotlib_save_ps\\save_ps.py\", line 7, in \r\n figure.savefig('figure.eps')\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\figure.py\", line 3272, in savefig\r\n self.canvas.print_figure(fname, **kwargs)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\backend_bases.py\", line 2338, in print_figure\r\n result = print_method(\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\backend_bases.py\", line 2204, in \r\n print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\_api\\deprecation.py\", line 410, in wrapper\r\n return func(*inner_args, **inner_kwargs)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\backends\\backend_ps.py\", line 869, in _print_ps\r\n printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\backends\\backend_ps.py\", line 927, in _print_figure\r\n self.figure.draw(renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\artist.py\", line 74, in draw_wrapper\r\n result = draw(artist, renderer, *args, **kwargs)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\artist.py\", line 51, in draw_wrapper\r\n return draw(artist, renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\figure.py\", line 3069, in draw\r\n mimage._draw_list_compositing_images(\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\image.py\", line 131, in _draw_list_compositing_images\r\n a.draw(renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\artist.py\", line 51, in draw_wrapper\r\n return draw(artist, renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\axes\\_base.py\", line 3106, in draw\r\n mimage._draw_list_compositing_images(\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\image.py\", line 131, in _draw_list_compositing_images\r\n a.draw(renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\artist.py\", line 51, in draw_wrapper\r\n return draw(artist, renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\text.py\", line 1995, in draw\r\n Text.draw(self, renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\artist.py\", line 51, in draw_wrapper\r\n return draw(artist, renderer)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\text.py\", line 736, in draw\r\n textrenderer.draw_text(gc, x, y, clean_line,\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\backends\\backend_ps.py\", line 248, in wrapper\r\n return meth(self, *args, **kwargs)\r\n File \"C:\\temp\\matplotlib_save_ps\\venv\\lib\\site-packages\\matplotlib\\backends\\backend_ps.py\", line 673, in draw_text\r\n for ps_name, xs_names in stream:\r\nTypeError: cannot unpack non-iterable NoneType object\r\n\n\n### Expected outcome\n\nThe figure can be saved as `figure.eps` without error.\n\n### Additional information\n\n- seems to happen if a text label or title contains a linebreak with an empty line\r\n- works without error for other backends such as PNG, PDF, SVG, Qt\r\n- works with matplotlib<=3.5.3\r\n- adding `if curr_stream:` before line 669 of `backend_ps.py` seems to fix the bug \n\n### Operating system\n\nWindows\n\n### Matplotlib Version\n\n3.6.0\n\n### Matplotlib Backend\n\n_No response_\n\n### Python version\n\n3.9.13\n\n### Jupyter version\n\n_No response_\n\n### Installation\n\npip\n", "hints_text": "", "created_at": "2022-09-20T13:49:19Z", "version": "3.6", "FAIL_TO_PASS": "[\"lib/matplotlib/tests/test_backend_ps.py::test_empty_line\"]", "PASS_TO_PASS": "[\"lib/matplotlib/tests/test_backend_ps.py::test_savefig_to_stringio[ps-portrait]\", \"lib/matplotlib/tests/test_backend_ps.py::test_savefig_to_stringio[ps-landscape]\", \"lib/matplotlib/tests/test_backend_ps.py::test_savefig_to_stringio[ps\", \"lib/matplotlib/tests/test_backend_ps.py::test_savefig_to_stringio[eps-portrait]\", \"lib/matplotlib/tests/test_backend_ps.py::test_savefig_to_stringio[eps-landscape]\", \"lib/matplotlib/tests/test_backend_ps.py::test_savefig_to_stringio[eps\", \"lib/matplotlib/tests/test_backend_ps.py::test_patheffects\", \"lib/matplotlib/tests/test_backend_ps.py::test_transparency[eps]\", \"lib/matplotlib/tests/test_backend_ps.py::test_bbox\", \"lib/matplotlib/tests/test_backend_ps.py::test_failing_latex\", \"lib/matplotlib/tests/test_backend_ps.py::test_text_clip[eps]\", \"lib/matplotlib/tests/test_backend_ps.py::test_d_glyph\", \"lib/matplotlib/tests/test_backend_ps.py::test_fonttype[3]\", \"lib/matplotlib/tests/test_backend_ps.py::test_fonttype[42]\", \"lib/matplotlib/tests/test_backend_ps.py::test_linedash\", \"lib/matplotlib/tests/test_backend_ps.py::test_no_duplicate_definition\"]", "environment_setup_commit": "73909bcb408886a22e2b84581d6b9e6d9907c813", "test_directives": ["lib/matplotlib/tests/test_backend_ps.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v lib/matplotlib/tests/test_backend_ps.py", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py\nindex b5c1bbff64..ec19743ddf 100644\n--- a/lib/matplotlib/tests/test_text.py\n+++ b/lib/matplotlib/tests/test_text.py\n@@ -814,3 +814,22 @@ def test_metrics_cache():\n info = mpl.text._get_text_metrics_with_cache_impl.cache_info()\n # Each string gets drawn twice, so the second draw results in a hit.\n assert info.hits == info.misses\n+\n+def test_multiline_text_with_empty_line_ps_backend():\n+ \"\"\"\n+ Test that saving a figure with the PostScript backend containing a multi-line\n+ text label with an empty line does not raise a TypeError.\n+ \"\"\"\n+ from matplotlib.figure import Figure\n+ figure = Figure()\n+ ax = figure.add_subplot(111)\n+ ax.annotate(text='\\nLower label', xy=(0, 0))\n+ \n+ # Save the figure to a BytesIO object to avoid file I/O\n+ from io import BytesIO\n+ buffer = BytesIO()\n+ \n+ try:\n+ figure.savefig(buffer, format='eps')\n+ except TypeError as e:\n+ pytest.fail(f\"Saving figure with PostScript backend raised TypeError: {e}\")\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["lib/matplotlib/tests/test_text.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py\nindex f209e811f1..abf726be34 100644\n--- a/lib/matplotlib/backends/backend_ps.py\n+++ b/lib/matplotlib/backends/backend_ps.py\n@@ -665,8 +665,9 @@ grestore\n curr_stream[1].append(\n (item.x, item.ft_object.get_glyph_name(item.glyph_idx))\n )\n- # append the last entry\n- stream.append(curr_stream)\n+ # append the last entry if not None\n+ if curr_stream:\n+ stream.append(curr_stream)\n \n self.set_color(*gc.get_rgb())\n \n", "model_lint_repair_patch": "diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py\nindex f209e811f1..abf726be34 100644\n--- a/lib/matplotlib/backends/backend_ps.py\n+++ b/lib/matplotlib/backends/backend_ps.py\n@@ -665,8 +665,9 @@ grestore\n curr_stream[1].append(\n (item.x, item.ft_object.get_glyph_name(item.glyph_idx))\n )\n- # append the last entry\n- stream.append(curr_stream)\n+ # append the last entry if not None\n+ if curr_stream:\n+ stream.append(curr_stream)\n \n self.set_color(*gc.get_rgb())\n \n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["lib/matplotlib/tests/test_text.py"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-20212", "base_commit": "a106f4782a9dbe7f8fd16030f15401d977e03ae9", "patch": "diff --git a/sympy/core/power.py b/sympy/core/power.py\n--- a/sympy/core/power.py\n+++ b/sympy/core/power.py\n@@ -291,6 +291,8 @@ def __new__(cls, b, e, evaluate=None):\n ).warn()\n \n if evaluate:\n+ if b is S.Zero and e is S.NegativeInfinity:\n+ return S.ComplexInfinity\n if e is S.ComplexInfinity:\n return S.NaN\n if e is S.Zero:\n", "test_patch": "diff --git a/sympy/core/tests/test_power.py b/sympy/core/tests/test_power.py\n--- a/sympy/core/tests/test_power.py\n+++ b/sympy/core/tests/test_power.py\n@@ -266,6 +266,9 @@ def test_zero():\n assert 0**(2*x*y) == 0**(x*y)\n assert 0**(-2*x*y) == S.ComplexInfinity**(x*y)\n \n+ #Test issue 19572\n+ assert 0 ** -oo is zoo\n+ assert power(0, -oo) is zoo\n \n def test_pow_as_base_exp():\n x = Symbol('x')\n", "problem_statement": "0**-oo produces 0, the documentation says it should produce zoo\nUsing SymPy 1.5.1, evaluate `0**-oo` produces `0`.\r\n\r\nThe documentation for the Pow class states that it should return `ComplexInfinity`, aka `zoo`\r\n\r\n| expr | value | reason |\r\n| :-- | :-- | :--|\r\n| `0**-oo` | `zoo` | This is not strictly true, as 0**oo may be oscillating between positive and negative values or rotating in the complex plane. It is convenient, however, when the base is positive.|\r\n\n", "hints_text": "", "created_at": "2020-10-06T11:34:13Z", "version": "1.7", "FAIL_TO_PASS": "[\"test_zero\"]", "PASS_TO_PASS": "[\"test_rational\", \"test_large_rational\", \"test_negative_real\", \"test_expand\", \"test_issue_3449\", \"test_issue_3866\", \"test_negative_one\", \"test_issue_4362\", \"test_Pow_Expr_args\", \"test_Pow_signs\", \"test_power_with_noncommutative_mul_as_base\", \"test_power_rewrite_exp\", \"test_pow_as_base_exp\", \"test_nseries\", \"test_issue_6100_12942_4473\", \"test_issue_6208\", \"test_issue_6990\", \"test_issue_6068\", \"test_issue_6782\", \"test_issue_6653\", \"test_issue_6429\", \"test_issue_7638\", \"test_issue_8582\", \"test_issue_8650\", \"test_issue_13914\", \"test_better_sqrt\", \"test_issue_2993\", \"test_issue_17450\", \"test_issue_18190\", \"test_issue_14815\", \"test_issue_18509\", \"test_issue_18762\"]", "environment_setup_commit": "cffd4e0f86fefd4802349a9f9b19ed70934ea354", "test_directives": ["sympy/core/tests/test_power.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/core/tests/test_power.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/sympy/core/tests/test_assumptions.py b/sympy/core/tests/test_assumptions.py\nindex de71bf5371..0e023ff8ff 100644\n--- a/sympy/core/tests/test_assumptions.py\n+++ b/sympy/core/tests/test_assumptions.py\n@@ -18,6 +18,8 @@ def test_symbol_unset():\n \n \n def test_zero():\n+ z = Integer(0)\n+ assert z**S.NegativeInfinity == S.ComplexInfinity\n z = Integer(0)\n assert z.is_commutative is True\n assert z.is_integer is True\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["sympy/core/tests/test_assumptions.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/core/power.py b/sympy/core/power.py\nindex 984398c760..cd44ad80ea 100644\n--- a/sympy/core/power.py\n+++ b/sympy/core/power.py\n@@ -299,6 +299,8 @@ def __new__(cls, b, e, evaluate=None):\n return b\n elif e == -1 and not b:\n return S.ComplexInfinity\n+ elif b is S.Zero and e is S.NegativeInfinity:\n+ return S.ComplexInfinity\n # Only perform autosimplification if exponent or base is a Symbol or number\n elif (b.is_Symbol or b.is_number) and (e.is_Symbol or e.is_number) and\\\n e.is_integer and _coeff_isneg(b):\n", "model_lint_repair_patch": "diff --git a/sympy/core/power.py b/sympy/core/power.py\nindex 984398c760..cd44ad80ea 100644\n--- a/sympy/core/power.py\n+++ b/sympy/core/power.py\n@@ -299,6 +299,8 @@ def __new__(cls, b, e, evaluate=None):\n return b\n elif e == -1 and not b:\n return S.ComplexInfinity\n+ elif b is S.Zero and e is S.NegativeInfinity:\n+ return S.ComplexInfinity\n # Only perform autosimplification if exponent or base is a Symbol or number\n elif (b.is_Symbol or b.is_number) and (e.is_Symbol or e.is_number) and\\\n e.is_integer and _coeff_isneg(b):\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/core/tests/test_assumptions.py"]} +{"repo": "django/django", "instance_id": "django__django-12497", "base_commit": "a4881f5e5d7ee38b7e83301331a0b4962845ef8a", "patch": "diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py\n--- a/django/db/models/fields/related.py\n+++ b/django/db/models/fields/related.py\n@@ -1309,7 +1309,7 @@ def _check_relationship_model(self, from_model=None, **kwargs):\n \"through_fields keyword argument.\") % (self, from_model_name),\n hint=(\n 'If you want to create a recursive relationship, '\n- 'use ForeignKey(\"%s\", symmetrical=False, through=\"%s\").'\n+ 'use ManyToManyField(\"%s\", through=\"%s\").'\n ) % (\n RECURSIVE_RELATIONSHIP_CONSTANT,\n relationship_model_name,\n@@ -1329,7 +1329,7 @@ def _check_relationship_model(self, from_model=None, **kwargs):\n \"through_fields keyword argument.\" % (self, to_model_name),\n hint=(\n 'If you want to create a recursive relationship, '\n- 'use ForeignKey(\"%s\", symmetrical=False, through=\"%s\").'\n+ 'use ManyToManyField(\"%s\", through=\"%s\").'\n ) % (\n RECURSIVE_RELATIONSHIP_CONSTANT,\n relationship_model_name,\n", "test_patch": "diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py\n--- a/tests/invalid_models_tests/test_relative_fields.py\n+++ b/tests/invalid_models_tests/test_relative_fields.py\n@@ -128,7 +128,36 @@ class ThroughModel(models.Model):\n ),\n ])\n \n- def test_ambiguous_relationship_model(self):\n+ def test_ambiguous_relationship_model_from(self):\n+ class Person(models.Model):\n+ pass\n+\n+ class Group(models.Model):\n+ field = models.ManyToManyField('Person', through='AmbiguousRelationship')\n+\n+ class AmbiguousRelationship(models.Model):\n+ person = models.ForeignKey(Person, models.CASCADE)\n+ first_group = models.ForeignKey(Group, models.CASCADE, related_name='first')\n+ second_group = models.ForeignKey(Group, models.CASCADE, related_name='second')\n+\n+ field = Group._meta.get_field('field')\n+ self.assertEqual(field.check(from_model=Group), [\n+ Error(\n+ \"The model is used as an intermediate model by \"\n+ \"'invalid_models_tests.Group.field', but it has more than one \"\n+ \"foreign key from 'Group', which is ambiguous. You must \"\n+ \"specify which foreign key Django should use via the \"\n+ \"through_fields keyword argument.\",\n+ hint=(\n+ 'If you want to create a recursive relationship, use '\n+ 'ManyToManyField(\"self\", through=\"AmbiguousRelationship\").'\n+ ),\n+ obj=field,\n+ id='fields.E334',\n+ ),\n+ ])\n+\n+ def test_ambiguous_relationship_model_to(self):\n \n class Person(models.Model):\n pass\n@@ -152,7 +181,7 @@ class AmbiguousRelationship(models.Model):\n \"keyword argument.\",\n hint=(\n 'If you want to create a recursive relationship, use '\n- 'ForeignKey(\"self\", symmetrical=False, through=\"AmbiguousRelationship\").'\n+ 'ManyToManyField(\"self\", through=\"AmbiguousRelationship\").'\n ),\n obj=field,\n id='fields.E335',\n", "problem_statement": "Wrong hint about recursive relationship.\nDescription\n\t \n\t\t(last modified by Matheus Cunha Motta)\n\t \nWhen there's more than 2 ForeignKeys in an intermediary model of a m2m field and no through_fields have been set, Django will show an error with the following hint:\nhint=(\n\t'If you want to create a recursive relationship, '\n\t'use ForeignKey(\"%s\", symmetrical=False, through=\"%s\").'\nBut 'symmetrical' and 'through' are m2m keyword arguments, not ForeignKey.\nThis was probably a small mistake where the developer thought ManyToManyField but typed ForeignKey instead. And the symmetrical=False is an outdated requirement to recursive relationships with intermediary model to self, not required since 3.0. I'll provide a PR with a proposed correction shortly after.\nEdit: fixed description.\n", "hints_text": "Here's a PR: \u200bhttps://github.com/django/django/pull/12497 Edit: forgot to run tests and there was an error detected in the PR. I'll try to fix and run tests before submitting again.", "created_at": "2020-02-26T18:12:31Z", "version": "3.1", "FAIL_TO_PASS": "[\"test_ambiguous_relationship_model_from (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_ambiguous_relationship_model_to (invalid_models_tests.test_relative_fields.RelativeFieldTests)\"]", "PASS_TO_PASS": "[\"test_accessor_clash (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)\", \"test_clash_under_explicit_related_name (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)\", \"test_reverse_query_name_clash (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)\", \"test_explicit_field_names (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)\", \"test_intersection_foreign_object (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)\", \"test_invalid_field (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)\", \"test_invalid_order (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)\", \"test_m2m_field_argument_validation (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)\", \"test_superset_foreign_object (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)\", \"test_clash_parent_link (invalid_models_tests.test_relative_fields.ComplexClashTests)\", \"test_complex_clash (invalid_models_tests.test_relative_fields.ComplexClashTests)\", \"test_accessor_clash (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)\", \"test_clash_between_accessors (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)\", \"test_clash_under_explicit_related_name (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)\", \"test_reverse_query_name_clash (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)\", \"test_valid_model (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)\", \"test_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)\", \"test_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)\", \"test_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)\", \"test_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)\", \"test_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)\", \"test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)\", \"test_clash_between_accessors (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"test_fk_to_fk (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"test_fk_to_integer (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"test_fk_to_m2m (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"test_m2m_to_fk (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"test_m2m_to_integer (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"test_m2m_to_m2m (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"Ref #22047.\", \"test_no_clash_for_hidden_related_name (invalid_models_tests.test_relative_fields.AccessorClashTests)\", \"test_fk_to_fk (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)\", \"test_fk_to_integer (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)\", \"test_fk_to_m2m (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)\", \"test_m2m_to_fk (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)\", \"test_m2m_to_integer (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)\", \"test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)\", \"test_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_hidden_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_hidden_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_hidden_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_hidden_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_hidden_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_hidden_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)\", \"test_foreign_key_to_abstract_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_key_to_isolate_apps_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_key_to_missing_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_key_to_non_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_key_to_non_unique_field_under_explicit_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_key_to_partially_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_key_to_unique_field_with_meta_constraint (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_object_to_non_unique_fields (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_object_to_partially_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_foreign_object_to_unique_field_with_meta_constraint (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_invalid_related_query_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_m2m_to_abstract_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_many_to_many_through_isolate_apps_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_many_to_many_to_isolate_apps_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_many_to_many_to_missing_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_many_to_many_with_limit_choices_auto_created_no_warning (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_many_to_many_with_useless_options (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_missing_relationship_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_missing_relationship_model_on_model_check (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_not_swapped_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_nullable_primary_key (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_on_delete_set_default_without_default_value (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_on_delete_set_null_on_non_nullable_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_referencing_to_swapped_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_related_field_has_invalid_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_related_field_has_valid_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_relationship_model_missing_foreign_key (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_relationship_model_with_foreign_key_to_wrong_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_to_fields_exist (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_to_fields_not_checked_if_related_model_doesnt_exist (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_too_many_foreign_keys_in_self_referential_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_unique_m2m (invalid_models_tests.test_relative_fields.RelativeFieldTests)\", \"test_valid_foreign_key_without_accessor (invalid_models_tests.test_relative_fields.RelativeFieldTests)\"]", "environment_setup_commit": "0668164b4ac93a5be79f5b87fae83c657124d9ab", "test_directives": ["invalid_models_tests.test_relative_fields"], "test_cmd": "./tests/runtests.py --verbosity 2 invalid_models_tests.test_relative_fields", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["m2m_intermediary.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py\nindex 3282fd6d4b..87b4846533 100644\n--- a/django/contrib/contenttypes/fields.py\n+++ b/django/contrib/contenttypes/fields.py\n@@ -133,21 +133,21 @@ class GenericForeignKey(FieldCacheMixin):\n self.model._meta.object_name, self.ct_field\n ),\n hint=(\n- \"GenericForeignKeys must use a ForeignKey to \"\n+ \"GenericForeignKeys must use a ManyToManyField to \"\n \"'contenttypes.ContentType' as the 'content_type' field.\"\n ),\n obj=self,\n id='contenttypes.E003',\n )\n- ]\n+ ]\n elif field.remote_field.model != ContentType:\n return [\n checks.Error(\n- \"'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'.\" % (\n+ \"'%s.%s' is not a ManyToManyField to 'contenttypes.ContentType'.\" % (\n self.model._meta.object_name, self.ct_field\n ),\n hint=(\n- \"GenericForeignKeys must use a ForeignKey to \"\n+ \"GenericForeignKeys must use a ManyToManyField to \"\n \"'contenttypes.ContentType' as the 'content_type' field.\"\n ),\n obj=self,\n", "model_lint_repair_patch": "diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py\nindex 3282fd6d4b..98c46b32d2 100644\n--- a/django/contrib/contenttypes/fields.py\n+++ b/django/contrib/contenttypes/fields.py\n@@ -133,7 +133,7 @@ class GenericForeignKey(FieldCacheMixin):\n self.model._meta.object_name, self.ct_field\n ),\n hint=(\n- \"GenericForeignKeys must use a ForeignKey to \"\n+ \"GenericForeignKeys must use a ManyToManyField to \"\n \"'contenttypes.ContentType' as the 'content_type' field.\"\n ),\n obj=self,\n@@ -143,11 +143,11 @@ class GenericForeignKey(FieldCacheMixin):\n elif field.remote_field.model != ContentType:\n return [\n checks.Error(\n- \"'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'.\" % (\n+ \"'%s.%s' is not a ManyToManyField to 'contenttypes.ContentType'.\" % (\n self.model._meta.object_name, self.ct_field\n ),\n hint=(\n- \"GenericForeignKeys must use a ForeignKey to \"\n+ \"GenericForeignKeys must use a ManyToManyField to \"\n \"'contenttypes.ContentType' as the 'content_type' field.\"\n ),\n obj=self,\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["m2m_intermediary.tests"]} +{"repo": "pytest-dev/pytest", "instance_id": "pytest-dev__pytest-9359", "base_commit": "e2ee3144ed6e241dea8d96215fcdca18b3892551", "patch": "diff --git a/src/_pytest/_code/source.py b/src/_pytest/_code/source.py\n--- a/src/_pytest/_code/source.py\n+++ b/src/_pytest/_code/source.py\n@@ -149,6 +149,11 @@ def get_statement_startend2(lineno: int, node: ast.AST) -> Tuple[int, Optional[i\n values: List[int] = []\n for x in ast.walk(node):\n if isinstance(x, (ast.stmt, ast.ExceptHandler)):\n+ # Before Python 3.8, the lineno of a decorated class or function pointed at the decorator.\n+ # Since Python 3.8, the lineno points to the class/def, so need to include the decorators.\n+ if isinstance(x, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):\n+ for d in x.decorator_list:\n+ values.append(d.lineno - 1)\n values.append(x.lineno - 1)\n for name in (\"finalbody\", \"orelse\"):\n val: Optional[List[ast.stmt]] = getattr(x, name, None)\n", "test_patch": "diff --git a/testing/code/test_source.py b/testing/code/test_source.py\n--- a/testing/code/test_source.py\n+++ b/testing/code/test_source.py\n@@ -618,6 +618,19 @@ def something():\n assert str(source) == \"def func(): raise ValueError(42)\"\n \n \n+def test_decorator() -> None:\n+ s = \"\"\"\\\n+def foo(f):\n+ pass\n+\n+@foo\n+def bar():\n+ pass\n+ \"\"\"\n+ source = getstatement(3, s)\n+ assert \"@foo\" in str(source)\n+\n+\n def XXX_test_expression_multiline() -> None:\n source = \"\"\"\\\n something\n", "problem_statement": "Error message prints extra code line when using assert in python3.9\n\r\n\r\n- [x] a detailed description of the bug or problem you are having\r\n- [x] output of `pip list` from the virtual environment you are using\r\n- [x] pytest and operating system versions\r\n- [ ] minimal example if possible\r\n### Description\r\nI have a test like this:\r\n```\r\nfrom pytest import fixture\r\n\r\n\r\ndef t(foo):\r\n return foo\r\n\r\n\r\n@fixture\r\ndef foo():\r\n return 1\r\n\r\n\r\ndef test_right_statement(foo):\r\n assert foo == (3 + 2) * (6 + 9)\r\n\r\n @t\r\n def inner():\r\n return 2\r\n\r\n assert 2 == inner\r\n\r\n\r\n@t\r\ndef outer():\r\n return 2\r\n```\r\nThe test \"test_right_statement\" fails at the first assertion,but print extra code (the \"t\" decorator) in error details, like this:\r\n\r\n```\r\n ============================= test session starts =============================\r\nplatform win32 -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-0.13.1 -- \r\ncachedir: .pytest_cache\r\nrootdir: \r\nplugins: allure-pytest-2.9.45\r\ncollecting ... collected 1 item\r\n\r\ntest_statement.py::test_right_statement FAILED [100%]\r\n\r\n================================== FAILURES ===================================\r\n____________________________ test_right_statement _____________________________\r\n\r\nfoo = 1\r\n\r\n def test_right_statement(foo):\r\n> assert foo == (3 + 2) * (6 + 9)\r\n \r\n @t\r\nE assert 1 == 75\r\nE +1\r\nE -75\r\n\r\ntest_statement.py:14: AssertionError\r\n=========================== short test summary info ===========================\r\nFAILED test_statement.py::test_right_statement - assert 1 == 75\r\n============================== 1 failed in 0.12s ==============================\r\n```\r\nAnd the same thing **did not** happen when using python3.7.10\uff1a\r\n```\r\n============================= test session starts =============================\r\nplatform win32 -- Python 3.7.10, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- \r\ncachedir: .pytest_cache\r\nrootdir: \r\ncollecting ... collected 1 item\r\n\r\ntest_statement.py::test_right_statement FAILED [100%]\r\n\r\n================================== FAILURES ===================================\r\n____________________________ test_right_statement _____________________________\r\n\r\nfoo = 1\r\n\r\n def test_right_statement(foo):\r\n> assert foo == (3 + 2) * (6 + 9)\r\nE assert 1 == 75\r\nE +1\r\nE -75\r\n\r\ntest_statement.py:14: AssertionError\r\n=========================== short test summary info ===========================\r\nFAILED test_statement.py::test_right_statement - assert 1 == 75\r\n============================== 1 failed in 0.03s ==============================\r\n```\r\nIs there some problems when calculate the statement lineno?\r\n\r\n### pip list \r\n```\r\n$ pip list\r\nPackage Version\r\n------------------ -------\r\natomicwrites 1.4.0\r\nattrs 21.2.0\r\ncolorama 0.4.4\r\nimportlib-metadata 4.8.2\r\niniconfig 1.1.1\r\npackaging 21.3\r\npip 21.3.1\r\npluggy 1.0.0\r\npy 1.11.0\r\npyparsing 3.0.6\r\npytest 6.2.5\r\nsetuptools 59.4.0\r\ntoml 0.10.2\r\ntyping_extensions 4.0.0\r\nzipp 3.6.0\r\n\r\n```\r\n### pytest and operating system versions\r\npytest 6.2.5\r\nWindows 10 \r\nSeems to happen in python 3.9,not 3.7\r\n\n", "hints_text": "", "created_at": "2021-12-01T14:31:38Z", "version": "7.0", "FAIL_TO_PASS": "[\"testing/code/test_source.py::test_decorator\"]", "PASS_TO_PASS": "[\"testing/code/test_source.py::test_source_str_function\", \"testing/code/test_source.py::test_source_from_function\", \"testing/code/test_source.py::test_source_from_method\", \"testing/code/test_source.py::test_source_from_lines\", \"testing/code/test_source.py::test_source_from_inner_function\", \"testing/code/test_source.py::test_source_strips\", \"testing/code/test_source.py::test_source_strip_multiline\", \"testing/code/test_source.py::TestAccesses::test_getrange\", \"testing/code/test_source.py::TestAccesses::test_getrange_step_not_supported\", \"testing/code/test_source.py::TestAccesses::test_getline\", \"testing/code/test_source.py::TestAccesses::test_len\", \"testing/code/test_source.py::TestAccesses::test_iter\", \"testing/code/test_source.py::TestSourceParsing::test_getstatement\", \"testing/code/test_source.py::TestSourceParsing::test_getstatementrange_triple_quoted\", \"testing/code/test_source.py::TestSourceParsing::test_getstatementrange_within_constructs\", \"testing/code/test_source.py::TestSourceParsing::test_getstatementrange_bug\", \"testing/code/test_source.py::TestSourceParsing::test_getstatementrange_bug2\", \"testing/code/test_source.py::TestSourceParsing::test_getstatementrange_ast_issue58\", \"testing/code/test_source.py::TestSourceParsing::test_getstatementrange_out_of_bounds_py3\", \"testing/code/test_source.py::TestSourceParsing::test_getstatementrange_with_syntaxerror_issue7\", \"testing/code/test_source.py::test_getstartingblock_singleline\", \"testing/code/test_source.py::test_getline_finally\", \"testing/code/test_source.py::test_getfuncsource_dynamic\", \"testing/code/test_source.py::test_getfuncsource_with_multine_string\", \"testing/code/test_source.py::test_deindent\", \"testing/code/test_source.py::test_source_of_class_at_eof_without_newline\", \"testing/code/test_source.py::test_source_fallback\", \"testing/code/test_source.py::test_findsource_fallback\", \"testing/code/test_source.py::test_findsource\", \"testing/code/test_source.py::test_getfslineno\", \"testing/code/test_source.py::test_code_of_object_instance_with_call\", \"testing/code/test_source.py::test_oneline\", \"testing/code/test_source.py::test_comment_and_no_newline_at_end\", \"testing/code/test_source.py::test_oneline_and_comment\", \"testing/code/test_source.py::test_comments\", \"testing/code/test_source.py::test_comment_in_statement\", \"testing/code/test_source.py::test_source_with_decorator\", \"testing/code/test_source.py::test_single_line_else\", \"testing/code/test_source.py::test_single_line_finally\", \"testing/code/test_source.py::test_issue55\", \"testing/code/test_source.py::test_multiline\", \"testing/code/test_source.py::TestTry::test_body\", \"testing/code/test_source.py::TestTry::test_except_line\", \"testing/code/test_source.py::TestTry::test_except_body\", \"testing/code/test_source.py::TestTry::test_else\", \"testing/code/test_source.py::TestTryFinally::test_body\", \"testing/code/test_source.py::TestTryFinally::test_finally\", \"testing/code/test_source.py::TestIf::test_body\", \"testing/code/test_source.py::TestIf::test_elif_clause\", \"testing/code/test_source.py::TestIf::test_elif\", \"testing/code/test_source.py::TestIf::test_else\", \"testing/code/test_source.py::test_semicolon\", \"testing/code/test_source.py::test_def_online\", \"testing/code/test_source.py::test_getstartingblock_multiline\"]", "environment_setup_commit": "e2ee3144ed6e241dea8d96215fcdca18b3892551", "test_directives": ["testing/code/test_source.py"], "test_cmd": "pytest -vrA testing/code/test_source.py", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["testing/code/test_excinfo.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/extra/get_issues.py b/extra/get_issues.py\nindex 4aaa3c3ec..9f859cda8 100644\n--- a/extra/get_issues.py\n+++ b/extra/get_issues.py\n@@ -20,7 +20,7 @@ def get_issues():\n issues.extend(data)\n \n # Look for next page\n- links = requests.utils.parse_header_links(r.headers[\"Link\"])\n+ links = requests.utils.parse_header_links(r.headers.get(\"Link\", \"\"))\n another_page = False\n for link in links:\n if link[\"rel\"] == \"next\":\n", "model_lint_repair_patch": "diff --git a/extra/get_issues.py b/extra/get_issues.py\nindex 4aaa3c3ec..9f859cda8 100644\n--- a/extra/get_issues.py\n+++ b/extra/get_issues.py\n@@ -20,7 +20,7 @@ def get_issues():\n issues.extend(data)\n \n # Look for next page\n- links = requests.utils.parse_header_links(r.headers[\"Link\"])\n+ links = requests.utils.parse_header_links(r.headers.get(\"Link\", \"\"))\n another_page = False\n for link in links:\n if link[\"rel\"] == \"next\":\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["testing/code/test_excinfo.py"]} +{"repo": "pytest-dev/pytest", "instance_id": "pytest-dev__pytest-7490", "base_commit": "7f7a36478abe7dd1fa993b115d22606aa0e35e88", "patch": "diff --git a/src/_pytest/skipping.py b/src/_pytest/skipping.py\n--- a/src/_pytest/skipping.py\n+++ b/src/_pytest/skipping.py\n@@ -231,17 +231,14 @@ def evaluate_xfail_marks(item: Item) -> Optional[Xfail]:\n \n @hookimpl(tryfirst=True)\n def pytest_runtest_setup(item: Item) -> None:\n- item._store[skipped_by_mark_key] = False\n-\n skipped = evaluate_skip_marks(item)\n+ item._store[skipped_by_mark_key] = skipped is not None\n if skipped:\n- item._store[skipped_by_mark_key] = True\n skip(skipped.reason)\n \n- if not item.config.option.runxfail:\n- item._store[xfailed_key] = xfailed = evaluate_xfail_marks(item)\n- if xfailed and not xfailed.run:\n- xfail(\"[NOTRUN] \" + xfailed.reason)\n+ item._store[xfailed_key] = xfailed = evaluate_xfail_marks(item)\n+ if xfailed and not item.config.option.runxfail and not xfailed.run:\n+ xfail(\"[NOTRUN] \" + xfailed.reason)\n \n \n @hookimpl(hookwrapper=True)\n@@ -250,12 +247,16 @@ def pytest_runtest_call(item: Item) -> Generator[None, None, None]:\n if xfailed is None:\n item._store[xfailed_key] = xfailed = evaluate_xfail_marks(item)\n \n- if not item.config.option.runxfail:\n- if xfailed and not xfailed.run:\n- xfail(\"[NOTRUN] \" + xfailed.reason)\n+ if xfailed and not item.config.option.runxfail and not xfailed.run:\n+ xfail(\"[NOTRUN] \" + xfailed.reason)\n \n yield\n \n+ # The test run may have added an xfail mark dynamically.\n+ xfailed = item._store.get(xfailed_key, None)\n+ if xfailed is None:\n+ item._store[xfailed_key] = xfailed = evaluate_xfail_marks(item)\n+\n \n @hookimpl(hookwrapper=True)\n def pytest_runtest_makereport(item: Item, call: CallInfo[None]):\n", "test_patch": "diff --git a/testing/test_skipping.py b/testing/test_skipping.py\n--- a/testing/test_skipping.py\n+++ b/testing/test_skipping.py\n@@ -1,6 +1,7 @@\n import sys\n \n import pytest\n+from _pytest.pytester import Testdir\n from _pytest.runner import runtestprotocol\n from _pytest.skipping import evaluate_skip_marks\n from _pytest.skipping import evaluate_xfail_marks\n@@ -425,6 +426,33 @@ def test_this2(arg):\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n \n+ def test_dynamic_xfail_set_during_runtest_failed(self, testdir: Testdir) -> None:\n+ # Issue #7486.\n+ p = testdir.makepyfile(\n+ \"\"\"\n+ import pytest\n+ def test_this(request):\n+ request.node.add_marker(pytest.mark.xfail(reason=\"xfail\"))\n+ assert 0\n+ \"\"\"\n+ )\n+ result = testdir.runpytest(p)\n+ result.assert_outcomes(xfailed=1)\n+\n+ def test_dynamic_xfail_set_during_runtest_passed_strict(\n+ self, testdir: Testdir\n+ ) -> None:\n+ # Issue #7486.\n+ p = testdir.makepyfile(\n+ \"\"\"\n+ import pytest\n+ def test_this(request):\n+ request.node.add_marker(pytest.mark.xfail(reason=\"xfail\", strict=True))\n+ \"\"\"\n+ )\n+ result = testdir.runpytest(p)\n+ result.assert_outcomes(failed=1)\n+\n @pytest.mark.parametrize(\n \"expected, actual, matchline\",\n [\n", "problem_statement": "Pytest 6: Dynamically adding xfail marker in test no longer ignores failure\n\r\n\r\n## Description\r\n\r\nWith pytest 5.x, we can dynamically add an xfail to a test `request` object using `request.node.add_marker(mark)` (see example below). In 5.x this treated the failing test like a a test marked statically with an `xfail`. With 6.0.0rc0 it raises. \r\n\r\n## Versions\r\n\r\n
\r\n\r\n```\r\n$ pip list\r\nPackage Version Location \r\n----------------------------- ------------------------------- --------------------------------------------------------------\r\na 1.0 \r\naioftp 0.13.0 \r\naiohttp 3.6.2 \r\nalabaster 0.7.12 \r\napipkg 1.5 \r\naplus 0.11.0 \r\nappdirs 1.4.3 \r\nappnope 0.1.0 \r\narrow 0.15.7 \r\naspy.yaml 1.3.0 \r\nastropy 3.2.3 \r\nasv 0.4.1 \r\nasync-timeout 3.0.1 \r\natomicwrites 1.3.0 \r\nattrs 19.1.0 \r\naws-sam-translator 1.15.1 \r\naws-xray-sdk 0.95 \r\nBabel 2.7.0 \r\nbackcall 0.1.0 \r\nbinaryornot 0.4.4 \r\nblack 19.10b0 \r\nbleach 3.1.0 \r\nblurb 1.0.7 \r\nbokeh 1.3.4 \r\nboto 2.49.0 \r\nboto3 1.7.84 \r\nbotocore 1.10.84 \r\nbqplot 0.12.12 \r\nbranca 0.3.1 \r\ncachetools 4.1.0 \r\ncertifi 2019.9.11 \r\ncffi 1.13.2 \r\ncfgv 2.0.1 \r\ncfn-lint 0.25.0 \r\ncftime 1.0.4.2 \r\nchardet 3.0.4 \r\nClick 7.0 \r\nclick-plugins 1.1.1 \r\ncligj 0.5.0 \r\ncloudpickle 1.2.2 \r\ncolorama 0.4.3 \r\ncolorcet 2.0.2 \r\ncoloredlogs 14.0 \r\ncookiecutter 1.7.2 \r\ncookies 2.2.1 \r\ncoverage 4.5.4 \r\ncryptography 2.8 \r\ncycler 0.10.0 \r\nCython 3.0a5 \r\ncytoolz 0.10.1 \r\ndask 2.4.0 /Users/taugspurger/Envs/pandas-dev/lib/python3.7/site-packages\r\nDateTime 4.3 \r\ndecorator 4.4.0 \r\ndefusedxml 0.6.0 \r\nDeprecated 1.2.7 \r\ndistributed 2.4.0 \r\ndocker 4.1.0 \r\ndocutils 0.15.2 \r\necdsa 0.14.1 \r\nentrypoints 0.3 \r\net-xmlfile 1.0.1 \r\nexecnet 1.7.1 \r\nfastparquet 0.3.3 /Users/taugspurger/sandbox/fastparquet \r\nfeedparser 5.2.1 \r\nFiona 1.8.8 \r\nflake8 3.7.9 \r\nflake8-rst 0.7.1 \r\nfletcher 0.3.1 \r\nflit 2.1.0 \r\nflit-core 2.1.0 \r\nfsspec 0.7.4 \r\nfuture 0.18.2 \r\ngcsfs 0.6.2 \r\ngeopandas 0.6.0+1.g95b8e1a.dirty /Users/taugspurger/sandbox/geopandas \r\ngitdb2 2.0.5 \r\nGitPython 3.0.2 \r\ngoogle-auth 1.16.1 \r\ngoogle-auth-oauthlib 0.4.1 \r\ngraphviz 0.13 \r\nh5py 2.10.0 \r\nHeapDict 1.0.1 \r\nholoviews 1.12.6 \r\nhumanfriendly 8.1 \r\nhunter 3.1.3 \r\nhvplot 0.5.2 \r\nhypothesis 4.36.2 \r\nidentify 1.4.7 \r\nidna 2.8 \r\nimagesize 1.1.0 \r\nimportlib-metadata 0.23 \r\nimportlib-resources 1.0.2 \r\niniconfig 1.0.0 \r\nintake 0.5.3 \r\nipydatawidgets 4.0.1 \r\nipykernel 5.1.2 \r\nipyleaflet 0.13.0 \r\nipympl 0.5.6 \r\nipython 7.11.1 \r\nipython-genutils 0.2.0 \r\nipyvolume 0.5.2 \r\nipyvue 1.3.2 \r\nipyvuetify 1.4.0 \r\nipywebrtc 0.5.0 \r\nipywidgets 7.5.1 \r\nisort 4.3.21 \r\njdcal 1.4.1 \r\njedi 0.16.0 \r\nJinja2 2.11.2 \r\njinja2-time 0.2.0 \r\njmespath 0.9.4 \r\njoblib 0.14.1 \r\njson5 0.9.4 \r\njsondiff 1.1.1 \r\njsonpatch 1.24 \r\njsonpickle 1.2 \r\njsonpointer 2.0 \r\njsonschema 3.0.2 \r\njupyter 1.0.0 \r\njupyter-client 5.3.3 \r\njupyter-console 6.0.0 \r\njupyter-core 4.5.0 \r\njupyterlab 2.1.2 \r\njupyterlab-server 1.1.4 \r\nkiwisolver 1.1.0 \r\nline-profiler 2.1.1 \r\nllvmlite 0.33.0 \r\nlocket 0.2.0 /Users/taugspurger/sandbox/locket.py \r\nlxml 4.5.0 \r\nmanhole 1.6.0 \r\nMarkdown 3.1.1 \r\nMarkupSafe 1.1.1 \r\nmatplotlib 3.2.2 \r\nmccabe 0.6.1 \r\nmemory-profiler 0.55.0 \r\nmistune 0.8.4 \r\nmock 3.0.5 \r\nmore-itertools 7.2.0 \r\nmoto 1.3.6 \r\nmsgpack 0.6.2 \r\nmultidict 4.5.2 \r\nmunch 2.3.2 \r\nmypy 0.730 \r\nmypy-extensions 0.4.1 \r\nnbconvert 5.6.0 \r\nnbformat 4.4.0 \r\nnbsphinx 0.4.2 \r\nnest-asyncio 1.3.3 \r\nnodeenv 1.3.3 \r\nnotebook 6.0.1 \r\nnumexpr 2.7.1 \r\nnumpy 1.19.0 \r\nnumpydoc 1.0.0.dev0 \r\noauthlib 3.1.0 \r\nodfpy 1.4.0 \r\nopenpyxl 3.0.3 \r\npackaging 20.4 \r\npandas 1.1.0.dev0+1758.g035e1fe831 /Users/taugspurger/sandbox/pandas \r\npandas-sphinx-theme 0.0.1.dev0 /Users/taugspurger/sandbox/pandas-sphinx-theme \r\npandocfilters 1.4.2 \r\nparam 1.9.2 \r\nparfive 1.0.0 \r\nparso 0.6.0 \r\npartd 1.0.0 \r\npathspec 0.8.0 \r\npatsy 0.5.1 \r\npexpect 4.7.0 \r\npickleshare 0.7.5 \r\nPillow 6.1.0 \r\npip 20.0.2 \r\npluggy 0.13.0 \r\npoyo 0.5.0 \r\npre-commit 1.18.3 \r\nprogressbar2 3.51.3 \r\nprometheus-client 0.7.1 \r\nprompt-toolkit 2.0.9 \r\npsutil 5.6.3 \r\nptyprocess 0.6.0 \r\npy 1.9.0 \r\npyaml 20.4.0 \r\npyarrow 0.16.0 \r\npyasn1 0.4.7 \r\npyasn1-modules 0.2.8 \r\npycodestyle 2.5.0 \r\npycparser 2.19 \r\npycryptodome 3.9.8 \r\npyct 0.4.6 \r\npydata-sphinx-theme 0.1.1 \r\npydeps 1.9.0 \r\npyflakes 2.1.1 \r\nPyGithub 1.44.1 \r\nPygments 2.4.2 \r\nPyJWT 1.7.1 \r\npyparsing 2.4.2 \r\npyproj 2.4.0 \r\npyrsistent 0.15.4 \r\npytest 5.4.3 \r\npytest-asyncio 0.10.0 \r\npytest-cov 2.8.1 \r\npytest-cover 3.0.0 \r\npytest-forked 1.0.2 \r\npytest-repeat 0.8.0 \r\npytest-xdist 1.29.0 \r\npython-boilerplate 0.1.0 \r\npython-dateutil 2.8.0 \r\npython-jose 2.0.2 \r\npython-jsonrpc-server 0.3.2 \r\npython-language-server 0.31.4 \r\npython-slugify 4.0.1 \r\npython-utils 2.4.0 \r\npythreejs 2.2.0 \r\npytoml 0.1.21 \r\npytz 2019.2 \r\npyviz-comms 0.7.2 \r\nPyYAML 5.1.2 \r\npyzmq 18.1.0 \r\nqtconsole 4.5.5 \r\nregex 2020.6.8 \r\nrequests 2.24.0 \r\nrequests-oauthlib 1.3.0 \r\nresponses 0.10.6 \r\nrsa 4.0 \r\nrstcheck 3.3.1 \r\ns3fs 0.4.2 \r\ns3transfer 0.1.13 \r\nscikit-learn 0.22.2.post1 \r\nscipy 1.3.1 \r\nseaborn 0.9.0 \r\nSend2Trash 1.5.0 \r\nsetuptools 49.2.0 \r\nShapely 1.6.4.post2 \r\nsix 1.12.0 \r\nsmmap2 2.0.5 \r\nsnakeviz 2.0.1 \r\nsnowballstemmer 1.9.1 \r\nsortedcontainers 2.1.0 \r\nsparse 0.10.0 \r\nSphinx 3.1.1 \r\nsphinxcontrib-applehelp 1.0.2 \r\nsphinxcontrib-devhelp 1.0.2 \r\nsphinxcontrib-htmlhelp 1.0.3 \r\nsphinxcontrib-jsmath 1.0.1 \r\nsphinxcontrib-qthelp 1.0.3 \r\nsphinxcontrib-serializinghtml 1.1.4 \r\nsphinxcontrib-websupport 1.1.2 \r\nsphinxcontrib.youtube 0.1.2 \r\nSQLAlchemy 1.3.11 \r\nsshpubkeys 3.1.0 \r\nstatsmodels 0.10.2 \r\nstdlib-list 0.6.0 \r\nsunpy 1.1.dev518+gcad2d473f.d20191103 /Users/taugspurger/sandbox/sunpy \r\ntables 3.6.1 \r\ntabulate 0.8.6 \r\ntblib 1.4.0 \r\nterminado 0.8.2 \r\ntest 1.0.0 \r\ntestpath 0.4.2 \r\ntext-unidecode 1.3 \r\nthrift 0.13.0 \r\ntoml 0.10.0 \r\ntoolz 0.10.0 \r\ntornado 6.0.3 \r\ntqdm 4.37.0 \r\ntraitlets 4.3.2 \r\ntraittypes 0.2.1 \r\ntyped-ast 1.4.0 \r\ntyping-extensions 3.7.4 \r\nujson 1.35 \r\nurllib3 1.25.5 \r\nvaex 3.0.0 \r\nvaex-arrow 0.5.1 \r\nvaex-astro 0.7.0 \r\nvaex-core 2.0.2 \r\nvaex-hdf5 0.6.0 \r\nvaex-jupyter 0.5.1.post0 \r\nvaex-ml 0.9.0 \r\nvaex-server 0.3.1 \r\nvaex-viz 0.4.0 \r\nvirtualenv 16.7.5 \r\nwcwidth 0.1.7 \r\nwebencodings 0.5.1 \r\nwebsocket-client 0.56.0 \r\nWerkzeug 0.16.0 \r\nwheel 0.34.2 \r\nwidgetsnbextension 3.5.1 \r\nwrapt 1.11.2 \r\nxarray 0.14.1+36.gb3d3b448 /Users/taugspurger/sandbox/xarray \r\nxlwt 1.3.0 \r\nxmltodict 0.12.0 \r\nyarl 1.3.0 \r\nzict 1.0.0 \r\nzipp 0.6.0 \r\nzope.interface 4.7.1 \r\n```\r\n\r\n
\r\n\r\n- [ ] pytest and operating system versions\r\n\r\nPytest 6.0.1rc0 and MacOS 10.14.5\r\n\r\n```python\r\n# file: test_foo.py\r\nimport pytest\r\n\r\n\r\ndef test_xfail_test(request):\r\n mark = pytest.mark.xfail(reason=\"xfail\")\r\n request.node.add_marker(mark)\r\n assert 0\r\n```\r\n\r\nWith 5.4.3\r\n\r\n```\r\n\r\n$ pytest -rsx test_foo.py\r\n=============================================================================== test session starts ================================================================================\r\nplatform darwin -- Python 3.7.6, pytest-5.4.3, py-1.9.0, pluggy-0.13.0\r\nhypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/Users/taugspurger/sandbox/.hypothesis/examples')\r\nrootdir: /Users/taugspurger/sandbox\r\nplugins: xdist-1.29.0, hypothesis-4.36.2, forked-1.0.2, repeat-0.8.0, asyncio-0.10.0, cov-2.8.1\r\ncollected 1 item\r\n\r\ntest_foo.py x [100%]\r\n\r\n============================================================================= short test summary info ==============================================================================\r\nXFAIL test_foo.py::test_xfail_test\r\n xfail\r\n================================================================================ 1 xfailed in 0.07s ================================================================================\r\n```\r\n\r\nWith 6.0.0rc0\r\n\r\n```\r\n$ pytest -rsx test_foo.py\r\n=============================================================================== test session starts ================================================================================\r\nplatform darwin -- Python 3.7.6, pytest-6.0.0rc1, py-1.9.0, pluggy-0.13.0\r\nhypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/Users/taugspurger/sandbox/.hypothesis/examples')\r\nrootdir: /Users/taugspurger/sandbox\r\nplugins: xdist-1.29.0, hypothesis-4.36.2, forked-1.0.2, repeat-0.8.0, asyncio-0.10.0, cov-2.8.1\r\ncollected 1 item\r\n\r\ntest_foo.py F [100%]\r\n\r\n===================================================================================== FAILURES =====================================================================================\r\n_________________________________________________________________________________ test_xfail_test __________________________________________________________________________________\r\n\r\nrequest = >\r\n\r\n def test_xfail_test(request):\r\n mark = pytest.mark.xfail(reason=\"xfail\")\r\n request.node.add_marker(mark)\r\n> assert 0\r\nE assert 0\r\n\r\ntest_foo.py:7: AssertionError\r\n```\r\n\n", "hints_text": "Thanks for testing the release candidate! This is probably a regression in c9737ae914891027da5f0bd39494dd51a3b3f19f, will fix.", "created_at": "2020-07-13T22:20:10Z", "version": "6.0", "FAIL_TO_PASS": "[\"testing/test_skipping.py::TestXFail::test_dynamic_xfail_set_during_runtest_failed\", \"testing/test_skipping.py::TestXFail::test_dynamic_xfail_set_during_runtest_passed_strict\"]", "PASS_TO_PASS": "[\"testing/test_skipping.py::test_importorskip\", \"testing/test_skipping.py::TestEvaluation::test_no_marker\", \"testing/test_skipping.py::TestEvaluation::test_marked_xfail_no_args\", \"testing/test_skipping.py::TestEvaluation::test_marked_skipif_no_args\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg_with_reason\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg_twice\", \"testing/test_skipping.py::TestEvaluation::test_marked_one_arg_twice2\", \"testing/test_skipping.py::TestEvaluation::test_marked_skipif_with_boolean_without_reason\", \"testing/test_skipping.py::TestEvaluation::test_marked_skipif_with_invalid_boolean\", \"testing/test_skipping.py::TestEvaluation::test_skipif_class\", \"testing/test_skipping.py::TestXFail::test_xfail_simple[True]\", \"testing/test_skipping.py::TestXFail::test_xfail_simple[False]\", \"testing/test_skipping.py::TestXFail::test_xfail_xpassed\", \"testing/test_skipping.py::TestXFail::test_xfail_using_platform\", \"testing/test_skipping.py::TestXFail::test_xfail_xpassed_strict\", \"testing/test_skipping.py::TestXFail::test_xfail_run_anyway\", \"testing/test_skipping.py::TestXFail::test_xfail_run_with_skip_mark[test_input0-expected0]\", \"testing/test_skipping.py::TestXFail::test_xfail_run_with_skip_mark[test_input1-expected1]\", \"testing/test_skipping.py::TestXFail::test_xfail_evalfalse_but_fails\", \"testing/test_skipping.py::TestXFail::test_xfail_not_report_default\", \"testing/test_skipping.py::TestXFail::test_xfail_not_run_xfail_reporting\", \"testing/test_skipping.py::TestXFail::test_xfail_not_run_no_setup_run\", \"testing/test_skipping.py::TestXFail::test_xfail_xpass\", \"testing/test_skipping.py::TestXFail::test_xfail_imperative\", \"testing/test_skipping.py::TestXFail::test_xfail_imperative_in_setup_function\", \"testing/test_skipping.py::TestXFail::test_dynamic_xfail_no_run\", \"testing/test_skipping.py::TestXFail::test_dynamic_xfail_set_during_funcarg_setup\", \"testing/test_skipping.py::TestXFail::test_xfail_raises[TypeError-TypeError-*1\", \"testing/test_skipping.py::TestXFail::test_xfail_raises[(AttributeError,\", \"testing/test_skipping.py::TestXFail::test_xfail_raises[TypeError-IndexError-*1\", \"testing/test_skipping.py::TestXFail::test_strict_sanity\", \"testing/test_skipping.py::TestXFail::test_strict_xfail[True]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail[False]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_condition[True]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_condition[False]\", \"testing/test_skipping.py::TestXFail::test_xfail_condition_keyword[True]\", \"testing/test_skipping.py::TestXFail::test_xfail_condition_keyword[False]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_default_from_file[true]\", \"testing/test_skipping.py::TestXFail::test_strict_xfail_default_from_file[false]\", \"testing/test_skipping.py::TestXFailwithSetupTeardown::test_failing_setup_issue9\", \"testing/test_skipping.py::TestXFailwithSetupTeardown::test_failing_teardown_issue9\", \"testing/test_skipping.py::TestSkip::test_skip_class\", \"testing/test_skipping.py::TestSkip::test_skips_on_false_string\", \"testing/test_skipping.py::TestSkip::test_arg_as_reason\", \"testing/test_skipping.py::TestSkip::test_skip_no_reason\", \"testing/test_skipping.py::TestSkip::test_skip_with_reason\", \"testing/test_skipping.py::TestSkip::test_only_skips_marked_test\", \"testing/test_skipping.py::TestSkip::test_strict_and_skip\", \"testing/test_skipping.py::TestSkipif::test_skipif_conditional\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting[\\\"hasattr(sys,\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting[True,\", \"testing/test_skipping.py::TestSkipif::test_skipif_using_platform\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting_multiple[skipif-SKIP-skipped]\", \"testing/test_skipping.py::TestSkipif::test_skipif_reporting_multiple[xfail-XPASS-xpassed]\", \"testing/test_skipping.py::test_skip_not_report_default\", \"testing/test_skipping.py::test_skipif_class\", \"testing/test_skipping.py::test_skipped_reasons_functional\", \"testing/test_skipping.py::test_skipped_folding\", \"testing/test_skipping.py::test_reportchars\", \"testing/test_skipping.py::test_reportchars_error\", \"testing/test_skipping.py::test_reportchars_all\", \"testing/test_skipping.py::test_reportchars_all_error\", \"testing/test_skipping.py::test_errors_in_xfail_skip_expressions\", \"testing/test_skipping.py::test_xfail_skipif_with_globals\", \"testing/test_skipping.py::test_default_markers\", \"testing/test_skipping.py::test_xfail_test_setup_exception\", \"testing/test_skipping.py::test_imperativeskip_on_xfail_test\", \"testing/test_skipping.py::TestBooleanCondition::test_skipif\", \"testing/test_skipping.py::TestBooleanCondition::test_skipif_noreason\", \"testing/test_skipping.py::TestBooleanCondition::test_xfail\", \"testing/test_skipping.py::test_xfail_item\", \"testing/test_skipping.py::test_module_level_skip_error\", \"testing/test_skipping.py::test_module_level_skip_with_allow_module_level\", \"testing/test_skipping.py::test_invalid_skip_keyword_parameter\", \"testing/test_skipping.py::test_mark_xfail_item\", \"testing/test_skipping.py::test_summary_list_after_errors\", \"testing/test_skipping.py::test_relpath_rootdir\"]", "environment_setup_commit": "634cde9506eb1f48dec3ec77974ee8dc952207c6", "test_directives": ["testing/test_skipping.py"], "test_cmd": "pytest -vrA testing/test_skipping.py", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/testing/test_skipping.py b/testing/test_skipping.py\nindex 8fceb37aa..af62642be 100644\n--- a/testing/test_skipping.py\n+++ b/testing/test_skipping.py\n@@ -1230,3 +1230,23 @@ def test_relpath_rootdir(testdir):\n result.stdout.fnmatch_lines(\n [\"SKIPPED [[]1[]] tests/test_1.py:2: unconditional skip\"]\n )\n+\n+def test_dynamic_xfail_marker(request):\n+ \"\"\"\n+ Test that dynamically adding an xfail marker works correctly.\n+ \"\"\"\n+ mark = pytest.mark.xfail(reason=\"xfail\")\n+ request.node.add_marker(mark)\n+ assert 0\n+\n+def test_dynamic_xfail_marker_with_condition(request):\n+ \"\"\"\n+ Test that dynamically adding an xfail marker with a condition works correctly.\n+ \"\"\"\n+ condition = sys.platform == \"win32\"\n+ mark = pytest.mark.xfail(condition, reason=\"xfail on Windows\")\n+ request.node.add_marker(mark)\n+ if condition:\n+ assert 0\n+ else:\n+ assert 1\n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["testing/test_skipping.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/doc/en/example/xfail_demo.py b/doc/en/example/xfail_demo.py\nindex 01e6da1ad..f4b7913f4 100644\n--- a/doc/en/example/xfail_demo.py\n+++ b/doc/en/example/xfail_demo.py\n@@ -31,6 +31,10 @@ def test_hello5():\n def test_hello6():\n pytest.xfail(\"reason\")\n \n+def test_dynamic_xfail(request):\n+ request.node.add_marker(pytest.mark.xfail(reason=\"dynamic xfail\"))\n+ assert 0\n+\n \n @xfail(raises=IndexError)\n def test_hello7():\n", "model_lint_repair_patch": "diff --git a/doc/en/example/xfail_demo.py b/doc/en/example/xfail_demo.py\nindex 01e6da1ad..f4b7913f4 100644\n--- a/doc/en/example/xfail_demo.py\n+++ b/doc/en/example/xfail_demo.py\n@@ -31,6 +31,10 @@ def test_hello5():\n def test_hello6():\n pytest.xfail(\"reason\")\n \n+def test_dynamic_xfail(request):\n+ request.node.add_marker(pytest.mark.xfail(reason=\"dynamic xfail\"))\n+ assert 0\n+\n \n @xfail(raises=IndexError)\n def test_hello7():\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-16046", "base_commit": "ec13e801b820614ff374cb0046092caab8d67249", "patch": "diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py\n--- a/django/utils/numberformat.py\n+++ b/django/utils/numberformat.py\n@@ -25,6 +25,8 @@ def format(\n module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).\n * thousand_sep: Thousand separator symbol (for example \",\")\n \"\"\"\n+ if number is None or number == \"\":\n+ return mark_safe(number)\n use_grouping = (\n use_l10n or (use_l10n is None and settings.USE_L10N)\n ) and settings.USE_THOUSAND_SEPARATOR\n", "test_patch": "diff --git a/tests/utils_tests/test_numberformat.py b/tests/utils_tests/test_numberformat.py\n--- a/tests/utils_tests/test_numberformat.py\n+++ b/tests/utils_tests/test_numberformat.py\n@@ -172,3 +172,7 @@ def __format__(self, specifier, **kwargs):\n \n price = EuroDecimal(\"1.23\")\n self.assertEqual(nformat(price, \",\"), \"\u20ac 1,23\")\n+\n+ def test_empty(self):\n+ self.assertEqual(nformat(\"\", \".\"), \"\")\n+ self.assertEqual(nformat(None, \".\"), \"None\")\n", "problem_statement": "Fix numberformat.py \"string index out of range\" when null\nDescription\n\t\nWhen:\nif str_number[0] == \"-\"\nencounters a number field that's null when formatting for the admin list_display this causes an \nIndexError: string index out of range\nI can attach the proposed fix here, or open a pull request on GitHub if you like?\n", "hints_text": "proposed fix patch\nPlease provide a pull request, including a test.", "created_at": "2022-09-10T13:27:38Z", "version": "4.2", "FAIL_TO_PASS": "[\"test_empty (utils_tests.test_numberformat.TestNumberFormat)\"]", "PASS_TO_PASS": "[\"test_decimal_numbers (utils_tests.test_numberformat.TestNumberFormat)\", \"test_decimal_subclass (utils_tests.test_numberformat.TestNumberFormat)\", \"test_float_numbers (utils_tests.test_numberformat.TestNumberFormat)\", \"test_format_number (utils_tests.test_numberformat.TestNumberFormat)\", \"test_format_string (utils_tests.test_numberformat.TestNumberFormat)\", \"test_large_number (utils_tests.test_numberformat.TestNumberFormat)\"]", "environment_setup_commit": "0fbdb9784da915fce5dcc1fe82bac9b4785749e5", "test_directives": ["utils_tests.test_numberformat"], "test_cmd": "./tests/runtests.py --verbosity 2 utils_tests.test_numberformat", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["utils_tests.test_numberformat"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/utils/formats.py b/django/utils/formats.py\nindex b0a66e4e25..4219ff2589 100644\n--- a/django/utils/formats.py\n+++ b/django/utils/formats.py\n@@ -179,6 +179,8 @@ def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):\n If use_l10n is provided and is not None, it forces the value to\n be localized (or not), overriding the value of settings.USE_L10N.\n \"\"\"\n+ if value is None:\n+ return \"\"\n if use_l10n is None:\n try:\n use_l10n = settings._USE_L10N_INTERNAL\n\ndiff --git a/django/utils/numberformat.py b/django/utils/numberformat.py\nindex 488d6a77cd..4c4519a57a 100644\n--- a/django/utils/numberformat.py\n+++ b/django/utils/numberformat.py\n@@ -25,6 +25,8 @@ def format(\n module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).\n * thousand_sep: Thousand separator symbol (for example \",\")\n \"\"\"\n+ if number is None:\n+ return \"\"\n use_grouping = (\n use_l10n or (use_l10n is None and settings.USE_L10N)\n ) and settings.USE_THOUSAND_SEPARATOR\n", "model_lint_repair_patch": "diff --git a/django/utils/formats.py b/django/utils/formats.py\nindex b0a66e4e25..4219ff2589 100644\n--- a/django/utils/formats.py\n+++ b/django/utils/formats.py\n@@ -179,6 +179,8 @@ def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):\n If use_l10n is provided and is not None, it forces the value to\n be localized (or not), overriding the value of settings.USE_L10N.\n \"\"\"\n+ if value is None:\n+ return \"\"\n if use_l10n is None:\n try:\n use_l10n = settings._USE_L10N_INTERNAL\n\ndiff --git a/django/utils/numberformat.py b/django/utils/numberformat.py\nindex 488d6a77cd..4c4519a57a 100644\n--- a/django/utils/numberformat.py\n+++ b/django/utils/numberformat.py\n@@ -25,6 +25,8 @@ def format(\n module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).\n * thousand_sep: Thousand separator symbol (for example \",\")\n \"\"\"\n+ if number is None:\n+ return \"\"\n use_grouping = (\n use_l10n or (use_l10n is None and settings.USE_L10N)\n ) and settings.USE_THOUSAND_SEPARATOR\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["utils_tests.test_numberformat"]} +{"repo": "django/django", "instance_id": "django__django-12983", "base_commit": "3bc4240d979812bd11365ede04c028ea13fdc8c6", "patch": "diff --git a/django/utils/text.py b/django/utils/text.py\n--- a/django/utils/text.py\n+++ b/django/utils/text.py\n@@ -393,17 +393,18 @@ def unescape_string_literal(s):\n @keep_lazy_text\n def slugify(value, allow_unicode=False):\n \"\"\"\n- Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.\n- Remove characters that aren't alphanumerics, underscores, or hyphens.\n- Convert to lowercase. Also strip leading and trailing whitespace.\n+ Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated\n+ dashes to single dashes. Remove characters that aren't alphanumerics,\n+ underscores, or hyphens. Convert to lowercase. Also strip leading and\n+ trailing whitespace, dashes, and underscores.\n \"\"\"\n value = str(value)\n if allow_unicode:\n value = unicodedata.normalize('NFKC', value)\n else:\n value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')\n- value = re.sub(r'[^\\w\\s-]', '', value.lower()).strip()\n- return re.sub(r'[-\\s]+', '-', value)\n+ value = re.sub(r'[^\\w\\s-]', '', value.lower())\n+ return re.sub(r'[-\\s]+', '-', value).strip('-_')\n \n \n def camel_case_to_spaces(value):\n", "test_patch": "diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py\n--- a/tests/utils_tests/test_text.py\n+++ b/tests/utils_tests/test_text.py\n@@ -192,6 +192,13 @@ def test_slugify(self):\n # given - expected - Unicode?\n ('Hello, World!', 'hello-world', False),\n ('spam & eggs', 'spam-eggs', False),\n+ (' multiple---dash and space ', 'multiple-dash-and-space', False),\n+ ('\\t whitespace-in-value \\n', 'whitespace-in-value', False),\n+ ('underscore_in-value', 'underscore_in-value', False),\n+ ('__strip__underscore-value___', 'strip__underscore-value', False),\n+ ('--strip-dash-value---', 'strip-dash-value', False),\n+ ('__strip-mixed-value---', 'strip-mixed-value', False),\n+ ('_ -strip-mixed-value _-', 'strip-mixed-value', False),\n ('spam & \u0131\u00e7\u00fc\u015f', 'spam-\u0131\u00e7\u00fc\u015f', True),\n ('foo \u0131\u00e7 bar', 'foo-\u0131\u00e7-bar', True),\n (' foo \u0131\u00e7 bar', 'foo-\u0131\u00e7-bar', True),\n", "problem_statement": "Make django.utils.text.slugify() strip dashes and underscores\nDescription\n\t \n\t\t(last modified by Elinaldo do Nascimento Monteiro)\n\t \nBug generation slug\nExample:\nfrom django.utils import text\ntext.slugify(\"___This is a test ---\")\noutput: ___this-is-a-test-\nImprovement after correction\nfrom django.utils import text\ntext.slugify(\"___This is a test ---\")\noutput: this-is-a-test\n\u200bPR\n", "hints_text": "The current version of the patch converts all underscores to dashes which (as discussed on the PR) isn't an obviously desired change. A discussion is needed to see if there's consensus about that change.", "created_at": "2020-05-26T22:02:40Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_slugify (utils_tests.test_text.TestUtilsText)\"]", "PASS_TO_PASS": "[\"test_compress_sequence (utils_tests.test_text.TestUtilsText)\", \"test_format_lazy (utils_tests.test_text.TestUtilsText)\", \"test_get_text_list (utils_tests.test_text.TestUtilsText)\", \"test_get_valid_filename (utils_tests.test_text.TestUtilsText)\", \"test_normalize_newlines (utils_tests.test_text.TestUtilsText)\", \"test_phone2numeric (utils_tests.test_text.TestUtilsText)\", \"test_smart_split (utils_tests.test_text.TestUtilsText)\", \"test_truncate_chars (utils_tests.test_text.TestUtilsText)\", \"test_truncate_chars_html (utils_tests.test_text.TestUtilsText)\", \"test_truncate_html_words (utils_tests.test_text.TestUtilsText)\", \"test_truncate_words (utils_tests.test_text.TestUtilsText)\", \"test_unescape_entities (utils_tests.test_text.TestUtilsText)\", \"test_unescape_entities_deprecated (utils_tests.test_text.TestUtilsText)\", \"test_unescape_string_literal (utils_tests.test_text.TestUtilsText)\", \"test_wrap (utils_tests.test_text.TestUtilsText)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["utils_tests.test_text"], "test_cmd": "./tests/runtests.py --verbosity 2 utils_tests.test_text", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py\nindex 9dbf9367c3..df3e6345e2 100644\n--- a/tests/utils_tests/test_text.py\n+++ b/tests/utils_tests/test_text.py\n@@ -197,6 +197,7 @@ class TestUtilsText(SimpleTestCase):\n (' foo \u0131\u00e7 bar', 'foo-\u0131\u00e7-bar', True),\n ('\u4f60\u597d', '\u4f60\u597d', True),\n ('\u0130stanbul', 'istanbul', True),\n+ ('___This is a test ---', 'this-is-a-test', False), # New test case\n )\n for value, output, is_unicode in items:\n self.assertEqual(text.slugify(value, allow_unicode=is_unicode), output)\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["utils_tests.test_text"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/utils/text.py b/django/utils/text.py\nindex fb5f6298c4..258168ed7b 100644\n--- a/django/utils/text.py\n+++ b/django/utils/text.py\n@@ -395,7 +395,8 @@ def slugify(value, allow_unicode=False):\n \"\"\"\n Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.\n Remove characters that aren't alphanumerics, underscores, or hyphens.\n- Convert to lowercase. Also strip leading and trailing whitespace.\n+ Convert to lowercase. Also strip leading and trailing whitespace, dashes,\n+ and underscores.\n \"\"\"\n value = str(value)\n if allow_unicode:\n@@ -403,7 +404,8 @@ def slugify(value, allow_unicode=False):\n else:\n value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')\n value = re.sub(r'[^\\w\\s-]', '', value.lower()).strip()\n- return re.sub(r'[-\\s]+', '-', value)\n+ value = re.sub(r'[-\\s]+', '-', value)\n+ return value.strip('-_')\n \n \n def camel_case_to_spaces(value):\n", "model_lint_repair_patch": "diff --git a/django/utils/text.py b/django/utils/text.py\nindex fb5f6298c4..258168ed7b 100644\n--- a/django/utils/text.py\n+++ b/django/utils/text.py\n@@ -395,7 +395,8 @@ def slugify(value, allow_unicode=False):\n \"\"\"\n Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.\n Remove characters that aren't alphanumerics, underscores, or hyphens.\n- Convert to lowercase. Also strip leading and trailing whitespace.\n+ Convert to lowercase. Also strip leading and trailing whitespace, dashes,\n+ and underscores.\n \"\"\"\n value = str(value)\n if allow_unicode:\n@@ -403,7 +404,8 @@ def slugify(value, allow_unicode=False):\n else:\n value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')\n value = re.sub(r'[^\\w\\s-]', '', value.lower()).strip()\n- return re.sub(r'[-\\s]+', '-', value)\n+ value = re.sub(r'[-\\s]+', '-', value)\n+ return value.strip('-_')\n \n \n def camel_case_to_spaces(value):\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["utils_tests.test_text"]} +{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-14894", "base_commit": "fdbaa58acbead5a254f2e6d597dc1ab3b947f4c6", "patch": "diff --git a/sklearn/svm/base.py b/sklearn/svm/base.py\n--- a/sklearn/svm/base.py\n+++ b/sklearn/svm/base.py\n@@ -287,11 +287,14 @@ def _sparse_fit(self, X, y, sample_weight, solver_type, kernel,\n n_SV = self.support_vectors_.shape[0]\n \n dual_coef_indices = np.tile(np.arange(n_SV), n_class)\n- dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,\n- dual_coef_indices.size / n_class)\n- self.dual_coef_ = sp.csr_matrix(\n- (dual_coef_data, dual_coef_indices, dual_coef_indptr),\n- (n_class, n_SV))\n+ if not n_SV:\n+ self.dual_coef_ = sp.csr_matrix([])\n+ else:\n+ dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,\n+ dual_coef_indices.size / n_class)\n+ self.dual_coef_ = sp.csr_matrix(\n+ (dual_coef_data, dual_coef_indices, dual_coef_indptr),\n+ (n_class, n_SV))\n \n def predict(self, X):\n \"\"\"Perform regression on samples in X.\n", "test_patch": "diff --git a/sklearn/svm/tests/test_svm.py b/sklearn/svm/tests/test_svm.py\n--- a/sklearn/svm/tests/test_svm.py\n+++ b/sklearn/svm/tests/test_svm.py\n@@ -690,6 +690,19 @@ def test_sparse_precomputed():\n assert \"Sparse precomputed\" in str(e)\n \n \n+def test_sparse_fit_support_vectors_empty():\n+ # Regression test for #14893\n+ X_train = sparse.csr_matrix([[0, 1, 0, 0],\n+ [0, 0, 0, 1],\n+ [0, 0, 1, 0],\n+ [0, 0, 0, 1]])\n+ y_train = np.array([0.04, 0.04, 0.10, 0.16])\n+ model = svm.SVR(kernel='linear')\n+ model.fit(X_train, y_train)\n+ assert not model.support_vectors_.data.size\n+ assert not model.dual_coef_.data.size\n+\n+\n def test_linearsvc_parameters():\n # Test possible parameter combinations in LinearSVC\n # Generate list of possible parameter combinations\n", "problem_statement": "ZeroDivisionError in _sparse_fit for SVM with empty support_vectors_\n#### Description\r\nWhen using sparse data, in the case where the support_vectors_ attribute is be empty, _fit_sparse gives a ZeroDivisionError\r\n\r\n#### Steps/Code to Reproduce\r\n```\r\nimport numpy as np\r\nimport scipy\r\nimport sklearn\r\nfrom sklearn.svm import SVR\r\nx_train = np.array([[0, 1, 0, 0],\r\n[0, 0, 0, 1],\r\n[0, 0, 1, 0],\r\n[0, 0, 0, 1]])\r\ny_train = np.array([0.04, 0.04, 0.10, 0.16])\r\nmodel = SVR(C=316.227766017, cache_size=200, coef0=0.0, degree=3, epsilon=0.1,\r\n \t gamma=1.0, kernel='linear', max_iter=15000,\r\n \t shrinking=True, tol=0.001, verbose=False)\r\n# dense x_train has no error\r\nmodel.fit(x_train, y_train)\r\n\r\n# convert to sparse\r\nxtrain= scipy.sparse.csr_matrix(x_train)\r\nmodel.fit(xtrain, y_train)\r\n\r\n```\r\n#### Expected Results\r\nNo error is thrown and `self.dual_coef_ = sp.csr_matrix([])`\r\n\r\n#### Actual Results\r\n```\r\nTraceback (most recent call last):\r\n File \"\", line 1, in \r\n File \"/usr/local/lib/python3.5/dist-packages/sklearn/svm/base.py\", line 209, in fit\r\n fit(X, y, sample_weight, solver_type, kernel, random_seed=seed)\r\n File \"/usr/local/lib/python3.5/dist-packages/sklearn/svm/base.py\", line 302, in _sparse_fit\r\n dual_coef_indices.size / n_class)\r\nZeroDivisionError: float division by zero\r\n```\r\n\r\n#### Versions\r\n```\r\n>>> sklearn.show_versions() \r\n\r\nSystem:\r\nexecutable: /usr/bin/python3\r\n python: 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609]\r\n machine: Linux-4.15.0-58-generic-x86_64-with-Ubuntu-16.04-xenial\r\n\r\nPython deps:\r\n numpy: 1.17.0\r\n Cython: None\r\n pip: 19.2.1\r\n pandas: 0.22.0\r\n sklearn: 0.21.3\r\n scipy: 1.3.0\r\nsetuptools: 40.4.3\r\n```\n", "hints_text": "", "created_at": "2019-09-05T17:41:11Z", "version": "0.22", "FAIL_TO_PASS": "[\"sklearn/svm/tests/test_svm.py::test_sparse_fit_support_vectors_empty\"]", "PASS_TO_PASS": "[\"sklearn/svm/tests/test_svm.py::test_libsvm_parameters\", \"sklearn/svm/tests/test_svm.py::test_libsvm_iris\", \"sklearn/svm/tests/test_svm.py::test_precomputed\", \"sklearn/svm/tests/test_svm.py::test_svr\", \"sklearn/svm/tests/test_svm.py::test_linearsvr\", \"sklearn/svm/tests/test_svm.py::test_linearsvr_fit_sampleweight\", \"sklearn/svm/tests/test_svm.py::test_svr_errors\", \"sklearn/svm/tests/test_svm.py::test_oneclass\", \"sklearn/svm/tests/test_svm.py::test_oneclass_decision_function\", \"sklearn/svm/tests/test_svm.py::test_oneclass_score_samples\", \"sklearn/svm/tests/test_svm.py::test_tweak_params\", \"sklearn/svm/tests/test_svm.py::test_probability\", \"sklearn/svm/tests/test_svm.py::test_decision_function\", \"sklearn/svm/tests/test_svm.py::test_decision_function_shape\", \"sklearn/svm/tests/test_svm.py::test_svr_predict\", \"sklearn/svm/tests/test_svm.py::test_weight\", \"sklearn/svm/tests/test_svm.py::test_svm_classifier_sided_sample_weight[estimator0]\", \"sklearn/svm/tests/test_svm.py::test_svm_classifier_sided_sample_weight[estimator1]\", \"sklearn/svm/tests/test_svm.py::test_svm_regressor_sided_sample_weight[estimator0]\", \"sklearn/svm/tests/test_svm.py::test_svm_regressor_sided_sample_weight[estimator1]\", \"sklearn/svm/tests/test_svm.py::test_svm_equivalence_sample_weight_C\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-SVR]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-NuSVR]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-OneClassSVM]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-SVR]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-NuSVR]\", \"sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-OneClassSVM]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-1-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-1-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-2-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-2-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-1-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-1-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-2-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-2-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-NuSVR]\", \"sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-SVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-NuSVR]\", \"sklearn/svm/tests/test_svm.py::test_auto_weight\", \"sklearn/svm/tests/test_svm.py::test_bad_input\", \"sklearn/svm/tests/test_svm.py::test_svm_gamma_error[SVC-data0]\", \"sklearn/svm/tests/test_svm.py::test_svm_gamma_error[NuSVC-data1]\", \"sklearn/svm/tests/test_svm.py::test_svm_gamma_error[SVR-data2]\", \"sklearn/svm/tests/test_svm.py::test_svm_gamma_error[NuSVR-data3]\", \"sklearn/svm/tests/test_svm.py::test_svm_gamma_error[OneClassSVM-data4]\", \"sklearn/svm/tests/test_svm.py::test_unicode_kernel\", \"sklearn/svm/tests/test_svm.py::test_sparse_precomputed\", \"sklearn/svm/tests/test_svm.py::test_linearsvc_parameters\", \"sklearn/svm/tests/test_svm.py::test_linearsvx_loss_penalty_deprecations\", \"sklearn/svm/tests/test_svm.py::test_linear_svx_uppercase_loss_penality_raises_error\", \"sklearn/svm/tests/test_svm.py::test_linearsvc\", \"sklearn/svm/tests/test_svm.py::test_linearsvc_crammer_singer\", \"sklearn/svm/tests/test_svm.py::test_linearsvc_fit_sampleweight\", \"sklearn/svm/tests/test_svm.py::test_crammer_singer_binary\", \"sklearn/svm/tests/test_svm.py::test_linearsvc_iris\", \"sklearn/svm/tests/test_svm.py::test_dense_liblinear_intercept_handling\", \"sklearn/svm/tests/test_svm.py::test_liblinear_set_coef\", \"sklearn/svm/tests/test_svm.py::test_immutable_coef_property\", \"sklearn/svm/tests/test_svm.py::test_linearsvc_verbose\", \"sklearn/svm/tests/test_svm.py::test_svc_clone_with_callable_kernel\", \"sklearn/svm/tests/test_svm.py::test_svc_bad_kernel\", \"sklearn/svm/tests/test_svm.py::test_timeout\", \"sklearn/svm/tests/test_svm.py::test_unfitted\", \"sklearn/svm/tests/test_svm.py::test_consistent_proba\", \"sklearn/svm/tests/test_svm.py::test_linear_svm_convergence_warnings\", \"sklearn/svm/tests/test_svm.py::test_svr_coef_sign\", \"sklearn/svm/tests/test_svm.py::test_linear_svc_intercept_scaling\", \"sklearn/svm/tests/test_svm.py::test_lsvc_intercept_scaling_zero\", \"sklearn/svm/tests/test_svm.py::test_hasattr_predict_proba\", \"sklearn/svm/tests/test_svm.py::test_decision_function_shape_two_class\", \"sklearn/svm/tests/test_svm.py::test_ovr_decision_function\", \"sklearn/svm/tests/test_svm.py::test_svc_invalid_break_ties_param[SVC]\", \"sklearn/svm/tests/test_svm.py::test_svc_invalid_break_ties_param[NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_svc_ovr_tie_breaking[SVC]\", \"sklearn/svm/tests/test_svm.py::test_svc_ovr_tie_breaking[NuSVC]\", \"sklearn/svm/tests/test_svm.py::test_gamma_auto\", \"sklearn/svm/tests/test_svm.py::test_gamma_scale\", \"sklearn/svm/tests/test_svm.py::test_n_support_oneclass_svr\"]", "environment_setup_commit": "7e85a6d1f038bbb932b36f18d75df6be937ed00d", "test_directives": ["sklearn/svm/tests/test_svm.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v sklearn/svm/tests/test_svm.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/sklearn/svm/tests/test_sparse.py b/sklearn/svm/tests/test_sparse.py\nindex 7cf6e8af2..a90e6bf88 100644\n--- a/sklearn/svm/tests/test_sparse.py\n+++ b/sklearn/svm/tests/test_sparse.py\n@@ -345,6 +345,21 @@ def test_sparse_svc_clone_with_callable_kernel():\n # b.decision_function(X_sp) # XXX : should be supported\n \n \n+def test_sparse_svr_with_empty_support_vectors():\n+ # Test that sparse SVR does not raise ZeroDivisionError with empty support_vectors_\n+ x_train = np.array([[0, 1, 0, 0],\n+ [0, 0, 0, 1],\n+ [0, 0, 1, 0],\n+ [0, 0, 0, 1]])\n+ y_train = np.array([0.04, 0.04, 0.10, 0.16])\n+ model = svm.SVR(C=316.227766017, cache_size=200, coef0=0.0, degree=3, epsilon=0.1,\n+ gamma=1.0, kernel='linear', max_iter=15000,\n+ shrinking=True, tol=0.001, verbose=False)\n+ xtrain_sparse = sparse.csr_matrix(x_train)\n+ model.fit(xtrain_sparse, y_train)\n+ assert model.dual_coef_.shape == (1, 0)\n+\n+\n def test_timeout():\n sp = svm.SVC(C=1, kernel=lambda x, y: x * y.T,\n probability=True, random_state=0, max_iter=1)\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["sklearn/svm/tests/test_sparse.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sklearn/svm/base.py b/sklearn/svm/base.py\nindex 64cebe837..e59affefb 100644\n--- a/sklearn/svm/base.py\n+++ b/sklearn/svm/base.py\n@@ -286,12 +286,15 @@ class BaseLibSVM(BaseEstimator, metaclass=ABCMeta):\n n_class = 1\n n_SV = self.support_vectors_.shape[0]\n \n- dual_coef_indices = np.tile(np.arange(n_SV), n_class)\n- dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,\n- dual_coef_indices.size / n_class)\n- self.dual_coef_ = sp.csr_matrix(\n- (dual_coef_data, dual_coef_indices, dual_coef_indptr),\n- (n_class, n_SV))\n+ if n_SV == 0:\n+ self.dual_coef_ = sp.csr_matrix((n_class, 0))\n+ else:\n+ dual_coef_indices = np.tile(np.arange(n_SV), n_class)\n+ dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,\n+ dual_coef_indices.size / n_class)\n+ self.dual_coef_ = sp.csr_matrix(\n+ (dual_coef_data, dual_coef_indices, dual_coef_indptr),\n+ (n_class, n_SV))\n \n def predict(self, X):\n \"\"\"Perform regression on samples in X.\n", "model_lint_repair_patch": "diff --git a/sklearn/svm/base.py b/sklearn/svm/base.py\nindex 64cebe837..e59affefb 100644\n--- a/sklearn/svm/base.py\n+++ b/sklearn/svm/base.py\n@@ -286,12 +286,15 @@ class BaseLibSVM(BaseEstimator, metaclass=ABCMeta):\n n_class = 1\n n_SV = self.support_vectors_.shape[0]\n \n- dual_coef_indices = np.tile(np.arange(n_SV), n_class)\n- dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,\n- dual_coef_indices.size / n_class)\n- self.dual_coef_ = sp.csr_matrix(\n- (dual_coef_data, dual_coef_indices, dual_coef_indptr),\n- (n_class, n_SV))\n+ if n_SV == 0:\n+ self.dual_coef_ = sp.csr_matrix((n_class, 0))\n+ else:\n+ dual_coef_indices = np.tile(np.arange(n_SV), n_class)\n+ dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,\n+ dual_coef_indices.size / n_class)\n+ self.dual_coef_ = sp.csr_matrix(\n+ (dual_coef_data, dual_coef_indices, dual_coef_indptr),\n+ (n_class, n_SV))\n \n def predict(self, X):\n \"\"\"Perform regression on samples in X.\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sklearn/svm/tests/test_sparse.py"]} +{"repo": "django/django", "instance_id": "django__django-17087", "base_commit": "4a72da71001f154ea60906a2f74898d32b7322a7", "patch": "diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py\n--- a/django/db/migrations/serializer.py\n+++ b/django/db/migrations/serializer.py\n@@ -168,7 +168,7 @@ def serialize(self):\n ):\n klass = self.value.__self__\n module = klass.__module__\n- return \"%s.%s.%s\" % (module, klass.__name__, self.value.__name__), {\n+ return \"%s.%s.%s\" % (module, klass.__qualname__, self.value.__name__), {\n \"import %s\" % module\n }\n # Further error checking\n", "test_patch": "diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py\n--- a/tests/migrations/test_writer.py\n+++ b/tests/migrations/test_writer.py\n@@ -211,6 +211,10 @@ class NestedChoices(models.TextChoices):\n X = \"X\", \"X value\"\n Y = \"Y\", \"Y value\"\n \n+ @classmethod\n+ def method(cls):\n+ return cls.X\n+\n def safe_exec(self, string, value=None):\n d = {}\n try:\n@@ -468,6 +472,15 @@ def test_serialize_nested_class(self):\n ),\n )\n \n+ def test_serialize_nested_class_method(self):\n+ self.assertSerializedResultEqual(\n+ self.NestedChoices.method,\n+ (\n+ \"migrations.test_writer.WriterTests.NestedChoices.method\",\n+ {\"import migrations.test_writer\"},\n+ ),\n+ )\n+\n def test_serialize_uuid(self):\n self.assertSerializedEqual(uuid.uuid1())\n self.assertSerializedEqual(uuid.uuid4())\n", "problem_statement": "Class methods from nested classes cannot be used as Field.default.\nDescription\n\t \n\t\t(last modified by Mariusz Felisiak)\n\t \nGiven the following model:\n \nclass Profile(models.Model):\n\tclass Capability(models.TextChoices):\n\t\tBASIC = (\"BASIC\", \"Basic\")\n\t\tPROFESSIONAL = (\"PROFESSIONAL\", \"Professional\")\n\t\t\n\t\t@classmethod\n\t\tdef default(cls) -> list[str]:\n\t\t\treturn [cls.BASIC]\n\tcapabilities = ArrayField(\n\t\tmodels.CharField(choices=Capability.choices, max_length=30, blank=True),\n\t\tnull=True,\n\t\tdefault=Capability.default\n\t)\nThe resulting migration contained the following:\n # ...\n\t migrations.AddField(\n\t\t model_name='profile',\n\t\t name='capabilities',\n\t\t field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, choices=[('BASIC', 'Basic'), ('PROFESSIONAL', 'Professional')], max_length=30), default=appname.models.Capability.default, null=True, size=None),\n\t ),\n # ...\nAs you can see, migrations.AddField is passed as argument \"default\" a wrong value \"appname.models.Capability.default\", which leads to an error when trying to migrate. The right value should be \"appname.models.Profile.Capability.default\".\n", "hints_text": "Thanks for the report. It seems that FunctionTypeSerializer should use __qualname__ instead of __name__: django/db/migrations/serializer.py diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index d88cda6e20..06657ebaab 100644 a b class FunctionTypeSerializer(BaseSerializer): 168168 ): 169169 klass = self.value.__self__ 170170 module = klass.__module__ 171 return \"%s.%s.%s\" % (module, klass.__name__, self.value.__name__), { 171 return \"%s.%s.%s\" % (module, klass.__qualname__, self.value.__name__), { 172172 \"import %s\" % module 173173 } 174174 # Further error checking Would you like to prepare a patch? (regression test is required)\nAlso to nitpick the terminology: Capability is a nested class, not a subclass. (fyi for anyone preparing tests/commit message)\nReplying to David Sanders: Also to nitpick the terminology: Capability is a nested class, not a subclass. (fyi for anyone preparing tests/commit message) You're right, that was inaccurate. Thanks for having fixed the title\nReplying to Mariusz Felisiak: Thanks for the report. It seems that FunctionTypeSerializer should use __qualname__ instead of __name__: django/db/migrations/serializer.py diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index d88cda6e20..06657ebaab 100644 a b class FunctionTypeSerializer(BaseSerializer): 168168 ): 169169 klass = self.value.__self__ 170170 module = klass.__module__ 171 return \"%s.%s.%s\" % (module, klass.__name__, self.value.__name__), { 171 return \"%s.%s.%s\" % (module, klass.__qualname__, self.value.__name__), { 172172 \"import %s\" % module 173173 } 174174 # Further error checking Would you like to prepare a patch? (regression test is required) I would be very happy to prepare a patch, i will do my best to write a test that's coherent with the current suite\nI would be very happy to prepare a patch, i will do my best to write a test that's coherent with the current suite You can check tests in tests.migrations.test_writer.WriterTests, e.g. test_serialize_nested_class().", "created_at": "2023-07-17T20:28:41Z", "version": "5.0", "FAIL_TO_PASS": "[\"test_serialize_nested_class_method (migrations.test_writer.WriterTests.test_serialize_nested_class_method)\"]", "PASS_TO_PASS": "[\"test_args_kwargs_signature (migrations.test_writer.OperationWriterTests.test_args_kwargs_signature)\", \"test_args_signature (migrations.test_writer.OperationWriterTests.test_args_signature)\", \"test_empty_signature (migrations.test_writer.OperationWriterTests.test_empty_signature)\", \"test_expand_args_signature (migrations.test_writer.OperationWriterTests.test_expand_args_signature)\", \"test_kwargs_signature (migrations.test_writer.OperationWriterTests.test_kwargs_signature)\", \"test_multiline_args_signature (migrations.test_writer.OperationWriterTests.test_multiline_args_signature)\", \"test_nested_args_signature (migrations.test_writer.OperationWriterTests.test_nested_args_signature)\", \"test_nested_operation_expand_args_signature (migrations.test_writer.OperationWriterTests.test_nested_operation_expand_args_signature)\", \"test_custom_operation (migrations.test_writer.WriterTests.test_custom_operation)\", \"test_deconstruct_class_arguments (migrations.test_writer.WriterTests.test_deconstruct_class_arguments)\", \"Test comments at top of file.\", \"test_migration_path (migrations.test_writer.WriterTests.test_migration_path)\", \"django.db.models shouldn't be imported if unused.\", \"test_register_non_serializer (migrations.test_writer.WriterTests.test_register_non_serializer)\", \"test_register_serializer (migrations.test_writer.WriterTests.test_register_serializer)\", \"test_serialize_builtin_types (migrations.test_writer.WriterTests.test_serialize_builtin_types)\", \"test_serialize_builtins (migrations.test_writer.WriterTests.test_serialize_builtins)\", \"test_serialize_choices (migrations.test_writer.WriterTests.test_serialize_choices)\", \"Ticket #22943: Test serialization of class-based validators, including\", \"test_serialize_collections (migrations.test_writer.WriterTests.test_serialize_collections)\", \"Make sure compiled regex can be serialized.\", \"test_serialize_complex_func_index (migrations.test_writer.WriterTests.test_serialize_complex_func_index)\", \"test_serialize_constants (migrations.test_writer.WriterTests.test_serialize_constants)\", \"test_serialize_datetime (migrations.test_writer.WriterTests.test_serialize_datetime)\", \"Ticket #22679: makemigrations generates invalid code for (an empty\", \"test_serialize_enum_flags (migrations.test_writer.WriterTests.test_serialize_enum_flags)\", \"test_serialize_enums (migrations.test_writer.WriterTests.test_serialize_enums)\", \"test_serialize_fields (migrations.test_writer.WriterTests.test_serialize_fields)\", \"test_serialize_frozensets (migrations.test_writer.WriterTests.test_serialize_frozensets)\", \"test_serialize_functions (migrations.test_writer.WriterTests.test_serialize_functions)\", \"test_serialize_functools_partial (migrations.test_writer.WriterTests.test_serialize_functools_partial)\", \"test_serialize_functools_partialmethod (migrations.test_writer.WriterTests.test_serialize_functools_partialmethod)\", \"test_serialize_iterators (migrations.test_writer.WriterTests.test_serialize_iterators)\", \"test_serialize_lazy_objects (migrations.test_writer.WriterTests.test_serialize_lazy_objects)\", \"A reference in a local scope can't be serialized.\", \"test_serialize_managers (migrations.test_writer.WriterTests.test_serialize_managers)\", \"test_serialize_multiline_strings (migrations.test_writer.WriterTests.test_serialize_multiline_strings)\", \"test_serialize_nested_class (migrations.test_writer.WriterTests.test_serialize_nested_class)\", \"test_serialize_numbers (migrations.test_writer.WriterTests.test_serialize_numbers)\", \"test_serialize_path_like (migrations.test_writer.WriterTests.test_serialize_path_like)\", \"test_serialize_pathlib (migrations.test_writer.WriterTests.test_serialize_pathlib)\", \"test_serialize_range (migrations.test_writer.WriterTests.test_serialize_range)\", \"test_serialize_set (migrations.test_writer.WriterTests.test_serialize_set)\", \"test_serialize_settings (migrations.test_writer.WriterTests.test_serialize_settings)\", \"test_serialize_strings (migrations.test_writer.WriterTests.test_serialize_strings)\", \"test_serialize_timedelta (migrations.test_writer.WriterTests.test_serialize_timedelta)\", \"test_serialize_type_model (migrations.test_writer.WriterTests.test_serialize_type_model)\", \"test_serialize_type_none (migrations.test_writer.WriterTests.test_serialize_type_none)\", \"An unbound method used within a class body can be serialized.\", \"test_serialize_uuid (migrations.test_writer.WriterTests.test_serialize_uuid)\", \"Tests serializing a simple migration.\", \"test_sorted_dependencies (migrations.test_writer.WriterTests.test_sorted_dependencies)\", \"#24155 - Tests ordering of imports.\"]", "environment_setup_commit": "4a72da71001f154ea60906a2f74898d32b7322a7", "test_directives": ["migrations.test_writer"], "test_cmd": "./tests/runtests.py --verbosity 2 migrations.test_writer", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py\nindex fe8526a480..63dedd3b78 100644\n--- a/tests/model_fields/tests.py\n+++ b/tests/model_fields/tests.py\n@@ -35,7 +35,25 @@ class BasicFieldTests(SimpleTestCase):\n form_field = model_field.formfield(show_hidden_initial=True)\n self.assertTrue(form_field.show_hidden_initial)\n \n- form_field = model_field.formfield(show_hidden_initial=False)\n+ def test_nested_class_method_as_default(self):\n+ \"\"\"\n+ Ensure that nested class methods can be used as Field.default.\n+ \"\"\"\n+ class Profile(models.Model):\n+ class Capability(models.TextChoices):\n+ BASIC = (\"BASIC\", \"Basic\")\n+ PROFESSIONAL = (\"PROFESSIONAL\", \"Professional\")\n+\n+ @classmethod\n+ def default(cls) -> list[str]:\n+ return [cls.BASIC]\n+\n+ capabilities = models.JSONField(default=Capability.default)\n+\n+ field = Profile._meta.get_field(\"capabilities\")\n+ self.assertEqual(field.default, Profile.Capability.default)\n+\n+ form_field = field.formfield(show_hidden_initial=False)\n self.assertFalse(form_field.show_hidden_initial)\n \n def test_field_repr(self):\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["field_defaults.models"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex 64e5ff53ea..ac414be0ba 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -174,18 +174,18 @@ class Options:\n def contribute_to_class(self, cls, name):\n from django.db import connection\n from django.db.backends.utils import truncate_name\n-\n+ \n cls._meta = self\n self.model = cls\n # First, construct the default values for these options.\n self.object_name = cls.__name__\n self.model_name = self.object_name.lower()\n self.verbose_name = camel_case_to_spaces(self.object_name)\n-\n+ \n # Store the original user-defined values for each option,\n # for use when serializing the model definition\n self.original_attrs = {}\n-\n+ \n # Next, apply any overridden values from 'class Meta'.\n if self.meta:\n meta_attrs = self.meta.__dict__.copy()\n@@ -197,12 +197,12 @@ class Options:\n del meta_attrs[name]\n for attr_name in DEFAULT_NAMES:\n if attr_name in meta_attrs:\n- setattr(self, attr_name, meta_attrs.pop(attr_name))\n+ setattr(self, attr_name, self._serialize_default(meta_attrs.pop(attr_name)))\n self.original_attrs[attr_name] = getattr(self, attr_name)\n elif hasattr(self.meta, attr_name):\n- setattr(self, attr_name, getattr(self.meta, attr_name))\n+ setattr(self, attr_name, self._serialize_default(getattr(self.meta, attr_name)))\n self.original_attrs[attr_name] = getattr(self, attr_name)\n-\n+ \n self.unique_together = normalize_together(self.unique_together)\n self.index_together = normalize_together(self.index_together)\n if self.index_together:\n@@ -217,15 +217,15 @@ class Options:\n for attr_name in {\"constraints\", \"indexes\"}:\n objs = getattr(self, attr_name, [])\n setattr(self, attr_name, self._format_names_with_class(cls, objs))\n-\n+ \n # verbose_name_plural is a special case because it uses a 's'\n # by default.\n if self.verbose_name_plural is None:\n self.verbose_name_plural = format_lazy(\"{}s\", self.verbose_name)\n-\n+ \n # order_with_respect_and ordering are mutually exclusive.\n self._ordering_clash = bool(self.ordering and self.order_with_respect_to)\n-\n+ \n # Any leftover attributes must be invalid.\n if meta_attrs != {}:\n raise TypeError(\n@@ -234,7 +234,7 @@ class Options:\n else:\n self.verbose_name_plural = format_lazy(\"{}s\", self.verbose_name)\n del self.meta\n-\n+ \n # If the db_table wasn't provided, use the app_label + model_name.\n if not self.db_table:\n self.db_table = \"%s_%s\" % (self.app_label, self.model_name)\n@@ -284,6 +284,13 @@ class Options:\n f\"subclass AutoField.\"\n )\n return pk_class\n+ \n+ def _serialize_default(self, default):\n+ if isinstance(default, types.MethodType):\n+ method_self = default.__self__\n+ if method_self:\n+ return f\"{method_self.__module__}.{method_self.__class__.__qualname__}.{default.__name__}\"\n+ return default\n \n def _prepare(self, model):\n if self.order_with_respect_to:\n", "model_lint_repair_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex 64e5ff53ea..c04d1fc5b3 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -174,18 +174,18 @@ class Options:\n def contribute_to_class(self, cls, name):\n from django.db import connection\n from django.db.backends.utils import truncate_name\n-\n+ \n cls._meta = self\n self.model = cls\n # First, construct the default values for these options.\n self.object_name = cls.__name__\n self.model_name = self.object_name.lower()\n self.verbose_name = camel_case_to_spaces(self.object_name)\n-\n+ \n # Store the original user-defined values for each option,\n # for use when serializing the model definition\n self.original_attrs = {}\n-\n+ \n # Next, apply any overridden values from 'class Meta'.\n if self.meta:\n meta_attrs = self.meta.__dict__.copy()\n@@ -197,12 +197,12 @@ class Options:\n del meta_attrs[name]\n for attr_name in DEFAULT_NAMES:\n if attr_name in meta_attrs:\n- setattr(self, attr_name, meta_attrs.pop(attr_name))\n+ setattr(self, attr_name, self._serialize_default(meta_attrs.pop(attr_name)))\n self.original_attrs[attr_name] = getattr(self, attr_name)\n elif hasattr(self.meta, attr_name):\n- setattr(self, attr_name, getattr(self.meta, attr_name))\n+ setattr(self, attr_name, self._serialize_default(getattr(self.meta, attr_name)))\n self.original_attrs[attr_name] = getattr(self, attr_name)\n-\n+ \n self.unique_together = normalize_together(self.unique_together)\n self.index_together = normalize_together(self.index_together)\n if self.index_together:\n@@ -217,15 +217,15 @@ class Options:\n for attr_name in {\"constraints\", \"indexes\"}:\n objs = getattr(self, attr_name, [])\n setattr(self, attr_name, self._format_names_with_class(cls, objs))\n-\n+ \n # verbose_name_plural is a special case because it uses a 's'\n # by default.\n if self.verbose_name_plural is None:\n self.verbose_name_plural = format_lazy(\"{}s\", self.verbose_name)\n-\n+ \n # order_with_respect_and ordering are mutually exclusive.\n self._ordering_clash = bool(self.ordering and self.order_with_respect_to)\n-\n+ \n # Any leftover attributes must be invalid.\n if meta_attrs != {}:\n raise TypeError(\n@@ -234,7 +234,7 @@ class Options:\n else:\n self.verbose_name_plural = format_lazy(\"{}s\", self.verbose_name)\n del self.meta\n-\n+ \n # If the db_table wasn't provided, use the app_label + model_name.\n if not self.db_table:\n self.db_table = \"%s_%s\" % (self.app_label, self.model_name)\n@@ -284,6 +284,14 @@ class Options:\n f\"subclass AutoField.\"\n )\n return pk_class\n+ \n+ def _serialize_default(self, default):\n+ import types\n+ if isinstance(default, types.MethodType):\n+ method_self = default.__self__\n+ if method_self:\n+ return f\"{method_self.__module__}.{method_self.__class__.__qualname__}.{default.__name__}\"\n+ return default\n \n def _prepare(self, model):\n if self.order_with_respect_to:\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["field_defaults.models"]} +{"repo": "django/django", "instance_id": "django__django-17051", "base_commit": "b7a17b0ea0a2061bae752a3a2292007d41825814", "patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -1837,12 +1837,17 @@ def _batched_insert(\n inserted_rows = []\n bulk_return = connection.features.can_return_rows_from_bulk_insert\n for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]:\n- if bulk_return and on_conflict is None:\n+ if bulk_return and (\n+ on_conflict is None or on_conflict == OnConflict.UPDATE\n+ ):\n inserted_rows.extend(\n self._insert(\n item,\n fields=fields,\n using=self.db,\n+ on_conflict=on_conflict,\n+ update_fields=update_fields,\n+ unique_fields=unique_fields,\n returning_fields=self.model._meta.db_returning_fields,\n )\n )\n", "test_patch": "diff --git a/tests/bulk_create/tests.py b/tests/bulk_create/tests.py\n--- a/tests/bulk_create/tests.py\n+++ b/tests/bulk_create/tests.py\n@@ -582,12 +582,16 @@ def _test_update_conflicts_two_fields(self, unique_fields):\n TwoFields(f1=1, f2=1, name=\"c\"),\n TwoFields(f1=2, f2=2, name=\"d\"),\n ]\n- TwoFields.objects.bulk_create(\n+ results = TwoFields.objects.bulk_create(\n conflicting_objects,\n update_conflicts=True,\n unique_fields=unique_fields,\n update_fields=[\"name\"],\n )\n+ self.assertEqual(len(results), len(conflicting_objects))\n+ if connection.features.can_return_rows_from_bulk_insert:\n+ for instance in results:\n+ self.assertIsNotNone(instance.pk)\n self.assertEqual(TwoFields.objects.count(), 2)\n self.assertCountEqual(\n TwoFields.objects.values(\"f1\", \"f2\", \"name\"),\n@@ -619,7 +623,6 @@ def test_update_conflicts_unique_fields_pk(self):\n TwoFields(f1=2, f2=2, name=\"b\"),\n ]\n )\n- self.assertEqual(TwoFields.objects.count(), 2)\n \n obj1 = TwoFields.objects.get(f1=1)\n obj2 = TwoFields.objects.get(f1=2)\n@@ -627,12 +630,16 @@ def test_update_conflicts_unique_fields_pk(self):\n TwoFields(pk=obj1.pk, f1=3, f2=3, name=\"c\"),\n TwoFields(pk=obj2.pk, f1=4, f2=4, name=\"d\"),\n ]\n- TwoFields.objects.bulk_create(\n+ results = TwoFields.objects.bulk_create(\n conflicting_objects,\n update_conflicts=True,\n unique_fields=[\"pk\"],\n update_fields=[\"name\"],\n )\n+ self.assertEqual(len(results), len(conflicting_objects))\n+ if connection.features.can_return_rows_from_bulk_insert:\n+ for instance in results:\n+ self.assertIsNotNone(instance.pk)\n self.assertEqual(TwoFields.objects.count(), 2)\n self.assertCountEqual(\n TwoFields.objects.values(\"f1\", \"f2\", \"name\"),\n@@ -680,12 +687,16 @@ def _test_update_conflicts_unique_two_fields(self, unique_fields):\n description=(\"Japan is an island country in East Asia.\"),\n ),\n ]\n- Country.objects.bulk_create(\n+ results = Country.objects.bulk_create(\n new_data,\n update_conflicts=True,\n update_fields=[\"description\"],\n unique_fields=unique_fields,\n )\n+ self.assertEqual(len(results), len(new_data))\n+ if connection.features.can_return_rows_from_bulk_insert:\n+ for instance in results:\n+ self.assertIsNotNone(instance.pk)\n self.assertEqual(Country.objects.count(), 6)\n self.assertCountEqual(\n Country.objects.values(\"iso_two_letter\", \"description\"),\n@@ -743,12 +754,16 @@ def _test_update_conflicts(self, unique_fields):\n UpsertConflict(number=2, rank=2, name=\"Olivia\"),\n UpsertConflict(number=3, rank=1, name=\"Hannah\"),\n ]\n- UpsertConflict.objects.bulk_create(\n+ results = UpsertConflict.objects.bulk_create(\n conflicting_objects,\n update_conflicts=True,\n update_fields=[\"name\", \"rank\"],\n unique_fields=unique_fields,\n )\n+ self.assertEqual(len(results), len(conflicting_objects))\n+ if connection.features.can_return_rows_from_bulk_insert:\n+ for instance in results:\n+ self.assertIsNotNone(instance.pk)\n self.assertEqual(UpsertConflict.objects.count(), 3)\n self.assertCountEqual(\n UpsertConflict.objects.values(\"number\", \"rank\", \"name\"),\n@@ -759,12 +774,16 @@ def _test_update_conflicts(self, unique_fields):\n ],\n )\n \n- UpsertConflict.objects.bulk_create(\n+ results = UpsertConflict.objects.bulk_create(\n conflicting_objects + [UpsertConflict(number=4, rank=4, name=\"Mark\")],\n update_conflicts=True,\n update_fields=[\"name\", \"rank\"],\n unique_fields=unique_fields,\n )\n+ self.assertEqual(len(results), 4)\n+ if connection.features.can_return_rows_from_bulk_insert:\n+ for instance in results:\n+ self.assertIsNotNone(instance.pk)\n self.assertEqual(UpsertConflict.objects.count(), 4)\n self.assertCountEqual(\n UpsertConflict.objects.values(\"number\", \"rank\", \"name\"),\n@@ -803,12 +822,16 @@ def test_update_conflicts_unique_fields_update_fields_db_column(self):\n FieldsWithDbColumns(rank=1, name=\"c\"),\n FieldsWithDbColumns(rank=2, name=\"d\"),\n ]\n- FieldsWithDbColumns.objects.bulk_create(\n+ results = FieldsWithDbColumns.objects.bulk_create(\n conflicting_objects,\n update_conflicts=True,\n unique_fields=[\"rank\"],\n update_fields=[\"name\"],\n )\n+ self.assertEqual(len(results), len(conflicting_objects))\n+ if connection.features.can_return_rows_from_bulk_insert:\n+ for instance in results:\n+ self.assertIsNotNone(instance.pk)\n self.assertEqual(FieldsWithDbColumns.objects.count(), 2)\n self.assertCountEqual(\n FieldsWithDbColumns.objects.values(\"rank\", \"name\"),\n", "problem_statement": "Allow returning IDs in QuerySet.bulk_create() when updating conflicts.\nDescription\n\t\nCurrently, when using bulk_create with a conflict handling flag turned on (e.g. ignore_conflicts or update_conflicts), the primary keys are not set in the returned queryset, as documented in bulk_create.\nWhile I understand using ignore_conflicts can lead to PostgreSQL not returning the IDs when a row is ignored (see \u200bthis SO thread), I don't understand why we don't return the IDs in the case of update_conflicts.\nFor instance:\nMyModel.objects.bulk_create([MyModel(...)], update_conflicts=True, update_fields=[...], unique_fields=[...])\ngenerates a query without a RETURNING my_model.id part:\nINSERT INTO \"my_model\" (...)\nVALUES (...)\n\tON CONFLICT(...) DO UPDATE ...\nIf I append the RETURNING my_model.id clause, the query is indeed valid and the ID is returned (checked with PostgreSQL).\nI investigated a bit and \u200bthis in Django source is where the returning_fields gets removed.\nI believe we could discriminate the cases differently so as to keep those returning_fields in the case of update_conflicts.\nThis would be highly helpful when using bulk_create as a bulk upsert feature.\n", "hints_text": "Thanks for the ticket. I've checked and it works on PostgreSQL, MariaDB 10.5+, and SQLite 3.35+: django/db/models/query.py diff --git a/django/db/models/query.py b/django/db/models/query.py index a5b0f464a9..f1e052cb36 100644 a b class QuerySet(AltersData): 18371837 inserted_rows = [] 18381838 bulk_return = connection.features.can_return_rows_from_bulk_insert 18391839 for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]: 1840 if bulk_return and on_conflict is None: 1840 if bulk_return and (on_conflict is None or on_conflict == OnConflict.UPDATE): 18411841 inserted_rows.extend( 18421842 self._insert( 18431843 item, 18441844 fields=fields, 18451845 using=self.db, 1846 on_conflict=on_conflict, 1847 update_fields=update_fields, 1848 unique_fields=unique_fields, 18461849 returning_fields=self.model._meta.db_returning_fields, 18471850 ) 18481851 ) Would you like to prepare a patch via GitHub PR? (docs changes and tests are required)\nSure I will.\nReplying to Thomas C: Sure I will. Thanks. About tests, it should be enough to add some assertions to existing tests: _test_update_conflicts_two_fields(), test_update_conflicts_unique_fields_pk(), _test_update_conflicts_unique_two_fields(), _test_update_conflicts(), and test_update_conflicts_unique_fields_update_fields_db_column() when connection.features.can_return_rows_from_bulk_insert is True.\nSee \u200bhttps://github.com/django/django/pull/17051", "created_at": "2023-07-07T11:01:09Z", "version": "5.0", "FAIL_TO_PASS": "[\"test_update_conflicts_two_fields_unique_fields_first (bulk_create.tests.BulkCreateTests.test_update_conflicts_two_fields_unique_fields_first)\", \"test_update_conflicts_two_fields_unique_fields_second (bulk_create.tests.BulkCreateTests.test_update_conflicts_two_fields_unique_fields_second)\", \"test_update_conflicts_unique_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields)\", \"test_update_conflicts_unique_fields_update_fields_db_column (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields_update_fields_db_column)\", \"test_update_conflicts_unique_two_fields_unique_fields_both (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_two_fields_unique_fields_both)\"]", "PASS_TO_PASS": "[\"test_batch_same_vals (bulk_create.tests.BulkCreateTests.test_batch_same_vals)\", \"test_bulk_insert_expressions (bulk_create.tests.BulkCreateTests.test_bulk_insert_expressions)\", \"test_bulk_insert_now (bulk_create.tests.BulkCreateTests.test_bulk_insert_now)\", \"test_bulk_insert_nullable_fields (bulk_create.tests.BulkCreateTests.test_bulk_insert_nullable_fields)\", \"test_efficiency (bulk_create.tests.BulkCreateTests.test_efficiency)\", \"test_empty_model (bulk_create.tests.BulkCreateTests.test_empty_model)\", \"test_explicit_batch_size (bulk_create.tests.BulkCreateTests.test_explicit_batch_size)\", \"test_explicit_batch_size_efficiency (bulk_create.tests.BulkCreateTests.test_explicit_batch_size_efficiency)\", \"test_explicit_batch_size_respects_max_batch_size (bulk_create.tests.BulkCreateTests.test_explicit_batch_size_respects_max_batch_size)\", \"test_ignore_conflicts_ignore (bulk_create.tests.BulkCreateTests.test_ignore_conflicts_ignore)\", \"test_ignore_update_conflicts_exclusive (bulk_create.tests.BulkCreateTests.test_ignore_update_conflicts_exclusive)\", \"test_invalid_batch_size_exception (bulk_create.tests.BulkCreateTests.test_invalid_batch_size_exception)\", \"test_large_batch (bulk_create.tests.BulkCreateTests.test_large_batch)\", \"test_large_batch_efficiency (bulk_create.tests.BulkCreateTests.test_large_batch_efficiency)\", \"Test inserting a large batch with objects having primary key set\", \"test_large_single_field_batch (bulk_create.tests.BulkCreateTests.test_large_single_field_batch)\", \"test_long_and_short_text (bulk_create.tests.BulkCreateTests.test_long_and_short_text)\", \"Inserting non-ASCII values with a length in the range 2001 to 4000\", \"test_multi_table_inheritance_unsupported (bulk_create.tests.BulkCreateTests.test_multi_table_inheritance_unsupported)\", \"test_non_auto_increment_pk (bulk_create.tests.BulkCreateTests.test_non_auto_increment_pk)\", \"test_non_auto_increment_pk_efficiency (bulk_create.tests.BulkCreateTests.test_non_auto_increment_pk_efficiency)\", \"test_nullable_fk_after_parent (bulk_create.tests.BulkCreateTests.test_nullable_fk_after_parent)\", \"test_nullable_fk_after_parent_bulk_create (bulk_create.tests.BulkCreateTests.test_nullable_fk_after_parent_bulk_create)\", \"test_proxy_inheritance_supported (bulk_create.tests.BulkCreateTests.test_proxy_inheritance_supported)\", \"test_set_pk_and_insert_single_item (bulk_create.tests.BulkCreateTests.test_set_pk_and_insert_single_item)\", \"test_set_pk_and_query_efficiency (bulk_create.tests.BulkCreateTests.test_set_pk_and_query_efficiency)\", \"test_set_state (bulk_create.tests.BulkCreateTests.test_set_state)\", \"test_set_state_with_pk_specified (bulk_create.tests.BulkCreateTests.test_set_state_with_pk_specified)\", \"test_simple (bulk_create.tests.BulkCreateTests.test_simple)\", \"test_unsaved_parent (bulk_create.tests.BulkCreateTests.test_unsaved_parent)\", \"test_update_conflicts_invalid_unique_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_invalid_unique_fields)\", \"test_update_conflicts_invalid_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_invalid_update_fields)\", \"test_update_conflicts_no_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_no_update_fields)\", \"test_update_conflicts_nonexistent_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_nonexistent_update_fields)\", \"test_update_conflicts_pk_in_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_pk_in_update_fields)\", \"test_update_conflicts_two_fields_unique_fields_both (bulk_create.tests.BulkCreateTests.test_update_conflicts_two_fields_unique_fields_both)\", \"test_update_conflicts_unique_fields_pk (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields_pk)\", \"test_update_conflicts_unique_fields_required (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields_required)\", \"test_update_conflicts_unique_two_fields_unique_fields_one (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_two_fields_unique_fields_one)\"]", "environment_setup_commit": "4a72da71001f154ea60906a2f74898d32b7322a7", "test_directives": ["bulk_create.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 bulk_create.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["bulk_create.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/db/backends/postgresql/operations.py b/django/db/backends/postgresql/operations.py\nindex aa839f5634..38e89360eb 100644\n--- a/django/db/backends/postgresql/operations.py\n+++ b/django/db/backends/postgresql/operations.py\n@@ -399,7 +399,7 @@ class DatabaseOperations(BaseDatabaseOperations):\n if on_conflict == OnConflict.IGNORE:\n return \"ON CONFLICT DO NOTHING\"\n if on_conflict == OnConflict.UPDATE:\n- return \"ON CONFLICT(%s) DO UPDATE SET %s\" % (\n+ conflict_clause = \"ON CONFLICT(%s) DO UPDATE SET %s\" % (\n \", \".join(map(self.quote_name, unique_fields)),\n \", \".join(\n [\n@@ -408,6 +408,9 @@ class DatabaseOperations(BaseDatabaseOperations):\n ]\n ),\n )\n+ # Append RETURNING clause to return the primary keys of the updated rows\n+ returning_clause = \"RETURNING %s\" % self.quote_name(fields[0].model._meta.pk.column)\n+ return f\"{conflict_clause} {returning_clause}\"\n return super().on_conflict_suffix_sql(\n fields,\n on_conflict,\n", "model_lint_repair_patch": "diff --git a/django/db/backends/postgresql/operations.py b/django/db/backends/postgresql/operations.py\nindex aa839f5634..38e89360eb 100644\n--- a/django/db/backends/postgresql/operations.py\n+++ b/django/db/backends/postgresql/operations.py\n@@ -399,7 +399,7 @@ class DatabaseOperations(BaseDatabaseOperations):\n if on_conflict == OnConflict.IGNORE:\n return \"ON CONFLICT DO NOTHING\"\n if on_conflict == OnConflict.UPDATE:\n- return \"ON CONFLICT(%s) DO UPDATE SET %s\" % (\n+ conflict_clause = \"ON CONFLICT(%s) DO UPDATE SET %s\" % (\n \", \".join(map(self.quote_name, unique_fields)),\n \", \".join(\n [\n@@ -408,6 +408,9 @@ class DatabaseOperations(BaseDatabaseOperations):\n ]\n ),\n )\n+ # Append RETURNING clause to return the primary keys of the updated rows\n+ returning_clause = \"RETURNING %s\" % self.quote_name(fields[0].model._meta.pk.column)\n+ return f\"{conflict_clause} {returning_clause}\"\n return super().on_conflict_suffix_sql(\n fields,\n on_conflict,\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["bulk_create.tests"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-15678", "base_commit": "31c68eef3ffef39e2e792b0ec92cd92b7010eb2a", "patch": "diff --git a/sympy/geometry/util.py b/sympy/geometry/util.py\n--- a/sympy/geometry/util.py\n+++ b/sympy/geometry/util.py\n@@ -570,12 +570,19 @@ def idiff(eq, y, x, n=1):\n y = y[0]\n elif isinstance(y, Symbol):\n dep = {y}\n+ elif isinstance(y, Function):\n+ pass\n else:\n- raise ValueError(\"expecting x-dependent symbol(s) but got: %s\" % y)\n+ raise ValueError(\"expecting x-dependent symbol(s) or function(s) but got: %s\" % y)\n \n f = dict([(s, Function(\n s.name)(x)) for s in eq.free_symbols if s != x and s in dep])\n- dydx = Function(y.name)(x).diff(x)\n+\n+ if isinstance(y, Symbol):\n+ dydx = Function(y.name)(x).diff(x)\n+ else:\n+ dydx = y.diff(x)\n+\n eq = eq.subs(f)\n derivs = {}\n for i in range(n):\n", "test_patch": "diff --git a/sympy/geometry/tests/test_util.py b/sympy/geometry/tests/test_util.py\n--- a/sympy/geometry/tests/test_util.py\n+++ b/sympy/geometry/tests/test_util.py\n@@ -1,5 +1,5 @@\n-from sympy import Symbol, sqrt, Derivative, S\n-from sympy.geometry import Point, Point2D, Line, Circle ,Polygon, Segment, convex_hull, intersection, centroid\n+from sympy import Symbol, sqrt, Derivative, S, Function, exp\n+from sympy.geometry import Point, Point2D, Line, Circle, Polygon, Segment, convex_hull, intersection, centroid\n from sympy.geometry.util import idiff, closest_points, farthest_points, _ordered_points\n from sympy.solvers.solvers import solve\n from sympy.utilities.pytest import raises\n@@ -9,6 +9,8 @@ def test_idiff():\n x = Symbol('x', real=True)\n y = Symbol('y', real=True)\n t = Symbol('t', real=True)\n+ f = Function('f')\n+ g = Function('g')\n # the use of idiff in ellipse also provides coverage\n circ = x**2 + y**2 - 4\n ans = -3*x*(x**2 + y**2)/y**5\n@@ -19,6 +21,10 @@ def test_idiff():\n assert ans.subs(y, solve(circ, y)[0]).equals(explicit)\n assert True in [sol.diff(x, 3).equals(explicit) for sol in solve(circ, y)]\n assert idiff(x + t + y, [y, t], x) == -Derivative(t, x) - 1\n+ assert idiff(f(x) * exp(f(x)) - x * exp(x), f(x), x) == (x + 1) * exp(x - f(x))/(f(x) + 1)\n+ assert idiff(f(x) - y * exp(x), [f(x), y], x) == (y + Derivative(y, x)) * exp(x)\n+ assert idiff(f(x) - y * exp(x), [y, f(x)], x) == -y + exp(-x) * Derivative(f(x), x)\n+ assert idiff(f(x) - g(x), [f(x), g(x)], x) == Derivative(g(x), x)\n \n \n def test_intersection():\n", "problem_statement": "Some issues with idiff\nidiff doesn't support Eq, and it also doesn't support f(x) instead of y. Both should be easy to correct.\r\n\r\n```\r\n>>> idiff(Eq(y*exp(y), x*exp(x)), y, x)\r\nTraceback (most recent call last):\r\n File \"\", line 1, in \r\n File \"./sympy/geometry/util.py\", line 582, in idiff\r\n yp = solve(eq.diff(x), dydx)[0].subs(derivs)\r\nIndexError: list index out of range\r\n>>> idiff(f(x)*exp(f(x)) - x*exp(x), f(x), x)\r\nTraceback (most recent call last):\r\n File \"\", line 1, in \r\n File \"./sympy/geometry/util.py\", line 574, in idiff\r\n raise ValueError(\"expecting x-dependent symbol(s) but got: %s\" % y)\r\nValueError: expecting x-dependent symbol(s) but got: f(x)\r\n>>> idiff(y*exp(y)- x*exp(x), y, x)\r\n(x + 1)*exp(x - y)/(y + 1)\r\n```\n", "hints_text": "Hi i am a beginner and i would like to work on this issue.\n@krishna-akula are you still working on this?... I'd like to work on it too", "created_at": "2018-12-20T18:11:56Z", "version": "1.4", "FAIL_TO_PASS": "[\"test_idiff\"]", "PASS_TO_PASS": "[\"test_intersection\", \"test_convex_hull\", \"test_centroid\"]", "environment_setup_commit": "73b3f90093754c5ed1561bd885242330e3583004", "test_directives": ["sympy/geometry/tests/test_util.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/geometry/tests/test_util.py", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/sympy/geometry/tests/test_util.py b/sympy/geometry/tests/test_util.py\nindex a6ded44062..cb7ea48fbe 100644\n--- a/sympy/geometry/tests/test_util.py\n+++ b/sympy/geometry/tests/test_util.py\n@@ -109,18 +109,18 @@ def test_farthest_points_closest_points():\n # equidistant points\n a, b, c = (\n Point2D(0, 0), Point2D(1, 0), Point2D(S(1)/2, sqrt(3)/2))\n- ans = set([_ordered_points((i, j))\n- for i, j in subsets((a, b, c), 2)])\n+ ans = {_ordered_points((i, j))\n+ for i, j in subsets((a, b, c), 2)}\n assert closest_points(b, c, a) == ans\n assert farthest_points(b, c, a) == ans\n \n # unique to farthest\n points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]\n- assert farthest_points(*points) == set(\n- [(Point2D(-5, 2), Point2D(15, 4))])\n+ assert farthest_points(*points) == {\n+ (Point2D(-5, 2), Point2D(15, 4))}\n points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]\n- assert farthest_points(*points) == set(\n- [(Point2D(-5, -2), Point2D(15, -4))])\n- assert farthest_points((1, 1), (0, 0)) == set(\n- [(Point2D(0, 0), Point2D(1, 1))])\n+ assert farthest_points(*points) == {\n+ (Point2D(-5, -2), Point2D(15, -4))}\n+ assert farthest_points((1, 1), (0, 0)) == {\n+ (Point2D(0, 0), Point2D(1, 1))}\n raises(ValueError, lambda: farthest_points((1, 1)))\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/geometry/tests/test_util.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/sympy/geometry/util.py b/sympy/geometry/util.py\nindex d32adc3066..9bd2ef9800 100644\n--- a/sympy/geometry/util.py\n+++ b/sympy/geometry/util.py\n@@ -541,7 +541,8 @@ def idiff(eq, y, x, n=1):\n >>> from sympy.abc import x, y, a\n >>> from sympy.geometry.util import idiff\n \n- >>> circ = x**2 + y**2 - 4\n+ >>> from sympy import Eq\n+ >>> circ = Eq(x**2 + y**2, 4)\n >>> idiff(circ, y, x)\n -x/y\n >>> idiff(circ, y, x, 2).simplify()\n@@ -565,17 +566,20 @@ def idiff(eq, y, x, n=1):\n sympy.core.function.diff: explicitly differentiates wrt symbols\n \n \"\"\"\n+ if isinstance(eq, Eq):\n+ eq = eq.lhs - eq.rhs\n+\n if is_sequence(y):\n dep = set(y)\n y = y[0]\n- elif isinstance(y, Symbol):\n+ elif isinstance(y, (Symbol, Function)):\n dep = {y}\n else:\n raise ValueError(\"expecting x-dependent symbol(s) but got: %s\" % y)\n \n f = dict([(s, Function(\n s.name)(x)) for s in eq.free_symbols if s != x and s in dep])\n- dydx = Function(y.name)(x).diff(x)\n+ dydx = y.diff(x) if isinstance(y, Function) else Function(y.name)(x).diff(x)\n eq = eq.subs(f)\n derivs = {}\n for i in range(n):\n@@ -678,3 +682,18 @@ def intersection(*entities, **kwargs):\n for k in range(j + 1, len(entities)):\n ans.extend(intersection(entities[j], entities[k]))\n return list(ordered(set(ans)))\n+\n+from sympy import Eq, exp, Function\n+from sympy.abc import x, y\n+from sympy.geometry.util import idiff\n+\n+def test_idiff():\n+ # Test case for Eq\n+ assert idiff(Eq(y*exp(y), x*exp(x)), y, x) == (x + 1)*exp(x - y)/(y + 1)\n+\n+ # Test case for Function\n+ f = Function('f')\n+ assert idiff(Eq(f(x)*exp(f(x)), x*exp(x)), f(x), x) == (x + 1)*exp(x - f(x))/(f(x) + 1)\n+\n+ # Existing test case\n+ assert idiff(y*exp(y) - x*exp(x), y, x) == (x + 1)*exp(x - y)/(y + 1)\n\\ No newline at end of file\n", "model_lint_repair_patch": "diff --git a/sympy/geometry/util.py b/sympy/geometry/util.py\nindex d32adc3066..9bd2ef9800 100644\n--- a/sympy/geometry/util.py\n+++ b/sympy/geometry/util.py\n@@ -541,7 +541,8 @@ def idiff(eq, y, x, n=1):\n >>> from sympy.abc import x, y, a\n >>> from sympy.geometry.util import idiff\n \n- >>> circ = x**2 + y**2 - 4\n+ >>> from sympy import Eq\n+ >>> circ = Eq(x**2 + y**2, 4)\n >>> idiff(circ, y, x)\n -x/y\n >>> idiff(circ, y, x, 2).simplify()\n@@ -565,17 +566,20 @@ def idiff(eq, y, x, n=1):\n sympy.core.function.diff: explicitly differentiates wrt symbols\n \n \"\"\"\n+ if isinstance(eq, Eq):\n+ eq = eq.lhs - eq.rhs\n+\n if is_sequence(y):\n dep = set(y)\n y = y[0]\n- elif isinstance(y, Symbol):\n+ elif isinstance(y, (Symbol, Function)):\n dep = {y}\n else:\n raise ValueError(\"expecting x-dependent symbol(s) but got: %s\" % y)\n \n f = dict([(s, Function(\n s.name)(x)) for s in eq.free_symbols if s != x and s in dep])\n- dydx = Function(y.name)(x).diff(x)\n+ dydx = y.diff(x) if isinstance(y, Function) else Function(y.name)(x).diff(x)\n eq = eq.subs(f)\n derivs = {}\n for i in range(n):\n@@ -678,3 +682,18 @@ def intersection(*entities, **kwargs):\n for k in range(j + 1, len(entities)):\n ans.extend(intersection(entities[j], entities[k]))\n return list(ordered(set(ans)))\n+\n+from sympy import Eq, exp, Function\n+from sympy.abc import x, y\n+from sympy.geometry.util import idiff\n+\n+def test_idiff():\n+ # Test case for Eq\n+ assert idiff(Eq(y*exp(y), x*exp(x)), y, x) == (x + 1)*exp(x - y)/(y + 1)\n+\n+ # Test case for Function\n+ f = Function('f')\n+ assert idiff(Eq(f(x)*exp(f(x)), x*exp(x)), f(x), x) == (x + 1)*exp(x - f(x))/(f(x) + 1)\n+\n+ # Existing test case\n+ assert idiff(y*exp(y) - x*exp(x), y, x) == (x + 1)*exp(x - y)/(y + 1)\n\\ No newline at end of file\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/geometry/tests/test_util.py"]} +{"repo": "django/django", "instance_id": "django__django-15789", "base_commit": "d4d5427571b4bf3a21c902276c2a00215c2a37cc", "patch": "diff --git a/django/utils/html.py b/django/utils/html.py\n--- a/django/utils/html.py\n+++ b/django/utils/html.py\n@@ -59,7 +59,7 @@ def escapejs(value):\n }\n \n \n-def json_script(value, element_id=None):\n+def json_script(value, element_id=None, encoder=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@@ -67,7 +67,9 @@ def json_script(value, element_id=None):\n \"\"\"\n from django.core.serializers.json import DjangoJSONEncoder\n \n- json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)\n+ json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate(\n+ _json_script_escapes\n+ )\n if element_id:\n template = ''\n args = (element_id, mark_safe(json_str))\n", "test_patch": "diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py\n--- a/tests/utils_tests/test_html.py\n+++ b/tests/utils_tests/test_html.py\n@@ -1,6 +1,7 @@\n import os\n from datetime import datetime\n \n+from django.core.serializers.json import DjangoJSONEncoder\n from django.test import SimpleTestCase\n from django.utils.functional import lazystr\n from django.utils.html import (\n@@ -211,6 +212,16 @@ def test_json_script(self):\n with self.subTest(arg=arg):\n self.assertEqual(json_script(arg, \"test_id\"), expected)\n \n+ def test_json_script_custom_encoder(self):\n+ class CustomDjangoJSONEncoder(DjangoJSONEncoder):\n+ def encode(self, o):\n+ return '{\"hello\": \"world\"}'\n+\n+ self.assertHTMLEqual(\n+ json_script({}, encoder=CustomDjangoJSONEncoder),\n+ '',\n+ )\n+\n def test_json_script_without_id(self):\n self.assertHTMLEqual(\n json_script({\"key\": \"value\"}),\n", "problem_statement": "Add an encoder parameter to django.utils.html.json_script().\nDescription\n\t\nI have a use case where I want to customize the JSON encoding of some values to output to the template layer. It looks like django.utils.html.json_script is a good utility for that, however the JSON encoder is hardcoded to DjangoJSONEncoder. I think it would be nice to be able to pass a custom encoder class.\nBy the way, django.utils.html.json_script is not documented (only its template filter counterpart is), would it be a good thing to add to the docs?\n", "hints_text": "Sounds good, and yes, we should document django.utils.html.json_script().\n\u200bPR I'll also add docs for json_script() soon\n\u200bPR", "created_at": "2022-06-23T08:59:04Z", "version": "4.2", "FAIL_TO_PASS": "[\"test_json_script_custom_encoder (utils_tests.test_html.TestUtilsHtml)\"]", "PASS_TO_PASS": "[\"test_conditional_escape (utils_tests.test_html.TestUtilsHtml)\", \"test_escape (utils_tests.test_html.TestUtilsHtml)\", \"test_escapejs (utils_tests.test_html.TestUtilsHtml)\", \"test_format_html (utils_tests.test_html.TestUtilsHtml)\", \"test_html_safe (utils_tests.test_html.TestUtilsHtml)\", \"test_html_safe_defines_html_error (utils_tests.test_html.TestUtilsHtml)\", \"test_html_safe_doesnt_define_str (utils_tests.test_html.TestUtilsHtml)\", \"test_html_safe_subclass (utils_tests.test_html.TestUtilsHtml)\", \"test_json_script (utils_tests.test_html.TestUtilsHtml)\", \"test_json_script_without_id (utils_tests.test_html.TestUtilsHtml)\", \"test_linebreaks (utils_tests.test_html.TestUtilsHtml)\", \"test_smart_urlquote (utils_tests.test_html.TestUtilsHtml)\", \"test_strip_spaces_between_tags (utils_tests.test_html.TestUtilsHtml)\", \"test_strip_tags (utils_tests.test_html.TestUtilsHtml)\", \"test_strip_tags_files (utils_tests.test_html.TestUtilsHtml)\", \"test_urlize (utils_tests.test_html.TestUtilsHtml)\", \"test_urlize_unchanged_inputs (utils_tests.test_html.TestUtilsHtml)\"]", "environment_setup_commit": "0fbdb9784da915fce5dcc1fe82bac9b4785749e5", "test_directives": ["utils_tests.test_html"], "test_cmd": "./tests/runtests.py --verbosity 2 utils_tests.test_html", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py\nindex 22a43fd4cd..b5f007308e 100644\n--- a/tests/utils_tests/test_html.py\n+++ b/tests/utils_tests/test_html.py\n@@ -1,4 +1,5 @@\n import os\n+import json\n from datetime import datetime\n \n from django.test import SimpleTestCase\n@@ -211,6 +212,24 @@ class TestUtilsHtml(SimpleTestCase):\n with self.subTest(arg=arg):\n self.assertEqual(json_script(arg, \"test_id\"), expected)\n \n+ # Test with custom encoder\n+ class CustomEncoder(json.JSONEncoder):\n+ def default(self, obj):\n+ if isinstance(obj, set):\n+ return list(obj)\n+ return super().default(obj)\n+\n+ custom_tests = (\n+ (\n+ {\"a\": {1, 2, 3}},\n+ '',\n+ ),\n+ )\n+ for arg, expected in custom_tests:\n+ with self.subTest(arg=arg):\n+ self.assertEqual(json_script(arg, \"test_id\", encoder=CustomEncoder), expected)\n+\n def test_json_script_without_id(self):\n self.assertHTMLEqual(\n json_script({\"key\": \"value\"}),\n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["utils_tests.test_html"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py\nindex 46334791c6..00f5c44bd2 100644\n--- a/django/template/defaultfilters.py\n+++ b/django/template/defaultfilters.py\n@@ -82,12 +82,12 @@ def escapejs_filter(value):\n \n \n @register.filter(is_safe=True)\n-def json_script(value, element_id=None):\n+def json_script(value, element_id=None, encoder=None):\n \"\"\"\n Output value JSON-encoded, wrapped in a '\n args = (element_id, mark_safe(json_str))\n", "model_lint_repair_patch": "diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py\nindex 46334791c6..00f5c44bd2 100644\n--- a/django/template/defaultfilters.py\n+++ b/django/template/defaultfilters.py\n@@ -82,12 +82,12 @@ def escapejs_filter(value):\n \n \n @register.filter(is_safe=True)\n-def json_script(value, element_id=None):\n+def json_script(value, element_id=None, encoder=None):\n \"\"\"\n Output value JSON-encoded, wrapped in a '\n args = (element_id, mark_safe(json_str))\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["utils_tests.test_html"]} +{"repo": "django/django", "instance_id": "django__django-13315", "base_commit": "36bc47069ce071e80c8129500de3b8664d2058a7", "patch": "diff --git a/django/forms/models.py b/django/forms/models.py\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -97,10 +97,18 @@ def model_to_dict(instance, fields=None, exclude=None):\n \n def apply_limit_choices_to_to_formfield(formfield):\n \"\"\"Apply limit_choices_to to the formfield's queryset if needed.\"\"\"\n+ from django.db.models import Exists, OuterRef, Q\n if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'):\n limit_choices_to = formfield.get_limit_choices_to()\n- if limit_choices_to is not None:\n- formfield.queryset = formfield.queryset.complex_filter(limit_choices_to)\n+ if limit_choices_to:\n+ complex_filter = limit_choices_to\n+ if not isinstance(complex_filter, Q):\n+ complex_filter = Q(**limit_choices_to)\n+ complex_filter &= Q(pk=OuterRef('pk'))\n+ # Use Exists() to avoid potential duplicates.\n+ formfield.queryset = formfield.queryset.filter(\n+ Exists(formfield.queryset.model._base_manager.filter(complex_filter)),\n+ )\n \n \n def fields_for_model(model, fields=None, exclude=None, widgets=None,\n", "test_patch": "diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py\n--- a/tests/model_forms/models.py\n+++ b/tests/model_forms/models.py\n@@ -411,9 +411,14 @@ class StumpJoke(models.Model):\n Character,\n models.CASCADE,\n limit_choices_to=today_callable_dict,\n- related_name=\"+\",\n+ related_name='jokes',\n )\n- has_fooled_today = models.ManyToManyField(Character, limit_choices_to=today_callable_q, related_name=\"+\")\n+ has_fooled_today = models.ManyToManyField(\n+ Character,\n+ limit_choices_to=today_callable_q,\n+ related_name='jokes_today',\n+ )\n+ funny = models.BooleanField(default=False)\n \n \n # Model for #13776\ndiff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py\n--- a/tests/model_forms/tests.py\n+++ b/tests/model_forms/tests.py\n@@ -16,6 +16,7 @@\n )\n from django.template import Context, Template\n from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature\n+from django.test.utils import isolate_apps\n \n from .models import (\n Article, ArticleStatus, Author, Author1, Award, BetterWriter, BigInt, Book,\n@@ -2829,6 +2830,72 @@ def test_callable_called_each_time_form_is_instantiated(self):\n StumpJokeForm()\n self.assertEqual(today_callable_dict.call_count, 3)\n \n+ @isolate_apps('model_forms')\n+ def test_limit_choices_to_no_duplicates(self):\n+ joke1 = StumpJoke.objects.create(\n+ funny=True,\n+ most_recently_fooled=self.threepwood,\n+ )\n+ joke2 = StumpJoke.objects.create(\n+ funny=True,\n+ most_recently_fooled=self.threepwood,\n+ )\n+ joke3 = StumpJoke.objects.create(\n+ funny=True,\n+ most_recently_fooled=self.marley,\n+ )\n+ StumpJoke.objects.create(funny=False, most_recently_fooled=self.marley)\n+ joke1.has_fooled_today.add(self.marley, self.threepwood)\n+ joke2.has_fooled_today.add(self.marley)\n+ joke3.has_fooled_today.add(self.marley, self.threepwood)\n+\n+ class CharacterDetails(models.Model):\n+ character1 = models.ForeignKey(\n+ Character,\n+ models.CASCADE,\n+ limit_choices_to=models.Q(\n+ jokes__funny=True,\n+ jokes_today__funny=True,\n+ ),\n+ related_name='details_fk_1',\n+ )\n+ character2 = models.ForeignKey(\n+ Character,\n+ models.CASCADE,\n+ limit_choices_to={\n+ 'jokes__funny': True,\n+ 'jokes_today__funny': True,\n+ },\n+ related_name='details_fk_2',\n+ )\n+ character3 = models.ManyToManyField(\n+ Character,\n+ limit_choices_to=models.Q(\n+ jokes__funny=True,\n+ jokes_today__funny=True,\n+ ),\n+ related_name='details_m2m_1',\n+ )\n+\n+ class CharacterDetailsForm(forms.ModelForm):\n+ class Meta:\n+ model = CharacterDetails\n+ fields = '__all__'\n+\n+ form = CharacterDetailsForm()\n+ self.assertCountEqual(\n+ form.fields['character1'].queryset,\n+ [self.marley, self.threepwood],\n+ )\n+ self.assertCountEqual(\n+ form.fields['character2'].queryset,\n+ [self.marley, self.threepwood],\n+ )\n+ self.assertCountEqual(\n+ form.fields['character3'].queryset,\n+ [self.marley, self.threepwood],\n+ )\n+\n \n class FormFieldCallbackTests(SimpleTestCase):\n \n", "problem_statement": "limit_choices_to on a ForeignKey can render duplicate options in formfield\nDescription\n\t\nIf you pass a Q object as limit_choices_to on a ForeignKey field involving a join, you may end up with duplicate options in your form.\nSee regressiontest in patch for a clear view on the problem.\n", "hints_text": "Replying to SmileyChris: I've updated the patch to resolve the conflicts I've had since you flagged this one as \"Ready for checkin\". No real change.\nupdate resolving conflict\nIs there something I can do to get this checked in? I re-read the \u200bTriage docs. As far as I can see \"A developer checks in the fix\" is the only step left.\nThe \u200b1.2 roadmap shows that we're in a feature freeze. I'd suggest bringing this up on the django-dev google group a week or so after 1.2 final is released.\nIn [15607]: Fixed #11707 - limit_choices_to on a ForeignKey can render duplicate options in formfield Thanks to Chris Wesseling for the report and patch.\nIn [15610]: [1.2.X] Fixed #11707 - limit_choices_to on a ForeignKey can render duplicate options in formfield Thanks to Chris Wesseling for the report and patch. Backport of [15607] from trunk.\nIn [15791]: Fixed #15559 - distinct queries introduced by [15607] cause errors with some custom model fields This patch just reverts [15607] until a more satisfying solution can be found. Refs #11707\nIn [15792]: [1.2.X] Fixed #15559 - distinct queries introduced by [15607] cause errors with some custom model fields This patch just reverts [15607] until a more satisfying solution can be found. Refs #11707 Backport of [15791] from trunk.\nRe-opened due to the fix being reverted, as above. For future reference, a possible alternative solution might be to do filtering of duplicates in Python, at the point of rendering the form field, rather than in the database.\nReplying to lukeplant: (The changeset message doesn't reference this ticket) Can someone point me to an example of such a custom model field or, even better, a test showing the breakage? Replying to lukeplant: For future reference, a possible alternative solution might be to do filtering of duplicates in Python, at the point of rendering the form field, rather than in the database. Assuming 'limit_choices_to' is only used by Forms...\nReplying to charstring: Replying to lukeplant: (The changeset message doesn't reference this ticket) Can someone point me to an example of such a custom model field or, even better, a test showing the breakage? The discussion linked from the description of the other ticket has an example. It's in dpaste so may not be long-lived. Copying here for reference: class PointField(models.Field): description = _(\"A geometric point\") __metaclass__ = models.SubfieldBase pattern = re.compile('^\\(([\\d\\.]+),([\\d\\.]+)\\)$') def db_type(self, connection): if connection.settings_dict['ENGINE'] is not 'django.db.backends.postgresql_psycopg2': return None return 'point' def to_python(self, value): if isinstance(value, tuple): return (float(value[0]), float(value[1])) if not value: return (0, 0) match = self.pattern.findall(value)[0] return (float(match[0]), float(match[1])) def get_prep_value(self, value): return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return '({0}, {1})'.format(value[0], value[1]) def get_prep_lookup(self, lookup_type, value): raise TypeError('Lookup type %r not supported.' % lookup_type) def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_db_prep_value(value)\nThis is nasty because it not only renders duplicates but also blows up when .get() is called on the queryset if you select one of the duplicates (MultipleObjectsReturned).\nTalked to Russ. Picked one of the unclean solutions: filter in python before displaying and checking again before getting the choice. Thanks to Jonas and Roald!\njust removed a the previous fix from the comments\nThis issue also breaks ModelChoiceField - MultipleObjectsReturned error\nReplying to simon29: This issue also breaks ModelChoiceField - MultipleObjectsReturned error By \"this issue also breaks\", do you mean, you've tried the patch and it needs improvement? If it does work, please set it to \"ready for checkin\".\nbackported to 1.2.X and refactored to reduce complexity\nRefactored less complex against trunk\nagainst 1.3.X branch\nDiscussion from IRC: [02:24am] I don't see a test case here that emulates the failures seen when the previous (committed then reverted) approach. Am I just missing it? [09:26am] jacobkm: I also can't say I'm particularly happy with the patch, particularly iterating over the qs in distinct_choices(). [09:26am] chars:It's pretty hard to test for me. It's a case where Postgres can't compare the values. [09:26am] chars: So it can't test for uniqueness [09:26am] jacobkm: It also needs additions to documentation to mention that Q() objects are acceptable in limit_choices_to.\nReplying to jacob: Discussion from IRC: [09:26am] jacobkm: It also needs additions to documentation to mention that Q() objects are acceptable in limit_choices_to. \u200bDocumentation on ForeignKey.limit_choices_to already mentions: \"Instead of a dictionary this can also be a Q object for more complex queries.\" Further discussion: 17:00 < chars> jacobkm: The only known case that broke the original .distinct() solution was in Postgres. So maybe if #6422 gets accepted, we could test for the distinct_on_fields feature and then distinct on the pk, which is unique by definition. 17:00 < jacobkm> chars: see now *that* makes me a lot happier. 17:00 < chars> And fallback to the vanilla .distinct() if the backend doesn't support it. That's #6422.\nDISTINCT is just a special GROUP BY... So an empty .annotate() does the trick too, since it groups by the pk. And the DBMS should by definition be able to compare pk's. I'll try to put up a patch tonight.\nReplying to charstring: DISTINCT is just a special GROUP BY... So an empty .annotate() does the trick too, since it groups by the pk. And the DBMS should by definition be able to compare pk's. I'll try to put up a patch tonight. Well, that was a long night. ;) I got implemented the .annotate() solution in here \u200bhttps://github.com/CharString/django/tree/ticket-11707 Is the PointField mentioned in 12 the same as the one that now lives in django.contrib.gis?\nI think the PointField in comment 12 is a custom field that's different from the one in contrib.gis. It's difficult for me to tell from the comments what the issue was. In any case, I'm going to mark this as \"Patch needs improvement\" since it appears it needs additional tests.\nReplying to charstring: Is the PointField mentioned in 12 the same as the one that now lives in django.contrib.gis? No, it isn't. I've installed postgis for this bug. postgis points *can* be tested on equality.. the PointField in 12 uses the builtin postgres point type, *not* the postgis point type that django.crontib.gis does.", "created_at": "2020-08-17T04:24:39Z", "version": "3.2", "FAIL_TO_PASS": "[\"test_limit_choices_to_no_duplicates (model_forms.tests.LimitChoicesToTests)\"]", "PASS_TO_PASS": "[\"test_modelform_factory_metaclass (model_forms.tests.CustomMetaclassTestCase)\", \"test_bad_callback (model_forms.tests.FormFieldCallbackTests)\", \"Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.\", \"A custom formfield_callback is used if provided\", \"Regression for #15315: modelform_factory should accept widgets\", \"test_inherit_after_custom_callback (model_forms.tests.FormFieldCallbackTests)\", \"Regression for #19733\", \"test_custom_error_messages (model_forms.tests.ModelFormCustomErrorTests)\", \"test_model_clean_error_messages (model_forms.tests.ModelFormCustomErrorTests)\", \"test_setattr_raises_validation_error_field_specific (model_forms.tests.StrictAssignmentTests)\", \"test_setattr_raises_validation_error_non_field (model_forms.tests.StrictAssignmentTests)\", \"test_notrequired_overrides_notblank (model_forms.tests.ValidationTest)\", \"test_validates_with_replaced_field_excluded (model_forms.tests.ValidationTest)\", \"test_validates_with_replaced_field_not_specified (model_forms.tests.ValidationTest)\", \"test_override_clean (model_forms.tests.CustomCleanTests)\", \"test_field_removal (model_forms.tests.ModelFormInheritanceTests)\", \"test_field_removal_name_clashes (model_forms.tests.ModelFormInheritanceTests)\", \"test_form_subclass_inheritance (model_forms.tests.ModelFormInheritanceTests)\", \"test_model_form_applies_localize_to_all_fields (model_forms.tests.LocalizedModelFormTest)\", \"test_model_form_applies_localize_to_some_fields (model_forms.tests.LocalizedModelFormTest)\", \"test_model_form_refuses_arbitrary_string (model_forms.tests.LocalizedModelFormTest)\", \"Data for a ManyToManyField is a list rather than a lazy QuerySet.\", \"test_callable_called_each_time_form_is_instantiated (model_forms.tests.LimitChoicesToTests)\", \"test_custom_field_with_queryset_but_no_limit_choices_to (model_forms.tests.LimitChoicesToTests)\", \"test_fields_for_model_applies_limit_choices_to (model_forms.tests.LimitChoicesToTests)\", \"test_limit_choices_to_callable_for_fk_rel (model_forms.tests.LimitChoicesToTests)\", \"test_limit_choices_to_callable_for_m2m_rel (model_forms.tests.LimitChoicesToTests)\", \"test_assignment_of_none (model_forms.tests.ModelOneToOneFieldTests)\", \"test_assignment_of_none_null_false (model_forms.tests.ModelOneToOneFieldTests)\", \"test_modelform_onetoonefield (model_forms.tests.ModelOneToOneFieldTests)\", \"test_modelform_subclassed_model (model_forms.tests.ModelOneToOneFieldTests)\", \"test_onetoonefield (model_forms.tests.ModelOneToOneFieldTests)\", \"test_article_form (model_forms.tests.ModelFormBaseTest)\", \"test_bad_form (model_forms.tests.ModelFormBaseTest)\", \"test_base_form (model_forms.tests.ModelFormBaseTest)\", \"test_blank_false_with_null_true_foreign_key_field (model_forms.tests.ModelFormBaseTest)\", \"test_blank_foreign_key_with_radio (model_forms.tests.ModelFormBaseTest)\", \"test_blank_with_null_foreign_key_field (model_forms.tests.ModelFormBaseTest)\", \"test_confused_form (model_forms.tests.ModelFormBaseTest)\", \"test_default_filefield (model_forms.tests.ModelFormBaseTest)\", \"test_default_not_populated_on_checkboxselectmultiple (model_forms.tests.ModelFormBaseTest)\", \"test_default_not_populated_on_non_empty_value_in_cleaned_data (model_forms.tests.ModelFormBaseTest)\", \"test_default_not_populated_on_optional_checkbox_input (model_forms.tests.ModelFormBaseTest)\", \"test_default_not_populated_on_selectmultiple (model_forms.tests.ModelFormBaseTest)\", \"test_default_populated_on_optional_field (model_forms.tests.ModelFormBaseTest)\", \"test_default_selectdatewidget (model_forms.tests.ModelFormBaseTest)\", \"test_default_splitdatetime_field (model_forms.tests.ModelFormBaseTest)\", \"test_empty_fields_on_modelform (model_forms.tests.ModelFormBaseTest)\", \"test_empty_fields_to_construct_instance (model_forms.tests.ModelFormBaseTest)\", \"test_empty_fields_to_fields_for_model (model_forms.tests.ModelFormBaseTest)\", \"test_exclude_and_validation (model_forms.tests.ModelFormBaseTest)\", \"test_exclude_fields (model_forms.tests.ModelFormBaseTest)\", \"test_exclude_fields_with_string (model_forms.tests.ModelFormBaseTest)\", \"test_exclude_nonexistent_field (model_forms.tests.ModelFormBaseTest)\", \"test_extra_declared_field_model_form (model_forms.tests.ModelFormBaseTest)\", \"test_extra_field_model_form (model_forms.tests.ModelFormBaseTest)\", \"test_extra_field_modelform_factory (model_forms.tests.ModelFormBaseTest)\", \"test_extra_fields (model_forms.tests.ModelFormBaseTest)\", \"test_invalid_meta_model (model_forms.tests.ModelFormBaseTest)\", \"test_limit_fields_with_string (model_forms.tests.ModelFormBaseTest)\", \"test_limit_nonexistent_field (model_forms.tests.ModelFormBaseTest)\", \"test_missing_fields_attribute (model_forms.tests.ModelFormBaseTest)\", \"test_mixmodel_form (model_forms.tests.ModelFormBaseTest)\", \"test_no_model_class (model_forms.tests.ModelFormBaseTest)\", \"test_non_blank_foreign_key_with_radio (model_forms.tests.ModelFormBaseTest)\", \"test_orderfields2_form (model_forms.tests.ModelFormBaseTest)\", \"test_orderfields_form (model_forms.tests.ModelFormBaseTest)\", \"test_override_field (model_forms.tests.ModelFormBaseTest)\", \"test_prefixed_form_with_default_field (model_forms.tests.ModelFormBaseTest)\", \"test_renderer_kwarg (model_forms.tests.ModelFormBaseTest)\", \"test_replace_field (model_forms.tests.ModelFormBaseTest)\", \"test_replace_field_variant_2 (model_forms.tests.ModelFormBaseTest)\", \"test_replace_field_variant_3 (model_forms.tests.ModelFormBaseTest)\", \"test_save_blank_false_with_required_false (model_forms.tests.ModelFormBaseTest)\", \"test_save_blank_null_unique_charfield_saves_null (model_forms.tests.ModelFormBaseTest)\", \"test_subcategory_form (model_forms.tests.ModelFormBaseTest)\", \"test_subclassmeta_form (model_forms.tests.ModelFormBaseTest)\", \"test_callable_field_default (model_forms.tests.OtherModelFormTests)\", \"test_choices_type (model_forms.tests.OtherModelFormTests)\", \"test_foreignkeys_which_use_to_field (model_forms.tests.OtherModelFormTests)\", \"test_iterable_model_m2m (model_forms.tests.OtherModelFormTests)\", \"test_media_on_modelform (model_forms.tests.OtherModelFormTests)\", \"test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields (model_forms.tests.OtherModelFormTests)\", \"test_prefetch_related_queryset (model_forms.tests.OtherModelFormTests)\", \"test_clean_does_deduplicate_values (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_model_multiple_choice_field (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_model_multiple_choice_field_22745 (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_model_multiple_choice_number_of_queries (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_model_multiple_choice_required_false (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_model_multiple_choice_run_validators (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_model_multiple_choice_show_hidden_initial (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_show_hidden_initial_changed_queries_efficiently (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_to_field_name_with_initial_data (model_forms.tests.ModelMultipleChoiceFieldTests)\", \"test_big_integer_field (model_forms.tests.ModelOtherFieldTests)\", \"test_http_prefixing (model_forms.tests.ModelOtherFieldTests)\", \"test_modelform_non_editable_field (model_forms.tests.ModelOtherFieldTests)\", \"Check basic URL field validation on model forms\", \"test_error_messages_overrides (model_forms.tests.TestFieldOverridesByFormMeta)\", \"test_field_type_overrides (model_forms.tests.TestFieldOverridesByFormMeta)\", \"test_help_text_overrides (model_forms.tests.TestFieldOverridesByFormMeta)\", \"test_label_overrides (model_forms.tests.TestFieldOverridesByFormMeta)\", \"test_widget_overrides (model_forms.tests.TestFieldOverridesByFormMeta)\", \"test_abstract_inherited_unique (model_forms.tests.UniqueTest)\", \"test_abstract_inherited_unique_together (model_forms.tests.UniqueTest)\", \"Ensure keys and blank character strings are tested for uniqueness.\", \"Test for primary_key being in the form and failing validation.\", \"test_inherited_unique (model_forms.tests.UniqueTest)\", \"test_inherited_unique_for_date (model_forms.tests.UniqueTest)\", \"test_inherited_unique_together (model_forms.tests.UniqueTest)\", \"test_multiple_field_unique_together (model_forms.tests.UniqueTest)\", \"test_override_unique_for_date_message (model_forms.tests.UniqueTest)\", \"test_override_unique_message (model_forms.tests.UniqueTest)\", \"test_override_unique_together_message (model_forms.tests.UniqueTest)\", \"test_simple_unique (model_forms.tests.UniqueTest)\", \"test_unique_for_date (model_forms.tests.UniqueTest)\", \"test_unique_for_date_in_exclude (model_forms.tests.UniqueTest)\", \"test_unique_for_date_with_nullable_date (model_forms.tests.UniqueTest)\", \"test_unique_null (model_forms.tests.UniqueTest)\", \"ModelForm test of unique_together constraint\", \"test_unique_together_exclusion (model_forms.tests.UniqueTest)\", \"test_auto_id (model_forms.tests.ModelFormBasicTests)\", \"test_base_form (model_forms.tests.ModelFormBasicTests)\", \"test_basic_creation (model_forms.tests.ModelFormBasicTests)\", \"test_custom_form_fields (model_forms.tests.ModelFormBasicTests)\", \"test_initial_values (model_forms.tests.ModelFormBasicTests)\", \"test_m2m_editing (model_forms.tests.ModelFormBasicTests)\", \"test_m2m_initial_callable (model_forms.tests.ModelFormBasicTests)\", \"test_multi_fields (model_forms.tests.ModelFormBasicTests)\", \"test_recleaning_model_form_instance (model_forms.tests.ModelFormBasicTests)\", \"test_runtime_choicefield_populated (model_forms.tests.ModelFormBasicTests)\", \"test_save_commit_false (model_forms.tests.ModelFormBasicTests)\", \"test_save_with_data_errors (model_forms.tests.ModelFormBasicTests)\", \"test_subset_fields (model_forms.tests.ModelFormBasicTests)\", \"test_validate_foreign_key_to_model_with_overridden_manager (model_forms.tests.ModelFormBasicTests)\", \"test_validate_foreign_key_uses_default_manager (model_forms.tests.ModelFormBasicTests)\", \"test_clean_false (model_forms.tests.FileAndImageFieldTests)\", \"test_clean_false_required (model_forms.tests.FileAndImageFieldTests)\", \"test_clear_and_file_contradiction (model_forms.tests.FileAndImageFieldTests)\", \"test_custom_file_field_save (model_forms.tests.FileAndImageFieldTests)\", \"test_file_field_data (model_forms.tests.FileAndImageFieldTests)\", \"test_file_field_multiple_save (model_forms.tests.FileAndImageFieldTests)\", \"FilePathField(blank=True) includes the empty option.\", \"test_filefield_required_false (model_forms.tests.FileAndImageFieldTests)\", \"test_full_clear (model_forms.tests.FileAndImageFieldTests)\", \"test_image_field (model_forms.tests.FileAndImageFieldTests)\", \"test_render_empty_file_field (model_forms.tests.FileAndImageFieldTests)\"]", "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d", "test_directives": ["model_forms.models", "model_forms.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 model_forms.models model_forms.tests", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/inline_formsets/tests.py b/tests/inline_formsets/tests.py\nindex 1769bc0f49..bf2bcb984e 100644\n--- a/tests/inline_formsets/tests.py\n+++ b/tests/inline_formsets/tests.py\n@@ -124,6 +124,17 @@ class InlineFormsetFactoryTest(TestCase):\n with self.assertRaisesMessage(ValueError, msg):\n inlineformset_factory(Parent, Child)\n \n+ def test_limit_choices_to_with_q_object(self):\n+ \"\"\"\n+ Test that limit_choices_to with a Q object does not render duplicate options.\n+ \"\"\"\n+ from django.db import models\n+ from django.db.models import Q\n+ limit_choices = Q(name__startswith='test')\n+ field = models.ForeignKey(Parent, limit_choices_to=limit_choices, on_delete=models.CASCADE)\n+ form_field = field.formfield()\n+ self.assertEqual(len(form_field.queryset), len(set(form_field.queryset)))\n+\n def test_fk_name_not_foreign_key_field_from_child(self):\n \"\"\"\n If we specify fk_name, but it isn't a ForeignKey from the child model\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["model_fields.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py\nindex c0d085ffc2..2b3c5095b9 100644\n--- a/django/contrib/contenttypes/fields.py\n+++ b/django/contrib/contenttypes/fields.py\n@@ -173,7 +173,7 @@ class GenericForeignKey(FieldCacheMixin):\n def get_prefetch_queryset(self, instances, queryset=None):\n if queryset is not None:\n raise ValueError(\"Custom queryset can't be used for this lookup.\")\n-\n+ \n # For efficiency, group the instances by content type and then do one\n # query per model\n fk_dict = defaultdict(set)\n@@ -188,13 +188,13 @@ class GenericForeignKey(FieldCacheMixin):\n if fk_val is not None:\n fk_dict[ct_id].add(fk_val)\n instance_dict[ct_id] = instance\n-\n+ \n ret_val = []\n for ct_id, fkeys in fk_dict.items():\n instance = instance_dict[ct_id]\n ct = self.get_content_type(id=ct_id, using=instance._state.db)\n- ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys))\n-\n+ ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys).distinct()) # Ensure distinct values\n+ \n # For doing the join in Python, we have to match both the FK val and the\n # content type, so we use a callable that returns a (fk, class) pair.\n def gfk_key(obj):\n@@ -206,7 +206,7 @@ class GenericForeignKey(FieldCacheMixin):\n using=obj._state.db).model_class()\n return (model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),\n model)\n-\n+ \n return (\n ret_val,\n lambda obj: (obj.pk, obj.__class__),\n@@ -473,6 +473,7 @@ class GenericRelation(ForeignObject):\n cond = where_class()\n lookup = field.get_lookup('exact')(field.get_col(remote_alias), contenttype_pk)\n cond.add(lookup, 'AND')\n+ cond.add(where_class.distinct(), 'AND') # Ensure distinct values\n return cond\n \n def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS):\n", "model_lint_repair_patch": "diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py\nindex c0d085ffc2..2b3c5095b9 100644\n--- a/django/contrib/contenttypes/fields.py\n+++ b/django/contrib/contenttypes/fields.py\n@@ -173,7 +173,7 @@ class GenericForeignKey(FieldCacheMixin):\n def get_prefetch_queryset(self, instances, queryset=None):\n if queryset is not None:\n raise ValueError(\"Custom queryset can't be used for this lookup.\")\n-\n+ \n # For efficiency, group the instances by content type and then do one\n # query per model\n fk_dict = defaultdict(set)\n@@ -188,13 +188,13 @@ class GenericForeignKey(FieldCacheMixin):\n if fk_val is not None:\n fk_dict[ct_id].add(fk_val)\n instance_dict[ct_id] = instance\n-\n+ \n ret_val = []\n for ct_id, fkeys in fk_dict.items():\n instance = instance_dict[ct_id]\n ct = self.get_content_type(id=ct_id, using=instance._state.db)\n- ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys))\n-\n+ ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys).distinct()) # Ensure distinct values\n+ \n # For doing the join in Python, we have to match both the FK val and the\n # content type, so we use a callable that returns a (fk, class) pair.\n def gfk_key(obj):\n@@ -206,7 +206,7 @@ class GenericForeignKey(FieldCacheMixin):\n using=obj._state.db).model_class()\n return (model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),\n model)\n-\n+ \n return (\n ret_val,\n lambda obj: (obj.pk, obj.__class__),\n@@ -473,6 +473,7 @@ class GenericRelation(ForeignObject):\n cond = where_class()\n lookup = field.get_lookup('exact')(field.get_col(remote_alias), contenttype_pk)\n cond.add(lookup, 'AND')\n+ cond.add(where_class.distinct(), 'AND') # Ensure distinct values\n return cond\n \n def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS):\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["model_fields.tests"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-13471", "base_commit": "3546ac7ed78e1780c1a76929864bb33330055740", "patch": "diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py\n--- a/sympy/core/numbers.py\n+++ b/sympy/core/numbers.py\n@@ -1042,6 +1042,11 @@ def __new__(cls, num, dps=None, prec=None, precision=None):\n # it's a hexadecimal (coming from a pickled object)\n # assume that it is in standard form\n num = list(num)\n+ # If we're loading an object pickled in Python 2 into\n+ # Python 3, we may need to strip a tailing 'L' because\n+ # of a shim for int on Python 3, see issue #13470.\n+ if num[1].endswith('L'):\n+ num[1] = num[1][:-1]\n num[1] = long(num[1], 16)\n _mpf_ = tuple(num)\n else:\n", "test_patch": "diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py\n--- a/sympy/core/tests/test_numbers.py\n+++ b/sympy/core/tests/test_numbers.py\n@@ -582,6 +582,12 @@ def test_Float_issue_2107():\n assert S.Zero + b + (-b) == 0\n \n \n+def test_Float_from_tuple():\n+ a = Float((0, '1L', 0, 1))\n+ b = Float((0, '1', 0, 1))\n+ assert a == b\n+\n+\n def test_Infinity():\n assert oo != 1\n assert 1*oo == oo\n", "problem_statement": "Python 2->3 pickle fails with float-containing expressions\nDumping a pickled sympy expression containing a float in Python 2, then loading it in Python 3 generates an error.\r\n\r\nHere is a minimum working example, verified with sympy git commit 3546ac7 (master at time of writing), Python 2.7 and Python 3.6:\r\n\r\n```python\r\npython2 -c 'import pickle; import sympy; x = sympy.symbols(\"x\"); print pickle.dumps(x + 1.0, 2)' | python3 -c 'import pickle; import sys; print(pickle.loads(sys.stdin.buffer.read()))'\r\n```\r\n\r\nand the result:\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"\", line 1, in \r\n File \"/Users/alex/git/VU/sympy/sympy/core/numbers.py\", line 1045, in __new__\r\n num[1] = long(num[1], 16)\r\nValueError: invalid literal for int() with base 16: '1L'\r\n```\n", "hints_text": "", "created_at": "2017-10-17T22:52:35Z", "version": "1.1", "FAIL_TO_PASS": "[\"test_Float_from_tuple\"]", "PASS_TO_PASS": "[\"test_integers_cache\", \"test_seterr\", \"test_mod\", \"test_divmod\", \"test_igcd\", \"test_igcd_lehmer\", \"test_igcd2\", \"test_ilcm\", \"test_igcdex\", \"test_Integer_new\", \"test_Rational_new\", \"test_Number_new\", \"test_Rational_cmp\", \"test_Float\", \"test_float_mpf\", \"test_Float_RealElement\", \"test_Float_default_to_highprec_from_str\", \"test_Float_eval\", \"test_Float_issue_2107\", \"test_Infinity\", \"test_Infinity_2\", \"test_Mul_Infinity_Zero\", \"test_Div_By_Zero\", \"test_Infinity_inequations\", \"test_NaN\", \"test_special_numbers\", \"test_powers\", \"test_integer_nthroot_overflow\", \"test_isqrt\", \"test_powers_Integer\", \"test_powers_Rational\", \"test_powers_Float\", \"test_abs1\", \"test_accept_int\", \"test_dont_accept_str\", \"test_int\", \"test_long\", \"test_real_bug\", \"test_bug_sqrt\", \"test_pi_Pi\", \"test_no_len\", \"test_issue_3321\", \"test_issue_3692\", \"test_issue_3423\", \"test_issue_3449\", \"test_Integer_factors\", \"test_Rational_factors\", \"test_issue_4107\", \"test_IntegerInteger\", \"test_Rational_gcd_lcm_cofactors\", \"test_Float_gcd_lcm_cofactors\", \"test_issue_4611\", \"test_conversion_to_mpmath\", \"test_relational\", \"test_Integer_as_index\", \"test_Rational_int\", \"test_zoo\", \"test_issue_4122\", \"test_GoldenRatio_expand\", \"test_as_content_primitive\", \"test_hashing_sympy_integers\", \"test_issue_4172\", \"test_Catalan_EulerGamma_prec\", \"test_Float_eq\", \"test_int_NumberSymbols\", \"test_issue_6640\", \"test_issue_6349\", \"test_mpf_norm\", \"test_latex\", \"test_issue_7742\", \"test_simplify_AlgebraicNumber\", \"test_Float_idempotence\", \"test_comp\", \"test_issue_9491\", \"test_issue_10063\", \"test_issue_10020\", \"test_invert_numbers\", \"test_mod_inverse\", \"test_golden_ratio_rewrite_as_sqrt\", \"test_comparisons_with_unknown_type\", \"test_NumberSymbol_comparison\", \"test_Integer_precision\"]", "environment_setup_commit": "ec9e3c0436fbff934fa84e22bf07f1b3ef5bfac3", "test_directives": ["sympy/core/tests/test_numbers.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/core/tests/test_numbers.py", "model_name_or_path": "navie", "model_iteration": 1, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/utilities/tests/test_pickling.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py\nindex 7bc96e68eb..03cea99583 100644\n--- a/sympy/core/numbers.py\n+++ b/sympy/core/numbers.py\n@@ -788,6 +788,9 @@ class Float(Number):\n precision will automatically increase to capture all digits\n entered.\n \n+ Note: This class has been updated to handle pickled floats\n+ from Python 2 that may have an 'L' suffix.\n+\n >>> Float(1)\n 1.00000000000000\n >>> Float(10**20)\n@@ -953,6 +956,10 @@ def __new__(cls, num, dps=None, prec=None, precision=None):\n raise ValueError('Both decimal and binary precision supplied. '\n 'Supply only one. ')\n \n+ # Handle floats with 'L' suffix from Python 2 pickles\n+ if isinstance(num, str) and num.endswith('L'):\n+ num = num[:-1]\n+\n if isinstance(num, string_types):\n num = num.replace(' ', '')\n if num.startswith('.') and len(num) > 1:\n\ndiff --git a/sympy/utilities/misc.py b/sympy/utilities/misc.py\nindex 7005bd905b..4982d965e2 100644\n--- a/sympy/utilities/misc.py\n+++ b/sympy/utilities/misc.py\n@@ -345,6 +345,9 @@ def translate(s, a, b=None, c=None):\n then each character in ``oldchars`` is replaced with the\n corresponding character in ``newchars``\n \n+ Note: This function has been updated to handle 'L' suffix in floats\n+ from Python 2 pickles.\n+\n Examples\n ========\n \n", "model_lint_repair_patch": "diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py\nindex 7bc96e68eb..03cea99583 100644\n--- a/sympy/core/numbers.py\n+++ b/sympy/core/numbers.py\n@@ -788,6 +788,9 @@ class Float(Number):\n precision will automatically increase to capture all digits\n entered.\n \n+ Note: This class has been updated to handle pickled floats\n+ from Python 2 that may have an 'L' suffix.\n+\n >>> Float(1)\n 1.00000000000000\n >>> Float(10**20)\n@@ -953,6 +956,10 @@ def __new__(cls, num, dps=None, prec=None, precision=None):\n raise ValueError('Both decimal and binary precision supplied. '\n 'Supply only one. ')\n \n+ # Handle floats with 'L' suffix from Python 2 pickles\n+ if isinstance(num, str) and num.endswith('L'):\n+ num = num[:-1]\n+\n if isinstance(num, string_types):\n num = num.replace(' ', '')\n if num.startswith('.') and len(num) > 1:\n\ndiff --git a/sympy/utilities/misc.py b/sympy/utilities/misc.py\nindex 7005bd905b..4982d965e2 100644\n--- a/sympy/utilities/misc.py\n+++ b/sympy/utilities/misc.py\n@@ -345,6 +345,9 @@ def translate(s, a, b=None, c=None):\n then each character in ``oldchars`` is replaced with the\n corresponding character in ``newchars``\n \n+ Note: This function has been updated to handle 'L' suffix in floats\n+ from Python 2 pickles.\n+\n Examples\n ========\n \n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/utilities/tests/test_pickling.py"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-18621", "base_commit": "b17ef6effe278d5b861d65896cc53442a6370d8f", "patch": "diff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py\n--- a/sympy/matrices/expressions/blockmatrix.py\n+++ b/sympy/matrices/expressions/blockmatrix.py\n@@ -301,7 +301,7 @@ def blocks(self):\n data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)\n for j in range(len(mats))]\n for i in range(len(mats))]\n- return ImmutableDenseMatrix(data)\n+ return ImmutableDenseMatrix(data, evaluate=False)\n \n @property\n def shape(self):\n", "test_patch": "diff --git a/sympy/matrices/expressions/tests/test_blockmatrix.py b/sympy/matrices/expressions/tests/test_blockmatrix.py\n--- a/sympy/matrices/expressions/tests/test_blockmatrix.py\n+++ b/sympy/matrices/expressions/tests/test_blockmatrix.py\n@@ -110,6 +110,10 @@ def test_issue_17624():\n assert block_collapse(b * b) == BlockMatrix([[a**2, z], [z, z]])\n assert block_collapse(b * b * b) == BlockMatrix([[a**3, z], [z, z]])\n \n+def test_issue_18618():\n+ A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n+ assert A == Matrix(BlockDiagMatrix(A))\n+\n def test_BlockMatrix_trace():\n A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']\n X = BlockMatrix([[A, B], [C, D]])\n", "problem_statement": "BlockDiagMatrix with one element cannot be converted to regular Matrix\nCreating a BlockDiagMatrix with one Matrix element will raise if trying to convert it back to a regular Matrix:\r\n\r\n```python\r\nM = sympy.Matrix([[1, 2], [3, 4]])\r\nD = sympy.BlockDiagMatrix(M)\r\nB = sympy.Matrix(D)\r\n```\r\n\r\n```\r\nTraceback (most recent call last):\r\n\r\n File \"\", line 3, in \r\n B = sympy.Matrix(D)\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/dense.py\", line 430, in __new__\r\n return cls._new(*args, **kwargs)\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/dense.py\", line 442, in _new\r\n rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/matrices.py\", line 2528, in _handle_creation_inputs\r\n return args[0].rows, args[0].cols, args[0].as_explicit()._mat\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py\", line 340, in as_explicit\r\n for i in range(self.rows)])\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py\", line 340, in \r\n for i in range(self.rows)])\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py\", line 339, in \r\n for j in range(self.cols)]\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py\", line 289, in __getitem__\r\n return self._entry(i, j)\r\n\r\n File \"/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/blockmatrix.py\", line 248, in _entry\r\n return self.blocks[row_block, col_block][i, j]\r\n\r\nTypeError: 'One' object is not subscriptable\r\n```\r\n\r\nInstead having two elements will work as expected:\r\n\r\n```python\r\nM = sympy.Matrix([[1, 2], [3, 4]])\r\nD = sympy.BlockDiagMatrix(M, M)\r\nB = sympy.Matrix(D)\r\n```\r\n\r\n```\r\nMatrix([\r\n[1, 2, 0, 0],\r\n[3, 4, 0, 0],\r\n[0, 0, 1, 2],\r\n[0, 0, 3, 4]])\r\n```\r\nThis issue exists for sympy 1.5.1 but not for sympy 1.4\n", "hints_text": "```diff\r\ndiff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py\r\nindex 11aebbc59f..b821c42845 100644\r\n--- a/sympy/matrices/expressions/blockmatrix.py\r\n+++ b/sympy/matrices/expressions/blockmatrix.py\r\n@@ -301,7 +301,7 @@ def blocks(self):\r\n data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)\r\n for j in range(len(mats))]\r\n for i in range(len(mats))]\r\n- return ImmutableDenseMatrix(data)\r\n+ return ImmutableDenseMatrix(data, evaluate=False)\r\n\r\n @property\r\n def shape(self):\r\n```\r\n\r\nOkay, someone should do the workaround and add some tests about the issue.\ni will submit a pr today.", "created_at": "2020-02-10T05:36:30Z", "version": "1.6", "FAIL_TO_PASS": "[\"test_issue_18618\"]", "PASS_TO_PASS": "[\"test_bc_matmul\", \"test_bc_matadd\", \"test_bc_transpose\", \"test_bc_dist_diag\", \"test_block_plus_ident\", \"test_BlockMatrix\", \"test_block_collapse_explicit_matrices\", \"test_issue_17624\", \"test_BlockMatrix_trace\", \"test_BlockMatrix_Determinant\", \"test_squareBlockMatrix\", \"test_BlockDiagMatrix\", \"test_blockcut\", \"test_reblock_2x2\", \"test_deblock\"]", "environment_setup_commit": "28b41c73c12b70d6ad9f6e45109a80649c4456da", "test_directives": ["sympy/matrices/expressions/tests/test_blockmatrix.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/matrices/expressions/tests/test_blockmatrix.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/matrices/expressions/tests/test_blockmatrix.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py\nindex 11aebbc59f..595ae7c834 100644\n--- a/sympy/matrices/expressions/blockmatrix.py\n+++ b/sympy/matrices/expressions/blockmatrix.py\n@@ -233,6 +233,8 @@ def transpose(self):\n return self._eval_transpose()\n \n def _entry(self, i, j, **kwargs):\n+ if self.blockshape == (1, 1):\n+ return self.blocks[0, 0][i, j]\n # Find row entry\n for row_block, numrows in enumerate(self.rowblocksizes):\n if (i < numrows) != False:\n", "model_lint_repair_patch": "diff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py\nindex 11aebbc59f..595ae7c834 100644\n--- a/sympy/matrices/expressions/blockmatrix.py\n+++ b/sympy/matrices/expressions/blockmatrix.py\n@@ -233,6 +233,8 @@ def transpose(self):\n return self._eval_transpose()\n \n def _entry(self, i, j, **kwargs):\n+ if self.blockshape == (1, 1):\n+ return self.blocks[0, 0][i, j]\n # Find row entry\n for row_block, numrows in enumerate(self.rowblocksizes):\n if (i < numrows) != False:\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sympy/matrices/expressions/tests/test_blockmatrix.py"]} +{"repo": "django/django", "instance_id": "django__django-13933", "base_commit": "42e8cf47c7ee2db238bf91197ea398126c546741", "patch": "diff --git a/django/forms/models.py b/django/forms/models.py\n--- a/django/forms/models.py\n+++ b/django/forms/models.py\n@@ -1284,7 +1284,11 @@ def to_python(self, value):\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/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py\n--- a/tests/forms_tests/tests/test_error_messages.py\n+++ b/tests/forms_tests/tests/test_error_messages.py\n@@ -308,3 +308,16 @@ def test_modelchoicefield(self):\n self.assertFormErrors(['REQUIRED'], f.clean, '')\n self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3')\n self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4'])\n+\n+ def test_modelchoicefield_value_placeholder(self):\n+ f = ModelChoiceField(\n+ queryset=ChoiceModel.objects.all(),\n+ error_messages={\n+ 'invalid_choice': '\"%(value)s\" is not one of the available choices.',\n+ },\n+ )\n+ self.assertFormErrors(\n+ ['\"invalid\" is not one of the available choices.'],\n+ f.clean,\n+ 'invalid',\n+ )\n", "problem_statement": "ModelChoiceField does not provide value of invalid choice when raising ValidationError\nDescription\n\t \n\t\t(last modified by Aaron Wiegel)\n\t \nCompared with ChoiceField and others, ModelChoiceField does not show the value of the invalid choice when raising a validation error. Passing in parameters with the invalid value and modifying the default error message for the code invalid_choice should fix this.\nFrom source code:\nclass ModelMultipleChoiceField(ModelChoiceField):\n\t\"\"\"A MultipleChoiceField whose choices are a model QuerySet.\"\"\"\n\twidget = SelectMultiple\n\thidden_widget = MultipleHiddenInput\n\tdefault_error_messages = {\n\t\t'invalid_list': _('Enter a list of values.'),\n\t\t'invalid_choice': _('Select a valid choice. %(value)s is not one of the'\n\t\t\t\t\t\t\t' available choices.'),\n\t\t'invalid_pk_value': _('\u201c%(pk)s\u201d is not a valid value.')\n\t}\n\t...\nclass ModelChoiceField(ChoiceField):\n\t\"\"\"A ChoiceField whose choices are a model QuerySet.\"\"\"\n\t# This class is a subclass of ChoiceField for purity, but it doesn't\n\t# actually use any of ChoiceField's implementation.\n\tdefault_error_messages = {\n\t\t'invalid_choice': _('Select a valid choice. That choice is not one of'\n\t\t\t\t\t\t\t' the available choices.'),\n\t}\n\t...\n", "hints_text": "This message has been the same literally forever b2b6fc8e3c78671c8b6af2709358c3213c84d119. \u200bGiven that ChoiceField passes the value when raising the error, if you set \u200berror_messages you should be able to get the result you want.\nReplying to Carlton Gibson: This message has been the same literally forever b2b6fc8e3c78671c8b6af2709358c3213c84d119. \u200bGiven that ChoiceField passes the value when raising the error, if you set \u200berror_messages you should be able to get the result you want. That is ChoiceField. ModelChoiceField \u200bdoes not pass the value to the validation error. So, when the invalid value error is raised, you can't display the offending value even if you override the defaults.\nOK, if you want to look at submitting a PR we can see if any objections come up in review. Thanks.\nPR: \u200bhttps://github.com/django/django/pull/13933", "created_at": "2021-01-26T03:58:23Z", "version": "4.0", "FAIL_TO_PASS": "[\"test_modelchoicefield_value_placeholder (forms_tests.tests.test_error_messages.ModelChoiceFieldErrorMessagesTestCase)\"]", "PASS_TO_PASS": "[\"test_modelchoicefield (forms_tests.tests.test_error_messages.ModelChoiceFieldErrorMessagesTestCase)\", \"test_booleanfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_charfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_choicefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_datefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_datetimefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_decimalfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_emailfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_error_messages_escaping (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_filefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_floatfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_generic_ipaddressfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_integerfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_multiplechoicefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_regexfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_splitdatetimefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_subclassing_errorlist (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_timefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\", \"test_urlfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)\"]", "environment_setup_commit": "475cffd1d64c690cdad16ede4d5e81985738ceb4", "test_directives": ["forms_tests.tests.test_error_messages"], "test_cmd": "./tests/runtests.py --verbosity 2 forms_tests.tests.test_error_messages", "model_name_or_path": "navie", "model_patch": null} +{"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-26011", "base_commit": "00afcc0c6d4d2e4390338127f05b8f4fdb4e7087", "patch": "diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py\n--- a/lib/matplotlib/axis.py\n+++ b/lib/matplotlib/axis.py\n@@ -1241,11 +1241,13 @@ def _set_lim(self, v0, v1, *, emit=True, auto):\n self.axes.callbacks.process(f\"{name}lim_changed\", self.axes)\n # Call all of the other axes that are shared with this one\n for other in self._get_shared_axes():\n- if other is not self.axes:\n- other._axis_map[name]._set_lim(\n- v0, v1, emit=False, auto=auto)\n- if other.figure != self.figure:\n- other.figure.canvas.draw_idle()\n+ if other is self.axes:\n+ continue\n+ other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto)\n+ if emit:\n+ other.callbacks.process(f\"{name}lim_changed\", other)\n+ if other.figure != self.figure:\n+ other.figure.canvas.draw_idle()\n \n self.stale = True\n return v0, v1\n", "test_patch": "diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py\n--- a/lib/matplotlib/tests/test_axes.py\n+++ b/lib/matplotlib/tests/test_axes.py\n@@ -8794,3 +8794,12 @@ def test_set_secondary_axis_color():\n assert mcolors.same_color(sax.xaxis.get_tick_params()[\"color\"], \"red\")\n assert mcolors.same_color(sax.xaxis.get_tick_params()[\"labelcolor\"], \"red\")\n assert mcolors.same_color(sax.xaxis.label.get_color(), \"red\")\n+\n+\n+def test_xylim_changed_shared():\n+ fig, axs = plt.subplots(2, sharex=True, sharey=True)\n+ events = []\n+ axs[1].callbacks.connect(\"xlim_changed\", events.append)\n+ axs[1].callbacks.connect(\"ylim_changed\", events.append)\n+ axs[0].set(xlim=[1, 3], ylim=[2, 4])\n+ assert events == [axs[1], axs[1]]\n", "problem_statement": "xlim_changed not emitted on shared axis\n\r\n\r\n\r\n### Bug report\r\n\r\n**Bug summary**\r\n\r\nWhen an axis is shared with another its registered \"xlim_changed\" callbacks does not get called when the change is induced by a shared axis (via sharex=). \r\n\r\nIn _base.py the set_xlim for sibling axis are called with emit=False:\r\n\r\n```\r\nmatplotlib/lib/matplotlib/axes/_base.py:\r\n\r\n/.../\r\ndef set_xlim(...)\r\n/.../\r\n if emit:\r\n self.callbacks.process('xlim_changed', self)\r\n # Call all of the other x-axes that are shared with this one\r\n for other in self._shared_x_axes.get_siblings(self):\r\n if other is not self:\r\n other.set_xlim(self.viewLim.intervalx,\r\n emit=False, auto=auto)\r\n```\r\n\r\nI'm very new to matplotlib, so perhaps there is a good reason for this? emit=False seems to disable both continued \"inheritance\" of axis (why?) and triggering of change callbacks (looking at the code above).\r\n\r\nIt seems like one would at least want to trigger the xlim_changed callbacks as they would be intended to react to any change in axis limits.\r\n\r\nEdit: Setting emit=True seems to introduce a recursion issue (not sure why but as inheritance seems to be passed along anyway it doesn't really matter). Moving the callback call to outside of the \"if emit:\"-statement seems to solve the issue as far as I can see when trying it out. Any reason to keep it inside the if-statement? \r\n\n", "hints_text": "I'm also seeing this behavior on matplotlib 3.4.1. Working from the [resampling data example](https://matplotlib.org/stable/gallery/event_handling/resample.html), I've been developing an adaptive waveform plotter in [this PR](https://github.com/librosa/librosa/issues/1207) (code included there). The specific quirks that I'm seeing are as follows:\r\n\r\n- Create two axes with shared x axis (eg, `fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)`), and set an axis callback on `ax0` for `xlim_changed`. If the xlim changes on `ax1`, which does not directly have the callback set, the axes still update appropriately but the callback is never triggered.\r\n- Possibly related: if the callback is set on `ax0` first, and some time later we draw on `ax1`, the callback never triggers even if we directly set the xlims on `ax0`.\r\n\r\nNote: if I create the shared axes, draw on `ax1` first and set the callback on `ax0` last, everything works as expected. So I don't think there's any fundamental incompatibility here. It does seem like some data structure is being either ignored or clobbered though.\nA short self-contained example would be very helpful here! Thanks \n\"short\" is relative here :) There is a full setup in the linked PR, but here's something hopefully a little more streamlined:\r\n\r\n```python\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# From https://matplotlib.org/stable/gallery/event_handling/resample.html\r\n# A class that will downsample the data and recompute when zoomed.\r\nclass DataDisplayDownsampler:\r\n def __init__(self, xdata, ydata):\r\n self.origYData = ydata\r\n self.origXData = xdata\r\n self.max_points = 50\r\n self.delta = xdata[-1] - xdata[0]\r\n\r\n def downsample(self, xstart, xend):\r\n # get the points in the view range\r\n mask = (self.origXData > xstart) & (self.origXData < xend)\r\n # dilate the mask by one to catch the points just outside\r\n # of the view range to not truncate the line\r\n mask = np.convolve([1, 1, 1], mask, mode='same').astype(bool)\r\n # sort out how many points to drop\r\n ratio = max(np.sum(mask) // self.max_points, 1)\r\n\r\n # mask data\r\n xdata = self.origXData[mask]\r\n ydata = self.origYData[mask]\r\n\r\n # downsample data\r\n xdata = xdata[::ratio]\r\n ydata = ydata[::ratio]\r\n\r\n print(\"using {} of {} visible points\".format(len(ydata), np.sum(mask)))\r\n\r\n return xdata, ydata\r\n\r\n def update(self, ax):\r\n # Update the line\r\n lims = ax.viewLim\r\n if abs(lims.width - self.delta) > 1e-8:\r\n self.delta = lims.width\r\n xstart, xend = lims.intervalx\r\n self.line.set_data(*self.downsample(xstart, xend))\r\n ax.figure.canvas.draw_idle()\r\n\r\n\r\n# Create a signal\r\nxdata = np.linspace(16, 365, (365-16)*4)\r\nydata = np.sin(2*np.pi*xdata/153) + np.cos(2*np.pi*xdata/127)\r\n\r\n\r\n# --- This does not work: ax1 drawn after ax0 kills callbacks\r\nd = DataDisplayDownsampler(xdata, ydata)\r\nfig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)\r\n\r\n# Hook up the line\r\nd.line, = ax0.plot(xdata, ydata, 'o-')\r\nax0.set_autoscale_on(False) # Otherwise, infinite loop\r\n\r\n# Connect for changing the view limits\r\nax0.callbacks.connect('xlim_changed', d.update)\r\nax0.set_xlim(16, 365)\r\n\r\nax1.plot(xdata, -ydata)\r\nplt.show()\r\n\r\n\r\n# --- This does work: ax0 drawn after ax1\r\n# --- Note: only works if axis limits are controlled via ax0, not ax1\r\n# Create a signal\r\nxdata = np.linspace(16, 365, (365-16)*4)\r\nydata = np.sin(2*np.pi*xdata/153) + np.cos(2*np.pi*xdata/127)\r\n\r\nd = DataDisplayDownsampler(xdata, ydata)\r\n\r\nfig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)\r\n\r\nax1.plot(xdata, -ydata)\r\n\r\n# Hook up the line\r\nd.line, = ax0.plot(xdata, ydata, 'o-')\r\nax0.set_autoscale_on(False) # Otherwise, infinite loop\r\n\r\n# Connect for changing the view limits\r\nax0.callbacks.connect('xlim_changed', d.update)\r\nax0.set_xlim(16, 365)\r\n\r\n\r\nplt.show()\r\n\r\n```\r\n\r\nIn neither case does panning/zooming/setting limits on `ax1` do the right thing.\nThats not bad ;-)\nThe problem is that we do \r\n```\r\nother.set_xlim(self.viewLim.intervalx, emit=False, auto=auto)\r\n```\r\nwhich doesn't do the `ax0.callbacks.process('xlim_changed', self)` \r\n\r\nIf we don't do this, it continues to emit to the shared axes and we get an infinite recursion. \r\n\r\nSomething like \r\n```diff\r\ndiff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py\r\nindex 9898c7c75..0c1941efb 100644\r\n--- a/lib/matplotlib/axes/_base.py\r\n+++ b/lib/matplotlib/axes/_base.py\r\n@@ -3742,10 +3742,11 @@ class _AxesBase(martist.Artist):\r\n # Call all of the other x-axes that are shared with this one\r\n for other in self._shared_x_axes.get_siblings(self):\r\n if other is not self:\r\n- other.set_xlim(self.viewLim.intervalx,\r\n- emit=False, auto=auto)\r\n- if other.figure != self.figure:\r\n- other.figure.canvas.draw_idle()\r\n+ if not np.allclose(other.viewLim.intervalx, self.viewLim.intervalx):\r\n+ other.set_xlim(self.viewLim.intervalx,\r\n+ emit=True, auto=auto)\r\n+ if other.figure != self.figure:\r\n+ other.figure.canvas.draw_idle()\r\n```\r\n\r\nFixes the problem (plus we'd need the same for yaxis). However, I'm not really expert enough on how sharing is supposed to work versus the callbacks to know if this is right or the best. @anntzer or @efiring last touched this part of the code I think. \nI think I would prefer something like\r\n```patch\r\ndiff --git i/lib/matplotlib/axes/_base.py w/lib/matplotlib/axes/_base.py\r\nindex 9898c7c75..1116d120f 100644\r\n--- i/lib/matplotlib/axes/_base.py\r\n+++ w/lib/matplotlib/axes/_base.py\r\n@@ -541,6 +541,11 @@ class _process_plot_var_args:\r\n return [l[0] for l in result]\r\n \r\n \r\n+import dataclasses\r\n+_NoRecursionMarker = dataclasses.make_dataclass(\r\n+ \"_NoRecursionMarker\", [\"event_src\"])\r\n+\r\n+\r\n @cbook._define_aliases({\"facecolor\": [\"fc\"]})\r\n class _AxesBase(martist.Artist):\r\n name = \"rectilinear\"\r\n@@ -3737,13 +3742,18 @@ class _AxesBase(martist.Artist):\r\n if auto is not None:\r\n self._autoscaleXon = bool(auto)\r\n \r\n- if emit:\r\n+ if emit and emit != _NoRecursionMarker(self):\r\n self.callbacks.process('xlim_changed', self)\r\n # Call all of the other x-axes that are shared with this one\r\n for other in self._shared_x_axes.get_siblings(self):\r\n if other is not self:\r\n+ # Undocumented internal feature: emit can be set to\r\n+ # _NoRecursionMarker(self) which is treated as True, but\r\n+ # avoids infinite recursion.\r\n+ if not isinstance(emit, _NoRecursionMarker):\r\n+ emit = _NoRecursionMarker(self)\r\n other.set_xlim(self.viewLim.intervalx,\r\n- emit=False, auto=auto)\r\n+ emit=emit, auto=auto)\r\n if other.figure != self.figure:\r\n other.figure.canvas.draw_idle()\r\n self.stale = True\r\n```\r\nto more explicitly block infinite recursion, but other than that the basic idea seems fine to me.\nI'm not sure if this is related, but I'm seeing a similar issue if I try to run the same example code multiple times on one ax. As far as I can tell from reading https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/cbook/__init__.py , it should support multiple callbacks on the same signal (or am I misunderstanding?), but the above example when run twice only issues the second callback.\r\n\r\nIf you think this is unrelated, I can open a separate issue for it.\nI'm not exactly sure what you mean, but note that CallbackRegistry currently drops duplicate callbacks (connecting a same callback a second time to the same signal results in it being dropped and the original cid is returned). I actually think that's a pretty unhelpful behavior and would be happy to see it deprecated (that can just go through a normal deprecation cycle), but that would be a separate issue.\nAh, I see. Thanks @anntzer for the clarification.\nI am :+1: on @anntzer 's solution here.\r\n\r\nMarking this as a good first issue because we have a patch for it. Will still need to write a test, a simplified version of the initial bug report would probably work (we do not need convolve in the tests / real signals etc).\r\n\r\n------\r\n\r\nalso good to see fellow NYers around!\nHaving the same problem with perhaps a somewhat simpler example. If the registered callbacks were triggered by changes in axes limits from plots with shared x/y-axes, the gray dashed line in the left plot would extend across the whole canvas:\r\n\r\n![tmp](https://user-images.githubusercontent.com/30958850/130777946-5fd58887-d4e3-4287-a6e7-1be4a093fa98.png)\r\n\r\n```py\r\nfrom typing import Any\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.axes import Axes\r\n\r\n\r\ndef add_identity(ax: Axes = None, **line_kwargs: Any) -> None:\r\n \"\"\"Add a parity line (y = x) to the provided axis.\"\"\"\r\n if ax is None:\r\n ax = plt.gca()\r\n\r\n # zorder=0 ensures other plotted data displays on top of line\r\n default_kwargs = dict(alpha=0.5, zorder=0, linestyle=\"dashed\", color=\"black\")\r\n (identity,) = ax.plot([], [], **default_kwargs, **line_kwargs)\r\n\r\n def callback(axes: Axes) -> None:\r\n x_min, x_max = axes.get_xlim()\r\n y_min, y_max = axes.get_ylim()\r\n low = max(x_min, y_min)\r\n high = min(x_max, y_max)\r\n identity.set_data([low, high], [low, high])\r\n\r\n callback(ax)\r\n # Register callbacks to update identity line when moving plots in interactive\r\n # mode to ensure line always extend to plot edges.\r\n ax.callbacks.connect(\"xlim_changed\", callback)\r\n ax.callbacks.connect(\"ylim_changed\", callback)\r\n\r\n\r\nfig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)\r\n\r\nax1.plot([0, 1], [1, 0])\r\nadd_identity(ax1)\r\n\r\nax2.plot([0, 2], [2, 0])\r\nadd_identity(ax2)\r\n\r\nplt.savefig('tmp.png')\r\n```\nWhile not the point of this issue, that identity line can be achieved with [`axline`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axline.html).\n@QuLogic Damn, that's what I get for not reading the docs closely enough: unnecessary work reinventing a (worse) wheel. Thanks for the pointer!\nNo worries, it's [new-ish](https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.3.0.html#new-axes-axline-method).", "created_at": "2023-05-30T13:45:49Z", "version": "3.7", "FAIL_TO_PASS": "[\"lib/matplotlib/tests/test_axes.py::test_xylim_changed_shared\"]", "PASS_TO_PASS": "[\"lib/matplotlib/tests/test_axes.py::test_invisible_axes[png]\", \"lib/matplotlib/tests/test_axes.py::test_get_labels\", \"lib/matplotlib/tests/test_axes.py::test_repr\", \"lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[png]\", \"lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_label_loc_horizontal[png]\", \"lib/matplotlib/tests/test_axes.py::test_label_loc_horizontal[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_label_loc_rc[png]\", \"lib/matplotlib/tests/test_axes.py::test_label_loc_rc[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_label_shift\", \"lib/matplotlib/tests/test_axes.py::test_acorr[png]\", \"lib/matplotlib/tests/test_axes.py::test_acorr_integers[png]\", \"lib/matplotlib/tests/test_axes.py::test_spy[png]\", \"lib/matplotlib/tests/test_axes.py::test_spy_invalid_kwargs\", \"lib/matplotlib/tests/test_axes.py::test_matshow[png]\", \"lib/matplotlib/tests/test_axes.py::test_formatter_ticker[png]\", \"lib/matplotlib/tests/test_axes.py::test_formatter_ticker[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_funcformatter_auto_formatter\", \"lib/matplotlib/tests/test_axes.py::test_strmethodformatter_auto_formatter\", \"lib/matplotlib/tests/test_axes.py::test_twin_axis_locators_formatters[png]\", \"lib/matplotlib/tests/test_axes.py::test_twin_axis_locators_formatters[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_twinx_cla\", \"lib/matplotlib/tests/test_axes.py::test_twin_units[x]\", \"lib/matplotlib/tests/test_axes.py::test_twin_units[y]\", \"lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-x]\", \"lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-y]\", \"lib/matplotlib/tests/test_axes.py::test_twinx_axis_scales[png]\", \"lib/matplotlib/tests/test_axes.py::test_twin_inherit_autoscale_setting\", \"lib/matplotlib/tests/test_axes.py::test_inverted_cla\", \"lib/matplotlib/tests/test_axes.py::test_subclass_clear_cla\", \"lib/matplotlib/tests/test_axes.py::test_cla_not_redefined_internally\", \"lib/matplotlib/tests/test_axes.py::test_minorticks_on_rcParams_both[png]\", \"lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_range[png]\", \"lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_range[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_autoscale_tight\", \"lib/matplotlib/tests/test_axes.py::test_autoscale_log_shared\", \"lib/matplotlib/tests/test_axes.py::test_use_sticky_edges\", \"lib/matplotlib/tests/test_axes.py::test_sticky_shared_axes[png]\", \"lib/matplotlib/tests/test_axes.py::test_nargs_stem\", \"lib/matplotlib/tests/test_axes.py::test_nargs_legend\", \"lib/matplotlib/tests/test_axes.py::test_nargs_pcolorfast\", \"lib/matplotlib/tests/test_axes.py::test_basic_annotate[png]\", \"lib/matplotlib/tests/test_axes.py::test_basic_annotate[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_arrow_simple[png]\", \"lib/matplotlib/tests/test_axes.py::test_arrow_empty\", \"lib/matplotlib/tests/test_axes.py::test_arrow_in_view\", \"lib/matplotlib/tests/test_axes.py::test_annotate_default_arrow\", \"lib/matplotlib/tests/test_axes.py::test_annotate_signature\", \"lib/matplotlib/tests/test_axes.py::test_fill_units[png]\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_kwarg_redundant\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_dashes[png]\", \"lib/matplotlib/tests/test_axes.py::test_single_point[png]\", \"lib/matplotlib/tests/test_axes.py::test_single_point[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_single_date[png]\", \"lib/matplotlib/tests/test_axes.py::test_shaped_data[png]\", \"lib/matplotlib/tests/test_axes.py::test_structured_data\", \"lib/matplotlib/tests/test_axes.py::test_aitoff_proj[png]\", \"lib/matplotlib/tests/test_axes.py::test_axvspan_epoch[png]\", \"lib/matplotlib/tests/test_axes.py::test_axvspan_epoch[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_axhspan_epoch[png]\", \"lib/matplotlib/tests/test_axes.py::test_axhspan_epoch[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hexbin_extent[png]\", \"lib/matplotlib/tests/test_axes.py::test_hexbin_empty[png]\", \"lib/matplotlib/tests/test_axes.py::test_hexbin_pickable\", \"lib/matplotlib/tests/test_axes.py::test_hexbin_log[png]\", \"lib/matplotlib/tests/test_axes.py::test_hexbin_linear[png]\", \"lib/matplotlib/tests/test_axes.py::test_hexbin_log_clim\", \"lib/matplotlib/tests/test_axes.py::test_hexbin_mincnt_behavior_upon_C_parameter[png]\", \"lib/matplotlib/tests/test_axes.py::test_inverted_limits\", \"lib/matplotlib/tests/test_axes.py::test_nonfinite_limits[png]\", \"lib/matplotlib/tests/test_axes.py::test_nonfinite_limits[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-scatter]\", \"lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-plot]\", \"lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-fill_between]\", \"lib/matplotlib/tests/test_axes.py::test_imshow[png]\", \"lib/matplotlib/tests/test_axes.py::test_imshow[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_imshow_clip[png]\", \"lib/matplotlib/tests/test_axes.py::test_imshow_clip[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_imshow_norm_vminvmax\", \"lib/matplotlib/tests/test_axes.py::test_polycollection_joinstyle[png]\", \"lib/matplotlib/tests/test_axes.py::test_polycollection_joinstyle[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_x_input]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y1_input]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y2_input]\", \"lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_y_input]\", \"lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x1_input]\", \"lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x2_input]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate[png]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_decreasing[png]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_decreasing[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_nan[png]\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_nan[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_symlog[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_symlog2[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorargs_5205\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh[png]\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh_small[eps]\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh_alpha[png]\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh_alpha[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh_rgba[png-3-1]\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh_rgba[png-4-0.5]\", \"lib/matplotlib/tests/test_axes.py::test_pcolormesh_datetime_axis[png]\", \"lib/matplotlib/tests/test_axes.py::test_pcolor_datetime_axis[png]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorargs\", \"lib/matplotlib/tests/test_axes.py::test_pcolorargs_with_read_only\", \"lib/matplotlib/tests/test_axes.py::test_pcolornearest[png]\", \"lib/matplotlib/tests/test_axes.py::test_pcolornearestunits[png]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorflaterror\", \"lib/matplotlib/tests/test_axes.py::test_samesizepcolorflaterror\", \"lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-False]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-True]\", \"lib/matplotlib/tests/test_axes.py::test_canonical[png]\", \"lib/matplotlib/tests/test_axes.py::test_canonical[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_arc_angles[png]\", \"lib/matplotlib/tests/test_axes.py::test_arc_ellipse[png]\", \"lib/matplotlib/tests/test_axes.py::test_arc_ellipse[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_marker_as_markerstyle\", \"lib/matplotlib/tests/test_axes.py::test_markevery[png]\", \"lib/matplotlib/tests/test_axes.py::test_markevery[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_line[png]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_line[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales[png]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_zoomed[png]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_zoomed[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_log_scales[png]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_log_scales[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_polar[png]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_polar[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_nans[png]\", \"lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_nans[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_marker_edges[png]\", \"lib/matplotlib/tests/test_axes.py::test_marker_edges[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_bar_tick_label_single[png]\", \"lib/matplotlib/tests/test_axes.py::test_nan_bar_values\", \"lib/matplotlib/tests/test_axes.py::test_bar_ticklabel_fail\", \"lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple[png]\", \"lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple_old_alignment[png]\", \"lib/matplotlib/tests/test_axes.py::test_bar_decimal_center[png]\", \"lib/matplotlib/tests/test_axes.py::test_barh_decimal_center[png]\", \"lib/matplotlib/tests/test_axes.py::test_bar_decimal_width[png]\", \"lib/matplotlib/tests/test_axes.py::test_barh_decimal_height[png]\", \"lib/matplotlib/tests/test_axes.py::test_bar_color_none_alpha\", \"lib/matplotlib/tests/test_axes.py::test_bar_edgecolor_none_alpha\", \"lib/matplotlib/tests/test_axes.py::test_barh_tick_label[png]\", \"lib/matplotlib/tests/test_axes.py::test_bar_timedelta\", \"lib/matplotlib/tests/test_axes.py::test_bar_datetime_start\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_dates_pandas\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_capwidths\", \"lib/matplotlib/tests/test_axes.py::test_pcolor_regression\", \"lib/matplotlib/tests/test_axes.py::test_bar_pandas\", \"lib/matplotlib/tests/test_axes.py::test_bar_pandas_indexed\", \"lib/matplotlib/tests/test_axes.py::test_bar_hatches[png]\", \"lib/matplotlib/tests/test_axes.py::test_bar_hatches[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_bar_labels[x-1-x-expected_labels0-x]\", \"lib/matplotlib/tests/test_axes.py::test_bar_labels[x1-width1-label1-expected_labels1-_nolegend_]\", \"lib/matplotlib/tests/test_axes.py::test_bar_labels[x2-width2-label2-expected_labels2-_nolegend_]\", \"lib/matplotlib/tests/test_axes.py::test_bar_labels[x3-width3-bars-expected_labels3-bars]\", \"lib/matplotlib/tests/test_axes.py::test_bar_labels_length\", \"lib/matplotlib/tests/test_axes.py::test_pandas_minimal_plot\", \"lib/matplotlib/tests/test_axes.py::test_hist_log[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_log[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist_log_2[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_log_barstacked\", \"lib/matplotlib/tests/test_axes.py::test_hist_bar_empty[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_float16\", \"lib/matplotlib/tests/test_axes.py::test_hist_step_empty[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_step_filled[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_density[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_unequal_bins_density\", \"lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets\", \"lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[date2num]\", \"lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[datetime.datetime]\", \"lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[np.datetime64]\", \"lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data0-1]\", \"lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data1-1]\", \"lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data2-2]\", \"lib/matplotlib/tests/test_axes.py::test_hist_zorder[bar-1]\", \"lib/matplotlib/tests/test_axes.py::test_hist_zorder[step-2]\", \"lib/matplotlib/tests/test_axes.py::test_hist_zorder[stepfilled-1]\", \"lib/matplotlib/tests/test_axes.py::test_stairs[png]\", \"lib/matplotlib/tests/test_axes.py::test_stairs_fill[png]\", \"lib/matplotlib/tests/test_axes.py::test_stairs_update[png]\", \"lib/matplotlib/tests/test_axes.py::test_stairs_baseline_0[png]\", \"lib/matplotlib/tests/test_axes.py::test_stairs_empty\", \"lib/matplotlib/tests/test_axes.py::test_stairs_invalid_nan\", \"lib/matplotlib/tests/test_axes.py::test_stairs_invalid_mismatch\", \"lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update\", \"lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update2\", \"lib/matplotlib/tests/test_axes.py::test_stairs_options[png]\", \"lib/matplotlib/tests/test_axes.py::test_stairs_datetime[png]\", \"lib/matplotlib/tests/test_axes.py::test_stairs_edge_handling[png]\", \"lib/matplotlib/tests/test_axes.py::test_contour_hatching[png]\", \"lib/matplotlib/tests/test_axes.py::test_contour_hatching[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_contour_colorbar[png]\", \"lib/matplotlib/tests/test_axes.py::test_contour_colorbar[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist2d[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist2d[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist2d_transpose[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist2d_transpose[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist2d_density\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_plot[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_plot[pdf]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_marker[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_2D[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_decimal[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs0]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs1]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs2]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs3]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfilled\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfillable\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_size_arg_size\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_edgecolor_RGB\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_invalid_color[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_no_invalid_color[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_norm_vminvmax\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_point[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_different_shapes[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[0.5-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case1-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[red-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[none-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[None-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case5-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[jaune-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case7-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case8-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case9-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case10-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case11-shape]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case12-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case13-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case14-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case15-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case16-shape]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case17-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case18-shape]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case19-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case20-shape]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case21-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case22-shape]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case23-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case24-shape]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case25-None]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case26-shape]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case27-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case28-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case29-conversion]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_color_c[png]\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_linewidths\", \"lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_singular_plural_arguments\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params0-expected_result0]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params1-expected_result1]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params2-expected_result2]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params3-expected_result3]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params4-expected_result4]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs0-None]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs1-None]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs2-r]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs3-expected_edgecolors3]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs4-r]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs5-face]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs6-none]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs7-r]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs8-r]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs9-r]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs10-g]\", \"lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_error\", \"lib/matplotlib/tests/test_axes.py::test_as_mpl_axes_api\", \"lib/matplotlib/tests/test_axes.py::test_pyplot_axes\", \"lib/matplotlib/tests/test_axes.py::test_log_scales\", \"lib/matplotlib/tests/test_axes.py::test_log_scales_no_data\", \"lib/matplotlib/tests/test_axes.py::test_log_scales_invalid\", \"lib/matplotlib/tests/test_axes.py::test_stackplot[png]\", \"lib/matplotlib/tests/test_axes.py::test_stackplot[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_stackplot_baseline[png]\", \"lib/matplotlib/tests/test_axes.py::test_stackplot_baseline[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_baseline[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_rangewhis[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_percentilewhis[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_with_xlabels[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_horizontal[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_with_ylabels[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_patchartist[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_custompatchartist[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_customoutlier[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_showcustommean[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_custombox[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_custommedian[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_customcap[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_customwhisker[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_shownotches[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_nocaps[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_nobox[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_no_flier_stats[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_showmean[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_showmeanasline[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_scalarwidth[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_customwidths[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_custompositions[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_bad_widths\", \"lib/matplotlib/tests/test_axes.py::test_bxp_bad_positions\", \"lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidths[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidth[png]\", \"lib/matplotlib/tests/test_axes.py::test_bxp_bad_capwidths\", \"lib/matplotlib/tests/test_axes.py::test_boxplot[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_custom_capwidths[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_sym2[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_sym[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_autorange_whiskers[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_rc_parameters[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_rc_parameters[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_with_CIarray[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_no_weird_whisker[png]\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_bad_medians\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_bad_ci\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_zorder\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_marker_behavior\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_mod_artist_after_plotting[png]\", \"lib/matplotlib/tests/test_axes.py::test_vert_violinplot_baseline[png]\", \"lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmeans[png]\", \"lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showextrema[png]\", \"lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmedians[png]\", \"lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showall[png]\", \"lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_10[png]\", \"lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_200[png]\", \"lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_baseline[png]\", \"lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmedians[png]\", \"lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmeans[png]\", \"lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showextrema[png]\", \"lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showall[png]\", \"lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_10[png]\", \"lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_200[png]\", \"lib/matplotlib/tests/test_axes.py::test_violinplot_bad_positions\", \"lib/matplotlib/tests/test_axes.py::test_violinplot_bad_widths\", \"lib/matplotlib/tests/test_axes.py::test_violinplot_bad_quantiles\", \"lib/matplotlib/tests/test_axes.py::test_violinplot_outofrange_quantiles\", \"lib/matplotlib/tests/test_axes.py::test_violinplot_single_list_quantiles[png]\", \"lib/matplotlib/tests/test_axes.py::test_violinplot_pandas_series[png]\", \"lib/matplotlib/tests/test_axes.py::test_manage_xticks\", \"lib/matplotlib/tests/test_axes.py::test_boxplot_not_single\", \"lib/matplotlib/tests/test_axes.py::test_tick_space_size_0\", \"lib/matplotlib/tests/test_axes.py::test_errorbar[png]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_mixed_errorbar_polar_caps[png]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_colorcycle\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_cycle_ecolor[png]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_cycle_ecolor[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_shape\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_limits[png]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_limits[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_nonefmt\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_line_specific_kwargs\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_with_prop_cycle[png]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_every_invalid\", \"lib/matplotlib/tests/test_axes.py::test_xerr_yerr_not_negative\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_every[png]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_every[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth0]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth1]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[1]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_nan[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist_offset[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_offset[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist_step[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_step_horiz[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_weighted[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_weighted[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_stem[png]\", \"lib/matplotlib/tests/test_axes.py::test_stem_args\", \"lib/matplotlib/tests/test_axes.py::test_stem_markerfmt\", \"lib/matplotlib/tests/test_axes.py::test_stem_dates\", \"lib/matplotlib/tests/test_axes.py::test_stem_orientation[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_alpha[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_alpha[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_step[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_step[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_density[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_density[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist_step_bottom[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_step_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_bottom_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_step_bottom_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_bottom_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_bottom_geometry\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_bar[png]\", \"lib/matplotlib/tests/test_axes.py::test_hist_stacked_bar[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_hist_barstacked_bottom_unchanged\", \"lib/matplotlib/tests/test_axes.py::test_hist_emptydata\", \"lib/matplotlib/tests/test_axes.py::test_hist_labels\", \"lib/matplotlib/tests/test_axes.py::test_transparent_markers[png]\", \"lib/matplotlib/tests/test_axes.py::test_transparent_markers[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_rgba_markers[png]\", \"lib/matplotlib/tests/test_axes.py::test_rgba_markers[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_mollweide_grid[png]\", \"lib/matplotlib/tests/test_axes.py::test_mollweide_grid[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_mollweide_forward_inverse_closure\", \"lib/matplotlib/tests/test_axes.py::test_mollweide_inverse_forward_closure\", \"lib/matplotlib/tests/test_axes.py::test_alpha[png]\", \"lib/matplotlib/tests/test_axes.py::test_alpha[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot[png]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_defaults[png]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors0]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors1]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors2]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_alpha\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_problem_kwargs[png]\", \"lib/matplotlib/tests/test_axes.py::test_empty_eventplot\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data0]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data1]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data2]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data0]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data1]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data2]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data0]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data1]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data2]\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_units_list[png]\", \"lib/matplotlib/tests/test_axes.py::test_marker_styles[png]\", \"lib/matplotlib/tests/test_axes.py::test_markers_fillstyle_rcparams[png]\", \"lib/matplotlib/tests/test_axes.py::test_vertex_markers[png]\", \"lib/matplotlib/tests/test_axes.py::test_eb_line_zorder[png]\", \"lib/matplotlib/tests/test_axes.py::test_eb_line_zorder[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_axline_loglog[png]\", \"lib/matplotlib/tests/test_axes.py::test_axline_loglog[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_axline[png]\", \"lib/matplotlib/tests/test_axes.py::test_axline[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_axline_transaxes[png]\", \"lib/matplotlib/tests/test_axes.py::test_axline_transaxes[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_axline_transaxes_panzoom[png]\", \"lib/matplotlib/tests/test_axes.py::test_axline_transaxes_panzoom[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_axline_args\", \"lib/matplotlib/tests/test_axes.py::test_vlines[png]\", \"lib/matplotlib/tests/test_axes.py::test_vlines_default\", \"lib/matplotlib/tests/test_axes.py::test_hlines[png]\", \"lib/matplotlib/tests/test_axes.py::test_hlines_default\", \"lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data0]\", \"lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data1]\", \"lib/matplotlib/tests/test_axes.py::test_vlines_hlines_blended_transform[png]\", \"lib/matplotlib/tests/test_axes.py::test_step_linestyle[png]\", \"lib/matplotlib/tests/test_axes.py::test_step_linestyle[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_mixed_collection[png]\", \"lib/matplotlib/tests/test_axes.py::test_mixed_collection[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_subplot_key_hash\", \"lib/matplotlib/tests/test_axes.py::test_specgram[png]\", \"lib/matplotlib/tests/test_axes.py::test_specgram_magnitude[png]\", \"lib/matplotlib/tests/test_axes.py::test_specgram_angle[png]\", \"lib/matplotlib/tests/test_axes.py::test_specgram_fs_none\", \"lib/matplotlib/tests/test_axes.py::test_specgram_origin_rcparam[png]\", \"lib/matplotlib/tests/test_axes.py::test_specgram_origin_kwarg\", \"lib/matplotlib/tests/test_axes.py::test_psd_csd[png]\", \"lib/matplotlib/tests/test_axes.py::test_spectrum[png]\", \"lib/matplotlib/tests/test_axes.py::test_psd_csd_edge_cases\", \"lib/matplotlib/tests/test_axes.py::test_twin_remove[png]\", \"lib/matplotlib/tests/test_axes.py::test_twin_spines[png]\", \"lib/matplotlib/tests/test_axes.py::test_twin_spines_on_top[png]\", \"lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[both-True-True]\", \"lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[major-True-False]\", \"lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[minor-False-True]\", \"lib/matplotlib/tests/test_axes.py::test_grid\", \"lib/matplotlib/tests/test_axes.py::test_reset_grid\", \"lib/matplotlib/tests/test_axes.py::test_reset_ticks[png]\", \"lib/matplotlib/tests/test_axes.py::test_vline_limit\", \"lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvline-axhline-args0]\", \"lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvspan-axhspan-args1]\", \"lib/matplotlib/tests/test_axes.py::test_empty_shared_subplots\", \"lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_1\", \"lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_2\", \"lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_3\", \"lib/matplotlib/tests/test_axes.py::test_shared_aspect_error\", \"lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args0-kwargs0-axis\\\\\\\\(\\\\\\\\)\", \"lib/matplotlib/tests/test_axes.py::test_axis_errors[ValueError-args1-kwargs1-Unrecognized\", \"lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args2-kwargs2-The\", \"lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args3-kwargs3-axis\\\\\\\\(\\\\\\\\)\", \"lib/matplotlib/tests/test_axes.py::test_axis_method_errors\", \"lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[x]\", \"lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[y]\", \"lib/matplotlib/tests/test_axes.py::test_relim_visible_only\", \"lib/matplotlib/tests/test_axes.py::test_text_labelsize\", \"lib/matplotlib/tests/test_axes.py::test_pie_default[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_linewidth_0[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_center_radius[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_linewidth_2[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_ccw_true[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_frame_grid[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_rotatelabels_true[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_nolabel_but_legend[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_shadow[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_textprops\", \"lib/matplotlib/tests/test_axes.py::test_pie_get_negative_values\", \"lib/matplotlib/tests/test_axes.py::test_normalize_kwarg_pie\", \"lib/matplotlib/tests/test_axes.py::test_pie_hatch_single[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_hatch_single[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_pie_hatch_multi[png]\", \"lib/matplotlib/tests/test_axes.py::test_pie_hatch_multi[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_set_get_ticklabels[png]\", \"lib/matplotlib/tests/test_axes.py::test_set_ticks_kwargs_raise_error_without_labels\", \"lib/matplotlib/tests/test_axes.py::test_set_ticks_with_labels[png]\", \"lib/matplotlib/tests/test_axes.py::test_xticks_bad_args\", \"lib/matplotlib/tests/test_axes.py::test_subsampled_ticklabels\", \"lib/matplotlib/tests/test_axes.py::test_mismatched_ticklabels\", \"lib/matplotlib/tests/test_axes.py::test_empty_ticks_fixed_loc\", \"lib/matplotlib/tests/test_axes.py::test_retain_tick_visibility[png]\", \"lib/matplotlib/tests/test_axes.py::test_tick_label_update\", \"lib/matplotlib/tests/test_axes.py::test_o_marker_path_snap[png]\", \"lib/matplotlib/tests/test_axes.py::test_margins\", \"lib/matplotlib/tests/test_axes.py::test_set_margin_updates_limits\", \"lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args0-kwargs0-margin\", \"lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args1-kwargs1-margin\", \"lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args2-kwargs2-margin\", \"lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args3-kwargs3-margin\", \"lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args4-kwargs4-Cannot\", \"lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args5-kwargs5-Cannot\", \"lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args6-kwargs6-Must\", \"lib/matplotlib/tests/test_axes.py::test_length_one_hist\", \"lib/matplotlib/tests/test_axes.py::test_set_xy_bound\", \"lib/matplotlib/tests/test_axes.py::test_pathological_hexbin\", \"lib/matplotlib/tests/test_axes.py::test_color_None\", \"lib/matplotlib/tests/test_axes.py::test_color_alias\", \"lib/matplotlib/tests/test_axes.py::test_numerical_hist_label\", \"lib/matplotlib/tests/test_axes.py::test_unicode_hist_label\", \"lib/matplotlib/tests/test_axes.py::test_move_offsetlabel\", \"lib/matplotlib/tests/test_axes.py::test_rc_spines[png]\", \"lib/matplotlib/tests/test_axes.py::test_rc_grid[png]\", \"lib/matplotlib/tests/test_axes.py::test_rc_tick\", \"lib/matplotlib/tests/test_axes.py::test_rc_major_minor_tick\", \"lib/matplotlib/tests/test_axes.py::test_square_plot\", \"lib/matplotlib/tests/test_axes.py::test_bad_plot_args\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy0-AxesImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy1-AxesImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy2-AxesImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy3-PcolorImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy4-QuadMesh]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy0-AxesImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy1-AxesImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy2-AxesImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy3-PcolorImage]\", \"lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy4-QuadMesh]\", \"lib/matplotlib/tests/test_axes.py::test_shared_scale\", \"lib/matplotlib/tests/test_axes.py::test_shared_bool\", \"lib/matplotlib/tests/test_axes.py::test_violin_point_mass\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs0]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs1]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs2]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs3]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs4]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs5]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs6]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs7]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs8]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs9]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs10]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs11]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs12]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs13]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs14]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs15]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs16]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs17]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs18]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs19]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs20]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs21]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs22]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs23]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs24]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs25]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs26]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs27]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs28]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs29]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs30]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs31]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs32]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs33]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs34]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs35]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs36]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs37]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs38]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs39]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs40]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs41]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs42]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs43]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs44]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs45]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs46]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs47]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs48]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs49]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs50]\", \"lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs51]\", \"lib/matplotlib/tests/test_axes.py::test_dash_offset[png]\", \"lib/matplotlib/tests/test_axes.py::test_dash_offset[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_title_pad\", \"lib/matplotlib/tests/test_axes.py::test_title_location_roundtrip\", \"lib/matplotlib/tests/test_axes.py::test_title_location_shared[True]\", \"lib/matplotlib/tests/test_axes.py::test_title_location_shared[False]\", \"lib/matplotlib/tests/test_axes.py::test_loglog[png]\", \"lib/matplotlib/tests/test_axes.py::test_loglog_nonpos[png]\", \"lib/matplotlib/tests/test_axes.py::test_axes_margins\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-x]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-y]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-x]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-y]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-x]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-y]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-x]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-y]\", \"lib/matplotlib/tests/test_axes.py::test_remove_shared_axes_relim\", \"lib/matplotlib/tests/test_axes.py::test_shared_axes_autoscale\", \"lib/matplotlib/tests/test_axes.py::test_adjust_numtick_aspect\", \"lib/matplotlib/tests/test_axes.py::test_auto_numticks\", \"lib/matplotlib/tests/test_axes.py::test_auto_numticks_log\", \"lib/matplotlib/tests/test_axes.py::test_broken_barh_empty\", \"lib/matplotlib/tests/test_axes.py::test_broken_barh_timedelta\", \"lib/matplotlib/tests/test_axes.py::test_pandas_pcolormesh\", \"lib/matplotlib/tests/test_axes.py::test_pandas_indexing_dates\", \"lib/matplotlib/tests/test_axes.py::test_pandas_errorbar_indexing\", \"lib/matplotlib/tests/test_axes.py::test_pandas_index_shape\", \"lib/matplotlib/tests/test_axes.py::test_pandas_indexing_hist\", \"lib/matplotlib/tests/test_axes.py::test_pandas_bar_align_center\", \"lib/matplotlib/tests/test_axes.py::test_axis_get_tick_params\", \"lib/matplotlib/tests/test_axes.py::test_axis_set_tick_params_labelsize_labelcolor\", \"lib/matplotlib/tests/test_axes.py::test_axes_tick_params_gridlines\", \"lib/matplotlib/tests/test_axes.py::test_axes_tick_params_ylabelside\", \"lib/matplotlib/tests/test_axes.py::test_axes_tick_params_xlabelside\", \"lib/matplotlib/tests/test_axes.py::test_none_kwargs\", \"lib/matplotlib/tests/test_axes.py::test_bar_uint8\", \"lib/matplotlib/tests/test_axes.py::test_date_timezone_x[png]\", \"lib/matplotlib/tests/test_axes.py::test_date_timezone_y[png]\", \"lib/matplotlib/tests/test_axes.py::test_date_timezone_x_and_y[png]\", \"lib/matplotlib/tests/test_axes.py::test_axisbelow[png]\", \"lib/matplotlib/tests/test_axes.py::test_titletwiny\", \"lib/matplotlib/tests/test_axes.py::test_titlesetpos\", \"lib/matplotlib/tests/test_axes.py::test_title_xticks_top\", \"lib/matplotlib/tests/test_axes.py::test_title_xticks_top_both\", \"lib/matplotlib/tests/test_axes.py::test_title_above_offset[left\", \"lib/matplotlib/tests/test_axes.py::test_title_above_offset[center\", \"lib/matplotlib/tests/test_axes.py::test_title_above_offset[both\", \"lib/matplotlib/tests/test_axes.py::test_title_no_move_off_page\", \"lib/matplotlib/tests/test_axes.py::test_offset_label_color\", \"lib/matplotlib/tests/test_axes.py::test_offset_text_visible\", \"lib/matplotlib/tests/test_axes.py::test_large_offset\", \"lib/matplotlib/tests/test_axes.py::test_barb_units\", \"lib/matplotlib/tests/test_axes.py::test_quiver_units\", \"lib/matplotlib/tests/test_axes.py::test_bar_color_cycle\", \"lib/matplotlib/tests/test_axes.py::test_tick_param_label_rotation\", \"lib/matplotlib/tests/test_axes.py::test_fillbetween_cycle\", \"lib/matplotlib/tests/test_axes.py::test_log_margins\", \"lib/matplotlib/tests/test_axes.py::test_color_length_mismatch\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_legend\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args0-kwargs0-lineoffsets\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args1-kwargs1-linelengths\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args2-kwargs2-linewidths\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args3-kwargs3-linestyles\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args4-kwargs4-alpha\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args5-kwargs5-positions\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args6-kwargs6-lineoffsets\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args7-kwargs7-linelengths\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args8-kwargs8-linewidths\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args9-kwargs9-linestyles\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args10-kwargs10-alpha\", \"lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args11-kwargs11-colors\", \"lib/matplotlib/tests/test_axes.py::test_bar_broadcast_args\", \"lib/matplotlib/tests/test_axes.py::test_invalid_axis_limits\", \"lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-symlog]\", \"lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-log]\", \"lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-symlog]\", \"lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-log]\", \"lib/matplotlib/tests/test_axes.py::test_twinx_knows_limits\", \"lib/matplotlib/tests/test_axes.py::test_zero_linewidth\", \"lib/matplotlib/tests/test_axes.py::test_empty_errorbar_legend\", \"lib/matplotlib/tests/test_axes.py::test_plot_decimal[png]\", \"lib/matplotlib/tests/test_axes.py::test_markerfacecolor_none_alpha[png]\", \"lib/matplotlib/tests/test_axes.py::test_tick_padding_tightbbox\", \"lib/matplotlib/tests/test_axes.py::test_inset\", \"lib/matplotlib/tests/test_axes.py::test_zoom_inset\", \"lib/matplotlib/tests/test_axes.py::test_inset_polar[png]\", \"lib/matplotlib/tests/test_axes.py::test_inset_projection\", \"lib/matplotlib/tests/test_axes.py::test_inset_subclass\", \"lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-False]\", \"lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-True]\", \"lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-False]\", \"lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-True]\", \"lib/matplotlib/tests/test_axes.py::test_set_position\", \"lib/matplotlib/tests/test_axes.py::test_spines_properbbox_after_zoom\", \"lib/matplotlib/tests/test_axes.py::test_limits_after_scroll_zoom\", \"lib/matplotlib/tests/test_axes.py::test_gettightbbox_ignore_nan\", \"lib/matplotlib/tests/test_axes.py::test_scatter_series_non_zero_index\", \"lib/matplotlib/tests/test_axes.py::test_scatter_empty_data\", \"lib/matplotlib/tests/test_axes.py::test_annotate_across_transforms[png]\", \"lib/matplotlib/tests/test_axes.py::test_secondary_xy[png]\", \"lib/matplotlib/tests/test_axes.py::test_secondary_fail\", \"lib/matplotlib/tests/test_axes.py::test_secondary_resize\", \"lib/matplotlib/tests/test_axes.py::test_secondary_minorloc\", \"lib/matplotlib/tests/test_axes.py::test_secondary_formatter\", \"lib/matplotlib/tests/test_axes.py::test_secondary_repr\", \"lib/matplotlib/tests/test_axes.py::test_axis_options[png]\", \"lib/matplotlib/tests/test_axes.py::test_normal_axes\", \"lib/matplotlib/tests/test_axes.py::test_nodecorator\", \"lib/matplotlib/tests/test_axes.py::test_displaced_spine\", \"lib/matplotlib/tests/test_axes.py::test_tickdirs\", \"lib/matplotlib/tests/test_axes.py::test_minor_accountedfor\", \"lib/matplotlib/tests/test_axes.py::test_axis_bool_arguments[png]\", \"lib/matplotlib/tests/test_axes.py::test_axis_extent_arg\", \"lib/matplotlib/tests/test_axes.py::test_axis_extent_arg2\", \"lib/matplotlib/tests/test_axes.py::test_hist_auto_bins\", \"lib/matplotlib/tests/test_axes.py::test_hist_nan_data\", \"lib/matplotlib/tests/test_axes.py::test_hist_range_and_density\", \"lib/matplotlib/tests/test_axes.py::test_bar_errbar_zorder\", \"lib/matplotlib/tests/test_axes.py::test_set_ticks_inverted\", \"lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_box\", \"lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_datalim\", \"lib/matplotlib/tests/test_axes.py::test_box_aspect\", \"lib/matplotlib/tests/test_axes.py::test_box_aspect_custom_position\", \"lib/matplotlib/tests/test_axes.py::test_bbox_aspect_axes_init\", \"lib/matplotlib/tests/test_axes.py::test_set_aspect_negative\", \"lib/matplotlib/tests/test_axes.py::test_redraw_in_frame\", \"lib/matplotlib/tests/test_axes.py::test_invisible_axes_events\", \"lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_markercolor\", \"lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_markercolor\", \"lib/matplotlib/tests/test_axes.py::test_unautoscale[True-x]\", \"lib/matplotlib/tests/test_axes.py::test_unautoscale[True-y]\", \"lib/matplotlib/tests/test_axes.py::test_unautoscale[False-x]\", \"lib/matplotlib/tests/test_axes.py::test_unautoscale[False-y]\", \"lib/matplotlib/tests/test_axes.py::test_unautoscale[None-x]\", \"lib/matplotlib/tests/test_axes.py::test_unautoscale[None-y]\", \"lib/matplotlib/tests/test_axes.py::test_polar_interpolation_steps_variable_r[png]\", \"lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_sticky\", \"lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_xticklabelcolor\", \"lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_yticklabelcolor\", \"lib/matplotlib/tests/test_axes.py::test_xaxis_offsetText_color\", \"lib/matplotlib/tests/test_axes.py::test_yaxis_offsetText_color\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-small]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-small]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[small]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[medium]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[large]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-large]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-large]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[larger]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[smaller]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[8]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[10]\", \"lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[12]\", \"lib/matplotlib/tests/test_axes.py::test_multiplot_autoscale\", \"lib/matplotlib/tests/test_axes.py::test_sharing_does_not_link_positions\", \"lib/matplotlib/tests/test_axes.py::test_2dcolor_plot[pdf]\", \"lib/matplotlib/tests/test_axes.py::test_shared_axes_clear[png]\", \"lib/matplotlib/tests/test_axes.py::test_shared_axes_retick\", \"lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[left]\", \"lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[center]\", \"lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[right]\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical_yinverted\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_yinverted\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xinverted\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xyinverted\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_center\", \"lib/matplotlib/tests/test_axes.py::test_centered_bar_label_label_beyond_limits\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_location_errorbars\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[%.2f]\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[{:.2f}]\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[format]\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_fmt_error\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_labels\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata\", \"lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata_inverted\", \"lib/matplotlib/tests/test_axes.py::test_nan_barlabels\", \"lib/matplotlib/tests/test_axes.py::test_patch_bounds\", \"lib/matplotlib/tests/test_axes.py::test_warn_ignored_scatter_kwargs\", \"lib/matplotlib/tests/test_axes.py::test_artist_sublists\", \"lib/matplotlib/tests/test_axes.py::test_empty_line_plots\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-f-'f'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-o+-'o\\\\\\\\+'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:--':-'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-rk-'rk'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:o-r-':o-r'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-f-'f'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-o+-'o\\\\\\\\+'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:--':-'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-rk-'rk'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:o-r-':o-r'\", \"lib/matplotlib/tests/test_axes.py::test_plot_format\", \"lib/matplotlib/tests/test_axes.py::test_automatic_legend\", \"lib/matplotlib/tests/test_axes.py::test_plot_errors\", \"lib/matplotlib/tests/test_axes.py::test_clim\", \"lib/matplotlib/tests/test_axes.py::test_bezier_autoscale\", \"lib/matplotlib/tests/test_axes.py::test_small_autoscale\", \"lib/matplotlib/tests/test_axes.py::test_get_xticklabel\", \"lib/matplotlib/tests/test_axes.py::test_bar_leading_nan\", \"lib/matplotlib/tests/test_axes.py::test_bar_all_nan[png]\", \"lib/matplotlib/tests/test_axes.py::test_extent_units[png]\", \"lib/matplotlib/tests/test_axes.py::test_cla_clears_children_axes_and_fig\", \"lib/matplotlib/tests/test_axes.py::test_scatter_color_repr_error\", \"lib/matplotlib/tests/test_axes.py::test_zorder_and_explicit_rasterization\", \"lib/matplotlib/tests/test_axes.py::test_preset_clip_paths[png]\", \"lib/matplotlib/tests/test_axes.py::test_rc_axes_label_formatting\", \"lib/matplotlib/tests/test_axes.py::test_ecdf[png]\", \"lib/matplotlib/tests/test_axes.py::test_ecdf_invalid\", \"lib/matplotlib/tests/test_axes.py::test_fill_between_axes_limits\", \"lib/matplotlib/tests/test_axes.py::test_tick_param_labelfont\", \"lib/matplotlib/tests/test_axes.py::test_set_secondary_axis_color\"]", "environment_setup_commit": "0849036fd992a2dd133a0cffc3f84f58ccf1840f", "test_directives": ["lib/matplotlib/tests/test_axes.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v lib/matplotlib/tests/test_axes.py", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py\nindex 8d1e20b4cb..605cbc86fa 100644\n--- a/lib/matplotlib/tests/test_pickle.py\n+++ b/lib/matplotlib/tests/test_pickle.py\n@@ -301,3 +301,23 @@ def test_cycler():\n ax = pickle.loads(pickle.dumps(ax))\n l, = ax.plot([3, 4])\n assert l.get_color() == \"m\"\n+\n+def test_xlim_changed_on_shared_axis():\n+ import matplotlib.pyplot as plt\n+ import numpy as np\n+\n+ fig, (ax1, ax2) = plt.subplots(2, sharex=True)\n+ xlim_changed_called = [False, False]\n+\n+ def on_xlim_changed(event):\n+ if event is ax1:\n+ xlim_changed_called[0] = True\n+ elif event is ax2:\n+ xlim_changed_called[1] = True\n+\n+ ax1.callbacks.connect('xlim_changed', on_xlim_changed)\n+ ax2.callbacks.connect('xlim_changed', on_xlim_changed)\n+\n+ ax1.set_xlim(0, 10)\n+ assert xlim_changed_called == [True, True], \"xlim_changed not called for both axes\"\n+ \n\\ No newline at end of file\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["lib/matplotlib/tests/test_pickle.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/lib/matplotlib/axes/_base.pyi b/lib/matplotlib/axes/_base.pyi\nindex 507ecc2e51..c0be017231 100644\n--- a/lib/matplotlib/axes/_base.pyi\n+++ b/lib/matplotlib/axes/_base.pyi\n@@ -318,7 +318,18 @@ class _AxesBase(martist.Artist):\n auto: bool | None = ...,\n xmin: float | None = ...,\n xmax: float | None = ...\n- ) -> tuple[float, float]: ...\n+ ) -> tuple[float, float]:\n+ # Original implementation details\n+ ...\n+ # Ensure callbacks are processed outside the emit check\n+ if emit:\n+ self.callbacks.process('xlim_changed', self)\n+ for ax in self._shared_x_axes.get_siblings(self):\n+ if ax is not self:\n+ ax.set_xlim(left, right, emit=False, auto=auto, xmin=xmin, xmax=xmax)\n+ if not emit:\n+ self.callbacks.process('xlim_changed', self)\n+ return left, right\n def get_ylabel(self) -> str: ...\n def set_ylabel(\n self,\n", "model_lint_repair_patch": "diff --git a/lib/matplotlib/axes/_base.pyi b/lib/matplotlib/axes/_base.pyi\nindex 507ecc2e51..c0be017231 100644\n--- a/lib/matplotlib/axes/_base.pyi\n+++ b/lib/matplotlib/axes/_base.pyi\n@@ -318,7 +318,18 @@ class _AxesBase(martist.Artist):\n auto: bool | None = ...,\n xmin: float | None = ...,\n xmax: float | None = ...\n- ) -> tuple[float, float]: ...\n+ ) -> tuple[float, float]:\n+ # Original implementation details\n+ ...\n+ # Ensure callbacks are processed outside the emit check\n+ if emit:\n+ self.callbacks.process('xlim_changed', self)\n+ for ax in self._shared_x_axes.get_siblings(self):\n+ if ax is not self:\n+ ax.set_xlim(left, right, emit=False, auto=auto, xmin=xmin, xmax=xmax)\n+ if not emit:\n+ self.callbacks.process('xlim_changed', self)\n+ return left, right\n def get_ylabel(self) -> str: ...\n def set_ylabel(\n self,\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-16139", "base_commit": "d559cb02da30f74debbb1fc3a46de0df134d2d80", "patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\n--- a/django/contrib/auth/forms.py\n+++ b/django/contrib/auth/forms.py\n@@ -163,7 +163,9 @@ def __init__(self, *args, **kwargs):\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(\n+ f\"../../{self.instance.pk}/password/\"\n+ )\n user_permissions = self.fields.get(\"user_permissions\")\n if user_permissions:\n user_permissions.queryset = user_permissions.queryset.select_related(\n", "test_patch": "diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py\n--- a/tests/auth_tests/test_forms.py\n+++ b/tests/auth_tests/test_forms.py\n@@ -1,5 +1,6 @@\n import datetime\n import re\n+import urllib.parse\n from unittest import mock\n \n from django.contrib.auth.forms import (\n@@ -22,6 +23,7 @@\n from django.forms import forms\n from django.forms.fields import CharField, Field, IntegerField\n from django.test import SimpleTestCase, TestCase, override_settings\n+from django.urls import reverse\n from django.utils import translation\n from django.utils.text import capfirst\n from django.utils.translation import gettext as _\n@@ -892,6 +894,26 @@ def test_bug_19349_bound_password_field(self):\n # value to render correctly\n self.assertEqual(form.initial[\"password\"], form[\"password\"].value())\n \n+ @override_settings(ROOT_URLCONF=\"auth_tests.urls_admin\")\n+ def test_link_to_password_reset_in_helptext_via_to_field(self):\n+ user = User.objects.get(username=\"testclient\")\n+ form = UserChangeForm(data={}, instance=user)\n+ password_help_text = form.fields[\"password\"].help_text\n+ matches = re.search('', password_help_text)\n+\n+ # URL to UserChangeForm in admin via to_field (instead of pk).\n+ admin_user_change_url = reverse(\n+ f\"admin:{user._meta.app_label}_{user._meta.model_name}_change\",\n+ args=(user.username,),\n+ )\n+ joined_url = urllib.parse.urljoin(admin_user_change_url, matches.group(1))\n+\n+ pw_change_url = reverse(\n+ f\"admin:{user._meta.app_label}_{user._meta.model_name}_password_change\",\n+ args=(user.pk,),\n+ )\n+ self.assertEqual(joined_url, pw_change_url)\n+\n def test_custom_form(self):\n class CustomUserChangeForm(UserChangeForm):\n class Meta(UserChangeForm.Meta):\n", "problem_statement": "Accessing UserAdmin via to_field leads to link to PasswordResetForm being broken (404)\nDescription\n\t \n\t\t(last modified by Simon Kern)\n\t \nAccessing the UserAdmin via another model's Admin that has a reference to User (with to_field set, e.g., to_field=\"uuid\") leads to the UserAdmin being accessed via an url that looks similar to this one:\n.../user/22222222-3333-4444-5555-666677778888/change/?_to_field=uuid\nHowever the underlying form looks like this: \nCode highlighting:\nclass UserChangeForm(forms.ModelForm):\n\tpassword = ReadOnlyPasswordHashField(\n\t\tlabel=_(\"Password\"),\n\t\thelp_text=_(\n\t\t\t\"Raw passwords are not stored, so there is no way to see this \"\n\t\t\t\"user\u2019s password, but you can change the password using \"\n\t\t\t'this form.'\n\t\t),\n\t)\n\t...\n\t...\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tpassword = self.fields.get(\"password\")\n\t\tif password:\n\t\t\tpassword.help_text = password.help_text.format(\"../password/\")\n\t...\n\t...\nThis results in the link to the PasswordResetForm being wrong and thus ending up in a 404. If we drop the assumption that UserAdmin is always accessed via its pk, then we're good to go. It's as simple as replacing password.help_text = password.help_text.format(\"../password/\") with password.help_text = password.help_text.format(f\"../../{self.instance.pk}/password/\")\nI've opened a pull request on GitHub for this Ticket, please see:\n\u200bPR\n", "hints_text": "", "created_at": "2022-09-30T08:51:16Z", "version": "4.2", "FAIL_TO_PASS": "[\"test_link_to_password_reset_in_helptext_via_to_field (auth_tests.test_forms.UserChangeFormTest)\"]", "PASS_TO_PASS": "[\"test_field_order (auth_tests.test_forms.PasswordChangeFormTest)\", \"test_html_autocomplete_attributes (auth_tests.test_forms.PasswordChangeFormTest)\", \"test_incorrect_password (auth_tests.test_forms.PasswordChangeFormTest)\", \"test_password_verification (auth_tests.test_forms.PasswordChangeFormTest)\", \"test_password_whitespace_not_stripped (auth_tests.test_forms.PasswordChangeFormTest)\", \"test_success (auth_tests.test_forms.PasswordChangeFormTest)\", \"test_html_autocomplete_attributes (auth_tests.test_forms.AdminPasswordChangeFormTest)\", \"test_missing_passwords (auth_tests.test_forms.AdminPasswordChangeFormTest)\", \"test_non_matching_passwords (auth_tests.test_forms.AdminPasswordChangeFormTest)\", \"test_one_password (auth_tests.test_forms.AdminPasswordChangeFormTest)\", \"test_password_whitespace_not_stripped (auth_tests.test_forms.AdminPasswordChangeFormTest)\", \"test_success (auth_tests.test_forms.AdminPasswordChangeFormTest)\", \"test_both_passwords (auth_tests.test_forms.UserCreationFormTest)\", \"test_custom_form (auth_tests.test_forms.UserCreationFormTest)\", \"test_custom_form_hidden_username_field (auth_tests.test_forms.UserCreationFormTest)\", \"test_custom_form_with_different_username_field (auth_tests.test_forms.UserCreationFormTest)\", \"To prevent almost identical usernames, visually identical but differing\", \"test_html_autocomplete_attributes (auth_tests.test_forms.UserCreationFormTest)\", \"test_invalid_data (auth_tests.test_forms.UserCreationFormTest)\", \"test_normalize_username (auth_tests.test_forms.UserCreationFormTest)\", \"test_password_help_text (auth_tests.test_forms.UserCreationFormTest)\", \"test_password_verification (auth_tests.test_forms.UserCreationFormTest)\", \"test_password_whitespace_not_stripped (auth_tests.test_forms.UserCreationFormTest)\", \"test_success (auth_tests.test_forms.UserCreationFormTest)\", \"test_unicode_username (auth_tests.test_forms.UserCreationFormTest)\", \"test_user_already_exists (auth_tests.test_forms.UserCreationFormTest)\", \"UserCreationForm password validation uses all of the form's data.\", \"test_username_field_autocapitalize_none (auth_tests.test_forms.UserCreationFormTest)\", \"test_validates_password (auth_tests.test_forms.UserCreationFormTest)\", \"test_bug_19349_render_with_none_value (auth_tests.test_forms.ReadOnlyPasswordHashTest)\", \"ReadOnlyPasswordHashWidget doesn't contain a for attribute in the\", \"test_readonly_field_has_changed (auth_tests.test_forms.ReadOnlyPasswordHashTest)\", \"test_render (auth_tests.test_forms.ReadOnlyPasswordHashTest)\", \"test_help_text_translation (auth_tests.test_forms.SetPasswordFormTest)\", \"test_html_autocomplete_attributes (auth_tests.test_forms.SetPasswordFormTest)\", \"test_no_password (auth_tests.test_forms.SetPasswordFormTest)\", \"test_password_verification (auth_tests.test_forms.SetPasswordFormTest)\", \"test_password_whitespace_not_stripped (auth_tests.test_forms.SetPasswordFormTest)\", \"test_success (auth_tests.test_forms.SetPasswordFormTest)\", \"test_validates_password (auth_tests.test_forms.SetPasswordFormTest)\", \"test_custom_login_allowed_policy (auth_tests.test_forms.AuthenticationFormTest)\", \"test_get_invalid_login_error (auth_tests.test_forms.AuthenticationFormTest)\", \"test_html_autocomplete_attributes (auth_tests.test_forms.AuthenticationFormTest)\", \"test_inactive_user (auth_tests.test_forms.AuthenticationFormTest)\", \"test_inactive_user_i18n (auth_tests.test_forms.AuthenticationFormTest)\", \"An invalid login doesn't leak the inactive status of a user.\", \"test_integer_username (auth_tests.test_forms.AuthenticationFormTest)\", \"test_invalid_username (auth_tests.test_forms.AuthenticationFormTest)\", \"test_login_failed (auth_tests.test_forms.AuthenticationFormTest)\", \"test_no_password (auth_tests.test_forms.AuthenticationFormTest)\", \"test_password_whitespace_not_stripped (auth_tests.test_forms.AuthenticationFormTest)\", \"test_success (auth_tests.test_forms.AuthenticationFormTest)\", \"test_unicode_username (auth_tests.test_forms.AuthenticationFormTest)\", \"test_username_field_autocapitalize_none (auth_tests.test_forms.AuthenticationFormTest)\", \"test_username_field_label (auth_tests.test_forms.AuthenticationFormTest)\", \"test_username_field_label_empty_string (auth_tests.test_forms.AuthenticationFormTest)\", \"test_username_field_label_not_set (auth_tests.test_forms.AuthenticationFormTest)\", \"test_username_field_max_length_defaults_to_254 (auth_tests.test_forms.AuthenticationFormTest)\", \"test_username_field_max_length_matches_user_model (auth_tests.test_forms.AuthenticationFormTest)\", \"test_cleaned_data (auth_tests.test_forms.PasswordResetFormTest)\", \"test_custom_email_constructor (auth_tests.test_forms.PasswordResetFormTest)\", \"test_custom_email_field (auth_tests.test_forms.PasswordResetFormTest)\", \"test_custom_email_subject (auth_tests.test_forms.PasswordResetFormTest)\", \"test_html_autocomplete_attributes (auth_tests.test_forms.PasswordResetFormTest)\", \"Inactive user cannot receive password reset email.\", \"test_invalid_email (auth_tests.test_forms.PasswordResetFormTest)\", \"Test nonexistent email address. This should not fail because it would\", \"Preserve the case of the user name (before the @ in the email address)\", \"Test the PasswordResetForm.save() method with html_email_template_name\", \"Test the PasswordResetForm.save() method with no html_email_template_name\", \"test_unusable_password (auth_tests.test_forms.PasswordResetFormTest)\", \"test_user_email_domain_unicode_collision (auth_tests.test_forms.PasswordResetFormTest)\", \"test_user_email_domain_unicode_collision_nonexistent (auth_tests.test_forms.PasswordResetFormTest)\", \"test_user_email_unicode_collision (auth_tests.test_forms.PasswordResetFormTest)\", \"test_user_email_unicode_collision_nonexistent (auth_tests.test_forms.PasswordResetFormTest)\", \"test_bug_14242 (auth_tests.test_forms.UserChangeFormTest)\", \"test_bug_17944_empty_password (auth_tests.test_forms.UserChangeFormTest)\", \"test_bug_17944_unknown_password_algorithm (auth_tests.test_forms.UserChangeFormTest)\", \"test_bug_17944_unmanageable_password (auth_tests.test_forms.UserChangeFormTest)\", \"The change form does not return the password value\", \"test_bug_19349_bound_password_field (auth_tests.test_forms.UserChangeFormTest)\", \"test_custom_form (auth_tests.test_forms.UserChangeFormTest)\", \"test_password_excluded (auth_tests.test_forms.UserChangeFormTest)\", \"test_unusable_password (auth_tests.test_forms.UserChangeFormTest)\", \"test_username_field_autocapitalize_none (auth_tests.test_forms.UserChangeFormTest)\", \"test_username_validity (auth_tests.test_forms.UserChangeFormTest)\"]", "environment_setup_commit": "0fbdb9784da915fce5dcc1fe82bac9b4785749e5", "test_directives": ["auth_tests.test_forms"], "test_cmd": "./tests/runtests.py --verbosity 2 auth_tests.test_forms", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["auth_tests.test_forms"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\nindex b3cfc6723c..f6c4b7fc2f 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", "model_lint_repair_patch": "diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py\nindex b3cfc6723c..f6c4b7fc2f 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", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["auth_tests.test_forms"]} +{"repo": "django/django", "instance_id": "django__django-11999", "base_commit": "84633905273fc916e3d17883810d9969c03f73c2", "patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -763,8 +763,12 @@ def contribute_to_class(self, cls, name, private_only=False):\n if not getattr(cls, self.attname, None):\n setattr(cls, self.attname, self.descriptor_class(self))\n if self.choices is not None:\n- setattr(cls, 'get_%s_display' % self.name,\n- partialmethod(cls._get_FIELD_display, field=self))\n+ if not hasattr(cls, 'get_%s_display' % self.name):\n+ setattr(\n+ cls,\n+ 'get_%s_display' % self.name,\n+ partialmethod(cls._get_FIELD_display, field=self),\n+ )\n \n def get_filter_kwargs_for_object(self, obj):\n \"\"\"\n", "test_patch": "diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py\n--- a/tests/model_fields/tests.py\n+++ b/tests/model_fields/tests.py\n@@ -168,6 +168,16 @@ def test_get_FIELD_display_translated(self):\n self.assertIsInstance(val, str)\n self.assertEqual(val, 'translated')\n \n+ def test_overriding_FIELD_display(self):\n+ class FooBar(models.Model):\n+ foo_bar = models.IntegerField(choices=[(1, 'foo'), (2, 'bar')])\n+\n+ def get_foo_bar_display(self):\n+ return 'something'\n+\n+ f = FooBar(foo_bar=1)\n+ self.assertEqual(f.get_foo_bar_display(), 'something')\n+\n def test_iterator_choices(self):\n \"\"\"\n get_choices() works with Iterators.\n", "problem_statement": "Cannot override get_FOO_display() in Django 2.2+.\nDescription\n\t\nI cannot override the get_FIELD_display function on models since version 2.2. It works in version 2.1.\nExample:\nclass FooBar(models.Model):\n\tfoo_bar = models.CharField(_(\"foo\"), choices=[(1, 'foo'), (2, 'bar')])\n\tdef __str__(self):\n\t\treturn self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1\n\tdef get_foo_bar_display(self):\n\t\treturn \"something\"\nWhat I expect is that I should be able to override this function.\n", "hints_text": "Thanks for this report. Regression in a68ea231012434b522ce45c513d84add516afa60. Reproduced at 54a7b021125d23a248e70ba17bf8b10bc8619234.\nOK, I have a lead on this. Not at all happy about how it looks at first pass, but I'll a proof of concept PR together for it tomorrow AM.\nI don't think it should be marked as blocker since it looks like it was never supported, because it depends on the order of attrs passed in ModelBase.__new__(). So on Django 2.1 and Python 3.7: In [1]: import django ...: django.VERSION In [2]: from django.db import models ...: ...: class FooBar(models.Model): ...: def get_foo_bar_display(self): ...: return \"something\" ...: ...: foo_bar = models.CharField(\"foo\", choices=[(1, 'foo'), (2, 'bar')]) ...: ...: def __str__(self): ...: return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 ...: ...: class Meta: ...: app_label = 'test' ...: ...: FooBar(foo_bar=1) Out[2]: Before \u200bPython 3.6 the order of attrs wasn't defined at all.\nSergey, an example from the ticket description works for me with Django 2.1 and Python 3.6, 3.7 and 3.8.\nIn [2]: import django ...: django.VERSION Out[2]: (2, 1, 13, 'final', 0) In [3]: import sys ...: sys.version Out[3]: '3.5.7 (default, Oct 17 2019, 07:04:41) \\n[GCC 8.3.0]' In [4]: from django.db import models ...: ...: class FooBar(models.Model): ...: foo_bar = models.CharField(\"foo\", choices=[(1, 'foo'), (2, 'bar')]) ...: ...: def __str__(self): ...: return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 ...: ...: def get_foo_bar_display(self): ...: return \"something\" ...: ...: class Meta: ...: app_label = 'test' ...: ...: FooBar(foo_bar=1) Out[4]: \nOK, so there is a behaviour change here, but Sergey is correct that it does depend on attr order, so it's hard to say that this can be said to ever have been thought of as supported, with the exact example provided. This example produces the opposite result on 2.1 (even on >=PY36): def test_overriding_display_backwards(self): class FooBar2(models.Model): def get_foo_bar_display(self): return \"something\" foo_bar = models.CharField(\"foo\", choices=[(1, 'foo'), (2, 'bar')]) f = FooBar2(foo_bar=1) # This returns 'foo' or 'bar' in both 2.2 and 2.1 self.assertEqual(f.get_foo_bar_display(), \"foo\") Because get_foo_bar_display() is defined before foo_bar is gets replaced in the the add_to_class() step. Semantically order shouldn't make a difference. Given that it does, I can't see that we're bound to maintain that behaviour. (There's a possible fix in Field.contribute_to_class() but implementing that just reverses the pass/fail behaviour depending on order...) Rather, the correct way to implement this on 2.2+ is: def test_overriding_display(self): class FooBar(models.Model): foo_bar = models.CharField(\"foo\", choices=[(1, 'foo'), (2, 'bar')]) def _get_FIELD_display(self, field): if field.attname == 'foo_bar': return \"something\" return super()._get_FIELD_display(field) f = FooBar(foo_bar=1) self.assertEqual(f.get_foo_bar_display(), \"something\") This is stable for declaration order on version 2.2+. This approach requires overriding _get_FIELD_display() before declaring fields on 2.1, because otherwise Model._get_FIELD_display() is picked up during Field.contribute_to_class(). This ordering dependency is, ultimately, the same issue that was addressed in a68ea231012434b522ce45c513d84add516afa60, and the follow-up in #30254. The behaviour in 2.1 (and before) was incorrect. Yes, there's a behaviour change here but it's a bugfix, and all bugfixes are breaking changes if you're depending on the broken behaviour. I'm going to downgrade this from Release Blocker accordingly. I'll reclassify this as a Documentation issue and provide the working example, as overriding _get_FIELD_display() is a legitimate use-case I'd guess.\nReplying to Carlton Gibson: (There's a possible fix in Field.contribute_to_class() but implementing that just reverses the pass/fail behaviour depending on order...) Doesn't this fix it? if not hasattr(cls, 'get_%s_display' % self.name): setattr(cls, 'get_%s_display' % self.name, partialmethod(cls._get_FIELD_display, field=self))", "created_at": "2019-10-31T10:39:18Z", "version": "3.1", "FAIL_TO_PASS": "[\"test_overriding_FIELD_display (model_fields.tests.GetFieldDisplayTests)\"]", "PASS_TO_PASS": "[\"test_blank_in_choices (model_fields.tests.GetChoicesTests)\", \"test_blank_in_grouped_choices (model_fields.tests.GetChoicesTests)\", \"test_empty_choices (model_fields.tests.GetChoicesTests)\", \"test_lazy_strings_not_evaluated (model_fields.tests.GetChoicesTests)\", \"test_check (model_fields.tests.ChoicesTests)\", \"test_choices (model_fields.tests.ChoicesTests)\", \"test_flatchoices (model_fields.tests.ChoicesTests)\", \"test_formfield (model_fields.tests.ChoicesTests)\", \"test_invalid_choice (model_fields.tests.ChoicesTests)\", \"Can supply a custom choices form class to Field.formfield()\", \"deconstruct() uses __qualname__ for nested class support.\", \"Field instances can be pickled.\", \"test_field_name (model_fields.tests.BasicFieldTests)\", \"Fields are ordered based on their creation.\", \"test_field_repr (model_fields.tests.BasicFieldTests)\", \"__repr__() uses __qualname__ for nested class support.\", \"test_field_str (model_fields.tests.BasicFieldTests)\", \"test_field_verbose_name (model_fields.tests.BasicFieldTests)\", \"Field.formfield() sets disabled for fields with choices.\", \"test_show_hidden_initial (model_fields.tests.BasicFieldTests)\", \"test_choices_and_field_display (model_fields.tests.GetFieldDisplayTests)\", \"test_empty_iterator_choices (model_fields.tests.GetFieldDisplayTests)\", \"A translated display value is coerced to str.\", \"test_iterator_choices (model_fields.tests.GetFieldDisplayTests)\", \"test_get_choices (model_fields.tests.GetChoicesLimitChoicesToTests)\", \"test_get_choices_reverse_related_field (model_fields.tests.GetChoicesLimitChoicesToTests)\", \"test_get_choices (model_fields.tests.GetChoicesOrderingTests)\", \"test_get_choices_default_ordering (model_fields.tests.GetChoicesOrderingTests)\", \"test_get_choices_reverse_related_field (model_fields.tests.GetChoicesOrderingTests)\", \"test_get_choices_reverse_related_field_default_ordering (model_fields.tests.GetChoicesOrderingTests)\"]", "environment_setup_commit": "0668164b4ac93a5be79f5b87fae83c657124d9ab", "test_directives": ["model_fields.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 model_fields.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py\nindex 0d6e930b06..db29a6306d 100644\n--- a/tests/model_fields/tests.py\n+++ b/tests/model_fields/tests.py\n@@ -29,6 +29,20 @@ class BasicFieldTests(SimpleTestCase):\n form_field = model_field.formfield(show_hidden_initial=True)\n self.assertTrue(form_field.show_hidden_initial)\n \n+ def test_custom_get_FIELD_display(self):\n+ \"\"\"\n+ Custom get_FIELD_display method should be called and return the expected value.\n+ \"\"\"\n+ class FooBar(models.Model):\n+ foo_bar = models.CharField(choices=[(1, 'foo'), (2, 'bar')])\n+\n+ def get_foo_bar_display(self):\n+ return \"something\"\n+\n+ instance = FooBar(foo_bar=1)\n+ self.assertEqual(instance.get_foo_bar_display(), \"something\")\n+\n+ model_field = models.Field(choices=[(1, 'foo'), (2, 'bar')])\n form_field = model_field.formfield(show_hidden_initial=False)\n self.assertFalse(form_field.show_hidden_initial)\n \n", "model_prepare_test_num_attempts": 1, "model_test_directives": ["model_fields.tests"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex baa0c875b2..e8ae9cfd66 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -232,11 +232,17 @@ class Options:\n except StopIteration:\n raise FieldDoesNotExist(\"%s has no field named '%s'\" % (self.object_name, query))\n \n- self.ordering = ('_order',)\n- if not any(isinstance(field, OrderWrt) for field in model._meta.local_fields):\n- model.add_to_class('_order', OrderWrt())\n- else:\n- self.order_with_respect_to = None\n+ self.ordering = ('_order',)\n+ if not any(isinstance(field, OrderWrt) for field in model._meta.local_fields):\n+ model.add_to_class('_order', OrderWrt())\n+ else:\n+ self.order_with_respect_to = None\n+\n+ # Check for overridden get_FIELD_display methods\n+ for field in self.local_fields:\n+ display_method_name = f'get_{field.name}_display'\n+ if hasattr(model, display_method_name):\n+ setattr(model, display_method_name, getattr(model, display_method_name))\n \n if self.pk is None:\n if self.parents:\n", "model_lint_repair_patch": "diff --git a/django/db/models/options.py b/django/db/models/options.py\nindex baa0c875b2..e8ae9cfd66 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -232,11 +232,17 @@ class Options:\n except StopIteration:\n raise FieldDoesNotExist(\"%s has no field named '%s'\" % (self.object_name, query))\n \n- self.ordering = ('_order',)\n- if not any(isinstance(field, OrderWrt) for field in model._meta.local_fields):\n- model.add_to_class('_order', OrderWrt())\n- else:\n- self.order_with_respect_to = None\n+ self.ordering = ('_order',)\n+ if not any(isinstance(field, OrderWrt) for field in model._meta.local_fields):\n+ model.add_to_class('_order', OrderWrt())\n+ else:\n+ self.order_with_respect_to = None\n+\n+ # Check for overridden get_FIELD_display methods\n+ for field in self.local_fields:\n+ display_method_name = f'get_{field.name}_display'\n+ if hasattr(model, display_method_name):\n+ setattr(model, display_method_name, getattr(model, display_method_name))\n \n if self.pk is None:\n if self.parents:\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "django/django", "instance_id": "django__django-11620", "base_commit": "514efa3129792ec2abb2444f3e7aeb3f21a38386", "patch": "diff --git a/django/views/debug.py b/django/views/debug.py\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -5,10 +5,10 @@\n from pathlib import Path\n \n from django.conf import settings\n-from django.http import HttpResponse, HttpResponseNotFound\n+from django.http import Http404, HttpResponse, HttpResponseNotFound\n from django.template import Context, Engine, TemplateDoesNotExist\n from django.template.defaultfilters import pprint\n-from django.urls import Resolver404, resolve\n+from django.urls import resolve\n from django.utils import timezone\n from django.utils.datastructures import MultiValueDict\n from django.utils.encoding import force_str\n@@ -483,7 +483,7 @@ def technical_404_response(request, exception):\n caller = ''\n try:\n resolver_match = resolve(request.path)\n- except Resolver404:\n+ except Http404:\n pass\n else:\n obj = resolver_match.func\n", "test_patch": "diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py\n--- a/tests/view_tests/tests/test_debug.py\n+++ b/tests/view_tests/tests/test_debug.py\n@@ -12,11 +12,13 @@\n from django.core import mail\n from django.core.files.uploadedfile import SimpleUploadedFile\n from django.db import DatabaseError, connection\n+from django.http import Http404\n from django.shortcuts import render\n from django.template import TemplateDoesNotExist\n from django.test import RequestFactory, SimpleTestCase, override_settings\n from django.test.utils import LoggingCaptureMixin\n from django.urls import path, reverse\n+from django.urls.converters import IntConverter\n from django.utils.functional import SimpleLazyObject\n from django.utils.safestring import mark_safe\n from django.views.debug import (\n@@ -237,6 +239,11 @@ def test_template_encoding(self):\n technical_404_response(mock.MagicMock(), mock.Mock())\n m.assert_called_once_with(encoding='utf-8')\n \n+ def test_technical_404_converter_raise_404(self):\n+ with mock.patch.object(IntConverter, 'to_python', side_effect=Http404):\n+ response = self.client.get('/path-post/1/')\n+ self.assertContains(response, 'Page not found', status_code=404)\n+\n \n class DebugViewQueriesAllowedTests(SimpleTestCase):\n # May need a query to initialize MySQL connection\n", "problem_statement": "When DEBUG is True, raising Http404 in a path converter's to_python method does not result in a technical response\nDescription\n\t\nThis is the response I get (plain text): \nA server error occurred. Please contact the administrator.\nI understand a ValueError should be raised which tells the URL resolver \"this path does not match, try next one\" but Http404 is what came to my mind intuitively and the error message was not very helpful.\nOne could also make a point that raising a Http404 should be valid way to tell the resolver \"this is indeed the right path but the current parameter value does not match anything so stop what you are doing and let the handler return the 404 page (including a helpful error message when DEBUG is True instead of the default 'Django tried these URL patterns')\".\nThis would prove useful for example to implement a path converter that uses get_object_or_404.\n", "hints_text": "It seems that other exceptions correctly result in a technical 500 response.\nThe technical_404_response view performs a new URL resolving (cf \u200bhttps://github.com/django/django/blob/a8e492bc81fca829f5d270e2d57703c02e58701e/django/views/debug.py#L482) which will obviously raise a new Http404 which won't be caught as only Resolver404 is checked. That means the WSGI handler fails and the WSGI server returns the previously described default error message (indeed the error message is the default one from wsgiref.handlers.BaseHandler \u200bhttps://docs.python.org/3.6/library/wsgiref.html#wsgiref.handlers.BaseHandler.error_body). The solution seems to be to catch Http404 instead of Resolver404 in technical_404_response. This will result in a technical 404 page with the Http404's message displayed and will match the behaviour of when DEBUG is False.\nCreated \u200bPR , but I am not sure how to write the tests. I've looking about the response before and after catch Http404 instead of Resolver404, and there is no difference. Should I also change the technical_404.html for response?\nI've added test to the patch, but not sure if it is correct.\nI have made the requested changes; please review again", "created_at": "2019-08-02T13:56:08Z", "version": "3.0", "FAIL_TO_PASS": "[\"test_technical_404_converter_raise_404 (view_tests.tests.test_debug.DebugViewTests)\"]", "PASS_TO_PASS": "[\"test_repr (view_tests.tests.test_debug.CallableSettingWrapperTests)\", \"test_cleanse_setting_basic (view_tests.tests.test_debug.HelperFunctionTests)\", \"test_cleanse_setting_ignore_case (view_tests.tests.test_debug.HelperFunctionTests)\", \"test_cleanse_setting_recurses_in_dictionary (view_tests.tests.test_debug.HelperFunctionTests)\", \"test_handle_db_exception (view_tests.tests.test_debug.DebugViewQueriesAllowedTests)\", \"test_400 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"test_403 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"test_404 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"test_template_not_found_error (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)\", \"An exception report can be generated even for a disallowed host.\", \"test_message_only (view_tests.tests.test_debug.PlainTextReportTests)\", \"An exception report can be generated for just a request\", \"An exception report can be generated without request\", \"A simple exception report can be generated\", \"A message can be provided in addition to a request\", \"test_request_with_items_key (view_tests.tests.test_debug.PlainTextReportTests)\", \"test_template_exception (view_tests.tests.test_debug.PlainTextReportTests)\", \"test_ajax_response_encoding (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)\", \"test_custom_exception_reporter_filter (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)\", \"test_non_sensitive_request (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)\", \"test_paranoid_request (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)\", \"test_sensitive_request (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)\", \"test_400 (view_tests.tests.test_debug.DebugViewTests)\", \"test_403 (view_tests.tests.test_debug.DebugViewTests)\", \"test_403_template (view_tests.tests.test_debug.DebugViewTests)\", \"test_404 (view_tests.tests.test_debug.DebugViewTests)\", \"test_404_empty_path_not_in_urls (view_tests.tests.test_debug.DebugViewTests)\", \"test_404_not_in_urls (view_tests.tests.test_debug.DebugViewTests)\", \"test_classbased_technical_404 (view_tests.tests.test_debug.DebugViewTests)\", \"test_default_urlconf_template (view_tests.tests.test_debug.DebugViewTests)\", \"test_files (view_tests.tests.test_debug.DebugViewTests)\", \"test_no_template_source_loaders (view_tests.tests.test_debug.DebugViewTests)\", \"test_non_l10ned_numeric_ids (view_tests.tests.test_debug.DebugViewTests)\", \"test_regression_21530 (view_tests.tests.test_debug.DebugViewTests)\", \"test_technical_404 (view_tests.tests.test_debug.DebugViewTests)\", \"test_template_encoding (view_tests.tests.test_debug.DebugViewTests)\", \"test_template_exceptions (view_tests.tests.test_debug.DebugViewTests)\", \"Tests for not existing file\", \"test_encoding_error (view_tests.tests.test_debug.ExceptionReporterTests)\", \"The ExceptionReporter supports Unix, Windows and Macintosh EOL markers\", \"test_exception_fetching_user (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_ignore_traceback_evaluation_exceptions (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Safe strings in local variables are escaped.\", \"test_message_only (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Non-UTF-8 exceptions/values should not make the output generation choke.\", \"test_reporting_frames_for_cyclic_reference (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_reporting_frames_without_source (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_reporting_of_nested_exceptions (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_request_with_items_key (view_tests.tests.test_debug.ExceptionReporterTests)\", \"test_template_encoding (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Large values should not create a large HTML.\", \"test_unfrozen_importlib (view_tests.tests.test_debug.ExceptionReporterTests)\", \"Unprintable values should not make the output generation choke.\", \"test_callable_settings (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_callable_settings_forbidding_to_set_attributes (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_custom_exception_reporter_filter (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_dict_setting_with_non_str_key (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_multivalue_dict_key_error (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_non_sensitive_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_paranoid_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_function_arguments (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_function_keyword_arguments (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_method (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_sensitive_settings (view_tests.tests.test_debug.ExceptionReporterFilterTests)\", \"test_settings_with_sensitive_keys (view_tests.tests.test_debug.ExceptionReporterFilterTests)\"]", "environment_setup_commit": "419a78300f7cd27611196e1e464d50fd0385ff27", "test_directives": ["view_tests.tests.test_debug"], "test_cmd": "./tests/runtests.py --verbosity 2 view_tests.tests.test_debug", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/urlpatterns/tests.py b/tests/urlpatterns/tests.py\nindex 214739f678..26f7dcb686 100644\n--- a/tests/urlpatterns/tests.py\n+++ b/tests/urlpatterns/tests.py\n@@ -1,6 +1,7 @@\n import uuid\n \n from django.core.exceptions import ImproperlyConfigured\n+from django.http import Http404\n from django.test import SimpleTestCase\n from django.test.utils import override_settings\n from django.urls import Resolver404, path, resolve, reverse\n@@ -225,3 +226,22 @@ class ConversionExceptionTests(SimpleTestCase):\n raise ValueError('This value error propagates.')\n with self.assertRaisesMessage(ValueError, 'This value error propagates.'):\n reverse('dynamic', kwargs={'value': object()})\n+\n+ @override_settings(DEBUG=True)\n+ def test_resolve_http404_in_converter(self):\n+ @DynamicConverter.register_to_python\n+ def raises_http404(value):\n+ raise Http404('This is a custom 404 message.')\n+ with self.assertRaisesMessage(Http404, 'This is a custom 404 message.'):\n+ resolve('/dynamic/abc/')\n+\n+ @override_settings(DEBUG=True)\n+ def test_resolve_http404_in_converter_with_technical_response(self):\n+ @DynamicConverter.register_to_python\n+ def raises_http404(value):\n+ raise Http404('This is a custom 404 message.')\n+ with self.assertRaisesMessage(Http404, 'This is a custom 404 message.'):\n+ response = self.client.get('/dynamic/abc/')\n+ self.assertEqual(response.status_code, 404)\n+ self.assertIn('This is a custom 404 message.', response.content.decode())\n+ self.assertIn('Technical details', response.content.decode())\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["urlpatterns.tests"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/urls/converters.py b/django/urls/converters.py\nindex bb8478e32f..e6b3d2f74d 100644\n--- a/django/urls/converters.py\n+++ b/django/urls/converters.py\n@@ -36,9 +36,21 @@ class SlugConverter(StringConverter):\n regex = '[-a-zA-Z0-9_]+'\n \n \n+from django.http import Http404\n+from django.conf import settings\n+\n class PathConverter(StringConverter):\n regex = '.+'\n \n+ def to_python(self, value):\n+ try:\n+ return super().to_python(value)\n+ except Http404 as e:\n+ if settings.DEBUG:\n+ raise Http404(f\"PathConverter error: {e}\")\n+ else:\n+ raise\n+\n \n DEFAULT_CONVERTERS = {\n 'int': IntConverter(),\n", "model_lint_repair_patch": "diff --git a/django/urls/converters.py b/django/urls/converters.py\nindex bb8478e32f..e6b3d2f74d 100644\n--- a/django/urls/converters.py\n+++ b/django/urls/converters.py\n@@ -36,9 +36,21 @@ class SlugConverter(StringConverter):\n regex = '[-a-zA-Z0-9_]+'\n \n \n+from django.http import Http404\n+from django.conf import settings\n+\n class PathConverter(StringConverter):\n regex = '.+'\n \n+ def to_python(self, value):\n+ try:\n+ return super().to_python(value)\n+ except Http404 as e:\n+ if settings.DEBUG:\n+ raise Http404(f\"PathConverter error: {e}\")\n+ else:\n+ raise\n+\n \n DEFAULT_CONVERTERS = {\n 'int': IntConverter(),\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["urlpatterns.tests"]} +{"repo": "django/django", "instance_id": "django__django-11815", "base_commit": "e02f67ef2d03d48128e7a118bf75f0418e24e8ac", "patch": "diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py\n--- a/django/db/migrations/serializer.py\n+++ b/django/db/migrations/serializer.py\n@@ -120,9 +120,10 @@ class EnumSerializer(BaseSerializer):\n def serialize(self):\n enum_class = self.value.__class__\n module = enum_class.__module__\n- v_string, v_imports = serializer_factory(self.value.value).serialize()\n- imports = {'import %s' % module, *v_imports}\n- return \"%s.%s(%s)\" % (module, enum_class.__name__, v_string), imports\n+ return (\n+ '%s.%s[%r]' % (module, enum_class.__name__, self.value.name),\n+ {'import %s' % module},\n+ )\n \n \n class FloatSerializer(BaseSimpleSerializer):\n", "test_patch": "diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py\n--- a/tests/migrations/test_writer.py\n+++ b/tests/migrations/test_writer.py\n@@ -257,6 +257,10 @@ class TextEnum(enum.Enum):\n A = 'a-value'\n B = 'value-b'\n \n+ class TextTranslatedEnum(enum.Enum):\n+ A = _('a-value')\n+ B = _('value-b')\n+\n class BinaryEnum(enum.Enum):\n A = b'a-value'\n B = b'value-b'\n@@ -267,15 +271,19 @@ class IntEnum(enum.IntEnum):\n \n self.assertSerializedResultEqual(\n TextEnum.A,\n- (\"migrations.test_writer.TextEnum('a-value')\", {'import migrations.test_writer'})\n+ (\"migrations.test_writer.TextEnum['A']\", {'import migrations.test_writer'})\n+ )\n+ self.assertSerializedResultEqual(\n+ TextTranslatedEnum.A,\n+ (\"migrations.test_writer.TextTranslatedEnum['A']\", {'import migrations.test_writer'})\n )\n self.assertSerializedResultEqual(\n BinaryEnum.A,\n- (\"migrations.test_writer.BinaryEnum(b'a-value')\", {'import migrations.test_writer'})\n+ (\"migrations.test_writer.BinaryEnum['A']\", {'import migrations.test_writer'})\n )\n self.assertSerializedResultEqual(\n IntEnum.B,\n- (\"migrations.test_writer.IntEnum(2)\", {'import migrations.test_writer'})\n+ (\"migrations.test_writer.IntEnum['B']\", {'import migrations.test_writer'})\n )\n \n field = models.CharField(default=TextEnum.B, choices=[(m.value, m) for m in TextEnum])\n@@ -283,27 +291,39 @@ class IntEnum(enum.IntEnum):\n self.assertEqual(\n string,\n \"models.CharField(choices=[\"\n- \"('a-value', migrations.test_writer.TextEnum('a-value')), \"\n- \"('value-b', migrations.test_writer.TextEnum('value-b'))], \"\n- \"default=migrations.test_writer.TextEnum('value-b'))\"\n+ \"('a-value', migrations.test_writer.TextEnum['A']), \"\n+ \"('value-b', migrations.test_writer.TextEnum['B'])], \"\n+ \"default=migrations.test_writer.TextEnum['B'])\"\n+ )\n+ field = models.CharField(\n+ default=TextTranslatedEnum.A,\n+ choices=[(m.value, m) for m in TextTranslatedEnum],\n+ )\n+ string = MigrationWriter.serialize(field)[0]\n+ self.assertEqual(\n+ string,\n+ \"models.CharField(choices=[\"\n+ \"('a-value', migrations.test_writer.TextTranslatedEnum['A']), \"\n+ \"('value-b', migrations.test_writer.TextTranslatedEnum['B'])], \"\n+ \"default=migrations.test_writer.TextTranslatedEnum['A'])\"\n )\n field = models.CharField(default=BinaryEnum.B, choices=[(m.value, m) for m in BinaryEnum])\n string = MigrationWriter.serialize(field)[0]\n self.assertEqual(\n string,\n \"models.CharField(choices=[\"\n- \"(b'a-value', migrations.test_writer.BinaryEnum(b'a-value')), \"\n- \"(b'value-b', migrations.test_writer.BinaryEnum(b'value-b'))], \"\n- \"default=migrations.test_writer.BinaryEnum(b'value-b'))\"\n+ \"(b'a-value', migrations.test_writer.BinaryEnum['A']), \"\n+ \"(b'value-b', migrations.test_writer.BinaryEnum['B'])], \"\n+ \"default=migrations.test_writer.BinaryEnum['B'])\"\n )\n field = models.IntegerField(default=IntEnum.A, choices=[(m.value, m) for m in IntEnum])\n string = MigrationWriter.serialize(field)[0]\n self.assertEqual(\n string,\n \"models.IntegerField(choices=[\"\n- \"(1, migrations.test_writer.IntEnum(1)), \"\n- \"(2, migrations.test_writer.IntEnum(2))], \"\n- \"default=migrations.test_writer.IntEnum(1))\"\n+ \"(1, migrations.test_writer.IntEnum['A']), \"\n+ \"(2, migrations.test_writer.IntEnum['B'])], \"\n+ \"default=migrations.test_writer.IntEnum['A'])\"\n )\n \n def test_serialize_choices(self):\n@@ -454,7 +474,7 @@ def test_serialize_class_based_validators(self):\n # Test a string regex with flag\n validator = RegexValidator(r'^[0-9]+$', flags=re.S)\n string = MigrationWriter.serialize(validator)[0]\n- self.assertEqual(string, \"django.core.validators.RegexValidator('^[0-9]+$', flags=re.RegexFlag(16))\")\n+ self.assertEqual(string, \"django.core.validators.RegexValidator('^[0-9]+$', flags=re.RegexFlag['DOTALL'])\")\n self.serialize_round_trip(validator)\n \n # Test message and code\n", "problem_statement": "Migrations uses value of enum object instead of its name.\nDescription\n\t \n\t\t(last modified by oasl)\n\t \nWhen using Enum object as a default value for a CharField, the generated migration file uses the value of the Enum object instead of the its name. This causes a problem when using Django translation on the value of the Enum object. \nThe problem is that, when the Enum object value get translated to the users language, the old migration files raise an error stating that the Enum does not have the corresponding value. (because the Enum value is translated to another language)\nExample:\nLet say we have this code in models.py:\nfrom enum import Enum\nfrom django.utils.translation import gettext_lazy as _\nfrom django.db import models\nclass Status(Enum):\n\tGOOD = _('Good') # 'Good' will be translated\n\tBAD = _('Bad') # 'Bad' will be translated\n\tdef __str__(self):\n\t\treturn self.name\nclass Item(models.Model):\n\tstatus = models.CharField(default=Status.GOOD, max_length=128)\nIn the generated migration file, the code will be:\n...\n('status', models.CharField(default=Status('Good'), max_length=128))\n...\nAfter the translation, 'Good' will be translated to another word and it will not be part of the Status Enum class any more, so the migration file will raise the error on the previous line:\nValueError: 'Good' is not a valid Status\nShouldn't the code generated by the migration uses the name of the Status Enum 'GOOD', not the value of it, since it is changeable?\nIt should be:\n('status', models.CharField(default=Status['GOOD'], max_length=128))\nThis will be correct regardless of the translated word\n", "hints_text": "Thanks for this report, however I'm not sure how translated values can brake migrations. Can you provide a sample project to reproduce this issue? Migrations with translatable strings works fine for me: >>> class TextEnum(enum.Enum): ... C = _('translatable value') ... >>> TextEnum(_('translatable value')) >>> TextEnum('translatable value') \nTo experience the bug: In any Django project, set the default value of a CharField as an enum object: class EnumClass(Enum): VALUE = _('Value') where: VALUE: is the constant enum object name 'Value': is the translatable enum object value In the model: field = models.CharField(default=EnumClass.VALUE, max_length=128) then run: python manage.py makemigrations In the generated migration file, you will notice that the default value of the field is set to: EnumClass('Value'), so it calls the enum object by its translatable value not it is constant name. (This is exactly the BUG, you can think of it without even continue) run: python manage.py migrate In the settings.py file: LANGUAGE_CODE = 'fr-FR' # set it to any language code other than English Run the project after generating, translating, and compiling the messages file (see: \u200bmessage-files) The project will raise the error: ValueError: 'Value' is not a valid EnumClass , on the generated migration file.\nThis use case looks quite niche for me, i.e. I would expect to store a unified values (the same for all languages) and translate only labels visible for users, however I agree that we can fix this.\nHere is the diff based on the @oasl solution Shouldn't the code generated by the migration uses the name of the Status Enum 'GOOD', not the value of it, since it is changeable? It should be: ('status', models.CharField(default=Status['GOOD'], max_length=128)) diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index 27b5cbd379..b00c6f0df2 100644 --- a/django/db/migrations/serializer.py +++ b/django/db/migrations/serializer.py @@ -120,9 +120,9 @@ class EnumSerializer(BaseSerializer): def serialize(self): enum_class = self.value.__class__ module = enum_class.__module__ - v_string, v_imports = serializer_factory(self.value.value).serialize() + _, v_imports = serializer_factory(self.value.value).serialize() imports = {'import %s' % module, *v_imports} - return \"%s.%s(%s)\" % (module, enum_class.__name__, v_string), imports + return \"%s.%s['%s']\" % (module, enum_class.__name__, self.value), imports @felixxm, what do you think?\nYou cannot use a string representation of self.value i.e. 'EnumClass.GOOD', IMO we should use a name property: return \"%s.%s[%r]\" % (module, enum_class.__name__, self.value.name), imports", "created_at": "2019-09-24T21:45:36Z", "version": "3.1", "FAIL_TO_PASS": "[\"test_serialize_class_based_validators (migrations.test_writer.WriterTests)\", \"test_serialize_enums (migrations.test_writer.WriterTests)\"]", "PASS_TO_PASS": "[\"test_args_kwargs_signature (migrations.test_writer.OperationWriterTests)\", \"test_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_empty_signature (migrations.test_writer.OperationWriterTests)\", \"test_expand_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_kwargs_signature (migrations.test_writer.OperationWriterTests)\", \"test_multiline_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_nested_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_nested_operation_expand_args_signature (migrations.test_writer.OperationWriterTests)\", \"test_custom_operation (migrations.test_writer.WriterTests)\", \"test_deconstruct_class_arguments (migrations.test_writer.WriterTests)\", \"test_migration_file_header_comments (migrations.test_writer.WriterTests)\", \"test_migration_path (migrations.test_writer.WriterTests)\", \"test_models_import_omitted (migrations.test_writer.WriterTests)\", \"test_register_non_serializer (migrations.test_writer.WriterTests)\", \"test_register_serializer (migrations.test_writer.WriterTests)\", \"test_serialize_builtin_types (migrations.test_writer.WriterTests)\", \"test_serialize_builtins (migrations.test_writer.WriterTests)\", \"test_serialize_choices (migrations.test_writer.WriterTests)\", \"test_serialize_collections (migrations.test_writer.WriterTests)\", \"test_serialize_compiled_regex (migrations.test_writer.WriterTests)\", \"test_serialize_constants (migrations.test_writer.WriterTests)\", \"test_serialize_datetime (migrations.test_writer.WriterTests)\", \"test_serialize_empty_nonempty_tuple (migrations.test_writer.WriterTests)\", \"test_serialize_fields (migrations.test_writer.WriterTests)\", \"test_serialize_frozensets (migrations.test_writer.WriterTests)\", \"test_serialize_functions (migrations.test_writer.WriterTests)\", \"test_serialize_functools_partial (migrations.test_writer.WriterTests)\", \"test_serialize_functools_partialmethod (migrations.test_writer.WriterTests)\", \"test_serialize_iterators (migrations.test_writer.WriterTests)\", \"test_serialize_lazy_objects (migrations.test_writer.WriterTests)\", \"A reference in a local scope can't be serialized.\", \"test_serialize_managers (migrations.test_writer.WriterTests)\", \"test_serialize_multiline_strings (migrations.test_writer.WriterTests)\", \"test_serialize_numbers (migrations.test_writer.WriterTests)\", \"test_serialize_range (migrations.test_writer.WriterTests)\", \"test_serialize_set (migrations.test_writer.WriterTests)\", \"test_serialize_settings (migrations.test_writer.WriterTests)\", \"test_serialize_strings (migrations.test_writer.WriterTests)\", \"test_serialize_timedelta (migrations.test_writer.WriterTests)\", \"test_serialize_type_none (migrations.test_writer.WriterTests)\", \"An unbound method used within a class body can be serialized.\", \"test_serialize_uuid (migrations.test_writer.WriterTests)\", \"test_simple_migration (migrations.test_writer.WriterTests)\", \"test_sorted_imports (migrations.test_writer.WriterTests)\"]", "environment_setup_commit": "0668164b4ac93a5be79f5b87fae83c657124d9ab", "test_directives": ["migrations.test_writer"], "test_cmd": "./tests/runtests.py --verbosity 2 migrations.test_writer", "model_name_or_path": "navie", "model_iteration": 2, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "diff --git a/tests/postgres_tests/test_array.py b/tests/postgres_tests/test_array.py\nindex 42885e61f6..a9bb8f7999 100644\n--- a/tests/postgres_tests/test_array.py\n+++ b/tests/postgres_tests/test_array.py\n@@ -587,6 +587,31 @@ class TestChecks(PostgreSQLSimpleTestCase):\n @unittest.skipUnless(connection.vendor == 'postgresql', \"PostgreSQL specific tests\")\n class TestMigrations(TransactionTestCase):\n \n+ def test_enum_default_value_in_migration(self):\n+ from enum import Enum\n+ from django.utils.translation import gettext_lazy as _\n+ from django.db import models\n+ from django.db.migrations.writer import MigrationWriter\n+ from django.db.migrations.operations import AddField\n+ from django.db.migrations.state import ModelState\n+\n+ class Status(Enum):\n+ GOOD = _('Good')\n+ BAD = _('Bad')\n+\n+ class Item(models.Model):\n+ status = models.CharField(default=Status.GOOD, max_length=128)\n+\n+ operation = AddField(\n+ model_name='item',\n+ name='status',\n+ field=models.CharField(default=Status.GOOD, max_length=128),\n+ )\n+ project_state = ModelState.from_model(Item)\n+ migration = MigrationWriter(operation.migration_class('test', '0001_initial', project_state))\n+ migration_string = migration.as_string()\n+ self.assertIn(\"default=Status['GOOD']\", migration_string)\n+\n available_apps = ['postgres_tests']\n \n def test_deconstruct(self):\n", "model_prepare_test_num_attempts": 3, "model_test_directives": ["postgres_tests.fields"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py\nindex 27b5cbd379..1147e74b76 100644\n--- a/django/db/migrations/serializer.py\n+++ b/django/db/migrations/serializer.py\n@@ -48,7 +48,7 @@ class BaseSimpleSerializer(BaseSerializer):\n \n class ChoicesSerializer(BaseSerializer):\n def serialize(self):\n- return serializer_factory(self.value.value).serialize()\n+ return serializer_factory(self.value.name).serialize()\n \n \n class DateTimeSerializer(BaseSerializer):\n@@ -120,9 +120,9 @@ class EnumSerializer(BaseSerializer):\n def serialize(self):\n enum_class = self.value.__class__\n module = enum_class.__module__\n- v_string, v_imports = serializer_factory(self.value.value).serialize()\n- imports = {'import %s' % module, *v_imports}\n- return \"%s.%s(%s)\" % (module, enum_class.__name__, v_string), imports\n+ name_string, name_imports = serializer_factory(self.value.name).serialize()\n+ imports = {'import %s' % module, *name_imports}\n+ return \"%s.%s[%s]\" % (module, enum_class.__name__, name_string), imports\n \n \n class FloatSerializer(BaseSimpleSerializer):\n@@ -286,6 +286,8 @@ class Serializer:\n dict: DictionarySerializer,\n models.Choices: ChoicesSerializer,\n enum.Enum: EnumSerializer,\n+ models.IntegerChoices: ChoicesSerializer,\n+ models.TextChoices: ChoicesSerializer,\n datetime.datetime: DatetimeDatetimeSerializer,\n (datetime.date, datetime.timedelta, datetime.time): DateTimeSerializer,\n SettingsReference: SettingsReferenceSerializer,\n", "model_lint_repair_patch": "diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py\nindex 27b5cbd379..1147e74b76 100644\n--- a/django/db/migrations/serializer.py\n+++ b/django/db/migrations/serializer.py\n@@ -48,7 +48,7 @@ class BaseSimpleSerializer(BaseSerializer):\n \n class ChoicesSerializer(BaseSerializer):\n def serialize(self):\n- return serializer_factory(self.value.value).serialize()\n+ return serializer_factory(self.value.name).serialize()\n \n \n class DateTimeSerializer(BaseSerializer):\n@@ -120,9 +120,9 @@ class EnumSerializer(BaseSerializer):\n def serialize(self):\n enum_class = self.value.__class__\n module = enum_class.__module__\n- v_string, v_imports = serializer_factory(self.value.value).serialize()\n- imports = {'import %s' % module, *v_imports}\n- return \"%s.%s(%s)\" % (module, enum_class.__name__, v_string), imports\n+ name_string, name_imports = serializer_factory(self.value.name).serialize()\n+ imports = {'import %s' % module, *name_imports}\n+ return \"%s.%s[%s]\" % (module, enum_class.__name__, name_string), imports\n \n \n class FloatSerializer(BaseSimpleSerializer):\n@@ -286,6 +286,8 @@ class Serializer:\n dict: DictionarySerializer,\n models.Choices: ChoicesSerializer,\n enum.Enum: EnumSerializer,\n+ models.IntegerChoices: ChoicesSerializer,\n+ models.TextChoices: ChoicesSerializer,\n datetime.datetime: DatetimeDatetimeSerializer,\n (datetime.date, datetime.timedelta, datetime.time): DateTimeSerializer,\n SettingsReference: SettingsReferenceSerializer,\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["postgres_tests.fields"]} +{"repo": "sympy/sympy", "instance_id": "sympy__sympy-13031", "base_commit": "2dfa7457f20ee187fbb09b5b6a1631da4458388c", "patch": "diff --git a/sympy/matrices/sparse.py b/sympy/matrices/sparse.py\n--- a/sympy/matrices/sparse.py\n+++ b/sympy/matrices/sparse.py\n@@ -985,8 +985,10 @@ def col_join(self, other):\n >>> C == A.row_insert(A.rows, Matrix(B))\n True\n \"\"\"\n- if not self:\n- return type(self)(other)\n+ # A null matrix can always be stacked (see #10770)\n+ if self.rows == 0 and self.cols != other.cols:\n+ return self._new(0, other.cols, []).col_join(other)\n+\n A, B = self, other\n if not A.cols == B.cols:\n raise ShapeError()\n@@ -1191,8 +1193,10 @@ def row_join(self, other):\n >>> C == A.col_insert(A.cols, B)\n True\n \"\"\"\n- if not self:\n- return type(self)(other)\n+ # A null matrix can always be stacked (see #10770)\n+ if self.cols == 0 and self.rows != other.rows:\n+ return self._new(other.rows, 0, []).row_join(other)\n+\n A, B = self, other\n if not A.rows == B.rows:\n raise ShapeError()\n", "test_patch": "diff --git a/sympy/matrices/tests/test_sparse.py b/sympy/matrices/tests/test_sparse.py\n--- a/sympy/matrices/tests/test_sparse.py\n+++ b/sympy/matrices/tests/test_sparse.py\n@@ -26,6 +26,12 @@ def sparse_zeros(n):\n assert type(a.row_join(b)) == type(a)\n assert type(a.col_join(b)) == type(a)\n \n+ # make sure 0 x n matrices get stacked correctly\n+ sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]\n+ assert SparseMatrix.hstack(*sparse_matrices) == Matrix(0, 6, [])\n+ sparse_matrices = [SparseMatrix.zeros(n, 0) for n in range(4)]\n+ assert SparseMatrix.vstack(*sparse_matrices) == Matrix(6, 0, [])\n+\n # test element assignment\n a = SparseMatrix((\n (1, 0),\n", "problem_statement": "Behavior of Matrix hstack and vstack changed in sympy 1.1\nIn sympy 1.0:\r\n```\r\nimport sympy as sy\r\nM1 = sy.Matrix.zeros(0, 0)\r\nM2 = sy.Matrix.zeros(0, 1)\r\nM3 = sy.Matrix.zeros(0, 2)\r\nM4 = sy.Matrix.zeros(0, 3)\r\nsy.Matrix.hstack(M1, M2, M3, M4).shape\r\n```\r\nreturns \r\n`(0, 6)`\r\n\r\nNow, same in sympy 1.1:\r\n```\r\nimport sympy as sy\r\nM1 = sy.Matrix.zeros(0, 0)\r\nM2 = sy.Matrix.zeros(0, 1)\r\nM3 = sy.Matrix.zeros(0, 2)\r\nM4 = sy.Matrix.zeros(0, 3)\r\nsy.Matrix.hstack(M1, M2, M3, M4).shape\r\n```\r\nreturns\r\n`(0, 3)\r\n`\r\nwhereas:\r\n```\r\nimport sympy as sy\r\nM1 = sy.Matrix.zeros(1, 0)\r\nM2 = sy.Matrix.zeros(1, 1)\r\nM3 = sy.Matrix.zeros(1, 2)\r\nM4 = sy.Matrix.zeros(1, 3)\r\nsy.Matrix.hstack(M1, M2, M3, M4).shape\r\n```\r\nreturns\r\n`(1, 6)\r\n`\n", "hints_text": "CC @siefkenj \nI update my comment in case someone already read it. We still have an issue with matrices shape in [pyphs](https://github.com/pyphs/pyphs/issues/49#issuecomment-316618994), but hstack and vstack seem ok in sympy 1.1.1rc1:\r\n\r\n```\r\n>>> import sympy as sy\r\n>>> sy.__version__\r\n'1.1.1rc1'\r\n>>> '1.1.1rc1'\r\n'1.1.1rc1'\r\n>>> matrices = [sy.Matrix.zeros(0, n) for n in range(4)]\r\n>>> sy.Matrix.hstack(*matrices).shape\r\n(0, 6)\r\n>>> matrices = [sy.Matrix.zeros(1, n) for n in range(4)]\r\n>>> sy.Matrix.hstack(*matrices).shape\r\n(1, 6)\r\n>>> matrices = [sy.Matrix.zeros(n, 0) for n in range(4)]\r\n>>> sy.Matrix.vstack(*matrices).shape\r\n(6, 0)\r\n>>> matrices = [sy.Matrix.zeros(1, n) for n in range(4)]\r\n>>> sy.Matrix.hstack(*matrices).shape\r\n(1, 6)\r\n>>> \r\n```\nThe problem is solved with Matrix but not SparseMatrix:\r\n```\r\n>>> import sympy as sy\r\n>>> sy.__version__\r\n'1.1.1rc1'\r\n>>> matrices = [Matrix.zeros(0, n) for n in range(4)]\r\n>>> Matrix.hstack(*matrices)\r\nMatrix(0, 6, [])\r\n>>> sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]\r\n>>> SparseMatrix.hstack(*sparse_matrices)\r\nMatrix(0, 3, [])\r\n>>> \r\n```\nBisected to 27e9ee425819fa09a4cbb8179fb38939cc693249. Should we revert that commit? CC @aravindkanna\nAny thoughts? This is the last fix to potentially go in the 1.1.1 release, but I want to cut a release candidate today or tomorrow, so speak now, or hold your peace (until the next major release).\nI am away at a conference. The change should be almost identical to the fix for dense matrices, if someone can manage to get a patch in. I *might* be able to do it tomorrow.\nOkay. I've looked this over and its convoluted...\r\n\r\n`SparseMatrix` should impliment `_eval_col_join`. `col_join` should not be implemented. It is, and that is what `hstack` is calling, which is why my previous patch didn't fix `SparseMatrix`s as well. However, the patch that @asmeurer referenced ensures that `SparseMatrix.row_join(DenseMatrix)` returns a `SparseMatrix` whereas `CommonMatrix.row_join(SparseMatrix, DenseMatrix)` returns a `classof(SparseMatrix, DenseMatrix)` which happens to be a `DenseMatrix`. I don't think that these should behave differently. This API needs to be better thought out.\nSo is there a simple fix that can be made for the release or should this be postponed?", "created_at": "2017-07-23T15:48:13Z", "version": "1.1", "FAIL_TO_PASS": "[\"test_sparse_matrix\"]", "PASS_TO_PASS": "[\"test_transpose\", \"test_trace\", \"test_CL_RL\", \"test_add\", \"test_errors\", \"test_len\", \"test_sparse_zeros_sparse_eye\", \"test_copyin\", \"test_sparse_solve\"]", "environment_setup_commit": "ec9e3c0436fbff934fa84e22bf07f1b3ef5bfac3", "test_directives": ["sympy/matrices/tests/test_sparse.py"], "test_cmd": "PYTHONWARNINGS=ignore bin/test -C --verbose sympy/matrices/tests/test_sparse.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sympy/matrices/tests/test_commonmatrix.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py\nindex 76390dc14c..329d04871a 100644\n--- a/sympy/matrices/expressions/blockmatrix.py\n+++ b/sympy/matrices/expressions/blockmatrix.py\n@@ -49,6 +49,10 @@ def __new__(cls, *args):\n args = map(sympify, args)\n mat = ImmutableDenseMatrix(*args)\n \n+ # Handle zero-sized matrices\n+ if mat.rows == 0 or mat.cols == 0:\n+ mat = ImmutableDenseMatrix.zeros(mat.rows, mat.cols)\n+\n obj = Basic.__new__(cls, mat)\n return obj\n \n@@ -88,6 +92,8 @@ def structurally_equal(self, other):\n def _blockmul(self, other):\n if (isinstance(other, BlockMatrix) and\n self.colblocksizes == other.rowblocksizes):\n+ if self.blocks.rows == 0 or self.blocks.cols == 0 or other.blocks.rows == 0 or other.blocks.cols == 0:\n+ return BlockMatrix.zeros(self.blocks.rows, other.blocks.cols)\n return BlockMatrix(self.blocks*other.blocks)\n \n return self * other\n@@ -95,6 +101,8 @@ def _blockmul(self, other):\n def _blockadd(self, other):\n if (isinstance(other, BlockMatrix)\n and self.structurally_equal(other)):\n+ if self.blocks.rows == 0 or self.blocks.cols == 0 or other.blocks.rows == 0 or other.blocks.cols == 0:\n+ return BlockMatrix.zeros(self.blocks.rows, self.blocks.cols)\n return BlockMatrix(self.blocks + other.blocks)\n \n return self + other\n@@ -397,6 +405,8 @@ def deblock(B):\n \n from sympy import Matrix\n try:\n+ if bb.rows == 0 or bb.cols == 0:\n+ return BlockMatrix.zeros(bb.rows, bb.cols)\n MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])\n for row in range(0, bb.shape[0]):\n M = Matrix(bb[row, 0].blocks)\n@@ -448,6 +458,8 @@ def blockcut(expr, rowsizes, colsizes):\n \n rowbounds = bounds(rowsizes)\n colbounds = bounds(colsizes)\n+ if expr.rows == 0 or expr.cols == 0:\n+ return BlockMatrix.zeros(len(rowbounds), len(colbounds))\n return BlockMatrix([[MatrixSlice(expr, rowbound, colbound)\n for colbound in colbounds]\n for rowbound in rowbounds])\n\ndiff --git a/sympy/printing/theanocode.py b/sympy/printing/theanocode.py\nindex 9bd1525e90..b96544b9b3 100644\n--- a/sympy/printing/theanocode.py\n+++ b/sympy/printing/theanocode.py\n@@ -139,6 +139,8 @@ def _print_MatrixSlice(self, expr, **kwargs):\n \n def _print_BlockMatrix(self, expr, **kwargs):\n nrows, ncols = expr.blocks.shape\n+ if nrows == 0 or ncols == 0:\n+ return tt.zeros((nrows, ncols))\n blocks = [[self._print(expr.blocks[r, c], **kwargs)\n for c in range(ncols)]\n for r in range(nrows)]\n", "model_lint_repair_patch": "diff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py\nindex 76390dc14c..329d04871a 100644\n--- a/sympy/matrices/expressions/blockmatrix.py\n+++ b/sympy/matrices/expressions/blockmatrix.py\n@@ -49,6 +49,10 @@ def __new__(cls, *args):\n args = map(sympify, args)\n mat = ImmutableDenseMatrix(*args)\n \n+ # Handle zero-sized matrices\n+ if mat.rows == 0 or mat.cols == 0:\n+ mat = ImmutableDenseMatrix.zeros(mat.rows, mat.cols)\n+\n obj = Basic.__new__(cls, mat)\n return obj\n \n@@ -88,6 +92,8 @@ def structurally_equal(self, other):\n def _blockmul(self, other):\n if (isinstance(other, BlockMatrix) and\n self.colblocksizes == other.rowblocksizes):\n+ if self.blocks.rows == 0 or self.blocks.cols == 0 or other.blocks.rows == 0 or other.blocks.cols == 0:\n+ return BlockMatrix.zeros(self.blocks.rows, other.blocks.cols)\n return BlockMatrix(self.blocks*other.blocks)\n \n return self * other\n@@ -95,6 +101,8 @@ def _blockmul(self, other):\n def _blockadd(self, other):\n if (isinstance(other, BlockMatrix)\n and self.structurally_equal(other)):\n+ if self.blocks.rows == 0 or self.blocks.cols == 0 or other.blocks.rows == 0 or other.blocks.cols == 0:\n+ return BlockMatrix.zeros(self.blocks.rows, self.blocks.cols)\n return BlockMatrix(self.blocks + other.blocks)\n \n return self + other\n@@ -397,6 +405,8 @@ def deblock(B):\n \n from sympy import Matrix\n try:\n+ if bb.rows == 0 or bb.cols == 0:\n+ return BlockMatrix.zeros(bb.rows, bb.cols)\n MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])\n for row in range(0, bb.shape[0]):\n M = Matrix(bb[row, 0].blocks)\n@@ -448,6 +458,8 @@ def blockcut(expr, rowsizes, colsizes):\n \n rowbounds = bounds(rowsizes)\n colbounds = bounds(colsizes)\n+ if expr.rows == 0 or expr.cols == 0:\n+ return BlockMatrix.zeros(len(rowbounds), len(colbounds))\n return BlockMatrix([[MatrixSlice(expr, rowbound, colbound)\n for colbound in colbounds]\n for rowbound in rowbounds])\n\ndiff --git a/sympy/printing/theanocode.py b/sympy/printing/theanocode.py\nindex 9bd1525e90..b96544b9b3 100644\n--- a/sympy/printing/theanocode.py\n+++ b/sympy/printing/theanocode.py\n@@ -139,6 +139,8 @@ def _print_MatrixSlice(self, expr, **kwargs):\n \n def _print_BlockMatrix(self, expr, **kwargs):\n nrows, ncols = expr.blocks.shape\n+ if nrows == 0 or ncols == 0:\n+ return tt.zeros((nrows, ncols))\n blocks = [[self._print(expr.blocks[r, c], **kwargs)\n for c in range(ncols)]\n for r in range(nrows)]\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "sphinx-doc/sphinx", "instance_id": "sphinx-doc__sphinx-8713", "base_commit": "3ed7590ed411bd93b26098faab4f23619cdb2267", "patch": "diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py\n--- a/sphinx/ext/napoleon/docstring.py\n+++ b/sphinx/ext/napoleon/docstring.py\n@@ -682,7 +682,13 @@ def _parse_notes_section(self, section: str) -> List[str]:\n return self._parse_generic_section(_('Notes'), use_admonition)\n \n def _parse_other_parameters_section(self, section: str) -> List[str]:\n- return self._format_fields(_('Other Parameters'), self._consume_fields())\n+ if self._config.napoleon_use_param:\n+ # Allow to declare multiple parameters at once (ex: x, y: int)\n+ fields = self._consume_fields(multiple=True)\n+ return self._format_docutils_params(fields)\n+ else:\n+ fields = self._consume_fields()\n+ return self._format_fields(_('Other Parameters'), fields)\n \n def _parse_parameters_section(self, section: str) -> List[str]:\n if self._config.napoleon_use_param:\n", "test_patch": "diff --git a/tests/test_ext_napoleon_docstring.py b/tests/test_ext_napoleon_docstring.py\n--- a/tests/test_ext_napoleon_docstring.py\n+++ b/tests/test_ext_napoleon_docstring.py\n@@ -1441,12 +1441,18 @@ def test_parameters_with_class_reference(self):\n ----------\n param1 : :class:`MyClass ` instance\n \n+Other Parameters\n+----------------\n+param2 : :class:`MyClass ` instance\n+\n \"\"\"\n \n config = Config(napoleon_use_param=False)\n actual = str(NumpyDocstring(docstring, config))\n expected = \"\"\"\\\n :Parameters: **param1** (:class:`MyClass ` instance)\n+\n+:Other Parameters: **param2** (:class:`MyClass ` instance)\n \"\"\"\n self.assertEqual(expected, actual)\n \n@@ -1455,6 +1461,9 @@ def test_parameters_with_class_reference(self):\n expected = \"\"\"\\\n :param param1:\n :type param1: :class:`MyClass ` instance\n+\n+:param param2:\n+:type param2: :class:`MyClass ` instance\n \"\"\"\n self.assertEqual(expected, actual)\n \n", "problem_statement": "napoleon_use_param should also affect \"other parameters\" section\nSubject: napoleon_use_param should also affect \"other parameters\" section\r\n\r\n### Problem\r\nCurrently, napoleon always renders the Other parameters section as if napoleon_use_param was False, see source\r\n```\r\n def _parse_other_parameters_section(self, section):\r\n # type: (unicode) -> List[unicode]\r\n return self._format_fields(_('Other Parameters'), self._consume_fields())\r\n\r\n def _parse_parameters_section(self, section):\r\n # type: (unicode) -> List[unicode]\r\n fields = self._consume_fields()\r\n if self._config.napoleon_use_param:\r\n return self._format_docutils_params(fields)\r\n else:\r\n return self._format_fields(_('Parameters'), fields)\r\n```\r\nwhereas it would make sense that this section should follow the same formatting rules as the Parameters section.\r\n\r\n#### Procedure to reproduce the problem\r\n```\r\nIn [5]: print(str(sphinx.ext.napoleon.NumpyDocstring(\"\"\"\\ \r\n ...: Parameters \r\n ...: ---------- \r\n ...: x : int \r\n ...: \r\n ...: Other parameters \r\n ...: ---------------- \r\n ...: y: float \r\n ...: \"\"\"))) \r\n:param x:\r\n:type x: int\r\n\r\n:Other Parameters: **y** (*float*)\r\n```\r\n\r\nNote the difference in rendering.\r\n\r\n#### Error logs / results\r\nSee above.\r\n\r\n#### Expected results\r\n```\r\n:param x:\r\n:type x: int\r\n\r\n:Other Parameters: // Or some other kind of heading.\r\n:param: y\r\n:type y: float\r\n```\r\n\r\nAlternatively another separate config value could be introduced, but that seems a bit overkill.\r\n\r\n### Reproducible project / your project\r\nN/A\r\n\r\n### Environment info\r\n- OS: Linux\r\n- Python version: 3.7\r\n- Sphinx version: 1.8.1\r\n\n", "hints_text": "", "created_at": "2021-01-20T14:24:12Z", "version": "4.0", "FAIL_TO_PASS": "[\"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_parameters_with_class_reference\"]", "PASS_TO_PASS": "[\"tests/test_ext_napoleon_docstring.py::NamedtupleSubclassTest::test_attributes_docstring\", \"tests/test_ext_napoleon_docstring.py::InlineAttributeTest::test_class_data_member\", \"tests/test_ext_napoleon_docstring.py::InlineAttributeTest::test_class_data_member_inline\", \"tests/test_ext_napoleon_docstring.py::InlineAttributeTest::test_class_data_member_inline_no_type\", \"tests/test_ext_napoleon_docstring.py::InlineAttributeTest::test_class_data_member_inline_ref_in_type\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_attributes_with_class_reference\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_code_block_in_returns_section\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_colon_in_return_type\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_custom_generic_sections\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_docstrings\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_keywords_with_types\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_kwargs_in_arguments\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_list_in_parameter_description\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_noindex\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_parameters_with_class_reference\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_pep526_annotations\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_raises_types\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_section_header_formatting\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_sphinx_admonitions\", \"tests/test_ext_napoleon_docstring.py::GoogleDocstringTest::test_xrefs_in_return_type\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_colon_in_return_type\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_convert_numpy_type_spec\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_docstrings\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_list_in_parameter_description\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_multiple_parameters\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_parameter_types\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_parameters_without_class_reference\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_raises_types\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_recombine_set_tokens\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_recombine_set_tokens_invalid\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_return_types\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_section_header_underline_length\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_see_also_refs\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_sphinx_admonitions\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_token_type\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_tokenize_type_spec\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_type_preprocessor\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_underscore_in_attribute\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_underscore_in_attribute_strip_signature_backslash\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_xrefs_in_return_type\", \"tests/test_ext_napoleon_docstring.py::NumpyDocstringTest::test_yield_types\", \"tests/test_ext_napoleon_docstring.py::TestNumpyDocstring::test_escape_args_and_kwargs[x,\", \"tests/test_ext_napoleon_docstring.py::TestNumpyDocstring::test_escape_args_and_kwargs[*args,\", \"tests/test_ext_napoleon_docstring.py::TestNumpyDocstring::test_escape_args_and_kwargs[*x,\", \"tests/test_ext_napoleon_docstring.py::TestNumpyDocstring::test_pep526_annotations\"]", "environment_setup_commit": "8939a75efaa911a12dbe6edccedf261e88bf7eef", "test_directives": ["tests/test_ext_napoleon_docstring.py"], "test_cmd": "tox -epy39 -v -- tests/test_ext_napoleon_docstring.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 1, "model_test_directives": ["tests/ext_napoleon_pep526_data_google.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py\nindex 755088ca5..ba0bccd64 100644\n--- a/sphinx/ext/napoleon/docstring.py\n+++ b/sphinx/ext/napoleon/docstring.py\n@@ -682,7 +682,14 @@ class GoogleDocstring:\n return self._parse_generic_section(_('Notes'), use_admonition)\n \n def _parse_other_parameters_section(self, section: str) -> List[str]:\n- return self._format_fields(_('Other Parameters'), self._consume_fields())\n+ # Check napoleon_use_param setting\n+ if self._config.napoleon_use_param:\n+ # Allow to declare multiple parameters at once (ex: x, y: int)\n+ fields = self._consume_fields(multiple=True)\n+ return self._format_docutils_params(fields)\n+ else:\n+ fields = self._consume_fields()\n+ return self._format_fields(_('Other Parameters'), fields)\n \n def _parse_parameters_section(self, section: str) -> List[str]:\n if self._config.napoleon_use_param:\n", "model_lint_repair_patch": "diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py\nindex 755088ca5..28caac561 100644\n--- a/sphinx/ext/napoleon/docstring.py\n+++ b/sphinx/ext/napoleon/docstring.py\n@@ -682,7 +682,14 @@ class GoogleDocstring:\n return self._parse_generic_section(_('Notes'), use_admonition)\n \n def _parse_other_parameters_section(self, section: str) -> List[str]:\n- return self._format_fields(_('Other Parameters'), self._consume_fields())\n+ # Check napoleon_use_param setting\n+ if self._config.napoleon_use_param:\n+ # Allow to declare multiple parameters at once (ex: x, y: int)\n+ fields = self._consume_fields(multiple=True)\n+ return self._format_docutils_params(fields)\n+ else:\n+ fields = self._consume_fields()\n+ return self._format_fields(_('Other Parameters'), fields)\n \n def _parse_parameters_section(self, section: str) -> List[str]:\n if self._config.napoleon_use_param:\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-23913", "base_commit": "5c4595267ccd3daf78f5fd05693b7ecbcd575c1e", "patch": "diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py\n--- a/lib/matplotlib/legend.py\n+++ b/lib/matplotlib/legend.py\n@@ -286,6 +286,9 @@ def _update_bbox_to_anchor(self, loc_in_canvas):\n The custom dictionary mapping instances or types to a legend\n handler. This *handler_map* updates the default handler map\n found at `matplotlib.legend.Legend.get_legend_handler_map`.\n+\n+draggable : bool, default: False\n+ Whether the legend can be dragged with the mouse.\n \"\"\")\n \n \n@@ -342,7 +345,8 @@ def __init__(\n title_fontproperties=None, # properties for the legend title\n alignment=\"center\", # control the alignment within the legend box\n *,\n- ncol=1 # synonym for ncols (backward compatibility)\n+ ncol=1, # synonym for ncols (backward compatibility)\n+ draggable=False # whether the legend can be dragged with the mouse\n ):\n \"\"\"\n Parameters\n@@ -537,7 +541,9 @@ def val_or_rc(val, rc_name):\n title_prop_fp.set_size(title_fontsize)\n \n self.set_title(title, prop=title_prop_fp)\n+\n self._draggable = None\n+ self.set_draggable(state=draggable)\n \n # set the text color\n \n", "test_patch": "diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py\n--- a/lib/matplotlib/tests/test_legend.py\n+++ b/lib/matplotlib/tests/test_legend.py\n@@ -783,6 +783,14 @@ def test_get_set_draggable():\n assert not legend.get_draggable()\n \n \n+@pytest.mark.parametrize('draggable', (True, False))\n+def test_legend_draggable(draggable):\n+ fig, ax = plt.subplots()\n+ ax.plot(range(10), label='shabnams')\n+ leg = ax.legend(draggable=draggable)\n+ assert leg.get_draggable() is draggable\n+\n+\n def test_alpha_handles():\n x, n, hh = plt.hist([1, 2, 3], alpha=0.25, label='data', color='red')\n legend = plt.legend()\n", "problem_statement": "legend draggable as keyword\n\r\n\r\n\r\n### Feature request\r\n\r\n**There is not keyword to make legend draggable at creation**\r\n\r\n\r\n\r\nIs there a code reason why one can not add a \"draggable=True\" keyword to the __init__ function for Legend? This would be more handy than having to call it after legend creation. And, naively, it would seem simple to do. But maybe there is a reason why it would not work?\n", "hints_text": "This seems like a reasonable request, you're welcome to submit a PR :-) Note that the same comment applies to annotations.\r\nI would also deprecate `draggable()` in favor of the more classic `set_draggable()`, `get_draggable()` (and thus, in the long-term future, `.draggable` could become a property).", "created_at": "2022-09-16T21:51:24Z", "version": "3.6", "FAIL_TO_PASS": "[\"lib/matplotlib/tests/test_legend.py::test_legend_draggable[True]\", \"lib/matplotlib/tests/test_legend.py::test_legend_draggable[False]\"]", "PASS_TO_PASS": "[\"lib/matplotlib/tests/test_legend.py::test_legend_ordereddict\", \"lib/matplotlib/tests/test_legend.py::test_legend_auto1[png]\", \"lib/matplotlib/tests/test_legend.py::test_legend_auto1[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_legend_auto2[png]\", \"lib/matplotlib/tests/test_legend.py::test_legend_auto2[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_legend_auto3[png]\", \"lib/matplotlib/tests/test_legend.py::test_legend_auto3[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_various_labels[png]\", \"lib/matplotlib/tests/test_legend.py::test_various_labels[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_legend_label_with_leading_underscore\", \"lib/matplotlib/tests/test_legend.py::test_labels_first[png]\", \"lib/matplotlib/tests/test_legend.py::test_multiple_keys[png]\", \"lib/matplotlib/tests/test_legend.py::test_alpha_rgba[png]\", \"lib/matplotlib/tests/test_legend.py::test_alpha_rcparam[png]\", \"lib/matplotlib/tests/test_legend.py::test_fancy[png]\", \"lib/matplotlib/tests/test_legend.py::test_fancy[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_framealpha[png]\", \"lib/matplotlib/tests/test_legend.py::test_framealpha[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_rc[png]\", \"lib/matplotlib/tests/test_legend.py::test_rc[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_legend_expand[png]\", \"lib/matplotlib/tests/test_legend.py::test_legend_expand[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_hatching[png]\", \"lib/matplotlib/tests/test_legend.py::test_hatching[pdf]\", \"lib/matplotlib/tests/test_legend.py::test_legend_remove\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_no_args\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_positional_handles_labels\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_positional_handles_only\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_positional_labels_only\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_three_args\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_handler_map\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_kwargs_handles_only\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_kwargs_labels_only\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_legend_kwargs_handles_labels\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_warn_mixed_args_and_kwargs\", \"lib/matplotlib/tests/test_legend.py::TestLegendFunction::test_parasite\", \"lib/matplotlib/tests/test_legend.py::TestLegendFigureFunction::test_legend_handle_label\", \"lib/matplotlib/tests/test_legend.py::TestLegendFigureFunction::test_legend_no_args\", \"lib/matplotlib/tests/test_legend.py::TestLegendFigureFunction::test_legend_label_arg\", \"lib/matplotlib/tests/test_legend.py::TestLegendFigureFunction::test_legend_label_three_args\", \"lib/matplotlib/tests/test_legend.py::TestLegendFigureFunction::test_legend_label_three_args_pluskw\", \"lib/matplotlib/tests/test_legend.py::TestLegendFigureFunction::test_legend_kw_args\", \"lib/matplotlib/tests/test_legend.py::TestLegendFigureFunction::test_warn_args_kwargs\", \"lib/matplotlib/tests/test_legend.py::test_legend_stackplot[png]\", \"lib/matplotlib/tests/test_legend.py::test_cross_figure_patch_legend\", \"lib/matplotlib/tests/test_legend.py::test_nanscatter\", \"lib/matplotlib/tests/test_legend.py::test_legend_repeatcheckok\", \"lib/matplotlib/tests/test_legend.py::test_not_covering_scatter[png]\", \"lib/matplotlib/tests/test_legend.py::test_not_covering_scatter_transform[png]\", \"lib/matplotlib/tests/test_legend.py::test_linecollection_scaled_dashes\", \"lib/matplotlib/tests/test_legend.py::test_handler_numpoints\", \"lib/matplotlib/tests/test_legend.py::test_text_nohandler_warning\", \"lib/matplotlib/tests/test_legend.py::test_empty_bar_chart_with_legend\", \"lib/matplotlib/tests/test_legend.py::test_shadow_framealpha\", \"lib/matplotlib/tests/test_legend.py::test_legend_title_empty\", \"lib/matplotlib/tests/test_legend.py::test_legend_proper_window_extent\", \"lib/matplotlib/tests/test_legend.py::test_window_extent_cached_renderer\", \"lib/matplotlib/tests/test_legend.py::test_legend_title_fontprop_fontsize\", \"lib/matplotlib/tests/test_legend.py::test_legend_alignment[center]\", \"lib/matplotlib/tests/test_legend.py::test_legend_alignment[left]\", \"lib/matplotlib/tests/test_legend.py::test_legend_alignment[right]\", \"lib/matplotlib/tests/test_legend.py::test_legend_set_alignment[center]\", \"lib/matplotlib/tests/test_legend.py::test_legend_set_alignment[left]\", \"lib/matplotlib/tests/test_legend.py::test_legend_set_alignment[right]\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_single[red]\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_single[none]\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_single[color2]\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_list\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_linecolor\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_markeredgecolor\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_markerfacecolor\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_single[red]\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_single[none]\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_single[color2]\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_linecolor\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_markeredgecolor\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_markeredgecolor_short\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_markerfacecolor\", \"lib/matplotlib/tests/test_legend.py::test_legend_labelcolor_rcparam_markerfacecolor_short\", \"lib/matplotlib/tests/test_legend.py::test_get_set_draggable\", \"lib/matplotlib/tests/test_legend.py::test_alpha_handles\", \"lib/matplotlib/tests/test_legend.py::test_warn_big_data_best_loc\", \"lib/matplotlib/tests/test_legend.py::test_no_warn_big_data_when_loc_specified\", \"lib/matplotlib/tests/test_legend.py::test_plot_multiple_input_multiple_label[label_array0]\", \"lib/matplotlib/tests/test_legend.py::test_plot_multiple_input_multiple_label[label_array1]\", \"lib/matplotlib/tests/test_legend.py::test_plot_multiple_input_multiple_label[label_array2]\", \"lib/matplotlib/tests/test_legend.py::test_plot_multiple_input_single_label[one]\", \"lib/matplotlib/tests/test_legend.py::test_plot_multiple_input_single_label[1]\", \"lib/matplotlib/tests/test_legend.py::test_plot_multiple_input_single_label[int]\", \"lib/matplotlib/tests/test_legend.py::test_plot_single_input_multiple_label[label_array0]\", \"lib/matplotlib/tests/test_legend.py::test_plot_single_input_multiple_label[label_array1]\", \"lib/matplotlib/tests/test_legend.py::test_plot_single_input_multiple_label[label_array2]\", \"lib/matplotlib/tests/test_legend.py::test_plot_multiple_label_incorrect_length_exception\", \"lib/matplotlib/tests/test_legend.py::test_legend_face_edgecolor\", \"lib/matplotlib/tests/test_legend.py::test_legend_text_axes\", \"lib/matplotlib/tests/test_legend.py::test_handlerline2d\", \"lib/matplotlib/tests/test_legend.py::test_subfigure_legend\", \"lib/matplotlib/tests/test_legend.py::test_setting_alpha_keeps_polycollection_color\", \"lib/matplotlib/tests/test_legend.py::test_legend_markers_from_line2d\", \"lib/matplotlib/tests/test_legend.py::test_ncol_ncols[png]\", \"lib/matplotlib/tests/test_legend.py::test_ncol_ncols[pdf]\"]", "environment_setup_commit": "73909bcb408886a22e2b84581d6b9e6d9907c813", "test_directives": ["lib/matplotlib/tests/test_legend.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v lib/matplotlib/tests/test_legend.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "fail_to_pass", "model_prepare_test_patch": "diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py\nindex 16847e0be6..e474fe4a46 100644\n--- a/lib/matplotlib/tests/test_legend.py\n+++ b/lib/matplotlib/tests/test_legend.py\n@@ -245,6 +245,11 @@ class TestLegendFunction:\n with mock.patch('matplotlib.legend.Legend') as Legend:\n plt.legend()\n Legend.assert_called_with(plt.gca(), lines, ['hello world'])\n+ \n+ def test_legend_draggable(self):\n+ lines = plt.plot(range(10), label='hello world')\n+ legend = plt.legend(draggable=True)\n+ assert legend.get_draggable() is True\n \n def test_legend_positional_handles_labels(self):\n lines = plt.plot(range(10))\n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["lib/matplotlib/tests/test_legend.py"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py\nindex 9e5b903d59..bba954b6f8 100644\n--- a/lib/matplotlib/legend.py\n+++ b/lib/matplotlib/legend.py\n@@ -323,6 +323,7 @@ class Legend(Artist):\n handletextpad=None, # pad between the legend handle and text\n borderaxespad=None, # pad between the axes and legend border\n columnspacing=None, # spacing between columns\n+ draggable=False, # make the legend draggable\n \n ncols=1, # number of columns\n mode=None, # horizontal distribution of columns: None or \"expand\"\n@@ -539,6 +540,9 @@ class Legend(Artist):\n self.set_title(title, prop=title_prop_fp)\n self._draggable = None\n \n+ # Set the draggable state if specified\n+ self.set_draggable(draggable)\n+\n # set the text color\n \n color_getters = { # getter function depends on line or patch\n", "model_lint_repair_patch": "diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py\nindex 9e5b903d59..bba954b6f8 100644\n--- a/lib/matplotlib/legend.py\n+++ b/lib/matplotlib/legend.py\n@@ -323,6 +323,7 @@ class Legend(Artist):\n handletextpad=None, # pad between the legend handle and text\n borderaxespad=None, # pad between the axes and legend border\n columnspacing=None, # spacing between columns\n+ draggable=False, # make the legend draggable\n \n ncols=1, # number of columns\n mode=None, # horizontal distribution of columns: None or \"expand\"\n@@ -539,6 +540,9 @@ class Legend(Artist):\n self.set_title(title, prop=title_prop_fp)\n self._draggable = None\n \n+ # Set the draggable state if specified\n+ self.set_draggable(draggable)\n+\n # set the text color\n \n color_getters = { # getter function depends on line or patch\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["lib/matplotlib/tests/test_legend.py"]} +{"repo": "django/django", "instance_id": "django__django-13964", "base_commit": "f39634ff229887bf7790c069d0c411b38494ca38", "patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -933,7 +933,7 @@ def _prepare_related_fields_for_save(self, operation_name):\n \"%s() prohibited to prevent data loss due to unsaved \"\n \"related object '%s'.\" % (operation_name, field.name)\n )\n- elif getattr(self, field.attname) is None:\n+ elif getattr(self, field.attname) in field.empty_values:\n # Use pk from related object if it has been saved after\n # an assignment.\n setattr(self, field.attname, obj.pk)\n", "test_patch": "diff --git a/tests/many_to_one/models.py b/tests/many_to_one/models.py\n--- a/tests/many_to_one/models.py\n+++ b/tests/many_to_one/models.py\n@@ -68,6 +68,10 @@ class Parent(models.Model):\n bestchild = models.ForeignKey('Child', models.SET_NULL, null=True, related_name='favored_by')\n \n \n+class ParentStringPrimaryKey(models.Model):\n+ name = models.CharField(primary_key=True, max_length=15)\n+\n+\n class Child(models.Model):\n name = models.CharField(max_length=20)\n parent = models.ForeignKey(Parent, models.CASCADE)\n@@ -77,6 +81,10 @@ class ChildNullableParent(models.Model):\n parent = models.ForeignKey(Parent, models.CASCADE, null=True)\n \n \n+class ChildStringPrimaryKeyParent(models.Model):\n+ parent = models.ForeignKey(ParentStringPrimaryKey, on_delete=models.CASCADE)\n+\n+\n class ToFieldChild(models.Model):\n parent = models.ForeignKey(Parent, models.CASCADE, to_field='name', related_name='to_field_children')\n \ndiff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py\n--- a/tests/many_to_one/tests.py\n+++ b/tests/many_to_one/tests.py\n@@ -7,9 +7,9 @@\n from django.utils.translation import gettext_lazy\n \n from .models import (\n- Article, Category, Child, ChildNullableParent, City, Country, District,\n- First, Parent, Record, Relation, Reporter, School, Student, Third,\n- ToFieldChild,\n+ Article, Category, Child, ChildNullableParent, ChildStringPrimaryKeyParent,\n+ City, Country, District, First, Parent, ParentStringPrimaryKey, Record,\n+ Relation, Reporter, School, Student, Third, ToFieldChild,\n )\n \n \n@@ -549,6 +549,16 @@ def test_save_nullable_fk_after_parent_with_to_field(self):\n self.assertEqual(child.parent, parent)\n self.assertEqual(child.parent_id, parent.name)\n \n+ def test_save_fk_after_parent_with_non_numeric_pk_set_on_child(self):\n+ parent = ParentStringPrimaryKey()\n+ child = ChildStringPrimaryKeyParent(parent=parent)\n+ child.parent.name = 'jeff'\n+ parent.save()\n+ child.save()\n+ child.refresh_from_db()\n+ self.assertEqual(child.parent, parent)\n+ self.assertEqual(child.parent_id, parent.name)\n+\n def test_fk_to_bigautofield(self):\n ch = City.objects.create(name='Chicago')\n District.objects.create(city=ch, name='Far South')\n", "problem_statement": "Saving parent object after setting on child leads to data loss for parents with non-numeric primary key.\nDescription\n\t \n\t\t(last modified by Charlie DeTar)\n\t \nGiven a model with a foreign key relation to another model that has a non-auto CharField as its primary key:\nclass Product(models.Model):\n\tsku = models.CharField(primary_key=True, max_length=50)\nclass Order(models.Model):\n\tproduct = models.ForeignKey(Product, on_delete=models.CASCADE)\nIf the relation is initialized on the parent with an empty instance that does not yet specify its primary key, and the primary key is subsequently defined, the parent does not \"see\" the primary key's change:\nwith transaction.atomic():\n\torder = Order()\n\torder.product = Product()\n\torder.product.sku = \"foo\"\n\torder.product.save()\n\torder.save()\n\tassert Order.objects.filter(product_id=\"\").exists() # Succeeds, but shouldn't\n\tassert Order.objects.filter(product=order.product).exists() # Fails\nInstead of product_id being populated with product.sku, it is set to emptystring. The foreign key constraint which would enforce the existence of a product with sku=\"\" is deferred until the transaction commits. The transaction does correctly fail on commit with a ForeignKeyViolation due to the non-existence of a product with emptystring as its primary key.\nOn the other hand, if the related unsaved instance is initialized with its primary key before assignment to the parent, it is persisted correctly:\nwith transaction.atomic():\n\torder = Order()\n\torder.product = Product(sku=\"foo\")\n\torder.product.save()\n\torder.save()\n\tassert Order.objects.filter(product=order.product).exists() # succeeds\nCommitting the transaction also succeeds.\nThis may have something to do with how the Order.product_id field is handled at assignment, together with something about handling fetching of auto vs non-auto primary keys from the related instance.\n", "hints_text": "Thanks for this report. product_id is an empty string in \u200b_prepare_related_fields_for_save() that's why pk from a related object is not used. We could use empty_values: diff --git a/django/db/models/base.py b/django/db/models/base.py index 822aad080d..8e7a8e3ae7 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -933,7 +933,7 @@ class Model(metaclass=ModelBase): \"%s() prohibited to prevent data loss due to unsaved \" \"related object '%s'.\" % (operation_name, field.name) ) - elif getattr(self, field.attname) is None: + elif getattr(self, field.attname) in field.empty_values: # Use pk from related object if it has been saved after # an assignment. setattr(self, field.attname, obj.pk) but I'm not sure. Related with #28147.", "created_at": "2021-02-02T17:07:43Z", "version": "4.0", "FAIL_TO_PASS": "[\"test_save_fk_after_parent_with_non_numeric_pk_set_on_child (many_to_one.tests.ManyToOneTests)\"]", "PASS_TO_PASS": "[\"test_add (many_to_one.tests.ManyToOneTests)\", \"test_add_after_prefetch (many_to_one.tests.ManyToOneTests)\", \"test_add_remove_set_by_pk_raises (many_to_one.tests.ManyToOneTests)\", \"test_add_then_remove_after_prefetch (many_to_one.tests.ManyToOneTests)\", \"test_assign (many_to_one.tests.ManyToOneTests)\", \"test_assign_fk_id_none (many_to_one.tests.ManyToOneTests)\", \"test_assign_fk_id_value (many_to_one.tests.ManyToOneTests)\", \"test_cached_foreign_key_with_to_field_not_cleared_by_save (many_to_one.tests.ManyToOneTests)\", \"Model.save() invalidates stale ForeignKey relations after a primary key\", \"test_clear_after_prefetch (many_to_one.tests.ManyToOneTests)\", \"test_create (many_to_one.tests.ManyToOneTests)\", \"test_create_relation_with_gettext_lazy (many_to_one.tests.ManyToOneTests)\", \"test_deepcopy_and_circular_references (many_to_one.tests.ManyToOneTests)\", \"test_delete (many_to_one.tests.ManyToOneTests)\", \"test_explicit_fk (many_to_one.tests.ManyToOneTests)\", \"test_fk_assignment_and_related_object_cache (many_to_one.tests.ManyToOneTests)\", \"test_fk_instantiation_outside_model (many_to_one.tests.ManyToOneTests)\", \"test_fk_to_bigautofield (many_to_one.tests.ManyToOneTests)\", \"test_fk_to_smallautofield (many_to_one.tests.ManyToOneTests)\", \"test_get (many_to_one.tests.ManyToOneTests)\", \"test_hasattr_related_object (many_to_one.tests.ManyToOneTests)\", \"test_manager_class_caching (many_to_one.tests.ManyToOneTests)\", \"test_multiple_foreignkeys (many_to_one.tests.ManyToOneTests)\", \"test_related_object (many_to_one.tests.ManyToOneTests)\", \"test_relation_unsaved (many_to_one.tests.ManyToOneTests)\", \"test_remove_after_prefetch (many_to_one.tests.ManyToOneTests)\", \"test_reverse_assignment_deprecation (many_to_one.tests.ManyToOneTests)\", \"test_reverse_foreign_key_instance_to_field_caching (many_to_one.tests.ManyToOneTests)\", \"test_reverse_selects (many_to_one.tests.ManyToOneTests)\", \"test_save_nullable_fk_after_parent (many_to_one.tests.ManyToOneTests)\", \"test_save_nullable_fk_after_parent_with_to_field (many_to_one.tests.ManyToOneTests)\", \"test_select_related (many_to_one.tests.ManyToOneTests)\", \"test_selects (many_to_one.tests.ManyToOneTests)\", \"test_set (many_to_one.tests.ManyToOneTests)\", \"test_set_after_prefetch (many_to_one.tests.ManyToOneTests)\", \"test_values_list_exception (many_to_one.tests.ManyToOneTests)\"]", "environment_setup_commit": "475cffd1d64c690cdad16ede4d5e81985738ceb4", "test_directives": ["many_to_one.models", "many_to_one.tests"], "test_cmd": "./tests/runtests.py --verbosity 2 many_to_one.models many_to_one.tests", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_fail", "model_prepare_test_patch": "diff --git a/tests/model_fields/test_foreignkey.py b/tests/model_fields/test_foreignkey.py\nindex d30cca9b5c..587418eef3 100644\n--- a/tests/model_fields/test_foreignkey.py\n+++ b/tests/model_fields/test_foreignkey.py\n@@ -3,7 +3,7 @@ from decimal import Decimal\n from django.apps import apps\n from django.core import checks\n from django.core.exceptions import FieldError\n-from django.db import models\n+from django.db import models, transaction\n from django.test import TestCase, skipIfDBFeature\n from django.test.utils import isolate_apps\n \n@@ -29,7 +29,33 @@ class ForeignKeyTests(TestCase):\n self.assertEqual(fk_model_empty.out, char_model_empty)\n \n @isolate_apps('model_fields')\n+ def test_save_parent_after_setting_child_with_non_numeric_pk(self):\n+ \"\"\"\n+ Saving parent object after setting on child leads to data loss for parents with non-numeric primary key.\n+ \"\"\"\n+ class Product(models.Model):\n+ sku = models.CharField(primary_key=True, max_length=50)\n+\n+ class Order(models.Model):\n+ product = models.ForeignKey(Product, on_delete=models.CASCADE)\n+\n+ with transaction.atomic():\n+ order = Order()\n+ order.product = Product()\n+ order.product.sku = \"foo\"\n+ order.product.save()\n+ order.save()\n+ self.assertFalse(Order.objects.filter(product_id=\"\").exists(), \"Order with empty product_id should not exist\")\n+ self.assertTrue(Order.objects.filter(product=order.product).exists(), \"Order with correct product should exist\")\n+\n+ with transaction.atomic():\n+ order = Order()\n+ order.product = Product(sku=\"foo\")\n+ order.product.save()\n+ order.save()\n+ self.assertTrue(Order.objects.filter(product=order.product).exists(), \"Order with correct product should exist\")\n def test_warning_when_unique_true_on_fk(self):\n+\n class Foo(models.Model):\n pass\n \n", "model_prepare_test_num_attempts": 2, "model_test_directives": ["model_fields.test_foreignkey"], "model_is_issue_reproduced": true, "model_apply_patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\nindex 2428218696..6eb7b6df92 100644\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -425,6 +425,12 @@ class Model(metaclass=ModelBase):\n # Daft, but matches old exception sans the err msg.\n raise IndexError(\"Number of args exceeds number of fields\")\n \n+ if hasattr(opts, '_related_pk_changes'):\n+ for field_name, field in opts._related_pk_changes.items():\n+ related_obj = kwargs.get(field_name)\n+ if related_obj:\n+ related_obj._meta._related_pk_changes[field_name] = field\n+\n if not kwargs:\n fields_iter = iter(opts.concrete_fields)\n # The ordering of the zip calls matter - zip throws StopIteration\n\ndiff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py\nindex 899ae8efe8..f1a34f7675 100644\n--- a/django/db/models/fields/related.py\n+++ b/django/db/models/fields/related.py\n@@ -105,6 +105,43 @@ class RelatedField(FieldCacheMixin, Field):\n *self._check_clashes(),\n ]\n \n+ def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n+ super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n+ self.opts = cls._meta\n+\n+ if not cls._meta.abstract:\n+ if self.remote_field.related_name:\n+ related_name = self.remote_field.related_name\n+ else:\n+ related_name = self.opts.default_related_name\n+ if related_name:\n+ related_name = related_name % {\n+ 'class': cls.__name__.lower(),\n+ 'model_name': cls._meta.model_name.lower(),\n+ 'app_label': cls._meta.app_label.lower()\n+ }\n+ self.remote_field.related_name = related_name\n+\n+ if self.remote_field.related_query_name:\n+ related_query_name = self.remote_field.related_query_name % {\n+ 'class': cls.__name__.lower(),\n+ 'app_label': cls._meta.app_label.lower(),\n+ }\n+ self.remote_field.related_query_name = related_query_name\n+\n+ def resolve_related_class(model, related, field):\n+ field.remote_field.model = related\n+ field.do_related_class(related, model)\n+ # Listen for changes to the primary key of the related object\n+ if hasattr(related, '_meta'):\n+ related._meta._related_pk_changes[field.name] = field\n+\n+ lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)\n+ *self._check_relation_model_exists(),\n+ *self._check_referencing_to_swapped_model(),\n+ *self._check_clashes(),\n+ ]\n+\n def _check_related_name_is_valid(self):\n import keyword\n related_name = self.remote_field.related_name\n\ndiff --git a/django/db/models/options.py b/django/db/models/options.py\nindex 4028e05b99..8dcbb511d1 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -77,6 +77,7 @@ class Options:\n self.local_many_to_many = []\n self.private_fields = []\n self.local_managers = []\n+ self._related_pk_changes = {}\n self.base_manager_name = None\n self.default_manager_name = None\n self.model_name = None\n", "model_lint_repair_patch": "diff --git a/django/db/models/base.py b/django/db/models/base.py\nindex 2428218696..6eb7b6df92 100644\n--- a/django/db/models/base.py\n+++ b/django/db/models/base.py\n@@ -425,6 +425,12 @@ class Model(metaclass=ModelBase):\n # Daft, but matches old exception sans the err msg.\n raise IndexError(\"Number of args exceeds number of fields\")\n \n+ if hasattr(opts, '_related_pk_changes'):\n+ for field_name, field in opts._related_pk_changes.items():\n+ related_obj = kwargs.get(field_name)\n+ if related_obj:\n+ related_obj._meta._related_pk_changes[field_name] = field\n+\n if not kwargs:\n fields_iter = iter(opts.concrete_fields)\n # The ordering of the zip calls matter - zip throws StopIteration\n\ndiff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py\nindex 899ae8efe8..da81e31b3f 100644\n--- a/django/db/models/fields/related.py\n+++ b/django/db/models/fields/related.py\n@@ -105,6 +105,42 @@ class RelatedField(FieldCacheMixin, Field):\n *self._check_clashes(),\n ]\n \n+ def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n+ super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n+ self.opts = cls._meta\n+\n+ if not cls._meta.abstract:\n+ if self.remote_field.related_name:\n+ related_name = self.remote_field.related_name\n+ else:\n+ related_name = self.opts.default_related_name\n+ if related_name:\n+ related_name = related_name % {\n+ 'class': cls.__name__.lower(),\n+ 'model_name': cls._meta.model_name.lower(),\n+ 'app_label': cls._meta.app_label.lower()\n+ }\n+ self.remote_field.related_name = related_name\n+\n+ if self.remote_field.related_query_name:\n+ related_query_name = self.remote_field.related_query_name % {\n+ 'class': cls.__name__.lower(),\n+ 'app_label': cls._meta.app_label.lower(),\n+ }\n+ self.remote_field.related_query_name = related_query_name\n+\n+ def resolve_related_class(model, related, field):\n+ field.remote_field.model = related\n+ field.do_related_class(related, model)\n+ # Listen for changes to the primary key of the related object\n+ if hasattr(related, '_meta'):\n+ related._meta._related_pk_changes[field.name] = field\n+\n+ lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)\n+ *self._check_relation_model_exists(),\n+ *self._check_referencing_to_swapped_model(),\n+ *self._check_clashes()\n+\n def _check_related_name_is_valid(self):\n import keyword\n related_name = self.remote_field.related_name\n\ndiff --git a/django/db/models/options.py b/django/db/models/options.py\nindex 4028e05b99..8dcbb511d1 100644\n--- a/django/db/models/options.py\n+++ b/django/db/models/options.py\n@@ -77,6 +77,7 @@ class Options:\n self.local_many_to_many = []\n self.private_fields = []\n self.local_managers = []\n+ self._related_pk_changes = {}\n self.base_manager_name = None\n self.default_manager_name = None\n self.model_name = None\n", "model_verify_succeeded": false, "model_verify_patch": null, "model_verify_test_directives_succeeded": []} +{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-13584", "base_commit": "0e3c1879b06d839171b7d0a607d71bbb19a966a9", "patch": "diff --git a/sklearn/utils/_pprint.py b/sklearn/utils/_pprint.py\n--- a/sklearn/utils/_pprint.py\n+++ b/sklearn/utils/_pprint.py\n@@ -95,7 +95,7 @@ def _changed_params(estimator):\n init_params = signature(init_func).parameters\n init_params = {name: param.default for name, param in init_params.items()}\n for k, v in params.items():\n- if (v != init_params[k] and\n+ if (repr(v) != repr(init_params[k]) and\n not (is_scalar_nan(init_params[k]) and is_scalar_nan(v))):\n filtered_params[k] = v\n return filtered_params\n", "test_patch": "diff --git a/sklearn/utils/tests/test_pprint.py b/sklearn/utils/tests/test_pprint.py\n--- a/sklearn/utils/tests/test_pprint.py\n+++ b/sklearn/utils/tests/test_pprint.py\n@@ -4,6 +4,7 @@\n import numpy as np\n \n from sklearn.utils._pprint import _EstimatorPrettyPrinter\n+from sklearn.linear_model import LogisticRegressionCV\n from sklearn.pipeline import make_pipeline\n from sklearn.base import BaseEstimator, TransformerMixin\n from sklearn.feature_selection import SelectKBest, chi2\n@@ -212,6 +213,9 @@ def test_changed_only():\n expected = \"\"\"SimpleImputer()\"\"\"\n assert imputer.__repr__() == expected\n \n+ # make sure array parameters don't throw error (see #13583)\n+ repr(LogisticRegressionCV(Cs=np.array([0.1, 1])))\n+\n set_config(print_changed_only=False)\n \n \n", "problem_statement": "bug in print_changed_only in new repr: vector values\n```python\r\nimport sklearn\r\nimport numpy as np\r\nfrom sklearn.linear_model import LogisticRegressionCV\r\nsklearn.set_config(print_changed_only=True)\r\nprint(LogisticRegressionCV(Cs=np.array([0.1, 1])))\r\n```\r\n> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\r\n\r\nping @NicolasHug \r\n\n", "hints_text": "", "created_at": "2019-04-05T23:09:48Z", "version": "0.21", "FAIL_TO_PASS": "[\"sklearn/utils/tests/test_pprint.py::test_changed_only\", \"sklearn/utils/tests/test_pprint.py::test_pipeline\", \"sklearn/utils/tests/test_pprint.py::test_deeply_nested\", \"sklearn/utils/tests/test_pprint.py::test_gridsearch\", \"sklearn/utils/tests/test_pprint.py::test_gridsearch_pipeline\", \"sklearn/utils/tests/test_pprint.py::test_n_max_elements_to_show\"]", "PASS_TO_PASS": "[\"sklearn/utils/tests/test_pprint.py::test_basic\", \"sklearn/utils/tests/test_pprint.py::test_length_constraint\", \"sklearn/utils/tests/test_pprint.py::test_builtin_prettyprinter\"]", "environment_setup_commit": "7813f7efb5b2012412888b69e73d76f2df2b50b6", "test_directives": ["sklearn/utils/tests/test_pprint.py"], "test_cmd": "pytest --no-header -rA --tb=no -p no:cacheprovider -v sklearn/utils/tests/test_pprint.py", "model_name_or_path": "navie", "model_iteration": 3, "model_patch": null, "model_patch_name": "pass_to_pass", "model_prepare_test_patch": "", "model_prepare_test_num_attempts": 3, "model_test_directives": ["sklearn/utils/tests/test_pprint.py"], "model_is_issue_reproduced": false, "model_apply_patch": "diff --git a/sklearn/utils/_pprint.py b/sklearn/utils/_pprint.py\nindex b8686dba5..195d20755 100644\n--- a/sklearn/utils/_pprint.py\n+++ b/sklearn/utils/_pprint.py\n@@ -332,9 +332,10 @@ class _EstimatorPrettyPrinter(pprint.PrettyPrinter):\n def _safe_repr(object, context, maxlevels, level, changed_only=False):\n \"\"\"Same as the builtin _safe_repr, with added support for Estimator\n objects.\"\"\"\n+ import numpy as np\n typ = type(object)\n \n- if typ in pprint._builtin_scalars:\n+ if typ in pprint._builtin_scalars or isinstance(object, np.ndarray):\n return repr(object), True, False\n \n r = getattr(typ, \"__repr__\", None)\n@@ -390,15 +391,20 @@ def _safe_repr(object, context, maxlevels, level, changed_only=False):\n append = components.append\n level += 1\n for o in object:\n- orepr, oreadable, orecur = _safe_repr(\n- o, context, maxlevels, level, changed_only=changed_only)\n- append(orepr)\n- if not oreadable:\n- readable = False\n- if orecur:\n- recursive = True\n- del context[objid]\n- return format % \", \".join(components), readable, recursive\n+ if isinstance(o, np.ndarray):\n+ orepr = repr(o)\n+ oreadable = True\n+ orecur = False\n+ else:\n+ orepr, oreadable, orecur = _safe_repr(\n+ o, context, maxlevels, level, changed_only=changed_only)\n+ append(orepr)\n+ if not oreadable:\n+ readable = False\n+ if orecur:\n+ recursive = True\n+ del context[objid]\n+ return format % \", \".join(components), readable, recursive\n \n if issubclass(typ, BaseEstimator):\n objid = id(object)\n", "model_lint_repair_patch": "diff --git a/sklearn/utils/_pprint.py b/sklearn/utils/_pprint.py\nindex b8686dba5..18b2d3864 100644\n--- a/sklearn/utils/_pprint.py\n+++ b/sklearn/utils/_pprint.py\n@@ -332,9 +332,10 @@ class _EstimatorPrettyPrinter(pprint.PrettyPrinter):\n def _safe_repr(object, context, maxlevels, level, changed_only=False):\n \"\"\"Same as the builtin _safe_repr, with added support for Estimator\n objects.\"\"\"\n+ import numpy as np\n typ = type(object)\n \n- if typ in pprint._builtin_scalars:\n+ if typ in pprint._builtin_scalars or isinstance(object, np.ndarray):\n return repr(object), True, False\n \n r = getattr(typ, \"__repr__\", None)\n@@ -390,8 +391,13 @@ def _safe_repr(object, context, maxlevels, level, changed_only=False):\n append = components.append\n level += 1\n for o in object:\n- orepr, oreadable, orecur = _safe_repr(\n- o, context, maxlevels, level, changed_only=changed_only)\n+ if isinstance(o, np.ndarray):\n+ orepr = repr(o)\n+ oreadable = True\n+ orecur = False\n+ else:\n+ orepr, oreadable, orecur = _safe_repr(\n+ o, context, maxlevels, level, changed_only=changed_only)\n append(orepr)\n if not oreadable:\n readable = False\n", "model_verify_succeeded": true, "model_verify_patch": null, "model_verify_test_directives_succeeded": ["sklearn/utils/tests/test_pprint.py"]}