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

Issue:
CSRF error when add cases to test runs
Reproduce steps:

* Go to a plan page
* Select a few cases
* Click "Add cases to runs"
* Select at least one test run and click Update button
* Confirm yes, then error occurs:

Forbidden (403)
CSRF verification failed. Request aborted.


Discussion:

Resolving patch:
diff --git a/src/tcms/testplans/views.py b/src/tcms/testplans/views.py
--- a/src/tcms/testplans/views.py
+++ b/src/tcms/testplans/views.py
@@ -339,8 +339,8 @@ def get(self, request, plan_id):
         )
 
     def post(self, request, plan_id):
-        choosed_testrun_ids = request.POST.getlist("testrun_ids")
-        to_be_added_cases = TestCase.objects.filter(pk__in=request.POST.getlist("case_ids"))
+        choosed_testrun_ids = request.POST.getlist("run")
+        to_be_added_cases = TestCase.objects.filter(pk__in=request.POST.getlist("case"))
 
         plan_url = reverse("plan-get", args=[plan_id])
 


Test patch:
diff --git a/src/tests/testplans/test_views.py b/src/tests/testplans/test_views.py
--- a/src/tests/testplans/test_views.py
+++ b/src/tests/testplans/test_views.py
@@ -889,8 +889,8 @@ def test_add_cases_to_runs(self):
         resp = self.client.post(
             self.url,
             data={
-                "testrun_ids": self.test_run_2.pk,
-                "case_ids": [self.case_1.pk, self.case_2.pk],
+                "run": self.test_run_2.pk,
+                "case": [self.case_1.pk, self.case_2.pk],
             },
         )
 
@@ -918,8 +918,8 @@ def test_404_if_some_run_id_does_not_exist(self):
         resp = self.client.post(
             self.url,
             data={
-                "testrun_ids": self.test_run_2.pk + 1,
-                "case_ids": [self.case_1.pk, self.case_2.pk],
+                "run": self.test_run_2.pk + 1,
+                "case": [self.case_1.pk, self.case_2.pk],
             },
         )
Repository: Nitrate/Nitrate

Issue:
View function `testplans.views.delete` is not used, remove it.
As per subject.


Discussion:

Resolving patch:
diff --git a/src/tcms/testplans/urls/plan_urls.py b/src/tcms/testplans/urls/plan_urls.py
--- a/src/tcms/testplans/urls/plan_urls.py
+++ b/src/tcms/testplans/urls/plan_urls.py
@@ -9,7 +9,6 @@
 urlpatterns = [
     path("<int:plan_id>/", views.get, name="plan-get"),
     path("<int:plan_id>/<slug:slug>", views.get, name="plan-get"),
-    path("<int:plan_id>/delete/", views.delete, name="plan-delete"),
     path(
         "<int:plan_id>/chooseruns/",
         views.AddCasesToRunsView.as_view(),
diff --git a/src/tcms/testplans/views.py b/src/tcms/testplans/views.py
--- a/src/tcms/testplans/views.py
+++ b/src/tcms/testplans/views.py
@@ -149,35 +149,6 @@ def post(self, request):
         return HttpResponseRedirect(reverse("plan-get", args=[tp.plan_id]))
 
 
-@require_GET
-@permission_required("testplans.delete_testplan")
-def delete(request, plan_id):
-    """Delete testplan"""
-    if request.GET.get("sure", "no") == "no":
-        # TODO: rewrite the response
-        plan_delete_url = reverse("plan-delete", args=[plan_id])
-        return HttpResponse(
-            "<script>"
-            "if (confirm('Are you sure you want to delete this plan %s?\\n\\n"
-            "Click OK to delete or cancel to come back'))"
-            "{ window.location.href='%s?sure=yes' }"
-            "else { history.go(-1) }"
-            "</script>" % (plan_id, plan_delete_url)
-        )
-    elif request.GET.get("sure") == "yes":
-        tp = get_object_or_404(TestPlan, plan_id=plan_id)
-
-        try:
-            tp.delete()
-            return HttpResponse(
-                "<script>window.location.href='%s'</script>" % reverse("tcms.testplans.views.all")
-            )
-        except Exception:
-            return prompt.info(request, "Delete failed.")
-    else:
-        return prompt.info(request, "Nothing yet.")
-
-
 class SimplePlansFilterView(TemplateView):
     """Providing base plans filter functionaity"""
 


Test patch:
diff --git a/src/tests/testplans/test_views.py b/src/tests/testplans/test_views.py
--- a/src/tests/testplans/test_views.py
+++ b/src/tests/testplans/test_views.py
@@ -66,21 +66,6 @@ def test_search_plans(self):
         response = self.c.get(location, {"action": "search", "type": self.test_plan.type.pk})
         self.assert200(response)
 
-    def test_plan_delete(self):
-        tp_pk = self.test_plan.pk
-
-        location = reverse("plan-delete", args=[tp_pk])
-        response = self.c.get(location)
-        self.assert200(response)
-
-        response = self.c.get(location, {"sure": "no"})
-        self.assert200(response)
-
-        response = self.c.get(location, {"sure": "yes"})
-        self.assert200(response)
-        deleted = not TestPlan.objects.filter(pk=tp_pk).exists()
-        self.assertTrue(deleted, f"TestPlan {tp_pk} should be deleted. But, not.")
-
     def test_plan_edit(self):
         location = reverse("plan-edit", args=[self.plan_id])
         response = self.c.get(location)
Repository: Nitrate/Nitrate

Issue:
Social Auth Provider requires URLS
According to the [python-social-auth documentation](https://python-social-auth.readthedocs.io/en/latest/configuration/django.html#urls-entries), the url patterns have to be extended to support social auth properly.

```python
urlpatterns = patterns('',
    ...
    url('', include('social_django.urls', namespace='social'))
    ...
)
```

Hence the `urls.py` of the nitrate should be extended like this:

```python
if "SOCIAL" in settings.ENABLED_AUTH_BACKENDS:
    urlpatterns += [ path("", include('social_django.urls', namespace='social')) ]
```

Otherwise, the namespace social cannot be resolved when compiling the login page (refer to [this](https://github.com/Nitrate/Nitrate/blob/b89b37309f00469428e0372166d8c4c804bd9d0d/src/templates/registration/login.html#L53) for details).

Would you accept a pull request?
Social Auth Provider requires URLS
According to the [python-social-auth documentation](https://python-social-auth.readthedocs.io/en/latest/configuration/django.html#urls-entries), the url patterns have to be extended to support social auth properly.

```python
urlpatterns = patterns('',
    ...
    url('', include('social_django.urls', namespace='social'))
    ...
)
```

Hence the `urls.py` of the nitrate should be extended like this:

```python
if "SOCIAL" in settings.ENABLED_AUTH_BACKENDS:
    urlpatterns += [ path("", include('social_django.urls', namespace='social')) ]
```

Otherwise, the namespace social cannot be resolved when compiling the login page (refer to [this](https://github.com/Nitrate/Nitrate/blob/b89b37309f00469428e0372166d8c4c804bd9d0d/src/templates/registration/login.html#L53) for details).

Would you accept a pull request?


Discussion:
> Would you accept a pull request?

Sure. Appreicated.
> Would you accept a pull request?

Sure. Appreicated.

Resolving patch:
diff --git a/src/tcms/urls.py b/src/tcms/urls.py
--- a/src/tcms/urls.py
+++ b/src/tcms/urls.py
@@ -39,6 +39,10 @@
     path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
 ]
 
+# Python Social Core / Django Social Auth
+if "SOCIAL" in settings.ENABLED_AUTH_BACKENDS:
+    urlpatterns += [path("", include("social_django.urls", namespace="social"))]
+
 # Debug zone
 
 if settings.DEBUG:


Test patch:
Repository: allegro/ralph

Issue:
DC grid disappears when the amount of columns in a DC is greater than 40
I found out that the DC grid is limited to a 40x40 square and if the DC has more columns than 40, then the grid on it disappears completely. I think it would be nice to remove this limit so that the grid could scale indefinitely if possible or at least increase the limit to say 100x100.



Discussion:

Resolving patch:
diff --git a/src/ralph/data_center/migrations/0021_auto_20161003_0751.py b/src/ralph/data_center/migrations/0021_auto_20161003_0751.py
new file mode 100644
--- /dev/null
+++ b/src/ralph/data_center/migrations/0021_auto_20161003_0751.py
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.core.validators
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('data_center', '0020_auto_20160907_1116'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='serverroom',
+            name='visualization_cols_num',
+            field=models.PositiveIntegerField(default=20, verbose_name='visualization grid columns number', validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(100)]),
+        ),
+        migrations.AlterField(
+            model_name='serverroom',
+            name='visualization_rows_num',
+            field=models.PositiveIntegerField(default=20, verbose_name='visualization grid rows number', validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(100)]),
+        ),
+    ]
diff --git a/src/ralph/data_center/models/physical.py b/src/ralph/data_center/models/physical.py
--- a/src/ralph/data_center/models/physical.py
+++ b/src/ralph/data_center/models/physical.py
@@ -8,7 +8,11 @@
 from django.conf import settings
 from django.core.exceptions import ValidationError
 from django.core.urlresolvers import reverse
-from django.core.validators import RegexValidator
+from django.core.validators import (
+    MaxValueValidator,
+    MinValueValidator,
+    RegexValidator
+)
 from django.db import models, transaction
 from django.db.models import Q
 from django.db.models.signals import post_save
@@ -129,10 +133,18 @@ class ServerRoom(AdminAbsoluteUrlMixin, NamedMixin.NonUnique, models.Model):
     visualization_cols_num = models.PositiveIntegerField(
         verbose_name=_('visualization grid columns number'),
         default=20,
+        validators=[
+            MinValueValidator(1),
+            MaxValueValidator(100)  # is correlate with $grid-count
+        ]
     )
     visualization_rows_num = models.PositiveIntegerField(
         verbose_name=_('visualization grid rows number'),
         default=20,
+        validators=[
+            MinValueValidator(1),
+            MaxValueValidator(100)  # is correlate with $grid-count
+        ]
     )
     objects = ServerRoomManager()
 


Test patch:
Repository: allegro/ralph

Issue:
Doc fixes
Some minor doc fixes with a bit of style change



Discussion:

Resolving patch:
diff --git a/src/ralph/dashboards/management/commands/push_graphs_to_statsd.py b/src/ralph/dashboards/management/commands/push_graphs_to_statsd.py
--- a/src/ralph/dashboards/management/commands/push_graphs_to_statsd.py
+++ b/src/ralph/dashboards/management/commands/push_graphs_to_statsd.py
@@ -10,8 +10,6 @@
 from ralph.lib.metrics import build_statsd_client
 
 logger = logging.getLogger(__name__)
-PREFIX = settings.STATSD_GRAPHS_PREFIX
-STATSD_PATH = '{}.{{}}.{{}}'.format(PREFIX)
 
 
 def normalize(s):
@@ -24,11 +22,11 @@ class Command(BaseCommand):
     help = textwrap.dedent(__doc__).strip()
 
     def handle(self, *args, **kwargs):
-        statsd = build_statsd_client(prefix=STATSD_PATH)
+        statsd = build_statsd_client(prefix=settings.STATSD_GRAPHS_PREFIX)
         graphs = Graph.objects.filter(push_to_statsd=True)
         for graph in graphs:
             graph_data = graph.get_data()
             graph_name = normalize(graph.name)
             for label, value in zip(graph_data['labels'], graph_data['series']):
-                path = STATSD_PATH.format(graph_name, normalize(label))
+                path = '.'.join((graph_name, normalize(label)))
                 statsd.gauge(path, value)


Test patch:
Repository: rdmorganiser/rdmo

Issue:
Sorting causes problems with import
### Description / Beschreibung

When using different `uri_prefix`es for, e.g. a domain import, the sorting by `uri` destroys the order in the file, and parent Attributes are imported *after* their children (with a different `uri_prefix` earlier in the alphabet). This is the problematic line:

https://github.com/rdmorganiser/rdmo/blob/master/rdmo/core/xml.py#L52

### Expected behaviour / Erwartetes Verhalten

I am not sure if we could get rid of the sorting, we could also sort by `path` (which would give the field some meaning in the xml again). Ideas? @triole @MyPyDavid 



Discussion:
could you not find the different `uri_prefixes`  _first_ and loop over them to keep them separate?  
Don't know if it applies here, would need to reproduce it to better see it..

Resolving patch:
diff --git a/rdmo/core/constants.py b/rdmo/core/constants.py
--- a/rdmo/core/constants.py
+++ b/rdmo/core/constants.py
@@ -55,3 +55,12 @@
         'views.add_view', 'views.change_view', 'views.delete_view'
     )
 }
+
+IMPORT_SORT_ORDER = (
+    'domain',
+    'conditions',
+    'options',
+    'questions',
+    'tasks',
+    'views'
+)
diff --git a/rdmo/core/xml.py b/rdmo/core/xml.py
--- a/rdmo/core/xml.py
+++ b/rdmo/core/xml.py
@@ -3,6 +3,9 @@
 
 import defusedxml.ElementTree as ET
 
+from .constants import IMPORT_SORT_ORDER
+
+
 log = logging.getLogger(__name__)
 
 
@@ -49,7 +52,7 @@ def flat_xml_to_elements(treenode):
 
         elements.append(element)
 
-    elements = sort_elements_by_key(elements, 'uri')
+    elements = sorted(elements, key=sort_elements)
     return elements
 
 
@@ -92,5 +95,13 @@ def filter_elements_by_type(elements, element_type):
             yield element
 
 
-def sort_elements_by_key(dictlist, key, reverse=False):
-    return sorted(dictlist, key=lambda k: k[key], reverse=reverse)
+def sort_elements(element):
+    # remove the uri_prefix from the uri to create the key to be sorted by
+    sort_key = element['uri'].replace(element['uri_prefix'], '')
+
+    # remove the app name from the sort_key and replace it by its import order
+    for i, item in enumerate(IMPORT_SORT_ORDER):
+        if sort_key.startswith(item):
+            sort_key = sort_key.replace(item, str(i))
+
+    return sort_key


Test patch:
Repository: rdmorganiser/rdmo

Issue:
Nested projects: cancel button actually imports data
### Description / Beschreibung

In nested projects if someone opens the import from parent project and then decides not to import anything by clicking <kbd>Cancel</kbd> the data will be imported anyway.

### Expected behaviour / Erwartetes Verhalten

Expected behaviour is to get back to the project details view without any changes to the answers, i.e. not importing anything from the parent project.

### Steps to reproduce / Schritte zum Reproduzieren

1. Create a project and add some answers
2. Create a child project
3. In the child project go the import from parent project view
4. Click <kbd>Cancel</kbd> button
5. Answers are imported to the child project.




Discussion:

Resolving patch:
diff --git a/rdmo/projects/mixins.py b/rdmo/projects/mixins.py
--- a/rdmo/projects/mixins.py
+++ b/rdmo/projects/mixins.py
@@ -204,6 +204,12 @@ def import_file(self):
     def import_project(self):
         current_project = self.object
 
+        if 'cancel' in self.request.POST:
+            if current_project:
+                return HttpResponseRedirect(current_project.get_absolute_url())
+            else:
+                return HttpResponseRedirect(self.success_url)
+
         # get the original project
         project = get_object_or_404(Project.objects.all(), id=self.request.POST.get('source'))
 


Test patch:
Repository: rdmorganiser/rdmo

Issue:
Users with same email can not be invited
### Description / Beschreibung

Surprisingly, email addresses in RDMO don't have to be unique. I you invite an existin user to a project via email with a non unique mail the managers `.get()` function raises a `MultipleObjectsReturned`.

### Expected behaviour / Erwartetes Verhalten

(a) emails should unique in the first place or
(b) both users should be invited

Probably (b) is easier to implement.


Discussion:

Resolving patch:
diff --git a/rdmo/projects/forms.py b/rdmo/projects/forms.py
--- a/rdmo/projects/forms.py
+++ b/rdmo/projects/forms.py
@@ -192,16 +192,17 @@ def __init__(self, *args, **kwargs):
 
     def clean_username_or_email(self):
         username_or_email = self.cleaned_data['username_or_email']
+        usermodel = get_user_model()
 
-        # check if it is a registered
+        # check if it is a registered user
         try:
-            self.cleaned_data['user'] = get_user_model().objects.get(Q(username=username_or_email) | Q(email__iexact=username_or_email))
+            self.cleaned_data['user'] = usermodel.objects.get(Q(username=username_or_email) | Q(email__iexact=username_or_email))
             self.cleaned_data['email'] = self.cleaned_data['user'].email
 
             if self.cleaned_data['user'] in self.project.user.all():
                 raise ValidationError(_('The user is already a member of the project.'))
 
-        except get_user_model().DoesNotExist:
+        except (usermodel.DoesNotExist, usermodel.MultipleObjectsReturned):
             if settings.PROJECT_SEND_INVITE:
                 # check if it is a valid email address, this will raise the correct ValidationError
                 EmailValidator()(username_or_email)


Test patch:
Repository: rdmorganiser/rdmo

Issue:
Import from parent project list doesn't check permissions
### Description / Beschreibung

The list of projects in the import from parent project selection displays all parent projects independent of the user permissions.

### Expected behaviour / Erwartetes Verhalten

Import from parent project should display only projects where users have permissions to import data.

### Steps to reproduce / Schritte zum Reproduzieren

1. Load the dev fixtures in the latest RDMO Version: `python manage.py loaddata ../rdmo/testing/fixtures/*`
3. Log in to manager account.
4. Open Project "Child 1" or "Child 11"
5. List contains "Parent" although user does not have permissions.
6. When chosing "Parent" and trying to get to next step, RDMO displays "Forbidden", but I think it would be nicer if the option would not be present in the list.



Discussion:
Do you mean the project that is called "Parent" in the Project hierarchy of Child1 or Child11 that is "Forbidden" for Manni Manager?
I think so too that this project "Parent" should not be displayed (in the import dropdown and in the project header hierarchy) since the user "manager" is not even a member of the project "Parent".  
Templates:
* https://github.com/rdmorganiser/rdmo/blob/ef6e1f84e9e74212cfcbce5d75b12831a09d2b6f/rdmo/projects/templates/projects/project_detail_sidebar.html#L152
* https://github.com/rdmorganiser/rdmo/blob/ef6e1f84e9e74212cfcbce5d75b12831a09d2b6f/rdmo/projects/templates/projects/project_detail_header_hierarchy.html#L13


> Do you mean the project that is called "Parent" in the Project hierarchy of Child1 or Child11 that is "Forbidden" for Manni Manager?

Yes, exactly! Sorry for the confusing description, I edited my issue. 

Resolving patch:
diff --git a/rdmo/projects/views/project.py b/rdmo/projects/views/project.py
--- a/rdmo/projects/views/project.py
+++ b/rdmo/projects/views/project.py
@@ -126,6 +126,11 @@ def get_context_data(self, **kwargs):
                                                  .filter_catalog(self.object.catalog) \
                                                  .filter_group(self.request.user) \
                                                  .filter_availability(self.request.user).exists()
+        ancestors_import = []
+        for instance in ancestors.exclude(id=project.id):
+            if self.request.user.has_perm('projects.view_project_object', instance):
+                ancestors_import.append(instance)
+        context['ancestors_import'] = ancestors_import
         context['memberships'] = memberships.order_by('user__last_name', '-project__level')
         context['integrations'] = integrations.order_by('provider_key', '-project__level')
         context['providers'] = get_plugins('PROJECT_ISSUE_PROVIDERS')
@@ -133,7 +138,6 @@ def get_context_data(self, **kwargs):
         context['snapshots'] = project.snapshots.all()
         context['invites'] = project.invites.all()
         context['membership'] = Membership.objects.filter(project=project, user=self.request.user).first()
-
         return context
 
 


Test patch:
Repository: tj-django/django-view-breadcrumbs

Issue:
action_view_name() breaks with multi-lingual verbose_name
When model's verbose_name is set to gettext_lazy("something"), action_view_name() fetches the translated model name, which probably will break the URL reversal. Suggestion is to fetch verbose_name_raw instead.


Discussion:

Resolving patch:
diff --git a/view_breadcrumbs/generic/base.py b/view_breadcrumbs/generic/base.py
--- a/view_breadcrumbs/generic/base.py
+++ b/view_breadcrumbs/generic/base.py
@@ -1,6 +1,7 @@
 import logging
 
 from django.urls import reverse
+from django.utils.encoding import force_text
 from django.utils.functional import cached_property
 from django.utils.translation import ugettext_lazy as _
 from django_bootstrap_breadcrumbs.templatetags import (
@@ -39,11 +40,11 @@ def crumbs(self):
 
     @property
     def model_name_title_plural(self):
-        return getattr(self.model._meta, 'verbose_name_plural', '').title()
+        return force_text(getattr(self.model._meta, 'verbose_name_plural', '')).title()
 
     @property
     def model_name_title(self):
-        return getattr(self.model._meta, 'verbose_name', '').title()
+        return force_text(getattr(self.model._meta, 'verbose_name', '')).title()
 
     @property
     def list_view_name(self):
@@ -60,9 +61,7 @@ def update_breadcrumbs(self, context):
             try:
                 label, view_name = crumb
             except (TypeError, ValueError):
-                raise ValueError(
-                    'Breadcrumb requires a tuple of label and view name.',
-                )
+                raise ValueError('Breadcrumb requires a tuple of label and view name.')
             else:
                 if hasattr(self, 'object') and self.object:
                     if callable(label):
diff --git a/view_breadcrumbs/utils.py b/view_breadcrumbs/utils.py
--- a/view_breadcrumbs/utils.py
+++ b/view_breadcrumbs/utils.py
@@ -3,7 +3,8 @@
 
 def get_app_name(model):
     if model._meta.installed:
-        return getattr(model._meta, 'app_label')
+        return getattr(model._meta, 'label', '.').split('.')
+
     raise AppRegistryNotReady(
         '{model} is not installed or missing from the app registry.'.format(
             model=getattr(model._meta, 'app_label', model.__class__.__name__)
@@ -11,10 +12,13 @@ def get_app_name(model):
     )
 
 def action_view_name(model, action):
-    return (
-        '{0}:{1}_{2}'.format(
-            get_app_name(model),
-            getattr(model._meta, 'verbose_name', '').replace(' ', '_'),
-            action,
+    app_label, model_name = get_app_name(model)
+
+    if app_label and model_name:
+        return (
+            '{0}:{1}_{2}'.format(
+                app_label,
+                model_name.lower().replace(' ', '_'),
+                action,
+            )
         )
-    )


Test patch: