We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Language dropdown not showing template languages
_Version: 2.5.1_

The language dropdown menu is only displaying languages that are _not_ specified as source language in any project.

Deactivating this filter shows all possible languages and does not seem to have any undesirable side effects:

``` diff
diff --git a/pootle/apps/pootle_language/models.py b/pootle/apps/pootle_language/models.py
index 03dbd96..9611602 100644
--- a/pootle/apps/pootle_language/models.py
+++ b/pootle/apps/pootle_language/models.py
@@ -56,7 +56,6 @@ class LiveLanguageManager(models.Manager):
         return super(LiveLanguageManager, self).get_query_set().filter(
                 ~models.Q(code='templates'),
                 translationproject__isnull=False,
-                project__isnull=True,
             ).distinct()
```


--- 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_language/models.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) Pootle contributors.
4 #
5 # This file is a part of the Pootle project. It is distributed under the GPL3
6 # or later license. See the LICENSE file for a copy of the license and the
7 # AUTHORS file for copyright and authorship information.
8 
9 import locale
10 from collections import OrderedDict
11 
12 from django.conf import settings
13 from django.core.cache import cache
14 from django.core.urlresolvers import reverse
15 from django.db import models
16 from django.db.models.signals import post_delete, post_save
17 from django.dispatch import receiver
18 
19 from pootle.core.cache import make_method_key
20 from pootle.core.mixins import TreeItem
21 from pootle.core.url_helpers import get_editor_filter
22 from pootle.i18n.gettext import language_dir, tr_lang, ugettext_lazy as _
23 from staticpages.models import StaticPage
24 
25 
26 class LiveLanguageManager(models.Manager):
27     """Manager that only considers `live` languages.
28 
29     A live language is any language containing at least a project with
30     translatable files.
31     """
32 
33     def get_queryset(self):
34         return super(LiveLanguageManager, self).get_queryset().filter(
35             translationproject__isnull=False,
36             project__isnull=True,
37         ).distinct()
38 
39     def cached_dict(self, locale_code='en-us'):
40         """Retrieves a sorted list of live language codes and names.
41 
42         :param locale_code: the UI locale for which language full names need to
43             be localized.
44         :return: an `OrderedDict`
45         """
46         key = make_method_key(self, 'cached_dict', locale_code)
47         languages = cache.get(key, None)
48         if languages is None:
49             languages = OrderedDict(
50                 sorted([(lang[0], tr_lang(lang[1]))
51                         for lang in self.values_list('code', 'fullname')],
52                        cmp=locale.strcoll,
53                        key=lambda x: x[1])
54             )
55             cache.set(key, languages, settings.POOTLE_CACHE_TIMEOUT)
56 
57         return languages
58 
59 
60 class Language(models.Model, TreeItem):
61 
62     # any changes to the `code` field may require updating the schema
63     # see migration 0002_case_insensitive_schema.py
64     code = models.CharField(
65         max_length=50, null=False, unique=True, db_index=True,
66         verbose_name=_("Code"),
67         help_text=_('ISO 639 language code for the language, possibly '
68                     'followed by an underscore (_) and an ISO 3166 country '
69                     'code. <a href="http://www.w3.org/International/'
70                     'articles/language-tags/">More information</a>')
71     )
72     fullname = models.CharField(max_length=255, null=False,
73                                 verbose_name=_("Full Name"))
74 
75     specialchars = models.CharField(
76         max_length=255, blank=True, verbose_name=_("Special Characters"),
77         help_text=_('Enter any special characters that users might find '
78                     'difficult to type')
79     )
80 
81     plurals_help_text = _('For more information, visit '
82                           '<a href="http://docs.translatehouse.org/projects/'
83                           'localization-guide/en/latest/l10n/'
84                           'pluralforms.html">'
85                           'our page</a> on plural forms.')
86     nplural_choices = (
87         (0, _('Unknown')), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)
88     )
89     nplurals = models.SmallIntegerField(
90         default=0, choices=nplural_choices,
91         verbose_name=_("Number of Plurals"), help_text=plurals_help_text
92     )
93     pluralequation = models.CharField(
94         max_length=255, blank=True, verbose_name=_("Plural Equation"),
95         help_text=plurals_help_text)
96 
97     directory = models.OneToOneField('pootle_app.Directory', db_index=True,
98                                      editable=False)
99 
100     objects = models.Manager()
101     live = LiveLanguageManager()
102 
103     class Meta(object):
104         ordering = ['code']
105         db_table = 'pootle_app_language'
106 
107     # # # # # # # # # # # # # #  Properties # # # # # # # # # # # # # # # # # #
108 
109     @property
110     def pootle_path(self):
111         return '/%s/' % self.code
112 
113     @property
114     def name(self):
115         """Localized fullname for the language."""
116         return tr_lang(self.fullname)
117 
118     @property
119     def direction(self):
120         """Return the language direction."""
121         return language_dir(self.code)
122 
123     # # # # # # # # # # # # # #  Methods # # # # # # # # # # # # # # # # # # #
124 
125     @classmethod
126     def get_canonical(cls, language_code):
127         """Returns the canonical `Language` object matching `language_code`.
128 
129         If no language can be matched, `None` will be returned.
130 
131         :param language_code: the code of the language to retrieve.
132         """
133         try:
134             return cls.objects.get(code__iexact=language_code)
135         except cls.DoesNotExist:
136             _lang_code = language_code
137             if "-" in language_code:
138                 _lang_code = language_code.replace("-", "_")
139             elif "_" in language_code:
140                 _lang_code = language_code.replace("_", "-")
141             try:
142                 return cls.objects.get(code__iexact=_lang_code)
143             except cls.DoesNotExist:
144                 return None
145 
146     def __unicode__(self):
147         return u"%s - %s" % (self.name, self.code)
148 
149     def __init__(self, *args, **kwargs):
150         super(Language, self).__init__(*args, **kwargs)
151 
152     def __repr__(self):
153         return u'<%s: %s>' % (self.__class__.__name__, self.fullname)
154 
155     def save(self, *args, **kwargs):
156         # create corresponding directory object
157         from pootle_app.models.directory import Directory
158         self.directory = Directory.objects.root.get_or_make_subdir(self.code)
159 
160         super(Language, self).save(*args, **kwargs)
161 
162     def delete(self, *args, **kwargs):
163         directory = self.directory
164         super(Language, self).delete(*args, **kwargs)
165         directory.delete()
166 
167     def get_absolute_url(self):
168         return reverse('pootle-language-browse', args=[self.code])
169 
170     def get_translate_url(self, **kwargs):
171         return u''.join([
172             reverse('pootle-language-translate', args=[self.code]),
173             get_editor_filter(**kwargs),
174         ])
175 
176     def clean(self):
177         super(Language, self).clean()
178 
179         if self.fullname:
180             self.fullname = self.fullname.strip()
181 
182     # # # TreeItem
183 
184     def get_children(self):
185         return self.translationproject_set.live()
186 
187     def get_cachekey(self):
188         return self.directory.pootle_path
189 
190     # # # /TreeItem
191 
192     def get_stats_for_user(self, user):
193         self.set_children(self.get_children_for_user(user))
194         return self.get_stats()
195 
196     def get_children_for_user(self, user, select_related=None):
197         return self.translationproject_set.for_user(
198             user, select_related=select_related
199         ).select_related(
200             "project"
201         ).order_by('project__fullname')
202 
203     def get_announcement(self, user=None):
204         """Return the related announcement, if any."""
205         return StaticPage.get_announcement_for(self.pootle_path, user)
206 
207 
208 @receiver([post_delete, post_save])
209 def invalidate_language_list_cache(**kwargs):
210     instance = kwargs["instance"]
211     # XXX: maybe use custom signals or simple function calls?
212     if instance.__class__.__name__ not in ['Language', 'TranslationProject']:
213         return
214 
215     key = make_method_key('LiveLanguageManager', 'cached_dict', '*')
216     cache.delete_pattern(key)
217
```

Path: `pootle/apps/pootle_app/views/index/index.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) Pootle contributors.
4 #
5 # This file is a part of the Pootle project. It is distributed under the GPL3
6 # or later license. See the LICENSE file for a copy of the license and the
7 # AUTHORS file for copyright and authorship information.
8 
9 from django.contrib.auth import REDIRECT_FIELD_NAME
10 from django.core.urlresolvers import reverse
11 from django.shortcuts import redirect, render
12 from django.views.generic import TemplateView
13 
14 from pootle.i18n.override import get_lang_from_http_header
15 from pootle_language.models import Language
16 
17 
18 COOKIE_NAME = 'pootle-language'
19 
20 
21 def view(request):
22     if not request.user.is_authenticated():
23         ctx = {
24             'next': request.GET.get(REDIRECT_FIELD_NAME, ''),
25         }
26         return render(request, 'welcome.html', ctx)
27 
28     lang = request.COOKIES.get(COOKIE_NAME, None)
29 
30     if lang is None:
31         supported = Language.live.cached_dict()
32         lang = get_lang_from_http_header(request, supported)
33 
34     if lang is not None and lang not in ('projects', ''):
35         url = reverse('pootle-language-browse', args=[lang])
36     else:
37         url = reverse('pootle-projects-browse')
38 
39     # Preserve query strings
40     args = request.GET.urlencode()
41     qs = '?%s' % args if args else ''
42     redirect_url = '%s%s' % (url, qs)
43 
44     return redirect(redirect_url)
45 
46 
47 class AboutView(TemplateView):
48     template_name = 'about.html'
49 
50     def get_context_data(self, **kwargs):
51         from translate.__version__ import sver as toolkit_version
52         from pootle import __version__
53 
54         return {
55             'pootle_version': __version__,
56             'toolkit_version': toolkit_version,
57         }
58
```

Path: `pootle/apps/pootle_misc/context_processors.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) Pootle contributors.
4 #
5 # This file is a part of the Pootle project. It is distributed under the GPL3
6 # or later license. See the LICENSE file for a copy of the license and the
7 # AUTHORS file for copyright and authorship information.
8 
9 from django.conf import settings
10 from django.utils import translation
11 
12 from pootle.core.markup import get_markup_filter_name
13 from pootle_language.models import Language
14 from pootle_project.models import Project
15 from staticpages.models import LegalPage
16 
17 
18 def _agreement_context(request):
19     """Returns whether the agreement box should be displayed or not."""
20     request_path = request.META['PATH_INFO']
21     nocheck = filter(lambda x: request_path.startswith(x),
22                      settings.POOTLE_LEGALPAGE_NOCHECK_PREFIXES)
23 
24     if (request.user.is_authenticated() and not nocheck and
25         LegalPage.objects.has_pending_agreement(request.user)):
26         return True
27 
28     return False
29 
30 
31 def _get_social_auth_providers(request):
32     if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
33         return []
34 
35     from allauth.socialaccount import providers
36     return [{'name': provider.name, 'url': provider.get_login_url(request)}
37             for provider in providers.registry.get_list()]
38 
39 
40 def pootle_context(request):
41     """Exposes settings to templates."""
42     # FIXME: maybe we should expose relevant settings only?
43     return {
44         'settings': {
45             'POOTLE_TITLE': settings.POOTLE_TITLE,
46             'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID,
47             'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and
48                                        settings.POOTLE_CONTACT_EMAIL),
49             'POOTLE_MARKUP_FILTER': get_markup_filter_name(),
50             'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED,
51             'SCRIPT_NAME': settings.SCRIPT_NAME,
52             'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT,
53             'DEBUG': settings.DEBUG,
54         },
55         'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT,
56         'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language()),
57         'ALL_PROJECTS': Project.objects.cached_dict(request.user),
58         'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request),
59         'display_agreement': _agreement_context(request),
60     }
61
```
--- 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/views/index/index.py b/pootle/apps/pootle_app/views/index/index.py
--- a/pootle/apps/pootle_app/views/index/index.py
+++ b/pootle/apps/pootle_app/views/index/index.py
@@ -28,7 +28,9 @@
     lang = request.COOKIES.get(COOKIE_NAME, None)
 
     if lang is None:
-        supported = Language.live.cached_dict()
+        supported = Language.live.cached_dict(
+            show_all=request.user.is_superuser
+        )
         lang = get_lang_from_http_header(request, supported)
 
     if lang is not None and lang not in ('projects', ''):
diff --git a/pootle/apps/pootle_language/models.py b/pootle/apps/pootle_language/models.py
--- a/pootle/apps/pootle_language/models.py
+++ b/pootle/apps/pootle_language/models.py
@@ -31,24 +31,41 @@
     """
 
     def get_queryset(self):
+        """Returns a queryset for all live languages for enabled projects."""
         return super(LiveLanguageManager, self).get_queryset().filter(
             translationproject__isnull=False,
-            project__isnull=True,
+            translationproject__directory__obsolete=False,
+            translationproject__project__disabled=False,
         ).distinct()
 
-    def cached_dict(self, locale_code='en-us'):
+    def get_all_queryset(self):
+        """Returns a queryset for all live languages for all projects."""
+        return super(LiveLanguageManager, self).get_queryset().filter(
+            translationproject__isnull=False,
+            translationproject__directory__obsolete=False,
+        ).distinct()
+
+    def cached_dict(self, locale_code='en-us', show_all=False):
         """Retrieves a sorted list of live language codes and names.
 
+        By default only returns live languages for enabled projects, but it can
+        also return live languages for disabled projects if specified.
+
         :param locale_code: the UI locale for which language full names need to
             be localized.
+        :param show_all: tells whether to return all live languages (both for
+            disabled and enabled projects) or only live languages for enabled
+            projects.
         :return: an `OrderedDict`
         """
-        key = make_method_key(self, 'cached_dict', locale_code)
+        key_prefix = 'all_cached_dict' if show_all else 'cached_dict'
+        key = make_method_key(self, key_prefix, locale_code)
         languages = cache.get(key, None)
         if languages is None:
+            qs = self.get_all_queryset() if show_all else self.get_queryset()
             languages = OrderedDict(
                 sorted([(lang[0], tr_lang(lang[1]))
-                        for lang in self.values_list('code', 'fullname')],
+                        for lang in qs.values_list('code', 'fullname')],
                        cmp=locale.strcoll,
                        key=lambda x: x[1])
             )
diff --git a/pootle/apps/pootle_misc/context_processors.py b/pootle/apps/pootle_misc/context_processors.py
--- a/pootle/apps/pootle_misc/context_processors.py
+++ b/pootle/apps/pootle_misc/context_processors.py
@@ -53,7 +53,8 @@
             'DEBUG': settings.DEBUG,
         },
         'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT,
-        'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language()),
+        'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language(),
+                                                   request.user.is_superuser),
         'ALL_PROJECTS': Project.objects.cached_dict(request.user),
         'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request),
         'display_agreement': _agreement_context(request),

{"golden_diff": "diff --git a/pootle/apps/pootle_app/views/index/index.py b/pootle/apps/pootle_app/views/index/index.py\n--- a/pootle/apps/pootle_app/views/index/index.py\n+++ b/pootle/apps/pootle_app/views/index/index.py\n@@ -28,7 +28,9 @@\n     lang = request.COOKIES.get(COOKIE_NAME, None)\n \n     if lang is None:\n-        supported = Language.live.cached_dict()\n+        supported = Language.live.cached_dict(\n+            show_all=request.user.is_superuser\n+        )\n         lang = get_lang_from_http_header(request, supported)\n \n     if lang is not None and lang not in ('projects', ''):\ndiff --git a/pootle/apps/pootle_language/models.py b/pootle/apps/pootle_language/models.py\n--- a/pootle/apps/pootle_language/models.py\n+++ b/pootle/apps/pootle_language/models.py\n@@ -31,24 +31,41 @@\n     \"\"\"\n \n     def get_queryset(self):\n+        \"\"\"Returns a queryset for all live languages for enabled projects.\"\"\"\n         return super(LiveLanguageManager, self).get_queryset().filter(\n             translationproject__isnull=False,\n-            project__isnull=True,\n+            translationproject__directory__obsolete=False,\n+            translationproject__project__disabled=False,\n         ).distinct()\n \n-    def cached_dict(self, locale_code='en-us'):\n+    def get_all_queryset(self):\n+        \"\"\"Returns a queryset for all live languages for all projects.\"\"\"\n+        return super(LiveLanguageManager, self).get_queryset().filter(\n+            translationproject__isnull=False,\n+            translationproject__directory__obsolete=False,\n+        ).distinct()\n+\n+    def cached_dict(self, locale_code='en-us', show_all=False):\n         \"\"\"Retrieves a sorted list of live language codes and names.\n \n+        By default only returns live languages for enabled projects, but it can\n+        also return live languages for disabled projects if specified.\n+\n         :param locale_code: the UI locale for which language full names need to\n             be localized.\n+        :param show_all: tells whether to return all live languages (both for\n+            disabled and enabled projects) or only live languages for enabled\n+            projects.\n         :return: an `OrderedDict`\n         \"\"\"\n-        key = make_method_key(self, 'cached_dict', locale_code)\n+        key_prefix = 'all_cached_dict' if show_all else 'cached_dict'\n+        key = make_method_key(self, key_prefix, locale_code)\n         languages = cache.get(key, None)\n         if languages is None:\n+            qs = self.get_all_queryset() if show_all else self.get_queryset()\n             languages = OrderedDict(\n                 sorted([(lang[0], tr_lang(lang[1]))\n-                        for lang in self.values_list('code', 'fullname')],\n+                        for lang in qs.values_list('code', 'fullname')],\n                        cmp=locale.strcoll,\n                        key=lambda x: x[1])\n             )\ndiff --git a/pootle/apps/pootle_misc/context_processors.py b/pootle/apps/pootle_misc/context_processors.py\n--- a/pootle/apps/pootle_misc/context_processors.py\n+++ b/pootle/apps/pootle_misc/context_processors.py\n@@ -53,7 +53,8 @@\n             'DEBUG': settings.DEBUG,\n         },\n         'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT,\n-        'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language()),\n+        'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language(),\n+                                                   request.user.is_superuser),\n         'ALL_PROJECTS': Project.objects.cached_dict(request.user),\n         'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request),\n         'display_agreement': _agreement_context(request),\n", "issue": "Language dropdown not showing template languages\n_Version: 2.5.1_\n\nThe language dropdown menu is only displaying languages that are _not_ specified as source language in any project.\n\nDeactivating this filter shows all possible languages and does not seem to have any undesirable side effects:\n\n``` diff\ndiff --git a/pootle/apps/pootle_language/models.py b/pootle/apps/pootle_language/models.py\nindex 03dbd96..9611602 100644\n--- a/pootle/apps/pootle_language/models.py\n+++ b/pootle/apps/pootle_language/models.py\n@@ -56,7 +56,6 @@ class LiveLanguageManager(models.Manager):\n         return super(LiveLanguageManager, self).get_query_set().filter(\n                 ~models.Q(code='templates'),\n                 translationproject__isnull=False,\n-                project__isnull=True,\n             ).distinct()\n```\n\n", "before_files": [{"content": "# -*- 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 locale\nfrom collections import OrderedDict\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.db.models.signals import post_delete, post_save\nfrom django.dispatch import receiver\n\nfrom pootle.core.cache import make_method_key\nfrom pootle.core.mixins import TreeItem\nfrom pootle.core.url_helpers import get_editor_filter\nfrom pootle.i18n.gettext import language_dir, tr_lang, ugettext_lazy as _\nfrom staticpages.models import StaticPage\n\n\nclass LiveLanguageManager(models.Manager):\n    \"\"\"Manager that only considers `live` languages.\n\n    A live language is any language containing at least a project with\n    translatable files.\n    \"\"\"\n\n    def get_queryset(self):\n        return super(LiveLanguageManager, self).get_queryset().filter(\n            translationproject__isnull=False,\n            project__isnull=True,\n        ).distinct()\n\n    def cached_dict(self, locale_code='en-us'):\n        \"\"\"Retrieves a sorted list of live language codes and names.\n\n        :param locale_code: the UI locale for which language full names need to\n            be localized.\n        :return: an `OrderedDict`\n        \"\"\"\n        key = make_method_key(self, 'cached_dict', locale_code)\n        languages = cache.get(key, None)\n        if languages is None:\n            languages = OrderedDict(\n                sorted([(lang[0], tr_lang(lang[1]))\n                        for lang in self.values_list('code', 'fullname')],\n                       cmp=locale.strcoll,\n                       key=lambda x: x[1])\n            )\n            cache.set(key, languages, settings.POOTLE_CACHE_TIMEOUT)\n\n        return languages\n\n\nclass Language(models.Model, TreeItem):\n\n    # any changes to the `code` field may require updating the schema\n    # see migration 0002_case_insensitive_schema.py\n    code = models.CharField(\n        max_length=50, null=False, unique=True, db_index=True,\n        verbose_name=_(\"Code\"),\n        help_text=_('ISO 639 language code for the language, possibly '\n                    'followed by an underscore (_) and an ISO 3166 country '\n                    'code. <a href=\"http://www.w3.org/International/'\n                    'articles/language-tags/\">More information</a>')\n    )\n    fullname = models.CharField(max_length=255, null=False,\n                                verbose_name=_(\"Full Name\"))\n\n    specialchars = models.CharField(\n        max_length=255, blank=True, verbose_name=_(\"Special Characters\"),\n        help_text=_('Enter any special characters that users might find '\n                    'difficult to type')\n    )\n\n    plurals_help_text = _('For more information, visit '\n                          '<a href=\"http://docs.translatehouse.org/projects/'\n                          'localization-guide/en/latest/l10n/'\n                          'pluralforms.html\">'\n                          'our page</a> on plural forms.')\n    nplural_choices = (\n        (0, _('Unknown')), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)\n    )\n    nplurals = models.SmallIntegerField(\n        default=0, choices=nplural_choices,\n        verbose_name=_(\"Number of Plurals\"), help_text=plurals_help_text\n    )\n    pluralequation = models.CharField(\n        max_length=255, blank=True, verbose_name=_(\"Plural Equation\"),\n        help_text=plurals_help_text)\n\n    directory = models.OneToOneField('pootle_app.Directory', db_index=True,\n                                     editable=False)\n\n    objects = models.Manager()\n    live = LiveLanguageManager()\n\n    class Meta(object):\n        ordering = ['code']\n        db_table = 'pootle_app_language'\n\n    # # # # # # # # # # # # # #  Properties # # # # # # # # # # # # # # # # # #\n\n    @property\n    def pootle_path(self):\n        return '/%s/' % self.code\n\n    @property\n    def name(self):\n        \"\"\"Localized fullname for the language.\"\"\"\n        return tr_lang(self.fullname)\n\n    @property\n    def direction(self):\n        \"\"\"Return the language direction.\"\"\"\n        return language_dir(self.code)\n\n    # # # # # # # # # # # # # #  Methods # # # # # # # # # # # # # # # # # # #\n\n    @classmethod\n    def get_canonical(cls, language_code):\n        \"\"\"Returns the canonical `Language` object matching `language_code`.\n\n        If no language can be matched, `None` will be returned.\n\n        :param language_code: the code of the language to retrieve.\n        \"\"\"\n        try:\n            return cls.objects.get(code__iexact=language_code)\n        except cls.DoesNotExist:\n            _lang_code = language_code\n            if \"-\" in language_code:\n                _lang_code = language_code.replace(\"-\", \"_\")\n            elif \"_\" in language_code:\n                _lang_code = language_code.replace(\"_\", \"-\")\n            try:\n                return cls.objects.get(code__iexact=_lang_code)\n            except cls.DoesNotExist:\n                return None\n\n    def __unicode__(self):\n        return u\"%s - %s\" % (self.name, self.code)\n\n    def __init__(self, *args, **kwargs):\n        super(Language, self).__init__(*args, **kwargs)\n\n    def __repr__(self):\n        return u'<%s: %s>' % (self.__class__.__name__, self.fullname)\n\n    def save(self, *args, **kwargs):\n        # create corresponding directory object\n        from pootle_app.models.directory import Directory\n        self.directory = Directory.objects.root.get_or_make_subdir(self.code)\n\n        super(Language, self).save(*args, **kwargs)\n\n    def delete(self, *args, **kwargs):\n        directory = self.directory\n        super(Language, self).delete(*args, **kwargs)\n        directory.delete()\n\n    def get_absolute_url(self):\n        return reverse('pootle-language-browse', args=[self.code])\n\n    def get_translate_url(self, **kwargs):\n        return u''.join([\n            reverse('pootle-language-translate', args=[self.code]),\n            get_editor_filter(**kwargs),\n        ])\n\n    def clean(self):\n        super(Language, self).clean()\n\n        if self.fullname:\n            self.fullname = self.fullname.strip()\n\n    # # # TreeItem\n\n    def get_children(self):\n        return self.translationproject_set.live()\n\n    def get_cachekey(self):\n        return self.directory.pootle_path\n\n    # # # /TreeItem\n\n    def get_stats_for_user(self, user):\n        self.set_children(self.get_children_for_user(user))\n        return self.get_stats()\n\n    def get_children_for_user(self, user, select_related=None):\n        return self.translationproject_set.for_user(\n            user, select_related=select_related\n        ).select_related(\n            \"project\"\n        ).order_by('project__fullname')\n\n    def get_announcement(self, user=None):\n        \"\"\"Return the related announcement, if any.\"\"\"\n        return StaticPage.get_announcement_for(self.pootle_path, user)\n\n\n@receiver([post_delete, post_save])\ndef invalidate_language_list_cache(**kwargs):\n    instance = kwargs[\"instance\"]\n    # XXX: maybe use custom signals or simple function calls?\n    if instance.__class__.__name__ not in ['Language', 'TranslationProject']:\n        return\n\n    key = make_method_key('LiveLanguageManager', 'cached_dict', '*')\n    cache.delete_pattern(key)\n", "path": "pootle/apps/pootle_language/models.py"}, {"content": "# -*- 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\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect, render\nfrom django.views.generic import TemplateView\n\nfrom pootle.i18n.override import get_lang_from_http_header\nfrom pootle_language.models import Language\n\n\nCOOKIE_NAME = 'pootle-language'\n\n\ndef view(request):\n    if not request.user.is_authenticated():\n        ctx = {\n            'next': request.GET.get(REDIRECT_FIELD_NAME, ''),\n        }\n        return render(request, 'welcome.html', ctx)\n\n    lang = request.COOKIES.get(COOKIE_NAME, None)\n\n    if lang is None:\n        supported = Language.live.cached_dict()\n        lang = get_lang_from_http_header(request, supported)\n\n    if lang is not None and lang not in ('projects', ''):\n        url = reverse('pootle-language-browse', args=[lang])\n    else:\n        url = reverse('pootle-projects-browse')\n\n    # Preserve query strings\n    args = request.GET.urlencode()\n    qs = '?%s' % args if args else ''\n    redirect_url = '%s%s' % (url, qs)\n\n    return redirect(redirect_url)\n\n\nclass AboutView(TemplateView):\n    template_name = 'about.html'\n\n    def get_context_data(self, **kwargs):\n        from translate.__version__ import sver as toolkit_version\n        from pootle import __version__\n\n        return {\n            'pootle_version': __version__,\n            'toolkit_version': toolkit_version,\n        }\n", "path": "pootle/apps/pootle_app/views/index/index.py"}, {"content": "# -*- 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\nfrom django.conf import settings\nfrom django.utils import translation\n\nfrom pootle.core.markup import get_markup_filter_name\nfrom pootle_language.models import Language\nfrom pootle_project.models import Project\nfrom staticpages.models import LegalPage\n\n\ndef _agreement_context(request):\n    \"\"\"Returns whether the agreement box should be displayed or not.\"\"\"\n    request_path = request.META['PATH_INFO']\n    nocheck = filter(lambda x: request_path.startswith(x),\n                     settings.POOTLE_LEGALPAGE_NOCHECK_PREFIXES)\n\n    if (request.user.is_authenticated() and not nocheck and\n        LegalPage.objects.has_pending_agreement(request.user)):\n        return True\n\n    return False\n\n\ndef _get_social_auth_providers(request):\n    if 'allauth.socialaccount' not in settings.INSTALLED_APPS:\n        return []\n\n    from allauth.socialaccount import providers\n    return [{'name': provider.name, 'url': provider.get_login_url(request)}\n            for provider in providers.registry.get_list()]\n\n\ndef pootle_context(request):\n    \"\"\"Exposes settings to templates.\"\"\"\n    # FIXME: maybe we should expose relevant settings only?\n    return {\n        'settings': {\n            'POOTLE_TITLE': settings.POOTLE_TITLE,\n            'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID,\n            'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and\n                                       settings.POOTLE_CONTACT_EMAIL),\n            'POOTLE_MARKUP_FILTER': get_markup_filter_name(),\n            'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED,\n            'SCRIPT_NAME': settings.SCRIPT_NAME,\n            'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT,\n            'DEBUG': settings.DEBUG,\n        },\n        'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT,\n        'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language()),\n        'ALL_PROJECTS': Project.objects.cached_dict(request.user),\n        'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request),\n        'display_agreement': _agreement_context(request),\n    }\n", "path": "pootle/apps/pootle_misc/context_processors.py"}], "after_files": [{"content": "# -*- 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 locale\nfrom collections import OrderedDict\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.db.models.signals import post_delete, post_save\nfrom django.dispatch import receiver\n\nfrom pootle.core.cache import make_method_key\nfrom pootle.core.mixins import TreeItem\nfrom pootle.core.url_helpers import get_editor_filter\nfrom pootle.i18n.gettext import language_dir, tr_lang, ugettext_lazy as _\nfrom staticpages.models import StaticPage\n\n\nclass LiveLanguageManager(models.Manager):\n    \"\"\"Manager that only considers `live` languages.\n\n    A live language is any language containing at least a project with\n    translatable files.\n    \"\"\"\n\n    def get_queryset(self):\n        \"\"\"Returns a queryset for all live languages for enabled projects.\"\"\"\n        return super(LiveLanguageManager, self).get_queryset().filter(\n            translationproject__isnull=False,\n            translationproject__directory__obsolete=False,\n            translationproject__project__disabled=False,\n        ).distinct()\n\n    def get_all_queryset(self):\n        \"\"\"Returns a queryset for all live languages for all projects.\"\"\"\n        return super(LiveLanguageManager, self).get_queryset().filter(\n            translationproject__isnull=False,\n            translationproject__directory__obsolete=False,\n        ).distinct()\n\n    def cached_dict(self, locale_code='en-us', show_all=False):\n        \"\"\"Retrieves a sorted list of live language codes and names.\n\n        By default only returns live languages for enabled projects, but it can\n        also return live languages for disabled projects if specified.\n\n        :param locale_code: the UI locale for which language full names need to\n            be localized.\n        :param show_all: tells whether to return all live languages (both for\n            disabled and enabled projects) or only live languages for enabled\n            projects.\n        :return: an `OrderedDict`\n        \"\"\"\n        key_prefix = 'all_cached_dict' if show_all else 'cached_dict'\n        key = make_method_key(self, key_prefix, locale_code)\n        languages = cache.get(key, None)\n        if languages is None:\n            qs = self.get_all_queryset() if show_all else self.get_queryset()\n            languages = OrderedDict(\n                sorted([(lang[0], tr_lang(lang[1]))\n                        for lang in qs.values_list('code', 'fullname')],\n                       cmp=locale.strcoll,\n                       key=lambda x: x[1])\n            )\n            cache.set(key, languages, settings.POOTLE_CACHE_TIMEOUT)\n\n        return languages\n\n\nclass Language(models.Model, TreeItem):\n\n    # any changes to the `code` field may require updating the schema\n    # see migration 0002_case_insensitive_schema.py\n    code = models.CharField(\n        max_length=50, null=False, unique=True, db_index=True,\n        verbose_name=_(\"Code\"),\n        help_text=_('ISO 639 language code for the language, possibly '\n                    'followed by an underscore (_) and an ISO 3166 country '\n                    'code. <a href=\"http://www.w3.org/International/'\n                    'articles/language-tags/\">More information</a>')\n    )\n    fullname = models.CharField(max_length=255, null=False,\n                                verbose_name=_(\"Full Name\"))\n\n    specialchars = models.CharField(\n        max_length=255, blank=True, verbose_name=_(\"Special Characters\"),\n        help_text=_('Enter any special characters that users might find '\n                    'difficult to type')\n    )\n\n    plurals_help_text = _('For more information, visit '\n                          '<a href=\"http://docs.translatehouse.org/projects/'\n                          'localization-guide/en/latest/l10n/'\n                          'pluralforms.html\">'\n                          'our page</a> on plural forms.')\n    nplural_choices = (\n        (0, _('Unknown')), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)\n    )\n    nplurals = models.SmallIntegerField(\n        default=0, choices=nplural_choices,\n        verbose_name=_(\"Number of Plurals\"), help_text=plurals_help_text\n    )\n    pluralequation = models.CharField(\n        max_length=255, blank=True, verbose_name=_(\"Plural Equation\"),\n        help_text=plurals_help_text)\n\n    directory = models.OneToOneField('pootle_app.Directory', db_index=True,\n                                     editable=False)\n\n    objects = models.Manager()\n    live = LiveLanguageManager()\n\n    class Meta(object):\n        ordering = ['code']\n        db_table = 'pootle_app_language'\n\n    # # # # # # # # # # # # # #  Properties # # # # # # # # # # # # # # # # # #\n\n    @property\n    def pootle_path(self):\n        return '/%s/' % self.code\n\n    @property\n    def name(self):\n        \"\"\"Localized fullname for the language.\"\"\"\n        return tr_lang(self.fullname)\n\n    @property\n    def direction(self):\n        \"\"\"Return the language direction.\"\"\"\n        return language_dir(self.code)\n\n    # # # # # # # # # # # # # #  Methods # # # # # # # # # # # # # # # # # # #\n\n    @classmethod\n    def get_canonical(cls, language_code):\n        \"\"\"Returns the canonical `Language` object matching `language_code`.\n\n        If no language can be matched, `None` will be returned.\n\n        :param language_code: the code of the language to retrieve.\n        \"\"\"\n        try:\n            return cls.objects.get(code__iexact=language_code)\n        except cls.DoesNotExist:\n            _lang_code = language_code\n            if \"-\" in language_code:\n                _lang_code = language_code.replace(\"-\", \"_\")\n            elif \"_\" in language_code:\n                _lang_code = language_code.replace(\"_\", \"-\")\n            try:\n                return cls.objects.get(code__iexact=_lang_code)\n            except cls.DoesNotExist:\n                return None\n\n    def __unicode__(self):\n        return u\"%s - %s\" % (self.name, self.code)\n\n    def __init__(self, *args, **kwargs):\n        super(Language, self).__init__(*args, **kwargs)\n\n    def __repr__(self):\n        return u'<%s: %s>' % (self.__class__.__name__, self.fullname)\n\n    def save(self, *args, **kwargs):\n        # create corresponding directory object\n        from pootle_app.models.directory import Directory\n        self.directory = Directory.objects.root.get_or_make_subdir(self.code)\n\n        super(Language, self).save(*args, **kwargs)\n\n    def delete(self, *args, **kwargs):\n        directory = self.directory\n        super(Language, self).delete(*args, **kwargs)\n        directory.delete()\n\n    def get_absolute_url(self):\n        return reverse('pootle-language-browse', args=[self.code])\n\n    def get_translate_url(self, **kwargs):\n        return u''.join([\n            reverse('pootle-language-translate', args=[self.code]),\n            get_editor_filter(**kwargs),\n        ])\n\n    def clean(self):\n        super(Language, self).clean()\n\n        if self.fullname:\n            self.fullname = self.fullname.strip()\n\n    # # # TreeItem\n\n    def get_children(self):\n        return self.translationproject_set.live()\n\n    def get_cachekey(self):\n        return self.directory.pootle_path\n\n    # # # /TreeItem\n\n    def get_stats_for_user(self, user):\n        self.set_children(self.get_children_for_user(user))\n        return self.get_stats()\n\n    def get_children_for_user(self, user, select_related=None):\n        return self.translationproject_set.for_user(\n            user, select_related=select_related\n        ).select_related(\n            \"project\"\n        ).order_by('project__fullname')\n\n    def get_announcement(self, user=None):\n        \"\"\"Return the related announcement, if any.\"\"\"\n        return StaticPage.get_announcement_for(self.pootle_path, user)\n\n\n@receiver([post_delete, post_save])\ndef invalidate_language_list_cache(**kwargs):\n    instance = kwargs[\"instance\"]\n    # XXX: maybe use custom signals or simple function calls?\n    if instance.__class__.__name__ not in ['Language', 'TranslationProject']:\n        return\n\n    key = make_method_key('LiveLanguageManager', 'cached_dict', '*')\n    cache.delete_pattern(key)\n", "path": "pootle/apps/pootle_language/models.py"}, {"content": "# -*- 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\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect, render\nfrom django.views.generic import TemplateView\n\nfrom pootle.i18n.override import get_lang_from_http_header\nfrom pootle_language.models import Language\n\n\nCOOKIE_NAME = 'pootle-language'\n\n\ndef view(request):\n    if not request.user.is_authenticated():\n        ctx = {\n            'next': request.GET.get(REDIRECT_FIELD_NAME, ''),\n        }\n        return render(request, 'welcome.html', ctx)\n\n    lang = request.COOKIES.get(COOKIE_NAME, None)\n\n    if lang is None:\n        supported = Language.live.cached_dict(\n            show_all=request.user.is_superuser\n        )\n        lang = get_lang_from_http_header(request, supported)\n\n    if lang is not None and lang not in ('projects', ''):\n        url = reverse('pootle-language-browse', args=[lang])\n    else:\n        url = reverse('pootle-projects-browse')\n\n    # Preserve query strings\n    args = request.GET.urlencode()\n    qs = '?%s' % args if args else ''\n    redirect_url = '%s%s' % (url, qs)\n\n    return redirect(redirect_url)\n\n\nclass AboutView(TemplateView):\n    template_name = 'about.html'\n\n    def get_context_data(self, **kwargs):\n        from translate.__version__ import sver as toolkit_version\n        from pootle import __version__\n\n        return {\n            'pootle_version': __version__,\n            'toolkit_version': toolkit_version,\n        }\n", "path": "pootle/apps/pootle_app/views/index/index.py"}, {"content": "# -*- 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\nfrom django.conf import settings\nfrom django.utils import translation\n\nfrom pootle.core.markup import get_markup_filter_name\nfrom pootle_language.models import Language\nfrom pootle_project.models import Project\nfrom staticpages.models import LegalPage\n\n\ndef _agreement_context(request):\n    \"\"\"Returns whether the agreement box should be displayed or not.\"\"\"\n    request_path = request.META['PATH_INFO']\n    nocheck = filter(lambda x: request_path.startswith(x),\n                     settings.POOTLE_LEGALPAGE_NOCHECK_PREFIXES)\n\n    if (request.user.is_authenticated() and not nocheck and\n        LegalPage.objects.has_pending_agreement(request.user)):\n        return True\n\n    return False\n\n\ndef _get_social_auth_providers(request):\n    if 'allauth.socialaccount' not in settings.INSTALLED_APPS:\n        return []\n\n    from allauth.socialaccount import providers\n    return [{'name': provider.name, 'url': provider.get_login_url(request)}\n            for provider in providers.registry.get_list()]\n\n\ndef pootle_context(request):\n    \"\"\"Exposes settings to templates.\"\"\"\n    # FIXME: maybe we should expose relevant settings only?\n    return {\n        'settings': {\n            'POOTLE_TITLE': settings.POOTLE_TITLE,\n            'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID,\n            'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and\n                                       settings.POOTLE_CONTACT_EMAIL),\n            'POOTLE_MARKUP_FILTER': get_markup_filter_name(),\n            'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED,\n            'SCRIPT_NAME': settings.SCRIPT_NAME,\n            'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT,\n            'DEBUG': settings.DEBUG,\n        },\n        'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT,\n        'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language(),\n                                                   request.user.is_superuser),\n        'ALL_PROJECTS': Project.objects.cached_dict(request.user),\n        'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request),\n        'display_agreement': _agreement_context(request),\n    }\n", "path": "pootle/apps/pootle_misc/context_processors.py"}]}