python类InvalidOperation()的实例源码

_function.py 文件源码 项目:DataProperty 作者: thombashi 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_integer_digit(value):
    from typepy import TypeConversionError
    from typepy.type import RealNumber

    float_type = RealNumber(value)

    try:
        abs_value = abs(float_type.convert())
    except TypeConversionError:
        raise ValueError(
            "the value must be a number: value='{}' type='{}'".format(
                value, type(value)))

    if abs_value.is_zero():
        return 1

    try:
        return len(str(abs_value.quantize(
            Decimal("1."), rounding=decimal.ROUND_DOWN)))
    except decimal.InvalidOperation as e:
        raise ValueError(e)
python.py 文件源码 项目:SwiftKitten 作者: johncsnyder 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def parse_value(lexer, symbol=None, pos=0):
    try:
        if symbol is None:
            pos, symbol = next(lexer)
        if symbol == 'null':
            yield ('null', None)
        elif symbol == 'true':
            yield ('boolean', True)
        elif symbol == 'false':
            yield ('boolean', False)
        elif symbol == '[':
            for event in parse_array(lexer):
                yield event
        elif symbol == '{':
            for event in parse_object(lexer):
                yield event
        elif symbol[0] == '"':
            yield ('string', unescape(symbol[1:-1]))
        else:
            try:
                yield ('number', common.number(symbol))
            except decimal.InvalidOperation:
                raise UnexpectedSymbol(symbol, pos)
    except StopIteration:
        raise common.IncompleteJSONError('Incomplete JSON data')
validators.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __call__(self, value):
        try:
            if isinstance(value, decimal.Decimal):
                v = value
            else:
                v = decimal.Decimal(str(value).replace(self.dot, '.'))
            if self.minimum is None:
                if self.maximum is None or v <= self.maximum:
                    return (v, None)
            elif self.maximum is None:
                if v >= self.minimum:
                    return (v, None)
            elif self.minimum <= v <= self.maximum:
                    return (v, None)
        except (ValueError, TypeError, decimal.InvalidOperation):
            pass
        return (value, self.error_message)
strategies.py 文件源码 项目:tumanov_castleoaks 作者: Roamdev 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def validate_form(cls, form, cleaned_data):
        parameter = cleaned_data.get('parameter', '')
        if not parameter:
            form.add_error('parameter', _('This field cannot be blank.'))
            return

        try:
            amount = Valute(parameter)
        except (TypeError, ValueError, InvalidOperation):
            form.add_error('parameter', _('Invalid value'))
            return

        if not amount:
            form.add_error('parameter', _('Ensure this value is greater than 0'))
            return

        return cleaned_data
strategies.py 文件源码 项目:tumanov_castleoaks 作者: Roamdev 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def validate_form(cls, form, cleaned_data):
        parameter = cleaned_data.get('parameter', '')
        if not parameter:
            form.add_error('parameter', _('This field cannot be blank.'))
            return

        try:
            percentage = Decimal(parameter)
        except (TypeError, ValueError, InvalidOperation):
            form.add_error('parameter', _('Invalid value'))
            return

        if not percentage:
            form.add_error('parameter', _('Ensure this value is greater than 0'))
            return

        return cleaned_data
decimal.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def logical_and(self, other, context=None):
        """Applies an 'and' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def logical_xor(self, other, context=None):
        """Applies an 'xor' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def scaleb(self, other, context=None):
        """Returns self operand after adding the second value to its exp."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        ans = self._check_nans(other, context)
        if ans:
            return ans

        if other._exp != 0:
            return context._raise_error(InvalidOperation)
        liminf = -2 * (context.Emax + context.prec)
        limsup =  2 * (context.Emax + context.prec)
        if not (liminf <= int(other) <= limsup):
            return context._raise_error(InvalidOperation)

        if self._isinfinity():
            return Decimal(self)

        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
        d = d._fix(context)
        return d
decimal.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def logical_and(self, other, context=None):
        """Applies an 'and' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def logical_xor(self, other, context=None):
        """Applies an 'xor' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def scaleb(self, other, context=None):
        """Returns self operand after adding the second value to its exp."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        ans = self._check_nans(other, context)
        if ans:
            return ans

        if other._exp != 0:
            return context._raise_error(InvalidOperation)
        liminf = -2 * (context.Emax + context.prec)
        limsup =  2 * (context.Emax + context.prec)
        if not (liminf <= int(other) <= limsup):
            return context._raise_error(InvalidOperation)

        if self._isinfinity():
            return Decimal(self)

        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
        d = d._fix(context)
        return d
scrapers.py 文件源码 项目:carbondoomsday 作者: giving-a-fuck-about-climate-change 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def parse_values(self, entries):
        """Retrieve the values from the data set."""
        values = []
        for entry in entries:
            if not entry:
                continue

            date, daily, _, _ = entry
            try:
                separated = date.split('-', 2)
                intified = map(int, separated)
                co2_date = datetime.date(*intified)
            except (ValueError, TypeError):
                continue

            try:
                co2_ppm = Decimal(daily)
            except InvalidOperation:
                continue

            values.append((co2_date, co2_ppm))

        return values
scrapers.py 文件源码 项目:carbondoomsday 作者: giving-a-fuck-about-climate-change 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def parse_values(self, entries):
        """Create new CO2 measurements."""
        values = []

        for entry in entries:
            try:
                co2_date = dt.strptime(entry[0], '%Y-%m-%d')
            except (ValueError, IndexError):
                continue

            try:
                co2_ppm = Decimal(entry[1])
            except (InvalidOperation, IndexError):
                continue

            values.append((co2_date, co2_ppm))

        return values
decimal.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def logical_and(self, other, context=None):
        """Applies an 'and' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def logical_xor(self, other, context=None):
        """Applies an 'xor' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 77 收藏 0 点赞 0 评论 0
def scaleb(self, other, context=None):
        """Returns self operand after adding the second value to its exp."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        ans = self._check_nans(other, context)
        if ans:
            return ans

        if other._exp != 0:
            return context._raise_error(InvalidOperation)
        liminf = -2 * (context.Emax + context.prec)
        limsup =  2 * (context.Emax + context.prec)
        if not (liminf <= int(other) <= limsup):
            return context._raise_error(InvalidOperation)

        if self._isinfinity():
            return Decimal(self)

        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
        d = d._fix(context)
        return d
python.py 文件源码 项目:SourceKittenSubl 作者: Dan2552 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def parse_value(lexer, symbol=None, pos=0):
    try:
        if symbol is None:
            pos, symbol = next(lexer)
        if symbol == 'null':
            yield ('null', None)
        elif symbol == 'true':
            yield ('boolean', True)
        elif symbol == 'false':
            yield ('boolean', False)
        elif symbol == '[':
            for event in parse_array(lexer):
                yield event
        elif symbol == '{':
            for event in parse_object(lexer):
                yield event
        elif symbol[0] == '"':
            yield ('string', unescape(symbol[1:-1]))
        else:
            try:
                yield ('number', common.number(symbol))
            except decimal.InvalidOperation:
                raise UnexpectedSymbol(symbol, pos)
    except StopIteration:
        raise common.IncompleteJSONError('Incomplete JSON data')
trafarets.py 文件源码 项目:aiohttp_json_api 作者: vovanbo 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def check_and_return(self, data):
        data = super(DecimalTrafaret, self).check_and_return(data)

        if self.allow_nan:
            if data.is_nan():
                return decimal.Decimal('NaN')  # avoid sNaN, -sNaN and -NaN
        else:
            if data.is_nan() or data.is_infinite():
                self._failure('Special numeric values are not permitted.',
                              value=data)

        if self.places is not None and data.is_finite():
            try:
                data = data.quantize(self.places, rounding=self.rounding)
            except decimal.InvalidOperation:
                self._failure('Decimal can not be properly quantized.',
                              value=data)

        return data
stdtypes.py 文件源码 项目:meta 作者: flowdas 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _load_(self, value, context):
        if isinstance(value, decimal.Decimal):
            if not self.get_options().allow_nan and not value.is_finite():
                raise ValueError()
            return value
        elif isinstance(value, text_types):
            try:
                with decimal.localcontext() as ctx:
                    ctx.traps[decimal.InvalidOperation] = 1
                    value = decimal.Decimal(value)
                    if not self.get_options().allow_nan and not value.is_finite():
                        raise ValueError()
                    return value
            except decimal.InvalidOperation:
                raise ValueError()
        elif isinstance(value, integer_types):
            return decimal.Decimal(value)
        elif isinstance(value, float):
            if not self.get_options().allow_nan:
                if math.isnan(value) or math.isinf(value):
                    raise ValueError()
            return decimal.Decimal(value)
        else:
            raise ValueError()
decimal.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def logical_and(self, other, context=None):
        """Applies an 'and' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def logical_xor(self, other, context=None):
        """Applies an 'xor' operation between self and other's digits."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        if not self._islogical() or not other._islogical():
            return context._raise_error(InvalidOperation)

        # fill to context.prec
        (opa, opb) = self._fill_logical(context, self._int, other._int)

        # make the operation, and clean starting zeroes
        result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
decimal.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def scaleb(self, other, context=None):
        """Returns self operand after adding the second value to its exp."""
        if context is None:
            context = getcontext()

        other = _convert_other(other, raiseit=True)

        ans = self._check_nans(other, context)
        if ans:
            return ans

        if other._exp != 0:
            return context._raise_error(InvalidOperation)
        liminf = -2 * (context.Emax + context.prec)
        limsup =  2 * (context.Emax + context.prec)
        if not (liminf <= int(other) <= limsup):
            return context._raise_error(InvalidOperation)

        if self._isinfinity():
            return Decimal(self)

        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
        d = d._fix(context)
        return d
schema.py 文件源码 项目:storjnet 作者: StorjRND 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _validate_subscription_number(key, value, description):
    if not isinstance(value, list):
        raise jsonschema.exceptions.ValidationError(
            "{0} value not a list.".format(key)
        )
    if len(value) != 2:
        raise jsonschema.exceptions.ValidationError(
            "{0} value {1} does not have two entries.".format(key, value)
        )
    try:
        lower = Decimal(value[0])
        upper = Decimal(value[1])
    except InvalidOperation:
        raise jsonschema.exceptions.ValidationError(
            "{0} values {1} not numbers.".format(key, value)
        )
    minimum = Decimal(description["minimum"])
    maximum = Decimal(description["maximum"])
    if not (minimum <= lower <= upper < maximum):  # maximum is exclusive
        raise jsonschema.exceptions.ValidationError(
            "{0} values {1} not in limits: {2} <= {4} <= {5} < {3}.".format(
                key, value, minimum, maximum, lower, upper
            )
        )
schema.py 文件源码 项目:storjnet 作者: StorjRND 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _validate_indexes(schema, indexes):
    if not isinstance(indexes, list):
        raise jsonschema.exceptions.ValidationError("Indexes must be a list.")
    maximum = len(schema["indexes"])
    for index in indexes:
        try:
            number = Decimal(index)
        except InvalidOperation:
            raise jsonschema.exceptions.ValidationError(
                "Index value {0} not a number.".format(index)
            )
        if not (0 <= number < maximum):
            raise jsonschema.exceptions.ValidationError(
                "Index value {0} not in limits: {1} <= {0} < {2}.".format(
                    number, 0, maximum
                )
            )
_realnumber.py 文件源码 项目:typepy 作者: thombashi 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def force_convert(self):
        if isinstance(self._value, float):
            return self.float_class(str(self._value))

        try:
            return self.float_class(self._value)
        except (TypeError, ValueError, decimal.InvalidOperation):
            raise TypeConversionError(
                "failed to force_convert to float: type={}".format(
                    type(self._value)))
columns.py 文件源码 项目:deb-python-cassandra-driver 作者: openstack 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def validate(self, value):
        from decimal import Decimal as _Decimal
        from decimal import InvalidOperation
        val = super(Decimal, self).validate(value)
        if val is None:
            return
        try:
            return _Decimal(repr(val)) if isinstance(val, float) else _Decimal(val)
        except InvalidOperation:
            raise ValidationError("{0} '{1}' can't be coerced to decimal".format(self.column_name, val))
numbers.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def parse_decimal(string, locale=LC_NUMERIC):
    """Parse localized decimal string into a decimal.

    >>> parse_decimal('1,099.98', locale='en_US')
    Decimal('1099.98')
    >>> parse_decimal('1.099,98', locale='de')
    Decimal('1099.98')

    When the given string cannot be parsed, an exception is raised:

    >>> parse_decimal('2,109,998', locale='de')
    Traceback (most recent call last):
        ...
    NumberFormatError: '2,109,998' is not a valid decimal number

    :param string: the string to parse
    :param locale: the `Locale` object or locale identifier
    :raise NumberFormatError: if the string can not be converted to a
                              decimal number
    """
    locale = Locale.parse(locale)
    try:
        return Decimal(string.replace(get_group_symbol(locale), '')
                           .replace(get_decimal_symbol(locale), '.'))
    except InvalidOperation:
        raise NumberFormatError('%r is not a valid decimal number' % string)
columns.py 文件源码 项目:cqlmapper 作者: reddit 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def validate(self, value):
        from decimal import Decimal as _Decimal
        from decimal import InvalidOperation
        val = super(Decimal, self).validate(value)
        if val is None:
            return
        try:
            return _Decimal(repr(val)) if isinstance(val, float) else _Decimal(val)
        except InvalidOperation:
            raise ValidationError("{0} '{1}' can't be coerced to decimal".format(self.column_name, val))
test_importdata.py 文件源码 项目:health-mosconi 作者: GNUHealth-Mosconi 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test0040numeric(self):
        'Test numeric'
        with Transaction().start(DB_NAME, USER, context=CONTEXT):
            self.assertEqual(self.numeric.import_data(['numeric'],
                [['1.1']]), 1)

            self.assertEqual(self.numeric.import_data(['numeric'],
                [['-1.1']]), 1)

            self.assertEqual(self.numeric.import_data(['numeric'],
                [['1']]), 1)

            self.assertEqual(self.numeric.import_data(['numeric'],
                [['']]), 1)

            self.assertEqual(self.numeric.import_data(['numeric'],
                [['1.1'], ['2.2']]), 2)

            self.assertRaises(InvalidOperation, self.numeric.import_data,
                ['numeric'], [['foo']])

            self.assertEqual(self.numeric.import_data(['numeric'],
                [['0']]), 1)

            self.assertEqual(self.numeric.import_data(['numeric'],
                [['0.0']]), 1)
test_importdata.py 文件源码 项目:health-mosconi 作者: GNUHealth-Mosconi 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test0041numeric_required(self):
        'Test required numeric'
        with Transaction().start(DB_NAME, USER,
                context=CONTEXT) as transaction:
            self.assertEqual(self.numeric_required.import_data(['numeric'],
                [['1.1']]), 1)

            self.assertEqual(self.numeric_required.import_data(['numeric'],
                [['-1.1']]), 1)

            self.assertEqual(self.numeric_required.import_data(['numeric'],
                [['1']]), 1)

            self.assertRaises(UserError, self.numeric_required.import_data,
                ['numeric'], [['']])
            transaction.cursor.rollback()

            self.assertEqual(self.numeric_required.import_data(['numeric'],
                [['1.1'], ['2.2']]), 2)

            self.assertRaises(InvalidOperation,
                self.numeric_required.import_data, ['numeric'], [['foo']])

            self.assertEqual(self.numeric_required.import_data(['numeric'],
                [['0']]), 1)

            self.assertEqual(self.numeric_required.import_data(['numeric'],
                [['0.0']]), 1)


问题


面经


文章

微信
公众号

扫码关注公众号