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

Issue:
[Copy event] Stats from previous event shouldn't be copied
When you clone an event, you also clone the stats of the previous one.


Discussion:

Resolving patch:
diff --git a/core/deploy_event.py b/core/deploy_event.py
--- a/core/deploy_event.py
+++ b/core/deploy_event.py
@@ -21,12 +21,14 @@ def copy_event(previous_event, event_date):
     previous_event_name = "{} #{}".format(generic_event_name, number)
     event_name = "{} #{}".format(generic_event_name, number+1)
 
-    # Copy event with a name {name} #{number} and new date
+    # Copy event with a name {name} #{number}, new date and empty stats
     new_event = previous_event
     new_event.pk = None
     new_event.name = event_name
     new_event.date = event_date
     new_event.is_page_live = False
+    new_event.attendees_count = None
+    new_event.applicants_count = None
     new_event.save()
 
     # Change url, title and name of previous event to {name} #{number-1}
@@ -64,4 +66,4 @@ def copy_menu_from_previous_event(previous_event, new_event):
         new_obj = obj
         new_obj.pk = None
         new_obj.event = new_event
-        new_obj.save()
\ No newline at end of file
+        new_obj.save()
diff --git a/core/management/commands/copy_event.py b/core/management/commands/copy_event.py
--- a/core/management/commands/copy_event.py
+++ b/core/management/commands/copy_event.py
@@ -58,12 +58,14 @@ def command():
     event.name = "{} #{}".format(name, number-1)
     event.save()
 
-    # Copy event with a name {name} #{number} and new date
+    # Copy event with a name {name} #{number}, new date and empty stats
     new_event = event
     new_event.pk = None
     new_event.name = "{} #{}".format(name, number)
     new_event.date = date
     new_event.is_page_live = False
+    new_event.attendees_count = None
+    new_event.applicants_count = None
     new_event.save()
 
     # Move organizers


Test patch:
Repository: DjangoGirls/djangogirls

Issue:
[Check-in emails] Wait at least a week before sending an email
I've just deployed an event that will happen in March: 5 min after that, the organizer received a check-in email :smile: 
We should at least wait a week before sending a check-in emails.


Discussion:

Resolving patch:
diff --git a/core/management/commands/handle_emails.py b/core/management/commands/handle_emails.py
--- a/core/management/commands/handle_emails.py
+++ b/core/management/commands/handle_emails.py
@@ -104,6 +104,7 @@ def send_offer_help_emails():
         is_on_homepage=True,
         date__gt=timezone.now(),
         date__lte=timezone.now() + timezone.timedelta(weeks=6),
+        created_at__lte=timezone.now() - timezone.timedelta(weeks=2),
         offer_help_email_sent__isnull=True
     ).filter(
         Q(is_page_live=False) | Q(form=None)


Test patch:
diff --git a/core/tests/test_cron_emails.py b/core/tests/test_cron_emails.py
--- a/core/tests/test_cron_emails.py
+++ b/core/tests/test_cron_emails.py
@@ -194,13 +194,18 @@ def _would_send_email(event, mock_send_mail):
 
             return any(event.city in send_kwargs['subject'] for _, send_kwargs in calls)
 
-        # Test one event with no form, should send an email
+        # Test one event with no form, created a few seconds ago, should not send an email
         event = Event.objects.create(
             city="Test City",
             is_on_homepage=True,
             date=in_six_weeks,
             is_page_live=True
         )
+        self.assertFalse(_would_send_email(event))
+
+        # Event was created more than a week ago, should send an event
+        event.created_at = timezone.now() - timezone.timedelta(weeks=3)
+        event.save()
         self.assertTrue(_would_send_email(event))
 
         # Event with a rough date at least a month in the future should also send an email
@@ -252,8 +257,10 @@ def test_send_summary_checkin_to_hello(self, mock_send_mail):
             city="Test City",
             is_on_homepage=True,
             date=in_six_weeks,
-            is_page_live=True
+            is_page_live=True,
         )
+        event.created_at = now - timezone.timedelta(weeks=3)
+        event.save()
         handle_emails.send_offer_help_emails()
         self.assertTrue(mock_send_mail.called)
         _, kwargs = mock_send_mail.call_args
Repository: DjangoGirls/djangogirls

Issue:
Admin considers current events "past" and won't allow editing
This bit me when I wanted to update our page the morning of the event. The admin still showed all the pages, but wouldn't allow editing them; the fields were displayed as static text instead of inputs. Luckily I got around this because the admin still allowed creating completely new pages and changing their order, I just had to get it all right in one shot.

The admin should allow editing until at least the day *after* the day of the event.


Discussion:
Will be happy to see a PR about that :+1: 

Resolving patch:
diff --git a/core/models.py b/core/models.py
--- a/core/models.py
+++ b/core/models.py
@@ -178,13 +178,9 @@ class Meta:
         verbose_name_plural = "List of events"
 
     def is_upcoming(self):
-        if not self.date:
-            return False
         now = timezone.now()
         now = ApproximateDate(year=now.year, month=now.month, day=now.day)
-        if now < self.date:
-            return True
-        return False
+        return self.date and now <= self.date
 
     @property
     def ical_uid(self):


Test patch:
diff --git a/core/tests/test_models.py b/core/tests/test_models.py
--- a/core/tests/test_models.py
+++ b/core/tests/test_models.py
@@ -1,5 +1,9 @@
+from datetime import timedelta
+
 from django.contrib.auth.models import Group
 from django.test import TestCase
+from django.utils import timezone
+from django_date_extensions.fields import ApproximateDate
 
 from coach.models import Coach, DEFAULT_COACH_PHOTO
 from core.models import Event, User
@@ -55,6 +59,21 @@ def test_invite_organizer_to_team(self):
         event.invite_organizer_to_team(user, is_new_user=True, password="pass")
         self.assertEquals(event.team.count(), 3)
 
+    def test_is_upcoming(self):
+        now = timezone.now()
+        now_event = Event(date=ApproximateDate(now.year, now.month, now.day))
+        yesterday = now - timedelta(days=1)
+        yesterday_event = Event(date=ApproximateDate(
+            yesterday.year, yesterday.month, yesterday.day
+        ))
+        tomorrow = now + timedelta(days=1)
+        tomorrow_event = Event(date=ApproximateDate(
+            tomorrow.year, tomorrow.month, tomorrow.day
+        ))
+        assert now_event.is_upcoming()
+        assert not yesterday_event.is_upcoming()
+        assert tomorrow_event.is_upcoming()
+
 
 class TestCoachModel(TestCase):
     def test_delete(self):
Repository: DjangoGirls/djangogirls

Issue:
Provide response for GET request to donation charge view. 
The donation charge view currently only responds to `POST` requests. It seems someone has managed to hit it with a `GET` request so we need to handle them.

It's now throwing a 403

Fixes DJANGO-GIRLS-WEBSITE-5
Fixes #656 


Discussion:

Resolving patch:
diff --git a/donations/views.py b/donations/views.py
--- a/donations/views.py
+++ b/donations/views.py
@@ -1,4 +1,5 @@
 import stripe
+from django.http import HttpResponseForbidden
 from stripe.error import StripeError
 from django.conf import settings
 from django.shortcuts import render, redirect
@@ -59,6 +60,9 @@ def charge(request):
                 )
         return redirect(reverse('donations:error'))
 
+    else:
+        return HttpResponseForbidden()
+
 
 def success(request, currency, amount):
     currency_symbol = {


Test patch:
diff --git a/tests/donations/test_views.py b/tests/donations/test_views.py
--- a/tests/donations/test_views.py
+++ b/tests/donations/test_views.py
@@ -29,8 +29,8 @@ def test_index(client):
 
 
 def test_charge_get(client):
-    with pytest.raises(ValueError):
-        client.get(reverse('donations:charge'))
+    resp = client.get(reverse('donations:charge'))
+    assert resp.status_code == 403
 
 
 def test_charge_post(client):
Repository: DjangoGirls/djangogirls

Issue:
TinyMCE - Unable to switch to "Source Code" from the toolbar
![image (1)](https://user-images.githubusercontent.com/52964908/133939364-2948df45-03d4-42be-8c35-d440bf93d25e.png)
 I would like to edit the HTML code directly for our website contents (Django Girls Antananarivo workshop), but it doesn't have that option even if it says the code plugin is available. 


Discussion:
Hey @marksweb, does `tincymce` allow editing the HTML code directly?
@amakarudze I'm not sure. Would need to look at the config options.

Resolving patch:
diff --git a/core/admin/forms/event_page_content.py b/core/admin/forms/event_page_content.py
--- a/core/admin/forms/event_page_content.py
+++ b/core/admin/forms/event_page_content.py
@@ -1,3 +1,5 @@
+import tinymce
+
 from django import forms
 from tinymce.widgets import AdminTinyMCE
 
@@ -6,7 +8,12 @@ class EventPageContentForm(forms.ModelForm):
 
     class Meta:
         widgets = {
-            'content': AdminTinyMCE()
+            'content': AdminTinyMCE(
+                mce_attrs={
+                    'plugins': tinymce.settings.DEFAULT_CONFIG['plugins'] + ' | code',
+                    'toolbar': tinymce.settings.DEFAULT_CONFIG['toolbar'] + ' | code',
+                },
+            )
         }
         fields = (
             'event',


Test patch:
Repository: DjangoGirls/djangogirls

Issue:
TypeError: "reply_to" argument must be a list or tuple
Sentry Issue: [DJANGO-GIRLS-WEBSITE-2J](https://sentry.io/organizations/django-girls/issues/2674442944/?referrer=github_integration)

```
TypeError: "reply_to" argument must be a list or tuple
(7 additional frame(s) were not displayed)
...
  File "formtools/wizard/views.py", line 358, in render_done
    done_response = self.done(list(final_forms.values()), form_dict=final_forms, **kwargs)
  File "organize/views.py", line 48, in done
    send_application_notification(application)
  File "organize/emails.py", line 31, in send_application_notification
    send_email(content, subject, ['hello@djangogirls.org'],
  File "core/emails.py", line 33, in send_email
    msg = EmailMessage(subject,
  File "django/core/mail/message.py", line 221, in __init__
    raise TypeError('"reply_to" argument must be a list or tuple')
```


Discussion:

Resolving patch:
diff --git a/organize/emails.py b/organize/emails.py
--- a/organize/emails.py
+++ b/organize/emails.py
@@ -29,7 +29,7 @@ def send_application_notification(event_application):
             'application': event_application,
         })
     send_email(content, subject, ['hello@djangogirls.org'],
-               reply_to=event_application.get_main_organizer_email())
+               reply_to=[event_application.get_main_organizer_email()])
 
 
 def send_application_deployed_email(event_application, event, email_password):


Test patch:
Repository: DjangoGirls/djangogirls

Issue:
return paginator.Paginator(self._items(), self.limit)
Sentry Issue: [DJANGO-GIRLS-WEBSITE-3V](https://sentry.io/organizations/django-girls/issues/3236790374/?referrer=github_integration)

```
  return paginator.Paginator(self._items(), self.limit)
```


Discussion:

Resolving patch:
diff --git a/story/sitemap.py b/story/sitemap.py
--- a/story/sitemap.py
+++ b/story/sitemap.py
@@ -7,7 +7,7 @@ class BlogSiteMap(Sitemap):
     priority = 0.5
 
     def items(self):
-        return Story.objects.all()
+        return Story.objects.all().order_by('-created')
 
     def location(self, item):
         url = item.post_url


Test patch:
Repository: DjangoGirls/djangogirls

Issue:
Automate code formatting
Although flake8 is a really helpful tool for maintaining code quality, it doesn't fix formatting issues automatically. As a result, there are still some inconsistencies in the codebase. I'd like to propose adopting the code formatting tools below, which would improve readability and consistency of the code, ultimately increasing development speed:

* [Black](https://github.com/psf/black), to reformat code to follow a consistent style
* [isort](https://pycqa.github.io/isort/), to sort imports
* [autoflake](https://github.com/PyCQA/autoflake), to remove unused imports

These tools can be added to the pre-commit hook to automatically fix and amend files as part of the commit process, saving developers time and effort of manually fixing formatting issues. We can also add a shortcut to run these commands for added convenience.

If we decide to move forward, there's the option of fixing files incrementally or all at once. While the latter approach may result in some merge conflicts with currently open PRs, it'd improve the readability of future PRs by separating formatting changes from actual functional changes.

Would this be useful? Happy to work on this once we've addressed more pressing bugs.


Discussion:
I'd love to have this level of standardization in our codebases. Happy to hear @amakarudze and @marksweb opinions on this too.
@vanessa @ramonsaraiva yeah I'm in favour of any hooks that improve the developer experience.

I thought I'd added isort and a few more already bit clearly I hadn't.

To give you an example of what I usually add to projects, python & Django upgrade are really helpful especially:
https://github.com/django-cms/django-cms/blob/develop/.pre-commit-config.yaml

Those upgrade tools will help get the site to django 4. I think it'd be good to look at doing that soon. 

And I don't use black myself and don't like the way it formats code, but I'm starting a new job soon where they use it... So I guess I need to get used to it 😂
From my personal experience, I have also hesitated to use black at some point, but after some customization to its standard configuration, it feels really good to just save the file and let it format the code for you. Especially when you're working with different people that have different code style tastes.
 I do use black now in my personal projects so I think this would be great.

Resolving patch:
diff --git a/applications/views.py b/applications/views.py
--- a/applications/views.py
+++ b/applications/views.py
@@ -4,8 +4,8 @@
 from django.http import Http404, HttpResponse, JsonResponse
 from django.shortcuts import get_object_or_404, redirect, render
 from django.template.defaultfilters import striptags
-from django.views.decorators.csrf import csrf_exempt
 from django.utils.translation import gettext_lazy as _
+from django.views.decorators.csrf import csrf_exempt
 
 from core.models import EventPageMenu
 from core.utils import get_event


Test patch:
Repository: DjangoGirls/djangogirls

Issue:
HTTPError 404: Not Found Exception When Fetching Images in fetch_stories Command
When running the `python manage.py fetch_stories` command to import blog posts from the Django Girls RSS feed, it encounters an `HTTPError 404: Not Found` exception for some posts when attempting to download associated images. This error halts the command, preventing further posts from being processed.

For example: [Django Girls CDO invades Bukidnon](https://blog.djangogirls.org/post/187602084318/django-girls-cdo-invades-bukidnon) blog post has a broken image which is failing while fetching the data due to this when I tried. 

**Reproduce the error**: This issue can be produced by deleting all the stories from Django admin and then running the command `python manage.py fetch_stories` as per the below screenshot:

<img width="912" alt="Screenshot 2024-02-18 at 3 17 21 am" src="https://github.com/DjangoGirls/djangogirls/assets/28702192/9d13e0ec-05da-438b-b55d-4a17be3e0089">

To solve this, We can Implement exception handling for HTTPError around the image download logic to allow the command to log the issue and continue with the next post.

I have already worked on this issue and will do a PR for review. 



Discussion:

Resolving patch:
diff --git a/story/management/commands/fetch_stories.py b/story/management/commands/fetch_stories.py
--- a/story/management/commands/fetch_stories.py
+++ b/story/management/commands/fetch_stories.py
@@ -1,3 +1,4 @@
+from urllib.error import HTTPError, URLError
 from xml.etree import ElementTree
 
 import requests
@@ -39,10 +40,17 @@ def handle(self, *args, **options):
                 story = Story(name=name, post_url=post_url, content=_post, is_story=is_story)
 
                 if image_url:
-                    img = NamedTemporaryFile(delete=True)
-                    img.write(urlopen(image_url).read())
-                    img.flush()
-                    story.image.save(image_url.split("/")[-1], File(img))
+                    try:
+                        with NamedTemporaryFile(delete=True) as img:
+                            img.write(urlopen(image_url).read())
+                            img.flush()
+                            story.image.save(image_url.split("/")[-1], File(img))
+                    except HTTPError as e:
+                        print(f"HTTP error when fetching image from {image_url}: {e.code} {e.reason}")
+                    except URLError as e:
+                        print(f"URL error when fetching image from {image_url}: {e.reason}")
+                    except Exception as e:
+                        print(f"Unexpected error when fetching image from {image_url}: {e}")
 
                 story.save()
 


Test patch:
Repository: rotki/rotki

Issue:
Runtime error when trying to add ether account
```
(...)/rotkehlchen/ui/usersettings.js:399 Uncaught ReferenceError: showLoading is not defined
    at HTMLButtonElement.add_blockchain_account ((...)/rotkehlchen/ui/usersettings.js:399)
    at HTMLButtonElement.dispatch ((...)/rotkehlchen/node_modules/jquery/dist/jquery.js:5183)
    at HTMLButtonElement.elemData.handle ((...)/rotkehlchen/node_modules/jquery/dist/jquery.js:4991)
```

Is this a vanilla JS/Jquery app? I'd strongly suggest to use TypeScript or something similar to have a minimum number of runtime errors.


Discussion:
Yeah it's a vanilla JS/Jquery app. I have no idea about front-end and it shows :)

Let me look at it when I get back home from the office. I have never seen this error before. You tried to add an ethereum account in the user settings?
Yes, exactly.

Resolving patch:
diff --git a/rotkehlchen/blockchain.py b/rotkehlchen/blockchain.py
--- a/rotkehlchen/blockchain.py
+++ b/rotkehlchen/blockchain.py
@@ -145,6 +145,8 @@ def modify_eth_account(self, account, append_or_remove, add_or_sub):
         Call with 'append', operator.add to add the account
         Call with 'remove', operator.sub to remove the account
         """
+        # Make sure account goes into web3.py as a properly checksummed address
+        account = to_checksum_address(account)
         getattr(self.accounts['ETH'], append_or_remove)(account)
         eth_usd_price = self.inquirer.find_usd_price('ETH')
         balance = self.ethchain.get_eth_balance(account)


Test patch:
Repository: rotki/rotki

Issue:
Updating decorator cache_response_timewise
I noticed that you don't use the `functools.wraps` function in your decorator

https://github.com/rotkehlchenio/rotkehlchen/blob/91f750bed086c46ed57ebc349d70a4630d929f29/rotkehlchen/utils.py#L66

Is it OK if I update the decorator with the following line:

```python
from functools import wraps
...

def _cache_response_timewise(f):
    @wraps(f)
    def wrapper(wrappingobj, *args):
```

Using the `@wraps(f)` decorator the information `f.__name__` and `f.__doc__` won't be replaced with 
the name and the docstring of the `wrapper` function eg. `wrapper` and `None` respectively.




Discussion:
Hey anselal would that introduce any overhead?
The function is a few lines of code but I think it is worth it since it could help while debugging.
My question was more aimed if it would add an overhead in in performance. Since this is a decorator on all RPC calls.
This is what a meant with a few lines of code. 

As I understand it just copies over some attributes from the old function to the new function.

Is there a way to benchmark the RPC calls ?
not yet. But I guess it should be fine. Overoptimization is not needed at this point.

Resolving patch:
diff --git a/rotkehlchen/utils.py b/rotkehlchen/utils.py
--- a/rotkehlchen/utils.py
+++ b/rotkehlchen/utils.py
@@ -7,6 +7,7 @@
 import calendar
 import operator
 import requests
+from functools import wraps
 from collections import namedtuple
 from rlp.sedes import big_endian_int
 
@@ -72,6 +73,7 @@ def cache_response_timewise(seconds=600):
     Objects adhering to this interface are all the exchanges and the rotkehlchen object.
     """
     def _cache_response_timewise(f):
+        @wraps(f)
         def wrapper(wrappingobj, *args):
             with wrappingobj.lock:
                 now = ts_now()


Test patch:
Repository: rotki/rotki

Issue:
Etherscan balance query for more than 20 accounts won't work
Etherscan has a 20 account limit per query.


Discussion:

Resolving patch:
diff --git a/rotkehlchen/ethchain.py b/rotkehlchen/ethchain.py
--- a/rotkehlchen/ethchain.py
+++ b/rotkehlchen/ethchain.py
@@ -90,19 +90,25 @@ def get_eth_balance(self, account):
     def get_multieth_balance(self, accounts):
         """Returns a dict with keys being accounts and balances in ETH"""
         balances = {}
+
         if not self.connected:
-            # TODO: accounts.length should be less than 20. If more we gotta do
-            # multiple calls
-            eth_resp = request_get(
-                'https://api.etherscan.io/api?module=account&action=balancemulti&address=%s' %
-                ','.join(accounts)
-            )
-            if eth_resp['status'] != 1:
-                raise ValueError('Failed to query etherscan for accounts balance')
-            eth_accounts = eth_resp['result']
-            for account_entry in eth_accounts:
-                amount = FVal(account_entry['balance'])
-                balances[account_entry['account']] = from_wei(amount)
+            if len(accounts) > 20:
+                new_accounts = [accounts[x:x+2] for x in range(0, len(accounts), 2)]
+            else:
+                new_accounts = [accounts]
+
+            for account_slice in new_accounts:
+                eth_resp = request_get(
+                    'https://api.etherscan.io/api?module=account&action=balancemulti&address=%s' %
+                    ','.join(account_slice)
+                )
+                if eth_resp['status'] != 1:
+                    raise ValueError('Failed to query etherscan for accounts balance')
+                eth_accounts = eth_resp['result']
+
+                for account_entry in eth_accounts:
+                    amount = FVal(account_entry['balance'])
+                    balances[account_entry['account']] = from_wei(amount)
 
         else:
             for account in accounts:


Test patch: