prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Allow backend to return Slices in reverse order
  ## Expected Behavior
  
  When user moves slider down, backend should send Slices in reverse order, so that UI will be able to show them first.
  
  ## Actual Behavior
  
  Backend always send Slices in ascending order.
  
  ## Steps to Reproduce the Problem
  
    1. Go to the marker page.
    2. Move to the bottom of current view (let's assume that the last Slice on which you are now has index N).
    3. UI will request backend to send Slices from range (N-10, N-1).
    4. Backend will send Slices **in order**: (N-10, N-9, N-8, ..., N-1).
    5. Marker will add (N-10)th Slice to the view from above response.
    6. Marker will allow user to move between all Slices in range from N-10 but Slices (N-9, N-8, ...) won't be loaded yet!
  
  ## Additional comment
  
  Marker should request backend to send Slices in descending order, so that it will be able to load them to the marker first. Such case should be enabled **only** if user wants to go back/down!
  
  To debug this case, slow your Internet connection down in your browser's dev tools or apply huge load on the backend server.
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `backend/medtagger/api/scans/service_web_socket.py`
  Content:
  ```
  1 """Module responsible for definition of Scans service available via WebSockets."""
  2 from typing import Dict
  3 
  4 from flask_socketio import Namespace, emit
  5 
  6 from medtagger.api import web_socket
  7 from medtagger.database.models import SliceOrientation
  8 from medtagger.types import ScanID
  9 from medtagger.api.exceptions import InvalidArgumentsException
  10 from medtagger.api.scans import business
  11 
  12 
  13 class Slices(Namespace):
  14     """WebSocket handler for /slices namespace."""
  15 
  16     MAX_NUMBER_OF_SLICES_PER_REQUEST = 25
  17 
  18     def on_request_slices(self, request: Dict) -> None:
  19         """Handle slices request triggered  by `request_slices` event."""
  20         assert request.get('scan_id'), 'ScanID is required!'
  21         scan_id = ScanID(str(request['scan_id']))
  22         begin = max(0, request.get('begin', 0))
  23         count = request.get('count', 1)
  24         orientation = request.get('orientation', SliceOrientation.Z.value)
  25         self._raise_on_invalid_request_slices(count, orientation)
  26 
  27         orientation = SliceOrientation[orientation]
  28         slices = business.get_slices_for_scan(scan_id, begin, count, orientation=orientation)
  29         for index, (_slice, image) in enumerate(slices):
  30             emit('slice', {'scan_id': scan_id, 'index': begin + index, 'image': image})
  31 
  32     def _raise_on_invalid_request_slices(self, count: int, orientation: str) -> None:
  33         """Validate incoming request and raise an exception if there are issues with given arguments.
  34 
  35         :param count: number of slices that should be returned
  36         :param orientation: Slice's orientation as a string
  37         """
  38         # Make sure that passed orientation is proper one
  39         if orientation not in SliceOrientation.__members__:
  40             raise InvalidArgumentsException('Invalid Slice orientation.')
  41 
  42         # Make sure that nobody will fetch whole scan at once. It could freeze our backend application.
  43         if count > self.MAX_NUMBER_OF_SLICES_PER_REQUEST:
  44             message = 'Cannot return more than {} slices per request.'.format(self.MAX_NUMBER_OF_SLICES_PER_REQUEST)
  45             raise InvalidArgumentsException(message)
  46 
  47 
  48 # Register above namespace
  49 web_socket.on_namespace(Slices('/slices'))
  50
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/backend/medtagger/api/scans/service_web_socket.py b/backend/medtagger/api/scans/service_web_socket.py
  --- a/backend/medtagger/api/scans/service_web_socket.py
  +++ b/backend/medtagger/api/scans/service_web_socket.py
  @@ -21,13 +21,21 @@
           scan_id = ScanID(str(request['scan_id']))
           begin = max(0, request.get('begin', 0))
           count = request.get('count', 1)
  +        reversed_order = request.get('reversed', False)
           orientation = request.get('orientation', SliceOrientation.Z.value)
           self._raise_on_invalid_request_slices(count, orientation)
   
           orientation = SliceOrientation[orientation]
           slices = business.get_slices_for_scan(scan_id, begin, count, orientation=orientation)
  -        for index, (_slice, image) in enumerate(slices):
  -            emit('slice', {'scan_id': scan_id, 'index': begin + index, 'image': image})
  +        slices_to_send = reversed(list(enumerate(slices))) if reversed_order else enumerate(slices)
  +        last_in_batch = begin if reversed_order else begin + count - 1
  +        for index, (_slice, image) in slices_to_send:
  +            emit('slice', {
  +                'scan_id': scan_id,
  +                'index': begin + index,
  +                'last_in_batch': last_in_batch,
  +                'image': image,
  +            })
   
       def _raise_on_invalid_request_slices(self, count: int, orientation: str) -> None:
           """Validate incoming request and raise an exception if there are issues with given arguments.
  
verification_info: {"golden_diff": "diff --git a/backend/medtagger/api/scans/service_web_socket.py b/backend/medtagger/api/scans/service_web_socket.py\n--- a/backend/medtagger/api/scans/service_web_socket.py\n+++ b/backend/medtagger/api/scans/service_web_socket.py\n@@ -21,13 +21,21 @@\n         scan_id = ScanID(str(request['scan_id']))\n         begin = max(0, request.get('begin', 0))\n         count = request.get('count', 1)\n+        reversed_order = request.get('reversed', False)\n         orientation = request.get('orientation', SliceOrientation.Z.value)\n         self._raise_on_invalid_request_slices(count, orientation)\n \n         orientation = SliceOrientation[orientation]\n         slices = business.get_slices_for_scan(scan_id, begin, count, orientation=orientation)\n-        for index, (_slice, image) in enumerate(slices):\n-            emit('slice', {'scan_id': scan_id, 'index': begin + index, 'image': image})\n+        slices_to_send = reversed(list(enumerate(slices))) if reversed_order else enumerate(slices)\n+        last_in_batch = begin if reversed_order else begin + count - 1\n+        for index, (_slice, image) in slices_to_send:\n+            emit('slice', {\n+                'scan_id': scan_id,\n+                'index': begin + index,\n+                'last_in_batch': last_in_batch,\n+                'image': image,\n+            })\n \n     def _raise_on_invalid_request_slices(self, count: int, orientation: str) -> None:\n         \"\"\"Validate incoming request and raise an exception if there are issues with given arguments.\n", "issue": "Allow backend to return Slices in reverse order\n## Expected Behavior\r\n\r\nWhen user moves slider down, backend should send Slices in reverse order, so that UI will be able to show them first.\r\n\r\n## Actual Behavior\r\n\r\nBackend always send Slices in ascending order.\r\n\r\n## Steps to Reproduce the Problem\r\n\r\n  1. Go to the marker page.\r\n  2. Move to the bottom of current view (let's assume that the last Slice on which you are now has index N).\r\n  3. UI will request backend to send Slices from range (N-10, N-1).\r\n  4. Backend will send Slices **in order**: (N-10, N-9, N-8, ..., N-1).\r\n  5. Marker will add (N-10)th Slice to the view from above response.\r\n  6. Marker will allow user to move between all Slices in range from N-10 but Slices (N-9, N-8, ...) won't be loaded yet!\r\n\r\n## Additional comment\r\n\r\nMarker should request backend to send Slices in descending order, so that it will be able to load them to the marker first. Such case should be enabled **only** if user wants to go back/down!\r\n\r\nTo debug this case, slow your Internet connection down in your browser's dev tools or apply huge load on the backend server.\n", "before_files": [{"content": "\"\"\"Module responsible for definition of Scans service available via WebSockets.\"\"\"\nfrom typing import Dict\n\nfrom flask_socketio import Namespace, emit\n\nfrom medtagger.api import web_socket\nfrom medtagger.database.models import SliceOrientation\nfrom medtagger.types import ScanID\nfrom medtagger.api.exceptions import InvalidArgumentsException\nfrom medtagger.api.scans import business\n\n\nclass Slices(Namespace):\n    \"\"\"WebSocket handler for /slices namespace.\"\"\"\n\n    MAX_NUMBER_OF_SLICES_PER_REQUEST = 25\n\n    def on_request_slices(self, request: Dict) -> None:\n        \"\"\"Handle slices request triggered  by `request_slices` event.\"\"\"\n        assert request.get('scan_id'), 'ScanID is required!'\n        scan_id = ScanID(str(request['scan_id']))\n        begin = max(0, request.get('begin', 0))\n        count = request.get('count', 1)\n        orientation = request.get('orientation', SliceOrientation.Z.value)\n        self._raise_on_invalid_request_slices(count, orientation)\n\n        orientation = SliceOrientation[orientation]\n        slices = business.get_slices_for_scan(scan_id, begin, count, orientation=orientation)\n        for index, (_slice, image) in enumerate(slices):\n            emit('slice', {'scan_id': scan_id, 'index': begin + index, 'image': image})\n\n    def _raise_on_invalid_request_slices(self, count: int, orientation: str) -> None:\n        \"\"\"Validate incoming request and raise an exception if there are issues with given arguments.\n\n        :param count: number of slices that should be returned\n        :param orientation: Slice's orientation as a string\n        \"\"\"\n        # Make sure that passed orientation is proper one\n        if orientation not in SliceOrientation.__members__:\n            raise InvalidArgumentsException('Invalid Slice orientation.')\n\n        # Make sure that nobody will fetch whole scan at once. It could freeze our backend application.\n        if count > self.MAX_NUMBER_OF_SLICES_PER_REQUEST:\n            message = 'Cannot return more than {} slices per request.'.format(self.MAX_NUMBER_OF_SLICES_PER_REQUEST)\n            raise InvalidArgumentsException(message)\n\n\n# Register above namespace\nweb_socket.on_namespace(Slices('/slices'))\n", "path": "backend/medtagger/api/scans/service_web_socket.py"}], "after_files": [{"content": "\"\"\"Module responsible for definition of Scans service available via WebSockets.\"\"\"\nfrom typing import Dict\n\nfrom flask_socketio import Namespace, emit\n\nfrom medtagger.api import web_socket\nfrom medtagger.database.models import SliceOrientation\nfrom medtagger.types import ScanID\nfrom medtagger.api.exceptions import InvalidArgumentsException\nfrom medtagger.api.scans import business\n\n\nclass Slices(Namespace):\n    \"\"\"WebSocket handler for /slices namespace.\"\"\"\n\n    MAX_NUMBER_OF_SLICES_PER_REQUEST = 25\n\n    def on_request_slices(self, request: Dict) -> None:\n        \"\"\"Handle slices request triggered  by `request_slices` event.\"\"\"\n        assert request.get('scan_id'), 'ScanID is required!'\n        scan_id = ScanID(str(request['scan_id']))\n        begin = max(0, request.get('begin', 0))\n        count = request.get('count', 1)\n        reversed_order = request.get('reversed', False)\n        orientation = request.get('orientation', SliceOrientation.Z.value)\n        self._raise_on_invalid_request_slices(count, orientation)\n\n        orientation = SliceOrientation[orientation]\n        slices = business.get_slices_for_scan(scan_id, begin, count, orientation=orientation)\n        slices_to_send = reversed(list(enumerate(slices))) if reversed_order else enumerate(slices)\n        last_in_batch = begin if reversed_order else begin + count - 1\n        for index, (_slice, image) in slices_to_send:\n            emit('slice', {\n                'scan_id': scan_id,\n                'index': begin + index,\n                'last_in_batch': last_in_batch,\n                'image': image,\n            })\n\n    def _raise_on_invalid_request_slices(self, count: int, orientation: str) -> None:\n        \"\"\"Validate incoming request and raise an exception if there are issues with given arguments.\n\n        :param count: number of slices that should be returned\n        :param orientation: Slice's orientation as a string\n        \"\"\"\n        # Make sure that passed orientation is proper one\n        if orientation not in SliceOrientation.__members__:\n            raise InvalidArgumentsException('Invalid Slice orientation.')\n\n        # Make sure that nobody will fetch whole scan at once. It could freeze our backend application.\n        if count > self.MAX_NUMBER_OF_SLICES_PER_REQUEST:\n            message = 'Cannot return more than {} slices per request.'.format(self.MAX_NUMBER_OF_SLICES_PER_REQUEST)\n            raise InvalidArgumentsException(message)\n\n\n# Register above namespace\nweb_socket.on_namespace(Slices('/slices'))\n", "path": "backend/medtagger/api/scans/service_web_socket.py"}]}