internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: fossasia/open-event-server

Issue:
Error 500 on Create Ticket : Unique name
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
TIcket creation with same name causes error 500
```json
{
    "errors": [
        {
            "status": 500,
            "source": {
                "pointer": "/data"
            },
            "detail": "Object creation error",
            "title": "Unknown error"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}
```

**Expected behavior:**
There is a unique constraint on name and event id, so this should be checked before saving and shown to the user 

**Steps to reproduce:**
Try to create two tickets of the same name for the same event




Discussion:
@iamareebjamal What should be the response?
Ticket <name> already exists
@iamareebjamal Can i work on this ?
Go ahead @Masquerade0097 

Resolving patch:
diff --git a/app/api/tickets.py b/app/api/tickets.py
--- a/app/api/tickets.py
+++ b/app/api/tickets.py
@@ -12,6 +12,8 @@
 from app.models.order import Order
 from app.models.ticket import Ticket, TicketTag, ticket_tags_table
 from app.models.ticket_holder import TicketHolder
+from app.api.helpers.exceptions import ConflictException
+from app.api.helpers.db import get_count
 
 
 class TicketListPost(ResourceList):
@@ -31,6 +33,9 @@ def before_post(self, args, kwargs, data):
             raise ObjectNotFound({'parameter': 'event_id'},
                                  "Event: {} not found".format(data['event_id']))
 
+        if get_count(db.session.query(Ticket.id).filter_by(name=data['name'], event_id=int(data['event']))) > 0:
+            raise ConflictException({'pointer': '/data/attributes/name'}, "Ticket already exists")
+
     schema = TicketSchema
     methods = ['POST', ]
     data_layer = {'session': db.session,


Test patch:
Repository: fossasia/open-event-server

Issue:
Should "Last name" in create attendee api be required?
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
Docs say that the last name field in create an attendee is required but None is allowed in the API.

**Expected behavior:**
@iamareebjamal @SaptakS @niranjan94 @poush @shubham-padia What should be the expected behaviour here - required or not required?

**Steps to reproduce:**
Create an attendee with no last name field. It is successfully created.


Discussion:
Both first name and last should be required.
Hey, i'd like to take this up.
@party98 I have solved it and am about to send in a PR. Maybe you could work on some other issue? ☺

Resolving patch:
diff --git a/app/api/schema/attendees.py b/app/api/schema/attendees.py
--- a/app/api/schema/attendees.py
+++ b/app/api/schema/attendees.py
@@ -20,7 +20,7 @@ class Meta:
 
     id = fields.Str(dump_only=True)
     firstname = fields.Str(required=True)
-    lastname = fields.Str(allow_none=True)
+    lastname = fields.Str(required=True)
     email = fields.Str(allow_none=True)
     address = fields.Str(allow_none=True)
     city = fields.Str(allow_none=True)


Test patch:
Repository: fossasia/open-event-server

Issue:
Migrate existing DB data to ensure a non-nullable last_name field for attendees
Follow up to #4682

> @shubham-padia: This might create problems when migrating the existing database as there maybe attendees without any last name. We need a migration to handle that. I'm not sure right now how we should go about that. Till we figure it out, we can make the field required in the API schema and let the db schema be as it was before. A follow-up issue can be made to handle change in the db schema. 




Discussion:
@mayank8318 you could take this up
@niranjan94 Okay on it! What should I take into account while doing this?
For empty last names, should I add a space character?

Resolving patch:
diff --git a/app/models/ticket_holder.py b/app/models/ticket_holder.py
--- a/app/models/ticket_holder.py
+++ b/app/models/ticket_holder.py
@@ -16,7 +16,7 @@ class TicketHolder(db.Model):
 
     id = db.Column(db.Integer, primary_key=True)
     firstname = db.Column(db.String, nullable=False)
-    lastname = db.Column(db.String)
+    lastname = db.Column(db.String, nullable=False)
     email = db.Column(db.String)
     address = db.Column(db.String)
     city = db.Column(db.String)
diff --git a/migrations/versions/4cac94c86047_.py b/migrations/versions/4cac94c86047_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/4cac94c86047_.py
@@ -0,0 +1,39 @@
+"""empty message
+
+Revision ID: 4cac94c86047
+Revises: 5b9f83cede65
+Create Date: 2018-05-02 19:59:47.823228
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+# revision identifiers, used by Alembic.
+revision = '4cac94c86047'
+down_revision = '5b9f83cede65'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+
+    ticket_holders_table = sa.sql.table('ticket_holders',
+                                        sa.Column('lastname', sa.VARCHAR()))
+
+    op.execute(ticket_holders_table.update()
+               .where(ticket_holders_table.c.lastname.is_(None))
+               .values({'lastname': op.inline_literal(' ')}))
+
+    op.alter_column('ticket_holders', 'lastname',
+                    existing_type=sa.VARCHAR(),
+                    nullable=False)
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.alter_column('ticket_holders', 'lastname',
+                    existing_type=sa.VARCHAR(),
+                    nullable=True)
+    # ### end Alembic commands ###


Test patch:
Repository: fossasia/open-event-server

Issue:
Internal Server error for update and delete endpoint for Speakers 
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
We get HTTP 500 Internal Server error when updating or deleting speakers. Creating a speaker works fine though.

**Expected behavior:**
It should work.

**Steps to reproduce:**
Make the update or delete requests to the server.

**System information:** 
Doesn't matter. I am using Postman and making requests on the development server for implementing these endpoints in the Organizer app.

**Would you like to work on it?**
Yes


Discussion:

Resolving patch:
diff --git a/app/api/helpers/permission_manager.py b/app/api/helpers/permission_manager.py
--- a/app/api/helpers/permission_manager.py
+++ b/app/api/helpers/permission_manager.py
@@ -119,7 +119,7 @@ def is_coorganizer_or_user_itself(view, view_args, view_kwargs, *args, **kwargs)
     """
     user = current_identity
 
-    if user.is_admin or user.is_super_admin or user.id == kwargs['user_id']:
+    if user.is_admin or user.is_super_admin or ('user_id' in kwargs and user.id == kwargs['user_id']):
         return view(*view_args, **view_kwargs)
 
     if user.is_staff:


Test patch:
Repository: fossasia/open-event-server

Issue:
Create_db always prompts for input

**I'm submitting a ...**  (check one with "x")
- [ ] bug report
- [x] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
Currently at create_db.py, it prompts in terminal for an e-mail address and a password, that all is fine, but currently there is no way to pass down variables from the terminal or from the enviroment so that it can decide beforehand which values to take from e-mail and password
**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
I should be able to create databases from a script using predetermined values.
**Related code:**

```
insert any relevant code here else remove this section
```
https://github.com/fossasia/open-event-server/blob/e0a63f37e0ce7c7a39718f005a959f4194e6ada4/create_db.py#L30



Discussion:
A condition can be added to check whether the shell session is interactive or not and use default values in case of non interactive session.
It can be done using configurations at `config.py` `Config.DevelopmentConfig` adding super user credentials there.
I would like to take up this one.
The script in question is used at a couple of places, and is not limited to development environments. Therefore, the solution needs to be concrete. Furthermore, `config.py` is used as an input for setting the various variables within the project so I don't think that would be a "safe" place to add this data.

Resolving patch:
diff --git a/create_db.py b/create_db.py
--- a/create_db.py
+++ b/create_db.py
@@ -1,3 +1,4 @@
+import argparse
 import getpass
 import re
 import sys
@@ -22,18 +23,26 @@ def _validate_password(password):
         sys.exit(1)
 
 
-def create_default_user():
+def create_default_user(email, password):
     print("Your login is 'super_admin'.")
-    email = input("Enter email for super_admin    : ")
+    if not email:
+        email = input("Enter email for super_admin    : ")
     _validate_email(email)
-    password = getpass.getpass("Enter password for super_admin : ")
+    if not password:
+        password = getpass.getpass("Enter password for super_admin : ")
     _validate_password(password)
     create_super_admin(email, password)
 
 
 if __name__ == "__main__":
+    parser = argparse.ArgumentParser()
+    parser.add_argument("email", nargs='?', help="The email for super_admin.", default='')
+    parser.add_argument("password", nargs='?', help="The password for super_admin.", default='')
+    parser.parse_args()
+    email = parser.email if hasattr(parser, "email") else ''
+    password = parser.password if hasattr(parser, "password") else ''
     with current_app.app_context():
         db.create_all()
         stamp()
-        create_default_user()
+        create_default_user(email, password)
         populate()


Test patch:
Repository: fossasia/open-event-server

Issue:
Add action detail in notifications of notifications API
**I'm submitting a ...**  (check one with "x")
- [ ] bug report
- [x] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
Currently following attributes/response are returned by the notifications api for a given notification
```js
"attributes": {
      "message": "example",
      "received-at": "2017-06-23T04:40:37.239724+00:00",
      "is-read": false,
      "title": "example"
    },
```
**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
Ideal response should be 
```js
{
  title: 'Export of session ...',
  state: 'error',
  message: 'The following error occurred ...',
  primaryAction: {
	action: 'view',
    type: 'session',
 	id: 12344
  },
  receivedAt: '2018-05-14T04:58:06Z'
}
```



Discussion:
@CosmicCoder96 I would like to work on this. 
The current notifications model has action but doesn't have a type property.
```python
    id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
    user = db.relationship('User', backref='notifications', foreign_keys=[user_id])

    title = db.Column(db.String)
    message = db.Column(db.Text)
    action = db.Column(db.String)
    received_at = db.Column(db.DateTime(timezone=True))
    is_read = db.Column(db.Boolean)
```
Should it be added to this model? Also, as far as I understand it is dynamic since a session has an id but some other field might need something else. How should I go about adding this?
@SaptakS @niranjan94 please guide on how to proceed.
I have seen the model of Github Notification and Events API. We can take inspiration from both.

Based on the notifications API of github, we can go for something like
```
    {
        "id": "334643408",
        "unread": true,
        "reason": "subscribed",
        "updated_at": "2018-05-12T21:06:44Z",
        "last_read_at": null,
        "subject": {
            "title": "Improve UI of filter dialog",
            "url": "",
            "type": "Issue"
        },
            "private": false
    },
```
@poush Just to confirm, `primaryActions` will be in a separate table right?

Resolving patch:
diff --git a/app/api/schema/notifications.py b/app/api/schema/notifications.py
--- a/app/api/schema/notifications.py
+++ b/app/api/schema/notifications.py
@@ -22,6 +22,7 @@ class Meta:
     id = fields.Str(dump_only=True)
     title = fields.Str(allow_none=True, dump_only=True)
     message = fields.Str(allow_none=True, dump_only=True)
+    action = fields.Str(allow_none=True, dump_only=True)
     received_at = fields.DateTime(dump_only=True)
     accept = fields.Str(allow_none=True, dump_only=True)
     is_read = fields.Boolean()


Test patch:
Repository: fossasia/open-event-server

Issue:
Create_db is not setting arguments to a variable
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
Basically it's not correctly identifying command line arguments because the object was not set to another variable
**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
you should be able to use the program by setting parameters on the terminal
**Steps to reproduce:**
<!-- If you are able to illustrate the bug or feature request with an example, please provide steps to reproduce -->
run the program with command options
**Related code:**

https://github.com/fossasia/open-event-server/blob/70bb78a9204a322e80d8e647b7cf8c617176b30a/create_db.py#L41



Discussion:

Resolving patch:
diff --git a/create_db.py b/create_db.py
--- a/create_db.py
+++ b/create_db.py
@@ -38,11 +38,9 @@ def create_default_user(email, password):
     parser = argparse.ArgumentParser()
     parser.add_argument("email", nargs='?', help="The email for super_admin.", default='')
     parser.add_argument("password", nargs='?', help="The password for super_admin.", default='')
-    parser.parse_args()
-    email = parser.email if hasattr(parser, "email") else ''
-    password = parser.password if hasattr(parser, "password") else ''
+    parsed = parser.parse_args()
     with current_app.app_context():
         db.create_all()
         stamp()
-        create_default_user(email, password)
+        create_default_user(parsed.email, parsed.password)
         populate()


Test patch:
Repository: fossasia/open-event-server

Issue:
Maximum order allowed to be more than the quantity of the Ticket
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
We can create a Ticket with Maximum order more than the quantity of the Ticket.

**Expected behavior:**
It shouldn't be allowed

**Steps to reproduce:**
Create a Ticket with max_order more than quantity of the ticket

![max_order_more than quantity](https://user-images.githubusercontent.com/21277837/40364522-2a4263de-5df0-11e8-9fe9-e90201c7b5ad.png)

Working on it.

@poush @niranjan94 Is this a bug or is it desirable to allow max_order to be more than the quantity of a ticket ?


Discussion:
@srv-twry valid bug. Please fix it. :)

Resolving patch:
diff --git a/app/api/schema/tickets.py b/app/api/schema/tickets.py
--- a/app/api/schema/tickets.py
+++ b/app/api/schema/tickets.py
@@ -108,6 +108,11 @@ def validate_quantity(self, data):
                 raise UnprocessableEntity({'pointer': '/data/attributes/quantity'},
                                           "quantity should be greater than min-order")
 
+        if 'quantity' in data and 'max_order' in data:
+            if data['quantity'] < data['max_order']:
+                raise UnprocessableEntity({'pointer': '/data/attributes/quantity'},
+                                          "quantity should be lesser than max-order")
+
     access_codes = Relationship(attribute='access_codes',
                                 self_view='v1.ticket_access_code',
                                 self_view_kwargs={'id': '<id>'},


Test patch:
Repository: fossasia/open-event-server

Issue:
Modules API gives 404 at localhost
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
<!-- Describe how the bug manifests. -->

Currently, neither GET  nor PATCH is working in `/v1/modules`
**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->

It should work.
**Steps to reproduce:**
<!-- If you are able to illustrate the bug or feature request with an example, please provide steps to reproduce -->

**Related code:**

```
insert any relevant code here else remove this section
```

**Other information:**
<!-- List any other information that is relevant to your issue. Stack traces, related issues, suggestions on how to fix, Stack Overflow links, forum links, etc. -->

**System information:** 

<!-- Add information about the system your facing this bug on. If you think this is irrelevant or if it's a UI bug or a feature request, please remove this section -->

```
Your operating system
```

```
output of `python --version`
```
**Wanna work on this issue**


Discussion:
This was reverted, so I reopened it.

Resolving patch:
diff --git a/app/api/modules.py b/app/api/modules.py
--- a/app/api/modules.py
+++ b/app/api/modules.py
@@ -10,6 +10,7 @@ class ModuleDetail(ResourceDetail):
     """
     module detail by id
     """
+
     def before_get(self, args, kwargs):
         """
         before get method to get the resource id for fetching details
@@ -19,7 +20,7 @@ def before_get(self, args, kwargs):
         """
         kwargs['id'] = 1
 
-    decorators = (api.has_permission('is_admin', methods="PATCH", id="1"),)
+    decorators = (api.has_permission('is_admin', methods='PATCH', id='1'),)
     methods = ['GET', 'PATCH']
     schema = ModuleSchema
     data_layer = {'session': db.session,
diff --git a/populate_db.py b/populate_db.py
--- a/populate_db.py
+++ b/populate_db.py
@@ -24,6 +24,7 @@
 from app.models.custom_system_role import CustomSysRole
 
 from app.models.setting import Setting
+from app.models.module import Module
 
 # User Permissions
 from app.models.user_permission import UserPermission
@@ -57,6 +58,10 @@ def create_settings():
     get_or_create(Setting, app_name='Open Event')
 
 
+def create_modules():
+    get_or_create(Module, donation_include=False)
+
+
 def create_permissions():
     orgr = Role.query.get(1)
     coorgr = Role.query.get(2)
@@ -176,6 +181,8 @@ def populate():
     create_user_permissions()
     print('Creating settings...')
     create_settings()
+    print('Creating modules...')
+    create_modules()
     print('Creating admin message settings...')
     create_admin_message_settings()
 


Test patch:
Repository: fossasia/open-event-server

Issue:
Change bytes to str in all instances of "file.write"
**Describe the bug**
`file.write` causes an error in python 3.5 (Stack trace below)

**To Reproduce**
Steps to reproduce the behavior:
1. Set up the project with python 3.5 (preferably a virtual env)
1. Make the API call to start a zip task.

For more details refer to #4775 

**Expected behavior**
No error

**Stacktrace**
```sh
  File "/open-event-server/app/api/helpers/tasks.py", line 64, in export_event_task
    path = event_export_task_base(event_id, settings)
  File "/open-event-server/app/api/exports.py", line 69, in event_export_task_base
    path = export_event_json(event_id, settings)
  File "/open-event-server/app/api/helpers/export_helpers.py", line 209, in export_event_json
    fp.write(data_str)
TypeError: write() argument must be str, not bytes
```
**Additional details (please complete the following information):**
 - OS: Ubuntu 18.04
 - Python Version 3.5
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
#4775 


Discussion:
@mayank8318 Is this also a problem in Python 3.6 ? 
If not, then please use it since we are supposed to use 3.6
@srv-twry doesn't happen in 3.6 but @iamareebjamal said we should fix it since it is 3+ anyways

Resolving patch:
diff --git a/app/api/helpers/export_helpers.py b/app/api/helpers/export_helpers.py
--- a/app/api/helpers/export_helpers.py
+++ b/app/api/helpers/export_helpers.py
@@ -206,7 +206,7 @@ def export_event_json(event_id, settings):
                 _download_media(data[count], e[0], dir_path, settings)
         data_str = json.dumps(data, indent=4, ensure_ascii=False).encode('utf-8')
         fp = open(dir_path + '/' + e[0], 'w')
-        fp.write(data_str)
+        fp.write(str(data_str, 'utf-8'))
         fp.close()
     # add meta
     data_str = json.dumps(
@@ -214,7 +214,7 @@ def export_event_json(event_id, settings):
         indent=4, ensure_ascii=False
     ).encode('utf-8')
     fp = open(dir_path + '/meta', 'w')
-    fp.write(data_str)
+    fp.write(str(data_str, 'utf-8'))
     fp.close()
     # make zip
     shutil.make_archive(dir_path, 'zip', dir_path)
diff --git a/app/api/helpers/storage.py b/app/api/helpers/storage.py
--- a/app/api/helpers/storage.py
+++ b/app/api/helpers/storage.py
@@ -109,7 +109,7 @@ def read(self):
 
     def save(self, path):
         f = open(path, 'w')
-        f.write(self.data)
+        f.write(str(self.data, 'utf-8'))
         f.close()
 
 
diff --git a/app/api/helpers/utilities.py b/app/api/helpers/utilities.py
--- a/app/api/helpers/utilities.py
+++ b/app/api/helpers/utilities.py
@@ -97,7 +97,7 @@ def get_filename_from_cd(cd):
 def write_file(file, data):
     """simple write to file"""
     fp = open(file, 'w')
-    fp.write(data)
+    fp.write(str(data, 'utf-8'))
     fp.close()
 
 


Test patch: