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

Issue:
Warning when opening gym with no members
When opening a gym with no members (e.g. the "default gym" generated by bootstrap_wger), there is an ugly warning by the datatables library because there is no data in the members table

![bildschirmfoto am 2015-10-03 um 23 29 10](https://cloud.githubusercontent.com/assets/2280729/10265211/2977a91a-6a27-11e5-9ace-b6be9b2394ba.png)

Deleting all gyms and then creating a new gym throws error.
To reproduce:

1) Delete all the gyms
2) Create a new gym
3) Try to view the gym members

---

NoReverseMatch at /en/gym/6/members

Reverse for 'edit' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['en/gym/admin-config/(?P<pk>\d+)/edit$']

Request Method:     GET
Request URL:    http://127.0.0.1:8000/en/gym/6/members
Django Version:     1.8.6
Exception Type:     NoReverseMatch
Exception Value:    

Reverse for 'edit' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['en/gym/admin-config/(?P<pk>\d+)/edit$']



Discussion:

Resolving patch:
diff --git a/wger/gym/views/gym.py b/wger/gym/views/gym.py
--- a/wger/gym/views/gym.py
+++ b/wger/gym/views/gym.py
@@ -138,7 +138,6 @@ class GymAddView(WgerFormMixin, CreateView):
 
     model = Gym
     fields = '__all__'
-    success_url = reverse_lazy('gym:gym:list')
     title = ugettext_lazy('Add new gym')
     form_action = reverse_lazy('gym:gym:add')
     permission_required = 'gym.add_gym'
diff --git a/wger/weight/helpers.py b/wger/weight/helpers.py
--- a/wger/weight/helpers.py
+++ b/wger/weight/helpers.py
@@ -47,6 +47,8 @@ def parse_weight_csv(request, cleaned_data):
     entry_dates = set()
     weight_list = []
     error_list = []
+    MAX_ROW_COUNT = 1000
+    row_count = 0
 
     # Process the CSV items first
     for row in parsed_csv:
@@ -69,6 +71,9 @@ def parse_weight_csv(request, cleaned_data):
 
         except (ValueError, IndexError, decimal.InvalidOperation):
             error_list.append(row)
+        row_count += 1
+        if row_count > MAX_ROW_COUNT:
+            break
 
     # Create the valid weight entries
     for date, weight in distinct_weight_entries:


Test patch:
Repository: wger-project/wger

Issue:
Duplicate weight entries in CSV import
It seems it's possible to trigger a uniqueness constraint error using the import CSV function for the weight entries. I could have sworn this was already fixed, but it looks it isn't.

During import the view should make sure that duplicate entries are not saved.



Discussion:

Resolving patch:
diff --git a/wger/weight/helpers.py b/wger/weight/helpers.py
--- a/wger/weight/helpers.py
+++ b/wger/weight/helpers.py
@@ -44,6 +44,7 @@ def parse_weight_csv(request, cleaned_data):
     parsed_csv = csv.reader(six.StringIO(cleaned_data['csv_input']),
                             dialect)
     distinct_weight_entries = []
+    entry_dates = set()
     weight_list = []
     error_list = []
 
@@ -54,13 +55,15 @@ def parse_weight_csv(request, cleaned_data):
             parsed_weight = decimal.Decimal(row[1].replace(',', '.'))
             duplicate_date_in_db = WeightEntry.objects.filter(date=parsed_date,
                                                               user=request.user).exists()
-            # within the list there are no duplicates
-            unique_among_csv = (parsed_date, parsed_weight) not in distinct_weight_entries
+            # within the list there are no duplicate dates
+            unique_among_csv = parsed_date not in entry_dates
+
             # there is no existing weight entry in the database for that date
             unique_in_db = not duplicate_date_in_db
 
             if unique_among_csv and unique_in_db:
                 distinct_weight_entries.append((parsed_date, parsed_weight))
+                entry_dates.add(parsed_date)
             else:
                 error_list.append(row)
 


Test patch:
Repository: wger-project/wger

Issue:
Deprecation warning in login function
Django currently throws a deprecation warning in the login function (`login` in `core/views/user.py`):

``` python
wger/core/views/user.py:77: RemovedInDjango19Warning: `request.REQUEST` is deprecated, use `request.GET` or `request.POST` instead.
    context['next'] = request.REQUEST.get('next')
```

This should be fixed, but I'm not sure if only GET or also POST is used in the code.



Discussion:

Resolving patch:
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -73,8 +73,8 @@ def login(request):
 
     context = {'hide_persona': check_request_amazon(request) or check_request_android(request),
                'active_tab': USER_TAB}
-    if request.REQUEST.get('next'):
-        context['next'] = request.REQUEST.get('next')
+    if request.GET.get('next'):
+        context['next'] = request.GET.get('next')
 
     return django_loginview(request,
                             template_name='user/login.html',


Test patch:
Repository: wger-project/wger

Issue:
Feature request: Password reset
After adding a new user to a Gym, I get a random password. I forgot to save/change the password...
I'm not able to reset it or delete the user again.



Discussion:
This makes sense. The gym manager (or whatever the role is called that can add users) should be able to change user's passwords to a random string again.

Looking into this.

I've got the reset password functionality coded, but I am still working on it. It has two problems at the present:
1. There is no confirmation dialogue for reseting the user's password, so if an admin clicks the link by accident, it will reset the password. I am working on adding a dialogue to confirm their intention to reset the password.
2. It's not translatable. This is the first time I've worked with Django translations. Are there any tips/tricks to offer aside from reading their documents, @rolandgeider ? I took a brief look at the .po files in the project and it appears they may be generated by some sort of script. Is that true?


Resolving patch:
diff --git a/wger/gym/urls.py b/wger/gym/urls.py
--- a/wger/gym/urls.py
+++ b/wger/gym/urls.py
@@ -63,6 +63,9 @@
     url(r'^user/(?P<user_pk>\d+)/permission-edit$',
         gym.gym_permissions_user_edit,
         name='edit-user-permission'),
+    url(r'^user/(?P<user_pk>\d+)/reset-user-password$',
+        gym.reset_user_password,
+        name='reset-user-password'),
 ]
 
 # 'sub patterns' for gym config
diff --git a/wger/gym/views/gym.py b/wger/gym/views/gym.py
--- a/wger/gym/views/gym.py
+++ b/wger/gym/views/gym.py
@@ -201,6 +201,33 @@ def gym_new_user_info_export(request):
     return response
 
 
+def reset_user_password(request, user_pk):
+    '''
+    Resets the password of the selected user to random password
+    '''
+
+    user = get_object_or_404(User, pk=user_pk)
+
+    if not request.user.is_authenticated():
+        return HttpResponseForbidden()
+
+    if not request.user.has_perm('gym.manage_gyms') \
+            and not request.user.has_perm('gym.manage_gym'):
+        return HttpResponseForbidden()
+
+    if request.user.has_perm('gym.manage_gym') \
+            and request.user.userprofile.gym != user.userprofile.gym:
+        return HttpResponseForbidden()
+
+    password = password_generator()
+    user.set_password(password)
+    user.save()
+
+    context = {'mod_user': user,
+               'password': password}
+    return render(request, 'gym/reset_user_password.html', context)
+
+
 def gym_permissions_user_edit(request, user_pk):
     '''
     Edits the permissions of a gym member


Test patch:
Repository: wger-project/wger

Issue:
Log in as user functionality produces 403 error 
Hello,  
when trying to log in from administrator account as user **without** default gym set (that happens when you register through site yourself), I get an 403 error.  

#### Steps to reproduce
Use any of the current deployment methods (docker, docker-compose, VM installation with Debian 10).  And try as an admin to use **log in as this user** (e.g. http://url/cs/user/5/trainer-login ).
Test user is guaranteed to produce this error if no gym is set:  
![image](https://user-images.githubusercontent.com/1702837/102336781-ee8da480-3f91-11eb-81a7-14267e3cef13.png)
#### Log
```
[Wed Dec 16 11:09:28.687239 2020] [wsgi:error] [pid 11615:tid 140290494953216] [remote 192.168.4.14:60186] Forbidden: /cs/user/5/trainer-login
```





Discussion:
With further testing this happens in two cases:

1. when user is either **not** in default gym 
2. or **does not have** any gym at all. 

So creating another gym and adding user there results in the same error.

Resolving patch:
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -520,6 +520,12 @@ def get_context_data(self, **kwargs):
         context['session'] = WorkoutSession.objects.filter(user=self.object).order_by('-date')[:10]
         context['admin_notes'] = AdminUserNote.objects.filter(member=self.object)[:5]
         context['contracts'] = Contract.objects.filter(member=self.object)[:5]
+
+        page_user = self.object  # type: User
+        request_user = self.request.user  # type: User
+        same_gym_id = request_user.userprofile.gym_id == page_user.userprofile.gym_id
+        context['enable_login_button'] = request_user.has_perm('gym.gym_trainer') and same_gym_id
+        context['gym_name'] = request_user.userprofile.gym.name
         return context
 
 


Test patch:
Repository: wger-project/wger

Issue:
Missing exercise name in notification emails
When a user submits a new exercise, the name is missing in the notification email, e.g.

``
The user <name> submitted a new exercise "".
``


It's probably an error in the template


Discussion:
Hi, I would like to try solve this issue. Is it ok?
Sure, go ahead!

Resolving patch:
diff --git a/wger/exercises/models.py b/wger/exercises/models.py
--- a/wger/exercises/models.py
+++ b/wger/exercises/models.py
@@ -417,6 +417,7 @@ def set_author(self, request):
         Set author and status
         This is only used when creating exercises (via web or API)
         """
+
         if request.user.has_perm('exercises.add_exercise'):
             self.status = self.STATUS_ACCEPTED
             if not self.license_author:
@@ -426,8 +427,9 @@ def set_author(self, request):
                 self.license_author = request.user.username
 
             subject = _('New user submitted exercise')
+
             message = _('The user {0} submitted a new exercise "{1}".').format(
-                request.user.username, self.name)
+                request.user.username, self.name_original)
             mail.mail_admins(str(subject),
                              str(message),
                              fail_silently=True)


Test patch:
Repository: wger-project/wger

Issue:
Rework the user preferences
The current user preferences need to be cleaned up somewhat

- Remove obsolete options
- Birthdate shouldn't be a required field
- Better error messages for birthdate
- Possibly: reimplement the settings page in react


Discussion:
Hi @rolandgeider , I would like to work on this issue. Can you please share which options need to be removed ?

Resolving patch:
diff --git a/wger/core/forms.py b/wger/core/forms.py
--- a/wger/core/forms.py
+++ b/wger/core/forms.py
@@ -14,6 +14,7 @@
 #
 # You should have received a copy of the GNU Affero General Public License
 
+from datetime import date
 # Django
 from django import forms
 from django.contrib.auth.forms import (
@@ -77,6 +78,17 @@ class UserPreferencesForm(forms.ModelForm):
         help_text=_("Used for password resets and, optionally, e-mail reminders."),
         required=False
     )
+    birthdate = forms.DateField(
+        label=_("Date of Birth"),
+        required=False,
+        widget=forms.DateInput(
+            attrs={
+                'type': 'date',
+                "max": str(date.today().replace(year=date.today().year - 10)),
+                "min": str(date.today().replace(year=date.today().year - 100))
+            },
+        )
+    )
 
     class Meta:
         model = UserProfile
@@ -104,7 +116,9 @@ def __init__(self, *args, **kwargs):
                     Column('first_name', css_class='form-group col-6 mb-0'),
                     Column('last_name', css_class='form-group col-6 mb-0'),
                     css_class='form-row'
-                ), HTML("<hr>")
+                ),
+                'birthdate',
+                HTML("<hr>")
             ),
             Fieldset(
                 _("Workout reminders"),
@@ -121,7 +135,6 @@ def __init__(self, *args, **kwargs):
                 "show_comments",
                 "show_english_ingredients",
                 "num_days_weight_reminder",
-                "birthdate",
             ), ButtonHolder(Submit('submit', _("Save"), css_class='btn-success btn-block'))
         )
 
diff --git a/wger/core/models/profile.py b/wger/core/models/profile.py
--- a/wger/core/models/profile.py
+++ b/wger/core/models/profile.py
@@ -191,7 +191,7 @@ class UserProfile(models.Model):
     """The user's age"""
 
     birthdate = models.DateField(
-        verbose_name=('Date of Birth'),
+        verbose_name=_('Date of Birth'),
         blank=False,
         null=True,
         validators=[birthdate_validator],


Test patch:
Repository: wger-project/wger

Issue:
Replace jqueryUI's datepicker with one for bootstrap
Replace jqueryUI's datepicker with one for bootstrap



Discussion:
TODO: format the date e.g. in WeightAddView.get_initial, otherwise the YYYY-MM-DD format confuses the plugin


Resolving patch:
diff --git a/extras/docker/development/settings.py b/extras/docker/development/settings.py
--- a/extras/docker/development/settings.py
+++ b/extras/docker/development/settings.py
@@ -123,7 +123,7 @@
 # Django Axes
 #
 AXES_ENABLED = env.bool('AXES_ENABLED', True)
-AXES_LOCKOUT_PARAMETERS = env.list('AXES_LOCKOUT_PARAMETERS', default=['ip-address'])
+AXES_LOCKOUT_PARAMETERS = env.list('AXES_LOCKOUT_PARAMETERS', default=['ip_address'])
 AXES_FAILURE_LIMIT = env.int('AXES_FAILURE_LIMIT', 10)
 AXES_COOLOFF_TIME = timedelta(minutes=env.float('AXES_COOLOFF_TIME', 30))
 AXES_HANDLER = env.str('AXES_HANDLER', 'axes.handlers.cache.AxesCacheHandler')


Test patch:
Repository: mikhailprivalov/l2

Issue:
Печать результатов на Vue



Discussion:

Resolving patch:
diff --git a/results/urls.py b/results/urls.py
--- a/results/urls.py
+++ b/results/urls.py
@@ -8,7 +8,7 @@
     path('enter', views.enter),
     path('get', views.result_get),
     path('pdf', views.result_print),
-    path('preview', TemplateView.as_view(template_name='dashboard/results_preview.html')),
+    path('preview', views.results_preview),
     path('results', views.results),
     path('journal', views.result_journal_print),
     path('journal_table', views.result_journal_table_print),
diff --git a/results/views.py b/results/views.py
--- a/results/views.py
+++ b/results/views.py
@@ -96,6 +96,11 @@ def save(form, filename: str):
         f.write(form.read())
 
 
+@logged_in_or_token
+def results_preview(request):
+    return redirect('/ui/results/preview?{}'.format(request.META['QUERY_STRING']))
+
+
 @logged_in_or_token
 def result_print(request):
     """Печать результатов"""


Test patch:
Repository: mikhailprivalov/l2

Issue:
Запись из окна ввода результатов



Discussion:

Resolving patch:
diff --git a/api/directions/views.py b/api/directions/views.py
--- a/api/directions/views.py
+++ b/api/directions/views.py
@@ -291,12 +291,14 @@ def directions_history(request):
         return JsonResponse(res)
 
     if req_status == 6:
-        # Получить записи регистратуры по РМИС
+        if not pk or pk == -1:
+            return JsonResponse(res)
+
         card = Card.objects.get(pk=pk)
         ecp_id = card.get_ecp_id()
 
         if not ecp_id:
-            return JsonResponse({"register": False, "message": "Пациент не найден в ЕЦП"})
+            return JsonResponse(res)
         patient_time_table = get_ecp_time_table_list_patient(ecp_id)
         patient_direction_time_table = get_ecp_evn_direction(ecp_id)
         patient_time_table.extend(patient_direction_time_table)
diff --git a/ecp_integration/integration.py b/ecp_integration/integration.py
--- a/ecp_integration/integration.py
+++ b/ecp_integration/integration.py
@@ -60,7 +60,7 @@ def get_reserves_ecp(date, med_staff_fact_id):
         sess_id=sess_id,
     )
     time_table = []
-    for r in result.get('data'):
+    for r in result.get('data') or []:
         cache_key = f"ecp-fio:{r['Person_id']}"
         fio = cache.get(cache_key)
         if not fio:
@@ -203,6 +203,8 @@ def search_patient_ecp_by_fio(patient):
         f"PersonBirthDay_BirthDay={patient['birthday']}&PersonSnils_Snils={patient['snils']}",
         sess_id=sess_id,
     )
+    if not result or not result.get("data"):
+        return None
     individual = result['data'][0]
     return individual['Person_id']
 


Test patch:
Repository: tiangolo/fastapi

Issue:
starlette update breaks routing
[starlette 0.9.11](https://pypi.org/project/starlette/0.9.11/) breaks fastapi routing
I'm currently working around this by enforcing starlette==0.9.10


Discussion:
Thanks for the report! I'll check it as soon as I get to my laptop.
It should now be fixed in the latest version `0.1.18`. The change is only pinning the dependencies so FastAPI is not broken, it should work now.

The next step will be to actually update FastAPI's code to be compatible with the latest changes in Starlette.

Resolving patch:
diff --git a/fastapi/routing.py b/fastapi/routing.py
--- a/fastapi/routing.py
+++ b/fastapi/routing.py
@@ -18,7 +18,7 @@
 from starlette.formparsers import UploadFile
 from starlette.requests import Request
 from starlette.responses import JSONResponse, Response
-from starlette.routing import get_name, request_response
+from starlette.routing import compile_path, get_name, request_response
 from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
 
 
@@ -149,9 +149,7 @@ def __init__(
         self.include_in_schema = include_in_schema
         self.content_type = content_type
 
-        self.path_regex, self.path_format, self.param_convertors = self.compile_path(
-            path
-        )
+        self.path_regex, self.path_format, self.param_convertors = compile_path(path)
         assert inspect.isfunction(endpoint) or inspect.ismethod(
             endpoint
         ), f"An endpoint must be a function or method"


Test patch:
Repository: tiangolo/fastapi

Issue:
eta on pydantic update to 0.28
really need your latest PR 
it shoud solve recurring issues with sqlalchemy to pydantic mapping
thank you !


Discussion:
Don't take it as an official response but I could be any momment this week

Resolving patch:
diff --git a/fastapi/utils.py b/fastapi/utils.py
--- a/fastapi/utils.py
+++ b/fastapi/utils.py
@@ -28,7 +28,7 @@ def get_flat_models_from_routes(
             if route.response_fields:
                 responses_from_routes.extend(route.response_fields.values())
     flat_models = get_flat_models_from_fields(
-        body_fields_from_routes + responses_from_routes
+        body_fields_from_routes + responses_from_routes, known_models=set()
     )
     return flat_models
 


Test patch:
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
@@ -31,7 +31,7 @@
                 "parameters": [
                     {
                         "required": False,
-                        "schema": {"title": "Q", "type": "array"},
+                        "schema": {"title": "Q", "type": "array", "items": {}},
                         "name": "q",
                         "in": "query",
                     }
Repository: tiangolo/fastapi

Issue:
Dependency override websocket broken
### Describe the bug

Dependency override does not work for websockets. 

The function `add_api_websocket_route` does not add `dependency_overrides_provider` to `APIWebSocketRoute`.

### To Reproduce

Create a simple app with websockets and test it with override.

### Expected behavior

The overrides should be taken into account, but the test uses the original dependency. 

### Environment

- OS: Windows
- FastAPI version: 0.49.0
- Python version: 3.6.8



Discussion:
`APIRouter.add_api_websocket_route` should be modified to construct the `APIWebSocketRoute` like this:
```
route = APIWebSocketRoute(
            path,
            endpoint=endpoint,
            name=name,
            dependency_overrides_provider=self.dependency_overrides_provider,
        )
```

Resolving patch:
diff --git a/fastapi/routing.py b/fastapi/routing.py
--- a/fastapi/routing.py
+++ b/fastapi/routing.py
@@ -480,7 +480,12 @@ def decorator(func: Callable) -> Callable:
     def add_api_websocket_route(
         self, path: str, endpoint: Callable, name: str = None
     ) -> None:
-        route = APIWebSocketRoute(path, endpoint=endpoint, name=name)
+        route = APIWebSocketRoute(
+            path,
+            endpoint=endpoint,
+            name=name,
+            dependency_overrides_provider=self.dependency_overrides_provider,
+        )
         self.routes.append(route)
 
     def websocket(self, path: str, name: str = None) -> Callable:


Test patch:
diff --git a/tests/test_ws_router.py b/tests/test_ws_router.py
--- a/tests/test_ws_router.py
+++ b/tests/test_ws_router.py
@@ -1,4 +1,4 @@
-from fastapi import APIRouter, FastAPI, WebSocket
+from fastapi import APIRouter, Depends, FastAPI, WebSocket
 from fastapi.testclient import TestClient
 
 router = APIRouter()
@@ -34,6 +34,19 @@ async def routerindex(websocket: WebSocket):
     await websocket.close()
 
 
+async def ws_dependency():
+    return "Socket Dependency"
+
+
+@router.websocket("/router-ws-depends/")
+async def router_ws_decorator_depends(
+    websocket: WebSocket, data=Depends(ws_dependency)
+):
+    await websocket.accept()
+    await websocket.send_text(data)
+    await websocket.close()
+
+
 app.include_router(router)
 app.include_router(prefix_router, prefix="/prefix")
 
@@ -64,3 +77,16 @@ def test_router2():
     with client.websocket_connect("/router2") as websocket:
         data = websocket.receive_text()
         assert data == "Hello, router!"
+
+
+def test_router_ws_depends():
+    client = TestClient(app)
+    with client.websocket_connect("/router-ws-depends/") as websocket:
+        assert websocket.receive_text() == "Socket Dependency"
+
+
+def test_router_ws_depends_with_override():
+    client = TestClient(app)
+    app.dependency_overrides[ws_dependency] = lambda: "Override"
+    with client.websocket_connect("/router-ws-depends/") as websocket:
+        assert websocket.receive_text() == "Override"