Example #1
0
def main():
	gettext.install('topqt')
	gettext.translation('topqt', './locale', languages=['sv']).install(True)
	
	global window
	app = QtGui.QApplication(sys.argv)
	if os.path.isfile("/usr/share/topqt/topqt.ui"):
		window = uic.loadUi("/usr/share/topqt/topqt.ui")
	elif os.path.isfile("topqt.ui"):
		window = uic.loadUi("topqt.ui")
	else:
		print(_("Error! Couldn't find user interface file topqt.ui! Aborting!"))
		sys.exit(1)
		
	readConfig()
	
	#setupTable([{"caption": "PID", "key": "PID"},{"caption":"Name","key":"NAME"}, {"caption":"%CPU","key":"%CPU"},{"caption":"path","key":"COMMAND"}])
	
	t = RefresherThread(5)
	t.start()

	window.connect(window.actionQuit, QtCore.SIGNAL("triggered()"), actionQuitTriggered);
	window.connect(window.actionSettings, QtCore.SIGNAL("triggered()"), actionSettingsTriggered);

	#window.tableWidget.connect(window.tableWidget, QtCore.SIGNAL('itemSelectionChanged()'), itemSelectionChanged)

	window.show();
	sys.exit(app.exec_())
Example #2
0
def installTranslations(langs):
    """Create a ``gettext.translation`` chain for all **langs**.

    Attempt to install the first language in the **langs** list. If that
    fails, we receive a ``gettext.NullTranslation`` object, and if it worked
    then we have a ``gettext.GNUTranslation`` object. Whichever one we end up
    with, get the other languages and add them as fallbacks to the
    first. Lastly, install this chain of translations.

    :param list langs: A list of language codes.
    :returns: A ``gettext.NullTranslation`` or ``gettext.GNUTranslation`` with
        fallback languages set.
    """
    try:
        language = gettext.translation("bridgedb", localedir=TRANSLATIONS_DIR,
                                       languages=langs, fallback=True)
        for lang in langs:
            language.add_fallback(
                gettext.translation("bridgedb", localedir=TRANSLATIONS_DIR,
                                    languages=langs, fallback=True))
    except IOError as error:
        logging.error(error.message)

    language.install(unicode=True)
    return language
Example #3
0
def _(s):
	try:
		s = gettext.translation('message', core.config.localesDir).gettext(s)
	except IOError:
		s = gettext.translation('message', core.config.localesDir, languages=['en_GB']).gettext(s)

	return s
    def data(self):
        # NOTE(mrodden): this should always resolve to a unicode string
        # that best represents the state of the message currently

        localedir = os.environ.get(self.domain.upper() + '_LOCALEDIR')
        if self.locale:
            lang = gettext.translation(self.domain,
                                       localedir=localedir,
                                       languages=[self.locale],
                                       fallback=True)
        else:
            # use system locale for translations
            lang = gettext.translation(self.domain,
                                       localedir=localedir,
                                       fallback=True)

        if six.PY3:
            ugettext = lang.gettext
        else:
            ugettext = lang.ugettext

        full_msg = (self._left_extra_msg +
                    ugettext(self._msg) +
                    self._right_extra_msg)

        if self.params is not None:
            full_msg = full_msg % self.params

        return six.text_type(full_msg)
Example #5
0
    def __init__( self, parent ):
        core.ttyUsbSpy.ttyUsbSpy.__init__( self, parent)
        self.SelectedT1 = False
        self.SelectedT2 = False
        self.listdata = []
        self.scroll = 0


        # Install gettext.  Once this is done, all strings enclosed in "_()" will automatically be translated.
        gettext.install('ttyUSBSpy', './locale', unicode=True)
        # Define supported languages
        self.presLan_en = gettext.translation('ttyUSBSpy', './locale', languages=['en']) # English
        self.presLan_es = gettext.translation('ttyUSBSpy', './locale', languages=['es']) # Spanish
        # Install English as the initial language
#        self.presLan_en.install()
        self.presLan_es.install()
#        self.UpdateText()
        
        for files in glob.glob("/dev/*ttyUSB*"):
            self.m_comboBoxttyUSB.Append(files)

        if self.m_comboBoxttyUSB.GetCount() > 0 and os.getuid()==0:
            print "self.m_comboBoxttyUSB:"+repr(self.m_comboBoxttyUSB.GetCount())
            self.m_buttonCapture.Enable()
        else:
# Como no hay ttyUSB o no soy superuser deshabilito la posibilidad de capturar
            self.m_buttonCapture.Disable()     
 def __init__(self, file_name, factory, instance_id, multi_instance, uuid):
     self.file_name = file_name
     self.factory = factory
     self.instance_id = instance_id
     self.multi_instance = multi_instance
     self.uuid = uuid
     try:
         self.tUser = gettext.translation(self.uuid, HOME_PATH + "/.local/share/locale")
     except IOError:
         try:
             self.tUser = gettext.translation(self.uuid, "/usr/share/locale")
         except IOError:
             self.tUser = None
     try:
         if os.path.exists("/usr/share/cinnamon/locale"):
             self.t = gettext.translation("cinnamon", "/usr/share/cinnamon/locale")
         else:
             self.t = gettext.translation("cinnamon", "/usr/share/locale")
     except IOError:
         self.t = None
     if self.t:
         try:
             self.t = self.t.ugettext
         except:
             self.t = self.t.gettext
     if self.tUser:
         try:
             self.tUser = self.tUser.ugettext
         except:
             self.tUser = self.tUser.gettext
     self.reload()
def generate(filename, prefix, name, comment, suffix):
    print "HERE"
    os.environ['LANG'] = "en_US.UTF-8"
    gettext.install(DOMAIN, PATH)
    desktopFile = open(filename, "w")

    desktopFile.writelines(prefix)

    desktopFile.writelines("Name=%s\n" % name)
    print ("Name=%s\n" % name)
    for directory in sorted(os.listdir(PATH)):
        if os.path.isdir(os.path.join(PATH, directory)):
            try:
                language = gettext.translation(DOMAIN, PATH, languages=[directory])
                language.install()
                if (_(name) != name):
                    desktopFile.writelines("Name[%s]=%s\n" % (directory, _(name)))
                    print ("Name[%s]=%s\n" % (directory, _(name)))
            except:
                pass

    desktopFile.writelines("Comment=%s\n" % comment)
    for directory in sorted(os.listdir(PATH)):
        if os.path.isdir(os.path.join(PATH, directory)):
            try:
                language = gettext.translation(DOMAIN, PATH, languages=[directory])
                language.install()
                if (_(comment) != comment):
                    desktopFile.writelines("Comment[%s]=%s\n" % (directory, _(comment)))
            except:
                pass

    desktopFile.writelines(suffix)
Example #8
0
 def i18n(self, domain="main", language=None):
     """
     Provides module based localization.
     Domain is a path relative to SelfPath that specifies the location
     of the translation catalog. ".." or "../.." or example.
     Language is the language to use.  Really?  Yes.
     """
     source_append = ""
     if domain:
         domain = os.path.basename(domain)
         source_append = os.path.dirname(domain)
     elif self.__i18n_domain__:
         domain = os.path.basename(self.__i18n_domain__)
         source_append = os.path.dirname(self.__i18n_domain__)
     else:
         domain = self.__class__.__name__.lower()
     if not language:
         language = self.__i18n_language__
     sources = [
         os.path.join(self.get_exec_path(), source_append),
         os.path.join(self.get_lib_path(), source_append),
         os.path.join(os.path.dirname(self.get_self_path()), source_append)]
     for i, s in enumerate(sources):
         sources[i] = os.path.abspath(s)
     for i, s in enumerate(sources):
         sources[i] = os.path.join(s, "locale")
     sources_ = []
     for source in sources:
         if source not in sources_:
             sources_.append(source)
     for source in sources:
         if gettext.find(domain, source, [language]):
             return gettext.translation(domain, source, [language]).ugettext
     return gettext.translation(domain, fallback=True).ugettext
Example #9
0
def main():
    """Main entry point for the script."""

# Set up message catalog access
    #t = gettext.translation('messages', './po', fallback=True)
    t = gettext.translation('messages', 'locale', ['en_US'])
    #_ = t.ugettext

    #gettext.bindtextdomain('messages', './po')
    #print gettext.bindtextdomain('messages')

    #gettext.textdomain('messages')
    #print gettext.textdomain()

    _ = t.gettext

    print _('test')
    print _('test-a')

    print gettext.find('messages')

    en_us = gettext.translation('messages', 'locale', languages=['en_US'])
    en_us.install()
    _ = en_us.gettext

    print _('test')
    print _('test-a')
    print en_us.gettext('test-a')
    print en_us.gettext('test-b')

    pass
Example #10
0
    def GET(self):
        global lang_in_use
        inputs = web.webapi.input(prev='/home/', ln='')
        if inputs.ln == 'cn':
             lang_in_use = 'zh_CN'
        elif inputs.ln == 'en':
             lang_in_use =  'en_US'
        elif inputs.ln == 'fr':
             lang_in_use =  'fr'
        elif inputs.ln == 'sk_SK':
             lang_in_use =  'sk_SK'
        elif inputs.ln == 'pt_BR':
             lang_in_use = 'pt_BR'
        elif inputs.ln == 'de_DE':
             lang_in_use = 'de_DE'
        else:
             lang_in_use = 'en_US'

        gettext.translation('messages', localedir,
                            languages=[lang_in_use]).install(True)

        seafile_rpc.set_config('lang_in_use', lang_in_use)

        default_options['lang'] = lang_in_use   

        raise web.seeother(inputs.prev)
Example #11
0
def set_lang(lang, codeset='utf-8', gui=False):
    if not isinstance(lang, list):
        lang = [lang]

    locale_dir = os.path.join(os.path.dirname(__file__), 'i18n')
    domain = 'irssinotifier'

    gettext.bindtextdomain(domain, locale_dir)
    gettext.textdomain(domain)
    locale.bindtextdomain(domain, locale_dir)
    locale.textdomain(domain)
    if gui:
        import gtk.glade
        gtk.glade.bindtextdomain(domain)
        gtk.glade.textdomain(domain)

    try:
        translator = gettext.translation(domain,
                                         locale_dir,
                                         languages=lang,
                                         codeset=codeset)

    except IOError, ioe:
        lang = ['en']
        print 'Language not supportted: %r' % ioe
        print 'Fallback to english'
        translator = gettext.translation(domain,
                                         locale_dir,
                                         languages=lang,
                                         codeset=codeset)
Example #12
0
def translate(uuid, string):
    if uuid not in TRANSLATIONS:
        try:
            TRANSLATIONS[uuid] = gettext.translation(uuid, HOME + "/.local/share/locale").gettext
        except IOError:
            try:
                TRANSLATIONS[uuid] = gettext.translation(uuid, "/usr/share/locale").gettext
            except IOError:
                TRANSLATIONS[uuid] = None

    # Do not translate white spaces
    if not string.strip():
        return string

    if TRANSLATIONS[uuid]:
        result = TRANSLATIONS[uuid](string)

        try:
            result = result.decode("UTF-8")
        except Exception:
            result = result

        if result != string:
            return result

    return gettext.gettext(string)
Example #13
0
    def __init__(self, schema_name, schema_dir=None, schema_filename=None, **options):
        if not schema_dir:
            schema_dir = gtweak.GSETTINGS_SCHEMA_DIR
        if not schema_filename:
            schema_filename = schema_name + ".gschema.xml"

        schema_path = os.path.join(schema_dir, schema_filename)
        if not os.path.exists(schema_path):
            logging.critical("Could not find schema %s" % schema_path)
            assert False

        self._schema_name = schema_name
        self._schema = {}

        try:
            dom = xml.dom.minidom.parse(schema_path)
            global_gettext_domain = dom.documentElement.getAttribute("gettext-domain")
            try:
                if global_gettext_domain:
                    # We can't know where the schema owner was installed, let's assume it's
                    # the same prefix as ours
                    global_translation = gettext.translation(global_gettext_domain, gtweak.LOCALE_DIR)
                else:
                    global_translation = gettext.NullTranslations()
            except IOError:
                global_translation = None
                logging.debug("No translated schema for %s (domain: %s)" % (schema_name, global_gettext_domain))
            for schema in dom.getElementsByTagName("schema"):
                gettext_domain = schema.getAttribute("gettext-domain")
                try:
                    if gettext_domain:
                        translation = gettext.translation(gettext_domain, gtweak.LOCALE_DIR)
                    else:
                        translation = global_translation
                except IOError:
                    translation = None
                    logging.debug("Schema not translated %s (domain: %s)" % (schema_name, gettext_domain))
                if schema_name == schema.getAttribute("id"):
                    for key in schema.getElementsByTagName("key"):
                        name = key.getAttribute("name")
                        # summary is 'compulsory', description is optional
                        # ... in theory, but we should not barf on bad schemas ever
                        try:
                            summary = key.getElementsByTagName("summary")[0].childNodes[0].data
                        except:
                            summary = ""
                            logging.info("Schema missing summary %s (key %s)" % (os.path.basename(schema_path), name))
                        try:
                            description = key.getElementsByTagName("description")[0].childNodes[0].data
                        except:
                            description = ""

                        # if missing translations, use the untranslated values
                        self._schema[name] = dict(
                            summary=translation.gettext(summary) if translation else summary,
                            description=translation.gettext(description) if translation else description,
                        )

        except:
            logging.critical("Error parsing schema %s (%s)" % (schema_name, schema_path), exc_info=True)
Example #14
0
File: locale.py Project: hydai/cms
def get_system_translations(lang):
    """Return the translation catalogs for our dependencies.

    Some strings we use come from external software (e.g. language and
    country names, mimetype descriptions, etc.) and their translations
    are thus provided by these packages' catalogs. This function has to
    return the gettext.*Translations classes that translate a string
    according to these message catalogs.

    lang (string): the language we want translations for

    return ([gettext.NullTranslations]): the translation catalogs

    """
    iso_639_locale = gettext.translation(
        "iso_639",
        os.path.join(config.iso_codes_prefix, "share", "locale"),
        [lang],
        fallback=True)
    iso_3166_locale = gettext.translation(
        "iso_3166",
        os.path.join(config.iso_codes_prefix, "share", "locale"),
        [lang],
        fallback=True)
    shared_mime_info_locale = gettext.translation(
        "shared-mime-info",
        os.path.join(config.shared_mime_info_prefix, "share", "locale"),
        [lang],
        fallback=True)

    return [iso_639_locale, iso_3166_locale, shared_mime_info_locale]
Example #15
0
File: i18n.py Project: B-Rich/smart
	def set_language( self, language = None ):
		if language is not None:
			Translation.locale.parse( language )

		if not Translation.locale:
			try:
				lang = getlocale( LC_MESSAGES )
				if lang[ 0 ] is None:
					language = 'C'
				else:
					language = lang[ 0 ]
				Translation.locale.parse( language )
			except Error:
				raise I18N_Error( 'The given locale is not vaild: %s' % str( e ) )

		if not self._domain:
			return

		try:
			self._translation = gettext.translation( self._domain, languages = ( Translation.locale.language, ), localedir = self._localedir )
		except IOError, e:
			try:
				self._translation = gettext.translation( self._domain, languages = ( '%s_%s' % ( Translation.locale.language, Translation.locale.territory ), ), localedir = self._localedir )
			except IOError:
				self._translation = None
def generate(filename, prefix, name, comment, suffix):
    gettext.install(DOMAIN, PATH)
    desktopFile = open(filename, "w")

    desktopFile.writelines(prefix)

    desktopFile.writelines("Name=%s\n" % name)
    for directory in sorted(os.listdir(PATH)):
        if os.path.isdir(os.path.join(PATH, directory)):
            try:
                language = gettext.translation(DOMAIN, PATH, languages=[directory])
                language.install()          
                desktopFile.writelines("Name[%s]=%s\n" % (directory, _(name)))
            except:
                pass

    desktopFile.writelines("Comment=%s\n" % comment)
    for directory in sorted(os.listdir(PATH)):
        if os.path.isdir(os.path.join(PATH, directory)):
            try:
                language = gettext.translation(DOMAIN, PATH, languages=[directory])
                language.install()                      
                desktopFile.writelines("Comment[%s]=%s\n" % (directory, _(comment)))
            except:
                pass

    desktopFile.writelines(suffix)
Example #17
0
def mylocale():
    """
    Disable in the original gui module the below changes:

        #import gettext
        #_ = gettext.lgettext

    Include in the original main module the below changes:
        import mylocale
        mylocale.mylocale()

    """
    import gettext

    try:
        mylanguage = "%s" % locale.getdefaultlocale()[0][0:2]
        #mylanguage = "en"
    except:
        mylanguage = "en"

    try:
        mylocale = gettext.translation('bakertool', localedir='locale', languages=[mylanguage])
        mylocale.install()
    except:
        mylocale = gettext.translation('bakertool', localedir='locale', languages=["en"])
        mylocale.install()
Example #18
0
    def test_cache(self):
        self.localedir = os.curdir
        self.mofile = MOFILE

        self.assertEqual(len(gettext._translations), 0)

        t = gettext.translation('gettext', self.localedir)

        self.assertEqual(len(gettext._translations), 1)

        t = gettext.translation('gettext', self.localedir,
                                class_=DummyGNUTranslations)

        self.assertEqual(len(gettext._translations), 2)
        self.assertEqual(t.__class__, DummyGNUTranslations)

        # Calling it again doesn't add to the cache

        t = gettext.translation('gettext', self.localedir,
                                class_=DummyGNUTranslations)

        self.assertEqual(len(gettext._translations), 2)
        self.assertEqual(t.__class__, DummyGNUTranslations)

        # Test deprecated parameter codeset
        with self.assertWarnsRegex(DeprecationWarning, 'parameter codeset'):
            t = gettext.translation('gettext', self.localedir,
                                    class_=DummyGNUTranslations,
                                    codeset='utf-16')
        self.assertEqual(len(gettext._translations), 2)
        self.assertEqual(t.__class__, DummyGNUTranslations)
        with self.assertWarns(DeprecationWarning):
            self.assertEqual(t.output_charset(), 'utf-16')
Example #19
0
def translate(uuid, string):
    #check for a translation for this xlet
    if uuid not in translations:
        try:
            translations[uuid] = gettext.translation(uuid, home + "/.local/share/locale").gettext
        except IOError:
            try:
                translations[uuid] = gettext.translation(uuid, "/usr/share/locale").gettext
            except IOError:
                translations[uuid] = None

    #do not translate whitespaces
    if not string.strip():
        return string

    if translations[uuid]:
        result = translations[uuid](string)

        try:
            result = result.decode("utf-8")
        except:
            result = result

        if result != string:
            return result
    return _(string)
Example #20
0
def generateDesktop(dest_path, installed_path, locale):
    menuName = "Cinnamon Installer"
    menuComment = "Install packages, applets, desklets, extensions and themes."
    tragetFile = os.path.join(dest_path, "cinnamon-installer.desktop")
    desktopFile = open(tragetFile, "w")
    desktopFile.writelines("[Desktop Entry]\n")
    desktopFile.writelines("Name=Cinnamon Installer\n")
    gettext.install("cinnamon", "/usr/share/locale")
    for directory in os.listdir(locale):
        if os.path.isdir(os.path.join(locale, directory)):
            try:
                language = gettext.translation("cinnamon-installer", locale, languages=[directory])
                language.install()
                desktopFile.writelines("Name[%s]=%s\n" % (directory, _(menuName)))
            except:
                pass
    for directory in os.listdir(locale):
        if os.path.isdir(os.path.join(locale, directory)):
            try:
                language = gettext.translation("cinnamon-installer", locale, languages=[directory])
                language.install()
                desktopFile.writelines("Comment[%s]=%s\n" % (directory, _(menuComment)))
            except:
                pass

    desktopFile.writelines("Exec=cinnamon-installer --manager applets\n")
    desktopFile.writelines("Icon=cinnamon-installer\n")
    desktopFile.writelines("Terminal=false\n")
    desktopFile.writelines("Type=Application\n")
    desktopFile.writelines("Encoding=UTF-8\n")
    desktopFile.writelines("OnlyShowIn=X-Cinnamon;\n")
    desktopFile.writelines("Categories=GNOME;GTK;Settings;DesktopSettings;\n")
    desktopFile.writelines("StartupNotify=false\n")
    st = os.stat(tragetFile)
    os.chmod(tragetFile, st.st_mode | stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH | stat.S_IEXEC)
Example #21
0
def set_active_language(app_name, locale_dir, lang):
 try:
  if lang == "Windows":
   LCID = ctypes.windll.kernel32.GetUserDefaultUILanguage()
   lang = locale.windows_locale[LCID]
   translation = gettext.translation(app_name, localedir=locale_dir, languages=[lang])
   translation.install(True, names=['ngettext'])
  else:
   translation = gettext.translation(app_name, localedir=locale_dir, languages=[lang])
   translation.install(True, names=['ngettext'])
   locale_changed = False
   try:
    locale.setlocale(locale.LC_ALL, lang)
    locale_changed = True
   except:
    pass
   if not locale_changed and '_' in lang:
    try:
					locale.setlocale(locale.LC_ALL, lang.split('_')[0])
    except:
     pass
   LCID = locale_name_to_LCID(lang)
   ctypes.windll.kernel32.SetThreadLocale(LCID)
  return True
 except IOError:
  gettext.install(app_name, unicode=True, names=['ngettext'])
Example #22
0
def ActivateTranslation(session, config, language):
    global ACTIVE_TRANSLATION, RECENTLY_TRANSLATED

    trans = None
    if language:
        try:
            trans = translation("mailpile", config.getLocaleDirectory(),
                                [language], codeset="utf-8")
        except IOError:
            if session and language[:2] != 'en':
                session.ui.debug('Failed to load language %s' % language)

    if not trans:
        trans = translation("mailpile", config.getLocaleDirectory(),
                            codeset='utf-8', fallback=True)

        if (session and language[:2] != 'en'
                and isinstance(trans, NullTranslations)):
            session.ui.debug('Failed to configure i18n. '
                             'Using fallback.')

    if trans:
        with RECENTLY_TRANSLATED_LOCK:
            RECENTLY_TRANSLATED = []
        ACTIVE_TRANSLATION = trans
        trans.set_output_charset("utf-8")

        if hasattr(config, 'jinja_env'):
            config.jinja_env.install_gettext_translations(trans,
                                                          newstyle=True)

        if session and language and not isinstance(trans, NullTranslations):
            session.ui.debug(gettext('Loaded language %s') % language)

    return trans
def setLanguage(lang):
	global curLang
	try:
		if lang=="Windows":
			windowsLCID=ctypes.windll.kernel32.GetUserDefaultUILanguage()
			localeName=locale.windows_locale[windowsLCID]
			gettext.translation('nvda',localedir='locale',languages=[localeName]).install(True)
			curLang=localeName
		else:
			gettext.translation("nvda", localedir="locale", languages=[lang]).install(True)
			curLang=lang
			localeChanged=False
			#Try setting Python's locale to lang
			try:
				locale.setlocale(locale.LC_ALL,lang)
				localeChanged=True
			except:
				pass
			if not localeChanged and '_' in lang:
				#Python couldn'tsupport the language_country locale, just try language.
				try:
					locale.setlocale(locale.LC_ALL,lang.split('_')[0])
				except:
					pass
			#Set the windows locale for this thread (NVDA core) to this locale.
			LCID=localeNameToWindowsLCID(lang)
			ctypes.windll.kernel32.SetThreadLocale(LCID)
		config.conf["general"]["language"]=lang
		return True
	except IOError:
		gettext.install("nvda", unicode=True)
		curLang="en"
		return False
Example #24
0
def setLanguage(lang):
	global curLang
	try:
		if lang=="Windows":
			localeName=getWindowsLanguage()
			trans=gettext.translation('nvda',localedir='locale',languages=[localeName])
			curLang=localeName
		else:
			trans=gettext.translation("nvda", localedir="locale", languages=[lang])
			curLang=lang
			localeChanged=False
			#Try setting Python's locale to lang
			try:
				locale.setlocale(locale.LC_ALL,lang)
				localeChanged=True
			except:
				pass
			if not localeChanged and '_' in lang:
				#Python couldn'tsupport the language_country locale, just try language.
				try:
					locale.setlocale(locale.LC_ALL,lang.split('_')[0])
				except:
					pass
			#Set the windows locale for this thread (NVDA core) to this locale.
			LCID=localeNameToWindowsLCID(lang)
			ctypes.windll.kernel32.SetThreadLocale(LCID)
	except IOError:
		trans=gettext.translation("nvda",fallback=True)
		curLang="en"
	trans.install(unicode=True)
	# Install our pgettext function.
	__builtin__.__dict__["pgettext"] = makePgettext(trans)
Example #25
0
def install():
    global le2mtrans
    try:
        le2mtrans = gettext.translation(
            "le2m", localedir, languages=[params.getp("LANG")]).ugettext
    except IOError:
        le2mtrans = gettext.translation("le2m", localedir).ugettext
Example #26
0
    def _switchLanguage(self):
        languages = None
        if self.c.language_select != 'automatic':
            languages = [self.c.language_select]

        log('Trying to set language to: "%s"' % languages)
        translationPath = os.path.abspath(os.path.join(xdm.APP_PATH, 'i18n'))
        log.info(u"Using i18n path %s" % translationPath)

        if not os.path.isdir(translationPath):
            log.error("%s is not a path. where is the i18n folder?" % translationPath)
            return
        fallback = common.STARTOPTIONS.dev
        try:
            t = gettext.translation('messages', translationPath, languages=languages, fallback=fallback)
        except IOError:
            log.warning("No language file found that matches %s. your locale %s" % (languages, locale.getlocale()))
            log.info("Trying to install language en_US as fallback")
            t = gettext.translation('messages', translationPath, languages=['en_US'], fallback=True)
            log.info("Setting language to en_US because of fallback")
            self.c.language_select = 'en_US'

        if isinstance(t, gettext.GNUTranslations):
            log.info(u'Instaling language "%s"' % t.info()['language-team'])
        else:
            log.warning(u'Installing a NULL translator because we could not find any matching .mo files not even for en_US :(')
        self._setLocale(self.c.language_select)
        t.install(True, ('gettext', 'ngettext', 'lgettext', 'lngettext'))
        # we need to re install the functions becuase they have changed
        # this is a very close binding of a plugin and the core XDM
        # but since this is the SYSTEM plugin i consider this ok
        # pylint: disable=E1101, E0602
        xdm.classes.elementWidgetEnvironment.install_gettext_callables(_, ngettext, newstyle=True)
        # pylint: disable=E1101, E0602
        web.env.install_gettext_callables(_, ngettext, newstyle=True)
Example #27
0
def _setLanguage(lang):
    if lang == 'en_US':
        import builtins as _builtins
        _builtins.__dict__['_'] = lambda s : s
    else:
        import gettext as _gettext
        _gettext.translation('cscircles', localedir='/static/locale/', languages=[lang]).install()
Example #28
0
def main ():
	
	APP = 'acqua'
	if os.name == 'nt':
		DIR = os.path.join (utils.DHOME_DIR, "locale")
	else:
		DIR = os.path.join (utils.PROG_DIR, "locale")
	
	try:
		
		if impostazioni.get ("lang").lower () == "en":
			en = gettext.translation (APP, DIR, ["en"])
			en.install ()
			try:
				os.environ['LANG'] = "en_US"
				locale.setlocale (locale.LC_MESSAGES, "en_US")
			except: pass
		elif impostazioni.get ("lang").lower () == "fr":
			fr = gettext.translation (APP, DIR, ["fr"])
			fr.install ()
			try:
				os.environ['LANG'] = "fr_FR"
				locale.setlocale (locale.LC_MESSAGES, "fr_FR")
			except: pass
		else:
			# In teoria qui risulta inutile settare. Il linguaggio italiano e' di default senza gettext.
			os.environ['LANG'] = "it_IT"
			it = gettext.translation (APP, DIR, [])
			it.install ()

	except (IOError, locale.Error), e:
		print "(%s): WARNING **: %s" % (APP, e)
		__builtins__.__dict__["_"] = gettext.gettext
Example #29
0
File: i18n.py Project: EHRI/resyto
def set_language(lang):
    __get__logger().debug("Trying to set language to %s", lang)
    languages.clear()
    languages.append(lang)

    __get__logger().debug(gettext.find(APP_NAME, LOCALE_DIR, languages=[lang]))
    gettext.translation(APP_NAME, LOCALE_DIR, languages=[lang], fallback=True).install()
    __get__logger().debug("Ready setting language to %s", lang)
Example #30
0
def get_i18n(languages = None):
    if languages is None:
        i18n = gettext.translation('libcredit', sys.prefix + '/share/locale', fallback = True)
    else:
        i18n = gettext.translation('libcredit', sys.prefix + '/share/locale', languages = languages)

    i18n.set_output_charset('utf-8')
    return i18n
Example #31
0
def iter_lines(f, f_name, lang):
    in_table = 0
    # if f_name:
    #    if "prj" in f_name:
    #        l = f_name.replace("\\", "/").split("prj")
    #        base_path = l[0] + "prj/" + l[1].split("/")[1] + "/"
    #    else:
    #        l = f_name.replace("\\", "/").split("templates_src")
    #        base_path = l[0] + "schserw/"
    # else:
    #    base_path = "./"
    base_path = os.path.join(settings.PRJ_PATH, get_prj_name())
    locale_path = os.path.join(base_path, "locale")

    tab_translate = []

    if lang != "en":
        try:
            try:
                t = gettext.translation(
                    "django",
                    locale_path,
                    languages=[
                        lang,
                    ],
                )
                t.install()
            except:
                t = None
            try:
                p = open(os.path.join(base_path, "translate.py"), "rt")
                for line in p.readlines():
                    fr = line.split('_("')
                    if len(fr) > 1:
                        fr = fr[1].split('")')
                        if len(fr) == 2:
                            tab_translate.append(fr[0])
                p.close()
            except:
                tab_translate = []

            def trans(word):
                if len(word) < 2:
                    return word
                if word[0] == word[-1] == '"' or word[0] == word[-1] == "'":
                    if word[0] == "'":
                        strtest = "'"
                    else:
                        strtest = '"'
                    word2 = word[1:-1]
                else:
                    strtest = None
                    word2 = word

                if not word2 in tab_translate:
                    tab_translate.append(word2)
                if t:
                    ret = t.gettext(word2)
                    if strtest != None:
                        return strtest + ret + strtest
                    else:
                        return ret
                else:
                    return translate(word)

            gt = trans
        except:
            gt = translate
    else:
        gt = translate

    for line in f:
        # if len(line.lstrip()) == 0:
        #    continue
        if line.lstrip().startswith("_") and not line.lstrip().startswith("_("):
            nr = line.find("_")
            line2 = " " * nr + "." + gt(line.strip()[1:])
        else:
            if "_(" in line and not "__(" in line:
                out = []
                if line.lstrip().startswith("_("):
                    fr0 = line.split("_(")
                    fr = (fr0[0] + ".", fr0[1])
                else:
                    fr = line.split("_(")
                out.append(fr[0])
                for pos in fr[1:]:
                    id2 = pos.find(")")
                    if id2 >= 0:
                        out.append(gt(pos[:id2]))
                        out.append(pos[id2 + 1 :])
                    else:
                        out.append(gt(pos))
                line2 = "".join(out)
            else:
                line2 = line

        line3 = line2.strip()
        if len(line3) > 0 and (line3[0] == "[" or line3[-1] == "]" or "|" in line3):
            if line3[0] == "[" and (
                line3[-1] == "|" or (line3[-1] == "]" and "|" in line3)
            ):
                if line3[1] == "[":
                    in_table = 2
                else:
                    in_table = 1
            if in_table == 1:
                line2 = (
                    line2.replace("[", "<tr><td>")
                    .replace("]", "</td></tr>")
                    .replace(" |", " </td><td>")
                )
            if in_table == 2:
                line2 = (
                    line2.replace("[[", "<tr><th>")
                    .replace("]]", "</th></tr>")
                    .replace(" |", " </th><th>")
                )
            if line3[-1] == "]":
                in_table = False
        yield line2
    yield "."
    if len(tab_translate) > 0:
        p = open(os.path.join(base_path, "translate.py"), "wt")
        for word in tab_translate:
            p.write('_("' + word + '")\n')
        p.close()
Example #32
0
from argparse import ArgumentParser,  RawTextHelpFormatter
from gettext import translation
from os import path, remove, makedirs
from polib import POEntry,  POFile, pofile
from shutil import copyfile
from subprocess import run
from pkg_resources import resource_filename
from translate_odf.version import __version__
from unogenerator import ODT
import xml.etree.ElementTree as ET

from translate_odf.version import argparse_epilog

try:
    t=translation('translate_odf', resource_filename("translate_odf","locale"))
    _=t.gettext
except:
    _=str

def run_check(command, shell=False):
    p=run(command, shell=shell, capture_output=True);
    if p.returncode!=0:
        print(f"Error en comando. {command}")
        print("STDOUT:")
        print(p.stdout.decode('utf-8'))
        print("STDERR:")
        print(p.stderr.decode('utf-8'))
        print("Saliendo de la instalación")
        exit(2)

def main_xlf():
Example #33
0
import gettext
import logging

logging.basicConfig(level=logging.DEBUG)

translation = gettext.translation('tkgbot', './locales', languages=['uk'])

database_url = 'sqlite:///data/data.sqlite3'

debug = True
database_debug_output = debug

POLLING_TIMEOUT = 300
FORUM_CHECK_INTERVAL = 60

THREAD_POOL_EXECUTOR_MAX_WORKERS = 3
Example #34
0
 def set_language(langs):
     global current_translation
     current_translation = _gettext.translation(APP_NAME,
                                                LOCALE_DIR,
                                                languages=langs,
                                                fallback=True)
Example #35
0
    You should have received a copy of the GNU General Public License
    along with Bottles.  If not, see <http://www.gnu.org/licenses/>.
'''
import gi
import os
import locale
import gettext
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

try:
    current_locale, encoding = locale.getdefaultlocale()
    locale_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                               'locale')
    print(locale_path)
    translate = gettext.translation('bottles', locale_path, [current_locale])
    _ = translate.gettext
except FileNotFoundError:
    _ = str


class App:
    application_shortname = "bottles"
    application_id = "com.github.mirkobrombin.bottles"
    application_name = _('Bottles')
    application_description = _('Easily manage your Wine bottles')
    application_version = "0.1.8"
    app_years = "2017-2018"
    main_url = "https://github.com/mirkobrombin/bottles"
    bug_url = "https://github.com/mirkobrombin/bottles/issues/labels/bug"
    help_url = "https://github.com/mirkobrombin/Bottles/wiki"
Example #36
0
from inary.util.curses import *
from inary.util.files import *
from inary.util.filesystem import *
from inary.util.kernel import *
from inary.util.misc import *
from inary.util.package import *
from inary.util.path import *
from inary.util.process import *
# Inary Modules
from inary.util.strings import *
from inary.util.terminal import *
from inary.util.terminal import *

# Gettext Library
import gettext
__trans = gettext.translation('inary', fallback=True)
_ = __trans.gettext


class Singleton(type):
    def __init__(cls, name, bases, dict):
        super(Singleton, cls).__init__(name, bases, dict)
        cls.instance = None

    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kw)

        return cls.instance

Example #37
0
# Copyright 2012 Red Hat, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         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.
"""
gettext for openstack-common modules.

Usual usage in an openstack.common module:

    from glance.openstack.common.gettextutils import _
"""

import gettext

t = gettext.translation('openstack-common', 'locale', fallback=True)


def _(msg):
    return t.ugettext(msg)
Example #38
0
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#

import csv
import sys

import gettext
t = gettext.translation('rho', 'locale', fallback=True)
_ = t.ugettext

# report fields we can use. Add them here so we can show them
# with --report-fields
report_fields = {
    'ip': _('ip address'),
    'port': _('ssh port'),
    'auth.type': _('type of ssh authentication used'),
    'auth.username': _('username ssh'),
    'auth.name': _('name of authentication class'),
    'error': _('any errors that are found')
}


class ScanReport(object):

    # rho_cmds and the list of rho_cmd_classes in scanner.Scanner to get
    # an idea what fields are available for reports
locale_dirs = [
    getBaseDir() + '/locale', '/usr/share/gyach/locale',
    '/usr/X11R6/share/gyach/locale', '/usr/gyach/locale',
    '/usr/local/share/gyach/locale'
]

# gettext locale support - pywebcam
pywebcam_xtext = gettext.NullTranslations()

try:
    # open pyvoice.mo in /usr/share/locale or whatever
    f_gettext = 0

    for LOCALE_DIR in locale_dirs:  # open the first catalog we find, try ./locale dir first
        try:
            pywebcam_xtext = gettext.translation("gyach", LOCALE_DIR)
            f_gettext = 1
            break
        except:
            pass
    if not f_gettext == 1:
        raise TypeError  # couldnt find a gettext catalog, raise exception, use empty catalog
except:
    pywebcam_xtext = gettext.NullTranslations()


def _(somestr):
    return to_utf8(pywebcam_xtext.gettext(somestr))


def set_window_icon(mywindow, my_xpm, is_stock=0):
Example #40
0
import ctypes
from ctypes import POINTER, byref

import six
from decimal import Decimal

import locale

import gettext
_ = lambda x: gettext.translation("libbytesize", fallback=True).gettext(
    x) if x != "" else ""
"""
Python bindings for the libbytesize library and it's BSSize "class". These
bindings provide a real Python class :class:`Size` which wraps the libbytesize
functionality and provides all the features one would expect from a numeric type
in Python.

.. note::
  ``None`` is treated as ``Size(0)`` in mathematical operations.

"""

c_bytesize = ctypes.CDLL("libbytesize.so.1")

B = 0
KiB = 1
MiB = 2
GiB = 3
TiB = 4
PiB = 5
EiB = 6
Example #41
0
# Client code for Update Agent
# Copyright (c) 2011--2012 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Simon Lukasik
#         Lukas Durfina
#

import os
import apt
import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
_ = t.ugettext


# FIXME: After Debian bug 187019 is resolved
def verifyPackages(packages):
    cache = apt.Cache()
    missing_packages = []
    for package in packages:
        pkg = cache[package[0]]
        if pkg == None or not pkg.is_installed:
            missing_packages.append(package)

    return [], missing_packages

def parseVRE(version):
    epoch = ''
    release = '0'
    if version.find(':') != -1:
        epoch, version = version.split(':')
    if version.find('-') != -1:
Example #42
0
"""
gettext for openstack-common modules.

Usual usage in an openstack.common module:

    from cinder.openstack.common.gettextutils import _
"""

import copy
import gettext
import logging.handlers
import os
import UserString

_localedir = os.environ.get('cinder'.upper() + '_LOCALEDIR')
_t = gettext.translation('cinder', localedir=_localedir, fallback=True)


def _(msg):
    return _t.ugettext(msg)


def install(domain):
    """Install a _() function using the given translation domain.

    Given a translation domain, install a _() function using gettext's
    install() function.

    The main difference from gettext.install() is that we allow
    overriding the default localedir (e.g. /usr/share/locale) using
    a translation-domain-specific environment variable (e.g.
Example #43
0
def get_i18n_content(fmt, local, **kw):
    """
    Get multilingual data structure according to format parameter id.

        reference
        - `Common Message Property <https://docs.python.org/2/library/gettext.html>`_

    :param fmt: Multilingual key string. like _('This is a translatable string.')
    :param local: Domain corresponding to "fmt".
    :param kw: Named variable parameter list.
        Common parameters:
            function: A callback function used to encapsulate multiple languages.
            type: Business type
    :return:
        If the parameter contains the package function of the package, An encapsulated multilingual dictionary object will be returned.
        If the parameter does not contain a package function, this returns a Multilingual list object.
    """
    ko = gettext.translation(local, 'locales', ['ko'])
    en = gettext.translation(local, 'locales', ['en'])
    ja = gettext.translation(local, 'locales', ['ja'])

    i18n_content = {}
    function = None
    if 'function' in kw:
        function = kw['function']
        if function is not None:
            i18n_content = []

    type = None
    i18n_types = None
    if 'type' in kw:
        type = kw['type']
        i18n_types = get_i18n_type(type)
        del kw['type']

    for lang in [('en_US', en), ('ja_JP', ja), ('ko_KR', ko)]:

        if function is not None:
            if len(kw) > 0:
                if type is not None:
                    i18n_content_item = function(
                        lang[0],
                        lang[1].gettext(fmt).format(type=i18n_types[lang[0]],
                                                    **kw))
                else:
                    i18n_content_item = function(
                        lang[0], lang[1].gettext(fmt).format(**kw))
            else:
                if type is not None:
                    i18n_content_item = function(
                        lang[0],
                        lang[1].gettext(fmt).format(type=i18n_types[lang[0]]))
                else:
                    i18n_content_item = function(lang[0], lang[1].gettext(fmt))

            i18n_content.append(i18n_content_item)
        elif len(kw) > 0:
            if type is not None:
                i18n_content[lang[0]] = lang[1].gettext(fmt).format(
                    type=i18n_types[lang[0]], **kw)
            else:
                i18n_content[lang[0]] = lang[1].gettext(fmt).format(**kw)
        else:
            if type is not None:
                i18n_content[lang[0]] = lang[1].gettext(fmt).format(
                    type=i18n_types[lang[0]])
            else:
                i18n_content[lang[0]] = lang[1].gettext(fmt)
    return i18n_content
Example #44
0
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import gettext, os

LOCALE_DIR = os.path.join(os.path.dirname(__file__), 'locale')
language = gettext.translation('electrum', LOCALE_DIR, fallback=True)


def _(x):
    global language
    return language.gettext(x)


def set_language(x):
    global language
    if x:
        language = gettext.translation('electrum',
                                       LOCALE_DIR,
                                       fallback=True,
                                       languages=[x])
Example #45
0
import codecs
import fnmatch
import logging
import os
import json
import urllib

from gi.repository import Gio

from .constants import XDG_CONFIG_DIR, XDG_AUTOSTART_DIR, XDG_AUTOSTART_FILE, APPINDICATOR_ID, LOCALE_DIR, LOG_LEVELS, MINIDLNA_INDICATOR_CONFIG, MINIDLNA_CONFIG_DIR
from .update_check_thread import UpdateCheckConfig
from .proxy import Proxy

import gettext
_ = gettext.translation(APPINDICATOR_ID, LOCALE_DIR, fallback=True).gettext


class MiniDLNAIndicatorConfig(UpdateCheckConfig):

    def __init__(self, config_file: str, cmd_log_level: Optional[str]=None) -> None:

        self.logger = logging.getLogger(__name__)

        UpdateCheckConfig.__init__(self)

        self.cmd_log_level = cmd_log_level

        if config_file and config_file != MINIDLNA_INDICATOR_CONFIG:
            if not os.path.exists(config_file):
                raise Exception(_("The file {file} doesn't exist.").format(file=config_file))
Example #46
0
import gettext
## contributed
import wx
## nobi
from nobi.ObserverPattern import Observer
## project
import UI
from UI import GUIId



# Internationalization
# requires "PackagePath = __path__[0]" in _init_.py
try:
    LocalesPath = os.path.join(UI.PackagePath, '..', 'locale')
    Translation = gettext.translation('MediaFiler', LocalesPath)  #, languages=['de'])
except BaseException as e:  # likely an IOError because no translation file found
    try:
        language = os.environ['LANGUAGE']
    except:
        print('%s: No LANGUAGE environment variable found!' % (__file__))
    else:
        print('%s: No translation found at %s; using originals instead of %s. Complete error:' % (__file__, LocalesPath, language))
        print(e)
    def _(message): return message
else:
#     _ = Translation.ugettext
    _ = Translation.gettext  # Python 3
def N_(message): return message

Example #47
0
#   SPDX-License-Identifier: GPL-3.0-or-later
#
#   Calamares is Free Software: see the License-Identifier above.
#

import abc
import os
import re
import libcalamares
import configparser

from libcalamares.utils import gettext_path, gettext_languages

import gettext
_translation = gettext.translation("calamares-python",
                                   localedir=gettext_path(),
                                   languages=gettext_languages(),
                                   fallback=True)
_ = _translation.gettext
_n = _translation.ngettext


class DesktopEnvironment:
    """
    Desktop Environment -- some utility functions for a desktop
    environment (e.g. finding out if it is installed). This
    is independent of the *Display Manager*, which is what
    we're configuring in this module.
    """
    def __init__(self, exec, desktop):
        self.executable = exec
        self.desktop_file = desktop
Example #48
0
import glob
import os
import shutil
import subprocess

from constants import HOME
from constants import MOUNT_ISO
from constants import MOUNT_USB
from constants import NAME
from constants import LOCALE
from constants import SHARE
from constants import SYSLINUX

from releases import releases

t = gettext.translation(NAME, LOCALE, fallback=True)
_ = t.ugettext


def getDiskInfo(dst):
    disk_info = os.statvfs(dst)
    capacity = int(disk_info.f_bsize * disk_info.f_blocks / 1024**2)
    available = int(disk_info.f_bsize * disk_info.f_bavail / 1024**2)
    used = int(disk_info.f_bsize * (disk_info.f_blocks - disk_info.f_bavail) /
               1024**2)

    return [capacity, available, used]


def getIsoSize(src):
    return os.stat(src).st_size
Example #49
0
the second.

It also implements a number of selector widgets, which can be used to select
various gimp data types.  Each of these selectors takes default as an argument
to the constructor, and has a get_value() method for retrieving the result.
'''

import pygtk
pygtk.require('2.0')

import gtk, gobject, gimp, gimpcolor

from _gimpui import *

import gettext
t = gettext.translation('gimp20-python', gimp.locale_directory, fallback=True)
_ = t.ugettext


def _callbackWrapper(menu_item, callback, data):
    callback(menu_item.get_data("Gimp-ID"), data)


def _createMenu(items, callback, data):
    menu = gtk.Menu()
    if not items:
        items = [("(none)", None)]
    for label, id in items:
        menu_item = gtk.MenuItem(label)
        menu_item.set_data("Gimp-ID", id)
        menu.add(menu_item)
Example #50
0
def setup_gettext(localedir, ui_language=None, logger=None):
    """Setup locales, load translations, install gettext functions."""
    if not logger:
        logger = lambda *a, **b: None  # noqa: E731
    current_locale = ''
    if ui_language:
        try:
            current_locale = locale.normalize(ui_language + '.' +
                                              locale.getpreferredencoding())
            locale.setlocale(locale.LC_ALL, current_locale)
        except Exception as e:
            logger(e)
    else:
        if IS_WIN:
            from ctypes import windll
            try:
                current_locale = locale.windows_locale[
                    windll.kernel32.GetUserDefaultUILanguage()]
                current_locale += '.' + locale.getpreferredencoding()
                locale.setlocale(locale.LC_ALL, current_locale)
            except KeyError:
                try:
                    current_locale = locale.setlocale(locale.LC_ALL, '')
                except Exception as e:
                    logger(e)
            except Exception as e:
                logger(e)
        elif IS_MACOS:
            try:
                import Foundation
                defaults = Foundation.NSUserDefaults.standardUserDefaults()
                current_locale = defaults.objectForKey_('AppleLanguages')[0]
                current_locale = current_locale.replace('-', '_')
                locale.setlocale(locale.LC_ALL, current_locale)
            except Exception as e:
                logger(e)
        else:
            try:
                locale.setlocale(locale.LC_ALL, '')
                current_locale = '.'.join(locale.getlocale(locale.LC_MESSAGES))
            except Exception as e:
                logger(e)
    os.environ['LANGUAGE'] = os.environ['LANG'] = current_locale
    QLocale.setDefault(QLocale(current_locale))
    logger("Using locale %r", current_locale)
    try:
        logger("Loading gettext translation, localedir=%r", localedir)
        trans = gettext.translation("picard", localedir)
        logger("Loading gettext translation (picard-countries), localedir=%r",
               localedir)
        trans_countries = gettext.translation("picard-countries", localedir)
        logger("Loading gettext translation (picard-attributes), localedir=%r",
               localedir)
        trans_attributes = gettext.translation("picard-attributes", localedir)
    except OSError as e:
        logger(e)
        trans = gettext.NullTranslations()
        trans_countries = gettext.NullTranslations()
        trans_attributes = gettext.NullTranslations()

    trans.install(['ngettext'])
    builtins.__dict__['gettext_countries'] = trans_countries.gettext
    builtins.__dict__['gettext_attributes'] = trans_attributes.gettext

    if hasattr(trans_attributes, 'pgettext'):
        builtins.__dict__['pgettext_attributes'] = trans_attributes.pgettext
    else:

        def pgettext(context, message):
            return gettext_ctxt(trans_attributes.gettext, message, context)

        builtins.__dict__['pgettext_attributes'] = pgettext

    logger("_ = %r", _)
    logger("N_ = %r", N_)
    logger("ngettext = %r", ngettext)
    logger("gettext_countries = %r", gettext_countries)
    logger("gettext_attributes = %r", gettext_attributes)
    logger("pgettext_attributes = %r", pgettext_attributes)
Example #51
0
import contextlib
import math
import os
import fcntl

import gi

gi.require_version('Gtk', '3.0')  # isort:skip
from gi.repository import Gtk, Gio, Gdk  # isort:skip

import gbulb
import pyinotify

import gettext

t = gettext.translation("desktop-linux-manager", fallback=True)
_ = t.gettext

gbulb.install()

DATA = "/var/run/qubes/qubes-clipboard.bin"
FROM = "/var/run/qubes/qubes-clipboard.bin.source"
FROM_DIR = "/var/run/qubes/"
XEVENT = "/var/run/qubes/qubes-clipboard.bin.xevent"
APPVIEWER_LOCK = "/var/run/qubes/appviewer.lock"


@contextlib.contextmanager
def appviewer_lock():
    fd = os.open(APPVIEWER_LOCK, os.O_RDWR | os.O_CREAT, 0o0666)
    try:
Example #52
0
"""i18n abstraction

License: GPL
Author: Vladimir Bormotov <*****@*****.**>

$Id: i18n.py,v 1.3 2004/01/28 07:31:02 skvidal Exp $
"""
# $RCSfile: i18n.py,v $
__version__ = "$Revision: 1.3 $"[11:-2]
__date__ = "$Date: 2004/01/28 07:31:02 $"[7:-2]

try:
    import gettext
    import sys
    if sys.version_info[0] == 2:
        t = gettext.translation('yum')
        _ = t.gettext
    else:
        gettext.bindtextdomain('yum', '/usr/share/locale')
        gettext.textdomain('yum')
        _ = gettext.gettext

except:

    def _(str):
        """pass given string as-is"""
        return str


if __name__ == '__main__':
    pass
Example #53
0
`fedmsg_meta_fedora_infrastructure
<https://github.com/fedora-infra/fedmsg_meta_fedora_infrastructure>`_.
If you'd like to add your own processors for your own deployment, you'll need
to extend :class:`fedmsg.meta.base.BaseProcessor` and override the appropriate
methods.  If you package up your processor and expose it on the ``fedmsg.meta``
entry-point, your new class will need to be added to the
:data:`fedmsg.meta.processors` list at runtime.

End users can have multiple plugin sets installed simultaneously.

"""

# gettext is used for internationalization.  I have tested that it can produce
# the correct files, but I haven't submitted it to anyone for translation.
import gettext
t = gettext.translation('fedmsg', 'locale', fallback=True)
_ = t.ugettext

import fedmsg.crypto

from fedmsg.meta.default import DefaultProcessor

import pkg_resources
import logging


class ProcessorsNotInitialized(Exception):
    def __iter__(self):
        raise self

    __len__ = __iter__
Example #54
0
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#

import sys
import os
import codecs
import re
import getopt
import glob
import zipfile

import gettext
__trans = gettext.translation('repokit', fallback=True)
_ = __trans.ugettext

from svn import core, client

import piksemel

sys.path.append('.')
import pisi.specfile
import pisi.uri
import pisi.metadata
from pisi.cli import printu
from pisi.util import filter_latest_packages

# Main HTML template
Example #55
0
def set_language(x):
    global language
    if x: language = gettext.translation('electrum', LOCALE_DIR, fallback = True, languages=[x])
# along with AFMS.  If not, see <http://www.gnu.org/licenses/>.
# -------------------------------------------------------------------

# $Id$

import os, os.path, sys, time, gettext, shutil
import unittest, subunittest
from pywinauto import application
import pywinauto.timings as timing
import afmstest
from afmstest import afEditorTestHelper

LOCALEDIR = os.path.join('..', 'locale')
DOMAIN = "afms"
gettext.install(DOMAIN, LOCALEDIR, unicode=True)
t = gettext.translation(DOMAIN, LOCALEDIR, languages=['en'])
t.install(unicode=True)
sys.path.append('..')

import afresource, afconfig


class TestDeleteRestoreArtefactContents(subunittest.TestCase):
    """Test deletion and restoration of artefacts"""
    def test_0010_NumberOfArtefacts(self):
        """Check number of artefacts in database"""
        self.assertEqual(helper.treeview.ItemCount(), 63)

    def _deleteSelectedItem(self, msg=None):
        helper.treeview.TypeKeys('{DEL}')
        helper.afeditorwin['&Yes'].Click()
Example #57
0
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#

import os

from pisi.scenarioapi.package import Package
from pisi.scenarioapi.withops import *
from pisi.scenarioapi.constants import *

import gettext
__trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext

repodb = {}

def repo_added_package(package, *args):
    if repodb.has_key(package):
        raise Exception(_("Repo already has package named %s.") % package)

    version = "1.0"
    partOf = "None"
    dependencies = []
    conflicts = []

    for with in args:
        if with.types == CONFLICT and with.action == INIT:
Example #58
0
except:
    logger.exception('error getting locale')
    user_locale = None
    encoding = None

if user_locale is None:
    user_locale = 'C'
    logger.warning("no default locale found.  Assuming '%s'", user_locale)

if 'win32' == sys.platform:
    os.environ['LANG'] = user_locale

try:
    if not os.path.exists(locale_dir):
        raise RuntimeError('translations not installed')
    t = gettext.translation('bleachbit', locale_dir)
    _ = t.gettext
except:

    def _(msg):
        """Dummy replacement for gettext"""
        return msg


try:
    locale.bindtextdomain('bleachbit', locale_dir)
except AttributeError:
    if sys.platform.startswith('win'):
        try:
            # We're on Windows; try and use libintl-8.dll instead
            import ctypes
Example #59
0
    def activateLanguage(self, index):
        try:
            if index not in self.lang:
                print "[Language] Selected language %s is not installed, fallback to en_US!" % index
                index = "en_US"
                Notifications.AddNotification(
                    MessageBox,
                    _("The selected langugage is unavailable - using en_US"),
                    MessageBox.TYPE_INFO,
                    timeout=3)
            lang = self.lang[index]
            print "[Language] Activating language " + lang[0]
            self.catalog = gettext.translation('enigma2',
                                               resolveFilename(
                                                   SCOPE_LANGUAGE, ""),
                                               languages=[index],
                                               fallback=True)
            self.catalog.install(names=("ngettext", "pgettext"))
            self.activeLanguage = index
            for x in self.callbacks:
                if x:
                    x()
        except:
            print "[Language] Selected language does not exist!"

        # These should always be C.UTF-8 (or POSIX if C.UTF-8 is unavaible) or program code might behave
        # differently depending on language setting
        try:
            locale.setlocale(locale.LC_CTYPE, ('C', 'UTF-8'))
        except:
            pass
        try:
            locale.setlocale(locale.LC_COLLATE, ('C', 'UTF-8'))
        except:
            try:
                locale.setlocale(locale.LC_COLLATE, ('POSIX', ''))
            except:
                pass

        # NOTE: we do not use LC_ALL, because LC_ALL will not set any of the categories, when one of the categories fails.
        # We'd rather try to set all available categories, and ignore the others
        for category in [
                locale.LC_TIME, locale.LC_MONETARY, locale.LC_MESSAGES,
                locale.LC_NUMERIC
        ]:
            try:
                locale.setlocale(category, (self.getLanguage(), 'UTF-8'))
            except:
                pass

        # Also write a locale.conf as /home/root/.config/locale.conf to apply language to interactive shells as well:
        try:
            os.stat('/home/root/.config')
        except:
            os.mkdir('/home/root/.config')

        localeconf = open('/home/root/.config/locale.conf', 'w')
        for category in [
                "LC_TIME", "LC_DATE", "LC_MONETARY", "LC_MESSAGES",
                "LC_NUMERIC", "LC_NAME", "LC_TELEPHONE", "LC_ADDRESS",
                "LC_PAPER", "LC_IDENTIFICATION", "LC_MEASUREMENT", "LANG"
        ]:
            if category == "LANG" or (category == "LC_DATE" and os.path.exists(
                    '/usr/lib/locale/' + self.getLanguage() +
                    '/LC_TIME')) or os.path.exists('/usr/lib/locale/' +
                                                   self.getLanguage() + '/' +
                                                   category):
                localeconf.write('export %s="%s.%s"\n' %
                                 (category, self.getLanguage(), "UTF-8"))
            else:
                if os.path.exists('/usr/lib/locale/C.UTF-8/' + category):
                    localeconf.write('export %s="C.UTF-8"\n' % category)
                else:
                    localeconf.write('export %s="POSIX"\n' % category)
        localeconf.close()
        # HACK: sometimes python 2.7 reverts to the LC_TIME environment value, so make sure it has the correct value
        os.environ["LC_TIME"] = self.getLanguage() + '.UTF-8'
        os.environ["LANGUAGE"] = self.getLanguage() + '.UTF-8'
        os.environ[
            "GST_SUBTITLE_ENCODING"] = self.getGStreamerSubtitleEncoding()
Example #60
0
def main():

    dir_path = str(Path.home())
    print("Starting NanoQuake2...")
    print()
    print("Current Dir: {}".format(dir_path))
    print("System: {}".format(platform.system()))

    # determine if application is a script file or frozen exe
    # https://stackoverflow.com/questions/404744/determining-application-path-in-a-python-exe-generated-by-pyinstaller
    if getattr(sys, 'frozen', False):
        work_dir = sys._MEIPASS
    elif __file__:
        work_dir = os.path.dirname(os.path.abspath(__file__))

    print("Work Dir: {}".format(work_dir))

    if (platform.system() == "Linux" or platform.system() == "Darwin"):
        dir_exists = Path(dir_path + '/.nanoquake').exists()
        if dir_exists == False:
            print("Making a new config directory")
            os.mkdir(dir_path + '/.nanoquake')
        nanoquake_path = dir_path + '/.nanoquake'

    elif (platform.system() == "Windows"):
        dir_exists = Path(dir_path + '/AppData/Local/NanoQuake').exists()
        if dir_exists == False:
            print("Making a new config directory")
            os.mkdir(dir_path + '/AppData/Local/NanoQuake')
        nanoquake_path = dir_path + '/AppData/Local/NanoQuake'

    else:
        print("Error - system not recognised")
        time.sleep(5)
        sys.exit()

    print("Config Directory: {}".format(nanoquake_path))

    old_exists = Path(nanoquake_path + '/seed.txt').exists()
    if old_exists == True:
        print(
            "Old seed file detected, as encryption has been upgraded please import your old seed, you can extract it with the decodeOldseed.py script"
        )

    exists = Path(nanoquake_path + '/seedAES.txt').exists()

    root = Tk()
    root.geometry("500x700")
    w = Label(root, text="NanoQuake v1.6", bg="blue4", fg="white")
    w.pack(fill=X)
    root.wm_title("NanoQuake v1.6")
    root.iconbitmap("nanoquake.ico")

    root.update()

    parser = configparser.ConfigParser()
    config_files = parser.read(nanoquake_path + '/config.ini')

    if len(config_files) == 0:
        lang = SelectLanguageDialog(root, nanoquake_path)
        root.wait_window(lang.top)
        selected_language = lang.get_lang()
        print(selected_language)
        parser.add_section('general')
        parser.set('general', 'language', selected_language)

        cfgfile = open(nanoquake_path + '/config.ini', 'w')
        parser.write(cfgfile)
        cfgfile.close()

    selected_language = parser.get('general', 'language')
    print(selected_language)
    localedirectory = work_dir + '/locale'
    try:
        lang1 = gettext.translation('nanoquake',
                                    localedir=localedirectory,
                                    languages=[selected_language])
        lang1.install()
    except:
        print("Error - not able to locate translation files, back to default")

    try:
        disclaimer_bool = parser.get('general', 'disclaimer')
    except:
        disclaimer_bool = "False"

    if disclaimer_bool != "True":
        disclaimer = disclaimerDialog(root)
        root.wait_window(disclaimer.top)
        parser.set('general', 'disclaimer', "True")

        cfgfile = open(nanoquake_path + '/config.ini', 'w')
        parser.write(cfgfile)
        cfgfile.close()

    while True:

        d = PasswordDialog(root, exists)
        root.wait_window(d.top)

        password = d.get_password()

        if exists == False:

            wallet_seed = None

            genImpSeed = GenerateSeedDialog(root, wallet_seed)
            root.wait_window(genImpSeed.top)

            wallet_seed = genImpSeed.get_seed()

            write_encrypted(password.encode('utf8'),
                            nanoquake_path + '/seedAES.txt', wallet_seed)
            priv_key, pub_key = nano.seed_account(str(wallet_seed), 0)
            public_key = str(binascii.hexlify(pub_key), 'ascii')
            print(_("Public Key: "), str(public_key))

            account = nano.account_xrb(str(public_key))
            print(_("Account Address: "), account)

            seed = wallet_seed
            break

        else:
            print()
            print(_("Seed file found"))
            print(_("Decoding wallet seed with your password"))
            try:
                wallet_seed = read_encrypted(password.encode('utf8'),
                                             nanoquake_path + '/seedAES.txt',
                                             string=True)
                priv_key, pub_key = nano.seed_account(str(wallet_seed), 0)
                public_key = str(binascii.hexlify(pub_key), 'ascii')
                print(_("Public Key: "), str(public_key))

                account = nano.account_xrb(str(public_key))
                print(_("Account Address: "), account)
                break
            except:
                print('\nError decoding seed, check password and try again')

    index = 0
    print()
    print(_("This is your game account address: {}").format(account))
    current_balance = nano.get_account_balance(account)
    if current_balance != "timeout":
        print(
            _("\nBalance: {:.3} Nano\n").format(
                Decimal(current_balance) / Decimal(raw_in_xrb)))

    r = nano.get_rates()
    if r != "timeout":

        print()
        print(_("NANO Rates"))
        print("- $:", r.json()['NANO']['USD'])
        print("- £:", r.json()['NANO']['GBP'])
        print("- €:", r.json()['NANO']['EUR'])

    if Path(work_dir + '/release/baseq2/pak0.pak').exists() == False or Path(
            work_dir + '/release/baseq2/players').exists() == False:

        f = DownloadDialog(root, work_dir)
        root.wait_window(f.top)

    if account == "xrb_33rhi9bp69i5zaftkyiacjmhwqnz1mcnfm9y6mpk8qx4xpht9cs9dzbxb9gb":
        showinfo(
            "NanoQuake",
            "Error incorrect seed - please delete seedAES.txt and restart NanoQuake"
        )
        sys.exit()

    data = 'xrb:' + account
    xrb_qr = pyqrcode.create(data)
    code_xbm = xrb_qr.xbm(scale=4)
    code_bmp = BitmapImage(data=code_xbm)
    code_bmp.config(background="white")
    label = Label(root, image=code_bmp)
    label.pack()

    w = Label(root, text=_("Your Game Account: "))
    w.pack()
    data_string = StringVar()
    data_string.set(account)
    w = Entry(root,
              textvariable=data_string,
              fg="black",
              bg="white",
              bd=0,
              state="readonly")
    w.pack()
    w.pack(fill=X)
    y = Label(root, text=_("Your Balance: "))
    y.pack()
    if current_balance != "timeout":
        y = Label(root,
                  text="{:.3} Nano".format(
                      Decimal(current_balance) / Decimal(raw_in_xrb)))
    else:
        y = Label(root, text=_("Timeout"))

    y.pack()

    listbox = Listbox(root)
    listbox.pack(fill=BOTH, expand=1)

    c = Button(root,
               text=_("Start Game"),
               command=lambda: thread_startGame(work_dir, account, wallet_seed,
                                                index))
    c.pack(pady=5)

    withdraw = Button(root,
                      text=_("Withdraw All"),
                      command=lambda: withdrawAllDialog(
                          root, account, index, wallet_seed, listbox))
    withdraw.pack(pady=5)

    settings = Button(
        root,
        text=_("Settings"),
        command=lambda: settingsDialog(root, nanoquake_path, wallet_seed))
    settings.pack(pady=5)

    quit = Button(root, text=_("Exit"), command=exitGame)
    quit.pack(pady=5)

    tcp = threading.Thread(target=start_server,
                           args=(
                               account,
                               wallet_seed,
                               index,
                               listbox,
                           ))
    tcp.daemon = True
    tcp.start()

    root.update()

    root.after(
        5000,
        lambda: update_txt(root, y, account, wallet_seed, index, listbox))
    root.mainloop()