We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PootleCommand handles obsolete translation projects
`update_stores` command can make obsolete TP directory many times. 
It doesn't affect us much except we get extra unnecessary log messages like this:

```
set(['get_last_updated', 'get_checks', 'get_mtime', 'get_suggestion_count', 'get_last_action', 'get_wordcount_stats']) deleted from /uk/android_announcements_evernote/ cache
```

which tells us that cache for TP has been deleted.

I think any `PootleCommand` shouldn't handle TP with obsolete directories. `update_stores` command will resurrect TP directory when it's added.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pootle/apps/pootle_app/management/commands/__init__.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (C) Pootle contributors.
5 #
6 # This file is a part of the Pootle project. It is distributed under the GPL3
7 # or later license. See the LICENSE file for a copy of the license and the
8 # AUTHORS file for copyright and authorship information.
9 
10 import datetime
11 import logging
12 
13 from optparse import make_option
14 
15 from django.core.management.base import BaseCommand, NoArgsCommand
16 
17 from pootle.runner import set_sync_mode
18 from pootle_project.models import Project
19 from pootle_translationproject.models import TranslationProject
20 
21 
22 class PootleCommand(NoArgsCommand):
23     """Base class for handling recursive pootle store management commands."""
24 
25     shared_option_list = (
26         make_option(
27             '--project',
28             action='append',
29             dest='projects',
30             help='Project to refresh',
31         ),
32         make_option(
33             '--language',
34             action='append',
35             dest='languages',
36             help='Language to refresh',
37         ),
38         make_option(
39             "--noinput",
40             action="store_true",
41             default=False,
42             help=u"Never prompt for input",
43         ),
44         make_option(
45             "--no-rq",
46             action="store_true",
47             default=False,
48             help=(u"Run all jobs in a single process, without "
49                   "using rq workers"),
50         ),
51     )
52     option_list = NoArgsCommand.option_list + shared_option_list
53     process_disabled_projects = False
54 
55     def __init__(self, *args, **kwargs):
56         self.languages = []
57         self.projects = []
58         super(PootleCommand, self).__init__(*args, **kwargs)
59 
60     def do_translation_project(self, tp, **options):
61         process_stores = True
62 
63         if hasattr(self, "handle_translation_project"):
64             logging.info(u"Running %s over %s", self.name, tp)
65             try:
66                 process_stores = self.handle_translation_project(tp, **options)
67             except Exception:
68                 logging.exception(u"Failed to run %s over %s", self.name, tp)
69                 return
70 
71             if not process_stores:
72                 return
73 
74         if hasattr(self, "handle_all_stores"):
75             logging.info(u"Running %s over %s's files", self.name, tp)
76             try:
77                 self.handle_all_stores(tp, **options)
78             except Exception:
79                 logging.exception(u"Failed to run %s over %s's files",
80                                   self.name, tp)
81                 return
82         elif hasattr(self, "handle_store"):
83             store_query = tp.stores.live()
84             for store in store_query.iterator():
85                 logging.info(u"Running %s over %s",
86                              self.name, store.pootle_path)
87                 try:
88                     self.handle_store(store, **options)
89                 except Exception:
90                     logging.exception(u"Failed to run %s over %s",
91                                       self.name, store.pootle_path)
92 
93     def handle_noargs(self, **options):
94         # adjust debug level to the verbosity option
95         verbosity = int(options.get('verbosity', 1))
96         debug_levels = {
97             0: logging.ERROR,
98             1: logging.WARNING,
99             2: logging.INFO,
100             3: logging.DEBUG
101         }
102         debug_level = debug_levels.get(verbosity, logging.DEBUG)
103         logging.getLogger().setLevel(debug_level)
104 
105         # reduce size of parse pool early on
106         self.name = self.__class__.__module__.split('.')[-1]
107         from pootle_store.fields import TranslationStoreFieldFile
108         TranslationStoreFieldFile._store_cache.maxsize = 2
109         TranslationStoreFieldFile._store_cache.cullsize = 2
110         TranslationProject._non_db_state_cache.maxsize = 2
111         TranslationProject._non_db_state_cache.cullsize = 2
112 
113         self.projects = options.pop('projects', [])
114         self.languages = options.pop('languages', [])
115 
116         # info start
117         start = datetime.datetime.now()
118         logging.info('Start running of %s', self.name)
119 
120         self.handle_all(**options)
121 
122         # info finish
123         end = datetime.datetime.now()
124         logging.info('All done for %s in %s', self.name, end - start)
125 
126     def handle_all(self, **options):
127         if options.get("no_rq", False):
128             set_sync_mode(options.get('noinput', False))
129 
130         if self.process_disabled_projects:
131             project_query = Project.objects.all()
132         else:
133             project_query = Project.objects.enabled()
134 
135         if self.projects:
136             project_query = project_query.filter(code__in=self.projects)
137 
138         for project in project_query.iterator():
139             tp_query = project.translationproject_set \
140                               .order_by('language__code')
141 
142             if self.languages:
143                 tp_query = tp_query.filter(language__code__in=self.languages)
144 
145             for tp in tp_query.iterator():
146                 self.do_translation_project(tp, **options)
147 
148 
149 class BaseRunCommand(BaseCommand):
150     """Base class to build new server runners.
151 
152     Based on code from `django-shoes
153     <https://bitbucket.org/mlzboy/django-shoes/>`_.
154     """
155 
156     hostport_option_list = (
157         make_option(
158             '--host',
159             action='store',
160             dest='host',
161             default='127.0.0.1',
162             help='Hostname to listen on.',
163         ),
164         make_option(
165             '--port',
166             action='store',
167             dest='port',
168             default=8000,
169             type=int,
170             help='The TCP port to listen on.',
171         ),
172     )
173 
174     option_list = BaseCommand.option_list + hostport_option_list
175 
176     def handle(self, *args, **options):
177         return self.serve_forever(*args, **options)
178 
179     def get_app(self):
180         from django.contrib.staticfiles.handlers import StaticFilesHandler
181         from django.core.handlers.wsgi import WSGIHandler
182 
183         app = StaticFilesHandler(WSGIHandler())
184         return app
185 
186     def serve_forever(self, *args, **kwargs):
187         raise NotImplementedError
188
```
--- 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/pootle/apps/pootle_app/management/commands/__init__.py b/pootle/apps/pootle_app/management/commands/__init__.py
--- a/pootle/apps/pootle_app/management/commands/__init__.py
+++ b/pootle/apps/pootle_app/management/commands/__init__.py
@@ -136,7 +136,7 @@
             project_query = project_query.filter(code__in=self.projects)
 
         for project in project_query.iterator():
-            tp_query = project.translationproject_set \
+            tp_query = project.translationproject_set.live() \
                               .order_by('language__code')
 
             if self.languages:

{"golden_diff": "diff --git a/pootle/apps/pootle_app/management/commands/__init__.py b/pootle/apps/pootle_app/management/commands/__init__.py\n--- a/pootle/apps/pootle_app/management/commands/__init__.py\n+++ b/pootle/apps/pootle_app/management/commands/__init__.py\n@@ -136,7 +136,7 @@\n             project_query = project_query.filter(code__in=self.projects)\n \n         for project in project_query.iterator():\n-            tp_query = project.translationproject_set \\\n+            tp_query = project.translationproject_set.live() \\\n                               .order_by('language__code')\n \n             if self.languages:\n", "issue": "PootleCommand handles obsolete translation projects\n`update_stores` command can make obsolete TP directory many times. \nIt doesn't affect us much except we get extra unnecessary log messages like this:\n\n```\nset(['get_last_updated', 'get_checks', 'get_mtime', 'get_suggestion_count', 'get_last_action', 'get_wordcount_stats']) deleted from /uk/android_announcements_evernote/ cache\n```\n\nwhich tells us that cache for TP has been deleted.\n\nI think any `PootleCommand` shouldn't handle TP with obsolete directories. `update_stores` command will resurrect TP directory when it's added.\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport datetime\nimport logging\n\nfrom optparse import make_option\n\nfrom django.core.management.base import BaseCommand, NoArgsCommand\n\nfrom pootle.runner import set_sync_mode\nfrom pootle_project.models import Project\nfrom pootle_translationproject.models import TranslationProject\n\n\nclass PootleCommand(NoArgsCommand):\n    \"\"\"Base class for handling recursive pootle store management commands.\"\"\"\n\n    shared_option_list = (\n        make_option(\n            '--project',\n            action='append',\n            dest='projects',\n            help='Project to refresh',\n        ),\n        make_option(\n            '--language',\n            action='append',\n            dest='languages',\n            help='Language to refresh',\n        ),\n        make_option(\n            \"--noinput\",\n            action=\"store_true\",\n            default=False,\n            help=u\"Never prompt for input\",\n        ),\n        make_option(\n            \"--no-rq\",\n            action=\"store_true\",\n            default=False,\n            help=(u\"Run all jobs in a single process, without \"\n                  \"using rq workers\"),\n        ),\n    )\n    option_list = NoArgsCommand.option_list + shared_option_list\n    process_disabled_projects = False\n\n    def __init__(self, *args, **kwargs):\n        self.languages = []\n        self.projects = []\n        super(PootleCommand, self).__init__(*args, **kwargs)\n\n    def do_translation_project(self, tp, **options):\n        process_stores = True\n\n        if hasattr(self, \"handle_translation_project\"):\n            logging.info(u\"Running %s over %s\", self.name, tp)\n            try:\n                process_stores = self.handle_translation_project(tp, **options)\n            except Exception:\n                logging.exception(u\"Failed to run %s over %s\", self.name, tp)\n                return\n\n            if not process_stores:\n                return\n\n        if hasattr(self, \"handle_all_stores\"):\n            logging.info(u\"Running %s over %s's files\", self.name, tp)\n            try:\n                self.handle_all_stores(tp, **options)\n            except Exception:\n                logging.exception(u\"Failed to run %s over %s's files\",\n                                  self.name, tp)\n                return\n        elif hasattr(self, \"handle_store\"):\n            store_query = tp.stores.live()\n            for store in store_query.iterator():\n                logging.info(u\"Running %s over %s\",\n                             self.name, store.pootle_path)\n                try:\n                    self.handle_store(store, **options)\n                except Exception:\n                    logging.exception(u\"Failed to run %s over %s\",\n                                      self.name, store.pootle_path)\n\n    def handle_noargs(self, **options):\n        # adjust debug level to the verbosity option\n        verbosity = int(options.get('verbosity', 1))\n        debug_levels = {\n            0: logging.ERROR,\n            1: logging.WARNING,\n            2: logging.INFO,\n            3: logging.DEBUG\n        }\n        debug_level = debug_levels.get(verbosity, logging.DEBUG)\n        logging.getLogger().setLevel(debug_level)\n\n        # reduce size of parse pool early on\n        self.name = self.__class__.__module__.split('.')[-1]\n        from pootle_store.fields import TranslationStoreFieldFile\n        TranslationStoreFieldFile._store_cache.maxsize = 2\n        TranslationStoreFieldFile._store_cache.cullsize = 2\n        TranslationProject._non_db_state_cache.maxsize = 2\n        TranslationProject._non_db_state_cache.cullsize = 2\n\n        self.projects = options.pop('projects', [])\n        self.languages = options.pop('languages', [])\n\n        # info start\n        start = datetime.datetime.now()\n        logging.info('Start running of %s', self.name)\n\n        self.handle_all(**options)\n\n        # info finish\n        end = datetime.datetime.now()\n        logging.info('All done for %s in %s', self.name, end - start)\n\n    def handle_all(self, **options):\n        if options.get(\"no_rq\", False):\n            set_sync_mode(options.get('noinput', False))\n\n        if self.process_disabled_projects:\n            project_query = Project.objects.all()\n        else:\n            project_query = Project.objects.enabled()\n\n        if self.projects:\n            project_query = project_query.filter(code__in=self.projects)\n\n        for project in project_query.iterator():\n            tp_query = project.translationproject_set \\\n                              .order_by('language__code')\n\n            if self.languages:\n                tp_query = tp_query.filter(language__code__in=self.languages)\n\n            for tp in tp_query.iterator():\n                self.do_translation_project(tp, **options)\n\n\nclass BaseRunCommand(BaseCommand):\n    \"\"\"Base class to build new server runners.\n\n    Based on code from `django-shoes\n    <https://bitbucket.org/mlzboy/django-shoes/>`_.\n    \"\"\"\n\n    hostport_option_list = (\n        make_option(\n            '--host',\n            action='store',\n            dest='host',\n            default='127.0.0.1',\n            help='Hostname to listen on.',\n        ),\n        make_option(\n            '--port',\n            action='store',\n            dest='port',\n            default=8000,\n            type=int,\n            help='The TCP port to listen on.',\n        ),\n    )\n\n    option_list = BaseCommand.option_list + hostport_option_list\n\n    def handle(self, *args, **options):\n        return self.serve_forever(*args, **options)\n\n    def get_app(self):\n        from django.contrib.staticfiles.handlers import StaticFilesHandler\n        from django.core.handlers.wsgi import WSGIHandler\n\n        app = StaticFilesHandler(WSGIHandler())\n        return app\n\n    def serve_forever(self, *args, **kwargs):\n        raise NotImplementedError\n", "path": "pootle/apps/pootle_app/management/commands/__init__.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport datetime\nimport logging\n\nfrom optparse import make_option\n\nfrom django.core.management.base import BaseCommand, NoArgsCommand\n\nfrom pootle.runner import set_sync_mode\nfrom pootle_project.models import Project\nfrom pootle_translationproject.models import TranslationProject\n\n\nclass PootleCommand(NoArgsCommand):\n    \"\"\"Base class for handling recursive pootle store management commands.\"\"\"\n\n    shared_option_list = (\n        make_option(\n            '--project',\n            action='append',\n            dest='projects',\n            help='Project to refresh',\n        ),\n        make_option(\n            '--language',\n            action='append',\n            dest='languages',\n            help='Language to refresh',\n        ),\n        make_option(\n            \"--noinput\",\n            action=\"store_true\",\n            default=False,\n            help=u\"Never prompt for input\",\n        ),\n        make_option(\n            \"--no-rq\",\n            action=\"store_true\",\n            default=False,\n            help=(u\"Run all jobs in a single process, without \"\n                  \"using rq workers\"),\n        ),\n    )\n    option_list = NoArgsCommand.option_list + shared_option_list\n    process_disabled_projects = False\n\n    def __init__(self, *args, **kwargs):\n        self.languages = []\n        self.projects = []\n        super(PootleCommand, self).__init__(*args, **kwargs)\n\n    def do_translation_project(self, tp, **options):\n        process_stores = True\n\n        if hasattr(self, \"handle_translation_project\"):\n            logging.info(u\"Running %s over %s\", self.name, tp)\n            try:\n                process_stores = self.handle_translation_project(tp, **options)\n            except Exception:\n                logging.exception(u\"Failed to run %s over %s\", self.name, tp)\n                return\n\n            if not process_stores:\n                return\n\n        if hasattr(self, \"handle_all_stores\"):\n            logging.info(u\"Running %s over %s's files\", self.name, tp)\n            try:\n                self.handle_all_stores(tp, **options)\n            except Exception:\n                logging.exception(u\"Failed to run %s over %s's files\",\n                                  self.name, tp)\n                return\n        elif hasattr(self, \"handle_store\"):\n            store_query = tp.stores.live()\n            for store in store_query.iterator():\n                logging.info(u\"Running %s over %s\",\n                             self.name, store.pootle_path)\n                try:\n                    self.handle_store(store, **options)\n                except Exception:\n                    logging.exception(u\"Failed to run %s over %s\",\n                                      self.name, store.pootle_path)\n\n    def handle_noargs(self, **options):\n        # adjust debug level to the verbosity option\n        verbosity = int(options.get('verbosity', 1))\n        debug_levels = {\n            0: logging.ERROR,\n            1: logging.WARNING,\n            2: logging.INFO,\n            3: logging.DEBUG\n        }\n        debug_level = debug_levels.get(verbosity, logging.DEBUG)\n        logging.getLogger().setLevel(debug_level)\n\n        # reduce size of parse pool early on\n        self.name = self.__class__.__module__.split('.')[-1]\n        from pootle_store.fields import TranslationStoreFieldFile\n        TranslationStoreFieldFile._store_cache.maxsize = 2\n        TranslationStoreFieldFile._store_cache.cullsize = 2\n        TranslationProject._non_db_state_cache.maxsize = 2\n        TranslationProject._non_db_state_cache.cullsize = 2\n\n        self.projects = options.pop('projects', [])\n        self.languages = options.pop('languages', [])\n\n        # info start\n        start = datetime.datetime.now()\n        logging.info('Start running of %s', self.name)\n\n        self.handle_all(**options)\n\n        # info finish\n        end = datetime.datetime.now()\n        logging.info('All done for %s in %s', self.name, end - start)\n\n    def handle_all(self, **options):\n        if options.get(\"no_rq\", False):\n            set_sync_mode(options.get('noinput', False))\n\n        if self.process_disabled_projects:\n            project_query = Project.objects.all()\n        else:\n            project_query = Project.objects.enabled()\n\n        if self.projects:\n            project_query = project_query.filter(code__in=self.projects)\n\n        for project in project_query.iterator():\n            tp_query = project.translationproject_set.live() \\\n                              .order_by('language__code')\n\n            if self.languages:\n                tp_query = tp_query.filter(language__code__in=self.languages)\n\n            for tp in tp_query.iterator():\n                self.do_translation_project(tp, **options)\n\n\nclass BaseRunCommand(BaseCommand):\n    \"\"\"Base class to build new server runners.\n\n    Based on code from `django-shoes\n    <https://bitbucket.org/mlzboy/django-shoes/>`_.\n    \"\"\"\n\n    hostport_option_list = (\n        make_option(\n            '--host',\n            action='store',\n            dest='host',\n            default='127.0.0.1',\n            help='Hostname to listen on.',\n        ),\n        make_option(\n            '--port',\n            action='store',\n            dest='port',\n            default=8000,\n            type=int,\n            help='The TCP port to listen on.',\n        ),\n    )\n\n    option_list = BaseCommand.option_list + hostport_option_list\n\n    def handle(self, *args, **options):\n        return self.serve_forever(*args, **options)\n\n    def get_app(self):\n        from django.contrib.staticfiles.handlers import StaticFilesHandler\n        from django.core.handlers.wsgi import WSGIHandler\n\n        app = StaticFilesHandler(WSGIHandler())\n        return app\n\n    def serve_forever(self, *args, **kwargs):\n        raise NotImplementedError\n", "path": "pootle/apps/pootle_app/management/commands/__init__.py"}]}