예제 #1
0
def ldnp(td, ctxt, id, idp, n, *args):
    if not dir or nolocales: _die("please set a locale directory with l_dir() before using other translate functions")

    if idp: args = (n,) + args
    out = None
    if dry:
        if not nowrite:
            save = []
            if td: save.push(' # domain: '+td)
            if ctxt: save.push('msgctxt: "'+gettext_escape(ctxt)+'"')
            save.push('msgid "'+gettext_escape(id)+'"')
            if idp: save.push('msgid_plural "'+gettext_escape(idp)+'"')
            wd(save)
        out = (idp if idp and n != 1 else id) % args
    else:
        if       td and not ctxt and id and     idp and     n: out = sprintf(dngettext(td, id, idp, n), *args)
        elif not td and not ctxt and id and     idp and     n: out = sprintf(ngettext(id, idp, n), *args)
        elif not td and not ctxt and id and not idp and not n: out = sprintf(gettext(id), *args)
        elif     td and not ctxt and id and not idp and not n: out = sprintf(dgettext(td, id), *args)

        # with context magic
        if       td and     ctxt and id and     idp and     n: out = sprintf(dngettext(td, ctxt+'\x04'+id, ctxt+'\x04'+idp, n), *args)
        elif not td and     ctxt and id and     idp and     n: out = sprintf(ngettext(ctxt+'\x04'+id, ctxt+'\x04'+idp, n), *args)
        elif not td and     ctxt and id and not idp and not n: out = sprintf(gettext(ctxt+'\x04'+id), *args)
        elif     td and     ctxt and id and not idp and not n: out = sprintf(dgettext(td, ctxt+'\x04'+id), *args)
    return out
예제 #2
0
 def many(self, events):
     """Show the number of files if many event of this type."""
     no_of_files = len(events)
     gettext.dngettext(
         GETTEXT_PACKAGE,
         "Found %(event_count)d new cloud folder.",
         "Found %(event_count)d new cloud folders.",
         no_of_files) % {'event_count': no_of_files}
예제 #3
0
 def many(self, events):
     """Show the number of files if many event of this type."""
     no_of_files = len(events)
     gettext.dngettext(
         GETTEXT_PACKAGE,
         "%(event_count)d file is no longer published.",
         "%(event_count)d files are no longer published.",
         no_of_files) % {'event_count': no_of_files}
예제 #4
0
 def many(self, events):
     """Show the number of files if many event of this type."""
     no_of_files = len(events)
     gettext.dngettext(
         GETTEXT_PACKAGE,
         "%(event_count)d file was just made public.",
         "%(event_count)d files were just made public.",
         no_of_files) % {'event_count': no_of_files}
예제 #5
0
    def _dnpgettext(
        self,
        msgctxt: Optional[str] = None,
        msgid: Optional[str] = None,
        msgid_plural: Optional[str] = None,
        n: Optional[int] = None,
        **kwargs,
    ) -> str:
        """
        Helper to handle all trans methods and delegate to corresponding
        gettext methods.

        Parameters
        ----------
        msgctxt : str, optional
            The message context.
        msgid : str, optional
            The singular string to translate.
        msgid_plural : str, optional
            The plural string to translate.
        n : int, optional
            The number for pluralization.
        **kwargs : dict, optional
            Any additional arguments to use when formating the string.
        """
        if msgid is None:
            trans = self
            raise ValueError(
                trans._("Must provide at least a `msgid` parameter!",
                        deferred=True))

        if PY37_OR_LOWER:
            translation = (gettext.dgettext(self._domain, msgid)
                           if n is None else gettext.dngettext(
                               self._domain, msgid, msgid_plural, n))
        else:
            if n is None and msgctxt is None:
                translation = gettext.dgettext(self._domain, msgid)
            elif n is None:
                translation = gettext.dpgettext(self._domain, msgctxt, msgid)
            elif msgctxt is None:
                translation = gettext.dngettext(
                    self._domain,
                    msgid,
                    msgid_plural,
                    n,
                )
            else:
                translation = gettext.dnpgettext(
                    self._domain,
                    msgctxt,
                    msgid,
                    msgid_plural,
                    n,
                )

        kwargs['n'] = n
        return translation.format(**kwargs)
예제 #6
0
def formatTime(seconds, fractional=0):
    """
    Nicely format time in a human-readable format, like
    5 days 3 weeks HH:MM

    If fractional is zero, no seconds will be shown.
    If it is greater than 0, we will show seconds and fractions of seconds.
    As a side consequence, there is no way to show seconds without fractions)

    @param seconds:    the time in seconds to format.
    @type  seconds:    int or float
    @param fractional: how many digits to show for the fractional part of
                       seconds.
    @type  fractional: int

    @rtype: string
    @returns: a nicely formatted time string.
    """
    chunks = []

    if seconds < 0:
        chunks.append(('-'))
        seconds = -seconds

    week = 60 * 60 * 24 * 7
    weeks = seconds / week
    seconds %= week

    day = 60 * 60 * 24
    days = seconds / day
    seconds %= day

    hour = 60 * 60
    hours = seconds / hour
    seconds %= hour

    minute = 60
    minutes = seconds / minute
    seconds %= minute

    if weeks >= 1:
        chunks.append(gettext.dngettext(
            configure.PACKAGE,
            N_('%d week'), N_('%d weeks'), weeks) % weeks)
    if days >= 1:
        chunks.append(gettext.dngettext(
            configure.PACKAGE,
            N_('%d day'), N_('%d days'), days) % days)

    chunk = _('%02d:%02d') % (hours, minutes)
    if fractional > 0:
        chunk += ':%0*.*f' % (fractional + 3, fractional, seconds)

    chunks.append(chunk)

    return " ".join(chunks)
예제 #7
0
def write_human_readable_summary(outstream, upgrades, security_updates):
    " write out human summary summary to outstream "
    outstream.write(
        gettext.dngettext("update-notifier", "%i package can be updated.",
                          "%i packages can be updated.", upgrades) % upgrades)
    outstream.write("\n")
    outstream.write(
        gettext.dngettext("update-notifier", "%i update is a security update.",
                          "%i updates are security updates.", security_updates)
        % security_updates)
    outstream.write("\n")
예제 #8
0
def write_human_readable_summary(outstream, upgrades, security_updates):
    " write out human summary summary to outstream "
    outstream.write(gettext.dngettext("update-notifier",
                            "%i package can be updated.",
                            "%i packages can be updated.",
                            upgrades) % upgrades)
    outstream.write("\n")
    outstream.write(gettext.dngettext("update-notifier",
                            "%i update is a security update.",
                            "%i updates are security updates.",
                            security_updates)  % security_updates)
    outstream.write("\n")
예제 #9
0
    def translation(self) -> str:
        """
        Return the translated string with interpolated kwargs, if provided.
        """

        if self._n is None and self._msgctxt is None:
            translation = gettext.dgettext(
                self._domain,
                self._msgid,
            )
        elif self._n is None:
            translation = gettext.dpgettext(
                self._domain,
                self._msgctxt,
                self._msgid,
            )
        elif self._msgctxt is None:
            translation = gettext.dngettext(
                self._domain,
                self._msgid,
                self._msgid_plural,
                self._n,
            )
        else:
            translation = gettext.dnpgettext(
                self._domain,
                self._msgctxt,
                self._msgid,
                self._msgid_plural,
                self._n,
            )

        return translation.format(**self._kwargs)
예제 #10
0
파일: l10n.py 프로젝트: htomeht/py-universe
 def gettext(self, text, plural=None, n=None):
     """
     Replacement for _() function from gettext.
     """
     if n:
         return gettext.dngettext(self.gettext_domain, text, plural, n)
     else:
         return gettext.dgettext(self.gettext_domain, text)
예제 #11
0
파일: format.py 프로젝트: flyapen/UgFlu
def formatTime(seconds, fractional=0):
    """
    Nicely format time in a human-readable format.
    Will chunks weeks, days, hours and minutes.

    @param seconds:    the time in seconds to format.
    @type  seconds:    int or float
    @param fractional: how many digits to show for the fractional part.
    @type  fractional: int

    @rtype: string
    @returns: a nicely formatted time string.
    """
    chunks = []

    week = 60 * 60 * 24 * 7
    weeks = seconds / week
    seconds %= week

    day = 60 * 60 * 24
    days = seconds / day
    seconds %= day

    hour = 60 * 60
    hours = seconds / hour
    seconds %= hour

    minute = 60
    minutes = seconds / minute
    seconds %= minute

    if weeks >= 1:
        chunks.append(gettext.dngettext(
            configure.PACKAGE,
            N_('%d week'), N_('%d weeks'), weeks) % weeks)
    if days >= 1:
        chunks.append(gettext.dngettext(
            configure.PACKAGE,
            N_('%d day'), N_('%d days'), days) % days)

    chunk = _('%02d:%02d') % (hours, minutes)
    if fractional > 0:
        chunk += ':%0*.*f' % (fractional + 3, fractional, seconds)

    chunks.append(chunk)
    return " ".join(chunks)
예제 #12
0
파일: i18n.py 프로젝트: raystsui/ddns
def _(singular, plural=None, n=None):
    """
		A function that returnes the translation of a string if available.
		The language is taken from the system environment.
	"""
    if plural is not None:
        assert n is not None
        return gettext.dngettext(TEXTDOMAIN, singular, plural, n)

    return gettext.dgettext(TEXTDOMAIN, singular)
예제 #13
0
    def translation(self) -> str:
        """
        Return the translated string with interpolated kwargs, if provided.
        """
        # Python 3.7 or lower does not offer translations based on context.
        # On these versions `gettext.npgettext` falls back to `gettext.ngettext`
        if PY37_OR_LOWER:
            if self._n is None:
                translation = gettext.dgettext(self._domain, self._msgid)
            else:
                translation = gettext.dngettext(
                    self._domain, self._msgid, self._msgid_plural, self._n
                )
        else:
            if self._n is None and self._msgctxt is None:
                translation = gettext.dgettext(
                    self._domain,
                    self._msgid,
                )
            elif self._n is None:
                translation = gettext.dpgettext(
                    self._domain,
                    self._msgctxt,
                    self._msgid,
                )
            elif self._msgctxt is None:
                translation = gettext.dngettext(
                    self._domain,
                    self._msgid,
                    self._msgid_plural,
                    self._n,
                )
            else:
                translation = gettext.dnpgettext(
                    self._domain,
                    self._msgctxt,
                    self._msgid,
                    self._msgid_plural,
                    self._n,
                )

        return translation.format(**self._kwargs)
예제 #14
0
파일: i18n.py 프로젝트: ipfire/pakfire
def _(singular, plural=None, n=None):
	"""
		A function that returnes the translation of a string if available.

		The language is taken from the system environment.
	"""
	if not plural is None:
		assert n is not None
		return gettext.dngettext("pakfire", singular, plural, n)

	return gettext.dgettext("pakfire", singular)
예제 #15
0
def files_were_downloaded(filename, download_done):
    """Get the i18n string for files that were downloaded."""
    other_files = download_done - 1
    if other_files < 1:
        return Q_(
            "'%(filename)s' was downloaded to your computer.") % {
            'filename': filename}
    format_args = {
        'filename': filename, 'other_files': other_files}
    return gettext.dngettext(
        GETTEXT_PACKAGE,
        "'%(filename)s' and %(other_files)d other file were "
        "downloaded to your computer.",
        "'%(filename)s' and %(other_files)d other files were "
        "downloaded to your computer.", other_files) % format_args
예제 #16
0
def files_were_uploaded(filename, upload_done):
    """Get the i18n string for files that were uploaded."""
    other_files = upload_done - 1
    if other_files < 1:
        return Q_(
            "'%(filename)s' was uploaded to your personal cloud.") % {
            'filename': filename}
    format_args = {
        'filename': filename, 'other_files': other_files}
    return gettext.dngettext(
        GETTEXT_PACKAGE,
        "'%(filename)s' and %(other_files)d other file were uploaded to "
        "your personal cloud.",
        "'%(filename)s' and %(other_files)d other files were uploaded "
        "to your personal cloud.", other_files) % format_args
예제 #17
0
def files_being_downloaded(filename, files_downloading):
    """Get the i18n string for files being downloaded."""
    other_files = files_downloading - 1
    if other_files < 1:
        return Q_(
            "'%(filename)s' is being downloaded to your computer.") % {
            'filename': filename}
    format_args = {
        "filename": filename, "other_files": other_files}
    return gettext.dngettext(
        GETTEXT_PACKAGE,
        "'%(filename)s' and %(other_files)d other file are being "
        "downloaded to your computer.",
        "'%(filename)s' and %(other_files)d other files are being "
        "downloaded to your computer.", other_files) % format_args
예제 #18
0
    def _init_translations(self):
        """Initialize localization functions.
        
        First, get the plugin info, then get the custom data storing the gettext
        domain and the locale directory.
        
        Then bind the gettext domain, and set up some some handy functions for
        translating UI strings.
        """

        # Get the plugin info
        peas_plugin_info = Peas.Engine.get_default().get_plugin_info(PLUGIN_MODULE_NAME)
        if peas_plugin_info is not None:
            global GETTEXT_PACKAGE

            # In the future, when libpeas 1.6+ is ubiquitous:
            # GETTEXT_PACKAGE = peas_plugin_info.get_external_data("gettext-package")
            # localedir       = peas_plugin_info.get_external_data("localedir")

            # Sadly, we don't have get_external_data(), so, time to improvise
            ### Begin hack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            user_data = {}
            try:
                for line in open(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)), PLUGIN_MODULE_NAME + ".plugin")
                ):
                    if line.lstrip().startswith("X-"):
                        try:
                            setting, value = line[2:].split("=", 1)
                            user_data[setting.rstrip()] = value.strip()
                        except ValueError:
                            pass
            except IOError:
                pass

            GETTEXT_PACKAGE = "" if "gettext-package" not in user_data else user_data["gettext-package"]
            localedir = "" if "localedir" not in user_data else user_data["localedir"]
            ### End hack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            if GETTEXT_PACKAGE and localedir:
                global _
                global P_

                gettext.bindtextdomain(GETTEXT_PACKAGE, localedir)
                _ = lambda s: gettext.dgettext(GETTEXT_PACKAGE, s)
                P_ = lambda s1, s2, n: gettext.dngettext(GETTEXT_PACKAGE, s1, s2, n)
예제 #19
0
def timestamp_to_elapsed_string(timestamp, max_levels=2):
    levels = 0
    time_period = ''
    elapsed_seconds = int(time.time() - timestamp)

    for name_singular, name_plural, factor in units:
        elapsed_units = elapsed_seconds / factor
        if elapsed_units > 0:

            if levels > 0:
                time_period += COMMA

            key = ''.join((os.environ['LANG'], name_singular,
                           str(elapsed_units)))
            if key in _i18n_timestamps_cache:
                time_period += _i18n_timestamps_cache[key]
            else:
                tmp = gettext.dngettext('sugar-toolkit-gtk3',
                                        name_singular,
                                        name_plural,
                                        elapsed_units)
                # FIXME: This is a hack so we don't crash when a translation
                # doesn't contain the expected number of placeholders (#2354)
                try:
                    translation = tmp % elapsed_units
                except TypeError:
                    translation = tmp

                _i18n_timestamps_cache[key] = translation
                time_period += translation

            elapsed_seconds -= elapsed_units * factor

        if time_period != '':
            levels += 1

        if levels == max_levels:
            break

    if levels == 0:
        return NOW

    return ELAPSED % time_period
예제 #20
0
def timestamp_to_elapsed_string(timestamp, max_levels=2):
    levels = 0
    time_period = ''
    elapsed_seconds = int(time.time() - timestamp)

    for name_singular, name_plural, factor in units:
        elapsed_units = elapsed_seconds / factor
        if elapsed_units > 0:

            if levels > 0:
                time_period += COMMA

            key = ''.join((os.environ['LANG'], name_singular,
                           str(elapsed_units)))
            if key in _i18n_timestamps_cache:
                time_period += _i18n_timestamps_cache[key]
            else:
                tmp = gettext.dngettext('sugar-toolkit-gtk3',
                                        name_singular,
                                        name_plural,
                                        elapsed_units)
                # FIXME: This is a hack so we don't crash when a translation
                # doesn't contain the expected number of placeholders (#2354)
                try:
                    translation = tmp % elapsed_units
                except TypeError:
                    translation = tmp

                _i18n_timestamps_cache[key] = translation
                time_period += translation

            elapsed_seconds -= elapsed_units * factor

        if time_period != '':
            levels += 1

        if levels == max_levels:
            break

    if levels == 0:
        return NOW

    return ELAPSED % time_period
예제 #21
0
def stoqlib_ngettext(singular, plural, n):
    return gettext_.dngettext('stoq', singular, plural, n)
예제 #22
0
def _N(singular, plural, n):
	t = gettext.dngettext(TEXT_DOMAIN, singular, plural, n)
	if t in (singular, plural):
		t = gettext.ngettext(singular, plural, n)
	return t
예제 #23
0
def ngettext(singular, plural, n):
    t = gettext.dngettext('EPGRefresh', singular, plural, n)
    if t in (singular, plural):
        t = gettext.ngettext(singular, plural, n)
    return t
예제 #24
0
def ngettext(singular, plural, n):
    t = gettext.dngettext('MovieManager', singular, plural, n)
    if t in (singular, plural):
        t = gettext.ngettext(singular, plural, n)
    return t
예제 #25
0
                # canidate version from another repo (-proposed or -updates)
                for ver in pkg.VersionList:
                    if (inst_ver and apt_pkg.VersionCompare(ver.VerStr, inst_ver.VerStr) <= 0):
                        #print "skipping '%s' " % ver.VerStr
                        continue
                    if isSecurityUpgrade(ver):
                        security_updates += 1
                        break

    # print the number of upgrades
    if options and options.show_package_names:
        pkgs = filter(lambda pkg: depcache.MarkedInstall(pkg) or depcache.MarkedUpgrade(pkg), cache.Packages)
        sys.stderr.write("\n".join(map(lambda p: p.Name, pkgs)))
    elif options and options.readable_output:
        print gettext.dngettext("update-notifier",
                                "%i package can be updated.",
                                "%i packages can be updated.",
                                upgrades) % upgrades
        print gettext.dngettext("update-notifier",
                                "%i update is a security update.",
                                "%i updates are security updates.",
                                security_updates)  % security_updates
    else:
        # print the number of regular upgrades and the number of 
        # security upgrades
        sys.stderr.write("%s;%s" % (upgrades,security_updates))

    # return the number of upgrades (if its used as a module)
    return(upgrades,security_updates)


if __name__ == "__main__":        
예제 #26
0
파일: source.py 프로젝트: desiderantes/bake
import gettext

n = 5
ng1 = gettext.ngettext("ngettext1", "ngettext1-plural", n)
dng1 = gettext.dngettext("test-domain", "dngettext1", "dngettext1-plural", n)
dng2 = gettext.dngettext("some-other-domain", "dngettext2", "dngettext2-plural", n)
예제 #27
0
 def update_event(self, inp=-1):
     self.set_output_val(
         0,
         gettext.dngettext(self.input(0), self.input(1), self.input(2),
                           self.input(3)))
예제 #28
0
    def update_target_tags(self, source=None, event=None):
        """
        Update target GtkTextBuffer highlighting
            void update_target_tags(event source: gtk.Object,
                                    event: gtk.gdk.Event)
        """

        # Set updating flag and undo stack lock
        self.updating = True
        self.tbuffer.set_stack_lock(True)

        # Save selection or cursor position
        if self.tbuffer.get_has_selection():
            start, end = self.tbuffer.get_selection_bounds()
            saved = (start.get_offset(), end.get_offset())
        else:
            saved = self.tbuffer.get_iter_at_mark(self.tbuffer.get_insert()).\
                get_offset()

        # Reset target GtkTextBuffer text
        self.tbuffer.set_text('')

        # Check target chunks
        count = 0
        first = True
        last = None

        for m in self.match:
            # Skip empty chunks
            if m.start() == m.end():
                continue

            # Append begin chunk if needed
            if self.tbuffer.get_char_count() == 0 and m.start() != 0:
                self.tbuffer.insert(self.tbuffer.get_end_iter(),
                    self.target[:m.start()])

            # Append chunk present between two matches
            if m.start() == last:
                pass
            elif last:
                self.tbuffer.insert(self.tbuffer.get_end_iter(),
                    self.target[last:m.start()])

            # Append chunk with tags
            self.tbuffer.insert_with_tags_by_name(self.tbuffer.get_end_iter(),
                self.target[m.start():m.end()], 'match-first' if first \
                    else 'match-next')

            if first:
                first = False

            last = m.end()
            count += 1

            # Stop if limit reached
            if count == self.limit:
                break

        # Append end chunk if needed
        if last != len(self.target):
            self.tbuffer.insert(self.tbuffer.get_end_iter(),
                self.target[last:])

        # Restore selection or cursor position
        if type(saved) == tuple:
            self.tbuffer.select_range(self.tbuffer.get_iter_at_offset(
                saved[0]), self.tbuffer.get_iter_at_offset(saved[1]))
        else:
            self.tbuffer.place_cursor(self.tbuffer.get_iter_at_offset(saved))

        # Set statusbar matches count
        self.wtree.get_object('statusbar').pop(0)
        self.wtree.get_object('statusbar').push(0, gettext.dngettext(
            __cmdname__, '%d match found', '%d matches found', count) % count)

        # Reset updating flag and undo stack lock
        self.updating = False
        self.tbuffer.set_stack_lock(False)
예제 #29
0
def _N(singular, plural, n):
	t = gettext.dngettext(TEXT_DOMAIN, singular, plural, n)
	if t in (singular, plural):
		t = gettext.ngettext(singular, plural, n)
	return t
예제 #30
0
def ngettext(singular, plural, n):
    t = gettext.dngettext('ManagerAutofs', singular, plural, n)
    if t in (singular, plural):
        t = gettext.ngettext(singular, plural, n)
    return t
def ngettext(singular, plural, n):
    t = gettext.dngettext('FileCommander', singular, plural, n)
    if t in (singular, plural):
        t = gettext.ngettext(singular, plural, n)
    return t
예제 #32
0
					errmsg = str(e.args)
					errstr = gettext.ldgettext('hildon-common-strings', "sfil_ni_operation_failed")
					self.show_system_note("%s\n%s" % (errstr, errmsg))
					raise
		
		to = self.eNumber.get_text()
		sender = self.config.get_phonenumber()
		tb = self.tvMessage.get_buffer()
		message = tb.get_text(tb.get_start_iter(), tb.get_end_iter())
		log.info("attachment: %s message: %s", attachment, message)

		(status, msg) = self.cont.send_mms(to, self.subject, message, attachment, sender)

		if status == 0:
			banner = hildon.hildon_banner_show_information(self.spawner, "", \
						 gettext.dngettext('modest', 'mcen_ib_message_sent', 'mcen_ib_messages_sent', 1))
		
			if self.attachmentIsResized == True:
				log.info("Removing temporary image: %s", attachment)
				os.remove(attachment)
			self.quit("clean")
			return
		elif status == -1:
			self.show_system_note(msg)
		
		hildon.hildon_gtk_window_set_progress_indicator(self.window, 0)
		self.bSend.set_sensitive(True)

	def from_sharing_service(self):
		try:
			if self.fromSharingService: