Beispiel #1
0
 def __init__(self, controller):
     self.__controller = controller
     self.__user_pics = {}
     self.__queued_pics = []
     self.updating = [False, False, False]
     
     self.columns_lists = {}
     self.columns_viewed = []
     self.update_color = {
         'unread' : '#D2E2FF',
         'own' : '#FFFFCC',
         'mention' : '#E2FFD2',
         'favorite' : '#FFECD2',
     }
     
     # Reescritos en la clase hija
     self.imgdir = ''
     
     # Initialize gettext
     gettext_domain = 'turpial'
     # Definicion de localedir en modo desarrollo
     if os.path.isdir(os.path.join(os.path.dirname(__file__), '..', 'i18n')):
         localedir = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'i18n'))
         trans = gettext.install(gettext_domain, localedir)
         log.debug('LOCALEDIR: %s' % localedir)
     else:
         trans = gettext.install(gettext_domain)
def install(domain, lazy=False):
    """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.
    NOVA_LOCALEDIR).

    :param domain: the translation domain
    :param lazy: indicates whether or not to install the lazy _() function.
                 The lazy _() introduces a way to do deferred translation
                 of messages by installing a _ that builds Message objects,
                 instead of strings, which can then be lazily translated into
                 any available locale.
    """
    if lazy:
        from six import moves
        tf = TranslatorFactory(domain, lazy=True)
        moves.builtins.__dict__['_'] = tf.primary
    else:
        localedir = '%s_LOCALEDIR' % domain.upper()
        if six.PY3:
            gettext.install(domain,
                            localedir=os.environ.get(localedir))
        else:
            gettext.install(domain,
                            localedir=os.environ.get(localedir),
                            unicode=True)
Beispiel #3
0
	def __init__(self):
		gettext.install('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), unicode=0, codeset="utf-8")
		self.activeLanguage = 0
		self.catalog = None
		self.lang = {}
		self.InitLang()
		self.callbacks = []
Beispiel #4
0
def get_translation(domain, modfile=None):
    """
    Initialize a translation domain. Unless modfile is supplied,
    the translation will be searched for in the default location. If it
    is supplied, it's parent directory will be pre-pended to i18n to get
    the location to use.
    
    Translation objects are cached.
    
    Keyword arguments:
    domain        --    translation domain
    modfile       --    module file location (search relative to this file + /i18n)
    """
    if domain in __translations:
        return __translations[domain]
    gettext.install (True, localedir=None, unicode=1)
    translation_location = mo_location
    if modfile is not None:
        translation_location = "%s/i18n" % os.path.dirname(modfile)
    gettext.find(domain, translation_location)
    locale.bindtextdomain(domain, translation_location)
    gettext.bindtextdomain(domain, translation_location)
    gettext.textdomain (domain)
    gettext.bind_textdomain_codeset(domain, "UTF-8")
    language = gettext.translation (domain, translation_location, languages=languages, fallback=True)
    __translations[domain] = language
    return language
def bindtextdomain(app_name, locale_dir=None):
    """    
    Bind the domain represented by app_name to the locale directory locale_dir.
    It has the effect of loading translations, enabling applications for different
    languages.

    app_name:
        a domain to look for translations, tipically the name of an application.

    locale_dir:
        a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo
        If omitted or None, then the current binding for app_name is used.
    """    
    try:
        import locale
        import gettext
        locale.setlocale(locale.LC_ALL, "")
        gtk.glade.bindtextdomain(app_name, locale_dir)
        gettext.install(app_name, locale_dir, unicode=1)
    except (IOError,locale.Error), e:
        #force english as default locale
        try:
            os.environ["LANGUAGE"] = "en_US.UTF-8"
            locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
            gtk.glade.bindtextdomain(app_name, locale_dir)
            gettext.install(app_name, locale_dir, unicode=1)
            return
        except:
            #english didnt work, just use spanish
            try:
                __builtins__.__dict__["_"] = lambda x : x        
            except:
                __builtins__["_"] = lambda x : x
Beispiel #6
0
def setup_i18n():
    #determine location of po files
    try:
        from hamster import defs
    except:
        defs = None


    # to avoid confusion, we won't translate unless running installed
    # reason for that is that bindtextdomain is expecting
    # localedir/language/LC_MESSAGES/domain.mo format, but we have
    # localedir/language.mo at it's best (after build)
    # and there does not seem to be any way to run straight from sources
    if defs:
        locale_dir = os.path.realpath(os.path.join(defs.DATA_DIR, "locale"))

        for module in (locale,gettext):
            module.bindtextdomain('hamster-time-tracker', locale_dir)
            module.textdomain('hamster-time-tracker')

            module.bind_textdomain_codeset('hamster-time-tracker','utf8')

        gettext.install("hamster-time-tracker", locale_dir, unicode = True)

    else:
        gettext.install("hamster-time-tracker-uninstalled")
Beispiel #7
0
    def setUp(self):
        """ These tests are meant to be executed for the source main directory.
            Need to initialize the locale to deal with FieldValidator
            translated error messages. """
        gettext_path =  "./locale"

        gettext.install("pytrainer", gettext_path, unicode=1)
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)
Beispiel #9
0
def setup_locale_and_gettext():
	"""Set up localization with gettext"""
	package_name = "kupfer"
	localedir = "./locale"
	try:
		from kupfer import version_subst
	except ImportError:
		pass
	else:
		package_name = version_subst.PACKAGE_NAME
		localedir = version_subst.LOCALEDIR
	# Install _() builtin for gettext; always returning unicode objects
	# also install ngettext()
	gettext.install(package_name, localedir=localedir, unicode=True,
			names=("ngettext",))
	# For gtk.Builder, we need to call the C library gettext functions
	# As well as set the codeset to avoid locale-dependent translation
	# of the message catalog
	locale.bindtextdomain(package_name, localedir)
	locale.bind_textdomain_codeset(package_name, "UTF-8")
	# to load in current locale properly for sorting etc
	try:
		locale.setlocale(locale.LC_ALL, "")
	except locale.Error, e:
		pass
Beispiel #10
0
def install(domain, localedir):
    """
    :param domain: translation domain
    :param localedir: locale directory

    Installs the function _() in Python’s builtin namespace, based on
    domain and localedir. Codeset is always UTF-8.

    As seen below, you usually mark the strings in your application that are
    candidates for translation, by wrapping them in a call to the _() function,
    like this:

    .. sourcecode:: python

        import elib.intl
        elib.intl.install('myapplication', '/path/to/usr/share/locale')
        print _('This string will be translated.')

    Note that this is only one way, albeit the most convenient way,
    to make the _() function available to your application. Because it affects
    the entire application globally, and specifically Python’s built-in
    namespace, localized modules should never install _(). Instead, you should
    use :func:`elib.intl.install_module` to make _() available to your module.
    """
    _install(domain, localedir, True)
    gettext.install(domain, localedir, unicode=True)
	def __init__(self, project):
		"""Constructor"""  
		self.project = project
		
		# Setup foreign language support
		langs = []
		lc, encoding = locale.getdefaultlocale()

		if (lc):
			langs = [lc]			
		language = os.environ.get('LANGUAGE', None)
		if (language):
			langs += language.split(":")
		# Add languages... for testing
		#langs += ["es", "fr"]

		gtk.glade.textdomain("OpenShot")
		gtk.glade.bindtextdomain("OpenShot", self.project.LOCALE_DIR)
		
		gettext.textdomain("OpenShot")
		gettext.bindtextdomain("OpenShot", self.project.LOCALE_DIR)
		
		gettext.install(domain="OpenShot", unicode = True, codeset = 'utf-8')

		# This reference is used by other classes to define the _ method 
		self.lang = gettext.translation("OpenShot", self.project.LOCALE_DIR, languages = langs, fallback = True)
Beispiel #12
0
def setlang(lang=None):
    APP = release.name
    DIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'share', 'locale')
    if not os.path.isdir(DIR):
        DIR = os.path.join(sys.prefix, 'share', 'locale')
    if not os.path.isdir(DIR):
        gettext.install(APP, unicode=1)
        return False
    if lang:
        lc, encoding = locale.getdefaultlocale()
        if not encoding:
            encoding = 'UTF-8'
        elif encoding.lower() in ('utf','utf8',):
            encoding = 'UTF-8'
        elif encoding == 'cp1252':
            encoding = '1252'

        lang2 = lang
        if os.name == 'nt':
            lang2 = _LOCALE2WIN32.get(lang, lang)
            os.environ['LANG'] = lang
        elif os.name == 'mac':
            encoding = 'UTF-8'

        lang_enc = str(lang2 + '.' + encoding)
        try:
            locale.setlocale(locale.LC_ALL, lang_enc)
        except Exception,exception:
            logging.getLogger('translate').warning(
                    _('Unable to set locale %(lang_enc)s: %(exception)s') % {'lang_enc':lang_enc,'exception':exception})

        lang = gettext.translation(APP, DIR, languages=[lang], fallback=True)
        lang.install(unicode=1)
Beispiel #13
0
    def __init__(self):
        '''Initialize system.
        
        This parses command line arguments, detects available hardware,
        and already installed drivers and handlers.
        '''
        gettext.install('jockey', unicode=True)

        (self.argv_options, self.argv_args) = self.parse_argv()
        fix_stdouterr()

        if not OSLib.inst:
            OSLib.inst = OSLib(client_only=not self.argv_options.no_dbus,
                    target_kernel=self.argv_options.kernel)

        if self.argv_options.check:
            time.sleep(self.argv_options.check)

        self.init_strings()

        self._dbus_iface = None
        self.dbus_server_main_loop = None
        self.have_ui = False
        self.search_only = False
        self.current_search = (None, None) # query, result

        # make Control-C work properly
        signal.signal(signal.SIGINT, signal.SIG_DFL)
Beispiel #14
0
def main_func():
        gettext.install("pkg", "/usr/share/locale",
            codeset=locale.getpreferredencoding())

        outfilename = None
        printfilename = None
        verbose = False
        ignoreincludes = False

        try:
                opts, pargs = getopt.getopt(sys.argv[1:], "ivD:I:O:P:?", ["help"])
                for opt, arg in opts:
                        if opt == "-D":
                                if "=" not in arg:
                                        error(_("macros must be of form name=value"))
                                a = arg.split("=", 1)
                                if a[0] == "":
                                        error(_("macros must be of form name=value"))
                                macros.update([("$(%s)" % a[0], a[1])])
                        if opt == "-i":
                                ignoreincludes = True
                        if opt == "-I":
                                includes.append(arg)
                        if opt == "-O":
                                outfilename = arg
                        if opt == "-P":
                                printfilename = arg
                        if opt == "-v":
                                verbose = True
                        if opt in ("--help", "-?"):
                                usage(exitcode=0)

        except getopt.GetoptError, e:
                usage(_("illegal global option -- %s") % e.opt)
Beispiel #15
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)
Beispiel #16
0
def pretty_size(size, verbose=False):
    """
    Convert an integer to an human-readable file size string.

    @param size The size to convert to an human-readable string.
    @param verbose If True, do not use abbreviations (M -> Mega etc.)
    @return A string representing the size in human readable form.
    """
    import gettext

    gettext.install("python-sjutils")
    base = _("Bytes")
    for unit in ["", "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Zetta", "Yotta"]:
        if verbose:
            final_unit = len(unit) and (unit + base) or base
        else:
            final_unit = len(unit) and (unit[0] + base[0]) or base[0]

        if size < 1024.0:
            import math

            if math.floor(size) == size:
                return "%d %s" % (int(size), final_unit)
            else:
                return "%3.1f %s" % (size, final_unit)

        if unit != "Yotta":
            size /= 1024.0

    return "%3.1f %s" % (size, final_unit)
Beispiel #17
0
	def update_languages(self, data=None):
		if data is None:
			data = self._setting.get(UH_MODULE, "Language")
		languages_map = dict(find_available_languages())
		languages_map['System default'] = ''
		symbol = None
		if data == unicode('System default'):
			symbol = 'System default'
		else:
			for key, value in LANGUAGENAMES.iteritems():
				if value == data:
					symbol = key
		assert symbol is not None, "Something went badly wrong with the translation update!" + \
		       " Searching for: " + str(data) + " in " + str(LANGUAGENAMES)

		index = sorted(languages_map.keys()).index(symbol)
		name, position = sorted(languages_map.items())[index]
		try:
			if name != 'System default':
				trans = gettext.translation('unknownhorizons', position, languages=[name])
				trans.install(unicode=1)
			else:
				gettext.install('unknownhorizons', 'build/mo', unicode=1)
				name = ''

		except IOError:
			print _("Configured language %(lang)s at %(place)s could not be loaded") % {'lang': settings.language.name, 'place': settings.language.position}
			install('unknownhorizons', 'build/mo', unicode=1)
			self._setting.set(UH_MODULE, "Language", 'System default')
		update_all_translations()
 def setup_l10n ():
     """
     Install the _ gettext function
     """
     # FIXME: must take care if it has been already called then we're
     #       going to override the _
     gettext.install (defs.GETTEXT_PACKAGE, unicode=True)
Beispiel #19
0
def bindtextdomain(app_name, locale_dir=None):
    """    
    Bind the domain represented by app_name to the locale directory locale_dir.
    It has the effect of loading translations, enabling applications for different
    languages.

    app_name:
        a domain to look for translations, tipically the name of an application.

    locale_dir:
        a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo
        If omitted or None, then the current binding for app_name is used.
    """    
    try:
        import locale
        import gettext
        # FIXME: Commented to avoid problems with a .utf8 LANG variable...
        # locale.setlocale(locale.LC_ALL, "")
        gettext.bindtextdomain(app_name, locale_dir)
        gettext.textdomain(app_name)
        gtk.glade.bindtextdomain(app_name, locale_dir)
        gtk.glade.textdomain(app_name)
        gettext.install(app_name, locale_dir, unicode = 1)
    except (IOError,locale.Error), e:
        print "Warning", app_name, e
        __builtins__.__dict__["_"] = lambda x : x
Beispiel #20
0
def main (args):
    import locale
    import gettext

    import pygtk; pygtk.require('2.0');

    import gobject
    from gobject.option import OptionParser, make_option

    import gtk

    import maindialog
    import config

    locale.setlocale (locale.LC_ALL, "")
    gettext.install (config.PACKAGE, config.LOCALEDIR)

    parser = OptionParser (
            option_list = [
		    # FIXME: remove this when we can get all the default
		    # options
                    make_option ("--version",
                                 action="store_true",
                                 dest="version",
                                 help=config.VERSION),
                ])
    parser.parse_args (args)

    if parser.values.version:
        # Translators: %s is the version number 
        print _("Simple Menu Editor %s") % (config.VERSION)
    else:
        dialog = maindialog.MenuEditorDialog (args)
        gtk.main ()
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)
Beispiel #22
0
 def __init__(self):
     # Command line args
     args = sys.argv[1:]
     testmode = True if "--test" in args else False
     root = os.path.dirname(__path__[0]) if testmode else sys.prefix
     debugmode = True if "--debug" in args else False
     __builtins__['log'] = logm.log_main if debugmode else logm.log_null
     # Directories and localization
     self.locale = locale.getlocale()
     maindir = os.path.join(root, 'share', 'euphorbia')
     datadir = os.path.join(glib.get_user_data_dir(), 'euphorbia')
     confdir = os.path.join(glib.get_user_config_dir(), 'euphorbia')
     cfgfile = os.path.join(confdir, 'euphorbia.cfg')
     locales = os.path.join(root, 'share', 'locale')
     gettext.install('euphorbia', locales)
     # Preferences
     self.prefm = prefs.PrefsManager(cfgfile, testmode)
     self.prefm.set_pref('system_maindir', maindir)
     self.prefm.set_pref('system_datadir', datadir)
     self.prefm.set_pref('system_confdir', confdir)
     # Load application
     self.plugm = exts.PluginsManager(self)
     self.gui = ui.EuphorbiaGUI(self)
     self._load_plugins()
     self.prefm.autoconnect_gtk(self.gui.win)
     # Open files given in command line
     args = [a for a in args if not a.startswith("--")]
     projfile = self.prefm.get_pref('files_lastprj')
     if len(args) > 0:
         for f in args:
             self.gui.do_open(f, 'all')
     elif self.prefm.get_pref('files_reopenprj') and projfile is not None:
         self.gui.do_open(projfile, 'project')
     else:
         self.gui.act_new()
Beispiel #23
0
def parseCLI(cli_opts_args):
    """Parse command line interface arguments."""

    gettext.install("beadm", "/usr/lib/locale")

    if len(cli_opts_args) == 0:
        usage()

    subcommand = cli_opts_args[0]
    opts_args = cli_opts_args[1:]

    if subcommand == "activate":
        rc = activate(opts_args)
    elif subcommand == "create":
        rc = create(opts_args)
    elif subcommand == "destroy":
        rc = destroy(opts_args)
    elif subcommand == "list":
        rc = list(opts_args)
    elif subcommand == "mount":
        rc = mount(opts_args)
    elif subcommand == "rename":
        rc = rename(opts_args)
    elif subcommand == "upgrade":
        rc = upgrade(opts_args)
    elif subcommand == "unmount" or subcommand == "umount":  # aliased for convenience
        rc = unmount(opts_args)
    elif subcommand == "verify":
        rc = verify()
    else:
        msg.printMsg(msg.Msgs.BEADM_ERR_ILL_SUBCOMMAND, subcommand, -1)
        usage()

    return rc
Beispiel #24
0
 def set_locales(self):
   """internationalization config. Use only once."""
   
   domain = self.distro + '-installer'
   bindtextdomain(domain, LOCALEDIR)
   textdomain(domain)
   install(domain, LOCALEDIR, unicode=1)
Beispiel #25
0
def bindtextdomain(app_name, lang='',locale_dir=None):
        """     
        Bind the domain represented by app_name to the locale directory locale_dir.
        It has the effect of loading translations, enabling applications for different
        languages.
        
        app_name:
                a domain to look for translations, tipically the name of an application.
        
        locale_dir:
                a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo
                If omitted or None, then the current binding for app_name is used.
        """ 
        module_logger.debug("bindtextdomain called with: %s %s %s" %\
                            (app_name, lang,locale_dir))
        module_logger.debug("Setting gvr_gtk to locale: %s" % lang) 
        try:
            import locale
            import gettext
##            locale.setlocale(locale.LC_ALL, lang)
            gtk.glade.bindtextdomain(app_name, locale_dir)
            gettext.textdomain(app_name)
            gettext.install(app_name, locale_dir, unicode=1)
        except (IOError,locale.Error), e:
            print "Warning", app_name, e
            __builtin__.__dict__["_"] = lambda x : x
Beispiel #26
0
 def __init__(self):
     fileDirectory = os.path.dirname(__file__)
     self.preferences = GFrameCatcher.libs.preferences.Preferences()
     gobject.set_application_name(self.preferences.ProgramName)
     gettext.bindtextdomain(self.preferences.ProgramName, self.preferences.LocalePath)
     gettext.textdomain(self.preferences.ProgramName)
     gettext.install(self.preferences.ProgramName, localedir= self.preferences.LocalePath,unicode= True)
     self.builder = gtk.Builder()
     self.builder.add_from_file(os.path.join(fileDirectory , "ui/mainWindow.ui"))
     self.builder.set_translation_domain(self.preferences.ProgramName)
     self.builder.connect_signals(self)
     self.window = self.builder.get_object("window1")
     self.window.set_icon(GdkPixbuf.Pixbuf.new_from_file(os.path.join(fileDirectory , "../icons/gframecatcher16.png")))
     self.window.set_default_size(int(self.preferences.getValue("Window", "width")), int(self.preferences.getValue("Window", "height")))
     self.builder.get_object("toolZoomFitButton").set_active(bool(int(self.preferences.getValue("Window", "zoomFit"))))
     self.window.show_all()
     self.MediaInfo = GFrameCatcher.media.mediaLibrary.MediaInfo()
     self.model = gtk.ListStore(GdkPixbuf.Pixbuf, str)
     self.builder.get_object("frameView").set_from_pixbuf(None)
     videoDrop = [("text/uri-list" , 0 , 82 )]
     # self.builder.get_object("frameIconView").set_model(self.model)
     # self.builder.get_object("frameIconView").drag_dest_set(
     #     gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP, videoDrop , gtk.gdk.ACTION_COPY
     # )
     self.__imageDrag = [("text/uri-list", 0, 81), ("image/png", 0, 82)]
     # self.builder.get_object("viewPort").drag_source_set(gtk.gdk.BUTTON1_MASK, self.__imageDrag, gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_COPY)
     self.builder.get_object("viewPort").drag_dest_unset()
     self.window.connect("configure-event", self.on_configure_event)
     self.window.connect("window-state-event", self.on_window_state_event)
     self.window.connect("destroy", self.on_imageQuit_activate)
Beispiel #27
0
 def __init__(self, template=None):
     """Create a new :api:`Resource <twisted.web.resource.Resource>` for a
     Mako-templated webpage.
     """
     gettext.install("bridgedb", unicode=True)
     CSPResource.__init__(self)
     self.template = template
Beispiel #28
0
 def __init__(self):
     self.message = Observable(None)
     self.users = []
     self.users.append(User("admin", "1234", True))
     self.users.append(User("reader", "qwerty", False))
     self.users.append(User("q", "q", True))
     gettext.install("IMsg", "./locale", unicode=True)
def init_i18n() :
    locale.setlocale(locale.LC_ALL, '')
    gettext.bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALEDIR)
    gettext.textdomain(GETTEXT_PACKAGE)
    lang = gettext.translation(GETTEXT_PACKAGE, PACKAGE_LOCALEDIR)
    _ = lang.gettext
    gettext.install(GETTEXT_PACKAGE, PACKAGE_LOCALEDIR)
Beispiel #30
0
def initialize_gettext(gettext_path):
    locale.bindtextdomain("pytrainer", gettext_path)
    locale.textdomain("pytrainer")
    if sys.version_info[0] == 2:
        gettext.install("pytrainer", gettext_path, unicode=1)
    else:
        gettext.install("pytrainer", gettext_path)
Beispiel #31
0
## the GNU General Public License for more details.  You should have
## received a copy of the GNU General Public License along with image-to-gcode;
## if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
## Fifth Floor, Boston, MA 02110-1301 USA.
##
## image-to-gcode.py is Copyright (C) 2005 Chris Radek
## [email protected]
## image-to-gcode.py is Copyright (C) 2006 Jeff Epler
## [email protected]

import sys, os
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
sys.path.insert(0, os.path.join(BASE, "lib", "python"))

import gettext
gettext.install("linuxcnc", localedir=os.path.join(BASE, "share", "locale"))


def cmp(a, b):
    return (a > b) - (a < b)


try:
    from PIL import Image
except ImportError:
    import Image

import numpy.core
plus_inf = numpy.core.Inf

from rs274.author import Gcode
Beispiel #32
0
#    under the License.

"""
Routines for configuring OpenStack Service
"""
import gettext
import logging
import logging.config
import logging.handlers
import sys
import os

from keystone import cfg


gettext.install("keystone", unicode=1)


class Config(cfg.CommonConfigOpts):
    def __call__(self, config_files=None):
        if config_files is not None:
            self._opts["config_file"]["opt"].default = config_files
        return super(Config, self).__call__()

    def __getitem__(self, key, default=None):
        return getattr(self, key, default)

    def __setitem__(self, key, value):
        return setattr(self, key, value)

    def iteritems(self):
Beispiel #33
0
    """ Exception handler, to log uncuaght exceptions to our log file.
    """
    logger.critical('Uncaught exception:\n{}'.format(
        logging.Formatter().formatException(exc_info)))
    sys.__excepthook__(*exc_info)


sys.excepthook = uncaught_handler

if util.IS_WINDOWS:
    if os.getenv('LANG') is None:
        lang, enc = locale.getdefaultlocale()
        os.environ['LANG'] = lang

locale.setlocale(locale.LC_ALL, '')
gettext.install('pympress', util.get_locale_dir())

try:
    # python 2.7 does not have this
    ModuleNotFoundError
except NameError:
    ModuleNotFoundError = ImportError

# Load python bindings for gobject introspections, aka pygobject, aka gi, and pycairo.
# These are dependencies that are not specified in the setup.py, so we need to start here.
# They are not specified because:
# - installing those via pip requires compiling (always for pygobject, if no compatible wheels exist for cairo),
# - compiling requires a compiling toolchain, development packages of the libraries, etc.,
# - all of this makes more sense to be handled by the OS package manager,
# - it is hard to make pretty error messages pointing this out at `pip install` time,
#   as they would have to be printed when the dependency resolution happens.
"""
system-monitor-applet-config
Tool for editing system-monitor-applet preference as
an alternative of dconf-editor

"""
from sys import exit

from gi.repository import Gtk, Gio, Gdk

import os.path
import gettext
#from gettext import gettext as _
#gettext.textdomain('system-monitor-applet')
home = os.path.expanduser("~")
gettext.install("system-monitor@ebbes", home + "/.local/share/locale")


def color_to_hex(color):
    return "#%02x%02x%02x%02x" % (color.red * 255, color.green * 255,
                                  color.blue * 255, color.alpha * 255)


def hex_to_color(hexstr):
    return Gdk.RGBA(
        int(hexstr[1:3], 16) / 255.,
        int(hexstr[3:5], 16) / 255.,
        int(hexstr[5:7], 16) / 255.,
        int(hexstr[7:9], 16) / 255. if len(hexstr) == 9 else 1) \
        if (len(hexstr) != 4 & len(hexstr) != 5) else Gdk.RGBA(
        int(hexstr[1], 16) / 15.,
Beispiel #35
0
sys.path.append('/usr/lib/cinnamon-settings/bin')
import os
import glob
import gettext
from gi.repository import Gio, Gtk, GObject, GdkPixbuf, GLib, Pango, Gdk, cairo
import SettingsWidgets
import capi
import time
import traceback
import locale
import urllib2
import proxygsettings
from functools import cmp_to_key

# i18n
gettext.install("cinnamon", "/usr/share/locale")

# Standard setting pages... this can be expanded to include applet dirs maybe?
mod_files = glob.glob('/usr/lib/cinnamon-settings/modules/*.py')
mod_files.sort()
if len(mod_files) is 0:
    print "No settings modules found!!"
    sys.exit(1)

mod_files = [x.split('/')[5].split('.')[0] for x in mod_files]

for mod_file in mod_files:
    if mod_file[0:3] != "cs_":
        raise Exception("Settings modules must have a prefix of 'cs_' !!")

modules = map(__import__, mod_files)
Beispiel #36
0
    def __str__(self):
        return self.scontext


##
## I18N
##
PROGNAME = "policycoreutils"
try:
    import gettext
    kwargs = {}
    if sys.version_info < (3, ):
        kwargs['unicode'] = True
    gettext.install(PROGNAME,
                    localedir="/usr/share/locale",
                    codeset='utf-8',
                    **kwargs)
except:
    try:
        import builtins
        builtins.__dict__['_'] = str
    except ImportError:
        import __builtin__
        __builtin__.__dict__['_'] = unicode


class fcontextPage(semanagePage):
    def __init__(self, xml):
        semanagePage.__init__(self, xml, "fcontext", _("File Labeling"))
        self.fcontextFilter = xml.get_object("fcontextFilterEntry")
        self.fcontextFilter.connect("focus_out_event", self.filter_changed)
Beispiel #37
0
import os
import re
import sys
import textwrap
import traceback
from copy import deepcopy
from clang.cindex import CursorKind

from clang.cindex import AccessSpecifier

class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
    pass


logger = logging.getLogger(__name__)
gettext.install(__name__)
_SEPARATOR = "\x00"

def _parents(container):
    parents = []
    parent = container.semantic_parent
    while parent and parent.kind != CursorKind.TRANSLATION_UNIT:
        parents.append(parent.spelling)
        parent = parent.semantic_parent
    if parents:
        parents = "::".join(reversed(parents))
    else:
        parents = os.path.basename(container.translation_unit.spelling)
    return parents

Beispiel #38
0
    import commands
    import sys
    import string    
    import gettext
    from gi.repository import Gio, Gtk
    from gi.repository import GdkPixbuf 
    import gconf
    import json
    from user import home
except Exception, detail:
    print detail
    sys.exit(1)


# i18n
gettext.install("cinnamon-settings", "/usr/share/cinnamon/locale")

# i18n for menu item
menuName = _("Desktop Settings")
menuGenericName = _("Desktop Configuration Tool")
menuComment = _("Fine-tune desktop settings")
                                  
class SidePage:
    def __init__(self, name, icon, content_box):        
        self.name = name
        self.icon = icon
        self.content_box = content_box
        self.widgets = []
        
    def add_widget(self, widget):
        self.widgets.append(widget)
Beispiel #39
0
# 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
"""
  Constants - manage VDO constants.

  $Id: //eng/vdo-releases/magnesium/src/python/vdo/vdomgmnt/Constants.py#1 $

"""
import gettext
gettext.install('vdomgmnt')


class Constants(object):
    """Constants manages constant values."""
    LOCK_DIR = '/var/lock/vdo'
    SECTOR_SIZE = 512
    VDO_BLOCK_SIZE = 4096
    (KB, MB, GB, TB, PB, EB) = map(lambda x: 2**(10 * x), range(1, 7))

    lvmByteSuffix = 'b'
    lvmKiloSuffix = 'k'
    lvmMegaSuffix = 'm'
    lvmGigaSuffix = 'g'
    lvmTeraSuffix = 't'
    lvmPetaSuffix = 'p'
Beispiel #40
0
import distutils.command.build
from distutils.dep_util import newer
from distutils.spawn import find_executable
import re
import os
import sys
import glob
import gettext
import json
import locale
import urllib.request
from stat import ST_MODE

import lazygal

gettext.install('lazygal')


class test_lazygal(Command):

    description = 'Run the test suite'
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        import lazygaltest
Beispiel #41
0
import locale
import os
#import inspect

GETTEXT_PACKAGE = 'myapplication'
APP_NAME = "wxSynfig"
VERSION = "0.0.1"

gui_path = os.path.dirname(__file__)  # studio\gui
src_path = os.path.dirname(gui_path)
studio_path = os.path.dirname(gui_path)  # studio
images_path = os.path.join(studio_path, "images//")  #studio\images

#__FILE__ =

gettext.install(GETTEXT_PACKAGE)


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


def N_(x):
    return x


def locale_from_utf8(utf8_str):
    try:
        retval = unicode(utf8_str,
                         "utf-8").encode(locale.getpreferredencoding())
    except:
Beispiel #42
0
def main_func():
    gettext.install("pkg",
                    "/usr/share/locale",
                    codeset=locale.getpreferredencoding())

    repo_uri = os.getenv("PKG_REPO", None)

    show_usage = False
    global_settings.client_name = "pkgsend"
    try:
        opts, pargs = getopt.getopt(sys.argv[1:], "s:D:?", ["help", "debug="])
        for opt, arg in opts:
            if opt == "-s":
                repo_uri = arg
            elif opt == "-D" or opt == "--debug":
                if arg == "allow-timestamp":
                    key = arg
                    value = True
                else:
                    try:
                        key, value = arg.split("=", 1)
                    except (AttributeError, ValueError):
                        usage(
                            _("{opt} takes argument of form "
                              "name=value, not {arg}").format(opt=opt,
                                                              arg=arg))
                DebugValues.set_value(key, value)
            elif opt in ("--help", "-?"):
                show_usage = True
    except getopt.GetoptError as e:
        usage(_("illegal global option -- {0}").format(e.opt))

    if repo_uri and not repo_uri.startswith("null:"):
        repo_uri = misc.parse_uri(repo_uri)

    if DebugValues:
        reload(pkg.digest)
    subcommand = None
    if pargs:
        subcommand = pargs.pop(0)
        if subcommand == "help":
            show_usage = True

    if show_usage:
        usage(retcode=0)
    elif not subcommand:
        usage()

    if not repo_uri and subcommand not in ("create-repository", "generate",
                                           "publish"):
        usage(_("A destination package repository must be provided "
                "using -s."),
              cmd=subcommand)

    visitors = [SolarisBundleVisitor()]
    ret = 0
    try:
        if subcommand == "create-repository":
            ret = trans_create_repository(repo_uri, pargs)
        elif subcommand == "open":
            ret = trans_open(repo_uri, pargs)
        elif subcommand == "append":
            ret = trans_append(repo_uri, pargs)
        elif subcommand == "close":
            ret = trans_close(repo_uri, pargs)
        elif subcommand == "add":
            ret = trans_add(repo_uri, pargs)
        elif subcommand == "import":
            ret = trans_import(repo_uri, pargs, visitors=visitors)
        elif subcommand == "include":
            ret = trans_include(repo_uri, pargs)
        elif subcommand == "publish":
            ret = trans_publish(repo_uri, pargs)
        elif subcommand == "generate":
            ret = trans_generate(pargs, visitors=visitors)
        elif subcommand == "refresh-index":
            ret = trans_refresh_index(repo_uri, pargs)
        else:
            usage(_("unknown subcommand '{0}'").format(subcommand))

        printed_space = False
        for visitor in visitors:
            for warn in visitor.warnings:
                if not printed_space:
                    print("")
                    printed_space = True
                error(warn, cmd=subcommand)

            for err in visitor.errors:
                if not printed_space:
                    print("")
                    printed_space = True
                error(err, cmd=subcommand)
                ret = 1
    except pkg.bundle.InvalidBundleException as e:
        error(e, cmd=subcommand)
        ret = 1
    except getopt.GetoptError as e:
        usage(
            _("illegal {cmd} option -- {opt}").format(cmd=subcommand,
                                                      opt=e.opt))

    return ret
"""

import os
import sys
import platform
import subprocess
import locale
import pickle
import json
import re
import gettext
import gpg

SHARE = os.getenv('TBL_SHARE', sys.prefix + '/share') + '/torbrowser-launcher'

gettext.install('torbrowser-launcher')

# We're looking for output which:
#
#  1. The first portion must be `[GNUPG:] IMPORT_OK`
#  2. The second must be an integer between [0, 15], inclusive
#  3. The third must be an uppercased hex-encoded 160-bit fingerprint
gnupg_import_ok_pattern = re.compile(
    b"(\[GNUPG\:\]) (IMPORT_OK) ([0-9]|[1]?[0-5]) ([A-F0-9]{40})")


class Common(object):
    def __init__(self, tbl_version):
        self.tbl_version = tbl_version

        # initialize the app
Beispiel #44
0
import os
import re
import subprocess
import time
import shutil
import gettext
import stat
import commands
import sys
import parted

gettext.install("live-installer", "/usr/share/linuxmint/locale")

CONFIG_FILE = '/etc/live-installer/live-installer.conf'


class InstallerEngine:
    ''' This is central to the live installer '''
    def __init__(self):
        # Set distribution name and version
        def _get_config_dict(
            file,
            key_value=re.compile(
                r'^\s*(\w+)\s*=\s*["\']?(.*?)["\']?\s*(#.*)?$')):
            """Returns POSIX config file (key=value, no sections) as dict.
            Assumptions: no multiline values, no value contains '#'. """
            d = {}
            with open(file) as f:
                for line in f:
                    try:
                        key, value, _ = key_value.match(line).groups()
Beispiel #45
0
import os
import sys
import types
import re
import atexit
import subprocess
import shutil
import codecs
import types as python_types

from utils import KeyValue, parse_key_val, basename, encode
from grass.exceptions import ScriptError

# i18N
import gettext
gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))

# subprocess wrapper that uses shell on Windows


class Popen(subprocess.Popen):
    _builtin_exts = set(['.com', '.exe', '.bat', '.cmd'])

    @staticmethod
    def _escape_for_shell(arg):
        # TODO: what are cmd.exe's parsing rules?
        return arg

    def __init__(self, args, **kwargs):
        if (sys.platform == 'win32' and isinstance(args, list)
                and not kwargs.get('shell', False)
Beispiel #46
0
import locale
import gettext
import os
import string
from glob import glob
from urllib import unquote

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gio, GLib

from plugins.easybuttons import easyButton
from plugins.execute import Execute

# i18n
gettext.install("mintmenu", "/usr/share/linuxmint/locale")
locale.bindtextdomain("mintmenu", "/usr/share/linuxmint/locale")
locale.textdomain("mintmenu")

home = os.path.expanduser("~")


class pluginclass(object):
    def __init__(self, mintMenuWin, toggleButton, de):

        self.mintMenuWin = mintMenuWin
        self.toggleButton = toggleButton
        self.de = de

        # Read UI file
        builder = Gtk.Builder()
Beispiel #47
0
        if curposition == self.dockp.position_bottom:
            menuxy = utils.getScreenMiddle('bottom')
            utils.m.click(menuxy[0], menuxy[1], 2)
            time.sleep(2)
            pyautogui.press('down')
            pyautogui.press('down')
            pyautogui.press('down')
            pyautogui.press('down')
            pyautogui.press('down')
            pyautogui.press('right')
            pyautogui.press('down')
            pyautogui.press('down')
            pyautogui.press('enter')
            utils.m.move(100, 100)
            time.sleep(2)

        pluginnetwork = self.dock.dockObj.child(self.dock.string_plugin_datetime)
        self.assertTrue(pluginnetwork != None)

    def suite():
        suite = unittest.TestSuite()
        suite.addTest(Dock_PluginDatetime('testPluginDatetimeHide'))
        suite.addTest(Dock_PluginDatetime('testPluginDatetimeDisplay'))
        return suite

if __name__ == "__main__":
    unittest.installHandler()
    LOCALE_DIR = os.path.abspath("./lib/locale")
    gettext.install('dsystem', LOCALE_DIR)
    runTest(Dock_PluginDatetime)
Beispiel #48
0
import codecs
import fnmatch
import gettext
import gi
import os
import platform
import re
import sys
from html.parser import HTMLParser
import traceback

from gi.repository import Gio

from Classes import Update, Alias, Rule, KERNEL_PKG_NAMES, META_NAMES

gettext.install("mintupdate", "/usr/share/locale")


class KernelVersion():
    def __init__(self, version):
        self.version = version
        version_array = self.version.replace("-", ".").split(".")
        self.numeric_versions = []
        for i in range(4):
            element = version_array[i]
            if len(element) == 1:
                element = "00%s" % element
            elif len(element) == 2:
                element = "0%s" % element
            self.numeric_versions.append(element)
        self.numeric_representation = ".".join(self.numeric_versions)
Beispiel #49
0
"""
Internationalization functionality for AutoSimC.
"""
import gettext
import locale
import logging

from settings import settings
try:
    from settings_local import settings
except ImportError:
    pass

gettext.install('AutoSimC')
translator = gettext.translation('AutoSimC', fallback=True)


class TranslatedText(str):
    """Represents a translatable text string, while also keeping a reference to the original (English) string"""
    def __new__(cls, message, translate=True):
        if translate:
            return super(TranslatedText,
                         cls).__new__(cls, translator.gettext(message))
        else:
            return super(TranslatedText, cls).__new__(cls, message)

    def __init__(self, message, translate=True):
        self.original_message = message

    def format(self, *args, **kwargs):
        s = TranslatedText(str.format(self, *args, **kwargs), translate=False)
Beispiel #50
0
	"<big><b>A programming error has been detected during the execution of %s %s.</b></big>"
	"\n\n<tt><small>%s</small></tt>") % ( NAME, VERSION, trace.getvalue())
	dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, 
		gtk.BUTTONS_OK, message)
	dialog.set_title(_("Bug Detected"))
	dialog.set_markup(message)
	dialog.run()
	dialog.hide()
	sys.exit(1)

if __name__ == "__main__":

	sys.excepthook = excepthook

	name = "parano"
	gettext.install(name, unicode=1)
	gtk.glade.bindtextdomain(name)
	gtk.glade.textdomain(name)

	# (longName, shortName, type , default, flags, descrip , argDescrip)
	table=[
		("quiet"  , 'q'   , None ,   None  , 0    , 'Do not print any message on stdout'   , ""),
	]

	gnome.init(NAME, VERSION, gnome.libgnome_module_info_get()) 
	
	leftover, argdict = gnome.popt_parse(sys.argv, table)

	if argdict["quiet"]: option_quiet = True
		
	log(NAME +" "+ VERSION)
Beispiel #51
0
import gettext

#: Version information (major, minor, revision[, 'dev']).
version_info = (1, 0, 0)
#: Version string 'major.minor.revision'.
version = __version__ = ".".join(map(str, version_info))
gettext.install('swift-setup')
Beispiel #52
0
def main():
    global app

    # set thread name
    threading.currentThread().setName('MAIN')

    # fix threading time bug
    time.strptime("2012", "%Y")

    # add sickrage libs path to python system path
    if not (LIBS_DIR in sys.path):
        sys.path, remainder = sys.path[:1], sys.path[1:]
        site.addsitedir(LIBS_DIR)
        sys.path.extend(remainder)

    # set system default language
    gettext.install('messages',
                    LOCALE_DIR,
                    unicode=1,
                    codeset='UTF-8',
                    names=["ngettext"])

    try:
        from sickrage.core import Core

        # main app instance
        app = Core()

        # sickrage startup options
        parser = argparse.ArgumentParser(prog='sickrage')
        parser.add_argument('-v',
                            '--version',
                            action='version',
                            version='%(prog)s {}'.format(version()))
        parser.add_argument('-d',
                            '--daemon',
                            action='store_true',
                            help='Run as a daemon (*NIX ONLY)')
        parser.add_argument('-q',
                            '--quite',
                            action='store_true',
                            help='Disables logging to CONSOLE')
        parser.add_argument(
            '-p',
            '--port',
            default=0,
            type=int,
            help='Override default/configured port to listen on')
        parser.add_argument('--dev',
                            action='store_true',
                            help='Enable developer mode')
        parser.add_argument('--debug',
                            action='store_true',
                            help='Enable debugging')
        parser.add_argument(
            '--datadir',
            default=os.path.abspath(
                os.path.join(os.path.expanduser("~"), '.sickrage')),
            help=
            'Overrides data folder for database, config, cache and logs (specify full path)'
        )
        parser.add_argument(
            '--config',
            default='config.ini',
            help=
            'Overrides config filename (specify full path and filename if outside datadir path)'
        )
        parser.add_argument(
            '--pidfile',
            default='sickrage.pid',
            help=
            'Creates a PID file (specify full path and filename if outside datadir path)'
        )
        parser.add_argument('--nolaunch',
                            action='store_true',
                            help='Suppress launching web browser on startup')

        # Parse startup args
        args = parser.parse_args()
        app.quite = args.quite
        app.web_port = int(args.port)
        app.no_launch = args.nolaunch
        app.developer = args.dev
        app.debug = args.debug
        app.data_dir = os.path.abspath(
            os.path.realpath(os.path.expanduser(args.datadir)))
        app.cache_dir = os.path.abspath(
            os.path.realpath(os.path.join(app.data_dir, 'cache')))
        app.config_file = args.config
        daemonize = (False, args.daemon)[not sys.platform == 'win32']
        pid_file = args.pidfile

        if not os.path.isabs(app.config_file):
            app.config_file = os.path.join(app.data_dir, app.config_file)

        if not os.path.isabs(pid_file):
            pid_file = os.path.join(app.data_dir, pid_file)

        # check lib requirements
        check_requirements()

        # add sickrage module to python system path
        if not (PROG_DIR in sys.path):
            sys.path, remainder = sys.path[:1], sys.path[1:]
            site.addsitedir(PROG_DIR)
            sys.path.extend(remainder)

        # Make sure that we can create the data dir
        if not os.access(app.data_dir, os.F_OK):
            try:
                os.makedirs(app.data_dir, 0o744)
            except os.error:
                sys.exit("Unable to create data directory '" + app.data_dir +
                         "'")

        # Make sure we can write to the data dir
        if not os.access(app.data_dir, os.W_OK):
            sys.exit("Data directory must be writeable '" + app.data_dir + "'")

        # Make sure that we can create the cache dir
        if not os.access(app.cache_dir, os.F_OK):
            try:
                os.makedirs(app.cache_dir, 0o744)
            except os.error:
                sys.exit("Unable to create cache directory '" + app.cache_dir +
                         "'")

        # Make sure we can write to the cache dir
        if not os.access(app.cache_dir, os.W_OK):
            sys.exit("Cache directory must be writeable '" + app.cache_dir +
                     "'")

        # daemonize if requested
        if daemonize:
            app.no_launch = True
            app.quite = True
            app.daemon = Daemon(pid_file, app.data_dir)
            app.daemon.daemonize()

        # start app
        app.start()

        # main thread loop
        while app.started:
            time.sleep(1)
    except (SystemExit, KeyboardInterrupt):
        if app: app.shutdown()
    except ImportError:
        traceback.print_exc()
        if os.path.isfile(REQS_FILE):
            print(
                "Failed to import required libs, please run "
                "'pip install --user -U -r {}' from console".format(REQS_FILE))
    except Exception:
        traceback.print_exc()
Beispiel #53
0
#    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.

import routes
import gettext

gettext.install('heat', unicode=1)

from heat.api.cloudwatch import watch
from heat.common import wsgi

from webob import Request
from heat.api.middleware.version_negotiation import VersionNegotiationFilter
from heat.api.cloudwatch import versions

from heat.openstack.common import log as logging

logger = logging.getLogger(__name__)


class API(wsgi.Router):
    """
Beispiel #54
0
import signal
import optparse
import inspect

import gtk

from . import widget
from .metacity import show_keybinder

from .meta import __version__, TRANSLATORS, COPYRIGHT, PROGRAMNAME, PROGRAMDESCRIPTION

#import os
#os.environ['DISPLAY']=':0.0'

import gettext
gettext.install('arandr')


def actioncallback(function):
    """Wrapper around a function that is intended to be used both as a callback from a gtk.Action and as a normal function.

    Functions taking no arguments will never be given any, functions taking one argument (callbacks for radio actions) will be given the value of the action or just the argument.

    A first argument called 'self' is passed through."""
    argnames = inspect.getargspec(function)[0]
    if argnames[0] == 'self':
        has_self = True
        argnames.pop(0)
    else:
        has_self = False
    assert len(argnames) in (0, 1)
Beispiel #55
0
import gettext, locale
#import pygtk
#pygtk.require('2.0')

from gobject import timeout_add_seconds
try:
    from gimpfu import *
except ImportError:
    import sys
    print("Note: GIMP is needed, '%s' is a plug-in.\n" % str(__file__))
    sys.exit(1)

# Internationalization 'i18n'
locale_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), \
                    'locale') # for users; administrator: gimp.locale_directory
gettext.install("autosave_a", locale_directory, unicode=True)


class Save_recall():
    """
    Store, load and query dictionary name with string variable keyNr
    N.B.: this version does not accept unicode (eval?)
    """
    def __init__(self):
        folder = os.path.dirname(
            os.path.abspath(__file__)) + os.sep + 'autosave_a'
        self.file_shelf = folder + os.sep + 'autosave.cfg'
        # if folder not there create it
        if not os.path.exists(folder): os.mkdir(folder)

    def save(self, keyNr):
Beispiel #56
0
import pkg_resources
import re
import readline
import shutil
import sys
import textwrap
import traceback

import lib50
import requests
import termcolor

from . import __version__, CONFIG_LOADER

# Internationalization
gettext.install("submit50",
                pkg_resources.resource_filename("submit50", "locale"))

SUBMIT_URL = "https://submit.cs50.io"


class Error(Exception):
    pass


def check_announcements():
    """Check for any announcements from submit.cs50.io, raise Error if so."""
    res = requests.get(f"{SUBMIT_URL}/status/submit50")
    if res.status_code == 200 and res.text.strip():
        raise Error(res.text.strip())

Beispiel #57
0
#!python3.6
import gettext
import pathlib
langPath = str(pathlib.Path('../res/i18n/languages').resolve())
gettext.install('hello', langPath)
print(_('Hello World !!'))

langs = ['ja', 'en', 'de']
lang = 'ja'
while lang:
    print(f'言語コードを入力してください(未入力+Enterで終了) {langs}: ', end='')
    lang = input()
    if lang not in langs: continue
    l = gettext.translation('hello', langPath, languages=[lang])
    l.install()
    print(_('Welcome i18n !!'))
                    wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        self.SetSizer(sizer_1)
        self.Layout()
        # end wxGlade

    def on_passwod(self, event):  # wxGlade: MyDialog.<event_handler>
        if self.text_ctrl_passwd.Value:
            self.button_ok.Enable(True)
        else:
            self.button_ok.Disable()
        event.Skip()

    def on_button_cancel(self, event):  # wxGlade: MyDialog.<event_handler>
        print "Event handler 'on_button_cancel' not implemented!"
        event.Skip()

    def on_button_ok(self, event):  # wxGlade: MyDialog.<event_handler>
        print "Event handler 'on_button_ok' not implemented!"
        event.Skip()


# end of class MyDialog
if __name__ == "__main__":
    gettext.install("app")  # replace with the appropriate catalog name

    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    password_input = MyDialog(None, wx.ID_ANY, "")
    app.SetTopWindow(password_input)
    password_input.Show()
    app.MainLoop()
Beispiel #59
0
try:
  from . import xlib
except ImportError:
  print('Error: Missing xlib, run sudo apt-get install python-xlib')
  sys.exit(-1)

from . import options
from . import lazy_pixbuf_creator
from . import mod_mapper
from . import settings
from . import shaped_window
from . import two_state_image

from configparser import SafeConfigParser

gettext.install('key-mon', 'locale')

def fix_svg_key_closure(fname, from_tos):
  """Create a closure to modify the key.
  Args:
    from_tos: list of from, to pairs for search replace.
  Returns:
    A bound function which returns the file fname with modifications.
  """

  def fix_svg_key():
    """Given an SVG file return the SVG text fixed."""
    logging.debug(f'Read file {fname!r}')
    fin = open(fname)
    fbytes = fin.read()
    fin.close()
Beispiel #60
0
# Copyright 2011 OpenStack Foundation
# 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.

import gettext

from debtcollector import removals
import six

if six.PY2:
    gettext.install('neutron', unicode=1)
else:
    gettext.install('neutron')

# flake8: noqa
six.moves.builtins.__dict__['_'] = removals.remove(
    message='Builtin _ translation function is deprecated in OpenStack; '
    'use the function from _i18n module for your project.')(_)