We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add field submitted_at in leaderboard
In the leaderboard, add support for showing the field `submitted_at` for each entry on the leaderboard. This will help the participants to keep track of the challenge submissions. 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `apps/jobs/views.py`
Content:
```
1 import datetime
2 
3 from rest_framework import permissions, status
4 from rest_framework.decorators import (api_view,
5                                        authentication_classes,
6                                        permission_classes,
7                                        throttle_classes,)
8 
9 from django.db.models.expressions import RawSQL
10 from django.db.models import FloatField
11 from django.utils import timezone
12 
13 from rest_framework_expiring_authtoken.authentication import (
14     ExpiringTokenAuthentication,)
15 from rest_framework.response import Response
16 from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
17 
18 from accounts.permissions import HasVerifiedEmail
19 from base.utils import paginated_queryset, StandardResultSetPagination
20 from challenges.models import (
21     ChallengePhase,
22     Challenge,
23     ChallengePhaseSplit,
24     LeaderboardData,)
25 from challenges.utils import get_challenge_model, get_challenge_phase_model
26 from participants.models import (ParticipantTeam,)
27 from participants.utils import (
28     get_participant_team_id_of_user_for_a_challenge,)
29 
30 from .models import Submission
31 from .sender import publish_submission_message
32 from .serializers import SubmissionSerializer
33 
34 
35 @throttle_classes([UserRateThrottle])
36 @api_view(['GET', 'POST'])
37 @permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
38 @authentication_classes((ExpiringTokenAuthentication,))
39 def challenge_submission(request, challenge_id, challenge_phase_id):
40     """API Endpoint for making a submission to a challenge"""
41 
42     # check if the challenge exists or not
43     try:
44         challenge = Challenge.objects.get(pk=challenge_id)
45     except Challenge.DoesNotExist:
46         response_data = {'error': 'Challenge does not exist'}
47         return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
48 
49     # check if the challenge phase exists or not
50     try:
51         challenge_phase = ChallengePhase.objects.get(
52             pk=challenge_phase_id, challenge=challenge)
53     except ChallengePhase.DoesNotExist:
54         response_data = {'error': 'Challenge Phase does not exist'}
55         return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
56 
57     if request.method == 'GET':
58         # getting participant team object for the user for a particular challenge.
59         participant_team_id = get_participant_team_id_of_user_for_a_challenge(
60             request.user, challenge_id)
61 
62         # check if participant team exists or not.
63         try:
64             ParticipantTeam.objects.get(pk=participant_team_id)
65         except ParticipantTeam.DoesNotExist:
66             response_data = {'error': 'You haven\'t participated in the challenge'}
67             return Response(response_data, status=status.HTTP_403_FORBIDDEN)
68 
69         submission = Submission.objects.filter(participant_team=participant_team_id,
70                                                challenge_phase=challenge_phase).order_by('-submitted_at')
71         paginator, result_page = paginated_queryset(submission, request)
72         try:
73             serializer = SubmissionSerializer(result_page, many=True, context={'request': request})
74             response_data = serializer.data
75             return paginator.get_paginated_response(response_data)
76         except:
77             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
78 
79     elif request.method == 'POST':
80 
81         # check if the challenge is active or not
82         if not challenge.is_active:
83             response_data = {'error': 'Challenge is not active'}
84             return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)
85 
86         # check if challenge phase is active
87         if not challenge_phase.is_active:
88             response_data = {
89                 'error': 'Sorry, cannot accept submissions since challenge phase is not active'}
90             return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)
91 
92         # check if challenge phase is public and accepting solutions
93         if not challenge_phase.is_public:
94             response_data = {
95                 'error': 'Sorry, cannot accept submissions since challenge phase is not public'}
96             return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)
97 
98         participant_team_id = get_participant_team_id_of_user_for_a_challenge(
99             request.user, challenge_id)
100         try:
101             participant_team = ParticipantTeam.objects.get(pk=participant_team_id)
102         except ParticipantTeam.DoesNotExist:
103             response_data = {'error': 'You haven\'t participated in the challenge'}
104             return Response(response_data, status=status.HTTP_403_FORBIDDEN)
105 
106         serializer = SubmissionSerializer(data=request.data,
107                                           context={'participant_team': participant_team,
108                                                    'challenge_phase': challenge_phase,
109                                                    'request': request
110                                                    })
111         if serializer.is_valid():
112             serializer.save()
113             response_data = serializer.data
114             submission = serializer.instance
115             # publish message in the queue
116             publish_submission_message(challenge_id, challenge_phase_id, submission.id)
117             return Response(response_data, status=status.HTTP_201_CREATED)
118         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
119 
120 
121 @throttle_classes([UserRateThrottle])
122 @api_view(['PATCH'])
123 @permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
124 @authentication_classes((ExpiringTokenAuthentication,))
125 def change_submission_data_and_visibility(request, challenge_pk, challenge_phase_pk, submission_pk):
126     """
127     API Endpoint for updating the submission meta data
128     and changing submission visibility.
129     """
130 
131     # check if the challenge exists or not
132     challenge = get_challenge_model(challenge_pk)
133 
134     # check if the challenge phase exists or not
135     challenge_phase = get_challenge_phase_model(challenge_phase_pk)
136 
137     if not challenge.is_active:
138         response_data = {'error': 'Challenge is not active'}
139         return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)
140 
141     # check if challenge phase is public and accepting solutions
142     if not challenge_phase.is_public:
143         response_data = {
144             'error': 'Sorry, cannot accept submissions since challenge phase is not public'}
145         return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)
146 
147     participant_team_pk = get_participant_team_id_of_user_for_a_challenge(
148         request.user, challenge_pk)
149 
150     try:
151         participant_team = ParticipantTeam.objects.get(pk=participant_team_pk)
152     except ParticipantTeam.DoesNotExist:
153         response_data = {'error': 'You haven\'t participated in the challenge'}
154         return Response(response_data, status=status.HTTP_403_FORBIDDEN)
155 
156     try:
157         submission = Submission.objects.get(participant_team=participant_team,
158                                             challenge_phase=challenge_phase,
159                                             id=submission_pk)
160     except Submission.DoesNotExist:
161         response_data = {'error': 'Submission does not exist'}
162         return Response(response_data, status=status.HTTP_403_FORBIDDEN)
163 
164     try:
165         is_public = request.data['is_public']
166         if is_public is True:
167             when_made_public = datetime.datetime.now()
168             request.data['when_made_public'] = when_made_public
169     except KeyError:
170         pass
171 
172     serializer = SubmissionSerializer(submission,
173                                       data=request.data,
174                                       context={
175                                                'participant_team': participant_team,
176                                                'challenge_phase': challenge_phase,
177                                                'request': request
178                                       },
179                                       partial=True)
180 
181     if serializer.is_valid():
182         serializer.save()
183         response_data = serializer.data
184         return Response(response_data, status=status.HTTP_200_OK)
185     else:
186         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
187 
188 
189 @throttle_classes([AnonRateThrottle])
190 @api_view(['GET'])
191 def leaderboard(request, challenge_phase_split_id):
192     """Returns leaderboard for a corresponding Challenge Phase Split"""
193 
194     # check if the challenge exists or not
195     try:
196         challenge_phase_split = ChallengePhaseSplit.objects.get(
197             pk=challenge_phase_split_id)
198     except ChallengePhaseSplit.DoesNotExist:
199         response_data = {'error': 'Challenge Phase Split does not exist'}
200         return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
201 
202     # Check if the Challenge Phase Split is publicly visible or not
203     if challenge_phase_split.visibility != ChallengePhaseSplit.PUBLIC:
204         response_data = {'error': 'Sorry, leaderboard is not public yet for this Challenge Phase Split!'}
205         return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
206 
207     # Get the leaderboard associated with the Challenge Phase Split
208     leaderboard = challenge_phase_split.leaderboard
209 
210     # Get the default order by key to rank the entries on the leaderboard
211     try:
212         default_order_by = leaderboard.schema['default_order_by']
213     except:
214         response_data = {'error': 'Sorry, Default filtering key not found in leaderboard schema!'}
215         return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
216 
217     # Get all the successful submissions related to the challenge phase split
218     leaderboard_data = LeaderboardData.objects.filter(
219         challenge_phase_split=challenge_phase_split,
220         submission__is_public=True,
221         submission__is_flagged=False).order_by('created_at')
222     leaderboard_data = leaderboard_data.annotate(
223         filtering_score=RawSQL('result->>%s', (default_order_by, ), output_field=FloatField())).values(
224             'id', 'submission__participant_team__team_name',
225             'challenge_phase_split', 'result', 'filtering_score', 'leaderboard__schema')
226 
227     sorted_leaderboard_data = sorted(leaderboard_data, key=lambda k: float(k['filtering_score']), reverse=True)
228 
229     distinct_sorted_leaderboard_data = []
230     team_list = []
231 
232     for data in sorted_leaderboard_data:
233         if data['submission__participant_team__team_name'] in team_list:
234             continue
235         else:
236             distinct_sorted_leaderboard_data.append(data)
237             team_list.append(data['submission__participant_team__team_name'])
238 
239     leaderboard_labels = challenge_phase_split.leaderboard.schema['labels']
240     for item in distinct_sorted_leaderboard_data:
241         item['result'] = [item['result'][index.lower()] for index in leaderboard_labels]
242 
243     paginator, result_page = paginated_queryset(
244                                                 distinct_sorted_leaderboard_data,
245                                                 request,
246                                                 pagination_class=StandardResultSetPagination())
247     response_data = result_page
248     return paginator.get_paginated_response(response_data)
249 
250 
251 @throttle_classes([UserRateThrottle])
252 @api_view(['GET'])
253 @permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
254 @authentication_classes((ExpiringTokenAuthentication,))
255 def get_remaining_submissions(request, challenge_phase_pk, challenge_pk):
256 
257     get_challenge_model(challenge_pk)
258 
259     challenge_phase = get_challenge_phase_model(challenge_phase_pk)
260 
261     participant_team_pk = get_participant_team_id_of_user_for_a_challenge(
262         request.user, challenge_pk)
263 
264     # Conditional check for the existence of participant team of the user.
265     if not participant_team_pk:
266         response_data = {'error': 'You haven\'t participated in the challenge'}
267         return Response(response_data, status=status.HTTP_403_FORBIDDEN)
268 
269     max_submission_per_day = challenge_phase.max_submissions_per_day
270 
271     max_submission = challenge_phase.max_submissions
272 
273     submissions_done_today_count = Submission.objects.filter(
274         challenge_phase__challenge=challenge_pk,
275         challenge_phase=challenge_phase_pk,
276         participant_team=participant_team_pk,
277         submitted_at__gte=timezone.now().date()).count()
278 
279     failed_submissions_count = Submission.objects.filter(
280         challenge_phase__challenge=challenge_pk,
281         challenge_phase=challenge_phase_pk,
282         participant_team=participant_team_pk,
283         status=Submission.FAILED,
284         submitted_at__gte=timezone.now().date()).count()
285 
286     # Checks if today's successfull submission is greater than or equal to max submission per day.
287     if ((submissions_done_today_count - failed_submissions_count) >= max_submission_per_day
288             or (max_submission_per_day == 0)):
289         # Get the UTC time of the instant when the above condition is true.
290         date_time_now = timezone.now()
291         # Calculate the next day's date.
292         date_time_tomorrow = date_time_now.date() + datetime.timedelta(1)
293         utc = timezone.utc
294         # Get the midnight time of the day i.e. 12:00 AM of next day.
295         midnight = utc.localize(datetime.datetime.combine(
296             date_time_tomorrow, datetime.time()))
297         # Subtract the current time from the midnight time to get the remaining time for the next day's submissions.
298         remaining_time = midnight - date_time_now
299         # Return the remaining time with a message.
300         response_data = {'message': 'You have exhausted today\'s submission limit',
301                          'remaining_time': remaining_time
302                          }
303         return Response(response_data, status=status.HTTP_200_OK)
304     else:
305         # Calculate the remaining submissions for today.
306         remaining_submissions_today_count = (max_submission_per_day -
307                                              (submissions_done_today_count -
308                                               failed_submissions_count)
309                                              )
310         # calculate the remaining submissions from total submissions.
311         remaining_submission_count = max_submission - \
312             (submissions_done_today_count - failed_submissions_count)
313         # Return the above calculated data.
314         response_data = {'remaining_submissions_today_count': remaining_submissions_today_count,
315                          'remaining_submissions': remaining_submission_count
316                          }
317         return Response(response_data, status=status.HTTP_200_OK)
318
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/apps/jobs/views.py b/apps/jobs/views.py
--- a/apps/jobs/views.py
+++ b/apps/jobs/views.py
@@ -222,7 +222,7 @@
     leaderboard_data = leaderboard_data.annotate(
         filtering_score=RawSQL('result->>%s', (default_order_by, ), output_field=FloatField())).values(
             'id', 'submission__participant_team__team_name',
-            'challenge_phase_split', 'result', 'filtering_score', 'leaderboard__schema')
+            'challenge_phase_split', 'result', 'filtering_score', 'leaderboard__schema', 'submission__submitted_at')
 
     sorted_leaderboard_data = sorted(leaderboard_data, key=lambda k: float(k['filtering_score']), reverse=True)

{"golden_diff": "diff --git a/apps/jobs/views.py b/apps/jobs/views.py\n--- a/apps/jobs/views.py\n+++ b/apps/jobs/views.py\n@@ -222,7 +222,7 @@\n     leaderboard_data = leaderboard_data.annotate(\n         filtering_score=RawSQL('result->>%s', (default_order_by, ), output_field=FloatField())).values(\n             'id', 'submission__participant_team__team_name',\n-            'challenge_phase_split', 'result', 'filtering_score', 'leaderboard__schema')\n+            'challenge_phase_split', 'result', 'filtering_score', 'leaderboard__schema', 'submission__submitted_at')\n \n     sorted_leaderboard_data = sorted(leaderboard_data, key=lambda k: float(k['filtering_score']), reverse=True)\n", "issue": "Add field submitted_at in leaderboard\nIn the leaderboard, add support for showing the field `submitted_at` for each entry on the leaderboard. This will help the participants to keep track of the challenge submissions. \n", "before_files": [{"content": "import datetime\n\nfrom rest_framework import permissions, status\nfrom rest_framework.decorators import (api_view,\n                                       authentication_classes,\n                                       permission_classes,\n                                       throttle_classes,)\n\nfrom django.db.models.expressions import RawSQL\nfrom django.db.models import FloatField\nfrom django.utils import timezone\n\nfrom rest_framework_expiring_authtoken.authentication import (\n    ExpiringTokenAuthentication,)\nfrom rest_framework.response import Response\nfrom rest_framework.throttling import UserRateThrottle, AnonRateThrottle\n\nfrom accounts.permissions import HasVerifiedEmail\nfrom base.utils import paginated_queryset, StandardResultSetPagination\nfrom challenges.models import (\n    ChallengePhase,\n    Challenge,\n    ChallengePhaseSplit,\n    LeaderboardData,)\nfrom challenges.utils import get_challenge_model, get_challenge_phase_model\nfrom participants.models import (ParticipantTeam,)\nfrom participants.utils import (\n    get_participant_team_id_of_user_for_a_challenge,)\n\nfrom .models import Submission\nfrom .sender import publish_submission_message\nfrom .serializers import SubmissionSerializer\n\n\n@throttle_classes([UserRateThrottle])\n@api_view(['GET', 'POST'])\n@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))\n@authentication_classes((ExpiringTokenAuthentication,))\ndef challenge_submission(request, challenge_id, challenge_phase_id):\n    \"\"\"API Endpoint for making a submission to a challenge\"\"\"\n\n    # check if the challenge exists or not\n    try:\n        challenge = Challenge.objects.get(pk=challenge_id)\n    except Challenge.DoesNotExist:\n        response_data = {'error': 'Challenge does not exist'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # check if the challenge phase exists or not\n    try:\n        challenge_phase = ChallengePhase.objects.get(\n            pk=challenge_phase_id, challenge=challenge)\n    except ChallengePhase.DoesNotExist:\n        response_data = {'error': 'Challenge Phase does not exist'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    if request.method == 'GET':\n        # getting participant team object for the user for a particular challenge.\n        participant_team_id = get_participant_team_id_of_user_for_a_challenge(\n            request.user, challenge_id)\n\n        # check if participant team exists or not.\n        try:\n            ParticipantTeam.objects.get(pk=participant_team_id)\n        except ParticipantTeam.DoesNotExist:\n            response_data = {'error': 'You haven\\'t participated in the challenge'}\n            return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n        submission = Submission.objects.filter(participant_team=participant_team_id,\n                                               challenge_phase=challenge_phase).order_by('-submitted_at')\n        paginator, result_page = paginated_queryset(submission, request)\n        try:\n            serializer = SubmissionSerializer(result_page, many=True, context={'request': request})\n            response_data = serializer.data\n            return paginator.get_paginated_response(response_data)\n        except:\n            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    elif request.method == 'POST':\n\n        # check if the challenge is active or not\n        if not challenge.is_active:\n            response_data = {'error': 'Challenge is not active'}\n            return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n        # check if challenge phase is active\n        if not challenge_phase.is_active:\n            response_data = {\n                'error': 'Sorry, cannot accept submissions since challenge phase is not active'}\n            return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n        # check if challenge phase is public and accepting solutions\n        if not challenge_phase.is_public:\n            response_data = {\n                'error': 'Sorry, cannot accept submissions since challenge phase is not public'}\n            return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n        participant_team_id = get_participant_team_id_of_user_for_a_challenge(\n            request.user, challenge_id)\n        try:\n            participant_team = ParticipantTeam.objects.get(pk=participant_team_id)\n        except ParticipantTeam.DoesNotExist:\n            response_data = {'error': 'You haven\\'t participated in the challenge'}\n            return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n        serializer = SubmissionSerializer(data=request.data,\n                                          context={'participant_team': participant_team,\n                                                   'challenge_phase': challenge_phase,\n                                                   'request': request\n                                                   })\n        if serializer.is_valid():\n            serializer.save()\n            response_data = serializer.data\n            submission = serializer.instance\n            # publish message in the queue\n            publish_submission_message(challenge_id, challenge_phase_id, submission.id)\n            return Response(response_data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@throttle_classes([UserRateThrottle])\n@api_view(['PATCH'])\n@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))\n@authentication_classes((ExpiringTokenAuthentication,))\ndef change_submission_data_and_visibility(request, challenge_pk, challenge_phase_pk, submission_pk):\n    \"\"\"\n    API Endpoint for updating the submission meta data\n    and changing submission visibility.\n    \"\"\"\n\n    # check if the challenge exists or not\n    challenge = get_challenge_model(challenge_pk)\n\n    # check if the challenge phase exists or not\n    challenge_phase = get_challenge_phase_model(challenge_phase_pk)\n\n    if not challenge.is_active:\n        response_data = {'error': 'Challenge is not active'}\n        return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n    # check if challenge phase is public and accepting solutions\n    if not challenge_phase.is_public:\n        response_data = {\n            'error': 'Sorry, cannot accept submissions since challenge phase is not public'}\n        return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n    participant_team_pk = get_participant_team_id_of_user_for_a_challenge(\n        request.user, challenge_pk)\n\n    try:\n        participant_team = ParticipantTeam.objects.get(pk=participant_team_pk)\n    except ParticipantTeam.DoesNotExist:\n        response_data = {'error': 'You haven\\'t participated in the challenge'}\n        return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n    try:\n        submission = Submission.objects.get(participant_team=participant_team,\n                                            challenge_phase=challenge_phase,\n                                            id=submission_pk)\n    except Submission.DoesNotExist:\n        response_data = {'error': 'Submission does not exist'}\n        return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n    try:\n        is_public = request.data['is_public']\n        if is_public is True:\n            when_made_public = datetime.datetime.now()\n            request.data['when_made_public'] = when_made_public\n    except KeyError:\n        pass\n\n    serializer = SubmissionSerializer(submission,\n                                      data=request.data,\n                                      context={\n                                               'participant_team': participant_team,\n                                               'challenge_phase': challenge_phase,\n                                               'request': request\n                                      },\n                                      partial=True)\n\n    if serializer.is_valid():\n        serializer.save()\n        response_data = serializer.data\n        return Response(response_data, status=status.HTTP_200_OK)\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@throttle_classes([AnonRateThrottle])\n@api_view(['GET'])\ndef leaderboard(request, challenge_phase_split_id):\n    \"\"\"Returns leaderboard for a corresponding Challenge Phase Split\"\"\"\n\n    # check if the challenge exists or not\n    try:\n        challenge_phase_split = ChallengePhaseSplit.objects.get(\n            pk=challenge_phase_split_id)\n    except ChallengePhaseSplit.DoesNotExist:\n        response_data = {'error': 'Challenge Phase Split does not exist'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # Check if the Challenge Phase Split is publicly visible or not\n    if challenge_phase_split.visibility != ChallengePhaseSplit.PUBLIC:\n        response_data = {'error': 'Sorry, leaderboard is not public yet for this Challenge Phase Split!'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # Get the leaderboard associated with the Challenge Phase Split\n    leaderboard = challenge_phase_split.leaderboard\n\n    # Get the default order by key to rank the entries on the leaderboard\n    try:\n        default_order_by = leaderboard.schema['default_order_by']\n    except:\n        response_data = {'error': 'Sorry, Default filtering key not found in leaderboard schema!'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # Get all the successful submissions related to the challenge phase split\n    leaderboard_data = LeaderboardData.objects.filter(\n        challenge_phase_split=challenge_phase_split,\n        submission__is_public=True,\n        submission__is_flagged=False).order_by('created_at')\n    leaderboard_data = leaderboard_data.annotate(\n        filtering_score=RawSQL('result->>%s', (default_order_by, ), output_field=FloatField())).values(\n            'id', 'submission__participant_team__team_name',\n            'challenge_phase_split', 'result', 'filtering_score', 'leaderboard__schema')\n\n    sorted_leaderboard_data = sorted(leaderboard_data, key=lambda k: float(k['filtering_score']), reverse=True)\n\n    distinct_sorted_leaderboard_data = []\n    team_list = []\n\n    for data in sorted_leaderboard_data:\n        if data['submission__participant_team__team_name'] in team_list:\n            continue\n        else:\n            distinct_sorted_leaderboard_data.append(data)\n            team_list.append(data['submission__participant_team__team_name'])\n\n    leaderboard_labels = challenge_phase_split.leaderboard.schema['labels']\n    for item in distinct_sorted_leaderboard_data:\n        item['result'] = [item['result'][index.lower()] for index in leaderboard_labels]\n\n    paginator, result_page = paginated_queryset(\n                                                distinct_sorted_leaderboard_data,\n                                                request,\n                                                pagination_class=StandardResultSetPagination())\n    response_data = result_page\n    return paginator.get_paginated_response(response_data)\n\n\n@throttle_classes([UserRateThrottle])\n@api_view(['GET'])\n@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))\n@authentication_classes((ExpiringTokenAuthentication,))\ndef get_remaining_submissions(request, challenge_phase_pk, challenge_pk):\n\n    get_challenge_model(challenge_pk)\n\n    challenge_phase = get_challenge_phase_model(challenge_phase_pk)\n\n    participant_team_pk = get_participant_team_id_of_user_for_a_challenge(\n        request.user, challenge_pk)\n\n    # Conditional check for the existence of participant team of the user.\n    if not participant_team_pk:\n        response_data = {'error': 'You haven\\'t participated in the challenge'}\n        return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n    max_submission_per_day = challenge_phase.max_submissions_per_day\n\n    max_submission = challenge_phase.max_submissions\n\n    submissions_done_today_count = Submission.objects.filter(\n        challenge_phase__challenge=challenge_pk,\n        challenge_phase=challenge_phase_pk,\n        participant_team=participant_team_pk,\n        submitted_at__gte=timezone.now().date()).count()\n\n    failed_submissions_count = Submission.objects.filter(\n        challenge_phase__challenge=challenge_pk,\n        challenge_phase=challenge_phase_pk,\n        participant_team=participant_team_pk,\n        status=Submission.FAILED,\n        submitted_at__gte=timezone.now().date()).count()\n\n    # Checks if today's successfull submission is greater than or equal to max submission per day.\n    if ((submissions_done_today_count - failed_submissions_count) >= max_submission_per_day\n            or (max_submission_per_day == 0)):\n        # Get the UTC time of the instant when the above condition is true.\n        date_time_now = timezone.now()\n        # Calculate the next day's date.\n        date_time_tomorrow = date_time_now.date() + datetime.timedelta(1)\n        utc = timezone.utc\n        # Get the midnight time of the day i.e. 12:00 AM of next day.\n        midnight = utc.localize(datetime.datetime.combine(\n            date_time_tomorrow, datetime.time()))\n        # Subtract the current time from the midnight time to get the remaining time for the next day's submissions.\n        remaining_time = midnight - date_time_now\n        # Return the remaining time with a message.\n        response_data = {'message': 'You have exhausted today\\'s submission limit',\n                         'remaining_time': remaining_time\n                         }\n        return Response(response_data, status=status.HTTP_200_OK)\n    else:\n        # Calculate the remaining submissions for today.\n        remaining_submissions_today_count = (max_submission_per_day -\n                                             (submissions_done_today_count -\n                                              failed_submissions_count)\n                                             )\n        # calculate the remaining submissions from total submissions.\n        remaining_submission_count = max_submission - \\\n            (submissions_done_today_count - failed_submissions_count)\n        # Return the above calculated data.\n        response_data = {'remaining_submissions_today_count': remaining_submissions_today_count,\n                         'remaining_submissions': remaining_submission_count\n                         }\n        return Response(response_data, status=status.HTTP_200_OK)\n", "path": "apps/jobs/views.py"}], "after_files": [{"content": "import datetime\n\nfrom rest_framework import permissions, status\nfrom rest_framework.decorators import (api_view,\n                                       authentication_classes,\n                                       permission_classes,\n                                       throttle_classes,)\n\nfrom django.db.models.expressions import RawSQL\nfrom django.db.models import FloatField\nfrom django.utils import timezone\n\nfrom rest_framework_expiring_authtoken.authentication import (\n    ExpiringTokenAuthentication,)\nfrom rest_framework.response import Response\nfrom rest_framework.throttling import UserRateThrottle, AnonRateThrottle\n\nfrom accounts.permissions import HasVerifiedEmail\nfrom base.utils import paginated_queryset, StandardResultSetPagination\nfrom challenges.models import (\n    ChallengePhase,\n    Challenge,\n    ChallengePhaseSplit,\n    LeaderboardData,)\nfrom challenges.utils import get_challenge_model, get_challenge_phase_model\nfrom participants.models import (ParticipantTeam,)\nfrom participants.utils import (\n    get_participant_team_id_of_user_for_a_challenge,)\n\nfrom .models import Submission\nfrom .sender import publish_submission_message\nfrom .serializers import SubmissionSerializer\n\n\n@throttle_classes([UserRateThrottle])\n@api_view(['GET', 'POST'])\n@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))\n@authentication_classes((ExpiringTokenAuthentication,))\ndef challenge_submission(request, challenge_id, challenge_phase_id):\n    \"\"\"API Endpoint for making a submission to a challenge\"\"\"\n\n    # check if the challenge exists or not\n    try:\n        challenge = Challenge.objects.get(pk=challenge_id)\n    except Challenge.DoesNotExist:\n        response_data = {'error': 'Challenge does not exist'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # check if the challenge phase exists or not\n    try:\n        challenge_phase = ChallengePhase.objects.get(\n            pk=challenge_phase_id, challenge=challenge)\n    except ChallengePhase.DoesNotExist:\n        response_data = {'error': 'Challenge Phase does not exist'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    if request.method == 'GET':\n        # getting participant team object for the user for a particular challenge.\n        participant_team_id = get_participant_team_id_of_user_for_a_challenge(\n            request.user, challenge_id)\n\n        # check if participant team exists or not.\n        try:\n            ParticipantTeam.objects.get(pk=participant_team_id)\n        except ParticipantTeam.DoesNotExist:\n            response_data = {'error': 'You haven\\'t participated in the challenge'}\n            return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n        submission = Submission.objects.filter(participant_team=participant_team_id,\n                                               challenge_phase=challenge_phase).order_by('-submitted_at')\n        paginator, result_page = paginated_queryset(submission, request)\n        try:\n            serializer = SubmissionSerializer(result_page, many=True, context={'request': request})\n            response_data = serializer.data\n            return paginator.get_paginated_response(response_data)\n        except:\n            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    elif request.method == 'POST':\n\n        # check if the challenge is active or not\n        if not challenge.is_active:\n            response_data = {'error': 'Challenge is not active'}\n            return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n        # check if challenge phase is active\n        if not challenge_phase.is_active:\n            response_data = {\n                'error': 'Sorry, cannot accept submissions since challenge phase is not active'}\n            return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n        # check if challenge phase is public and accepting solutions\n        if not challenge_phase.is_public:\n            response_data = {\n                'error': 'Sorry, cannot accept submissions since challenge phase is not public'}\n            return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n        participant_team_id = get_participant_team_id_of_user_for_a_challenge(\n            request.user, challenge_id)\n        try:\n            participant_team = ParticipantTeam.objects.get(pk=participant_team_id)\n        except ParticipantTeam.DoesNotExist:\n            response_data = {'error': 'You haven\\'t participated in the challenge'}\n            return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n        serializer = SubmissionSerializer(data=request.data,\n                                          context={'participant_team': participant_team,\n                                                   'challenge_phase': challenge_phase,\n                                                   'request': request\n                                                   })\n        if serializer.is_valid():\n            serializer.save()\n            response_data = serializer.data\n            submission = serializer.instance\n            # publish message in the queue\n            publish_submission_message(challenge_id, challenge_phase_id, submission.id)\n            return Response(response_data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@throttle_classes([UserRateThrottle])\n@api_view(['PATCH'])\n@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))\n@authentication_classes((ExpiringTokenAuthentication,))\ndef change_submission_data_and_visibility(request, challenge_pk, challenge_phase_pk, submission_pk):\n    \"\"\"\n    API Endpoint for updating the submission meta data\n    and changing submission visibility.\n    \"\"\"\n\n    # check if the challenge exists or not\n    challenge = get_challenge_model(challenge_pk)\n\n    # check if the challenge phase exists or not\n    challenge_phase = get_challenge_phase_model(challenge_phase_pk)\n\n    if not challenge.is_active:\n        response_data = {'error': 'Challenge is not active'}\n        return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n    # check if challenge phase is public and accepting solutions\n    if not challenge_phase.is_public:\n        response_data = {\n            'error': 'Sorry, cannot accept submissions since challenge phase is not public'}\n        return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n    participant_team_pk = get_participant_team_id_of_user_for_a_challenge(\n        request.user, challenge_pk)\n\n    try:\n        participant_team = ParticipantTeam.objects.get(pk=participant_team_pk)\n    except ParticipantTeam.DoesNotExist:\n        response_data = {'error': 'You haven\\'t participated in the challenge'}\n        return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n    try:\n        submission = Submission.objects.get(participant_team=participant_team,\n                                            challenge_phase=challenge_phase,\n                                            id=submission_pk)\n    except Submission.DoesNotExist:\n        response_data = {'error': 'Submission does not exist'}\n        return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n    try:\n        is_public = request.data['is_public']\n        if is_public is True:\n            when_made_public = datetime.datetime.now()\n            request.data['when_made_public'] = when_made_public\n    except KeyError:\n        pass\n\n    serializer = SubmissionSerializer(submission,\n                                      data=request.data,\n                                      context={\n                                               'participant_team': participant_team,\n                                               'challenge_phase': challenge_phase,\n                                               'request': request\n                                      },\n                                      partial=True)\n\n    if serializer.is_valid():\n        serializer.save()\n        response_data = serializer.data\n        return Response(response_data, status=status.HTTP_200_OK)\n    else:\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@throttle_classes([AnonRateThrottle])\n@api_view(['GET'])\ndef leaderboard(request, challenge_phase_split_id):\n    \"\"\"Returns leaderboard for a corresponding Challenge Phase Split\"\"\"\n\n    # check if the challenge exists or not\n    try:\n        challenge_phase_split = ChallengePhaseSplit.objects.get(\n            pk=challenge_phase_split_id)\n    except ChallengePhaseSplit.DoesNotExist:\n        response_data = {'error': 'Challenge Phase Split does not exist'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # Check if the Challenge Phase Split is publicly visible or not\n    if challenge_phase_split.visibility != ChallengePhaseSplit.PUBLIC:\n        response_data = {'error': 'Sorry, leaderboard is not public yet for this Challenge Phase Split!'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # Get the leaderboard associated with the Challenge Phase Split\n    leaderboard = challenge_phase_split.leaderboard\n\n    # Get the default order by key to rank the entries on the leaderboard\n    try:\n        default_order_by = leaderboard.schema['default_order_by']\n    except:\n        response_data = {'error': 'Sorry, Default filtering key not found in leaderboard schema!'}\n        return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n    # Get all the successful submissions related to the challenge phase split\n    leaderboard_data = LeaderboardData.objects.filter(\n        challenge_phase_split=challenge_phase_split,\n        submission__is_public=True,\n        submission__is_flagged=False).order_by('created_at')\n    leaderboard_data = leaderboard_data.annotate(\n        filtering_score=RawSQL('result->>%s', (default_order_by, ), output_field=FloatField())).values(\n            'id', 'submission__participant_team__team_name',\n            'challenge_phase_split', 'result', 'filtering_score', 'leaderboard__schema', 'submission__submitted_at')\n\n    sorted_leaderboard_data = sorted(leaderboard_data, key=lambda k: float(k['filtering_score']), reverse=True)\n\n    distinct_sorted_leaderboard_data = []\n    team_list = []\n\n    for data in sorted_leaderboard_data:\n        if data['submission__participant_team__team_name'] in team_list:\n            continue\n        else:\n            distinct_sorted_leaderboard_data.append(data)\n            team_list.append(data['submission__participant_team__team_name'])\n\n    leaderboard_labels = challenge_phase_split.leaderboard.schema['labels']\n    for item in distinct_sorted_leaderboard_data:\n        item['result'] = [item['result'][index.lower()] for index in leaderboard_labels]\n\n    paginator, result_page = paginated_queryset(\n                                                distinct_sorted_leaderboard_data,\n                                                request,\n                                                pagination_class=StandardResultSetPagination())\n    response_data = result_page\n    return paginator.get_paginated_response(response_data)\n\n\n@throttle_classes([UserRateThrottle])\n@api_view(['GET'])\n@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))\n@authentication_classes((ExpiringTokenAuthentication,))\ndef get_remaining_submissions(request, challenge_phase_pk, challenge_pk):\n\n    get_challenge_model(challenge_pk)\n\n    challenge_phase = get_challenge_phase_model(challenge_phase_pk)\n\n    participant_team_pk = get_participant_team_id_of_user_for_a_challenge(\n        request.user, challenge_pk)\n\n    # Conditional check for the existence of participant team of the user.\n    if not participant_team_pk:\n        response_data = {'error': 'You haven\\'t participated in the challenge'}\n        return Response(response_data, status=status.HTTP_403_FORBIDDEN)\n\n    max_submission_per_day = challenge_phase.max_submissions_per_day\n\n    max_submission = challenge_phase.max_submissions\n\n    submissions_done_today_count = Submission.objects.filter(\n        challenge_phase__challenge=challenge_pk,\n        challenge_phase=challenge_phase_pk,\n        participant_team=participant_team_pk,\n        submitted_at__gte=timezone.now().date()).count()\n\n    failed_submissions_count = Submission.objects.filter(\n        challenge_phase__challenge=challenge_pk,\n        challenge_phase=challenge_phase_pk,\n        participant_team=participant_team_pk,\n        status=Submission.FAILED,\n        submitted_at__gte=timezone.now().date()).count()\n\n    # Checks if today's successfull submission is greater than or equal to max submission per day.\n    if ((submissions_done_today_count - failed_submissions_count) >= max_submission_per_day\n            or (max_submission_per_day == 0)):\n        # Get the UTC time of the instant when the above condition is true.\n        date_time_now = timezone.now()\n        # Calculate the next day's date.\n        date_time_tomorrow = date_time_now.date() + datetime.timedelta(1)\n        utc = timezone.utc\n        # Get the midnight time of the day i.e. 12:00 AM of next day.\n        midnight = utc.localize(datetime.datetime.combine(\n            date_time_tomorrow, datetime.time()))\n        # Subtract the current time from the midnight time to get the remaining time for the next day's submissions.\n        remaining_time = midnight - date_time_now\n        # Return the remaining time with a message.\n        response_data = {'message': 'You have exhausted today\\'s submission limit',\n                         'remaining_time': remaining_time\n                         }\n        return Response(response_data, status=status.HTTP_200_OK)\n    else:\n        # Calculate the remaining submissions for today.\n        remaining_submissions_today_count = (max_submission_per_day -\n                                             (submissions_done_today_count -\n                                              failed_submissions_count)\n                                             )\n        # calculate the remaining submissions from total submissions.\n        remaining_submission_count = max_submission - \\\n            (submissions_done_today_count - failed_submissions_count)\n        # Return the above calculated data.\n        response_data = {'remaining_submissions_today_count': remaining_submissions_today_count,\n                         'remaining_submissions': remaining_submission_count\n                         }\n        return Response(response_data, status=status.HTTP_200_OK)\n", "path": "apps/jobs/views.py"}]}