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

Issue:
pytest is causing error in Jenkins
Example:

https://jenkins.preferred.jp/job/chainer/job/chainer_pr/2162/TEST=CHAINERX_chainer-py3,label=mn1-p100/console

```
14:33:27 + pytest -rfEX --showlocals -m 'not slow and not ideep' /repo/tests/chainer_tests
14:33:28 Traceback (most recent call last):
14:33:28   File "/workspace/conda/envs/testenv/bin/pytest", line 10, in <module>
14:33:28     sys.exit(main())
14:33:28   File "/workspace/conda/envs/testenv/lib/python3.6/site-packages/_pytest/config/__init__.py", line 61, in main
14:33:28     config = _prepareconfig(args, plugins)
14:33:28   File "/workspace/conda/envs/testenv/lib/python3.6/site-packages/_pytest/config/__init__.py", line 182, in _prepareconfig
14:33:28     config = get_config()
14:33:28   File "/workspace/conda/envs/testenv/lib/python3.6/site-packages/_pytest/config/__init__.py", line 156, in get_config
14:33:28     pluginmanager.import_plugin(spec)
14:33:28   File "/workspace/conda/envs/testenv/lib/python3.6/site-packages/_pytest/config/__init__.py", line 530, in import_plugin
14:33:28     __import__(importspec)
14:33:28   File "/workspace/conda/envs/testenv/lib/python3.6/site-packages/_pytest/tmpdir.py", line 25, in <module>
14:33:28     class TempPathFactory(object):
14:33:28   File "/workspace/conda/envs/testenv/lib/python3.6/site-packages/_pytest/tmpdir.py", line 35, in TempPathFactory
14:33:28     lambda p: Path(os.path.abspath(six.text_type(p)))
14:33:28 TypeError: attrib() got an unexpected keyword argument 'convert'
```


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -45,6 +45,7 @@
     ],
     'test': [
         'pytest<4.2.0',  # 4.2.0 is slow collecting tests and times out on CI.
+        'attrs<19.2.0',  # pytest 4.1.1 does not run with attrs==19.2.0
         'mock',
     ],
     'doctest': [


Test patch:
Repository: chainer/chainer

Issue:
Adding a usage example to NStepLSTM.
Adding an example would make NStepLSTM easier to understand.


Discussion:

Resolving patch:
diff --git a/chainer/links/rnn/n_step_lstm.py b/chainer/links/rnn/n_step_lstm.py
--- a/chainer/links/rnn/n_step_lstm.py
+++ b/chainer/links/rnn/n_step_lstm.py
@@ -89,6 +89,41 @@ class NStepLSTM(NStepLSTMBase):
     .. seealso::
         :func:`chainer.functions.n_step_lstm`
 
+    .. admonition:: Example
+
+        *Read* :meth:`forward` *method below first.*
+
+        >>> dropout_ratio = 0.0
+        >>> in_size, seq_len, n_layers, out_size = 2, 4, 2, 3
+        >>> batch = 5
+        >>> xs = [
+        ...     Variable(np.random.rand(seq_len, in_size).astype(np.float32))
+        ...     for i in range(batch)]
+        >>> [x.shape for x in xs]
+        [(4, 2), (4, 2), (4, 2), (4, 2), (4, 2)]
+        >>> lstm = L.NStepLSTM(n_layers, in_size, out_size, dropout_ratio)
+
+        Without hidden or cell state:
+
+        >>> hy, cy, ys = lstm(None, None, xs)
+        >>> hy.shape  # shape should be (n_layers, batch, out_size)
+        (2, 5, 3)
+        >>> ys[0].shape  # should be (seq_len, out_size)
+        (4, 3)
+        >>> len(ys)  # should be equal to batch
+        5
+
+        With hidden and cell states:
+
+        >>> h_shape = (n_layers, batch, out_size)
+        >>> hx = Variable(np.ones(h_shape, np.float32))
+        >>> cx = Variable(np.ones(h_shape, np.float32))
+        >>> hy, cy, ys = lstm(hx, cx, xs)
+        >>> hy.shape  # shape should be (n_layers, batch, out_size)
+        (2, 5, 3)
+        >>> ys[0].shape  # should be (seq_len, out_size)
+        (4, 3)
+
     """
 
     use_bi_direction = False
diff --git a/chainer/links/rnn/n_step_rnn.py b/chainer/links/rnn/n_step_rnn.py
--- a/chainer/links/rnn/n_step_rnn.py
+++ b/chainer/links/rnn/n_step_rnn.py
@@ -143,7 +143,7 @@ def forward(self, hx, xs, **kwargs):
                 the hidden units.
             xs (list of :class:`~chainer.Variable`): List of input sequences.
                 Each element ``xs[i]`` is a :class:`chainer.Variable` holding
-                a sequence. Its shape is ``(L_i, I)``, where ``L_t`` is the
+                a sequence. Its shape is ``(L_i, I)``, where ``L_i`` is the
                 length of a sequence for batch ``i``, and ``I`` is the size of
                 the input and is equal to ``in_size``.
 
@@ -156,7 +156,7 @@ def forward(self, hx, xs, **kwargs):
               ``ys[i]`` holds hidden states of the last layer corresponding
               to an input ``xs[i]``. Its shape is ``(L_i, N)`` for
               uni-directional RNN and ``(L_i, 2N)`` for bi-directional RNN
-              where ``L_t`` is the length of a sequence for batch ``i``,
+              where ``L_i`` is the length of a sequence for batch ``i``,
               and ``N`` is size of hidden units.
         """
         (hy,), ys = self._call([hx], xs, **kwargs)


Test patch:
Repository: techmatters/terraso-backend

Issue:
Add photo field to the User model
## Description
The user profile photo might be automatically fetched from the third-party account system (Google or Apple), or it can also be uploaded from by the user. Since the file itself might be stored on an external storage service, this field will be used to store the location of the file.

In this issue, it's important to consider the flow front-end → back-end for photo upload.

## Suggested subtasks
- [ ] Design the overall flow to upload photo considering front-end → back-end flow
- [ ] Add the new field on model with proper support to the external storage service (upload) and update DB migrations
- [ ] Implement upload feature to update photo
- [ ] Add support to present the proper photo URL from external services
- [ ] Add the new photo field on user API

This issue depends on:
- #21 


Discussion:

Resolving patch:
diff --git a/terraso_backend/apps/graphql/schema/users.py b/terraso_backend/apps/graphql/schema/users.py
--- a/terraso_backend/apps/graphql/schema/users.py
+++ b/terraso_backend/apps/graphql/schema/users.py
@@ -17,7 +17,7 @@ class Meta:
             "first_name": ["icontains"],
             "last_name": ["icontains"],
         }
-        fields = ("email", "first_name", "last_name", "memberships")
+        fields = ("email", "first_name", "last_name", "profile_image", "memberships")
         interfaces = (relay.Node,)
 
 


Test patch:
diff --git a/terraso_backend/tests/graphql/test_core_request.py b/terraso_backend/tests/graphql/test_core_request.py
--- a/terraso_backend/tests/graphql/test_core_request.py
+++ b/terraso_backend/tests/graphql/test_core_request.py
@@ -144,6 +144,7 @@ def test_users_query(client_query, users):
                 edges {
                     node {
                         email
+                        profileImage
                     }
                 }
             }
@@ -151,6 +152,8 @@ def test_users_query(client_query, users):
         """
     )
     edges = response.json()["data"]["users"]["edges"]
-    users_result = [edge["node"]["email"] for edge in edges]
+    users_result_nodes = [edge["node"] for edge in edges]
     for user in users:
-        assert user.email in users_result
+        user_node = next(item for item in users_result_nodes if item["email"] == user.email)
+        assert user_node
+        assert user.profile_image == user_node["profileImage"]
Repository: techmatters/terraso-backend

Issue:
Update structlog configuration to fix structlog.threadlocal deprecation warning
## Description
The new version of structlog deprecates structlog.threadlocal and generates this warning

```
terraso_backend/config/settings.py:183
  /app/terraso_backend/config/settings.py:183: DeprecationWarning: `structlog.threadlocal` is deprecated, please use `structlog.contextvars` instead.
    context_class=structlog.threadlocal.wrap_dict(dict),
```


Discussion:
References:

- [structlog docs](https://www.structlog.org/en/stable/contextvars.html)

Seems like a simple swap is all that's needed here.

Resolving patch:
diff --git a/terraso_backend/config/settings.py b/terraso_backend/config/settings.py
--- a/terraso_backend/config/settings.py
+++ b/terraso_backend/config/settings.py
@@ -182,7 +182,6 @@
         structlog.processors.UnicodeDecoder(),
         structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
     ],
-    context_class=structlog.threadlocal.wrap_dict(dict),
     logger_factory=structlog.stdlib.LoggerFactory(),
     wrapper_class=structlog.stdlib.BoundLogger,
     cache_logger_on_first_use=True,


Test patch:
Repository: techmatters/terraso-backend

Issue:
Description field limited to 512 characters
## Description
The description field is limited to 512 characters. This is too short for many of our sample descriptions:

<img width="843" alt="image" src="https://user-images.githubusercontent.com/86784/212425780-a9eb7efd-6942-47c6-9bbd-66b42aa8aee0.png">



Discussion:

Resolving patch:
diff --git a/terraso_backend/apps/core/models/groups.py b/terraso_backend/apps/core/models/groups.py
--- a/terraso_backend/apps/core/models/groups.py
+++ b/terraso_backend/apps/core/models/groups.py
@@ -35,7 +35,7 @@ class Group(SlugModel):
     fields_to_trim = ["name", "description"]
 
     name = models.CharField(max_length=128, validators=[validate_name])
-    description = models.TextField(max_length=512, blank=True, default="")
+    description = models.TextField(max_length=2048, blank=True, default="")
     website = models.URLField(blank=True, default="")
     email = models.EmailField(blank=True, default="")
 
diff --git a/terraso_backend/apps/shared_data/migrations/0010_alter_dataentry_created_by_and_more.py b/terraso_backend/apps/shared_data/migrations/0010_alter_dataentry_created_by_and_more.py
new file mode 100644
--- /dev/null
+++ b/terraso_backend/apps/shared_data/migrations/0010_alter_dataentry_created_by_and_more.py
@@ -0,0 +1,35 @@
+# Generated by Django 4.1.5 on 2023-01-13 21:53
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+        ("shared_data", "0009_alter_dataentry_resource_type"),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name="dataentry",
+            name="created_by",
+            field=models.ForeignKey(
+                null=True,
+                on_delete=django.db.models.deletion.DO_NOTHING,
+                to=settings.AUTH_USER_MODEL,
+            ),
+        ),
+        migrations.AlterField(
+            model_name="dataentry",
+            name="deleted_at",
+            field=models.DateTimeField(db_index=True, editable=False, null=True),
+        ),
+        migrations.AlterField(
+            model_name="visualizationconfig",
+            name="deleted_at",
+            field=models.DateTimeField(db_index=True, editable=False, null=True),
+        ),
+    ]


Test patch:
Repository: techmatters/terraso-backend

Issue:
feat: Handle error for SSO signup if user does not have email set
## Description

With Google and Apple SSO it seems we have a guarantee that the user will have their email set. This is good for us; the email is a required column in our user table. However, with Microsoft it seems like we do not have this guarantee, which causes us to display an ugly error message in the case where the user does not have an email defined. There are several ways we could handle this:

1) Display an error message that instructs the user to set their email. This is definitely less user friendly, but may be easier to implement.

2) Allow the user to set their email interactively. This is what is done, for example, with Kobo. The idea here would be to set up a signup page as the final signup step. This page would be pre-populated with whatever content we get from Microsoft, but it will allow the user to manually set their email if it is not present.

Any other options you see?



Discussion:
Note: we are just going to do the first option and display an error message to the user.

Resolving patch:
diff --git a/terraso_backend/apps/auth/services.py b/terraso_backend/apps/auth/services.py
--- a/terraso_backend/apps/auth/services.py
+++ b/terraso_backend/apps/auth/services.py
@@ -77,6 +77,10 @@ def sign_up_with_microsoft(self, authorization_code):
         )
 
     def _persist_user(self, email, first_name="", last_name="", profile_image_url=None):
+        if not email:
+            # it is possible for the email not to be set, notably with Microsoft
+            # here throw a more descriptive error message
+            raise ValueError("Could not create account, user email is empty")
         user, created = User.objects.get_or_create(email=email)
 
         self._update_profile_image(user, profile_image_url)


Test patch:
Repository: techmatters/terraso-backend

Issue:
On landscape model, "taxonomy terms" is a required field for Django admin
## Description
On landscape model, "taxonomy terms" is a required field for Django admin. It should be an optional field.


Discussion:

Resolving patch:
diff --git a/terraso_backend/apps/core/migrations/0043_landscapedefaultgroup_alter_group_deleted_at_and_more.py b/terraso_backend/apps/core/migrations/0043_landscapedefaultgroup_alter_group_deleted_at_and_more.py
new file mode 100644
--- /dev/null
+++ b/terraso_backend/apps/core/migrations/0043_landscapedefaultgroup_alter_group_deleted_at_and_more.py
@@ -0,0 +1,36 @@
+# Copyright © 2023 Technology Matters
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see https://www.gnu.org/licenses/.
+
+# Generated by Django 4.2.1 on 2023-05-18 16:24
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import apps.core.models.commons
+
+
+class Migration(migrations.Migration):
+    dependencies = [
+        ("core", "0042_landscapedefaultgroup_group_enroll_method_and_more"),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name="landscape",
+            name="taxonomy_terms",
+            field=models.ManyToManyField(blank=True, to="core.taxonomyterm"),
+        ),
+    ]
diff --git a/terraso_backend/apps/core/models/landscapes.py b/terraso_backend/apps/core/models/landscapes.py
--- a/terraso_backend/apps/core/models/landscapes.py
+++ b/terraso_backend/apps/core/models/landscapes.py
@@ -65,7 +65,7 @@ class Landscape(SlugModel, DirtyFieldsMixin):
     groups = models.ManyToManyField(Group, through="LandscapeGroup")
 
     area_types = models.JSONField(blank=True, null=True)
-    taxonomy_terms = models.ManyToManyField(TaxonomyTerm)
+    taxonomy_terms = models.ManyToManyField(TaxonomyTerm, blank=True)
     population = models.IntegerField(blank=True, null=True)
 
     PARTNERSHIP_STATUS_NONE = ""


Test patch:
Repository: techmatters/terraso-backend

Issue:
Set up Google iOS login on backend



Discussion:

Resolving patch:
diff --git a/terraso_backend/config/settings.py b/terraso_backend/config/settings.py
--- a/terraso_backend/config/settings.py
+++ b/terraso_backend/config/settings.py
@@ -382,10 +382,14 @@ class JWTProvider(TypedDict):
 
 
 JWT_EXCHANGE_PROVIDERS: dict[str, JWTProvider] = {
-    "google": dict(
+    "google-android": dict(
         url="https://www.googleapis.com/oauth2/v3/certs",
-        client_id=config("GOOGLE_MOBILE_CLIENT_ID", default=""),
-    )
+        client_id=config("GOOGLE_ANDROID_CLIENT_ID", default=""),
+    ),
+    "google-ios": dict(
+        url="https://www.googleapis.com/oauth2/v3/certs",
+        client_id=config("GOOGLE_IOS_CLIENT_ID", default=""),
+    ),
 }
 
 


Test patch:
Repository: techmatters/terraso-backend

Issue:
harddelete fails with AttributeError: 'NoneType' object has no attribute 'delete'
## Description
The `harddelete` command fails with this backtrace:
```
Aug 5 12:01:39 AM  {"extra": {"landscape_id": "UUID('8483fbd9-307a-4b1f-a6f2-2eafaf6526b9')"}, "event": "Landscape has no default group, but it must have", "timestamp": "2023-08-05T04:01:39.275313Z", "logger": "apps.core.models.landscapes", "level": "error"}
Aug 5 12:01:39 AM  Traceback (most recent call last):
Aug 5 12:01:39 AM    File "/app/terraso_backend/manage.py", line 34, in <module>
Aug 5 12:01:39 AM      main()
Aug 5 12:01:39 AM    File "/app/terraso_backend/manage.py", line 30, in main
Aug 5 12:01:39 AM      execute_from_command_line(sys.argv)
Aug 5 12:01:39 AM    File "/home/terraso/.local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
Aug 5 12:01:39 AM      utility.execute()
Aug 5 12:01:39 AM    File "/home/terraso/.local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute
Aug 5 12:01:39 AM      self.fetch_command(subcommand).run_from_argv(self.argv)
Aug 5 12:01:39 AM    File "/home/terraso/.local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv
Aug 5 12:01:39 AM      self.execute(*args, **cmd_options)
Aug 5 12:01:39 AM    File "/home/terraso/.local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute
Aug 5 12:01:39 AM      output = self.handle(*args, **options)
Aug 5 12:01:39 AM               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Aug 5 12:01:39 AM    File "/app/terraso_backend/apps/core/management/commands/harddelete.py", line 62, in handle
Aug 5 12:01:39 AM      obj.delete(force_policy=HARD_DELETE)
Aug 5 12:01:39 AM    File "/app/terraso_backend/apps/core/models/landscapes.py", line 129, in delete
Aug 5 12:01:39 AM      default_group.delete()
Aug 5 12:01:39 AM      ^^^^^^^^^^^^^^^^^^^^
Aug 5 12:01:39 AM  AttributeError: 'NoneType' object has no attribute 'delete'
```


Discussion:

Resolving patch:
diff --git a/terraso_backend/apps/core/models/landscapes.py b/terraso_backend/apps/core/models/landscapes.py
--- a/terraso_backend/apps/core/models/landscapes.py
+++ b/terraso_backend/apps/core/models/landscapes.py
@@ -126,7 +126,8 @@ def delete(self, *args, **kwargs):
         with transaction.atomic():
             ret = super().delete(*args, **kwargs)
             # default group should be deleted as well
-            default_group.delete()
+            if default_group is not None:
+                default_group.delete()
 
         return ret
 


Test patch:
Repository: techmatters/terraso-backend

Issue:
RuntimeWarning: DateTimeField Log.client_timestamp received a naive datetime
## Description
When running `make test`, many warnings of this form are observed:
```
  /home/terraso/.local/lib/python3.11/site-packages/django/db/models/fields/__init__.py:1595: RuntimeWarning: DateTimeField Log.client_timestamp received a naive datetime (2023-07-11 22:39:48.700825) while time zone support is active.
    warnings.warn(
```


Discussion:

Resolving patch:
diff --git a/terraso_backend/apps/audit_logs/services.py b/terraso_backend/apps/audit_logs/services.py
--- a/terraso_backend/apps/audit_logs/services.py
+++ b/terraso_backend/apps/audit_logs/services.py
@@ -2,6 +2,7 @@
 from datetime import datetime
 from enum import Enum
 
+from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 from django.core.paginator import Paginator
 from django.db import transaction
@@ -79,7 +80,12 @@ def log(
 
             if client_time is None:
                 client_time = datetime.now()
-            log.client_timestamp = client_time
+            if settings.USE_TZ:
+                from django.utils.timezone import make_aware
+
+                log.client_timestamp = make_aware(client_time)
+            else:
+                log.client_timestamp = client_time
 
             log.metadata = metadata
             log.save()


Test patch:
Repository: techmatters/terraso-backend

Issue:
Data validation for empty and too long project titles



Discussion:

Resolving patch:
diff --git a/terraso_backend/apps/project_management/migrations/0020_alter_project_name.py b/terraso_backend/apps/project_management/migrations/0020_alter_project_name.py
new file mode 100644
--- /dev/null
+++ b/terraso_backend/apps/project_management/migrations/0020_alter_project_name.py
@@ -0,0 +1,32 @@
+# Copyright © 2023 Technology Matters
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see https://www.gnu.org/licenses/.
+
+# Generated by Django 4.2.6 on 2023-10-16 18:22
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+    dependencies = [
+        ("project_management", "0019_project_seen_by_site_seen_by"),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name="project",
+            name="name",
+            field=models.CharField(max_length=120),
+        ),
+    ]
diff --git a/terraso_backend/apps/project_management/models/projects.py b/terraso_backend/apps/project_management/models/projects.py
--- a/terraso_backend/apps/project_management/models/projects.py
+++ b/terraso_backend/apps/project_management/models/projects.py
@@ -68,7 +68,7 @@ class Meta(BaseModel.Meta):
 
     PRIVACY_STATUS = ((PRIVATE, _("Private")), (PUBLIC, _("Public")))
 
-    name = models.CharField(max_length=200)
+    name = models.CharField(max_length=120)
     description = models.CharField(max_length=512, default="", blank=True)
     membership_list = models.OneToOneField(ProjectMembershipList, on_delete=models.CASCADE)
     privacy = models.CharField(


Test patch:
Repository: techmatters/terraso-backend

Issue:
Add ability to change user password from Django admin
## Description
Add ability to change user password from Django admin.


Discussion:

Resolving patch:
diff --git a/terraso_backend/apps/core/admin.py b/terraso_backend/apps/core/admin.py
--- a/terraso_backend/apps/core/admin.py
+++ b/terraso_backend/apps/core/admin.py
@@ -14,6 +14,7 @@
 # along with this program. If not, see https://www.gnu.org/licenses/.
 
 from django.contrib import admin
+from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
 
 from .models import (
     Group,
@@ -57,9 +58,28 @@ class UserPreferenceInline(admin.TabularInline):
 
 
 @admin.register(User)
-class UserAdmin(admin.ModelAdmin):
+class UserAdmin(DjangoUserAdmin):
+    ordering = ("email",)
     list_display = ("email", "first_name", "last_name", "created_at", "is_staff")
+    search_fields = ("email", "first_name", "last_name")
     inlines = [UserPreferenceInline]
+    fieldsets = (
+        (None, {"fields": ("email", "password")}),
+        ("Personal info", {"fields": ("first_name", "last_name")}),
+        (
+            "Permissions",
+            {
+                "fields": (
+                    "is_active",
+                    "is_staff",
+                    "is_superuser",
+                    "groups",
+                    "user_permissions",
+                ),
+            },
+        ),
+        ("Important dates", {"fields": ("last_login", "date_joined")}),
+    )
 
 
 @admin.register(TaxonomyTerm)


Test patch: