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

Issue:
Remove scrollbars when they are not necessary
The home page shows a scroll bar even when there is nothing to scroll

![image](https://user-images.githubusercontent.com/315678/41148811-6578191a-6af9-11e8-8469-cfdcaee737ad.png)

![image](https://user-images.githubusercontent.com/315678/41148904-a4713a02-6af9-11e8-9873-1cca3c4cc8a3.png)



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/organisation.py b/akvo/rest/views/organisation.py
--- a/akvo/rest/views/organisation.py
+++ b/akvo/rest/views/organisation.py
@@ -106,7 +106,7 @@ def organisation_directory(request):
 
     # Get related objects of page at once
     response = {
-        'project_count': all_organisations.count(),
+        'project_count': organisations_text_filtered.count(),
         'projects': OrganisationDirectorySerializer(display_organisations, many=True).data,
         'location': locations,
     }


Test patch:
Repository: akvo/akvo-rsr

Issue:
Results tab in project page doesn't show masqueraded dates for indicator periods
![image](https://user-images.githubusercontent.com/315678/41330393-c6490516-6ec2-11e8-9893-cd0e68ec64d3.png)
![image](https://user-images.githubusercontent.com/315678/41330395-cba2a4b8-6ec2-11e8-8bca-de956542df17.png)



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/project.py b/akvo/rsr/views/project.py
--- a/akvo/rsr/views/project.py
+++ b/akvo/rsr/views/project.py
@@ -141,6 +141,7 @@ def main(request, project_id, template="project_main.html"):
         'user_is_me_manager': 'false',
     }
 
+    context = project.project_hierarchy_context(context)
     return render(request, template, context)
 
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Pagination of projects is incorrect
On the home page, the pagination is off for large sets of projects. 

#### Example
Select the EU trust fund for Africa in the organisations filter. The pagination widget shows that there are 22 pages of projects, but the last [two are empty](https://rsr.akvo.org/en/projects/?organisation=3394&page=22)!


Discussion:
I suspect the bug is due to the [wrongly hard-coded default value](https://github.com/akvo/akvo-rsr/blob/develop/akvo/rsr/static/scripts-src/directory-utils.jsx#L552) of no. of projects in a page.  The server side setting needs to be propagated to the client. 

Resolving patch:
diff --git a/akvo/rest/views/project.py b/akvo/rest/views/project.py
--- a/akvo/rest/views/project.py
+++ b/akvo/rest/views/project.py
@@ -5,6 +5,7 @@
 For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
 """
 
+from django.conf import settings
 from django.db.models import Q
 from rest_framework.decorators import api_view
 from rest_framework.response import Response
@@ -289,6 +290,7 @@ def project_directory(request):
         'organisation': cached_organisations,
         'sector': TypeaheadSectorSerializer(sectors, many=True).data,
         'location': cached_locations,
+        'page_size_default': settings.PROJECT_DIRECTORY_PAGE_SIZES[0],
     }
 
     return Response(response)


Test patch:
Repository: akvo/akvo-rsr

Issue:
Add back API root page 
After versioning was implemented in the API, the default `api-root` view is broken. 


Discussion:

Resolving patch:
diff --git a/akvo/rest/urls.py b/akvo/rest/urls.py
--- a/akvo/rest/urls.py
+++ b/akvo/rest/urls.py
@@ -114,6 +114,13 @@
 router.register(r'(?P<version>(v1))/transaction_sector', views.TransactionSectorViewSet)
 router.register(r'(?P<version>(v1))/user', views.UserViewSet)
 
+
+# We turn off the API root view (since it's broken with URLPathVersioning)
+router.include_root_view = False
+# Add API root view by version
+root_url = url(r'(?P<version>(v1|v2))/$', router.get_api_root_view(), name=router.root_view_name)
+router.urls.append(root_url)
+
 # Additionally, we include URLs for non-viewsets (functional views).
 # NOTE: if versions is to be added to one of the views below, the view function needs to include
 # version in its parameters.


Test patch:
Repository: akvo/akvo-rsr

Issue:
Display last modified by information in the project editor



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/project.py b/akvo/rsr/models/project.py
--- a/akvo/rsr/models/project.py
+++ b/akvo/rsr/models/project.py
@@ -9,6 +9,8 @@
 from decimal import Decimal, InvalidOperation
 
 from django.conf import settings
+from django.contrib.admin.models import LogEntry
+from django.contrib.auth import get_user_model
 from django.core.exceptions import ValidationError, ObjectDoesNotExist, MultipleObjectsReturned
 from django.core.mail import send_mail
 from django.core.validators import MaxValueValidator, MinValueValidator
@@ -588,6 +590,16 @@ def update_funds_needed(self):
 
     # End new API
 
+    @property
+    def last_modified_by(self):
+        """Return the user who last edited this project."""
+        entries = LogEntry.objects.filter(object_id=self.id, object_repr=self.__unicode__())
+        if not entries.exists():
+            return None
+        user_id = entries.last().user_id
+        User = get_user_model()
+        return User.objects.only('first_name', 'last_name', 'email').get(id=user_id)
+
     @property
     def view_count(self):
         counter = ViewCounter.objects.get_for_object(self)


Test patch:
Repository: akvo/akvo-rsr

Issue:
Limit access to project access feature
Limit the access to the project access restrictions feature to users of a list of organisations.


Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/my_rsr.py b/akvo/rsr/views/my_rsr.py
--- a/akvo/rsr/views/my_rsr.py
+++ b/akvo/rsr/views/my_rsr.py
@@ -450,6 +450,16 @@ def user_management(request):
 
     :param request; a Django request.
     """
+
+    def _restrictions_turned_on(user):
+        # "Feature flag" for access restrictions
+        restricting_orgs = settings.ACCESS_RESTRICTIONS_ORGS
+
+        if ('ALL' in restricting_orgs or
+                user.approved_organisations().filter(pk__in=restricting_orgs).exists()):
+            return True
+        return False
+
     user = request.user
 
     if not user.has_perm('rsr.user_management'):
@@ -507,21 +517,24 @@ def user_management(request):
                 'id', 'first_name', 'last_name', 'email'
             ])
 
-            # determine if this user's project access can be restricted
-            if employment.user.has_perm('rsr.user_management'):
-                can_be_restricted = False
-            else:
-                can_be_restricted = True
-                #  We cannot limit project access to users that are employed by more than one
-                # organisation
-                if employment.user.approved_organisations().distinct().count() != 1:
+            if _restrictions_turned_on(user):
+                # determine if this user's project access can be restricted
+                if employment.user.has_perm('rsr.user_management'):
                     can_be_restricted = False
                 else:
-                    user_projects = UserProjects.objects.filter(user=employment.user)
-                    if user_projects.exists():
-                        user_dict['is_restricted'] = user_projects[0].is_restricted
-                        user_dict['restricted_count'] = user_projects[0].projects.count()
-            user_dict['can_be_restricted'] = can_be_restricted
+                    can_be_restricted = True
+                    #  We cannot limit project access to users that are employed by more than one
+                    # organisation
+                    if employment.user.approved_organisations().distinct().count() != 1:
+                        can_be_restricted = False
+                    else:
+                        user_projects = UserProjects.objects.filter(user=employment.user)
+                        if user_projects.exists():
+                            user_dict['is_restricted'] = user_projects[0].is_restricted
+                            user_dict['restricted_count'] = user_projects[0].projects.count()
+                user_dict['can_be_restricted'] = can_be_restricted
+            else:
+                user_dict['can_be_restricted'] = False
 
             employment_dict["user"] = user_dict
         employments_array.append(employment_dict)


Test patch:
Repository: akvo/akvo-rsr

Issue:
Google maps API requests should use an API key
`For development purposes only` watermark is being shown on our maps as Google has made it mandatory to use an API key to talk to the maps API. 


Discussion:

Resolving patch:
diff --git a/akvo/rsr/context_processors.py b/akvo/rsr/context_processors.py
--- a/akvo/rsr/context_processors.py
+++ b/akvo/rsr/context_processors.py
@@ -29,6 +29,7 @@ def extra_context(request, protocol="http"):
     deploy_commit_id = getattr(settings, 'DEPLOY_COMMIT_ID', 'Unknown')
     deploy_commit_full_id = getattr(settings, 'DEPLOY_COMMIT_FULL_ID', 'Unknown')
     sentry_dsn = get_sentry_dsn(settings)
+    gmaps_api_key = getattr(settings, 'GOOGLE_MAPS_API_KEY', 'NO_API_KEY')
 
     return dict(
         current_site=current_site,
@@ -39,6 +40,7 @@ def extra_context(request, protocol="http"):
         deploy_commit_id=deploy_commit_id,
         deploy_commit_full_id=deploy_commit_full_id,
         sentry_dsn=sentry_dsn,
+        gmaps_api_key=gmaps_api_key,
     )
 
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Pagination on the all updates page is broken



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/organisation.py b/akvo/rest/views/organisation.py
--- a/akvo/rest/views/organisation.py
+++ b/akvo/rest/views/organisation.py
@@ -109,6 +109,7 @@ def organisation_directory(request):
         'project_count': organisations_text_filtered.count(),
         'projects': OrganisationDirectorySerializer(display_organisations, many=True).data,
         'location': locations,
+        'page_size_default': settings.PROJECT_DIRECTORY_PAGE_SIZES[0],
     }
     return Response(response)
 
diff --git a/akvo/rest/views/project_update.py b/akvo/rest/views/project_update.py
--- a/akvo/rest/views/project_update.py
+++ b/akvo/rest/views/project_update.py
@@ -7,6 +7,7 @@
 
 from re import match
 
+from django.conf import settings
 from django.db.models import Q
 from rest_framework.decorators import api_view, permission_classes
 from rest_framework.permissions import IsAuthenticated
@@ -214,6 +215,7 @@ def update_directory(request):
         'organisation': TypeaheadOrganisationSerializer(organisations, many=True).data,
         'location': locations,
         'sector': TypeaheadSectorSerializer(sectors, many=True).data,
+        'page_size_default': settings.PROJECT_DIRECTORY_PAGE_SIZES[0],
     }
     return Response(response)
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
ValidationErrors should be handled correctly in POSTs to /auth/token 



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/account.py b/akvo/rsr/views/account.py
--- a/akvo/rsr/views/account.py
+++ b/akvo/rsr/views/account.py
@@ -20,7 +20,7 @@
 from django.conf import settings
 from django.contrib.auth import login, logout, authenticate, get_user_model
 from django.contrib.auth.forms import AuthenticationForm, PasswordResetForm
-from django.core.exceptions import ObjectDoesNotExist
+from django.core.exceptions import ObjectDoesNotExist, ValidationError
 from django.core.signing import TimestampSigner, BadSignature
 from django.http import (HttpResponse, HttpResponseRedirect,
                          HttpResponseForbidden)
@@ -295,7 +295,10 @@ def api_key(request):
     handles_unemployed = bool(request.POST.get("handles_unemployed", False))
 
     if username and password:
-        user = authenticate(username=username, password=password)
+        try:
+            user = authenticate(username=username, password=password)
+        except ValidationError:
+            user = None
         if user is not None and user.is_active:
             orgs = user.approved_organisations()
             if orgs or handles_unemployed:


Test patch:
Repository: akvo/akvo-rsr

Issue:
Results framework loads very slowly for projects with lot of indicator dimensions



Discussion:

Resolving patch:
diff --git a/akvo/rest/pagination.py b/akvo/rest/pagination.py
--- a/akvo/rest/pagination.py
+++ b/akvo/rest/pagination.py
@@ -8,12 +8,18 @@
 from rest_framework.response import Response
 
 
-class LimitSizePageNumberPagination(pagination.PageNumberPagination):
+class StandardSizePageNumberPagination(pagination.PageNumberPagination):
     page_size = 30
     page_size_query_param = 'limit'
     max_page_size = 100
 
 
+class LargeSizePageNumberPagination(pagination.PageNumberPagination):
+    page_size = 100
+    page_size_query_param = 'limit'
+    max_page_size = 1000
+
+
 class TastypieOffsetPagination(pagination.LimitOffsetPagination):
 
     def get_paginated_response(self, data):
diff --git a/akvo/rest/views/indicator_dimension.py b/akvo/rest/views/indicator_dimension.py
--- a/akvo/rest/views/indicator_dimension.py
+++ b/akvo/rest/views/indicator_dimension.py
@@ -6,6 +6,7 @@
 
 
 from akvo.rsr.models import IndicatorDimension
+from akvo.rest.pagination import LargeSizePageNumberPagination
 
 from ..serializers import IndicatorDimensionSerializer
 from ..viewsets import PublicProjectViewSet
@@ -17,3 +18,4 @@ class IndicatorDimensionViewSet(PublicProjectViewSet):
     queryset = IndicatorDimension.objects.all()
     serializer_class = IndicatorDimensionSerializer
     project_relation = 'indicator__result__project__'
+    pagination_class = LargeSizePageNumberPagination


Test patch:
Repository: akvo/akvo-rsr

Issue:
Min password length missng from activate invite page
Template rendering context is missing the `password_length` variable. 


Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/account.py b/akvo/rsr/views/account.py
--- a/akvo/rsr/views/account.py
+++ b/akvo/rsr/views/account.py
@@ -180,6 +180,7 @@ def login_and_redirect(req, invited):
     context = {
         'form': form,
         'bad_link': bad_link,
+        'password_length': settings.PASSWORD_MINIMUM_LENGTH
     }
     return render(request, 'registration/invite_activate.html', context)
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Project list widget fails due to a date vs. datetime formatting error



Discussion:

Resolving patch:
diff --git a/akvo/rsr/templatetags/rsr_filters.py b/akvo/rsr/templatetags/rsr_filters.py
--- a/akvo/rsr/templatetags/rsr_filters.py
+++ b/akvo/rsr/templatetags/rsr_filters.py
@@ -6,9 +6,6 @@
 For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
 """
 
-import datetime
-import time
-
 from django import template
 from django.conf import settings
 from decimal import Decimal, ROUND_HALF_UP
@@ -24,18 +21,7 @@ def get_item(dictionary, key):
     return dictionary.get(key)
 
 
-@register.filter
-def string_to_date(value):
-    try:
-        time_format = "%Y-%m-%d %H:%M:%S"
-        fmt_time = time.strptime(value, time_format)
-        return datetime.datetime(*fmt_time[:6])
-    except:
-        return value
-
 # http://stackoverflow.com/questions/250357/smart-truncate-in-python
-
-
 @register.filter("smart_truncate")
 def smart_truncate(content, length=100, suffix='...'):
     if len(content) <= length:


Test patch:
diff --git a/akvo/rsr/tests/pages/test_widgets.py b/akvo/rsr/tests/pages/test_widgets.py
--- a/akvo/rsr/tests/pages/test_widgets.py
+++ b/akvo/rsr/tests/pages/test_widgets.py
@@ -6,21 +6,25 @@
 For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
 """
 
-from django.conf import settings
-from django.test import Client, TestCase
-from akvo.rsr.models import Project, Organisation
+from akvo.rsr.models import Organisation, Partnership, Project, ProjectUpdate
+from akvo.rsr.tests.base import BaseTestCase
 from ..utils import contains_template_errors
 
 
-class PingWidgetsTest(TestCase):
+class PingWidgetsTest(BaseTestCase):
 
     """Simple ping."""
 
     def setUp(self):
         """Setup."""
-        self.c = Client(HTTP_HOST=settings.RSR_DOMAIN)
-        Project.objects.create(title="Test Project")
-        Organisation.objects.create(name="Partner1")
+        super(PingWidgetsTest, self).setUp()
+        project = Project.objects.create(title="Test Project")
+        project.publishingstatus.status = 'published'
+        project.publishingstatus.save()
+        organisation = Organisation.objects.create(name="Partner1")
+        user = self.create_user('foo@example.com')
+        Partnership.objects.create(project=project, organisation=organisation)
+        ProjectUpdate.objects.create(project=project, title='Project Update', user=user)
 
     def test_narrow(self):
         """Ping /widgets/project-narrow."""
Repository: akvo/akvo-rsr

Issue:
New User Registration is broken



Discussion:

Resolving patch:
diff --git a/akvo/rsr/forms.py b/akvo/rsr/forms.py
--- a/akvo/rsr/forms.py
+++ b/akvo/rsr/forms.py
@@ -153,26 +153,22 @@ def clean_password2(self):
         return password2
 
     def save(self, request):
-        """
-        Create the new User and RegistrationProfile, and returns the User.
+        """Create the new user and RegistrationProfile, and returns the user."""
+
+        User = get_user_model()
+        username = email = self.cleaned_data['email']
+        password = self.cleaned_data['password1']
+        first_name = self.cleaned_data['first_name']
+        last_name = self.cleaned_data['last_name']
+        user = User.objects.create_user(
+            username, email, password, first_name=first_name, last_name=last_name
+        )
 
-        This is essentially a light wrapper around
-        RegistrationProfile.objects.create_inactive_user(), feeding it the form data and
-        a profile callback (see the documentation on create_inactive_user() for details)
-        if supplied. Modified to set user.is_active = False and add User object creation.
-        """
+        registration_profile = RegistrationProfile.objects.create_profile(user)
         site = get_current_site(request)
-        new_user = RegistrationProfile.objects.create_inactive_user(
-            username=self.cleaned_data['email'],
-            email=self.cleaned_data['email'],
-            password=self.cleaned_data['password1'],
-            site=site,
-        )
-        new_user.first_name = self.cleaned_data['first_name']
-        new_user.last_name = self.cleaned_data['last_name']
-        new_user.is_active = False
-        new_user.save()
-        return new_user
+        registration_profile.send_activation_email(site)
+
+        return user
 
 
 class ProfileForm(forms.Form):


Test patch:
diff --git a/akvo/rsr/tests/views/test_account.py b/akvo/rsr/tests/views/test_account.py
--- a/akvo/rsr/tests/views/test_account.py
+++ b/akvo/rsr/tests/views/test_account.py
@@ -174,13 +174,14 @@ def _create_registration_data(self, password1, password2=None):
 
     def test_registration_without_honeypot_filled_in(self):
         # Given
-        self._create_registration_data('passwordA1$')
+        self._create_registration_data(self.password)
 
         # When
         response = self.c.post('/en/register/', data=self.data)
 
         # Then
         self.assertEqual(response.status_code, 200)
+        self.assertIn('confirmation will be sent to you via email', response.content)
 
     def test_registration_password_too_short(self):
         # Given
Repository: akvo/akvo-rsr

Issue:
Creating new organisations from the project editor fails



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/organisation.py b/akvo/rest/views/organisation.py
--- a/akvo/rest/views/organisation.py
+++ b/akvo/rest/views/organisation.py
@@ -9,8 +9,8 @@
 from django.utils import six
 from rest_framework.decorators import api_view
 from rest_framework.exceptions import ParseError
-from rest_framework.parsers import JSONParser
 from rest_framework.response import Response
+from rest_framework.settings import api_settings
 from rest_framework_xml.parsers import XMLParser
 from rest_framework_xml.compat import etree
 
@@ -74,7 +74,7 @@ class OrganisationViewSet(BaseRSRViewSet):
     """
     queryset = Organisation.objects.all()
     serializer_class = OrganisationSerializer
-    parser_classes = (AkvoOrganisationParser, JSONParser,)
+    parser_classes = [AkvoOrganisationParser] + api_settings.DEFAULT_PARSER_CLASSES
 
 
 @api_view(['GET'])


Test patch:
diff --git a/akvo/rsr/tests/rest/test_project_editor.py b/akvo/rsr/tests/rest/test_project_editor.py
--- a/akvo/rsr/tests/rest/test_project_editor.py
+++ b/akvo/rsr/tests/rest/test_project_editor.py
@@ -8,6 +8,7 @@
 """
 import datetime
 from tempfile import NamedTemporaryFile
+from urllib import urlencode
 
 from django.conf import settings
 from django.contrib.auth.models import Group
@@ -1015,3 +1016,34 @@ def test_creating_project_attirbute_hierarchy(self):
             self.assertEqual(2, len(change))
             attributes = 5 if isinstance(change[0], Indicator) else 4
             self.assertEqual(attributes, len(change[1]))
+
+
+class CreateNewOrganisationTestCase(TestCase):
+
+    def setUp(self):
+        super(CreateNewOrganisationTestCase, self).setUp()
+        self.user, self.username, self.password = create_user()
+        self.org = Organisation.objects.create(name='Akvo', long_name='Akvo')
+        Employment.objects.create(
+            user=self.user,
+            organisation=self.org,
+            group=Group.objects.get(name='Admins'),
+            is_approved=True,
+        )
+        self.c = Client(HTTP_HOST=settings.RSR_DOMAIN)
+
+    def test_create_new_organisation(self):
+        # Given
+        self.c.login(username=self.username, password=self.password)
+        url = '/rest/v1/organisation/?format=json'
+        content_type = 'application/x-www-form-urlencoded'
+        data = {'name': 'Test Org', 'long_name': 'Test Organisation'}
+
+        # When
+        response = self.c.post(url, data=urlencode(data), content_type=content_type)
+
+        # Then
+        self.assertTrue(response.status_code, 201)
+        self.assertIn('id', response.data)
+        for key in data:
+            self.assertEqual(response.data[key], data[key])