desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Swaps self/other and returns __mod__.'
| def __rmod__(self, other, context=None):
| other = _convert_other(other)
return other.__mod__(self, context=context)
|
'Remainder nearest to 0- abs(remainder-near) <= other/2'
| def remainder_near(self, other, context=None):
| other = _convert_other(other)
if (self._is_special or other._is_special):
ans = self._check_nans(other, context)
if ans:
return ans
if (self and (not other)):
return context._raise_error(InvalidOperation, 'x % 0')
if (context is None):
context = getcontext()
context = context._shallow_copy()
flags = context._ignore_flags(Rounded, Inexact)
(side, r) = self.__divmod__(other, context=context)
if r._isnan():
context._regard_flags(*flags)
return r
context = context._shallow_copy()
rounding = context._set_rounding_decision(NEVER_ROUND)
if other._sign:
comparison = other.__div__(Decimal((-2)), context=context)
else:
comparison = other.__div__(Decimal(2), context=context)
context._set_rounding_decision(rounding)
context._regard_flags(*flags)
(s1, s2) = (r._sign, comparison._sign)
(r._sign, comparison._sign) = (0, 0)
if (r < comparison):
(r._sign, comparison._sign) = (s1, s2)
self.__divmod__(other, context=context)
return r._fix(context)
(r._sign, comparison._sign) = (s1, s2)
rounding = context._set_rounding_decision(NEVER_ROUND)
(side, r) = self.__divmod__(other, context=context)
context._set_rounding_decision(rounding)
if r._isnan():
return r
decrease = (not side._iseven())
rounding = context._set_rounding_decision(NEVER_ROUND)
side = side.__abs__(context=context)
context._set_rounding_decision(rounding)
(s1, s2) = (r._sign, comparison._sign)
(r._sign, comparison._sign) = (0, 0)
if ((r > comparison) or (decrease and (r == comparison))):
(r._sign, comparison._sign) = (s1, s2)
context.prec += 1
if (len(side.__add__(Decimal(1), context=context)._int) >= context.prec):
context.prec -= 1
return context._raise_error(DivisionImpossible)[1]
context.prec -= 1
if (self._sign == other._sign):
r = r.__sub__(other, context=context)
else:
r = r.__add__(other, context=context)
else:
(r._sign, comparison._sign) = (s1, s2)
return r._fix(context)
|
'self // other'
| def __floordiv__(self, other, context=None):
| return self._divide(other, 2, context)[0]
|
'Swaps self/other and returns __floordiv__.'
| def __rfloordiv__(self, other, context=None):
| other = _convert_other(other)
return other.__floordiv__(self, context=context)
|
'Float representation.'
| def __float__(self):
| return float(str(self))
|
'Converts self to an int, truncating if necessary.'
| def __int__(self):
| if self._is_special:
if self._isnan():
context = getcontext()
return context._raise_error(InvalidContext)
elif self._isinfinity():
raise OverflowError, 'Cannot convert infinity to long'
if (self._exp >= 0):
s = (''.join(map(str, self._int)) + ('0' * self._exp))
else:
s = ''.join(map(str, self._int))[:self._exp]
if (s == ''):
s = '0'
sign = ('-' * self._sign)
return int((sign + s))
|
'Converts to a long.
Equivalent to long(int(self))'
| def __long__(self):
| return long(self.__int__())
|
'Round if it is necessary to keep self within prec precision.
Rounds and fixes the exponent. Does not raise on a sNaN.
Arguments:
self - Decimal instance
context - context used.'
| def _fix(self, context):
| if self._is_special:
return self
if (context is None):
context = getcontext()
prec = context.prec
ans = self._fixexponents(context)
if (len(ans._int) > prec):
ans = ans._round(prec, context=context)
ans = ans._fixexponents(context)
return ans
|
'Fix the exponents and return a copy with the exponent in bounds.
Only call if known to not be a special value.'
| def _fixexponents(self, context):
| folddown = context._clamp
Emin = context.Emin
ans = self
ans_adjusted = ans.adjusted()
if (ans_adjusted < Emin):
Etiny = context.Etiny()
if (ans._exp < Etiny):
if (not ans):
ans = Decimal(self)
ans._exp = Etiny
context._raise_error(Clamped)
return ans
ans = ans._rescale(Etiny, context=context)
context._raise_error(Subnormal)
if context.flags[Inexact]:
context._raise_error(Underflow)
elif ans:
context._raise_error(Subnormal)
else:
Etop = context.Etop()
if (folddown and (ans._exp > Etop)):
context._raise_error(Clamped)
ans = ans._rescale(Etop, context=context)
else:
Emax = context.Emax
if (ans_adjusted > Emax):
if (not ans):
ans = Decimal(self)
ans._exp = Emax
context._raise_error(Clamped)
return ans
context._raise_error(Inexact)
context._raise_error(Rounded)
return context._raise_error(Overflow, 'above Emax', ans._sign)
return ans
|
'Returns a rounded version of self.
You can specify the precision or rounding method. Otherwise, the
context determines it.'
| def _round(self, prec=None, rounding=None, context=None):
| if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if self._isinfinity():
return Decimal(self)
if (context is None):
context = getcontext()
if (rounding is None):
rounding = context.rounding
if (prec is None):
prec = context.prec
if (not self):
if (prec <= 0):
dig = (0,)
exp = ((len(self._int) - prec) + self._exp)
else:
dig = ((0,) * prec)
exp = ((len(self._int) + self._exp) - prec)
ans = Decimal((self._sign, dig, exp))
context._raise_error(Rounded)
return ans
if (prec == 0):
temp = Decimal(self)
temp._int = ((0,) + temp._int)
prec = 1
elif (prec < 0):
exp = (((self._exp + len(self._int)) - prec) - 1)
temp = Decimal((self._sign, (0, 1), exp))
prec = 1
else:
temp = Decimal(self)
numdigits = len(temp._int)
if (prec == numdigits):
return temp
expdiff = (prec - numdigits)
if (expdiff > 0):
tmp = list(temp._int)
tmp.extend(([0] * expdiff))
ans = Decimal((temp._sign, tmp, (temp._exp - expdiff)))
return ans
lostdigits = self._int[expdiff:]
if (lostdigits == ((0,) * len(lostdigits))):
ans = Decimal((temp._sign, temp._int[:prec], (temp._exp - expdiff)))
context._raise_error(Rounded)
return ans
this_function = getattr(temp, self._pick_rounding_function[rounding])
if (prec != context.prec):
context = context._shallow_copy()
context.prec = prec
ans = this_function(prec, expdiff, context)
context._raise_error(Rounded)
context._raise_error(Inexact, 'Changed in rounding')
return ans
|
'Also known as round-towards-0, truncate.'
| def _round_down(self, prec, expdiff, context):
| return Decimal((self._sign, self._int[:prec], (self._exp - expdiff)))
|
'Rounds 5 up (away from 0)'
| def _round_half_up(self, prec, expdiff, context, tmp=None):
| if (tmp is None):
tmp = Decimal((self._sign, self._int[:prec], (self._exp - expdiff)))
if (self._int[prec] >= 5):
tmp = tmp._increment(round=0, context=context)
if (len(tmp._int) > prec):
return Decimal((tmp._sign, tmp._int[:(-1)], (tmp._exp + 1)))
return tmp
|
'Round 5 to even, rest to nearest.'
| def _round_half_even(self, prec, expdiff, context):
| tmp = Decimal((self._sign, self._int[:prec], (self._exp - expdiff)))
half = (self._int[prec] == 5)
if half:
for digit in self._int[(prec + 1):]:
if (digit != 0):
half = 0
break
if half:
if ((self._int[(prec - 1)] & 1) == 0):
return tmp
return self._round_half_up(prec, expdiff, context, tmp)
|
'Round 5 down'
| def _round_half_down(self, prec, expdiff, context):
| tmp = Decimal((self._sign, self._int[:prec], (self._exp - expdiff)))
half = (self._int[prec] == 5)
if half:
for digit in self._int[(prec + 1):]:
if (digit != 0):
half = 0
break
if half:
return tmp
return self._round_half_up(prec, expdiff, context, tmp)
|
'Rounds away from 0.'
| def _round_up(self, prec, expdiff, context):
| tmp = Decimal((self._sign, self._int[:prec], (self._exp - expdiff)))
for digit in self._int[prec:]:
if (digit != 0):
tmp = tmp._increment(round=1, context=context)
if (len(tmp._int) > prec):
return Decimal((tmp._sign, tmp._int[:(-1)], (tmp._exp + 1)))
else:
return tmp
return tmp
|
'Rounds up (not away from 0 if negative.)'
| def _round_ceiling(self, prec, expdiff, context):
| if self._sign:
return self._round_down(prec, expdiff, context)
else:
return self._round_up(prec, expdiff, context)
|
'Rounds down (not towards 0 if negative)'
| def _round_floor(self, prec, expdiff, context):
| if (not self._sign):
return self._round_down(prec, expdiff, context)
else:
return self._round_up(prec, expdiff, context)
|
'Return self ** n (mod modulo)
If modulo is None (default), don\'t take it mod modulo.'
| def __pow__(self, n, modulo=None, context=None):
| n = _convert_other(n)
if (context is None):
context = getcontext()
if (self._is_special or n._is_special or (n.adjusted() > 8)):
if (n._isinfinity() or (n.adjusted() > 8)):
return context._raise_error(InvalidOperation, 'x ** INF')
ans = self._check_nans(n, context)
if ans:
return ans
if (not n._isinteger()):
return context._raise_error(InvalidOperation, 'x ** (non-integer)')
if ((not self) and (not n)):
return context._raise_error(InvalidOperation, '0 ** 0')
if (not n):
return Decimal(1)
if (self == Decimal(1)):
return Decimal(1)
sign = (self._sign and (not n._iseven()))
n = int(n)
if self._isinfinity():
if modulo:
return context._raise_error(InvalidOperation, 'INF % x')
if (n > 0):
return Infsign[sign]
return Decimal((sign, (0,), 0))
if ((not modulo) and (n > 0) and ((((self._exp + len(self._int)) - 1) * n) > context.Emax) and self):
tmp = Decimal('inf')
tmp._sign = sign
context._raise_error(Rounded)
context._raise_error(Inexact)
context._raise_error(Overflow, 'Big power', sign)
return tmp
elength = len(str(abs(n)))
firstprec = context.prec
if ((not modulo) and (((firstprec + elength) + 1) > DefaultContext.Emax)):
return context._raise_error(Overflow, 'Too much precision.', sign)
mul = Decimal(self)
val = Decimal(1)
context = context._shallow_copy()
context.prec = ((firstprec + elength) + 1)
if (n < 0):
n = (- n)
mul = Decimal(1).__div__(mul, context=context)
spot = 1
while (spot <= n):
spot <<= 1
spot >>= 1
while spot:
val = val.__mul__(val, context=context)
if val._isinfinity():
val = Infsign[sign]
break
if (spot & n):
val = val.__mul__(mul, context=context)
if (modulo is not None):
val = val.__mod__(modulo, context=context)
spot >>= 1
context.prec = firstprec
if (context._rounding_decision == ALWAYS_ROUND):
return val._fix(context)
return val
|
'Swaps self/other and returns __pow__.'
| def __rpow__(self, other, context=None):
| other = _convert_other(other)
return other.__pow__(self, context=context)
|
'Normalize- strip trailing 0s, change anything equal to 0 to 0e0'
| def normalize(self, context=None):
| if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
dup = self._fix(context)
if dup._isinfinity():
return dup
if (not dup):
return Decimal((dup._sign, (0,), 0))
end = len(dup._int)
exp = dup._exp
while (dup._int[(end - 1)] == 0):
exp += 1
end -= 1
return Decimal((dup._sign, dup._int[:end], exp))
|
'Quantize self so its exponent is the same as that of exp.
Similar to self._rescale(exp._exp) but with error checking.'
| def quantize(self, exp, rounding=None, context=None, watchexp=1):
| if (self._is_special or exp._is_special):
ans = self._check_nans(exp, context)
if ans:
return ans
if (exp._isinfinity() or self._isinfinity()):
if (exp._isinfinity() and self._isinfinity()):
return self
if (context is None):
context = getcontext()
return context._raise_error(InvalidOperation, 'quantize with one INF')
return self._rescale(exp._exp, rounding, context, watchexp)
|
'Test whether self and other have the same exponent.
same as self._exp == other._exp, except NaN == sNaN'
| def same_quantum(self, other):
| if (self._is_special or other._is_special):
if (self._isnan() or other._isnan()):
return (self._isnan() and other._isnan() and True)
if (self._isinfinity() or other._isinfinity()):
return (self._isinfinity() and other._isinfinity() and True)
return (self._exp == other._exp)
|
'Rescales so that the exponent is exp.
exp = exp to scale to (an integer)
rounding = rounding version
watchexp: if set (default) an error is returned if exp is greater
than Emax or less than Etiny.'
| def _rescale(self, exp, rounding=None, context=None, watchexp=1):
| if (context is None):
context = getcontext()
if self._is_special:
if self._isinfinity():
return context._raise_error(InvalidOperation, 'rescale with an INF')
ans = self._check_nans(context=context)
if ans:
return ans
if (watchexp and ((context.Emax < exp) or (context.Etiny() > exp))):
return context._raise_error(InvalidOperation, 'rescale(a, INF)')
if (not self):
ans = Decimal(self)
ans._int = (0,)
ans._exp = exp
return ans
diff = (self._exp - exp)
digits = (len(self._int) + diff)
if (watchexp and (digits > context.prec)):
return context._raise_error(InvalidOperation, 'Rescale > prec')
tmp = Decimal(self)
tmp._int = ((0,) + tmp._int)
digits += 1
if (digits < 0):
tmp._exp = ((- digits) + tmp._exp)
tmp._int = (0, 1)
digits = 1
tmp = tmp._round(digits, rounding, context=context)
if ((tmp._int[0] == 0) and (len(tmp._int) > 1)):
tmp._int = tmp._int[1:]
tmp._exp = exp
tmp_adjusted = tmp.adjusted()
if (tmp and (tmp_adjusted < context.Emin)):
context._raise_error(Subnormal)
elif (tmp and (tmp_adjusted > context.Emax)):
return context._raise_error(InvalidOperation, 'rescale(a, INF)')
return tmp
|
'Rounds to the nearest integer, without raising inexact, rounded.'
| def to_integral(self, rounding=None, context=None):
| if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if (self._exp >= 0):
return self
if (context is None):
context = getcontext()
flags = context._ignore_flags(Rounded, Inexact)
ans = self._rescale(0, rounding, context=context)
context._regard_flags(flags)
return ans
|
'Return the square root of self.
Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
Should quadratically approach the right answer.'
| def sqrt(self, context=None):
| if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if (self._isinfinity() and (self._sign == 0)):
return Decimal(self)
if (not self):
exp = (self._exp // 2)
if (self._sign == 1):
return Decimal((1, (0,), exp))
else:
return Decimal((0, (0,), exp))
if (context is None):
context = getcontext()
if (self._sign == 1):
return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
tmp = Decimal(self)
expadd = (tmp._exp // 2)
if (tmp._exp & 1):
tmp._int += (0,)
tmp._exp = 0
else:
tmp._exp = 0
context = context._shallow_copy()
flags = context._ignore_all_flags()
firstprec = context.prec
context.prec = 3
if ((tmp.adjusted() & 1) == 0):
ans = Decimal((0, (8, 1, 9), (tmp.adjusted() - 2)))
ans = ans.__add__(tmp.__mul__(Decimal((0, (2, 5, 9), (-2))), context=context), context=context)
ans._exp -= (1 + (tmp.adjusted() // 2))
else:
ans = Decimal((0, (2, 5, 9), ((tmp._exp + len(tmp._int)) - 3)))
ans = ans.__add__(tmp.__mul__(Decimal((0, (8, 1, 9), (-3))), context=context), context=context)
ans._exp -= (1 + (tmp.adjusted() // 2))
(Emax, Emin) = (context.Emax, context.Emin)
(context.Emax, context.Emin) = (DefaultContext.Emax, DefaultContext.Emin)
half = Decimal('0.5')
maxp = (firstprec + 2)
rounding = context._set_rounding(ROUND_HALF_EVEN)
while 1:
context.prec = min(((2 * context.prec) - 2), maxp)
ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context), context=context), context=context)
if (context.prec == maxp):
break
context.prec = firstprec
prevexp = ans.adjusted()
ans = ans._round(context=context)
context.prec = (firstprec + 1)
if (prevexp != ans.adjusted()):
ans._int += (0,)
ans._exp -= 1
lower = ans.__sub__(Decimal((0, (5,), (ans._exp - 1))), context=context)
context._set_rounding(ROUND_UP)
if (lower.__mul__(lower, context=context) > tmp):
ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context)
else:
upper = ans.__add__(Decimal((0, (5,), (ans._exp - 1))), context=context)
context._set_rounding(ROUND_DOWN)
if (upper.__mul__(upper, context=context) < tmp):
ans = ans.__add__(Decimal((0, (1,), ans._exp)), context=context)
ans._exp += expadd
context.prec = firstprec
context.rounding = rounding
ans = ans._fix(context)
rounding = context._set_rounding_decision(NEVER_ROUND)
if (not (ans.__mul__(ans, context=context) == self)):
context._regard_flags(flags)
context._raise_error(Rounded)
context._raise_error(Inexact)
else:
exp = (self._exp // 2)
context.prec += (ans._exp - exp)
ans = ans._rescale(exp, context=context)
context.prec = firstprec
context._regard_flags(flags)
(context.Emax, context.Emin) = (Emax, Emin)
return ans._fix(context)
|
'Returns the larger value.
like max(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN). Also rounds.'
| def max(self, other, context=None):
| other = _convert_other(other)
if (self._is_special or other._is_special):
sn = self._isnan()
on = other._isnan()
if (sn or on):
if ((on == 1) and (sn != 2)):
return self
if ((sn == 1) and (on != 2)):
return other
return self._check_nans(other, context)
ans = self
c = self.__cmp__(other)
if (c == 0):
if (self._sign != other._sign):
if self._sign:
ans = other
elif ((self._exp < other._exp) and (not self._sign)):
ans = other
elif ((self._exp > other._exp) and self._sign):
ans = other
elif (c == (-1)):
ans = other
if (context is None):
context = getcontext()
if (context._rounding_decision == ALWAYS_ROUND):
return ans._fix(context)
return ans
|
'Returns the smaller value.
like min(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN). Also rounds.'
| def min(self, other, context=None):
| other = _convert_other(other)
if (self._is_special or other._is_special):
sn = self._isnan()
on = other._isnan()
if (sn or on):
if ((on == 1) and (sn != 2)):
return self
if ((sn == 1) and (on != 2)):
return other
return self._check_nans(other, context)
ans = self
c = self.__cmp__(other)
if (c == 0):
if (self._sign != other._sign):
if other._sign:
ans = other
elif ((self._exp > other._exp) and (not self._sign)):
ans = other
elif ((self._exp < other._exp) and self._sign):
ans = other
elif (c == 1):
ans = other
if (context is None):
context = getcontext()
if (context._rounding_decision == ALWAYS_ROUND):
return ans._fix(context)
return ans
|
'Returns whether self is an integer'
| def _isinteger(self):
| if (self._exp >= 0):
return True
rest = self._int[self._exp:]
return (rest == ((0,) * len(rest)))
|
'Returns 1 if self is even. Assumes self is an integer.'
| def _iseven(self):
| if (self._exp > 0):
return 1
return ((self._int[((-1) + self._exp)] & 1) == 0)
|
'Return the adjusted exponent of self'
| def adjusted(self):
| try:
return ((self._exp + len(self._int)) - 1)
except TypeError:
return 0
|
'Show the current context.'
| def __repr__(self):
| s = []
s.append(('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self)))
s.append((('flags=[' + ', '.join([f.__name__ for (f, v) in self.flags.items() if v])) + ']'))
s.append((('traps=[' + ', '.join([t.__name__ for (t, v) in self.traps.items() if v])) + ']'))
return (', '.join(s) + ')')
|
'Reset all flags to zero'
| def clear_flags(self):
| for flag in self.flags:
self.flags[flag] = 0
|
'Returns a shallow copy from self.'
| def _shallow_copy(self):
| nc = Context(self.prec, self.rounding, self.traps, self.flags, self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
return nc
|
'Returns a deep copy from self.'
| def copy(self):
| nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
return nc
|
'Handles an error
If the flag is in _ignored_flags, returns the default response.
Otherwise, it increments the flag, then, if the corresponding
trap_enabler is set, it reaises the exception. Otherwise, it returns
the default value after incrementing the flag.'
| def _raise_error(self, condition, explanation=None, *args):
| error = _condition_map.get(condition, condition)
if (error in self._ignored_flags):
return error().handle(self, *args)
self.flags[error] += 1
if (not self.traps[error]):
return condition().handle(self, *args)
raise error, explanation
|
'Ignore all flags, if they are raised'
| def _ignore_all_flags(self):
| return self._ignore_flags(*_signals)
|
'Ignore the flags, if they are raised'
| def _ignore_flags(self, *flags):
| self._ignored_flags = (self._ignored_flags + list(flags))
return list(flags)
|
'Stop ignoring the flags, if they are raised'
| def _regard_flags(self, *flags):
| if (flags and isinstance(flags[0], (tuple, list))):
flags = flags[0]
for flag in flags:
self._ignored_flags.remove(flag)
|
'A Context cannot be hashed.'
| def __hash__(self):
| raise TypeError, 'Cannot hash a Context.'
|
'Returns Etiny (= Emin - prec + 1)'
| def Etiny(self):
| return int(((self.Emin - self.prec) + 1))
|
'Returns maximum exponent (= Emax - prec + 1)'
| def Etop(self):
| return int(((self.Emax - self.prec) + 1))
|
'Sets the rounding decision.
Sets the rounding decision, and returns the current (previous)
rounding decision. Often used like:
context = context._shallow_copy()
# That so you don\'t change the calling context
# if an error occurs in the middle (say DivisionImpossible is raised).
rounding = context._set_rounding_decision(NEVER_ROUND)
instance = instance / Decimal(2)
context._set_rounding_decision(rounding)
This will make it not round for that operation.'
| def _set_rounding_decision(self, type):
| rounding = self._rounding_decision
self._rounding_decision = type
return rounding
|
'Sets the rounding type.
Sets the rounding type, and returns the current (previous)
rounding type. Often used like:
context = context.copy()
# so you don\'t change the calling context
# if an error occurs in the middle.
rounding = context._set_rounding(ROUND_UP)
val = self.__sub__(other, context=context)
context._set_rounding(rounding)
This will make it round up for that operation.'
| def _set_rounding(self, type):
| rounding = self.rounding
self.rounding = type
return rounding
|
'Creates a new Decimal instance but using self as context.'
| def create_decimal(self, num='0'):
| d = Decimal(num, context=self)
return d._fix(self)
|
'Returns the absolute value of the operand.
If the operand is negative, the result is the same as using the minus
operation on the operand. Otherwise, the result is the same as using
the plus operation on the operand.
>>> ExtendedContext.abs(Decimal(\'2.1\'))
Decimal("2.1")
>>> ExtendedContext.abs(Decimal(\'-100\'))
Decimal("100")
>>> ExtendedContext.abs(Decimal(\'101.5\'))
Decimal("101.5")
>>> ExtendedContext.abs(Decimal(\'-101.5\'))
Decimal("101.5")'
| def abs(self, a):
| return a.__abs__(context=self)
|
'Return the sum of the two operands.
>>> ExtendedContext.add(Decimal(\'12\'), Decimal(\'7.00\'))
Decimal("19.00")
>>> ExtendedContext.add(Decimal(\'1E+2\'), Decimal(\'1.01E+4\'))
Decimal("1.02E+4")'
| def add(self, a, b):
| return a.__add__(b, context=self)
|
'Compares values numerically.
If the signs of the operands differ, a value representing each operand
(\'-1\' if the operand is less than zero, \'0\' if the operand is zero or
negative zero, or \'1\' if the operand is greater than zero) is used in
place of that operand for the comparison instead of the actual
operand.
The comparison is then effected by subtracting the second operand from
the first and then returning a value according to the result of the
subtraction: \'-1\' if the result is less than zero, \'0\' if the result is
zero or negative zero, or \'1\' if the result is greater than zero.
>>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'3\'))
Decimal("-1")
>>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'2.1\'))
Decimal("0")
>>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'2.10\'))
Decimal("0")
>>> ExtendedContext.compare(Decimal(\'3\'), Decimal(\'2.1\'))
Decimal("1")
>>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'-3\'))
Decimal("1")
>>> ExtendedContext.compare(Decimal(\'-3\'), Decimal(\'2.1\'))
Decimal("-1")'
| def compare(self, a, b):
| return a.compare(b, context=self)
|
'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")'
| def divide(self, a, b):
| return a.__div__(b, context=self)
|
'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")'
| def divide_int(self, a, b):
| return a.__floordiv__(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 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")'
| def max(self, a, b):
| return a.max(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 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")'
| def min(self, a, b):
| return a.min(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")'
| def minus(self, a):
| 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")'
| def multiply(self, a, b):
| return a.__mul__(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")'
| def normalize(self, a):
| return a.normalize(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")'
| def plus(self, a):
| return a.__pos__(context=self)
|
'Raises a to the power of b, to modulo if given.
The right-hand operand must be a whole number whose integer part (after
any exponent has been applied) has no more than 9 digits and whose
fractional part (if any) is all zeros before any rounding. The operand
may be positive, negative, or zero; if negative, the absolute value of
the power is used, and the left-hand operand is inverted (divided into
1) before use.
If the increased precision needed for the intermediate calculations
exceeds the capabilities of the implementation then an Invalid operation
condition is raised.
If, when raising to a negative power, an underflow occurs during the
division into 1, the operation is not halted at that point but
continues.
>>> ExtendedContext.power(Decimal(\'2\'), Decimal(\'3\'))
Decimal("8")
>>> ExtendedContext.power(Decimal(\'2\'), Decimal(\'-3\'))
Decimal("0.125")
>>> ExtendedContext.power(Decimal(\'1.7\'), Decimal(\'8\'))
Decimal("69.7575744")
>>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'-2\'))
Decimal("0")
>>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'-1\'))
Decimal("0")
>>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'0\'))
Decimal("1")
>>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'1\'))
Decimal("Infinity")
>>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'2\'))
Decimal("Infinity")
>>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'-2\'))
Decimal("0")
>>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'-1\'))
Decimal("-0")
>>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'0\'))
Decimal("1")
>>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'1\'))
Decimal("-Infinity")
>>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'2\'))
Decimal("Infinity")
>>> ExtendedContext.power(Decimal(\'0\'), Decimal(\'0\'))
Decimal("NaN")'
| def power(self, a, b, modulo=None):
| return a.__pow__(b, modulo, context=self)
|
'Returns a value equal to \'a\' (rounded) and 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")'
| def quantize(self, a, b):
| return a.quantize(b, context=self)
|
'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")'
| def remainder(self, a, b):
| return a.__mod__(b, context=self)
|
'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")'
| def remainder_near(self, a, b):
| return a.remainder_near(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'
| def same_quantum(self, a, b):
| return a.same_quantum(b)
|
'Returns the 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.prec
9'
| def sqrt(self, a):
| return a.sqrt(context=self)
|
'Return the sum of 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")'
| def subtract(self, a, b):
| return a.__sub__(b, context=self)
|
'Converts a number to a string, using scientific notation.
The operation is not affected by the context.'
| def to_eng_string(self, a):
| 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):
| 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, except that no flags will
be set. The rounding mode is taken from the context.
>>> ExtendedContext.to_integral(Decimal(\'2.1\'))
Decimal("2")
>>> ExtendedContext.to_integral(Decimal(\'100\'))
Decimal("100")
>>> ExtendedContext.to_integral(Decimal(\'100.0\'))
Decimal("100")
>>> ExtendedContext.to_integral(Decimal(\'101.5\'))
Decimal("102")
>>> ExtendedContext.to_integral(Decimal(\'-101.5\'))
Decimal("-102")
>>> ExtendedContext.to_integral(Decimal(\'10E+5\'))
Decimal("1.0E+6")
>>> ExtendedContext.to_integral(Decimal(\'7.89E+77\'))
Decimal("7.89E+77")
>>> ExtendedContext.to_integral(Decimal(\'-Inf\'))
Decimal("-Infinity")'
| def to_integral(self, a):
| return a.to_integral(context=self)
|
'Creates multiple threads using simple (but slower) marshalling.
Single interpreter object, but a new stream is created per thread.
Returns the handles the threads will set when complete.'
| def BeginThreadsSimpleMarshal(self, numThreads):
| interp = win32com.client.Dispatch('Python.Interpreter')
events = []
threads = []
for i in range(numThreads):
hEvent = win32event.CreateEvent(None, 0, 0, None)
events.append(hEvent)
interpStream = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, interp._oleobj_)
t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interpStream))
t.setDaemon(1)
t.start()
threads.append(t)
interp = None
return (threads, events)
|
'Creates multiple threads using fast (but complex) marshalling.
The marshal stream is created once, and each thread uses the same stream
Returns the handles the threads will set when complete.'
| def BeginThreadsFastMarshal(self, numThreads):
| interp = win32com.client.Dispatch('Python.Interpreter')
if freeThreaded:
interp = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, interp._oleobj_)
events = []
threads = []
for i in range(numThreads):
hEvent = win32event.CreateEvent(None, 0, 0, None)
t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interp))
t.setDaemon(1)
t.start()
events.append(hEvent)
threads.append(t)
return (threads, events)
|
'Initialize an exception
**Params**
description -- A string description for the exception.
scode -- An integer scode to be returned to the server, if necessary.
The pythoncom framework defaults this to be DISP_E_EXCEPTION if not specified otherwise.
source -- A string which identifies the source of the error.
helpfile -- A string which points to a help file which contains details on the error.
helpContext -- An integer context in the help file.
desc -- A short-cut for description.
hresult -- A short-cut for scode.'
| def __init__(self, description=None, scode=None, source=None, helpfile=None, helpContext=None, desc=None, hresult=None):
| scode = (scode or hresult)
if (scode and (scode != 1)):
if ((scode >= (-32768)) and (scode < 32768)):
scode = ((-2147024896) | (scode & 65535))
self.scode = scode
self.description = (description or desc)
if ((scode == 1) and (not self.description)):
self.description = 'S_FALSE'
elif (scode and (not self.description)):
self.description = pythoncom.GetScodeString(scode)
self.source = source
self.helpfile = helpfile
self.helpcontext = helpContext
pythoncom.com_error.__init__(self, scode, self.description, None, (-1))
|
'Called whenever an exception is raised.
Default behaviour is to print the exception.'
| def _HandleException_(self):
| if (not IsCOMServerException()):
if (self.logger is not None):
self.logger.exception('pythoncom server error')
else:
traceback.print_exc()
raise
|
'Invoke the debugger post mortem capability'
| def _HandleException_(self):
| (typ, val, tb) = exc_info()
debug = 0
try:
raise typ(val)
except Exception:
debug = pywin.debugger.GetDebugger().get_option(pywin.debugger.dbgcon.OPT_STOP_EXCEPTIONS)
except:
debug = 1
if debug:
try:
pywin.debugger.post_mortem(tb, typ, val)
except:
traceback.print_exc()
del tb
raise
|
'Initialise the policy object
Params:
object -- The object to wrap. May be None *iff* @BasicWrapPolicy._CreateInstance_@ will be
called immediately after this to setup a brand new object'
| def __init__(self, object):
| if (object is not None):
self._wrap_(object)
|
'Creates a new instance of a **wrapped** object
This method looks up a "@win32com.server.policy.regSpec@" % clsid entry
in the registry (using @DefaultPolicy@)'
| def _CreateInstance_(self, clsid, reqIID):
| try:
classSpec = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, (regSpec % clsid))
except win32api.error:
raise error(('The object is not correctly registered - %s key can not be read' % (regSpec % clsid)))
myob = call_func(classSpec)
self._wrap_(myob)
try:
return pythoncom.WrapObject(self, reqIID)
except pythoncom.com_error as (hr, desc, exc, arg):
from win32com.util import IIDToInterfaceName
desc = ("The object '%r' was created, but does not support the interface '%s'(%s): %s" % (myob, IIDToInterfaceName(reqIID), reqIID, desc))
raise pythoncom.com_error(hr, desc, exc, arg)
|
'Wraps up the specified object.
This function keeps a reference to the passed
object, and may interogate it to determine how to respond to COM requests, etc.'
| def _wrap_(self, object):
| self._name_to_dispid_ = {}
ob = self._obj_ = object
if hasattr(ob, '_query_interface_'):
self._query_interface_ = ob._query_interface_
if hasattr(ob, '_invoke_'):
self._invoke_ = ob._invoke_
if hasattr(ob, '_invokeex_'):
self._invokeex_ = ob._invokeex_
if hasattr(ob, '_getidsofnames_'):
self._getidsofnames_ = ob._getidsofnames_
if hasattr(ob, '_getdispid_'):
self._getdispid_ = ob._getdispid_
if hasattr(ob, '_com_interfaces_'):
self._com_interfaces_ = []
for i in ob._com_interfaces_:
if (type(i) != pywintypes.IIDType):
if (i[0] != '{'):
i = pythoncom.InterfaceNames[i]
else:
i = pythoncom.MakeIID(i)
self._com_interfaces_.append(i)
else:
self._com_interfaces_ = []
|
'The main COM entry-point for QueryInterface.
This checks the _com_interfaces_ attribute and if the interface is not specified
there, it calls the derived helper _query_interface_'
| def _QueryInterface_(self, iid):
| if (iid in self._com_interfaces_):
return 1
return self._query_interface_(iid)
|
'Called if the object does not provide the requested interface in _com_interfaces,
and does not provide a _query_interface_ handler.
Returns a result to the COM framework indicating the interface is not supported.'
| def _query_interface_(self, iid):
| return 0
|
'The main COM entry-point for Invoke.
This calls the _invoke_ helper.'
| def _Invoke_(self, dispid, lcid, wFlags, args):
| if (type(dispid) == type('')):
try:
dispid = self._name_to_dispid_[dispid.lower()]
except KeyError:
raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND, desc='Member not found')
return self._invoke_(dispid, lcid, wFlags, args)
|
'The main COM entry-point for GetIDsOfNames.
This checks the validity of the arguments, and calls the _getidsofnames_ helper.'
| def _GetIDsOfNames_(self, names, lcid):
| if (len(names) > 1):
raise COMException(scode=winerror.DISP_E_INVALID, desc='Cannot support member argument names')
return self._getidsofnames_(names, lcid)
|
'The main COM entry-point for InvokeEx.
This calls the _invokeex_ helper.'
| def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
| if (type(dispid) == type('')):
try:
dispid = self._name_to_dispid_[dispid.lower()]
except KeyError:
raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND, desc='Member not found')
return self._invokeex_(dispid, lcid, wFlags, args, kwargs, serviceProvider)
|
'A stub for _invokeex_ - should never be called.
Simply raises an exception.'
| def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
| raise error('This class does not provide _invokeex_ semantics')
|
'Constructor'
| def __init__(self):
| super(ExcelRTDServer, self).__init__()
self.IsAlive = self.ALIVE
self.__callback = None
self.topics = {}
|
'Use the callback we were given to tell excel new data is available.'
| def SignalExcel(self):
| if (self.__callback is None):
raise COMException(desc='Callback excel provided is Null')
self.__callback.UpdateNotify()
|
'Creates a new topic out of the Strings excel gives us.'
| def ConnectData(self, TopicID, Strings, GetNewValues):
| try:
self.topics[TopicID] = self.CreateTopic(Strings)
except Exception as why:
raise COMException(desc=str(why))
GetNewValues = True
result = self.topics[TopicID]
if (result is None):
result = ('# %s: Waiting for update' % self.__class__.__name__)
else:
result = result.GetValue()
self.OnConnectData(TopicID)
return (result, GetNewValues)
|
'Deletes the given topic.'
| def DisconnectData(self, TopicID):
| self.OnDisconnectData(TopicID)
if (TopicID in self.topics):
self.topics[TopicID] = None
del self.topics[TopicID]
|
'Called by excel to see if we\'re still here.'
| def Heartbeat(self):
| return self.IsAlive
|
'Packs up the topic values. Called by excel when it\'s ready for an update.
Needs to:
* Return the current number of topics, via the "ByRef" TopicCount
* Return a 2d SafeArray of the topic data.
- 1st dim: topic numbers
- 2nd dim: topic values
We could do some caching, instead of repacking everytime...
But this works for demonstration purposes.'
| def RefreshData(self, TopicCount):
| TopicCount = len(self.topics)
self.OnRefreshData()
results = [([None] * TopicCount), ([None] * TopicCount)]
for (idx, topicdata) in enumerate(self.topics.iteritems()):
(topicNum, topic) = topicdata
results[0][idx] = topicNum
results[1][idx] = topic.GetValue()
return (tuple(results), TopicCount)
|
'Excel has just created us... We take its callback for later, and set up shop.'
| def ServerStart(self, CallbackObject):
| self.IsAlive = self.ALIVE
if (CallbackObject is None):
raise COMException(desc='Excel did not provide a callback')
IRTDUpdateEventKlass = win32com.client.CLSIDToClass.GetClass('{A43788C1-D91B-11D3-8F39-00C04F3651B8}')
self.__callback = IRTDUpdateEventKlass(CallbackObject)
self.OnServerStart()
return self.IsAlive
|
'Called when excel no longer wants us.'
| def ServerTerminate(self):
| self.IsAlive = self.NOT_ALIVE
self.OnServerTerminate()
|
'Topic factory method. Subclass must override.
Topic objects need to provide:
* GetValue() method which returns an atomic value.
Will raise NotImplemented if not overridden.'
| def CreateTopic(self, TopicStrings=None):
| raise NotImplemented('Subclass must implement')
|
'Called when a new topic has been created, at excel\'s request.'
| def OnConnectData(self, TopicID):
| pass
|
'Called when a topic is about to be deleted, at excel\'s request.'
| def OnDisconnectData(self, TopicID):
| pass
|
'Called when excel has requested all current topic data.'
| def OnRefreshData(self):
| pass
|
'Called when excel has instanciated us.'
| def OnServerStart(self):
| pass
|
'Called when excel is about to destroy us.'
| def OnServerTerminate(self):
| pass
|
'Called by the RTD Server.
Gives us a chance to check if our topic data needs to be
changed (eg. check a file, quiz a database, etc).'
| def Update(self, sender):
| raise NotImplemented('subclass must implement')
|
'Call when this topic isn\'t considered "dirty" anymore.'
| def Reset(self):
| self.__dirty = False
|
'Topic factory. Builds a TimeTopic object out of the given TopicStrings.'
| def CreateTopic(self, TopicStrings=None):
| return TimeTopic(TopicStrings)
|
'Given the indirection level I was declared at (0=Normal, 1=*, 2=**)
return a string prefix so I can pass to a function with the
required indirection (where the default is the indirection of the method\'s param.
eg, assuming my arg has indirection level of 2, if this function was passed 1
it would return "&", so that a variable declared with indirection of 1
can be prefixed with this to turn it into the indirection level required of 2'
| def _IndirectPrefix(self, indirectionFrom, indirectionTo):
| dif = (indirectionFrom - indirectionTo)
if (dif == 0):
return ''
elif (dif == (-1)):
return '&'
elif (dif == 1):
return '*'
else:
return ('?? (%d)' % (dif,))
raise error_not_supported("Can't indirect this far - please fix me :-)")
|
'Get the argument to be passes to Py_BuildValue'
| def GetBuildValueArg(self):
| return self.arg.name
|
'Get the argument to be passed to PyArg_ParseTuple'
| def GetParseTupleArg(self):
| if self.gatewayMode:
return self.GetIndirectedArgName(None, 1)
return self.GetIndirectedArgName(self.builtinIndirection, 1)
|
'Provide information about the C++ object used.
Simple variables (such as integers) can declare their type (eg an integer)
and use it as the target of both PyArg_ParseTuple and the COM function itself.
More complex types require a PyObject * declared as the target of PyArg_ParseTuple,
then some conversion routine to the C++ object which is actually passed to COM.
This method provides the name, and optionally the type of that C++ variable.
If the type if provided, the caller will likely generate a variable declaration.
The name must always be returned.
Result is a tuple of (variableName, [DeclareType|None|""])'
| def GetInterfaceCppObjectInfo(self):
| return (self.GetIndirectedArgName(self.builtinIndirection, (self.arg.indirectionLevel + self.builtinIndirection)), ('%s %s' % (self.GetUnconstType(), self.arg.name)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.