We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[APP SUBMITTED]: TypeError: integer argument expected, got float
### INFO
**Python Version**: `2.7.13 (default, Apr 11 2017, 16:05:39) [GCC 4.8.4]`
**Operating System**: `Linux-4.2.8-x86_64-with-glibc2.2.5`
**Locale**: `UTF-8`
**Branch**: [master](../tree/master)
**Database**: `44.8`
**Commit**: pymedusa/Medusa@b16e0e5eb4ded727eebd2ab2cd9683ab597662f5
**Link to Log**: https://gist.github.com/28959ec35573f55afe29fc65ecbe8270
### ERROR
<pre>
2017-11-11 19:37:49 ERROR    TORNADO :: [b16e0e5] API :: 'integer argument expected, got float'
Traceback (most recent call last):
  File "/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href="../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/server/api/v1/core.py#L126">medusa/server/api/v1/core.py</a>", line 126, in get
    out_dict = _call_dispatcher(args, kwargs)
  File "/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href="../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/server/api/v1/core.py#L196">medusa/server/api/v1/core.py</a>", line 196, in call_dispatcher
    cur_out_dict = func(cur_args, cur_kwargs).run()  # call function and get response
  File "/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href="../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/server/api/v1/core.py#L1423">medusa/server/api/v1/core.py</a>", line 1423, in run
    next_backlog = app.backlog_search_scheduler.next_run().strftime(dateFormat).decode(app.SYS_ENCODING)
  File "/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href="../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/search/backlog.py#L33">medusa/search/backlog.py</a>", line 33, in next_run
    return datetime.date.fromordinal(self.action._last_backlog + self.action.cycleTime)
TypeError: integer argument expected, got float
</pre>
---
_STAFF NOTIFIED_: @pymedusa/support @pymedusa/moderators

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `medusa/search/backlog.py`
Content:
```
1 # coding=utf-8
2 
3 """Backlog module."""
4 
5 import datetime
6 import logging
7 import threading
8 
9 from medusa import app, common, db, scheduler, ui
10 from medusa.helper.common import episode_num
11 from medusa.logger.adapters.style import BraceAdapter
12 from medusa.search.queue import BacklogQueueItem
13 
14 from six import iteritems
15 
16 log = BraceAdapter(logging.getLogger(__name__))
17 log.logger.addHandler(logging.NullHandler())
18 
19 
20 class BacklogSearchScheduler(scheduler.Scheduler):
21     """Backlog search scheduler class."""
22 
23     def force_search(self):
24         """Set the last backlog in the DB."""
25         self.action._set_last_backlog(1)
26         self.lastRun = datetime.datetime.fromordinal(1)
27 
28     def next_run(self):
29         """Return when backlog should run next."""
30         if self.action._last_backlog <= 1:
31             return datetime.date.today()
32         else:
33             return datetime.date.fromordinal(self.action._last_backlog + self.action.cycleTime)
34 
35 
36 class BacklogSearcher(object):
37     """Backlog Searcher class."""
38 
39     def __init__(self):
40         """Initialize the class."""
41         self._last_backlog = self._get_last_backlog()
42         self.cycleTime = app.BACKLOG_FREQUENCY / 60.0 / 24
43         self.lock = threading.Lock()
44         self.amActive = False
45         self.amPaused = False
46         self.amWaiting = False
47         self.forced = False
48         self.currentSearchInfo = {}
49 
50         self._reset_pi()
51 
52     def _reset_pi(self):
53         """Reset percent done."""
54         self.percentDone = 0
55         self.currentSearchInfo = {'title': 'Initializing'}
56 
57     def get_progress_indicator(self):
58         """Get backlog search progress indicator."""
59         if self.amActive:
60             return ui.ProgressIndicator(self.percentDone, self.currentSearchInfo)
61         else:
62             return None
63 
64     def am_running(self):
65         """Check if backlog is running."""
66         log.debug(u'amWaiting: {0}, amActive: {1}', self.amWaiting, self.amActive)
67         return (not self.amWaiting) and self.amActive
68 
69     def search_backlog(self, which_shows=None):
70         """Run the backlog search for given shows."""
71         if self.amActive:
72             log.debug(u'Backlog is still running, not starting it again')
73             return
74 
75         if app.forced_search_queue_scheduler.action.is_forced_search_in_progress():
76             log.warning(u'Manual search is running. Unable to start Backlog Search')
77             return
78 
79         self.amActive = True
80         self.amPaused = False
81 
82         if which_shows:
83             show_list = which_shows
84         else:
85             show_list = app.showList
86 
87         self._get_last_backlog()
88 
89         cur_date = datetime.date.today().toordinal()
90         from_date = datetime.date.fromordinal(1)
91 
92         if not which_shows and self.forced:
93             log.info(u'Running limited backlog search on missed episodes from last {0} days',
94                      app.BACKLOG_DAYS)
95             from_date = datetime.date.today() - datetime.timedelta(days=app.BACKLOG_DAYS)
96         else:
97             log.info(u'Running full backlog search on missed episodes for selected shows')
98 
99         # go through non air-by-date shows and see if they need any episodes
100         for cur_show in show_list:
101 
102             if cur_show.paused:
103                 continue
104 
105             segments = self._get_segments(cur_show, from_date)
106 
107             for season, segment in iteritems(segments):
108                 self.currentSearchInfo = {'title': cur_show.name + ' Season ' + str(season)}
109 
110                 backlog_queue_item = BacklogQueueItem(cur_show, segment)
111                 app.search_queue_scheduler.action.add_item(backlog_queue_item)  # @UndefinedVariable
112 
113             if not segments:
114                 log.debug(u'Nothing needs to be downloaded for {0!r}, skipping', cur_show.name)
115 
116         # don't consider this an actual backlog search if we only did recent eps
117         # or if we only did certain shows
118         if from_date == datetime.date.fromordinal(1) and not which_shows:
119             self._set_last_backlog(cur_date)
120 
121         self.amActive = False
122         self._reset_pi()
123 
124     def _get_last_backlog(self):
125         """Get the last time backloged runned."""
126         log.debug(u'Retrieving the last check time from the DB')
127 
128         main_db_con = db.DBConnection()
129         sql_results = main_db_con.select('SELECT last_backlog '
130                                          'FROM info')
131 
132         if not sql_results:
133             last_backlog = 1
134         elif sql_results[0]['last_backlog'] is None or sql_results[0]['last_backlog'] == '':
135             last_backlog = 1
136         else:
137             last_backlog = int(sql_results[0]['last_backlog'])
138             if last_backlog > datetime.date.today().toordinal():
139                 last_backlog = 1
140 
141         self._last_backlog = last_backlog
142         return self._last_backlog
143 
144     @staticmethod
145     def _get_segments(show, from_date):
146         """Get episodes that should be backlog searched."""
147         wanted = {}
148         if show.paused:
149             log.debug(u'Skipping backlog for {0} because the show is paused', show.name)
150             return wanted
151 
152         log.debug(u'Seeing if we need anything from {0}', show.name)
153 
154         con = db.DBConnection()
155         sql_results = con.select(
156             'SELECT status, season, episode, manually_searched '
157             'FROM tv_episodes '
158             'WHERE airdate > ?'
159             ' AND showid = ?',
160             [from_date.toordinal(), show.indexerid]
161         )
162 
163         # check through the list of statuses to see if we want any
164         for sql_result in sql_results:
165             should_search, shold_search_reason = common.Quality.should_search(sql_result['status'], show,
166                                                                               sql_result['manually_searched'])
167             if not should_search:
168                 continue
169             log.debug(
170                 u'Found needed backlog episodes for: {show} {ep}. Reason: {reason}', {
171                     'show': show.name,
172                     'ep': episode_num(sql_result['season'], sql_result['episode']),
173                     'reason': shold_search_reason,
174                 }
175             )
176             ep_obj = show.get_episode(sql_result['season'], sql_result['episode'])
177 
178             if ep_obj.season not in wanted:
179                 wanted[ep_obj.season] = [ep_obj]
180             else:
181                 wanted[ep_obj.season].append(ep_obj)
182 
183         return wanted
184 
185     @staticmethod
186     def _set_last_backlog(when):
187         """Set the last backlog in the DB."""
188         log.debug(u'Setting the last backlog in the DB to {0}', when)
189 
190         main_db_con = db.DBConnection()
191         sql_results = main_db_con.select('SELECT last_backlog '
192                                          'FROM info')
193 
194         if not sql_results:
195             main_db_con.action('INSERT INTO info (last_backlog, last_indexer) '
196                                'VALUES (?,?)', [str(when), 0])
197         else:
198             main_db_con.action('UPDATE info '
199                                'SET last_backlog={0}'.format(when))
200 
201     def run(self, force=False):
202         """Run the backlog."""
203         try:
204             if force:
205                 self.forced = True
206             self.search_backlog()
207         except Exception:
208             self.amActive = False
209             raise
210
```
--- 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/medusa/search/backlog.py b/medusa/search/backlog.py
--- a/medusa/search/backlog.py
+++ b/medusa/search/backlog.py
@@ -30,7 +30,8 @@
         if self.action._last_backlog <= 1:
             return datetime.date.today()
         else:
-            return datetime.date.fromordinal(self.action._last_backlog + self.action.cycleTime)
+            backlog_frequency_in_days = int(self.action.cycleTime)
+            return datetime.date.fromordinal(self.action._last_backlog + backlog_frequency_in_days)
 
 
 class BacklogSearcher(object):

{"golden_diff": "diff --git a/medusa/search/backlog.py b/medusa/search/backlog.py\n--- a/medusa/search/backlog.py\n+++ b/medusa/search/backlog.py\n@@ -30,7 +30,8 @@\n         if self.action._last_backlog <= 1:\n             return datetime.date.today()\n         else:\n-            return datetime.date.fromordinal(self.action._last_backlog + self.action.cycleTime)\n+            backlog_frequency_in_days = int(self.action.cycleTime)\n+            return datetime.date.fromordinal(self.action._last_backlog + backlog_frequency_in_days)\n \n \n class BacklogSearcher(object):\n", "issue": "[APP SUBMITTED]: TypeError: integer argument expected, got float\n### INFO\n**Python Version**: `2.7.13 (default, Apr 11 2017, 16:05:39) [GCC 4.8.4]`\n**Operating System**: `Linux-4.2.8-x86_64-with-glibc2.2.5`\n**Locale**: `UTF-8`\n**Branch**: [master](../tree/master)\n**Database**: `44.8`\n**Commit**: pymedusa/Medusa@b16e0e5eb4ded727eebd2ab2cd9683ab597662f5\n**Link to Log**: https://gist.github.com/28959ec35573f55afe29fc65ecbe8270\n### ERROR\n<pre>\n2017-11-11 19:37:49 ERROR    TORNADO :: [b16e0e5] API :: 'integer argument expected, got float'\nTraceback (most recent call last):\n  File \"/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href=\"../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/server/api/v1/core.py#L126\">medusa/server/api/v1/core.py</a>\", line 126, in get\n    out_dict = _call_dispatcher(args, kwargs)\n  File \"/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href=\"../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/server/api/v1/core.py#L196\">medusa/server/api/v1/core.py</a>\", line 196, in call_dispatcher\n    cur_out_dict = func(cur_args, cur_kwargs).run()  # call function and get response\n  File \"/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href=\"../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/server/api/v1/core.py#L1423\">medusa/server/api/v1/core.py</a>\", line 1423, in run\n    next_backlog = app.backlog_search_scheduler.next_run().strftime(dateFormat).decode(app.SYS_ENCODING)\n  File \"/share/CACHEDEV1_DATA/.qpkg/Medusa/Medusa/<a href=\"../blob/b16e0e5eb4ded727eebd2ab2cd9683ab597662f5/medusa/search/backlog.py#L33\">medusa/search/backlog.py</a>\", line 33, in next_run\n    return datetime.date.fromordinal(self.action._last_backlog + self.action.cycleTime)\nTypeError: integer argument expected, got float\n</pre>\n---\n_STAFF NOTIFIED_: @pymedusa/support @pymedusa/moderators\n", "before_files": [{"content": "# coding=utf-8\n\n\"\"\"Backlog module.\"\"\"\n\nimport datetime\nimport logging\nimport threading\n\nfrom medusa import app, common, db, scheduler, ui\nfrom medusa.helper.common import episode_num\nfrom medusa.logger.adapters.style import BraceAdapter\nfrom medusa.search.queue import BacklogQueueItem\n\nfrom six import iteritems\n\nlog = BraceAdapter(logging.getLogger(__name__))\nlog.logger.addHandler(logging.NullHandler())\n\n\nclass BacklogSearchScheduler(scheduler.Scheduler):\n    \"\"\"Backlog search scheduler class.\"\"\"\n\n    def force_search(self):\n        \"\"\"Set the last backlog in the DB.\"\"\"\n        self.action._set_last_backlog(1)\n        self.lastRun = datetime.datetime.fromordinal(1)\n\n    def next_run(self):\n        \"\"\"Return when backlog should run next.\"\"\"\n        if self.action._last_backlog <= 1:\n            return datetime.date.today()\n        else:\n            return datetime.date.fromordinal(self.action._last_backlog + self.action.cycleTime)\n\n\nclass BacklogSearcher(object):\n    \"\"\"Backlog Searcher class.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize the class.\"\"\"\n        self._last_backlog = self._get_last_backlog()\n        self.cycleTime = app.BACKLOG_FREQUENCY / 60.0 / 24\n        self.lock = threading.Lock()\n        self.amActive = False\n        self.amPaused = False\n        self.amWaiting = False\n        self.forced = False\n        self.currentSearchInfo = {}\n\n        self._reset_pi()\n\n    def _reset_pi(self):\n        \"\"\"Reset percent done.\"\"\"\n        self.percentDone = 0\n        self.currentSearchInfo = {'title': 'Initializing'}\n\n    def get_progress_indicator(self):\n        \"\"\"Get backlog search progress indicator.\"\"\"\n        if self.amActive:\n            return ui.ProgressIndicator(self.percentDone, self.currentSearchInfo)\n        else:\n            return None\n\n    def am_running(self):\n        \"\"\"Check if backlog is running.\"\"\"\n        log.debug(u'amWaiting: {0}, amActive: {1}', self.amWaiting, self.amActive)\n        return (not self.amWaiting) and self.amActive\n\n    def search_backlog(self, which_shows=None):\n        \"\"\"Run the backlog search for given shows.\"\"\"\n        if self.amActive:\n            log.debug(u'Backlog is still running, not starting it again')\n            return\n\n        if app.forced_search_queue_scheduler.action.is_forced_search_in_progress():\n            log.warning(u'Manual search is running. Unable to start Backlog Search')\n            return\n\n        self.amActive = True\n        self.amPaused = False\n\n        if which_shows:\n            show_list = which_shows\n        else:\n            show_list = app.showList\n\n        self._get_last_backlog()\n\n        cur_date = datetime.date.today().toordinal()\n        from_date = datetime.date.fromordinal(1)\n\n        if not which_shows and self.forced:\n            log.info(u'Running limited backlog search on missed episodes from last {0} days',\n                     app.BACKLOG_DAYS)\n            from_date = datetime.date.today() - datetime.timedelta(days=app.BACKLOG_DAYS)\n        else:\n            log.info(u'Running full backlog search on missed episodes for selected shows')\n\n        # go through non air-by-date shows and see if they need any episodes\n        for cur_show in show_list:\n\n            if cur_show.paused:\n                continue\n\n            segments = self._get_segments(cur_show, from_date)\n\n            for season, segment in iteritems(segments):\n                self.currentSearchInfo = {'title': cur_show.name + ' Season ' + str(season)}\n\n                backlog_queue_item = BacklogQueueItem(cur_show, segment)\n                app.search_queue_scheduler.action.add_item(backlog_queue_item)  # @UndefinedVariable\n\n            if not segments:\n                log.debug(u'Nothing needs to be downloaded for {0!r}, skipping', cur_show.name)\n\n        # don't consider this an actual backlog search if we only did recent eps\n        # or if we only did certain shows\n        if from_date == datetime.date.fromordinal(1) and not which_shows:\n            self._set_last_backlog(cur_date)\n\n        self.amActive = False\n        self._reset_pi()\n\n    def _get_last_backlog(self):\n        \"\"\"Get the last time backloged runned.\"\"\"\n        log.debug(u'Retrieving the last check time from the DB')\n\n        main_db_con = db.DBConnection()\n        sql_results = main_db_con.select('SELECT last_backlog '\n                                         'FROM info')\n\n        if not sql_results:\n            last_backlog = 1\n        elif sql_results[0]['last_backlog'] is None or sql_results[0]['last_backlog'] == '':\n            last_backlog = 1\n        else:\n            last_backlog = int(sql_results[0]['last_backlog'])\n            if last_backlog > datetime.date.today().toordinal():\n                last_backlog = 1\n\n        self._last_backlog = last_backlog\n        return self._last_backlog\n\n    @staticmethod\n    def _get_segments(show, from_date):\n        \"\"\"Get episodes that should be backlog searched.\"\"\"\n        wanted = {}\n        if show.paused:\n            log.debug(u'Skipping backlog for {0} because the show is paused', show.name)\n            return wanted\n\n        log.debug(u'Seeing if we need anything from {0}', show.name)\n\n        con = db.DBConnection()\n        sql_results = con.select(\n            'SELECT status, season, episode, manually_searched '\n            'FROM tv_episodes '\n            'WHERE airdate > ?'\n            ' AND showid = ?',\n            [from_date.toordinal(), show.indexerid]\n        )\n\n        # check through the list of statuses to see if we want any\n        for sql_result in sql_results:\n            should_search, shold_search_reason = common.Quality.should_search(sql_result['status'], show,\n                                                                              sql_result['manually_searched'])\n            if not should_search:\n                continue\n            log.debug(\n                u'Found needed backlog episodes for: {show} {ep}. Reason: {reason}', {\n                    'show': show.name,\n                    'ep': episode_num(sql_result['season'], sql_result['episode']),\n                    'reason': shold_search_reason,\n                }\n            )\n            ep_obj = show.get_episode(sql_result['season'], sql_result['episode'])\n\n            if ep_obj.season not in wanted:\n                wanted[ep_obj.season] = [ep_obj]\n            else:\n                wanted[ep_obj.season].append(ep_obj)\n\n        return wanted\n\n    @staticmethod\n    def _set_last_backlog(when):\n        \"\"\"Set the last backlog in the DB.\"\"\"\n        log.debug(u'Setting the last backlog in the DB to {0}', when)\n\n        main_db_con = db.DBConnection()\n        sql_results = main_db_con.select('SELECT last_backlog '\n                                         'FROM info')\n\n        if not sql_results:\n            main_db_con.action('INSERT INTO info (last_backlog, last_indexer) '\n                               'VALUES (?,?)', [str(when), 0])\n        else:\n            main_db_con.action('UPDATE info '\n                               'SET last_backlog={0}'.format(when))\n\n    def run(self, force=False):\n        \"\"\"Run the backlog.\"\"\"\n        try:\n            if force:\n                self.forced = True\n            self.search_backlog()\n        except Exception:\n            self.amActive = False\n            raise\n", "path": "medusa/search/backlog.py"}], "after_files": [{"content": "# coding=utf-8\n\n\"\"\"Backlog module.\"\"\"\n\nimport datetime\nimport logging\nimport threading\n\nfrom medusa import app, common, db, scheduler, ui\nfrom medusa.helper.common import episode_num\nfrom medusa.logger.adapters.style import BraceAdapter\nfrom medusa.search.queue import BacklogQueueItem\n\nfrom six import iteritems\n\nlog = BraceAdapter(logging.getLogger(__name__))\nlog.logger.addHandler(logging.NullHandler())\n\n\nclass BacklogSearchScheduler(scheduler.Scheduler):\n    \"\"\"Backlog search scheduler class.\"\"\"\n\n    def force_search(self):\n        \"\"\"Set the last backlog in the DB.\"\"\"\n        self.action._set_last_backlog(1)\n        self.lastRun = datetime.datetime.fromordinal(1)\n\n    def next_run(self):\n        \"\"\"Return when backlog should run next.\"\"\"\n        if self.action._last_backlog <= 1:\n            return datetime.date.today()\n        else:\n            backlog_frequency_in_days = int(self.action.cycleTime)\n            return datetime.date.fromordinal(self.action._last_backlog + backlog_frequency_in_days)\n\n\nclass BacklogSearcher(object):\n    \"\"\"Backlog Searcher class.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize the class.\"\"\"\n        self._last_backlog = self._get_last_backlog()\n        self.cycleTime = app.BACKLOG_FREQUENCY / 60.0 / 24\n        self.lock = threading.Lock()\n        self.amActive = False\n        self.amPaused = False\n        self.amWaiting = False\n        self.forced = False\n        self.currentSearchInfo = {}\n\n        self._reset_pi()\n\n    def _reset_pi(self):\n        \"\"\"Reset percent done.\"\"\"\n        self.percentDone = 0\n        self.currentSearchInfo = {'title': 'Initializing'}\n\n    def get_progress_indicator(self):\n        \"\"\"Get backlog search progress indicator.\"\"\"\n        if self.amActive:\n            return ui.ProgressIndicator(self.percentDone, self.currentSearchInfo)\n        else:\n            return None\n\n    def am_running(self):\n        \"\"\"Check if backlog is running.\"\"\"\n        log.debug(u'amWaiting: {0}, amActive: {1}', self.amWaiting, self.amActive)\n        return (not self.amWaiting) and self.amActive\n\n    def search_backlog(self, which_shows=None):\n        \"\"\"Run the backlog search for given shows.\"\"\"\n        if self.amActive:\n            log.debug(u'Backlog is still running, not starting it again')\n            return\n\n        if app.forced_search_queue_scheduler.action.is_forced_search_in_progress():\n            log.warning(u'Manual search is running. Unable to start Backlog Search')\n            return\n\n        self.amActive = True\n        self.amPaused = False\n\n        if which_shows:\n            show_list = which_shows\n        else:\n            show_list = app.showList\n\n        self._get_last_backlog()\n\n        cur_date = datetime.date.today().toordinal()\n        from_date = datetime.date.fromordinal(1)\n\n        if not which_shows and self.forced:\n            log.info(u'Running limited backlog search on missed episodes from last {0} days',\n                     app.BACKLOG_DAYS)\n            from_date = datetime.date.today() - datetime.timedelta(days=app.BACKLOG_DAYS)\n        else:\n            log.info(u'Running full backlog search on missed episodes for selected shows')\n\n        # go through non air-by-date shows and see if they need any episodes\n        for cur_show in show_list:\n\n            if cur_show.paused:\n                continue\n\n            segments = self._get_segments(cur_show, from_date)\n\n            for season, segment in iteritems(segments):\n                self.currentSearchInfo = {'title': cur_show.name + ' Season ' + str(season)}\n\n                backlog_queue_item = BacklogQueueItem(cur_show, segment)\n                app.search_queue_scheduler.action.add_item(backlog_queue_item)  # @UndefinedVariable\n\n            if not segments:\n                log.debug(u'Nothing needs to be downloaded for {0!r}, skipping', cur_show.name)\n\n        # don't consider this an actual backlog search if we only did recent eps\n        # or if we only did certain shows\n        if from_date == datetime.date.fromordinal(1) and not which_shows:\n            self._set_last_backlog(cur_date)\n\n        self.amActive = False\n        self._reset_pi()\n\n    def _get_last_backlog(self):\n        \"\"\"Get the last time backloged runned.\"\"\"\n        log.debug(u'Retrieving the last check time from the DB')\n\n        main_db_con = db.DBConnection()\n        sql_results = main_db_con.select('SELECT last_backlog '\n                                         'FROM info')\n\n        if not sql_results:\n            last_backlog = 1\n        elif sql_results[0]['last_backlog'] is None or sql_results[0]['last_backlog'] == '':\n            last_backlog = 1\n        else:\n            last_backlog = int(sql_results[0]['last_backlog'])\n            if last_backlog > datetime.date.today().toordinal():\n                last_backlog = 1\n\n        self._last_backlog = last_backlog\n        return self._last_backlog\n\n    @staticmethod\n    def _get_segments(show, from_date):\n        \"\"\"Get episodes that should be backlog searched.\"\"\"\n        wanted = {}\n        if show.paused:\n            log.debug(u'Skipping backlog for {0} because the show is paused', show.name)\n            return wanted\n\n        log.debug(u'Seeing if we need anything from {0}', show.name)\n\n        con = db.DBConnection()\n        sql_results = con.select(\n            'SELECT status, season, episode, manually_searched '\n            'FROM tv_episodes '\n            'WHERE airdate > ?'\n            ' AND showid = ?',\n            [from_date.toordinal(), show.indexerid]\n        )\n\n        # check through the list of statuses to see if we want any\n        for sql_result in sql_results:\n            should_search, shold_search_reason = common.Quality.should_search(sql_result['status'], show,\n                                                                              sql_result['manually_searched'])\n            if not should_search:\n                continue\n            log.debug(\n                u'Found needed backlog episodes for: {show} {ep}. Reason: {reason}', {\n                    'show': show.name,\n                    'ep': episode_num(sql_result['season'], sql_result['episode']),\n                    'reason': shold_search_reason,\n                }\n            )\n            ep_obj = show.get_episode(sql_result['season'], sql_result['episode'])\n\n            if ep_obj.season not in wanted:\n                wanted[ep_obj.season] = [ep_obj]\n            else:\n                wanted[ep_obj.season].append(ep_obj)\n\n        return wanted\n\n    @staticmethod\n    def _set_last_backlog(when):\n        \"\"\"Set the last backlog in the DB.\"\"\"\n        log.debug(u'Setting the last backlog in the DB to {0}', when)\n\n        main_db_con = db.DBConnection()\n        sql_results = main_db_con.select('SELECT last_backlog '\n                                         'FROM info')\n\n        if not sql_results:\n            main_db_con.action('INSERT INTO info (last_backlog, last_indexer) '\n                               'VALUES (?,?)', [str(when), 0])\n        else:\n            main_db_con.action('UPDATE info '\n                               'SET last_backlog={0}'.format(when))\n\n    def run(self, force=False):\n        \"\"\"Run the backlog.\"\"\"\n        try:\n            if force:\n                self.forced = True\n            self.search_backlog()\n        except Exception:\n            self.amActive = False\n            raise\n", "path": "medusa/search/backlog.py"}]}