Exemple #1
0
    def __init__(self,
                 sourceLang,
                 targetLang,
                 sourceLocale,
                 targetLocale,
                 fullmatch=False):
        """Initialize a NumberTranslator instance

           Args:
              sourceLang (str): source language in full spelling, e.g., 'English'
                                ignored if sourceLocale is provided
              sourceLocale (str): source locale identifier
              targetLang (str): target language in full spelling, e.g., 'French'
                                ignored if targetLocale is provided
              targetLocale (str): target locale identifier
              fullmatch (bool): whether to full-match a text or not
                                if True, NumberTranslator can act as an independent translator
                                if False, NumberTranslator must work with other translators
        """

        self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]
        self.srcLocale = sourceLocale if sourceLocale else re.sub(
            '-', '_', CULTURE_CODES[sourceLang][0])
        self.tgtLocale = targetLocale if targetLocale else re.sub(
            '-', '_', CULTURE_CODES[targetLang][0])
        self._fullmatch = fullmatch

        self.srcDecimalSymbol = numbers.get_decimal_symbol(self.srcLocale)
        self.tgtDecimalSymbol = numbers.get_decimal_symbol(self.tgtLocale)
        self.srcGroupSymbol = numbers.get_group_symbol(self.srcLocale)
        self.tgtGroupSymbol = numbers.get_group_symbol(self.tgtLocale)
Exemple #2
0
def parse_decimal(string, locale):
    locale = Locale.parse(locale)
    decimal_symbol = get_decimal_symbol(locale)
    group_symbol = get_group_symbol(locale)
    group_symbol = " " if group_symbol == "\xa0" else group_symbol
    return Decimal(
        string.replace(group_symbol, "").replace(decimal_symbol, "."))
def parse_value(value):
    """
    Accepts a string value and attempts to parce it as a currency value.

    Returns the extracted numeric value converted to a string
    """
    l_currency_language_code, l_currency_code = _getCodes()

    curSym = get_currency_symbol(l_currency_code, l_currency_language_code)
    grpSym = get_group_symbol(locale=l_currency_language_code.lower())
    decSym = get_decimal_symbol(locale=l_currency_language_code.lower())

    # Convert the Official characters into what comes from the keyboard.
    #   This section may need to grow over time.
    #   - Character 160 is a non-breaking space, which is different from a typed space
    if ord(grpSym) == 160:
        value = value.replace(u' ', grpSym)

    allSym = _getSymbols(value)
    invalidSym = allSym.replace(curSym, '').replace(
        grpSym, '').replace(decSym, '').replace(u'-', '')

    value = value.replace(curSym, '')

    if allSym.count(decSym) > 1:
        raise NumberFormatError(default_error_messages['decimal_symbol'] % decSym)
    if (allSym.count(decSym) == 1 and allSym[-1] != decSym) or invalidSym:
        raise NumberFormatError(default_error_messages['invalid_format'] % (grpSym, decSym))
    if value.count(decSym) == 1:
        value = parse_decimal(value, locale=l_currency_language_code.lower())
    else:
        value = parse_number(value, locale=l_currency_language_code.lower())

    # The value is converted into a string because the parse functions return floats
    return str(value)
def parse_value(value):
    """
    Accepts a string value and attempts to parce it as a currency value.

    Returns the extracted numeric value converted to a string
    """
    l_currency_language_code, l_currency_code = _getCodes()

    curSym = get_currency_symbol(l_currency_code, l_currency_language_code)
    grpSym = get_group_symbol(locale=l_currency_language_code.lower())
    decSym = get_decimal_symbol(locale=l_currency_language_code.lower())

    # Convert the Official characters into what comes from the keyboard.
    #   This section may need to grow over time.
    #   - Character 160 is a non-breaking space, which is different from a typed space
    if ord(grpSym) == 160:
        value = value.replace(u" ", grpSym)

    allSym = _getSymbols(value)
    invalidSym = allSym.replace(curSym, "").replace(grpSym, "").replace(decSym, "").replace(u"-", "")

    value = value.replace(curSym, "")

    if allSym.count(decSym) > 1:
        raise NumberFormatError(default_error_messages["decimal_symbol"] % decSym)
    elif (allSym.count(decSym) == 1 and allSym[-1] != decSym) or len(invalidSym) > 0:
        raise NumberFormatError(default_error_messages["invalid_format"] % (grpSym, decSym))
    elif value.count(decSym) == 1:
        value = parse_decimal(value, locale=l_currency_language_code.lower())
    else:
        value = parse_number(value, locale=l_currency_language_code.lower())

    # The value is converted into a string because the parse functions return
    # floats
    return str(value)
Exemple #5
0
    def get_group_symbol(self):
        """Return the symbol used to separate groups of thousands

        >>> Locale('en', 'US').get_group_symbol()
        u','
        """
        return numbers.get_group_symbol(self)
Exemple #6
0
def number_size_format(size, lang="en"):
    '''
    Formatea un tamaño de fichero en el idioma actual
    '''
    if not size:
        return None, None
    elif int(float(size))==0:
        return "0", ("B","bytes")

    if lang in format_cache:
        decimal_sep, group_sep = format_cache[lang]
    else:
        decimal_sep, group_sep = format_cache[lang] = (get_decimal_symbol(lang), get_group_symbol(lang))

    try:
        if size<1000: # no aplica para los bytes
            return str(size), ("B","bytes")
        else:
            size = log(float(size),1000)
            number = 1000**(size-int(size))

            # parte decimal
            dec_part = int((number-int(number))*100)
            dec_part = "" if dec_part==0 else decimal_sep+"0"+str(dec_part) if dec_part<10 else decimal_sep+str(dec_part)

            # genera salida
            return ''.join(
                reversed([c + group_sep if i != 0 and i % 3 == 0 else c for i, c in enumerate(reversed(str(int(number))))])
            ) + dec_part, (("KB","kilobytes"),("MB","megabytes"),("GB","gigabytes"),("TB","terabytes"))[int(size)-1]
    except BaseException as e:
        logging.exception(e)
        return None, None
    def process_formdata(self, valuelist):

        if valuelist:
            try:
                self.data = Decimal(valuelist[0].replace(
                    numbers.get_group_symbol(DEFAULT_LOCALE), ''))
            except (ValueError, TypeError, InvalidOperation):
                pass
    def process_formdata(self, valuelist):

        if valuelist:
            try:
                self.data = int(valuelist[0].replace(
                    numbers.get_group_symbol(DEFAULT_LOCALE), ''))
            except ValueError:
                pass
Exemple #9
0
    def __call__(self, form, field):
        try:
            Decimal(field.raw_data[0].replace(
                numbers.get_group_symbol(flask_babel.get_locale()), ''))
        except (ValueError, TypeError, InvalidOperation, AttributeError):
            raise validators.StopValidation(self.message)

        if 'e' in field.raw_data[0].lower():
            raise validators.StopValidation(self.message)
 def __call__(self, form, field):
     data = field.raw_data[0].replace(
         numbers.get_group_symbol(DEFAULT_LOCALE), '').replace(' ', '')
     decimal_symbol = numbers.get_decimal_symbol(DEFAULT_LOCALE)
     if data and decimal_symbol in data:
         if self.max_decimals == 0:
             raise validators.ValidationError(
                 self.messages['INVALID_INTEGER'])
         elif len(data.split(decimal_symbol)[1]) > self.max_decimals:
             raise validators.ValidationError(
                 self.messages['INVALID_DECIMAL'] %
                 dict(max=self.max_decimals))
Exemple #11
0
 def __call__(self, form, field):
     data = (field.raw_data[0].replace(
         numbers.get_group_symbol(flask_babel.get_locale()),
         "").replace(" ", ""))
     decimal_symbol = numbers.get_decimal_symbol(flask_babel.get_locale())
     if data and decimal_symbol in data:
         if self.max_decimals == 0:
             raise validators.ValidationError(
                 self.messages["INVALID_INTEGER"])
         if len(data.split(decimal_symbol)[1]) > self.max_decimals:
             raise validators.ValidationError(
                 self.messages["INVALID_DECIMAL"] %
                 dict(max=self.max_decimals))
Exemple #12
0
    def __call__(
        self,
        form: FlaskForm,
        field: Union[DecimalFieldWithSeparator, IntegerFieldWithSeparator],
    ) -> None:
        try:
            Decimal(field.raw_data[0].replace(
                numbers.get_group_symbol(flask_babel.get_locale()), ""))
        except (ValueError, TypeError, InvalidOperation,
                AttributeError) as exc:
            raise validators.StopValidation(self.message) from exc

        if "e" in field.raw_data[0].lower():
            raise validators.StopValidation(self.message)
Exemple #13
0
def number_size_format_filter(size, lang=None):
    '''
    Formatea un tamaño de fichero en el idioma actual
    '''
    if not size:
        return ""
    elif int(float(size))==0:
        return "0 B"

    if not lang:
        lang = g.lang

    if lang in format_cache:
        decimal_sep, group_sep = format_cache[lang]
    else:
        decimal_sep, group_sep = format_cache[lang] = (get_decimal_symbol(lang), get_group_symbol(lang))

    try:
        if float(size)<1000: # no aplica para los bytes
            return str(size)+" B"
        else:
            size = log(float(size),1024)
            number = 1024**(size-int(size))

            fix=0
            if number>=1000: #para que los tamaños entre 1000 y 1024 pasen a la unidad siguiente
                number/=1024
                fix=1

            # parte decimal
            dec_part = int((number-int(number))*100)
            dec_part = "" if dec_part==0 else decimal_sep+"0"+str(dec_part) if dec_part<10 else decimal_sep+str(dec_part)

            # genera salida
            return ''.join(
                reversed([c + group_sep if i != 0 and i % 3 == 0 else c for i, c in enumerate(reversed(str(int(number))))])
            ) + dec_part + (" KiB"," MiB"," GiB"," TiB")[int(size)-1+fix]
    except BaseException as e:
        logging.exception(e)
        return ""
Exemple #14
0
def number_size_format(size, lang="en"):
    '''
    Formatea un tamaño de fichero en el idioma actual
    '''
    if not size:
        return None, None
    elif int(float(size)) == 0:
        return "0", ("B", "bytes")

    if lang in format_cache:
        decimal_sep, group_sep = format_cache[lang]
    else:
        decimal_sep, group_sep = format_cache[lang] = (
            get_decimal_symbol(lang), get_group_symbol(lang))

    try:
        if size < 1000:  # no aplica para los bytes
            return str(size), ("B", "bytes")
        else:
            size = log(float(size), 1000)
            number = 1000**(size - int(size))

            # parte decimal
            dec_part = int((number - int(number)) * 100)
            dec_part = "" if dec_part == 0 else decimal_sep + "0" + str(
                dec_part) if dec_part < 10 else decimal_sep + str(dec_part)

            # genera salida
            return ''.join(
                reversed([
                    c + group_sep if i != 0 and i % 3 == 0 else c
                    for i, c in enumerate(reversed(str(int(number))))
                ])) + dec_part, (("KB", "kilobytes"), ("MB", "megabytes"),
                                 ("GB", "gigabytes"),
                                 ("TB", "terabytes"))[int(size) - 1]
    except BaseException as e:
        logging.exception(e)
        return None, None
Exemple #15
0
 def get_thous_sep(self):
     return get_group_symbol(locale=self.locale)
Exemple #16
0
def test_get_group_symbol():
    assert numbers.get_group_symbol('en_US') == u','
Exemple #17
0
def get_lang_float_format(locale_lang,monetary=False):
    thousands_sep = cherrypy.session['lang'].get('thousands_sep') or numbers.get_group_symbol(locale_lang)
    decimal_point = cherrypy.session['lang'].get('decimal_point')
    grouping      = cherrypy.session['lang'].get('grouping')
    return (grouping, thousands_sep, decimal_point)
Exemple #18
0
 def get_group_symbol(self):
     """Return the symbol used to separate groups of thousands
     """
     return numbers.get_group_symbol(self)
Exemple #19
0
def remove_group_symbols(string, locale=LC_NUMERIC):
    symbol = get_group_symbol(locale)
    return string.replace(symbol, '')
Exemple #20
0
def get_group_format(locale=LC_TIME):
    """Get digit group separator for thousands for the locale."""
    return get_group_symbol(locale)
Exemple #21
0
 def clean(self, value):
     locale = get_request().locale
     value = value.replace(numbers.get_group_symbol(locale), "").replace(numbers.get_decimal_symbol(locale), ".")
     return forms.DecimalField(self, value)
Exemple #22
0
def remove_group_symbols(string, locale=LC_NUMERIC):
    symbol = get_group_symbol(locale)
    return string.replace(symbol, '')
def get_lang_float_format(locale_lang, monetary=False):
    thousands_sep = cherrypy.session['lang'].get(
        'thousands_sep') or numbers.get_group_symbol(locale_lang)
    decimal_point = cherrypy.session['lang'].get('decimal_point')
    grouping = cherrypy.session['lang'].get('grouping')
    return (grouping, thousands_sep, decimal_point)
Exemple #24
0
def get_thous_sep(request):
    return get_group_symbol(locale=get_locale(request))
Exemple #25
0
 def currency(self,bizplace_id,user_id):
     symbol=get_currency_symbol(bizplace_store.get(bizplace_id,fields=['currency']))
     user_locale = dbaccess.stores.memberpref_store.get_by(dict(member=user_id), ['language'])[0]['language']
     decimal=get_decimal_symbol(user_locale)
     group=get_group_symbol(user_locale)
     return dict(symbol=symbol, decimal=decimal, group=group)
Exemple #26
0
def test_get_group_symbol():
    assert numbers.get_group_symbol('en_US') == u','
Exemple #27
0
 def clean(self, value):
     locale = get_request().locale
     value = value.replace(numbers.get_group_symbol(locale), "")
     return forms.IntegerField(self, value)