We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
ValueError: invalid literal for int() with base 10
Sentry Issue: [KOLIBRI-BACKEND-8](https://sentry.io/learningequality/kolibri-backend/issues/877480545/?referrer=github_integration)

```
ValueError: invalid literal for int() with base 10: '0.00293684005737'
  File "django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "django/utils/deprecation.py", line 142, in __call__
    response = self.process_response(request, response)
  File "kolibri/core/analytics/middleware.py", line 144, in process_response
    if int(duration) > MetricsMiddleware.slowest_request_time:
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kolibri/core/analytics/middleware.py`
Content:
```
1 from __future__ import absolute_import
2 
3 import csv
4 import os
5 import time
6 
7 from django.conf import settings
8 from django.core.cache import caches
9 from django.core.exceptions import MiddlewareNotUsed
10 from django.utils.deprecation import MiddlewareMixin
11 
12 from kolibri.core.analytics import SUPPORTED_OS
13 from kolibri.utils import conf
14 from kolibri.utils.server import PROFILE_LOCK
15 from kolibri.utils.system import pid_exists
16 
17 requests_profiling_file = os.path.join(conf.KOLIBRI_HOME,
18                                        'performance',
19                                        '{}_requests_performance.csv'.format(time.strftime('%Y%m%d_%H%M%S')))
20 
21 cache = caches[settings.CACHE_MIDDLEWARE_ALIAS]
22 try:
23     import kolibri.core.analytics.pskolibri as psutil
24     kolibri_process = psutil.Process()
25 except NotImplementedError:
26     # This middleware can't work on this OS
27     kolibri_process = None
28 
29 
30 class Metrics(object):
31     def __init__(self):
32         """
33         Save the initial values when the request comes in
34         This class only will be used when MetricsMiddleware is not disabled, thus the OS is supported.
35         External instances of this class must check if the OS is supported before creating new objects.
36         """
37         self.memory = self.get_used_memory()
38         self.load = self.get_load_average()
39         self.time = time.time()
40 
41     def get_used_memory(self):
42         return kolibri_process.memory_info().vms
43 
44     def get_load_average(self):
45         return kolibri_process.cpu_percent()
46 
47     def get_stats(self):
48         """
49         Calcutes time spent in processing the request
50         and difference in memory and load consumed
51         by kolibri while processing the request
52         :returns: tuple of strings containing time consumed (in seconds),
53                   Kolibri used memory (in bytes) before and after executing the request,
54                   Kolibri cpu load (in %) before and after executing the request.
55         """
56         memory = str(self.get_used_memory())
57         load = str(self.get_load_average())
58         time_delta = str(time.time() - self.time)
59         return (time_delta, str(self.memory), memory, str(self.load), load)
60 
61 
62 class MetricsMiddleware(MiddlewareMixin):
63     """
64     This Middleware will produce a requests_performance.log file, with one line per requests having this structure:
65     - Timestamp
66     - Request path
67     - Time spent processing the request
68     - Memory (in Kbytes) used by the kolibri process when the request came in
69     - Memory (in Kbytes) used by the kolibri process when the response was sent
70     - Percentage of use of cpu by the Kolibri process when the request came in
71     - Percentage of use of cpu by the Kolibri process when the response was sent
72     - One flag indicating if this request is the slowest since the analysis was started
73     """
74     slowest_request_time = 0
75     disabled = True
76     command_pid = 0
77 
78     def __init__(self, get_response=None):
79         super(MetricsMiddleware, self).__init__(get_response=get_response)
80         if not conf.OPTIONS["Server"]["PROFILE"]:
81             raise MiddlewareNotUsed('Request profiling is not enabled')
82 
83     def process_request(self, request):
84         """
85         Store the start time, memory and load when the request comes in.
86         """
87         if not self.disabled:
88             self.metrics = Metrics()
89 
90     def shutdown(self):
91         """
92         Disable this middleware and clean all the static variables
93         """
94         MetricsMiddleware.disabled = True
95         MetricsMiddleware.command_pid = 0
96         delattr(self, 'metrics')
97         if os.path.exists(PROFILE_LOCK):
98             try:
99                 os.remove(PROFILE_LOCK)
100             except OSError:
101                 pass  # lock file was deleted by other process
102 
103     def check_start_conditions(self):
104         """
105         Do the needed checks to enable the Middleware if possible
106         """
107         if MetricsMiddleware.disabled and conf.OPTIONS["Server"]["PROFILE"]:
108             if os.path.exists(PROFILE_LOCK):
109                 try:
110                     with open(PROFILE_LOCK, 'r') as f:
111                         MetricsMiddleware.command_pid = int(f.readline())
112                         file_timestamp = f.readline()
113                         if SUPPORTED_OS:
114                             MetricsMiddleware.disabled = False
115                             self.requests_profiling_file = os.path.join(conf.KOLIBRI_HOME,
116                                                                         'performance',
117                                                                         '{}_requests_performance.csv'.format(file_timestamp))
118                             with open(self.requests_profiling_file, mode='a') as profile_file:
119                                 profile_writer = csv.writer(profile_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
120                                 profile_writer.writerow(('Date', 'Path', 'Duration', 'Memory before (Kb)',
121                                                          'Memory after (Kb)', 'Load before (%)', 'Load after(%)',
122                                                          'Longest time up to now'))
123                 except (IOError, TypeError, ValueError):
124                     # Kolibri command PID file has been deleted or it's corrupted
125                     try:
126                         os.remove(PROFILE_LOCK)
127                     except OSError:
128                         pass  # lock file was deleted by other process
129 
130     def process_response(self, request, response):
131         """
132         Calculate and output the page generation details
133         Log output consist on:
134         Datetime, request path, request duration, memory before, memory after requests is finished,
135         cpu load before, cpu load after the request is finished, max
136         Being `max` True or False to indicate if this is the slowest request since logging began.
137         """
138         self.check_start_conditions()
139 
140         if not MetricsMiddleware.disabled and hasattr(self, 'metrics'):
141             path = request.get_full_path()
142             duration, memory_before, memory, load_before, load = self.metrics.get_stats()
143             max_time = False
144             if int(duration) > MetricsMiddleware.slowest_request_time:
145                 MetricsMiddleware.slowest_request_time = int(duration)
146                 max_time = True
147             timestamp = time.strftime('%Y/%m/%d %H:%M:%S.%f')
148             collected_information = (timestamp, path, duration, memory_before, memory, load_before, load, str(max_time))
149             with open(self.requests_profiling_file, mode='a') as profile_file:
150                 profile_writer = csv.writer(profile_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
151                 profile_writer.writerow(collected_information)
152             if not pid_exists(MetricsMiddleware.command_pid) or not os.path.exists(PROFILE_LOCK):
153                 self.shutdown()
154         return response
155
```
--- 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/kolibri/core/analytics/middleware.py b/kolibri/core/analytics/middleware.py
--- a/kolibri/core/analytics/middleware.py
+++ b/kolibri/core/analytics/middleware.py
@@ -141,7 +141,7 @@
             path = request.get_full_path()
             duration, memory_before, memory, load_before, load = self.metrics.get_stats()
             max_time = False
-            if int(duration) > MetricsMiddleware.slowest_request_time:
+            if float(duration) > MetricsMiddleware.slowest_request_time:
                 MetricsMiddleware.slowest_request_time = int(duration)
                 max_time = True
             timestamp = time.strftime('%Y/%m/%d %H:%M:%S.%f')

{"golden_diff": "diff --git a/kolibri/core/analytics/middleware.py b/kolibri/core/analytics/middleware.py\n--- a/kolibri/core/analytics/middleware.py\n+++ b/kolibri/core/analytics/middleware.py\n@@ -141,7 +141,7 @@\n             path = request.get_full_path()\n             duration, memory_before, memory, load_before, load = self.metrics.get_stats()\n             max_time = False\n-            if int(duration) > MetricsMiddleware.slowest_request_time:\n+            if float(duration) > MetricsMiddleware.slowest_request_time:\n                 MetricsMiddleware.slowest_request_time = int(duration)\n                 max_time = True\n             timestamp = time.strftime('%Y/%m/%d %H:%M:%S.%f')\n", "issue": "ValueError: invalid literal for int() with base 10\nSentry Issue: [KOLIBRI-BACKEND-8](https://sentry.io/learningequality/kolibri-backend/issues/877480545/?referrer=github_integration)\n\n```\nValueError: invalid literal for int() with base 10: '0.00293684005737'\n  File \"django/core/handlers/exception.py\", line 41, in inner\n    response = get_response(request)\n  File \"django/utils/deprecation.py\", line 142, in __call__\n    response = self.process_response(request, response)\n  File \"kolibri/core/analytics/middleware.py\", line 144, in process_response\n    if int(duration) > MetricsMiddleware.slowest_request_time:\n```\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport csv\nimport os\nimport time\n\nfrom django.conf import settings\nfrom django.core.cache import caches\nfrom django.core.exceptions import MiddlewareNotUsed\nfrom django.utils.deprecation import MiddlewareMixin\n\nfrom kolibri.core.analytics import SUPPORTED_OS\nfrom kolibri.utils import conf\nfrom kolibri.utils.server import PROFILE_LOCK\nfrom kolibri.utils.system import pid_exists\n\nrequests_profiling_file = os.path.join(conf.KOLIBRI_HOME,\n                                       'performance',\n                                       '{}_requests_performance.csv'.format(time.strftime('%Y%m%d_%H%M%S')))\n\ncache = caches[settings.CACHE_MIDDLEWARE_ALIAS]\ntry:\n    import kolibri.core.analytics.pskolibri as psutil\n    kolibri_process = psutil.Process()\nexcept NotImplementedError:\n    # This middleware can't work on this OS\n    kolibri_process = None\n\n\nclass Metrics(object):\n    def __init__(self):\n        \"\"\"\n        Save the initial values when the request comes in\n        This class only will be used when MetricsMiddleware is not disabled, thus the OS is supported.\n        External instances of this class must check if the OS is supported before creating new objects.\n        \"\"\"\n        self.memory = self.get_used_memory()\n        self.load = self.get_load_average()\n        self.time = time.time()\n\n    def get_used_memory(self):\n        return kolibri_process.memory_info().vms\n\n    def get_load_average(self):\n        return kolibri_process.cpu_percent()\n\n    def get_stats(self):\n        \"\"\"\n        Calcutes time spent in processing the request\n        and difference in memory and load consumed\n        by kolibri while processing the request\n        :returns: tuple of strings containing time consumed (in seconds),\n                  Kolibri used memory (in bytes) before and after executing the request,\n                  Kolibri cpu load (in %) before and after executing the request.\n        \"\"\"\n        memory = str(self.get_used_memory())\n        load = str(self.get_load_average())\n        time_delta = str(time.time() - self.time)\n        return (time_delta, str(self.memory), memory, str(self.load), load)\n\n\nclass MetricsMiddleware(MiddlewareMixin):\n    \"\"\"\n    This Middleware will produce a requests_performance.log file, with one line per requests having this structure:\n    - Timestamp\n    - Request path\n    - Time spent processing the request\n    - Memory (in Kbytes) used by the kolibri process when the request came in\n    - Memory (in Kbytes) used by the kolibri process when the response was sent\n    - Percentage of use of cpu by the Kolibri process when the request came in\n    - Percentage of use of cpu by the Kolibri process when the response was sent\n    - One flag indicating if this request is the slowest since the analysis was started\n    \"\"\"\n    slowest_request_time = 0\n    disabled = True\n    command_pid = 0\n\n    def __init__(self, get_response=None):\n        super(MetricsMiddleware, self).__init__(get_response=get_response)\n        if not conf.OPTIONS[\"Server\"][\"PROFILE\"]:\n            raise MiddlewareNotUsed('Request profiling is not enabled')\n\n    def process_request(self, request):\n        \"\"\"\n        Store the start time, memory and load when the request comes in.\n        \"\"\"\n        if not self.disabled:\n            self.metrics = Metrics()\n\n    def shutdown(self):\n        \"\"\"\n        Disable this middleware and clean all the static variables\n        \"\"\"\n        MetricsMiddleware.disabled = True\n        MetricsMiddleware.command_pid = 0\n        delattr(self, 'metrics')\n        if os.path.exists(PROFILE_LOCK):\n            try:\n                os.remove(PROFILE_LOCK)\n            except OSError:\n                pass  # lock file was deleted by other process\n\n    def check_start_conditions(self):\n        \"\"\"\n        Do the needed checks to enable the Middleware if possible\n        \"\"\"\n        if MetricsMiddleware.disabled and conf.OPTIONS[\"Server\"][\"PROFILE\"]:\n            if os.path.exists(PROFILE_LOCK):\n                try:\n                    with open(PROFILE_LOCK, 'r') as f:\n                        MetricsMiddleware.command_pid = int(f.readline())\n                        file_timestamp = f.readline()\n                        if SUPPORTED_OS:\n                            MetricsMiddleware.disabled = False\n                            self.requests_profiling_file = os.path.join(conf.KOLIBRI_HOME,\n                                                                        'performance',\n                                                                        '{}_requests_performance.csv'.format(file_timestamp))\n                            with open(self.requests_profiling_file, mode='a') as profile_file:\n                                profile_writer = csv.writer(profile_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n                                profile_writer.writerow(('Date', 'Path', 'Duration', 'Memory before (Kb)',\n                                                         'Memory after (Kb)', 'Load before (%)', 'Load after(%)',\n                                                         'Longest time up to now'))\n                except (IOError, TypeError, ValueError):\n                    # Kolibri command PID file has been deleted or it's corrupted\n                    try:\n                        os.remove(PROFILE_LOCK)\n                    except OSError:\n                        pass  # lock file was deleted by other process\n\n    def process_response(self, request, response):\n        \"\"\"\n        Calculate and output the page generation details\n        Log output consist on:\n        Datetime, request path, request duration, memory before, memory after requests is finished,\n        cpu load before, cpu load after the request is finished, max\n        Being `max` True or False to indicate if this is the slowest request since logging began.\n        \"\"\"\n        self.check_start_conditions()\n\n        if not MetricsMiddleware.disabled and hasattr(self, 'metrics'):\n            path = request.get_full_path()\n            duration, memory_before, memory, load_before, load = self.metrics.get_stats()\n            max_time = False\n            if int(duration) > MetricsMiddleware.slowest_request_time:\n                MetricsMiddleware.slowest_request_time = int(duration)\n                max_time = True\n            timestamp = time.strftime('%Y/%m/%d %H:%M:%S.%f')\n            collected_information = (timestamp, path, duration, memory_before, memory, load_before, load, str(max_time))\n            with open(self.requests_profiling_file, mode='a') as profile_file:\n                profile_writer = csv.writer(profile_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n                profile_writer.writerow(collected_information)\n            if not pid_exists(MetricsMiddleware.command_pid) or not os.path.exists(PROFILE_LOCK):\n                self.shutdown()\n        return response\n", "path": "kolibri/core/analytics/middleware.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport csv\nimport os\nimport time\n\nfrom django.conf import settings\nfrom django.core.cache import caches\nfrom django.core.exceptions import MiddlewareNotUsed\nfrom django.utils.deprecation import MiddlewareMixin\n\nfrom kolibri.core.analytics import SUPPORTED_OS\nfrom kolibri.utils import conf\nfrom kolibri.utils.server import PROFILE_LOCK\nfrom kolibri.utils.system import pid_exists\n\nrequests_profiling_file = os.path.join(conf.KOLIBRI_HOME,\n                                       'performance',\n                                       '{}_requests_performance.csv'.format(time.strftime('%Y%m%d_%H%M%S')))\n\ncache = caches[settings.CACHE_MIDDLEWARE_ALIAS]\ntry:\n    import kolibri.core.analytics.pskolibri as psutil\n    kolibri_process = psutil.Process()\nexcept NotImplementedError:\n    # This middleware can't work on this OS\n    kolibri_process = None\n\n\nclass Metrics(object):\n    def __init__(self):\n        \"\"\"\n        Save the initial values when the request comes in\n        This class only will be used when MetricsMiddleware is not disabled, thus the OS is supported.\n        External instances of this class must check if the OS is supported before creating new objects.\n        \"\"\"\n        self.memory = self.get_used_memory()\n        self.load = self.get_load_average()\n        self.time = time.time()\n\n    def get_used_memory(self):\n        return kolibri_process.memory_info().vms\n\n    def get_load_average(self):\n        return kolibri_process.cpu_percent()\n\n    def get_stats(self):\n        \"\"\"\n        Calcutes time spent in processing the request\n        and difference in memory and load consumed\n        by kolibri while processing the request\n        :returns: tuple of strings containing time consumed (in seconds),\n                  Kolibri used memory (in bytes) before and after executing the request,\n                  Kolibri cpu load (in %) before and after executing the request.\n        \"\"\"\n        memory = str(self.get_used_memory())\n        load = str(self.get_load_average())\n        time_delta = str(time.time() - self.time)\n        return (time_delta, str(self.memory), memory, str(self.load), load)\n\n\nclass MetricsMiddleware(MiddlewareMixin):\n    \"\"\"\n    This Middleware will produce a requests_performance.log file, with one line per requests having this structure:\n    - Timestamp\n    - Request path\n    - Time spent processing the request\n    - Memory (in Kbytes) used by the kolibri process when the request came in\n    - Memory (in Kbytes) used by the kolibri process when the response was sent\n    - Percentage of use of cpu by the Kolibri process when the request came in\n    - Percentage of use of cpu by the Kolibri process when the response was sent\n    - One flag indicating if this request is the slowest since the analysis was started\n    \"\"\"\n    slowest_request_time = 0\n    disabled = True\n    command_pid = 0\n\n    def __init__(self, get_response=None):\n        super(MetricsMiddleware, self).__init__(get_response=get_response)\n        if not conf.OPTIONS[\"Server\"][\"PROFILE\"]:\n            raise MiddlewareNotUsed('Request profiling is not enabled')\n\n    def process_request(self, request):\n        \"\"\"\n        Store the start time, memory and load when the request comes in.\n        \"\"\"\n        if not self.disabled:\n            self.metrics = Metrics()\n\n    def shutdown(self):\n        \"\"\"\n        Disable this middleware and clean all the static variables\n        \"\"\"\n        MetricsMiddleware.disabled = True\n        MetricsMiddleware.command_pid = 0\n        delattr(self, 'metrics')\n        if os.path.exists(PROFILE_LOCK):\n            try:\n                os.remove(PROFILE_LOCK)\n            except OSError:\n                pass  # lock file was deleted by other process\n\n    def check_start_conditions(self):\n        \"\"\"\n        Do the needed checks to enable the Middleware if possible\n        \"\"\"\n        if MetricsMiddleware.disabled and conf.OPTIONS[\"Server\"][\"PROFILE\"]:\n            if os.path.exists(PROFILE_LOCK):\n                try:\n                    with open(PROFILE_LOCK, 'r') as f:\n                        MetricsMiddleware.command_pid = int(f.readline())\n                        file_timestamp = f.readline()\n                        if SUPPORTED_OS:\n                            MetricsMiddleware.disabled = False\n                            self.requests_profiling_file = os.path.join(conf.KOLIBRI_HOME,\n                                                                        'performance',\n                                                                        '{}_requests_performance.csv'.format(file_timestamp))\n                            with open(self.requests_profiling_file, mode='a') as profile_file:\n                                profile_writer = csv.writer(profile_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n                                profile_writer.writerow(('Date', 'Path', 'Duration', 'Memory before (Kb)',\n                                                         'Memory after (Kb)', 'Load before (%)', 'Load after(%)',\n                                                         'Longest time up to now'))\n                except (IOError, TypeError, ValueError):\n                    # Kolibri command PID file has been deleted or it's corrupted\n                    try:\n                        os.remove(PROFILE_LOCK)\n                    except OSError:\n                        pass  # lock file was deleted by other process\n\n    def process_response(self, request, response):\n        \"\"\"\n        Calculate and output the page generation details\n        Log output consist on:\n        Datetime, request path, request duration, memory before, memory after requests is finished,\n        cpu load before, cpu load after the request is finished, max\n        Being `max` True or False to indicate if this is the slowest request since logging began.\n        \"\"\"\n        self.check_start_conditions()\n\n        if not MetricsMiddleware.disabled and hasattr(self, 'metrics'):\n            path = request.get_full_path()\n            duration, memory_before, memory, load_before, load = self.metrics.get_stats()\n            max_time = False\n            if float(duration) > MetricsMiddleware.slowest_request_time:\n                MetricsMiddleware.slowest_request_time = int(duration)\n                max_time = True\n            timestamp = time.strftime('%Y/%m/%d %H:%M:%S.%f')\n            collected_information = (timestamp, path, duration, memory_before, memory, load_before, load, str(max_time))\n            with open(self.requests_profiling_file, mode='a') as profile_file:\n                profile_writer = csv.writer(profile_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n                profile_writer.writerow(collected_information)\n            if not pid_exists(MetricsMiddleware.command_pid) or not os.path.exists(PROFILE_LOCK):\n                self.shutdown()\n        return response\n", "path": "kolibri/core/analytics/middleware.py"}]}