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

Issue:
Timezone email
Format dates in emails in the same language as the email template (Norwegian), and converted to the proper timezone. 

![image](https://user-images.githubusercontent.com/1467188/34150647-476ffb12-e4a9-11e7-9f17-5b83e0690dad.png)

![screenshot 19 des 1 2017 10_39_27](https://user-images.githubusercontent.com/1467188/34150870-f9c33536-e4a9-11e7-836e-a3e93ae27f0f.png)




Discussion:

Resolving patch:
diff --git a/lego/apps/events/notifications.py b/lego/apps/events/notifications.py
--- a/lego/apps/events/notifications.py
+++ b/lego/apps/events/notifications.py
@@ -1,3 +1,7 @@
+from django.utils import timezone
+
+import pytz
+
 from lego.apps.notifications.constants import (
     EVENT_ADMIN_REGISTRATION,
     EVENT_ADMIN_UNREGISTRATION,
@@ -40,12 +44,18 @@ class EventPaymentOverdueNotification(Notification):
     def generate_mail(self):
         event = self.kwargs["event"]
 
+        date = timezone.localtime(
+            value=event.payment_due_date, timezone=pytz.timezone("Europe/Oslo")
+        )
+
+        due_date = date.strftime("%d.%m.%y, kl. %H:%M")
+
         return self._delay_mail(
             to_email=self.user.email,
             context={
                 "event": event.title,
                 "name": self.user.full_name,
-                "due_date": event.payment_due_date,
+                "due_date": due_date,
                 "id": event.id,
             },
             subject=f"Du har ikke betalt påmeldingen på arrangementet {event.title}",


Test patch:
Repository: webkom/lego

Issue:
Emails should contain a link to edit email preferences
Should be to just add a link to the base email template, as well as add a link to mails sent by restricted.


Discussion:

Resolving patch:
diff --git a/lego/apps/restricted/message_processor.py b/lego/apps/restricted/message_processor.py
--- a/lego/apps/restricted/message_processor.py
+++ b/lego/apps/restricted/message_processor.py
@@ -149,6 +149,9 @@ def decorate(message, hide_sender, sender):
             )
         else:
             footer.append("Opprinnelig avsender har valgt å skjule sin adresse.")
+        footer.append(
+            f"Meld deg av her: {settings.FRONTEND_URL}/users/me/settings/notifications"
+        )
 
         footer = "\n".join(footer)
         charset = message.get_content_charset() or "us-ascii"


Test patch:
Repository: webkom/lego

Issue:
Allow more characters for the allergies field
Like it is now, one can not have more than 100 characters in the allergies field for a user (the field in question is found in settings on the profile for a user on abakus.no). It turns out that some users need more space than this to be able to fit all their allergies, so we need to expand the limitation on this field. 

Tip: The validation for this field is done backend. A good start could be to search for "allergies" and see what you find then:)


Discussion:

Resolving patch:
diff --git a/lego/apps/users/migrations/0029_auto_20210921_1835.py b/lego/apps/users/migrations/0029_auto_20210921_1835.py
new file mode 100644
--- /dev/null
+++ b/lego/apps/users/migrations/0029_auto_20210921_1835.py
@@ -0,0 +1,20 @@
+# Generated by Django 2.2.24 on 2021-09-21 18:35
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ("users", "0028_auto_20210523_1252"),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name="user",
+            name="allergies",
+            field=models.CharField(
+                blank=True, max_length=500, verbose_name="allergies"
+            ),
+        ),
+    ]
diff --git a/lego/apps/users/models.py b/lego/apps/users/models.py
--- a/lego/apps/users/models.py
+++ b/lego/apps/users/models.py
@@ -327,7 +327,7 @@ class User(
     )
     first_name = models.CharField("first name", max_length=50, blank=False)
     last_name = models.CharField("last name", max_length=30, blank=False)
-    allergies = models.CharField("allergies", max_length=100, blank=True)
+    allergies = models.CharField("allergies", max_length=500, blank=True)
     selected_theme = models.CharField(
         "selected theme",
         max_length=50,


Test patch:
Repository: webkom/lego

Issue:
Phone number not saved from registration form
When creating a new user, LEGO ignores the phone number inserted into the registration form.


Discussion:
I have take a look at the users registrations (is this?)

(https://github.com/webkom/lego/blob/master/lego/apps/users/registrations.pyl)

but I can't find any mention to the phone number.

Resolving patch:
diff --git a/lego/apps/users/serializers/registration.py b/lego/apps/users/serializers/registration.py
--- a/lego/apps/users/serializers/registration.py
+++ b/lego/apps/users/serializers/registration.py
@@ -41,4 +41,5 @@ class Meta:
             "gender",
             "password",
             "allergies",
+            "phone_number",
         )


Test patch:
Repository: webkom/lego

Issue:
RestrictedMail notification
> Restricted mail is used when sending mails to multiple users at once by selecting users/events/meetings, and then send the email to <restricted@abkaus.no> together with the token.

The `restricted mail sent` should be sent to the proper email, not the `user.email` field. The address `user.email_address` should be used instead.

If the `from_address` is not the same as the `user.email_address`, both should receive the mail.

https://github.com/webkom/lego/blob/ccab14fbee223f16842ace6ca2ba0c2f3ac3ac86/lego/apps/restricted/notifications.py#L9


Discussion:

Resolving patch:
diff --git a/lego/apps/restricted/notifications.py b/lego/apps/restricted/notifications.py
--- a/lego/apps/restricted/notifications.py
+++ b/lego/apps/restricted/notifications.py
@@ -8,7 +8,7 @@ class RestrictedMailSentNotification(Notification):
 
     def generate_mail(self):
         return self._delay_mail(
-            to_email=self.user.email,
+            to_email=self.user.email.address,
             context={"first_name": self.user.first_name},
             subject="Begrenset epost sendt ut",
             plain_template="restricted/email/process_success.txt",
diff --git a/lego/apps/restricted/serializers.py b/lego/apps/restricted/serializers.py
--- a/lego/apps/restricted/serializers.py
+++ b/lego/apps/restricted/serializers.py
@@ -1,3 +1,7 @@
+from functools import reduce
+
+from rest_framework import exceptions
+
 from lego.apps.events.fields import PublicEventListField
 from lego.apps.meetings.fields import MeetingListField
 from lego.apps.restricted.models import RestrictedMail
@@ -28,6 +32,18 @@ class Meta(RestrictedMailListSerializer.Meta):
             "hide_sender",
         )
 
+    def create(self, validated_data):
+        groups = validated_data["groups"]
+        events = validated_data["events"]
+        MaxPermittedAmout = 500
+        num = reduce((lambda a, b: a + b.number_of_users), groups, 0)
+        num += reduce((lambda a, b: a + b.registration_count), events, 0)
+        if num > MaxPermittedAmout:
+            raise exceptions.ValidationError(
+                f"The number of students in selected groups/events exceed the permitted amount which is {MaxPermittedAmout}"
+            )
+        return super().create(validated_data)
+
 
 class RestrictedMailDetailSerializer(RestrictedMailSerializer):
     users = PublicUserListField({"read_only": True})


Test patch:
Repository: webkom/lego

Issue:
Stripe payments should link to user ID
At the moment, registrations are selected using the event id and the user email. Since users can change their email address, this association is not stable. We should instead select the registration using the user id, as this is already stored in the payment metadata.


Sentry Issue: [LEGO-AP](https://sentry.io/organizations/abakus/issues/3330779750/?referrer=github_integration)

```
WebhookDidNotFindRegistration: Stripe webhook with ID: evt_3Kxqk6LWnPJjOd3f0zPgIQSx for event 3122 tried getting registration for user <REDACTED>, but did not find any!
  File "celery/app/trace.py", line 734, in __protected_call__
    return self.run(*args, **kwargs)
  File "lego/apps/events/tasks.py", line 437, in stripe_webhook_event
    raise WebhookDidNotFindRegistration(event_id, metadata)
```


Discussion:

Resolving patch:
diff --git a/lego/apps/events/serializers/registrations.py b/lego/apps/events/serializers/registrations.py
--- a/lego/apps/events/serializers/registrations.py
+++ b/lego/apps/events/serializers/registrations.py
@@ -161,6 +161,7 @@ class RegistrationReadDetailedExportSerializer(RegistrationReadDetailedSerialize
 
 class StripeMetaSerializer(serializers.Serializer):
     EVENT_ID = serializers.IntegerField()
+    USER_ID = serializers.IntegerField()
     USER = serializers.CharField()
     EMAIL = serializers.EmailField()
 
diff --git a/lego/apps/events/tasks.py b/lego/apps/events/tasks.py
--- a/lego/apps/events/tasks.py
+++ b/lego/apps/events/tasks.py
@@ -395,7 +395,7 @@ def stripe_webhook_event(self, event_id, event_type, logger_context=None):
 
         metadata = serializer.data["metadata"]
         registration = Registration.objects.filter(
-            event_id=metadata["EVENT_ID"], user__email=metadata["EMAIL"]
+            event_id=metadata["EVENT_ID"], user__id=metadata["USER_ID"]
         ).first()
         if not registration:
             log.error("stripe_webhook_error", event_id=event_id, metadata=metadata)
@@ -430,7 +430,7 @@ def stripe_webhook_event(self, event_id, event_type, logger_context=None):
 
         metadata = serializer.data["metadata"]
         registration = Registration.objects.filter(
-            event_id=metadata["EVENT_ID"], user__email=metadata["EMAIL"]
+            event_id=metadata["EVENT_ID"], user__id=metadata["USER_ID"]
         ).first()
         if not registration:
             log.error("stripe_webhook_error", event_id=event_id, metadata=metadata)


Test patch:
Repository: webkom/lego

Issue:
Migrate from CAPTCHA to Turnstile
Turnstile
* is not from *Google*.
* doesn't force users to help train Google's car AI.
* easy (?) to [migrate to](https://developers.cloudflare.com/turnstile/get-started/migrating-from-recaptcha/).
* solves the stupid issue with showing captchas so early they expire (Bc. a Turnstile token is valid for 300 seconds).

Closes #2291 


Discussion:
Another alternative is also to use hCaptcha, which is very widely used and tested. https://www.hcaptcha.com/

It _does_ help train AIs as well, just not for a single entity, but anyone can use the results.

_And you donate to charity by using it_
HCaptcha is fine, but it has the same horrible ux when it thinks you're a bot or adblocker trips it up. 

Resolving patch:
diff --git a/lego/settings/base.py b/lego/settings/base.py
--- a/lego/settings/base.py
+++ b/lego/settings/base.py
@@ -174,7 +174,7 @@
 
 LDAP_BASE_DN = "dc=abakus,dc=no"
 
-CAPTCHA_URL = "https://www.google.com/recaptcha/api/siteverify"
+CAPTCHA_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
 
 PUSH_NOTIFICATIONS_SETTINGS = {
     "APNS_USE_SANDBOX": False,
diff --git a/lego/settings/development.py b/lego/settings/development.py
--- a/lego/settings/development.py
+++ b/lego/settings/development.py
@@ -17,9 +17,7 @@
 
 stripe.api_key = os.environ.get("STRIPE_TEST_KEY")
 STRIPE_WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET")
-CAPTCHA_KEY = (
-    os.environ.get("CAPTCHA_KEY") or "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe"
-)
+CAPTCHA_KEY = os.environ.get("CAPTCHA_KEY") or "1x0000000000000000000000000000000AA"
 
 SESSION_COOKIE_SECURE = False
 DATABASES = {


Test patch:
Repository: webkom/lego

Issue:
Broken link on weekly mails
The link used to unsubscribe from the mail is broken, because `frontend_url` is undefined. Probably due to the weekly mails being handled differently than all other notifications.


Discussion:

Resolving patch:
diff --git a/lego/apps/email/tasks.py b/lego/apps/email/tasks.py
--- a/lego/apps/email/tasks.py
+++ b/lego/apps/email/tasks.py
@@ -93,6 +93,7 @@ def create_weekly_mail(user):
             if todays_weekly is None
             else todays_weekly.get_absolute_url(),
             "joblistings": joblistings,
+            "frontend_url": settings.FRONTEND_URL,
         },
     )
     if events or joblistings or todays_weekly:


Test patch:
Repository: sanic-org/sanic

Issue:
During handling of the above exception, another exception occurred
In the examples/exception_monitoring.py, when i try to run the app and hit the default route, it prints out the exception and then it calls "return super.default(self, request, exception)", it returns with the following exception:

AttributeError: type object 'super' has no attribute 'default'

looks like in the exceptions.py, this line is the culprit (i could be wrong):

`handler = self.handlers.get(type(exception), self.default)
`
 since __init__ does not have that attribute defined.  I am running python 3.6


Discussion:
Oh that must be a typo, I think it should actually be `super().default(self, request, exception)`
i think it should be 

`return super().default(request, exception)`

without the "self"

Resolving patch:
diff --git a/examples/exception_monitoring.py b/examples/exception_monitoring.py
--- a/examples/exception_monitoring.py
+++ b/examples/exception_monitoring.py
@@ -9,17 +9,15 @@
 class' default handler, we can do anything including sending exceptions to
 an external service.
 """
-
-
-
+from sanic.exceptions import Handler, SanicException
 """
 Imports and code relevant for our CustomHandler class
 (Ordinarily this would be in a separate file)
 """
-from sanic.response import text
-from sanic.exceptions import Handler, SanicException
+
 
 class CustomHandler(Handler):
+
     def default(self, request, exception):
         # Here, we have access to the exception object
         # and can do anything with it (log, send to external service, etc)
@@ -31,9 +29,7 @@ def default(self, request, exception):
         # Then, we must finish handling the exception by returning
         # our response to the client
         # For this we can just call the super class' default handler
-        return super.default(self, request, exception)
-
-
+        return super().default(request, exception)
 
 
 """
@@ -49,11 +45,12 @@ def default(self, request, exception):
 handler = CustomHandler(sanic=app)
 app.error_handler = handler
 
+
 @app.route("/")
 async def test(request):
     # Here, something occurs which causes an unexpected exception
     # This exception will flow to our custom handler.
-    x = 1 / 0
+    1 / 0
     return json({"test": True})
 
 


Test patch:
Repository: sanic-org/sanic

Issue:
what have done to static.py?
On last Friday,everything is ok,my static file test works fine.

Today,when I pip install sanic==0.5.1
It raise 404 error.

when I pip install sanic==0.5.0
everything is ok again.

seems like the code blow has some problem?
if not file_path.startswith(root_path):
            raise FileNotFound('File not found',
                               path=file_or_directory,
                               relative_url=file_uri)


Discussion:
Can you please include the code to reproduce this?
@r0fls 
from sanic import Sanic
app = Sanic(__name__)
app.static('/st/index.html', './client/index.html')
app.static('/static', './client')

app.run(host="0.0.0.0", port=8000)

when in sanic 0.5.0,no matter 
wget localhost:8000/static/index.html
or 
wget localhost:8000/st/index.html
is ok.

but when I install pip install sanic == 0.5.1
both wget get 404.

thank you.

![allwrong](https://cloud.githubusercontent.com/assets/21253207/25078601/4b61b0d4-2367-11e7-9206-84997f4552f4.png)

It probably has something to do with #635

Resolving patch:
diff --git a/sanic/static.py b/sanic/static.py
--- a/sanic/static.py
+++ b/sanic/static.py
@@ -56,7 +56,7 @@ async def _handler(request, file_uri=None):
         # URL decode the path sent by the browser otherwise we won't be able to
         # match filenames which got encoded (filenames with spaces etc)
         file_path = path.abspath(unquote(file_path))
-        if not file_path.startswith(root_path):
+        if not file_path.startswith(path.abspath(unquote(root_path))):
             raise FileNotFound('File not found',
                                path=file_or_directory,
                                relative_url=file_uri)


Test patch:
Repository: sanic-org/sanic

Issue:
__main__ top-level script shadowing ImportError
Given `main.py`:
```python
import nonexistent  # assuming this is... non-existent
from sanic import Sanic, response


app = Sanic(__name__)


@app.route('/')
async def index(request):
    return response.html('<p>Hello</p>')
```

When we try to import something non-existent, exception `ImportError` will be thrown,
[line 38 of __main__.py](https://github.com/channelcat/sanic/blob/5fd62098bd2f2722876a0873d5856d70046d3889/sanic/__main__.py#L38) does not preserve the exception, reporting preset message (what's provided on commandline) instead.  This is what we will get:

```
python -m sanic main.app
No module named main found.
  Example File: project/sanic_server.py -> app
  Example Module: project.sanic_server.app
```

It is very hard to find the true cause if the import statement that failed is, let's say, buried three levels of modules deep, for example.


Discussion:

Resolving patch:
diff --git a/sanic/__main__.py b/sanic/__main__.py
--- a/sanic/__main__.py
+++ b/sanic/__main__.py
@@ -35,10 +35,10 @@
 
         app.run(host=args.host, port=args.port,
                 workers=args.workers, debug=args.debug, ssl=ssl)
-    except ImportError:
+    except ImportError as e:
         log.error("No module named {} found.\n"
                   "  Example File: project/sanic_server.py -> app\n"
                   "  Example Module: project.sanic_server.app"
-                  .format(module_name))
+                  .format(e.name))
     except ValueError as e:
         log.error("{}".format(e))


Test patch:
Repository: sanic-org/sanic

Issue:
Consistent module naming
I don't want to be the bad guy 😄 , but there is a module file named with camelCase. Disregard me if this is not a problem.


Discussion:
I would agree that is annoying. That should just go in log.py I think

Resolving patch:
diff --git a/sanic/config.py b/sanic/config.py
--- a/sanic/config.py
+++ b/sanic/config.py
@@ -1,10 +1,11 @@
-from sanic.defaultFilter import DefaultFilter
 import os
 import sys
 import syslog
 import platform
 import types
 
+from sanic.log import DefaultFilter
+
 SANIC_PREFIX = 'SANIC_'
 
 _address_dict = {
diff --git a/sanic/defaultFilter.py b/sanic/defaultFilter.py
deleted file mode 100644
--- a/sanic/defaultFilter.py
+++ /dev/null
@@ -1,13 +0,0 @@
-import logging
-
-
-class DefaultFilter(logging.Filter):
-    def __init__(self, param=None):
-        self.param = param
-
-    def filter(self, record):
-        if self.param is None:
-            return True
-        if record.levelno in self.param:
-            return True
-        return False
diff --git a/sanic/log.py b/sanic/log.py
--- a/sanic/log.py
+++ b/sanic/log.py
@@ -1,4 +1,18 @@
 import logging
 
+
+class DefaultFilter(logging.Filter):
+
+    def __init__(self, param=None):
+        self.param = param
+
+    def filter(self, record):
+        if self.param is None:
+            return True
+        if record.levelno in self.param:
+            return True
+        return False
+
+
 log = logging.getLogger('sanic')
 netlog = logging.getLogger('network')


Test patch:
Repository: sanic-org/sanic

Issue:
IPv6 addresses and netlog: TypeError: not all arguments converted during string formatting
Netlog is trying to log the IP address using request.ip (which is socket.getpeername()), and fails due to differences between returned tuples depending on the address family.

AF_INET returns (host, port), while AF_INET6 a four-tuple: (host, port, flowid, scopeid).
(https://docs.python.org/3/library/socket.html#socket.socket.getpeername)

I've got a PR ready, which simply changes the formatting at https://github.com/channelcat/sanic/blob/0.5.4/sanic/server.py#L204 to use host and port parts of the tuple explicitly.

Did you have any other plans on handling it? Currently it incorrectly logs each request that fails (and that's every IPv6 request) as a 500.


Discussion:

Resolving patch:
diff --git a/sanic/request.py b/sanic/request.py
--- a/sanic/request.py
+++ b/sanic/request.py
@@ -143,7 +143,8 @@ def cookies(self):
     @property
     def ip(self):
         if not hasattr(self, '_ip'):
-            self._ip = self.transport.get_extra_info('peername')
+            self._ip = (self.transport.get_extra_info('peername') or
+                        (None, None))
         return self._ip
 
     @property
diff --git a/sanic/server.py b/sanic/server.py
--- a/sanic/server.py
+++ b/sanic/server.py
@@ -201,7 +201,7 @@ def write_response(self, response):
                 netlog.info('', extra={
                     'status': response.status,
                     'byte': len(response.body),
-                    'host': '%s:%d' % self.request.ip,
+                    'host': '%s:%d' % (self.request.ip[0], self.request.ip[1]),
                     'request': '%s %s' % (self.request.method,
                                           self.request.url)
                 })


Test patch:
Repository: sanic-org/sanic

Issue:
fragmented headers
I stumbled upon an error where long header values (OAuth2 tokens in my case) may lead to fragmentation of the header names. This error was only reproducible with a remote server, not with a local dev server.

The error happens here: [server.py#L167](https://github.com/channelcat/sanic/blob/master/sanic/server.py#L167). The `value` param seems to be `None` if the header is not fully parsed. An empty header value is represented by `b''`.

Adding a debug log statement `log.debug('on_header: %s %s', name, value)` to the `on_header` function yield the following:

```
on_header: b'Conn' None
on_header: b'ection' b'close'
```

or 

```
on_header: b'Connection' None
on_header: b'' b'close'
```

I fixed this by adding the header only if the `value` is not `None` and saving the `name` values to a new class variable (`_header_fragment`) on the `HttpProtocol` instance.

I will open a pull request.


Discussion:

Resolving patch:
diff --git a/sanic/server.py b/sanic/server.py
--- a/sanic/server.py
+++ b/sanic/server.py
@@ -99,6 +99,7 @@ def __init__(self, *, loop, request_handler, error_handler,
         self._request_handler_task = None
         self._request_stream_task = None
         self._keep_alive = keep_alive
+        self._header_fragment = b''
         self.state = state if state else {}
         if 'requests_count' not in self.state:
             self.state['requests_count'] = 0
@@ -173,14 +174,25 @@ def data_received(self, data):
             self.write_error(exception)
 
     def on_url(self, url):
-        self.url = url
+        if not self.url:
+            self.url = url
+        else:
+            self.url += url
 
     def on_header(self, name, value):
-        if name == b'Content-Length' and int(value) > self.request_max_size:
-            exception = PayloadTooLarge('Payload Too Large')
-            self.write_error(exception)
+        self._header_fragment += name
+
+        if value is not None:
+            if self._header_fragment == b'Content-Length' \
+                    and int(value) > self.request_max_size:
+                exception = PayloadTooLarge('Payload Too Large')
+                self.write_error(exception)
+
+            self.headers.append(
+                    (self._header_fragment.decode().casefold(),
+                     value.decode()))
 
-        self.headers.append((name.decode().casefold(), value.decode()))
+            self._header_fragment = b''
 
     def on_headers_complete(self):
         self.request = self.request_class(


Test patch: