Python gettext.gettext() Examples

The following are 30 code examples of gettext.gettext(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gettext , or try the search function .
Example #1
Source File: add.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def scan_qr(self):
        """
            Scans a QRCode and fills the entries with the correct data.
        """
        from ...models import QRReader, GNOMEScreenshot
        filename = GNOMEScreenshot.area()
        if filename:
            qr_reader = QRReader(filename)
            secret = qr_reader.read()
            if qr_reader.ZBAR_FOUND:
                if not qr_reader.is_valid():
                    self.__send_notification(_("Invalid QR code"))
                else:
                    self.token_entry.set_text(secret)
            else:
                self.__send_notification(_("zbar library is not found. "
                                           "QRCode scanner will be disabled")) 
Example #2
Source File: argparse.py    From link-prediction_with_deep-learning with MIT License 6 votes vote down vote up
def _format_args(self, action, default_metavar):
        get_metavar = self._metavar_formatter(action, default_metavar)
        if action.nargs is None:
            result = '%s' % get_metavar(1)
        elif action.nargs == OPTIONAL:
            result = '[%s]' % get_metavar(1)
        elif action.nargs == ZERO_OR_MORE:
            result = '[%s [%s ...]]' % get_metavar(2)
        elif action.nargs == ONE_OR_MORE:
            result = '%s [%s ...]' % get_metavar(2)
        elif action.nargs == REMAINDER:
            result = '...'
        elif action.nargs == PARSER:
            result = '%s ...' % get_metavar(1)
        else:
            formats = ['%s' for _ in range(action.nargs)]
            result = ' '.join(formats) % get_metavar(action.nargs)
        return result 
Example #3
Source File: argparse.py    From link-prediction_with_deep-learning with MIT License 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        parser_name = values[0]
        arg_strings = values[1:]

        # set the parser name if requested
        if self.dest is not SUPPRESS:
            setattr(namespace, self.dest, parser_name)

        # select the parser
        try:
            parser = self._name_parser_map[parser_name]
        except KeyError:
            tup = parser_name, ', '.join(self._name_parser_map)
            msg = _('unknown parser %r (choices: %s)' % tup)
            raise ArgumentError(self, msg)

        # parse all the remaining options into the namespace
        parser.parse_args(arg_strings, namespace)


# ==============
# Type classes
# ============== 
Example #4
Source File: argparse.py    From link-prediction_with_deep-learning with MIT License 6 votes vote down vote up
def __call__(self, string):
        # the special argument "-" means sys.std{in,out}
        if string == '-':
            if 'r' in self._mode:
                return _sys.stdin
            elif 'w' in self._mode:
                return _sys.stdout
            else:
                msg = _('argument "-" with mode %r' % self._mode)
                raise ValueError(msg)

        # all other arguments are used as file names
        if self._bufsize:
            return open(string, self._mode, self._bufsize)
        else:
            return open(string, self._mode) 
Example #5
Source File: list.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def _build_widgets(self):
        """
            Build EmptyAccountList widget.
        """
        self.set_border_width(36)
        self.set_valign(Gtk.Align.CENTER)
        self.set_halign(Gtk.Align.CENTER)

        # Image
        g_icon = Gio.ThemedIcon(name="dialog-information-symbolic.symbolic")
        img = Gtk.Image.new_from_gicon(g_icon, Gtk.IconSize.DIALOG)

        # Label
        label = Gtk.Label(label=_("There are no accounts yet…"))

        self.pack_start(img, False, False, 6)
        self.pack_start(label, False, False, 6) 
Example #6
Source File: getopt.py    From jawfish with MIT License 6 votes vote down vote up
def long_has_args(opt, longopts):
    possibilities = [o for o in longopts if o.startswith(opt)]
    if not possibilities:
        raise GetoptError(_('option --%s not recognized') % opt, opt)
    # Is there an exact match?
    if opt in possibilities:
        return False, opt
    elif opt + '=' in possibilities:
        return True, opt
    # No exact match, so better be unique.
    if len(possibilities) > 1:
        # XXX since possibilities contains all valid continuations, might be
        # nice to work them into the error msg
        raise GetoptError(_('option --%s not a unique prefix') % opt, opt)
    assert len(possibilities) == 1
    unique_match = possibilities[0]
    has_arg = unique_match.endswith('=')
    if has_arg:
        unique_match = unique_match[:-1]
    return has_arg, unique_match 
Example #7
Source File: edit.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def _build_widgets(self):
        header_bar = Gtk.HeaderBar()
        header_bar.set_show_close_button(False)
        header_bar.set_title(_("Edit {} - {}".format(self._account.username,
                                                     self._account.provider)))
        self.set_titlebar(header_bar)
        # Save btn
        self.save_btn = Gtk.Button()
        self.save_btn.set_label(_("Save"))
        self.save_btn.connect("clicked", self._on_save)
        self.save_btn.get_style_context().add_class("suggested-action")
        header_bar.pack_end(self.save_btn)

        self.close_btn = Gtk.Button()
        self.close_btn.set_label(_("Close"))
        self.close_btn.connect("clicked", self._on_quit)

        header_bar.pack_start(self.close_btn)

        self.account_config = AccountConfig(edit=True, account=self._account)
        self.account_config.connect("changed", self._on_account_config_changed)

        self.add(self.account_config) 
Example #8
Source File: edit.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def _on_save(self, *_):
        """
            Save Button clicked signal handler.
        """
        new_account = self.account_config.account
        username = new_account["username"]
        provider = new_account["provider"]
        old_provider = self._account.provider
        # Update the AccountRow widget
        self.emit("updated", username, provider)
        # Update the providers list
        if provider != old_provider:
            from .list import AccountsWidget
            ac_widget = AccountsWidget.get_default()
            ac_widget.update_provider(self._account, provider)
        self._on_quit() 
Example #9
Source File: getopt.py    From jawfish with MIT License 6 votes vote down vote up
def do_longs(opts, opt, longopts, args):
    try:
        i = opt.index('=')
    except ValueError:
        optarg = None
    else:
        opt, optarg = opt[:i], opt[i+1:]

    has_arg, opt = long_has_args(opt, longopts)
    if has_arg:
        if optarg is None:
            if not args:
                raise GetoptError(_('option --%s requires argument') % opt, opt)
            optarg, args = args[0], args[1:]
    elif optarg is not None:
        raise GetoptError(_('option --%s must not have an argument') % opt, opt)
    opts.append(('--' + opt, optarg or ''))
    return opts, args

# Return:
#   has_arg?
#   full option name 
Example #10
Source File: settings.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def __on_clear_database_clicked(self, *__):
        notification = Gd.Notification()
        notification.set_timeout(5)
        notification.connect("dismissed", self.__clear_database)
        container = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        notification_lbl = Gtk.Label()
        notification_lbl.set_text(_("The existing accounts will be erased in 5 seconds"))
        container.pack_start(notification_lbl, False, False, 3)

        undo_btn = Gtk.Button()
        undo_btn.set_label(_("Undo"))
        undo_btn.connect("clicked", lambda widget: notification.hide())
        container.pack_end(undo_btn, False, False, 3)

        notification.add(container)
        notification_parent = self.stack.get_child_by_name("behaviour")
        notification_parent.add(notification)
        notification_parent.reorder_child(notification, 0)
        self.show_all() 
Example #11
Source File: argparse.py    From link-prediction_with_deep-learning with MIT License 6 votes vote down vote up
def _match_argument(self, action, arg_strings_pattern):
        # match the pattern for this action to the arg strings
        nargs_pattern = self._get_nargs_pattern(action)
        match = _re.match(nargs_pattern, arg_strings_pattern)

        # raise an exception if we weren't able to find a match
        if match is None:
            nargs_errors = {
                None: _('expected one argument'),
                OPTIONAL: _('expected at most one argument'),
                ONE_OR_MORE: _('expected at least one argument'),
            }
            default = _('expected %s argument(s)') % action.nargs
            msg = nargs_errors.get(action.nargs, default)
            raise ArgumentError(action, msg)

        # return the number of arguments matched
        return len(match.group(1)) 
Example #12
Source File: argparse.py    From link-prediction_with_deep-learning with MIT License 6 votes vote down vote up
def _get_value(self, action, arg_string):
        type_func = self._registry_get('type', action.type, action.type)
        if not _callable(type_func):
            msg = _('%r is not callable')
            raise ArgumentError(action, msg % type_func)

        # convert the value to the appropriate type
        try:
            result = type_func(arg_string)

        # ArgumentTypeErrors indicate errors
        except ArgumentTypeError:
            name = getattr(action.type, '__name__', repr(action.type))
            msg = str(_sys.exc_info()[1])
            raise ArgumentError(action, msg)

        # TypeErrors or ValueErrors also indicate errors
        except (TypeError, ValueError):
            name = getattr(action.type, '__name__', repr(action.type))
            msg = _('invalid %s value: %r')
            raise ArgumentError(action, msg % (name, arg_string))

        # return the converted value
        return result 
Example #13
Source File: argparse.py    From vulscan with MIT License 6 votes vote down vote up
def _format_args(self, action, default_metavar):
        get_metavar = self._metavar_formatter(action, default_metavar)
        if action.nargs is None:
            result = '%s' % get_metavar(1)
        elif action.nargs == OPTIONAL:
            result = '[%s]' % get_metavar(1)
        elif action.nargs == ZERO_OR_MORE:
            result = '[%s [%s ...]]' % get_metavar(2)
        elif action.nargs == ONE_OR_MORE:
            result = '%s [%s ...]' % get_metavar(2)
        elif action.nargs == REMAINDER:
            result = '...'
        elif action.nargs == PARSER:
            result = '%s ...' % get_metavar(1)
        else:
            formats = ['%s' for _ in range(action.nargs)]
            result = ' '.join(formats) % get_metavar(action.nargs)
        return result 
Example #14
Source File: gnupg.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def _build_widgets(self):
        header_bar = Gtk.HeaderBar()
        header_bar.set_show_close_button(True)
        header_bar.set_title(_("GPG paraphrase"))
        apply_btn = Gtk.Button()
        apply_btn.set_label(_("Import"))
        apply_btn.get_style_context().add_class("suggested-action")
        apply_btn.connect("clicked", self.__on_apply)
        header_bar.pack_end(apply_btn)
        self.set_titlebar(header_bar)

        container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.paraphrase_widget = SettingsBoxWithEntry(_("Paraphrase"), True)
        container.pack_start(self.paraphrase_widget, False, False, 0)
        container.get_style_context().add_class("settings-main-container")
        self.add(container) 
Example #15
Source File: gnupg.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def __on_apply(self, *__):
        from ...models import BackupJSON
        try:
            paraphrase = self.paraphrase_widget.entry.get_text()
            if not paraphrase:
                paraphrase = " "
            output_file = path.join(GLib.get_user_cache_dir(),
                                    path.basename(NamedTemporaryFile().name))
            status = GPG.get_default().decrypt_json(self._filename, paraphrase, output_file)
            if status.ok:
                BackupJSON.import_file(output_file)
                self.destroy()
            else:
                self.__send_notification(_("There was an error during the import of the encrypted file."))

        except AttributeError:
            Logger.error("[GPG] Invalid JSON file.") 
Example #16
Source File: argparse.py    From vulscan with MIT License 6 votes vote down vote up
def __call__(self, string):
        # the special argument "-" means sys.std{in,out}
        if string == '-':
            if 'r' in self._mode:
                return _sys.stdin
            elif 'w' in self._mode:
                return _sys.stdout
            else:
                msg = _('argument "-" with mode %r' % self._mode)
                raise ValueError(msg)

        try:
            # all other arguments are used as file names
            if self._bufsize:
                return open(string, self._mode, self._bufsize)
            else:
                return open(string, self._mode)
        except IOError:
            err = _sys.exc_info()[1]
            message = _("can't open '%s': %s")
            raise ArgumentTypeError(message % (string, err)) 
Example #17
Source File: headerbar.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
        Gtk.HeaderBar.__init__(self)

        self.search_btn = HeaderBarToggleButton("system-search-symbolic",
                                                _("Search"))
        self.add_btn = HeaderBarButton("list-add-symbolic",
                                       _("Add a new account"))
        self.settings_btn = HeaderBarButton("open-menu-symbolic",
                                            _("Settings"))
        self.select_btn = HeaderBarButton("object-select-symbolic",
                                          _("Selection mode"))

        self.cancel_btn = Gtk.Button(label=_("Cancel"))

        self.popover = None

        self._build_widgets() 
Example #18
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __on_about(*_):
        """
            Shows about dialog
        """
        dialog = AboutDialog()
        dialog.set_transient_for(Window.get_default())
        dialog.run()
        dialog.destroy() 
Example #19
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __on_settings(*_):
        from .widgets import SettingsWindow
        settings_window = SettingsWindow()
        settings_window.present()
        settings_window.show_all() 
Example #20
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __on_quit(self, *_):
        """
        Close the application, stops all threads
        and clear clipboard for safety reasons
        """
        Clipboard.clear()
        Window.get_default().close()
        self.quit() 
Example #21
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __on_export_pgp_json(*_):
        from .models import BackupPGPJSON
        filename = export_pgp_json(Window.get_default())
        if filename:
            def export_pgp(_, fingerprint):
                BackupPGPJSON.export_file(filename, fingerprint)

            from .widgets.backup import FingprintPGPWindow
            fingerprint_window = FingprintPGPWindow(filename)
            fingerprint_window.set_transient_for(Window.get_default())
            fingerprint_window.connect("selected", export_pgp)
            fingerprint_window.show_all() 
Example #22
Source File: argparse.py    From link-prediction_with_deep-learning with MIT License 5 votes vote down vote up
def add_subparsers(self, **kwargs):
        if self._subparsers is not None:
            self.error(_('cannot have multiple subparser arguments'))

        # add the parser class to the arguments if it's not present
        kwargs.setdefault('parser_class', type(self))

        if 'title' in kwargs or 'description' in kwargs:
            title = _(kwargs.pop('title', 'subcommands'))
            description = _(kwargs.pop('description', None))
            self._subparsers = self.add_argument_group(title, description)
        else:
            self._subparsers = self._positionals

        # prog defaults to the usage message of this parser, skipping
        # optional arguments and with no "usage:" prefix
        if kwargs.get('prog') is None:
            formatter = self._get_formatter()
            positionals = self._get_positional_actions()
            groups = self._mutually_exclusive_groups
            formatter.add_usage(self.usage, positionals, groups, '')
            kwargs['prog'] = formatter.format_help().strip()

        # create the parsers action and add it to the positionals list
        parsers_class = self._pop_action_class(kwargs, 'parsers')
        action = parsers_class(option_strings=[], **kwargs)
        self._subparsers._add_action(action)

        # return the created parsers action
        return action 
Example #23
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __on_import_pgp_json(*_):
        from .widgets import GPGRestoreWindow
        filename = import_pgp_json(Window.get_default())
        if filename:
            gpg_window = GPGRestoreWindow(filename)
            gpg_window.set_transient_for(Window.get_default())
            gpg_window.show_all() 
Example #24
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __on_export_json(*_):
        from .models import BackupJSON
        filename = export_json(Window.get_default())
        if filename:
            BackupJSON.export_file(filename) 
Example #25
Source File: gnupg.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __finger_print_selected(self, _, __, fingerprint):
        self.emit("selected", fingerprint)
        self.destroy() 
Example #26
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def do_activate(self, *_):
        """On activate signal override."""
        resources_path = "/com/github/bilelmoussaoui/Authenticator/"
        Gtk.IconTheme.get_default().add_resource_path(resources_path)
        window = Window.get_default()
        window.set_application(self)
        window.set_menu(self._menu)
        window.connect("delete-event", lambda x, y: self.__on_quit())
        self.add_window(window)
        window.show_all()
        window.present() 
Example #27
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __generate_menu(self):
        """Generate application menu."""
        # Backup
        backup_content = Gio.Menu.new()
        import_menu = Gio.Menu.new()
        export_menu = Gio.Menu.new()

        import_menu.append_item(Gio.MenuItem.new(_("from a plain-text JSON file"), "app.import_json"))
        import_menu.append_item(Gio.MenuItem.new(_("from an OpenPGP-encrypted JSON file"), "app.import_pgp_json"))
        export_menu.append_item(Gio.MenuItem.new(_("in a plain-text JSON file"), "app.export_json"))
        export_menu.append_item(Gio.MenuItem.new(_("in an OpenPGP-encrypted JSON file"), "app.export_pgp_json"))

        backup_content.insert_submenu(0, _("Restore"), import_menu)
        backup_content.insert_submenu(1, _("Backup"), export_menu)

        backup_section = Gio.MenuItem.new_section(None, backup_content)
        self._menu.append_item(backup_section)

        # Main section
        main_content = Gio.Menu.new()
        # Night mode action
        main_content.append_item(Gio.MenuItem.new(_("Settings"), "app.settings"))
        main_content.append_item(Gio.MenuItem.new(_("About"), "app.about"))
        main_content.append_item(Gio.MenuItem.new(_("Quit"), "app.quit"))
        help_section = Gio.MenuItem.new_section(None, main_content)
        self._menu.append_item(help_section) 
Example #28
Source File: application.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        Gtk.Application.__init__(self,
                                 application_id="com.github.bilelmoussaoui.Authenticator",
                                 flags=Gio.ApplicationFlags.FLAGS_NONE)
        GLib.set_application_name(_("Authenticator"))
        GLib.set_prgname("Authenticator")
        self.alive = True
        self._menu = Gio.Menu() 
Example #29
Source File: actions_bar.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def on_selected_rows_changed(self, _, selected_rows):
        """
            Set the sensitivity of the delete button depending
            on the total selected rows

            :param selected_rows: the total number of selected rows
            :type selected_rows: int
        """
        self.delete_btn.set_sensitive(selected_rows > 0) 
Example #30
Source File: argparse.py    From vulscan with MIT License 5 votes vote down vote up
def _add_container_actions(self, container):
        # collect groups by titles
        title_group_map = {}
        for group in self._action_groups:
            if group.title in title_group_map:
                msg = _('cannot merge actions - two groups are named %r')
                raise ValueError(msg % (group.title))
            title_group_map[group.title] = group

        # map each action to its group
        group_map = {}
        for group in container._action_groups:

            # if a group with the title exists, use that, otherwise
            # create a new group matching the container's group
            if group.title not in title_group_map:
                title_group_map[group.title] = self.add_argument_group(
                    title=group.title,
                    description=group.description,
                    conflict_handler=group.conflict_handler)

            # map the actions to their new group
            for action in group._group_actions:
                group_map[action] = title_group_map[group.title]

        # add container's mutually exclusive groups
        # NOTE: if add_mutually_exclusive_group ever gains title= and
        # description= then this code will need to be expanded as above
        for group in container._mutually_exclusive_groups:
            mutex_group = self.add_mutually_exclusive_group(
                required=group.required)

            # map the actions to their new mutex group
            for action in group._group_actions:
                group_map[action] = mutex_group

        # add all actions to this container or their group
        for action in container._actions:
            group_map.get(action, self)._add_action(action)