def clear_language(self): """Clear the current language(s) and set SpamBayes to use the default.""" self.current_langs_codes = [] self._clear_syspath() lang = NullTranslations() lang.install()
def init(locale_dirs, language, catalog='sphinx', namespace='general'): # type: (List[unicode], unicode, unicode, unicode) -> Tuple[NullTranslations, bool] """Look for message catalogs in `locale_dirs` and *ensure* that there is at least a NullTranslations catalog set in `translators`. If called multiple times or if several ``.mo`` files are found, their contents are merged together (thus making ``init`` reentrable). """ global translators translator = translators.get((namespace, catalog)) # ignore previously failed attempts to find message catalogs if translator.__class__ is NullTranslations: translator = None # the None entry is the system's default locale path has_translation = True if language and '_' in language: # for language having country code (like "de_AT") languages = [language, language.split('_')[0]] else: languages = [language] # loading for dir_ in locale_dirs: try: trans = gettext.translation(catalog, localedir=dir_, # type: ignore languages=languages) if translator is None: translator = trans else: translator.add_fallback(trans) except Exception: # Language couldn't be found in the specified path pass # guarantee translators[(namespace, catalog)] exists if translator is None: translator = NullTranslations() has_translation = False translators[(namespace, catalog)] = translator if hasattr(translator, 'ugettext'): translator.gettext = translator.ugettext # type: ignore return translator, has_translation
def pylons_formencode_gettext(value): from pylons.i18n import ugettext as pylons_gettext from gettext import NullTranslations trans = pylons_gettext(value) # Translation failed, try formencode if trans == value: try: fetrans = pylons.tmpl_context.formencode_translation except AttributeError, attrerror: # the translator was not set in the Pylons context # we are certainly in the test framework # let's make sure won't return something that is ok with the caller fetrans = NullTranslations() if not fetrans: fetrans = NullTranslations() trans = fetrans.ugettext(value)
def init_localization(app): """prepare l10n""" # ----- # Application localization # ----- try: # Language message file lang_filename = os.path.join( os.path.abspath(os.path.dirname(__file__)), "../locales/%s.mo" % app.config.get('locale', 'en_US') ) print("Opening message file %s for locale %s" % (lang_filename, app.config.get('locale', 'en_US'))) translation = GNUTranslations(open(lang_filename, "rb")) translation.install(True) _ = translation.gettext except IOError: print("Locale not found. Using default language messages (English)") null_translation = NullTranslations() null_translation.install() _ = null_translation.gettext except Exception as e: # pragma: no cover - should not happen print("Locale not found. Exception: %s" % str(e)) null_translation = NullTranslations() null_translation.install() _ = null_translation.gettext # Provide translation methods to templates app.config['_'] = _ print(_("Language is English (default)...")) return _
def translation(self, bundleId, languages, priority='gp', domain=None, localedir=None, class_=None, codeset=None): """Returns the ``Translations`` instance to be used for obtaining translations. ``bundleId`` is the name of the bundle to use. ``languages`` is the list of languages to use, with subsequent ones being fallbacks. Additionally, based on the value of ``priority``, local translated values can be given precedence over Globalization Pipeline translated values. For example, to fallback to Spanish if French translated values are not found, ``languages=['fr', 'es']``. And if ``priority=gp``, the fallback chain will be as follows: - use ``gp`` French translated value, if not found: - use ``local`` French translated value, if not found: - use ``gp`` Spanish translated value, if not found: - use ``local`` Spanish translated value, if not found: - use source value, if not found: - use provided key In order to search for local translated values, the optional parameters must be provided according to `gettext.translation <https://docs.python.org/2/library/gettext.html#gettext.translation>`_ """ availableLangs = self.get_avaliable_languages(bundleId) translations = None for language in languages: # get local translation localTranslations = None if domain: t = local_translation(domain=domain, localedir=localedir, languages=[language], class_=class_, fallback=True, codeset=codeset) # only use t if it's not NullTranslations - NullTranslations # indicates that a translation file was not found if t is not NullTranslations: localTranslations = t gpTranslations = None # get gp translation if the bundle has the language match = self.__get_language_match(languageCode=language, languageIds=availableLangs) if match: gpTranslations = GPTranslations( bundleId=bundleId, languageId=match, client=self, cacheTimeout=self.__cacheTimeout) # create the fallback chain if not translations: # set the first translation in the chain if priority == 'local': if not localTranslations: translations = gpTranslations else: translations = localTranslations if gpTranslations: translations.add_fallback(gpTranslations) elif priority == 'gp': if not gpTranslations: translations = localTranslations else: translations = gpTranslations if localTranslations: translations.add_fallback(localTranslations) else: # add fallback in the preferred order if priority == 'local': if localTranslations: translations.add_fallback(localTranslations) if gpTranslations: translations.add_fallback(gpTranslations) elif priority == 'gp': if gpTranslations: translations.add_fallback(gpTranslations) if localTranslations: translations.add_fallback(localTranslations) if not translations: logging.warning('No translations were found for bundleID <%s>' \ + ' and languages <%s> ', bundleId, languages) translations = NullTranslations() return translations
def __init__(self, client, bundleId, languageId, cacheTimeout, fp=None): NullTranslations.__init__(self, fp=fp) self.__client = client self.__bundleId = bundleId self.__languageId = languageId self.__cacheTimeout = cacheTimeout
# Chinese Support Redux is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # Chinese Support Redux. If not, see <https://www.gnu.org/licenses/>. from gettext import NullTranslations from json import load from logging import getLogger from unittest import TestCase from unittest.mock import MagicMock, patch NullTranslations().install() modules = { 'PyQt5.QtGui': MagicMock(), 'PyQt5.QtWidgets': MagicMock(), 'anki': MagicMock(), 'anki.find': MagicMock(), 'anki.hooks': MagicMock(), 'anki.lang': MagicMock(), 'anki.stats': MagicMock(), 'anki.stdmodels': MagicMock(), 'anki.template': MagicMock(), 'anki.template.hint': MagicMock(), 'anki.utils': MagicMock(), 'aqt': MagicMock(), 'aqt.utils': MagicMock(),
def __init__(self, fileobj=None, locale=None): NullTranslations.__init__(self, fileobj) self.lang = locale self._catalog = {}
def gettext(self, msg): translation = self.data.get(msg) if translation is not None: return translation return NullTranslations.gettext(self, msg)
def set_app_config(config): """ Update global application configuration """ global bottle_app, app_config, _ # Localization try: # Language message file filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), "res/%s.mo" % config.get('locale', 'en_US')) print("Opening message file %s for locale %s" % (filename, config.get('locale', 'en_US'))) translation = GNUTranslations(open(filename, "rb")) translation.install() _ = translation.gettext except IOError: print("Locale not found. Using default language messages (English)") default = NullTranslations() default.install() _ = default.gettext except Exception as e: # pragma: no cover - should not happen print("Locale not found. Exception: %s" % str(e)) default = NullTranslations() default.install() _ = default.gettext print(_("Language is English (default)...")) app_config = config bottle_app.config.update(config) # Set logging options for the application set_console_logger(logger) # Store logs in a daily file, keeping 6 days along ... as default! set_file_logger(logger, path=app_config.get('logs.dir', '/var/log/' + manifest['name'].lower()), filename=app_config.get('logs.filename', manifest['name'].lower() + '.log'), when=app_config.get('logs.when', 'D'), interval=int(app_config.get('logs.interval', '1')), backup_count=int(app_config.get('logs.backupCount', '6'))) # Set application log level (default is INFO (20)) print("Activate logs level: %d" % int(app_config.get('logs.level', '20'))) logger.setLevel(int(app_config.get('logs.level', '20'))) if app_config.get('debug', '0') == '1': # pragma: no cover - not testable easily... print("Activate DEBUG logs") logger.setLevel(DEBUG) logger.info( "--------------------------------------------------------------------------------" ) logger.info("%s, version %s", manifest['name'], manifest['version']) logger.info("Copyright %s", manifest['copyright']) logger.info("License: %s", manifest['license']) logger.info( "--------------------------------------------------------------------------------" ) logger.debug("Doc: %s", manifest['doc']) logger.debug("Release notes: %s", manifest['release']) logger.debug( "--------------------------------------------------------------------------------" ) logger.info( "--------------------------------------------------------------------------------" ) logger.info("%s, listening on %s:%d (debug mode: %s)", app_config.get('name', 'Test'), app_config.get('host', '127.0.0.1'), int(app_config.get('port', '5001')), app_config.get('debug', '0') == '1') logger.info("%s, using alignak backend on %s", app_config.get('name', 'Test'), app_config.get('alignak_backend', 'http://127.0.0.1:5000')) logger.info( "--------------------------------------------------------------------------------" ) logger.debug("Application settings: ") for key, value in sorted(app_config.items()): logger.debug(" %s = %s", key, value) logger.debug( "--------------------------------------------------------------------------------" )
def __init__(self, catalog): NullTranslations.__init__(self) self._catalog = catalog
def __init__(self, fileobj=None, locale=None): NullTranslations.__init__(self, fileobj) self.locale = locale self.client_keys = set()
def test_label(self) -> None: sut = Attendee() with Translations(NullTranslations()): self.assertIsInstance(sut.label, str) self.assertNotEqual('', sut.label)
def translations_factory(self): return NullTranslations()
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path from gettext import NullTranslations, translation from .logger import system_log translation_dir = os.path.join(os.path.dirname(os.path.abspath(__file__, ), ), "translations") current_translation = NullTranslations() def set_locale(locales, trans_dir=translation_dir): global current_translation try: current_translation = translation( domain="messages", localedir=trans_dir, languages=locales, ) except Exception as e: system_log.debug(e) current_translation = NullTranslations()
def __init__(self, trans=None): self.trans = NullTranslations() if trans is None else trans
import os import time import logging import datetime import unittest import importlib from unittest.mock import patch from types import SimpleNamespace from gettext import NullTranslations from dateutil import tz from skill_sdk import l10n from skill_sdk.intents import Context from skill_sdk.test_helpers import create_context, mock_datetime_now l10n.translations = {'de': NullTranslations()} logger = logging.getLogger(__name__) class TestIntentsContext(unittest.TestCase): ctx: Context def setUp(self): configuration = {'a': ['123'], 'b': [1, 2, 3]} session = {'attributes': {"key-1": "value-1", "key-2": "value-2"}} self.ctx = create_context('TELEKOM_Clock_GetTime', configuration=configuration, session=session) def test_check_prerequisite(self):
def ngettext(self, singular, plural, n): translation = self.data.get(singular if n == 1 else plural) if translation is not None: return translation return NullTranslations.ngettext(self, singular, plural, n)
__version__ = '0.9.2' from gettext import NullTranslations trans = NullTranslations() del NullTranslations
def test_label(self) -> None: with Translations(NullTranslations()): sut = DivorceAnnouncement() self.assertIsInstance(sut.label, str) self.assertNotEqual('', sut.label)
def __call__(self, language_code=None): if language_code in ('en', None): return NullTranslations() mo_file = 'mailman-%s.mo' % language_code with closing(resource_stream('mailman.testing', mo_file)) as fp: return GNUTranslations(fp)
def __init__(self, *args, **kwargs): NullTranslations.__init__(self, *args, **kwargs) self.new_catalog()
def test_label(self) -> None: with Translations(NullTranslations()): sut = UnknownEventType() self.assertIsInstance(sut.label, str) self.assertNotEqual('', sut.label)
def set_app_config(config): ''' Update global application configuration ''' global bottle_app, app_config, _ # Localization try: # Language message file filename = os.path.join( os.path.abspath(os.path.dirname(__file__)), "res/%s.mo" % config.get('locale', 'en_US') ) print "Opening message file %s for locale %s" % (filename, config.get('locale', 'en_US')) translation = GNUTranslations(open(filename, "rb")) translation.install() _ = translation.gettext except IOError: print "Locale not found. Using default language messages (English)" default = NullTranslations() default.install() _ = default.gettext except Exception as e: # pragma: no cover - should not happen print "Locale not found. Exception: %s" % str(e) default = NullTranslations() default.install() _ = default.gettext print _("Language is English (default)...") app_config = config bottle_app.config.update(config) # Set logging options for the application set_console_logger(logger) # Store logs in a daily file, keeping 6 days along ... as default! set_file_logger( logger, path=app_config.get('logs.dir', '/var/log'), filename=app_config.get('logs.filename', manifest['name'].lower() + '.log'), when=app_config.get('logs.when', 'D'), interval=int(app_config.get('logs.interval', '1')), backupCount=int(app_config.get('logs.backupCount', '6')) ) # Set application log level (default is INFO (20)) print "Activate logs level: %d" % int(app_config.get('logs.level', '20')) logger.setLevel(int(app_config.get('logs.level', '20'))) if app_config.get('debug', '0') == '1': print "Activate DEBUG logs" logger.setLevel(DEBUG) logger.info( "--------------------------------------------------------------------------------" ) logger.info("%s, version %s", manifest['name'], manifest['version']) logger.info("Copyright %s", manifest['copyright']) logger.info("License: %s", manifest['license']) logger.info( "--------------------------------------------------------------------------------" ) logger.debug("Doc: %s", manifest['doc']) logger.debug("Release notes: %s", manifest['release']) logger.debug( "--------------------------------------------------------------------------------" ) logger.debug("Application settings: ") for key, value in sorted(app_config.items()): logger.debug(" %s = %s", key, value) logger.debug( "--------------------------------------------------------------------------------" )
def test_label(self) -> None: with Translations(NullTranslations()): sut = Missing() self.assertIsInstance(sut.label, str) self.assertNotEqual('', sut.label)
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals from gettext import NullTranslations import filters # Dummy Translation to mark strings for translation _ = NullTranslations().gettext # Site defaults AUTHOR = 'Mark Hall' SITENAME = _('Under the Surface') SITE_TAGLINE = _('Authors in hiding from the Canon') BASE_SITEURL = '' SITEURL = '' # Path configuration PATH = 'content' PAGE_PATHS = ['pages'] ARTICLE_PATHS = ['articles'] ARTICLE_URL = 'articles/{slug}.html' ARTICLE_SAVE_AS = 'articles/{slug}.html' # Internationalisation TIMEZONE = 'Europe/Berlin' DEFAULT_LANG = 'en'
def get(self, langcode, fallback=NullTranslations()): try: return self.trans[langcode] except KeyError: return fallback
def __eq__(self, other): if isinstance(other, Address): return (self.host == other.host and self.port == other.port) if isinstance(other, enet.Address): return self.__eq__(Address(other)) return NotImplemented def __ne__(self, other): if isinstance(other, Address) or isinstance(other, enet.Address): return not self.__eq__(other) return NotImplemented #----------------------------------------------------------------------------- nulltranslation = NullTranslations() class Player: def __init__(self, peer, sid, protocol=0): # pickle doesn't use all of these attributes # for more detail check __getstate__() self.peer = peer assert isinstance(self.peer, enet.Peer) self.address = Address(self.peer.address) self.sid = sid # there's a difference between player.protocol and player.version: # - player.protocol is the network protocol version used by the # client while talking to the server # - player.version is the game version which all players in a game # must match. player.version gets set during oncreate/onjoin
def OnInit(self): self.Bind(wx.EVT_QUERY_END_SESSION, self._onEndSession) NullTranslations().install() return True
def __call__(self, language_code=None): if language_code in ('en', None): return NullTranslations() mo_file = 'mailman-%s.mo' % language_code with open_binary('mailman.testing', mo_file) as fp: return GNUTranslations(fp)