desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Compares two operands using their abstract representation ignoring sign. Like compare_total, but with operand\'s sign ignored and assumed to be 0.'
def compare_total_mag(self, a, b):
a = _convert_other(a, raiseit=True) return a.compare_total_mag(b)
'Returns a copy of the operand with the sign set to 0. >>> ExtendedContext.copy_abs(Decimal(\'2.1\')) Decimal(\'2.1\') >>> ExtendedContext.copy_abs(Decimal(\'-100\')) Decimal(\'100\') >>> ExtendedContext.copy_abs(-1) Decimal(\'1\')'
def copy_abs(self, a):
a = _convert_other(a, raiseit=True) return a.copy_abs()
'Returns a copy of the decimal object. >>> ExtendedContext.copy_decimal(Decimal(\'2.1\')) Decimal(\'2.1\') >>> ExtendedContext.copy_decimal(Decimal(\'-1.00\')) Decimal(\'-1.00\') >>> ExtendedContext.copy_decimal(1) Decimal(\'1\')'
def copy_decimal(self, a):
a = _convert_other(a, raiseit=True) return Decimal(a)
'Returns a copy of the operand with the sign inverted. >>> ExtendedContext.copy_negate(Decimal(\'101.5\')) Decimal(\'-101.5\') >>> ExtendedContext.copy_negate(Decimal(\'-101.5\')) Decimal(\'101.5\') >>> ExtendedContext.copy_negate(1) Decimal(\'-1\')'
def copy_negate(self, a):
a = _convert_other(a, raiseit=True) return a.copy_negate()
'Copies the second operand\'s sign to the first one. In detail, it returns a copy of the first operand with the sign equal to the sign of the second operand. >>> ExtendedContext.copy_sign(Decimal( \'1.50\'), Decimal(\'7.33\')) Decimal(\'1.50\') >>> ExtendedContext.copy_sign(Decimal(\'-1.50\'), Decimal(\'7.33\')) Decimal(\'1.50\') >>> ExtendedContext.copy_sign(Decimal( \'1.50\'), Decimal(\'-7.33\')) Decimal(\'-1.50\') >>> ExtendedContext.copy_sign(Decimal(\'-1.50\'), Decimal(\'-7.33\')) Decimal(\'-1.50\') >>> ExtendedContext.copy_sign(1, -2) Decimal(\'-1\') >>> ExtendedContext.copy_sign(Decimal(1), -2) Decimal(\'-1\') >>> ExtendedContext.copy_sign(1, Decimal(-2)) Decimal(\'-1\')'
def copy_sign(self, a, b):
a = _convert_other(a, raiseit=True) return a.copy_sign(b)
'Decimal division in a specified context. >>> ExtendedContext.divide(Decimal(\'1\'), Decimal(\'3\')) Decimal(\'0.333333333\') >>> ExtendedContext.divide(Decimal(\'2\'), Decimal(\'3\')) Decimal(\'0.666666667\') >>> ExtendedContext.divide(Decimal(\'5\'), Decimal(\'2\')) Decimal(\'2.5\') >>> ExtendedContext.divide(Decimal(\'1\'), Decimal(\'10\')) Decimal(\'0.1\') >>> ExtendedContext.divide(Decimal(\'12\'), Decimal(\'12\')) Decimal(\'1\') >>> ExtendedContext.divide(Decimal(\'8.00\'), Decimal(\'2\')) Decimal(\'4.00\') >>> ExtendedContext.divide(Decimal(\'2.400\'), Decimal(\'2.0\')) Decimal(\'1.20\') >>> ExtendedContext.divide(Decimal(\'1000\'), Decimal(\'100\')) Decimal(\'10\') >>> ExtendedContext.divide(Decimal(\'1000\'), Decimal(\'1\')) Decimal(\'1000\') >>> ExtendedContext.divide(Decimal(\'2.40E+6\'), Decimal(\'2\')) Decimal(\'1.20E+6\') >>> ExtendedContext.divide(5, 5) Decimal(\'1\') >>> ExtendedContext.divide(Decimal(5), 5) Decimal(\'1\') >>> ExtendedContext.divide(5, Decimal(5)) Decimal(\'1\')'
def divide(self, a, b):
a = _convert_other(a, raiseit=True) r = a.__div__(b, context=self) if (r is NotImplemented): raise TypeError(('Unable to convert %s to Decimal' % b)) else: return r
'Divides two numbers and returns the integer part of the result. >>> ExtendedContext.divide_int(Decimal(\'2\'), Decimal(\'3\')) Decimal(\'0\') >>> ExtendedContext.divide_int(Decimal(\'10\'), Decimal(\'3\')) Decimal(\'3\') >>> ExtendedContext.divide_int(Decimal(\'1\'), Decimal(\'0.3\')) Decimal(\'3\') >>> ExtendedContext.divide_int(10, 3) Decimal(\'3\') >>> ExtendedContext.divide_int(Decimal(10), 3) Decimal(\'3\') >>> ExtendedContext.divide_int(10, Decimal(3)) Decimal(\'3\')'
def divide_int(self, a, b):
a = _convert_other(a, raiseit=True) r = a.__floordiv__(b, context=self) if (r is NotImplemented): raise TypeError(('Unable to convert %s to Decimal' % b)) else: return r
'Return (a // b, a % b). >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) (Decimal(\'2\'), Decimal(\'2\')) >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) (Decimal(\'2\'), Decimal(\'0\')) >>> ExtendedContext.divmod(8, 4) (Decimal(\'2\'), Decimal(\'0\')) >>> ExtendedContext.divmod(Decimal(8), 4) (Decimal(\'2\'), Decimal(\'0\')) >>> ExtendedContext.divmod(8, Decimal(4)) (Decimal(\'2\'), Decimal(\'0\'))'
def divmod(self, a, b):
a = _convert_other(a, raiseit=True) r = a.__divmod__(b, context=self) if (r is NotImplemented): raise TypeError(('Unable to convert %s to Decimal' % b)) else: return r
'Returns e ** a. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.exp(Decimal(\'-Infinity\')) Decimal(\'0\') >>> c.exp(Decimal(\'-1\')) Decimal(\'0.367879441\') >>> c.exp(Decimal(\'0\')) Decimal(\'1\') >>> c.exp(Decimal(\'1\')) Decimal(\'2.71828183\') >>> c.exp(Decimal(\'0.693147181\')) Decimal(\'2.00000000\') >>> c.exp(Decimal(\'+Infinity\')) Decimal(\'Infinity\') >>> c.exp(10) Decimal(\'22026.4658\')'
def exp(self, a):
a = _convert_other(a, raiseit=True) return a.exp(context=self)
'Returns a multiplied by b, plus c. The first two operands are multiplied together, using multiply, the third operand is then added to the result of that multiplication, using add, all with only one final rounding. >>> ExtendedContext.fma(Decimal(\'3\'), Decimal(\'5\'), Decimal(\'7\')) Decimal(\'22\') >>> ExtendedContext.fma(Decimal(\'3\'), Decimal(\'-5\'), Decimal(\'7\')) Decimal(\'-8\') >>> ExtendedContext.fma(Decimal(\'888565290\'), Decimal(\'1557.96930\'), Decimal(\'-86087.7578\')) Decimal(\'1.38435736E+12\') >>> ExtendedContext.fma(1, 3, 4) Decimal(\'7\') >>> ExtendedContext.fma(1, Decimal(3), 4) Decimal(\'7\') >>> ExtendedContext.fma(1, 3, Decimal(4)) Decimal(\'7\')'
def fma(self, a, b, c):
a = _convert_other(a, raiseit=True) return a.fma(b, c, context=self)
'Return True if the operand is canonical; otherwise return False. Currently, the encoding of a Decimal instance is always canonical, so this method returns True for any Decimal. >>> ExtendedContext.is_canonical(Decimal(\'2.50\')) True'
def is_canonical(self, a):
return a.is_canonical()
'Return True if the operand is finite; otherwise return False. A Decimal instance is considered finite if it is neither infinite nor a NaN. >>> ExtendedContext.is_finite(Decimal(\'2.50\')) True >>> ExtendedContext.is_finite(Decimal(\'-0.3\')) True >>> ExtendedContext.is_finite(Decimal(\'0\')) True >>> ExtendedContext.is_finite(Decimal(\'Inf\')) False >>> ExtendedContext.is_finite(Decimal(\'NaN\')) False >>> ExtendedContext.is_finite(1) True'
def is_finite(self, a):
a = _convert_other(a, raiseit=True) return a.is_finite()
'Return True if the operand is infinite; otherwise return False. >>> ExtendedContext.is_infinite(Decimal(\'2.50\')) False >>> ExtendedContext.is_infinite(Decimal(\'-Inf\')) True >>> ExtendedContext.is_infinite(Decimal(\'NaN\')) False >>> ExtendedContext.is_infinite(1) False'
def is_infinite(self, a):
a = _convert_other(a, raiseit=True) return a.is_infinite()
'Return True if the operand is a qNaN or sNaN; otherwise return False. >>> ExtendedContext.is_nan(Decimal(\'2.50\')) False >>> ExtendedContext.is_nan(Decimal(\'NaN\')) True >>> ExtendedContext.is_nan(Decimal(\'-sNaN\')) True >>> ExtendedContext.is_nan(1) False'
def is_nan(self, a):
a = _convert_other(a, raiseit=True) return a.is_nan()
'Return True if the operand is a normal number; otherwise return False. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.is_normal(Decimal(\'2.50\')) True >>> c.is_normal(Decimal(\'0.1E-999\')) False >>> c.is_normal(Decimal(\'0.00\')) False >>> c.is_normal(Decimal(\'-Inf\')) False >>> c.is_normal(Decimal(\'NaN\')) False >>> c.is_normal(1) True'
def is_normal(self, a):
a = _convert_other(a, raiseit=True) return a.is_normal(context=self)
'Return True if the operand is a quiet NaN; otherwise return False. >>> ExtendedContext.is_qnan(Decimal(\'2.50\')) False >>> ExtendedContext.is_qnan(Decimal(\'NaN\')) True >>> ExtendedContext.is_qnan(Decimal(\'sNaN\')) False >>> ExtendedContext.is_qnan(1) False'
def is_qnan(self, a):
a = _convert_other(a, raiseit=True) return a.is_qnan()
'Return True if the operand is negative; otherwise return False. >>> ExtendedContext.is_signed(Decimal(\'2.50\')) False >>> ExtendedContext.is_signed(Decimal(\'-12\')) True >>> ExtendedContext.is_signed(Decimal(\'-0\')) True >>> ExtendedContext.is_signed(8) False >>> ExtendedContext.is_signed(-8) True'
def is_signed(self, a):
a = _convert_other(a, raiseit=True) return a.is_signed()
'Return True if the operand is a signaling NaN; otherwise return False. >>> ExtendedContext.is_snan(Decimal(\'2.50\')) False >>> ExtendedContext.is_snan(Decimal(\'NaN\')) False >>> ExtendedContext.is_snan(Decimal(\'sNaN\')) True >>> ExtendedContext.is_snan(1) False'
def is_snan(self, a):
a = _convert_other(a, raiseit=True) return a.is_snan()
'Return True if the operand is subnormal; otherwise return False. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.is_subnormal(Decimal(\'2.50\')) False >>> c.is_subnormal(Decimal(\'0.1E-999\')) True >>> c.is_subnormal(Decimal(\'0.00\')) False >>> c.is_subnormal(Decimal(\'-Inf\')) False >>> c.is_subnormal(Decimal(\'NaN\')) False >>> c.is_subnormal(1) False'
def is_subnormal(self, a):
a = _convert_other(a, raiseit=True) return a.is_subnormal(context=self)
'Return True if the operand is a zero; otherwise return False. >>> ExtendedContext.is_zero(Decimal(\'0\')) True >>> ExtendedContext.is_zero(Decimal(\'2.50\')) False >>> ExtendedContext.is_zero(Decimal(\'-0E+2\')) True >>> ExtendedContext.is_zero(1) False >>> ExtendedContext.is_zero(0) True'
def is_zero(self, a):
a = _convert_other(a, raiseit=True) return a.is_zero()
'Returns the natural (base e) logarithm of the operand. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.ln(Decimal(\'0\')) Decimal(\'-Infinity\') >>> c.ln(Decimal(\'1.000\')) Decimal(\'0\') >>> c.ln(Decimal(\'2.71828183\')) Decimal(\'1.00000000\') >>> c.ln(Decimal(\'10\')) Decimal(\'2.30258509\') >>> c.ln(Decimal(\'+Infinity\')) Decimal(\'Infinity\') >>> c.ln(1) Decimal(\'0\')'
def ln(self, a):
a = _convert_other(a, raiseit=True) return a.ln(context=self)
'Returns the base 10 logarithm of the operand. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.log10(Decimal(\'0\')) Decimal(\'-Infinity\') >>> c.log10(Decimal(\'0.001\')) Decimal(\'-3\') >>> c.log10(Decimal(\'1.000\')) Decimal(\'0\') >>> c.log10(Decimal(\'2\')) Decimal(\'0.301029996\') >>> c.log10(Decimal(\'10\')) Decimal(\'1\') >>> c.log10(Decimal(\'70\')) Decimal(\'1.84509804\') >>> c.log10(Decimal(\'+Infinity\')) Decimal(\'Infinity\') >>> c.log10(0) Decimal(\'-Infinity\') >>> c.log10(1) Decimal(\'0\')'
def log10(self, a):
a = _convert_other(a, raiseit=True) return a.log10(context=self)
'Returns the exponent of the magnitude of the operand\'s MSD. The result is the integer which is the exponent of the magnitude of the most significant digit of the operand (as though the operand were truncated to a single digit while maintaining the value of that digit and without limiting the resulting exponent). >>> ExtendedContext.logb(Decimal(\'250\')) Decimal(\'2\') >>> ExtendedContext.logb(Decimal(\'2.50\')) Decimal(\'0\') >>> ExtendedContext.logb(Decimal(\'0.03\')) Decimal(\'-2\') >>> ExtendedContext.logb(Decimal(\'0\')) Decimal(\'-Infinity\') >>> ExtendedContext.logb(1) Decimal(\'0\') >>> ExtendedContext.logb(10) Decimal(\'1\') >>> ExtendedContext.logb(100) Decimal(\'2\')'
def logb(self, a):
a = _convert_other(a, raiseit=True) return a.logb(context=self)
'Applies the logical operation \'and\' between each operand\'s digits. The operands must be both logical numbers. >>> ExtendedContext.logical_and(Decimal(\'0\'), Decimal(\'0\')) Decimal(\'0\') >>> ExtendedContext.logical_and(Decimal(\'0\'), Decimal(\'1\')) Decimal(\'0\') >>> ExtendedContext.logical_and(Decimal(\'1\'), Decimal(\'0\')) Decimal(\'0\') >>> ExtendedContext.logical_and(Decimal(\'1\'), Decimal(\'1\')) Decimal(\'1\') >>> ExtendedContext.logical_and(Decimal(\'1100\'), Decimal(\'1010\')) Decimal(\'1000\') >>> ExtendedContext.logical_and(Decimal(\'1111\'), Decimal(\'10\')) Decimal(\'10\') >>> ExtendedContext.logical_and(110, 1101) Decimal(\'100\') >>> ExtendedContext.logical_and(Decimal(110), 1101) Decimal(\'100\') >>> ExtendedContext.logical_and(110, Decimal(1101)) Decimal(\'100\')'
def logical_and(self, a, b):
a = _convert_other(a, raiseit=True) return a.logical_and(b, context=self)
'Invert all the digits in the operand. The operand must be a logical number. >>> ExtendedContext.logical_invert(Decimal(\'0\')) Decimal(\'111111111\') >>> ExtendedContext.logical_invert(Decimal(\'1\')) Decimal(\'111111110\') >>> ExtendedContext.logical_invert(Decimal(\'111111111\')) Decimal(\'0\') >>> ExtendedContext.logical_invert(Decimal(\'101010101\')) Decimal(\'10101010\') >>> ExtendedContext.logical_invert(1101) Decimal(\'111110010\')'
def logical_invert(self, a):
a = _convert_other(a, raiseit=True) return a.logical_invert(context=self)
'Applies the logical operation \'or\' between each operand\'s digits. The operands must be both logical numbers. >>> ExtendedContext.logical_or(Decimal(\'0\'), Decimal(\'0\')) Decimal(\'0\') >>> ExtendedContext.logical_or(Decimal(\'0\'), Decimal(\'1\')) Decimal(\'1\') >>> ExtendedContext.logical_or(Decimal(\'1\'), Decimal(\'0\')) Decimal(\'1\') >>> ExtendedContext.logical_or(Decimal(\'1\'), Decimal(\'1\')) Decimal(\'1\') >>> ExtendedContext.logical_or(Decimal(\'1100\'), Decimal(\'1010\')) Decimal(\'1110\') >>> ExtendedContext.logical_or(Decimal(\'1110\'), Decimal(\'10\')) Decimal(\'1110\') >>> ExtendedContext.logical_or(110, 1101) Decimal(\'1111\') >>> ExtendedContext.logical_or(Decimal(110), 1101) Decimal(\'1111\') >>> ExtendedContext.logical_or(110, Decimal(1101)) Decimal(\'1111\')'
def logical_or(self, a, b):
a = _convert_other(a, raiseit=True) return a.logical_or(b, context=self)
'Applies the logical operation \'xor\' between each operand\'s digits. The operands must be both logical numbers. >>> ExtendedContext.logical_xor(Decimal(\'0\'), Decimal(\'0\')) Decimal(\'0\') >>> ExtendedContext.logical_xor(Decimal(\'0\'), Decimal(\'1\')) Decimal(\'1\') >>> ExtendedContext.logical_xor(Decimal(\'1\'), Decimal(\'0\')) Decimal(\'1\') >>> ExtendedContext.logical_xor(Decimal(\'1\'), Decimal(\'1\')) Decimal(\'0\') >>> ExtendedContext.logical_xor(Decimal(\'1100\'), Decimal(\'1010\')) Decimal(\'110\') >>> ExtendedContext.logical_xor(Decimal(\'1111\'), Decimal(\'10\')) Decimal(\'1101\') >>> ExtendedContext.logical_xor(110, 1101) Decimal(\'1011\') >>> ExtendedContext.logical_xor(Decimal(110), 1101) Decimal(\'1011\') >>> ExtendedContext.logical_xor(110, Decimal(1101)) Decimal(\'1011\')'
def logical_xor(self, a, b):
a = _convert_other(a, raiseit=True) return a.logical_xor(b, context=self)
'max compares two values numerically and returns the maximum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the maximum (closer to positive infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal(\'3\'), Decimal(\'2\')) Decimal(\'3\') >>> ExtendedContext.max(Decimal(\'-10\'), Decimal(\'3\')) Decimal(\'3\') >>> ExtendedContext.max(Decimal(\'1.0\'), Decimal(\'1\')) Decimal(\'1\') >>> ExtendedContext.max(Decimal(\'7\'), Decimal(\'NaN\')) Decimal(\'7\') >>> ExtendedContext.max(1, 2) Decimal(\'2\') >>> ExtendedContext.max(Decimal(1), 2) Decimal(\'2\') >>> ExtendedContext.max(1, Decimal(2)) Decimal(\'2\')'
def max(self, a, b):
a = _convert_other(a, raiseit=True) return a.max(b, context=self)
'Compares the values numerically with their sign ignored. >>> ExtendedContext.max_mag(Decimal(\'7\'), Decimal(\'NaN\')) Decimal(\'7\') >>> ExtendedContext.max_mag(Decimal(\'7\'), Decimal(\'-10\')) Decimal(\'-10\') >>> ExtendedContext.max_mag(1, -2) Decimal(\'-2\') >>> ExtendedContext.max_mag(Decimal(1), -2) Decimal(\'-2\') >>> ExtendedContext.max_mag(1, Decimal(-2)) Decimal(\'-2\')'
def max_mag(self, a, b):
a = _convert_other(a, raiseit=True) return a.max_mag(b, context=self)
'min compares two values numerically and returns the minimum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the minimum (closer to negative infinity) of the two operands is chosen as the result. >>> ExtendedContext.min(Decimal(\'3\'), Decimal(\'2\')) Decimal(\'2\') >>> ExtendedContext.min(Decimal(\'-10\'), Decimal(\'3\')) Decimal(\'-10\') >>> ExtendedContext.min(Decimal(\'1.0\'), Decimal(\'1\')) Decimal(\'1.0\') >>> ExtendedContext.min(Decimal(\'7\'), Decimal(\'NaN\')) Decimal(\'7\') >>> ExtendedContext.min(1, 2) Decimal(\'1\') >>> ExtendedContext.min(Decimal(1), 2) Decimal(\'1\') >>> ExtendedContext.min(1, Decimal(29)) Decimal(\'1\')'
def min(self, a, b):
a = _convert_other(a, raiseit=True) return a.min(b, context=self)
'Compares the values numerically with their sign ignored. >>> ExtendedContext.min_mag(Decimal(\'3\'), Decimal(\'-2\')) Decimal(\'-2\') >>> ExtendedContext.min_mag(Decimal(\'-3\'), Decimal(\'NaN\')) Decimal(\'-3\') >>> ExtendedContext.min_mag(1, -2) Decimal(\'1\') >>> ExtendedContext.min_mag(Decimal(1), -2) Decimal(\'1\') >>> ExtendedContext.min_mag(1, Decimal(-2)) Decimal(\'1\')'
def min_mag(self, a, b):
a = _convert_other(a, raiseit=True) return a.min_mag(b, context=self)
'Minus corresponds to unary prefix minus in Python. The operation is evaluated using the same rules as subtract; the operation minus(a) is calculated as subtract(\'0\', a) where the \'0\' has the same exponent as the operand. >>> ExtendedContext.minus(Decimal(\'1.3\')) Decimal(\'-1.3\') >>> ExtendedContext.minus(Decimal(\'-1.3\')) Decimal(\'1.3\') >>> ExtendedContext.minus(1) Decimal(\'-1\')'
def minus(self, a):
a = _convert_other(a, raiseit=True) return a.__neg__(context=self)
'multiply multiplies two operands. If either operand is a special value then the general rules apply. Otherwise, the operands are multiplied together (\'long multiplication\'), resulting in a number which may be as long as the sum of the lengths of the two operands. >>> ExtendedContext.multiply(Decimal(\'1.20\'), Decimal(\'3\')) Decimal(\'3.60\') >>> ExtendedContext.multiply(Decimal(\'7\'), Decimal(\'3\')) Decimal(\'21\') >>> ExtendedContext.multiply(Decimal(\'0.9\'), Decimal(\'0.8\')) Decimal(\'0.72\') >>> ExtendedContext.multiply(Decimal(\'0.9\'), Decimal(\'-0\')) Decimal(\'-0.0\') >>> ExtendedContext.multiply(Decimal(\'654321\'), Decimal(\'654321\')) Decimal(\'4.28135971E+11\') >>> ExtendedContext.multiply(7, 7) Decimal(\'49\') >>> ExtendedContext.multiply(Decimal(7), 7) Decimal(\'49\') >>> ExtendedContext.multiply(7, Decimal(7)) Decimal(\'49\')'
def multiply(self, a, b):
a = _convert_other(a, raiseit=True) r = a.__mul__(b, context=self) if (r is NotImplemented): raise TypeError(('Unable to convert %s to Decimal' % b)) else: return r
'Returns the largest representable number smaller than a. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> ExtendedContext.next_minus(Decimal(\'1\')) Decimal(\'0.999999999\') >>> c.next_minus(Decimal(\'1E-1007\')) Decimal(\'0E-1007\') >>> ExtendedContext.next_minus(Decimal(\'-1.00000003\')) Decimal(\'-1.00000004\') >>> c.next_minus(Decimal(\'Infinity\')) Decimal(\'9.99999999E+999\') >>> c.next_minus(1) Decimal(\'0.999999999\')'
def next_minus(self, a):
a = _convert_other(a, raiseit=True) return a.next_minus(context=self)
'Returns the smallest representable number larger than a. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> ExtendedContext.next_plus(Decimal(\'1\')) Decimal(\'1.00000001\') >>> c.next_plus(Decimal(\'-1E-1007\')) Decimal(\'-0E-1007\') >>> ExtendedContext.next_plus(Decimal(\'-1.00000003\')) Decimal(\'-1.00000002\') >>> c.next_plus(Decimal(\'-Infinity\')) Decimal(\'-9.99999999E+999\') >>> c.next_plus(1) Decimal(\'1.00000001\')'
def next_plus(self, a):
a = _convert_other(a, raiseit=True) return a.next_plus(context=self)
'Returns the number closest to a, in direction towards b. The result is the closest representable number from the first operand (but not the first operand) that is in the direction towards the second operand, unless the operands have the same value. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.next_toward(Decimal(\'1\'), Decimal(\'2\')) Decimal(\'1.00000001\') >>> c.next_toward(Decimal(\'-1E-1007\'), Decimal(\'1\')) Decimal(\'-0E-1007\') >>> c.next_toward(Decimal(\'-1.00000003\'), Decimal(\'0\')) Decimal(\'-1.00000002\') >>> c.next_toward(Decimal(\'1\'), Decimal(\'0\')) Decimal(\'0.999999999\') >>> c.next_toward(Decimal(\'1E-1007\'), Decimal(\'-100\')) Decimal(\'0E-1007\') >>> c.next_toward(Decimal(\'-1.00000003\'), Decimal(\'-10\')) Decimal(\'-1.00000004\') >>> c.next_toward(Decimal(\'0.00\'), Decimal(\'-0.0000\')) Decimal(\'-0.00\') >>> c.next_toward(0, 1) Decimal(\'1E-1007\') >>> c.next_toward(Decimal(0), 1) Decimal(\'1E-1007\') >>> c.next_toward(0, Decimal(1)) Decimal(\'1E-1007\')'
def next_toward(self, a, b):
a = _convert_other(a, raiseit=True) return a.next_toward(b, context=self)
'normalize reduces an operand to its simplest form. Essentially a plus operation with all trailing zeros removed from the result. >>> ExtendedContext.normalize(Decimal(\'2.1\')) Decimal(\'2.1\') >>> ExtendedContext.normalize(Decimal(\'-2.0\')) Decimal(\'-2\') >>> ExtendedContext.normalize(Decimal(\'1.200\')) Decimal(\'1.2\') >>> ExtendedContext.normalize(Decimal(\'-120\')) Decimal(\'-1.2E+2\') >>> ExtendedContext.normalize(Decimal(\'120.00\')) Decimal(\'1.2E+2\') >>> ExtendedContext.normalize(Decimal(\'0.00\')) Decimal(\'0\') >>> ExtendedContext.normalize(6) Decimal(\'6\')'
def normalize(self, a):
a = _convert_other(a, raiseit=True) return a.normalize(context=self)
'Returns an indication of the class of the operand. The class is one of the following strings: -sNaN -NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity >>> c = Context(ExtendedContext) >>> c.Emin = -999 >>> c.Emax = 999 >>> c.number_class(Decimal(\'Infinity\')) \'+Infinity\' >>> c.number_class(Decimal(\'1E-10\')) \'+Normal\' >>> c.number_class(Decimal(\'2.50\')) \'+Normal\' >>> c.number_class(Decimal(\'0.1E-999\')) \'+Subnormal\' >>> c.number_class(Decimal(\'0\')) \'+Zero\' >>> c.number_class(Decimal(\'-0\')) \'-Zero\' >>> c.number_class(Decimal(\'-0.1E-999\')) \'-Subnormal\' >>> c.number_class(Decimal(\'-1E-10\')) \'-Normal\' >>> c.number_class(Decimal(\'-2.50\')) \'-Normal\' >>> c.number_class(Decimal(\'-Infinity\')) \'-Infinity\' >>> c.number_class(Decimal(\'NaN\')) \'NaN\' >>> c.number_class(Decimal(\'-NaN\')) \'NaN\' >>> c.number_class(Decimal(\'sNaN\')) \'sNaN\' >>> c.number_class(123) \'+Normal\''
def number_class(self, a):
a = _convert_other(a, raiseit=True) return a.number_class(context=self)
'Plus corresponds to unary prefix plus in Python. The operation is evaluated using the same rules as add; the operation plus(a) is calculated as add(\'0\', a) where the \'0\' has the same exponent as the operand. >>> ExtendedContext.plus(Decimal(\'1.3\')) Decimal(\'1.3\') >>> ExtendedContext.plus(Decimal(\'-1.3\')) Decimal(\'-1.3\') >>> ExtendedContext.plus(-1) Decimal(\'-1\')'
def plus(self, a):
a = _convert_other(a, raiseit=True) return a.__pos__(context=self)
'Raises a to the power of b, to modulo if given. With two arguments, compute a**b. If a is negative then b must be integral. The result will be inexact unless b is integral and the result is finite and can be expressed exactly in \'precision\' digits. With three arguments, compute (a**b) % modulo. For the three argument form, the following restrictions on the arguments hold: - all three arguments must be integral - b must be nonnegative - at least one of a or b must be nonzero - modulo must be nonzero and have at most \'precision\' digits The result of pow(a, b, modulo) is identical to the result that would be obtained by computing (a**b) % modulo with unbounded precision, but is computed more efficiently. It is always exact. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.power(Decimal(\'2\'), Decimal(\'3\')) Decimal(\'8\') >>> c.power(Decimal(\'-2\'), Decimal(\'3\')) Decimal(\'-8\') >>> c.power(Decimal(\'2\'), Decimal(\'-3\')) Decimal(\'0.125\') >>> c.power(Decimal(\'1.7\'), Decimal(\'8\')) Decimal(\'69.7575744\') >>> c.power(Decimal(\'10\'), Decimal(\'0.301029996\')) Decimal(\'2.00000000\') >>> c.power(Decimal(\'Infinity\'), Decimal(\'-1\')) Decimal(\'0\') >>> c.power(Decimal(\'Infinity\'), Decimal(\'0\')) Decimal(\'1\') >>> c.power(Decimal(\'Infinity\'), Decimal(\'1\')) Decimal(\'Infinity\') >>> c.power(Decimal(\'-Infinity\'), Decimal(\'-1\')) Decimal(\'-0\') >>> c.power(Decimal(\'-Infinity\'), Decimal(\'0\')) Decimal(\'1\') >>> c.power(Decimal(\'-Infinity\'), Decimal(\'1\')) Decimal(\'-Infinity\') >>> c.power(Decimal(\'-Infinity\'), Decimal(\'2\')) Decimal(\'Infinity\') >>> c.power(Decimal(\'0\'), Decimal(\'0\')) Decimal(\'NaN\') >>> c.power(Decimal(\'3\'), Decimal(\'7\'), Decimal(\'16\')) Decimal(\'11\') >>> c.power(Decimal(\'-3\'), Decimal(\'7\'), Decimal(\'16\')) Decimal(\'-11\') >>> c.power(Decimal(\'-3\'), Decimal(\'8\'), Decimal(\'16\')) Decimal(\'1\') >>> c.power(Decimal(\'3\'), Decimal(\'7\'), Decimal(\'-16\')) Decimal(\'11\') >>> c.power(Decimal(\'23E12345\'), Decimal(\'67E189\'), Decimal(\'123456789\')) Decimal(\'11729830\') >>> c.power(Decimal(\'-0\'), Decimal(\'17\'), Decimal(\'1729\')) Decimal(\'-0\') >>> c.power(Decimal(\'-23\'), Decimal(\'0\'), Decimal(\'65537\')) Decimal(\'1\') >>> ExtendedContext.power(7, 7) Decimal(\'823543\') >>> ExtendedContext.power(Decimal(7), 7) Decimal(\'823543\') >>> ExtendedContext.power(7, Decimal(7), 2) Decimal(\'1\')'
def power(self, a, b, modulo=None):
a = _convert_other(a, raiseit=True) r = a.__pow__(b, modulo, context=self) if (r is NotImplemented): raise TypeError(('Unable to convert %s to Decimal' % b)) else: return r
'Returns a value equal to \'a\' (rounded), having the exponent of \'b\'. The coefficient of the result is derived from that of the left-hand operand. It may be rounded using the current rounding setting (if the exponent is being increased), multiplied by a positive power of ten (if the exponent is being decreased), or is unchanged (if the exponent is already equal to that of the right-hand operand). Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision then an Invalid operation condition is raised. This guarantees that, unless there is an error condition, the exponent of the result of a quantize is always equal to that of the right-hand operand. Also unlike other operations, quantize will never raise Underflow, even if the result is subnormal and inexact. >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.001\')) Decimal(\'2.170\') >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.01\')) Decimal(\'2.17\') >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.1\')) Decimal(\'2.2\') >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'1e+0\')) Decimal(\'2\') >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'1e+1\')) Decimal(\'0E+1\') >>> ExtendedContext.quantize(Decimal(\'-Inf\'), Decimal(\'Infinity\')) Decimal(\'-Infinity\') >>> ExtendedContext.quantize(Decimal(\'2\'), Decimal(\'Infinity\')) Decimal(\'NaN\') >>> ExtendedContext.quantize(Decimal(\'-0.1\'), Decimal(\'1\')) Decimal(\'-0\') >>> ExtendedContext.quantize(Decimal(\'-0\'), Decimal(\'1e+5\')) Decimal(\'-0E+5\') >>> ExtendedContext.quantize(Decimal(\'+35236450.6\'), Decimal(\'1e-2\')) Decimal(\'NaN\') >>> ExtendedContext.quantize(Decimal(\'-35236450.6\'), Decimal(\'1e-2\')) Decimal(\'NaN\') >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e-1\')) Decimal(\'217.0\') >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e-0\')) Decimal(\'217\') >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e+1\')) Decimal(\'2.2E+2\') >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e+2\')) Decimal(\'2E+2\') >>> ExtendedContext.quantize(1, 2) Decimal(\'1\') >>> ExtendedContext.quantize(Decimal(1), 2) Decimal(\'1\') >>> ExtendedContext.quantize(1, Decimal(2)) Decimal(\'1\')'
def quantize(self, a, b):
a = _convert_other(a, raiseit=True) return a.quantize(b, context=self)
'Just returns 10, as this is Decimal, :) >>> ExtendedContext.radix() Decimal(\'10\')'
def radix(self):
return Decimal(10)
'Returns the remainder from integer division. The result is the residue of the dividend after the operation of calculating integer division as described for divide-integer, rounded to precision digits if necessary. The sign of the result, if non-zero, is the same as that of the original dividend. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder(Decimal(\'2.1\'), Decimal(\'3\')) Decimal(\'2.1\') >>> ExtendedContext.remainder(Decimal(\'10\'), Decimal(\'3\')) Decimal(\'1\') >>> ExtendedContext.remainder(Decimal(\'-10\'), Decimal(\'3\')) Decimal(\'-1\') >>> ExtendedContext.remainder(Decimal(\'10.2\'), Decimal(\'1\')) Decimal(\'0.2\') >>> ExtendedContext.remainder(Decimal(\'10\'), Decimal(\'0.3\')) Decimal(\'0.1\') >>> ExtendedContext.remainder(Decimal(\'3.6\'), Decimal(\'1.3\')) Decimal(\'1.0\') >>> ExtendedContext.remainder(22, 6) Decimal(\'4\') >>> ExtendedContext.remainder(Decimal(22), 6) Decimal(\'4\') >>> ExtendedContext.remainder(22, Decimal(6)) Decimal(\'4\')'
def remainder(self, a, b):
a = _convert_other(a, raiseit=True) r = a.__mod__(b, context=self) if (r is NotImplemented): raise TypeError(('Unable to convert %s to Decimal' % b)) else: return r
'Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal(\'2.1\'), Decimal(\'3\')) Decimal(\'-0.9\') >>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'6\')) Decimal(\'-2\') >>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'3\')) Decimal(\'1\') >>> ExtendedContext.remainder_near(Decimal(\'-10\'), Decimal(\'3\')) Decimal(\'-1\') >>> ExtendedContext.remainder_near(Decimal(\'10.2\'), Decimal(\'1\')) Decimal(\'0.2\') >>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'0.3\')) Decimal(\'0.1\') >>> ExtendedContext.remainder_near(Decimal(\'3.6\'), Decimal(\'1.3\')) Decimal(\'-0.3\') >>> ExtendedContext.remainder_near(3, 11) Decimal(\'3\') >>> ExtendedContext.remainder_near(Decimal(3), 11) Decimal(\'3\') >>> ExtendedContext.remainder_near(3, Decimal(11)) Decimal(\'3\')'
def remainder_near(self, a, b):
a = _convert_other(a, raiseit=True) return a.remainder_near(b, context=self)
'Returns a rotated copy of a, b times. The coefficient of the result is a rotated copy of the digits in the coefficient of the first operand. The number of places of rotation is taken from the absolute value of the second operand, with the rotation being to the left if the second operand is positive or to the right otherwise. >>> ExtendedContext.rotate(Decimal(\'34\'), Decimal(\'8\')) Decimal(\'400000003\') >>> ExtendedContext.rotate(Decimal(\'12\'), Decimal(\'9\')) Decimal(\'12\') >>> ExtendedContext.rotate(Decimal(\'123456789\'), Decimal(\'-2\')) Decimal(\'891234567\') >>> ExtendedContext.rotate(Decimal(\'123456789\'), Decimal(\'0\')) Decimal(\'123456789\') >>> ExtendedContext.rotate(Decimal(\'123456789\'), Decimal(\'+2\')) Decimal(\'345678912\') >>> ExtendedContext.rotate(1333333, 1) Decimal(\'13333330\') >>> ExtendedContext.rotate(Decimal(1333333), 1) Decimal(\'13333330\') >>> ExtendedContext.rotate(1333333, Decimal(1)) Decimal(\'13333330\')'
def rotate(self, a, b):
a = _convert_other(a, raiseit=True) return a.rotate(b, context=self)
'Returns True if the two operands have the same exponent. The result is never affected by either the sign or the coefficient of either operand. >>> ExtendedContext.same_quantum(Decimal(\'2.17\'), Decimal(\'0.001\')) False >>> ExtendedContext.same_quantum(Decimal(\'2.17\'), Decimal(\'0.01\')) True >>> ExtendedContext.same_quantum(Decimal(\'2.17\'), Decimal(\'1\')) False >>> ExtendedContext.same_quantum(Decimal(\'Inf\'), Decimal(\'-Inf\')) True >>> ExtendedContext.same_quantum(10000, -1) True >>> ExtendedContext.same_quantum(Decimal(10000), -1) True >>> ExtendedContext.same_quantum(10000, Decimal(-1)) True'
def same_quantum(self, a, b):
a = _convert_other(a, raiseit=True) return a.same_quantum(b)
'Returns the first operand after adding the second value its exp. >>> ExtendedContext.scaleb(Decimal(\'7.50\'), Decimal(\'-2\')) Decimal(\'0.0750\') >>> ExtendedContext.scaleb(Decimal(\'7.50\'), Decimal(\'0\')) Decimal(\'7.50\') >>> ExtendedContext.scaleb(Decimal(\'7.50\'), Decimal(\'3\')) Decimal(\'7.50E+3\') >>> ExtendedContext.scaleb(1, 4) Decimal(\'1E+4\') >>> ExtendedContext.scaleb(Decimal(1), 4) Decimal(\'1E+4\') >>> ExtendedContext.scaleb(1, Decimal(4)) Decimal(\'1E+4\')'
def scaleb(self, a, b):
a = _convert_other(a, raiseit=True) return a.scaleb(b, context=self)
'Returns a shifted copy of a, b times. The coefficient of the result is a shifted copy of the digits in the coefficient of the first operand. The number of places to shift is taken from the absolute value of the second operand, with the shift being to the left if the second operand is positive or to the right otherwise. Digits shifted into the coefficient are zeros. >>> ExtendedContext.shift(Decimal(\'34\'), Decimal(\'8\')) Decimal(\'400000000\') >>> ExtendedContext.shift(Decimal(\'12\'), Decimal(\'9\')) Decimal(\'0\') >>> ExtendedContext.shift(Decimal(\'123456789\'), Decimal(\'-2\')) Decimal(\'1234567\') >>> ExtendedContext.shift(Decimal(\'123456789\'), Decimal(\'0\')) Decimal(\'123456789\') >>> ExtendedContext.shift(Decimal(\'123456789\'), Decimal(\'+2\')) Decimal(\'345678900\') >>> ExtendedContext.shift(88888888, 2) Decimal(\'888888800\') >>> ExtendedContext.shift(Decimal(88888888), 2) Decimal(\'888888800\') >>> ExtendedContext.shift(88888888, Decimal(2)) Decimal(\'888888800\')'
def shift(self, a, b):
a = _convert_other(a, raiseit=True) return a.shift(b, context=self)
'Square root of a non-negative number to context precision. If the result must be inexact, it is rounded using the round-half-even algorithm. >>> ExtendedContext.sqrt(Decimal(\'0\')) Decimal(\'0\') >>> ExtendedContext.sqrt(Decimal(\'-0\')) Decimal(\'-0\') >>> ExtendedContext.sqrt(Decimal(\'0.39\')) Decimal(\'0.624499800\') >>> ExtendedContext.sqrt(Decimal(\'100\')) Decimal(\'10\') >>> ExtendedContext.sqrt(Decimal(\'1\')) Decimal(\'1\') >>> ExtendedContext.sqrt(Decimal(\'1.0\')) Decimal(\'1.0\') >>> ExtendedContext.sqrt(Decimal(\'1.00\')) Decimal(\'1.0\') >>> ExtendedContext.sqrt(Decimal(\'7\')) Decimal(\'2.64575131\') >>> ExtendedContext.sqrt(Decimal(\'10\')) Decimal(\'3.16227766\') >>> ExtendedContext.sqrt(2) Decimal(\'1.41421356\') >>> ExtendedContext.prec 9'
def sqrt(self, a):
a = _convert_other(a, raiseit=True) return a.sqrt(context=self)
'Return the difference between the two operands. >>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'1.07\')) Decimal(\'0.23\') >>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'1.30\')) Decimal(\'0.00\') >>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'2.07\')) Decimal(\'-0.77\') >>> ExtendedContext.subtract(8, 5) Decimal(\'3\') >>> ExtendedContext.subtract(Decimal(8), 5) Decimal(\'3\') >>> ExtendedContext.subtract(8, Decimal(5)) Decimal(\'3\')'
def subtract(self, a, b):
a = _convert_other(a, raiseit=True) r = a.__sub__(b, context=self) if (r is NotImplemented): raise TypeError(('Unable to convert %s to Decimal' % b)) else: return r
'Converts a number to a string, using scientific notation. The operation is not affected by the context.'
def to_eng_string(self, a):
a = _convert_other(a, raiseit=True) return a.to_eng_string(context=self)
'Converts a number to a string, using scientific notation. The operation is not affected by the context.'
def to_sci_string(self, a):
a = _convert_other(a, raiseit=True) return a.__str__(context=self)
'Rounds to an integer. When the operand has a negative exponent, the result is the same as using the quantize() operation using the given operand as the left-hand-operand, 1E+0 as the right-hand-operand, and the precision of the operand as the precision setting; Inexact and Rounded flags are allowed in this operation. The rounding mode is taken from the context. >>> ExtendedContext.to_integral_exact(Decimal(\'2.1\')) Decimal(\'2\') >>> ExtendedContext.to_integral_exact(Decimal(\'100\')) Decimal(\'100\') >>> ExtendedContext.to_integral_exact(Decimal(\'100.0\')) Decimal(\'100\') >>> ExtendedContext.to_integral_exact(Decimal(\'101.5\')) Decimal(\'102\') >>> ExtendedContext.to_integral_exact(Decimal(\'-101.5\')) Decimal(\'-102\') >>> ExtendedContext.to_integral_exact(Decimal(\'10E+5\')) Decimal(\'1.0E+6\') >>> ExtendedContext.to_integral_exact(Decimal(\'7.89E+77\')) Decimal(\'7.89E+77\') >>> ExtendedContext.to_integral_exact(Decimal(\'-Inf\')) Decimal(\'-Infinity\')'
def to_integral_exact(self, a):
a = _convert_other(a, raiseit=True) return a.to_integral_exact(context=self)
'Rounds to an integer. When the operand has a negative exponent, the result is the same as using the quantize() operation using the given operand as the left-hand-operand, 1E+0 as the right-hand-operand, and the precision of the operand as the precision setting, except that no flags will be set. The rounding mode is taken from the context. >>> ExtendedContext.to_integral_value(Decimal(\'2.1\')) Decimal(\'2\') >>> ExtendedContext.to_integral_value(Decimal(\'100\')) Decimal(\'100\') >>> ExtendedContext.to_integral_value(Decimal(\'100.0\')) Decimal(\'100\') >>> ExtendedContext.to_integral_value(Decimal(\'101.5\')) Decimal(\'102\') >>> ExtendedContext.to_integral_value(Decimal(\'-101.5\')) Decimal(\'-102\') >>> ExtendedContext.to_integral_value(Decimal(\'10E+5\')) Decimal(\'1.0E+6\') >>> ExtendedContext.to_integral_value(Decimal(\'7.89E+77\')) Decimal(\'7.89E+77\') >>> ExtendedContext.to_integral_value(Decimal(\'-Inf\')) Decimal(\'-Infinity\')'
def to_integral_value(self, a):
a = _convert_other(a, raiseit=True) return a.to_integral_value(context=self)
'Given an integer p >= 0, return floor(10**p)*log(10). For example, self.getdigits(3) returns 2302.'
def getdigits(self, p):
if (p < 0): raise ValueError('p should be nonnegative') if (p >= len(self.digits)): extra = 3 while True: M = (10 ** ((p + extra) + 2)) digits = str(_div_nearest(_ilog((10 * M), M), 100)) if (digits[(- extra):] != ('0' * extra)): break extra += 3 self.digits = digits.rstrip('0')[:(-1)] return int(self.digits[:(p + 1)])
'Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. *OR* A hashlib constructor returning a new hash object. Defaults to hashlib.md5.'
def __init__(self, key, msg=None, digestmod=None):
if (key is _secret_backdoor_key): return if (digestmod is None): import hashlib digestmod = hashlib.md5 if hasattr(digestmod, '__call__'): self.digest_cons = digestmod else: self.digest_cons = (lambda d='': digestmod.new(d)) self.outer = self.digest_cons() self.inner = self.digest_cons() self.digest_size = self.inner.digest_size if hasattr(self.inner, 'block_size'): blocksize = self.inner.block_size if (blocksize < 16): _warnings.warn(('block_size of %d seems too small; using our default of %d.' % (blocksize, self.blocksize)), RuntimeWarning, 2) blocksize = self.blocksize else: _warnings.warn(('No block_size attribute on given digest object; Assuming %d.' % self.blocksize), RuntimeWarning, 2) blocksize = self.blocksize if (len(key) > blocksize): key = self.digest_cons(key).digest() key = (key + (chr(0) * (blocksize - len(key)))) self.outer.update(key.translate(trans_5C)) self.inner.update(key.translate(trans_36)) if (msg is not None): self.update(msg)
'Update this hashing object with the string msg.'
def update(self, msg):
self.inner.update(msg)
'Return a separate copy of this hashing object. An update to this copy won\'t affect the original object.'
def copy(self):
other = self.__class__(_secret_backdoor_key) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other
'Return a hash object for the current state. To be used only internally with digest() and hexdigest().'
def _current(self):
h = self.outer.copy() h.update(self.inner.digest()) return h
'Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function.'
def digest(self):
h = self._current() return h.digest()
'Like digest(), but returns a string of hexadecimal digits instead.'
def hexdigest(self):
h = self._current() return h.hexdigest()
'Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.'
def __init__(self, methodName='runTest'):
self._testMethodName = methodName self._resultForDoCleanups = None try: testMethod = getattr(self, methodName) except AttributeError: raise ValueError(('no such test method in %s: %s' % (self.__class__, methodName))) self._testMethodDoc = testMethod.__doc__ self._cleanups = [] self._type_equality_funcs = {} self.addTypeEqualityFunc(dict, 'assertDictEqual') self.addTypeEqualityFunc(list, 'assertListEqual') self.addTypeEqualityFunc(tuple, 'assertTupleEqual') self.addTypeEqualityFunc(set, 'assertSetEqual') self.addTypeEqualityFunc(frozenset, 'assertSetEqual') try: self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual') except NameError: pass
'Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function: The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.'
def addTypeEqualityFunc(self, typeobj, function):
self._type_equality_funcs[typeobj] = function
'Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).'
def addCleanup(self, function, *args, **kwargs):
self._cleanups.append((function, args, kwargs))
'Hook method for setting up the test fixture before exercising it.'
def setUp(self):
pass
'Hook method for deconstructing the test fixture after testing it.'
def tearDown(self):
pass
'Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the specified test method\'s docstring.'
def shortDescription(self):
doc = self._testMethodDoc return ((doc and doc.split('\n')[0].strip()) or None)
'Execute all cleanup functions. Normally called for you after tearDown.'
def doCleanups(self):
result = self._resultForDoCleanups ok = True while self._cleanups: (function, args, kwargs) = self._cleanups.pop((-1)) try: function(*args, **kwargs) except KeyboardInterrupt: raise except: ok = False result.addError(self, sys.exc_info()) return ok
'Run the test without collecting errors in a TestResult'
def debug(self):
self.setUp() getattr(self, self._testMethodName)() self.tearDown() while self._cleanups: (function, args, kwargs) = self._cleanups.pop((-1)) function(*args, **kwargs)
'Skip this test.'
def skipTest(self, reason):
raise SkipTest(reason)
'Fail immediately, with the given message.'
def fail(self, msg=None):
raise self.failureException(msg)
'Check that the expression is false.'
def assertFalse(self, expr, msg=None):
if expr: msg = self._formatMessage(msg, ('%s is not false' % safe_repr(expr))) raise self.failureException(msg)
'Check that the expression is true.'
def assertTrue(self, expr, msg=None):
if (not expr): msg = self._formatMessage(msg, ('%s is not true' % safe_repr(expr))) raise self.failureException(msg)
'Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert If longMessage is True: * Use the standard message * If an explicit message is provided, plus \' : \' and the explicit message'
def _formatMessage(self, msg, standardMsg):
if (not self.longMessage): return (msg or standardMsg) if (msg is None): return standardMsg try: return ('%s : %s' % (standardMsg, msg)) except UnicodeDecodeError: return ('%s : %s' % (safe_repr(standardMsg), safe_repr(msg)))
'Fail unless an exception of class excClass is raised by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If called with callableObj omitted or None, will return a context object used like this:: with self.assertRaises(SomeException): do_something() The context manager keeps a reference to the exception as the \'exception\' attribute. This allows you to inspect the exception after the assertion:: with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3)'
def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
context = _AssertRaisesContext(excClass, self) if (callableObj is None): return context with context: callableObj(*args, **kwargs)
'Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types.'
def _getAssertEqualityFunc(self, first, second):
if (type(first) is type(second)): asserter = self._type_equality_funcs.get(type(first)) if (asserter is not None): if isinstance(asserter, basestring): asserter = getattr(self, asserter) return asserter return self._baseAssertEqual
'The default assertEqual implementation, not type specific.'
def _baseAssertEqual(self, first, second, msg=None):
if (not (first == second)): standardMsg = ('%s != %s' % (safe_repr(first), safe_repr(second))) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
'Fail if the two objects are unequal as determined by the \'==\' operator.'
def assertEqual(self, first, second, msg=None):
assertion_func = self._getAssertEqualityFunc(first, second) assertion_func(first, second, msg=msg)
'Fail if the two objects are equal as determined by the \'!=\' operator.'
def assertNotEqual(self, first, second, msg=None):
if (not (first != second)): msg = self._formatMessage(msg, ('%s == %s' % (safe_repr(first), safe_repr(second)))) raise self.failureException(msg)
'Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). If the two objects compare equal then they will automatically compare almost equal.'
def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
if (first == second): return if ((delta is not None) and (places is not None)): raise TypeError('specify delta or places not both') if (delta is not None): if (abs((first - second)) <= delta): return standardMsg = ('%s != %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta))) else: if (places is None): places = 7 if (round(abs((second - first)), places) == 0): return standardMsg = ('%s != %s within %r places' % (safe_repr(first), safe_repr(second), places)) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
'Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). Objects that are equal automatically fail.'
def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
if ((delta is not None) and (places is not None)): raise TypeError('specify delta or places not both') if (delta is not None): if ((not (first == second)) and (abs((first - second)) > delta)): return standardMsg = ('%s == %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta))) else: if (places is None): places = 7 if ((not (first == second)) and (round(abs((second - first)), places) != 0)): return standardMsg = ('%s == %s within %r places' % (safe_repr(first), safe_repr(second), places)) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
'An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences.'
def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
if (seq_type is not None): seq_type_name = seq_type.__name__ if (not isinstance(seq1, seq_type)): raise self.failureException(('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1)))) if (not isinstance(seq2, seq_type)): raise self.failureException(('Second sequence is not a %s: %s' % (seq_type_name, safe_repr(seq2)))) else: seq_type_name = 'sequence' differing = None try: len1 = len(seq1) except (TypeError, NotImplementedError): differing = ('First %s has no length. Non-sequence?' % seq_type_name) if (differing is None): try: len2 = len(seq2) except (TypeError, NotImplementedError): differing = ('Second %s has no length. Non-sequence?' % seq_type_name) if (differing is None): if (seq1 == seq2): return seq1_repr = safe_repr(seq1) seq2_repr = safe_repr(seq2) if (len(seq1_repr) > 30): seq1_repr = (seq1_repr[:30] + '...') if (len(seq2_repr) > 30): seq2_repr = (seq2_repr[:30] + '...') elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr) differing = ('%ss differ: %s != %s\n' % elements) for i in xrange(min(len1, len2)): try: item1 = seq1[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of first %s\n' % (i, seq_type_name)) break try: item2 = seq2[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of second %s\n' % (i, seq_type_name)) break if (item1 != item2): differing += ('\nFirst differing element %d:\n%s\n%s\n' % (i, safe_repr(item1), safe_repr(item2))) break else: if ((len1 == len2) and (seq_type is None) and (type(seq1) != type(seq2))): return if (len1 > len2): differing += ('\nFirst %s contains %d additional elements.\n' % (seq_type_name, (len1 - len2))) try: differing += ('First extra element %d:\n%s\n' % (len2, safe_repr(seq1[len2]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d of first %s\n' % (len2, seq_type_name)) elif (len1 < len2): differing += ('\nSecond %s contains %d additional elements.\n' % (seq_type_name, (len2 - len1))) try: differing += ('First extra element %d:\n%s\n' % (len1, safe_repr(seq2[len1]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d of second %s\n' % (len1, seq_type_name)) standardMsg = differing diffMsg = ('\n' + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines()))) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg)
'A list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences.'
def assertListEqual(self, list1, list2, msg=None):
self.assertSequenceEqual(list1, list2, msg, seq_type=list)
'A tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences.'
def assertTupleEqual(self, tuple1, tuple2, msg=None):
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
'A set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).'
def assertSetEqual(self, set1, set2, msg=None):
try: difference1 = set1.difference(set2) except TypeError as e: self.fail(('invalid type when attempting set difference: %s' % e)) except AttributeError as e: self.fail(('first argument does not support set difference: %s' % e)) try: difference2 = set2.difference(set1) except TypeError as e: self.fail(('invalid type when attempting set difference: %s' % e)) except AttributeError as e: self.fail(('second argument does not support set difference: %s' % e)) if (not (difference1 or difference2)): return lines = [] if difference1: lines.append('Items in the first set but not the second:') for item in difference1: lines.append(repr(item)) if difference2: lines.append('Items in the second set but not the first:') for item in difference2: lines.append(repr(item)) standardMsg = '\n'.join(lines) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a in b), but with a nicer default message.'
def assertIn(self, member, container, msg=None):
if (member not in container): standardMsg = ('%s not found in %s' % (safe_repr(member), safe_repr(container))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a not in b), but with a nicer default message.'
def assertNotIn(self, member, container, msg=None):
if (member in container): standardMsg = ('%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a is b), but with a nicer default message.'
def assertIs(self, expr1, expr2, msg=None):
if (expr1 is not expr2): standardMsg = ('%s is not %s' % (safe_repr(expr1), safe_repr(expr2))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a is not b), but with a nicer default message.'
def assertIsNot(self, expr1, expr2, msg=None):
if (expr1 is expr2): standardMsg = ('unexpectedly identical: %s' % (safe_repr(expr1),)) self.fail(self._formatMessage(msg, standardMsg))
'Checks whether actual is a superset of expected.'
def assertDictContainsSubset(self, expected, actual, msg=None):
missing = [] mismatched = [] for (key, value) in expected.iteritems(): if (key not in actual): missing.append(key) elif (value != actual[key]): mismatched.append(('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(actual[key])))) if (not (missing or mismatched)): return standardMsg = '' if missing: standardMsg = ('Missing: %s' % ','.join((safe_repr(m) for m in missing))) if mismatched: if standardMsg: standardMsg += '; ' standardMsg += ('Mismatched values: %s' % ','.join(mismatched)) self.fail(self._formatMessage(msg, standardMsg))
'An unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:: self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq))) Asserts that each element has the same count in both sequences. Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal.'
def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
(first_seq, second_seq) = (list(expected_seq), list(actual_seq)) with warnings.catch_warnings(): if sys.py3kwarning: for _msg in ['(code|dict|type) inequality comparisons', 'builtin_function_or_method order comparisons', 'comparing unequal types']: warnings.filterwarnings('ignore', _msg, DeprecationWarning) try: first = collections.Counter(first_seq) second = collections.Counter(second_seq) except TypeError: differences = _count_diff_all_purpose(first_seq, second_seq) else: if (first == second): return differences = _count_diff_hashable(first_seq, second_seq) if differences: standardMsg = 'Element counts were not equal:\n' lines = [('First has %d, Second has %d: %r' % diff) for diff in differences] diffMsg = '\n'.join(lines) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg)
'Assert that two multi-line strings are equal.'
def assertMultiLineEqual(self, first, second, msg=None):
self.assertIsInstance(first, basestring, 'First argument is not a string') self.assertIsInstance(second, basestring, 'Second argument is not a string') if (first != second): if ((len(first) > self._diffThreshold) or (len(second) > self._diffThreshold)): self._baseAssertEqual(first, second, msg) firstlines = first.splitlines(True) secondlines = second.splitlines(True) if ((len(firstlines) == 1) and (first.strip('\r\n') == first)): firstlines = [(first + '\n')] secondlines = [(second + '\n')] standardMsg = ('%s != %s' % (safe_repr(first, True), safe_repr(second, True))) diff = ('\n' + ''.join(difflib.ndiff(firstlines, secondlines))) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a < b), but with a nicer default message.'
def assertLess(self, a, b, msg=None):
if (not (a < b)): standardMsg = ('%s not less than %s' % (safe_repr(a), safe_repr(b))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a <= b), but with a nicer default message.'
def assertLessEqual(self, a, b, msg=None):
if (not (a <= b)): standardMsg = ('%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a > b), but with a nicer default message.'
def assertGreater(self, a, b, msg=None):
if (not (a > b)): standardMsg = ('%s not greater than %s' % (safe_repr(a), safe_repr(b))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a >= b), but with a nicer default message.'
def assertGreaterEqual(self, a, b, msg=None):
if (not (a >= b)): standardMsg = ('%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))) self.fail(self._formatMessage(msg, standardMsg))
'Same as self.assertTrue(obj is None), with a nicer default message.'
def assertIsNone(self, obj, msg=None):
if (obj is not None): standardMsg = ('%s is not None' % (safe_repr(obj),)) self.fail(self._formatMessage(msg, standardMsg))
'Included for symmetry with assertIsNone.'
def assertIsNotNone(self, obj, msg=None):
if (obj is None): standardMsg = 'unexpectedly None' self.fail(self._formatMessage(msg, standardMsg))
'Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.'
def assertIsInstance(self, obj, cls, msg=None):
if (not isinstance(obj, cls)): standardMsg = ('%s is not an instance of %r' % (safe_repr(obj), cls)) self.fail(self._formatMessage(msg, standardMsg))
'Included for symmetry with assertIsInstance.'
def assertNotIsInstance(self, obj, cls, msg=None):
if isinstance(obj, cls): standardMsg = ('%s is an instance of %r' % (safe_repr(obj), cls)) self.fail(self._formatMessage(msg, standardMsg))