Пример #1
0
    def calculate_amount(self):
        """
        Calculate total amount for deal.
        :return:
        """
        settings = self.kiosk_start.settings

        if self.deal_type_id == 1:
            # Rent
            # Use localcontext(BasicContext) for proper rounding of decimal
            # numbers
            with localcontext(BasicContext):

                tax_rate = settings.rent_tax_rate / Decimal('100.0')

                max_total = self.kiosk_start.settings.sale_convert_price

                # First night value
                fn_val = self.get_first_night()
                # Next night value
                fn_val = Decimal(fn_val)
                nn_val = Decimal(self.tariff_value.next_night)

                days_rent = Decimal(self.total_days) - 1

                sub_total = fn_val + days_rent * nn_val

                sub_total_with_discount = sub_total - self.discount

                if sub_total_with_discount > max_total:
                    total = max_total
                    taxes = tax_rate * max_total
                else:
                    total = sub_total_with_discount
                    taxes = tax_rate * sub_total_with_discount

                self.tariff_charge = total.quantize(Decimal('0.01'))

                self.taxes = taxes.quantize(Decimal('0.01'))

                total_charge = self.tariff_charge + self.taxes
                total_charge = float(total_charge)

            return total_charge

        elif self.deal_type_id == 2:
            # Sale
            with localcontext(BasicContext):
                tax_rate = Decimal(settings.sale_tax_rate) / Decimal('100.0')

                sale_tariff = Decimal(self.tariff_value.sale)

                self.taxes = (tax_rate * sale_tariff).quantize(Decimal('0.01'))

                total = (sale_tariff + self.taxes).quantize(Decimal('0.01'))

            return float(total)
        else:
            # OverRent
            return -1
Пример #2
0
    def _pi(n, M, AN, oldpi=0, i=0):

        # Area of 2N-polygon = radius * N-polygon semiperimeter
        A2N = radius * M * n # r * (2*M) * (n/2)

        lbound = A2N / radius**2
        ubound = (2 * A2N - AN) / radius**2 # A2N + (A2N - AN)

        pi = (lbound * 2 + ubound) / 3

        _print_pi_inequal(i,n, lbound, ubound, pi)

        with localcontext() as ctx:
            ctx.prec = precision
            if +pi == +oldpi:
                return pi

        # next polygon edge
        # G == apothem, M == edge/2, j == r - G
        # solving for m = next edge = new 2M, using right triangles GrM and jmM
        # http://en.wikipedia.org/wiki/File:Liuhui_geyuanshu.svg
        with localcontext() as ctx:
            ctx.prec = getcontext().prec * 2 # boost precision for sqrt
            m = (2 * radius * (radius - (radius**2 - M**2).sqrt())).sqrt()

        return _pi(n*2, m/2, A2N, pi, i+1)
Пример #3
0
    def assertDecimalEqual(self, result, expected, msg=None):
        """
        @param result:
        @type result:
        @param expected:
        @type expected:
        @param msg:
        @type msg:
        @return:
        @rtype:
        """

        from decimal import localcontext

        with localcontext() as ctx:
            ctx.prec = 3  # not testing decimal precision atm
            res = +result
            exp = +expected

            cmp = res == exp

        if not cmp:
            if msg is None:
                msg = ''

            msg += "Decimals do not match: %.3f != %.3f" % (res, exp)
            raise self.failureException(msg)
Пример #4
0
def _divide(num, den):
    """Return num/div without raising unnecessary exceptions.

    >>> _divide(1, 0)
    inf
    >>> from decimal import Decimal
    >>> _divide(Decimal(0), 0)
    Decimal('NaN')

    """
    try:
        return num/den
    except (decimal.DivisionByZero, decimal.InvalidOperation):
        # num and den could be NANs, INFs, or den == 0. The easiest way
        # to handle all the cases is just do the division again.
        with decimal.localcontext() as ctx:
            ctx.traps[decimal.DivisionByZero] = 0
            ctx.traps[decimal.InvalidOperation] = 0
            return num/den
    except ZeroDivisionError:
        assert den == 0  # Division by NAN or INF is handled okay.
        assert not math.isnan(num)  # NAN/x will not raise Zero
        if num == 0:
            return float('nan')
        else:
            result = math.copysign(float('inf'), den)  # Support signed zero.
            if num < 0:
                result = -result
            return result
Пример #5
0
 def wiener(self,public):
     q=self.eea(public[0],public[1])[3]  ##get continuous fraction
     print "Wiener Attack for:"      
     print "e:",public[0]
     print "n:",public[1]
     conv=[]                             ##start a list with convergent fractions
     for i in range(0,len(q)):
         if i==0:
             alfa=q[0]
             betta=1
         elif i==1:
             alfa=q[0]*q[1]+1            ##generate the fractions
             betta=q[1]
         else:
             alfa= q[i]*conv[i-1][0]+conv[i-2][0]
             betta=q[i]*conv[i-1][1]+conv[i-2][1]
         
         if alfa!=0:                     ##calculate the roots of the ecuation
             with decimal.localcontext() as ctx:
                 ctx.prec = 2048
                 euler=decimal.Decimal((public[0]*betta-1)/alfa)
                 b=public[1]-euler+1
                 disc=decimal.Decimal(b**2-4*public[1])
                 if disc>=0:
                     sqrdt=disc.sqrt()
                     if sqrdt.to_integral()==sqrdt:
                         x=decimal.Decimal((b-sqrdt)/2)
                         y=decimal.Decimal((b+sqrdt)/2)
                         if x.to_integral()==x and y.to_integral()==y:
                             if x*y==public[1]:      ##if the roots are integers and they are factors of "n" return
                                 return long(x),long(y)                
         conv.append((alfa,betta))
     return (0,0)    ##if no solution was found return (0,0)
Пример #6
0
def _read_decimal(data, size, writer_schema):
    """
    based on https://github.com/apache/avro/pull/82/
    """
    scale = writer_schema.get('scale', 0)
    precision = writer_schema['precision']

    datum_byte = str2ints(data)

    unscaled_datum = 0
    msb = fstint(data)
    leftmost_bit = (msb >> 7) & 1
    if leftmost_bit == 1:
        modified_first_byte = datum_byte[0] ^ (1 << 7)
        datum_byte = [modified_first_byte] + datum_byte[1:]
        for offset in xrange(size):
            unscaled_datum <<= 8
            unscaled_datum += datum_byte[offset]
        unscaled_datum += pow(-2, (size * 8) - 1)
    else:
        for offset in xrange(size):
            unscaled_datum <<= 8
            unscaled_datum += (datum_byte[offset])

    with localcontext() as ctx:
        ctx.prec = precision
        scaled_datum = Decimal(unscaled_datum).scaleb(-scale)
    return scaled_datum
Пример #7
0
 async def fractions(t, precision, x, y):
     with decimal.localcontext() as ctx:
         ctx.prec = precision
         a = decimal.Decimal(x) / decimal.Decimal(y)
         await asyncio.sleep(t)
         b = decimal.Decimal(x) / decimal.Decimal(y ** 2)
         return a, b
Пример #8
0
def LeibnizPi():
    with localcontext() as ctx:
        # Don't change precision! Leibniz is *painfully* slow.
        # 500K iterations for precision 6 (4 correct digits)
        ctx.prec = 5
        ctx_double = C(prec=ctx.prec + 2)

        pi = D(4)
        denominator = 3
        numerator = 4
        oldpi = i = 0

        while +pi != oldpi:
            oldpi = pi
            numerator = -numerator;
            pi = pi + ctx_double.divide(numerator, denominator)
            denominator = denominator + 2;
            i+=1


        print("")
        print("Leibniz")
        print (("{i}: pi {p}  {pi}").format(i=i,
                                            pi=pi,
                                            p=ctx.prec-1))
        return pi
Пример #9
0
def split_amount(amount, splits, places=2):
    """Return list of ``splits`` amounts where sum of items equals ``amount``.

    >>> from decimal import Decimal
    >>> split_amount(Decimal('12'), 1)
    Decimal('12.00')
    >>> split_amount(Decimal('12'), 2)
    [Decimal('6.00'), Decimal('6.00')]

    Amounts have a max of ``places`` decimal places. Last amount in the list
    may not be the same as others (will always be lower than or equal to
    others).

    >>> split_amount(Decimal('100'), 3)
    [Decimal('33,34'), Decimal('33,34'), Decimal('33,32')]
    >>> split_amount(Decimal('100'), 3, 4)
    [Decimal('33,3334'), Decimal('33,3334'), Decimal('33,3332')]
    >>> split_amount(Decimal('12'), 7)  # Doctest: +ELLIPSIS
    [Decimal('1.72'), ..., Decimal('1.72'), ..., Decimal('1.68')]
    >>> split_amount(Decimal('12'), 17)  # Doctest: +ELLIPSIS
    [Decimal('0.71'), ..., Decimal('0.71'), Decimal('0.64')]

    """
    one = decimal.Decimal(10) ** -places
    amount = amount.quantize(one)
    with decimal.localcontext() as decimal_context:
        decimal_context.rounding = decimal.ROUND_UP
        upper_split = (amount / splits).quantize(one)
    splitted_amounts = [upper_split] * (splits - 1)
    lower_split = amount - sum(splitted_amounts)
    splitted_amounts.append(lower_split)
    return splitted_amounts
Пример #10
0
 def _getSSInt96_(dec):
     dec_tuple = dec.as_tuple()
     digits = dec_tuple[1]
     allLen = len(digits)
     if allLen > 28:
         with localcontext() as ctx:
             ctx.prec = 28
             dec = dec/1
             dec_tuple = dec.as_tuple()
             digits = dec_tuple[1]
             allLen = len(digits)
     sign = 0
     if dec.is_signed():
         sign = 0x80
     scale = dec_tuple[2]
     if scale < 0:
         scale = -scale
     else:
         scale = 0
     s = str(dec)
     if sign:
         s = s[1:]
     if scale:
         pot = s.index('.')
         s = s[:pot] + s[pot+1:]
     from spa import isVersion3
     if isVersion3:
         return (sign, scale, int(s))
     else:
         return (sign, scale, long(s))
Пример #11
0
    def __new__(cls, value=_void):
        cumulative, last_increment = fpdecimal.CascadedContext.get()
        context = fpdecimal.CascadedContext.apply(
            cls.__sx_decimal_metadata__.decimal_context)

        if value is _void:
            value = cls.default()

        if value is None:
            value = 0

        if cumulative.scale is not None:
            fpcontext = cumulative
        else:
            scale = cls.__sx_decimal_metadata__.decimal_scale
            quantize_exponent = cls.__sx_decimal_metadata__.quantize_exponent
            fpcontext = fpdecimal.CascadedContext(
                scale=scale, quantize_exponent=quantize_exponent)

        try:
            with decimal.localcontext(context), fpcontext:
                result = fpdecimal.FPDecimal.__new__(cls, value)
        except (ValueError, decimal.InvalidOperation) as e:
            raise edgedb_error.ScalarTypeValueError(e.args[0]) from e

        return result
Пример #12
0
    def writeWin(self):
        """Write the current reception info to the window"""
        self.__logger.debug("system: %s", self.reception.sys_id)

# Compute the static information string once and cache it
        if not hasattr(self.reception, 'infocache'):
# Compute the frequency or 'NaN'
            with decimal.localcontext() as lctx:
                lctx.traps[decimal.InvalidOperation] = False
                frq = decimal.Decimal(self.reception.Frequency_TGID)

# Compute the 'lastseen' display value (HH:MM:SS)
            if self.reception.lastseen:
                d = self.reception.Starttime - self.reception.lastseen
                lastseen = str(timedelta(d.days, d.seconds, 0))
            else:
                lastseen = '*Forever'
            self.reception.infocache = \
                "{time:s}: Sys={sys:.<16s}|Grp={grp:.<16s}|Chan={chn:.<16s}|Freq={frq:#9.4f}|C/D={ctc:>3s} last={last:>8s}". \
                    format(time=self.reception.Starttime.strftime(GLGMonitor._TIMEFMT),
                        sys=self.reception.System,
                        grp=self.reception.Group,
                        chn=self.reception.Channel,
                        frq=frq,
                        ctc=self.reception.CTCSS_DCS,
                        last=lastseen)
            self.titleUpdater.put("{sys}|{grp}|{chan}".format(sys=self.reception.System, grp=self.reception.Group, chan=self.reception.Channel))
        self.monwin.putline("{info:s}| dur={dur}".format(
                dur=self.reception.Duration,
                info = self.reception.infocache),
            scroll = False)
Пример #13
0
def nthroot(A, n:int,*, precision:int=None,decimales:int=None) -> Decimal:
    """Calcula la raiz n-esima de A"""
    #https://en.wikipedia.org/wiki/Nth_root#Logarithmic_computation
    if n>1:
        if A>0:
            DA = Decimal(A)
            #N = Decimal(n)
            if not precision:
                dec = 21 + (decimales if decimales else 0)
                precision = max( 42+dec, ((abs(DA.adjusted())+1)//n ) + dec )
                #21 y 42 números arbitrarios para minimizar
                #errores de redondeo y entregar un numero
                #con precicion más que suficiente para lo
                #que se necesite. Se eligio 42 ya que es la
                #respuesta al universo, y 21 por se la mitad
                #de la respuesta
            with localcontext() as ctx:
                ctx.prec = precision
                resul = Decimal( DA.ln() / n ).exp()
                return resul if decimales is None else round(resul,decimales)
        elif A==0:
            return Decimal(0)
        else:
            if n%2==0:
                raise ValueError("Raiz par de un número negativo")
            return - nthroot(-A, n, precision=precision, decimales=decimales)
    else:
        raise ValueError("El indice de la raiz debe ser mayor que 1")
Пример #14
0
    def test_generator(self):
        privkey = reesa.reesa_so.genpriv()

        p, q, privexp, pubexp, modulus, totient_modulus = [
            ctypes.create_string_buffer("", reesa.MAX_NUMBER_SIZE) for i in range(6)
        ]

        retval = reesa.reesa_so.writepriv(privkey, p, q, pubexp, privexp, modulus, totient_modulus)

        q = Decimal(q.value)
        p = Decimal(p.value)

        self.assertEqual(retval, 1)

        with localcontext() as ctx:
            # use higher precision to match gmp
            ctx.prec = 200
            self.assertEqual(Decimal(modulus.value),
                             p*q)

            self.assertEqual(Decimal(totient_modulus.value),
                             (p-1)*(q-1))

            self.assertEqual(pubexp.value, "65537")

            self.assertEqual(
                Decimal(privexp.value),
                inverse(Decimal(pubexp.value),
                        Decimal(totient_modulus.value)))
Пример #15
0
 def process_bind_param   (self, value, dialect) :
     if value is not None :
         with decimal.localcontext (self._SAW_C) :
             result = int (value * self._SAW_scale)
     else :
         result = value
     return result
Пример #16
0
    def decoder_fn(self, data):
        value = big_endian_to_int(data)

        with decimal.localcontext(abi_decimal_context):
            decimal_value = decimal.Decimal(value) / TEN ** self.frac_places

        return decimal_value
Пример #17
0
	def getPriceGross(self):
		with localcontext() as ctx:
			ctx.rounding = ROUND_HALF_EVEN

			vatPercent = Decimal(settings.INVOICE_VAT) * Decimal("0.01")
			grossPrice = self.price + (self.price * vatPercent)
			return grossPrice.quantize(Decimal("0.01"))
Пример #18
0
	def getVATAmount(self):
		with localcontext() as ctx:
			ctx.rounding = ROUND_HALF_EVEN

			vatPercent = Decimal(settings.INVOICE_VAT) * Decimal("0.01")
			vatAmount = self.price * vatPercent
			return vatAmount.quantize(Decimal("0.01"))
Пример #19
0
 def partition_function(self, batch_size, prec):
     """The exact value of Z calculated with precision prec. 
     Only feasible for small number of hidden units."""
     with decimal.localcontext() as ctx:
         if prec != 0:
             ctx.prec = prec
         batches = ml.common.util.pack_in_batches(all_states(self.n_hid),
                                               batch_size)
         if prec != 0:
             s = decimal.Decimal(0)
         else:
             allfhes = np.array([])
         seen_samples = 0L
         total_samples = 2L**self.n_hid
         for hid in batches:
             print >>stderr, "%i / %i           \r" % (seen_samples, total_samples),
             fhes = self.free_hidden_energy(hid)
             if prec != 0:
                 for fhe in gp.as_numpy_array(fhes):
                     p = decimal.Decimal(-fhe).exp()
                     s += p
             else:
                 allfhes = np.concatenate((allfhes, 
                                           -gp.as_numpy_array(fhes)))
             seen_samples += hid.shape[0]
         if prec != 0:
             return s
         else:
             return logsum(allfhes)
Пример #20
0
    def _pi(n, iBC, iAC, cOC, cAC, oldpi=0, i=0):

        iedge = iBC
        cedge = 2 * cAC

        iperim = n * iedge / 2
        cperim = n * cedge / 2

        pi = (iperim * 2 + cperim) / 3 # inscribed is twice as better

        _print_pi_inequal(i,n, iperim, cperim, pi)

        # was result the same within p significant digits?
        with localcontext() as ctx:
            ctx.prec = precision
            if +pi == +oldpi:
                return pi

        # next inscribed edge (BD, the new BC)
        # (AB + AC) / BC = AD / DB
        # AD^2 + DB^2 = AB^2, ADB is a right triangle
        # solving for BD == edge == new iBC
        iBC = iBC * 2*radius / (iBC**2 + (2*radius + iAC)**2).sqrt()
        iAC = ((2*radius)**2 - iBC**2).sqrt() # from right triangle

        # next circumscribed edge (2*AD, the new AC)
        # (CO + OA) / CA = OA / AD
        # OA^2 + AD^2 = DO^2
        # solving for AD == edge/2 == new cAC
        cAC = radius * cAC / (cOC + radius)
        cOC = (cAC**2 + radius**2).sqrt()

        return _pi(n*2, iBC, iAC, cOC, cAC, pi, i+1)
Пример #21
0
def fib(count):
    """Return nth fibonacci number using Binet's formula."""
    with decimal.localcontext() as context:
        context.prec = count
        sqrt_five = decimal.Decimal(5).sqrt()
        golden_ratio = (1 + sqrt_five) / 2

        return int((golden_ratio**count - (-golden_ratio**(-count))) / sqrt_five)
Пример #22
0
    def encode_fn(self, value):
        with decimal.localcontext(abi_decimal_context):
            scaled_value = value * TEN ** self.frac_places
            integer_value = int(scaled_value)

        unsigned_integer_value = integer_value % (2 ** self.value_bit_size)

        return int_to_big_endian(unsigned_integer_value)
def test_consistent_decimal_error():
    bad = "invalid argument to Decimal"
    with pytest.raises(InvalidArgument) as excinfo:
        decimals(bad).example()
    with pytest.raises(InvalidArgument) as excinfo2:
        with decimal.localcontext(decimal.Context(traps=[])):
            decimals(bad).example()
    assert str(excinfo.value) == str(excinfo2.value)
Пример #24
0
def format_fraction(f, precision):
    if f == 0: return "0"
    s = str(int(f)) + "."
    f -= int(f)
    with localcontext() as ctx:
        ctx.prec = precision
        s += str(Decimal(f.numerator) / f.denominator).partition(".")[2]
    return s
Пример #25
0
    def convert_to(self, other_currency):
        """Return current Money converted to other_currency as new instance of
        Money

        """
        with localcontext(self.context):
            rate = self.get_rate(other_currency)
            result = Money(self.value * rate, other_currency)
            return result
Пример #26
0
 def ms_parse_numeric(positive, buf, scale):
     val = reduce(lambda acc, val: acc * 256 + ord(val), reversed(buf), 0)
     val = Decimal(val)
     with localcontext() as ctx:
         ctx.prec = 38
         if not positive:
             val *= -1
         val /= 10 ** scale
     return val
Пример #27
0
def find_denominator(target=1000):
    regex = re.compile(r"(.+?)\1+")
    with localcontext() as ctx:
        ctx.prec = 2000
        for num in range(1, target+1):
            dec = str(1 / Decimal(num))
            pattern = regex.findall(dec)
            if pattern:
                yield num, max(pattern, key=len)
Пример #28
0
def calculatePi(i):
    D = decimal.Decimal
    with decimal.localcontext() as ctx:
        ctx.prec = i + 1
        pi = sum(1/Decimal(16)**k *
		(Decimal(4)/(8*k+1) - Decimal(2)/(8*k+4) - Decimal(1)/(8*k+5) - Decimal(1)/(8*k+6))
		# k is the amount of iterations of the summation. I selected 100
		for k in range (100)) 
    return pi
Пример #29
0
def func3():
    with decimal.localcontext() as c:
        c.prec = 2
        print "Local precision:", c.prec
        print "3.14 / 3 =", (decimal.Decimal("3.14") / 3)
        print "3.14 / 3 =", (decimal.Decimal("3.14") / 3)

    print
    print "Default precision:", decimal.getcontext().prec
    print "1000000000000.93 =", (decimal.Decimal("1000000000000.93"))
Пример #30
0
def binet_decimal(n, precision=None):
    """Calculate nth fibonacci number using Binet's formula.

    O(1) steps, O(1) in memory

    NOTE: uninterruptable
    
    >>> map(binet_decimal, range(10))
    ['0', '1', '1', '2', '3', '5', '8', '13', '21', '34']
    """
    with decimal.localcontext() as cxt:
        if precision is not None:
            cxt.prec = precision
        with decimal.localcontext(cxt) as nested_cxt:
            nested_cxt.prec += 2  # increase prec. for intermediate results
            sqrt5 = decimal.Decimal(5).sqrt()
            f = ((1 + sqrt5) / 2)**n / sqrt5
        s = str(+f.to_integral()) # round to required precision
    return s
Пример #31
0
 def CountFee(self, MainForm):
     """
     First edition:
     Simply count the fee of Taiwanese stock without apply discount.
     Second edition:
     Plus other functions, likes choice Securities and time. 
     """
     BuyPrice = self.Buy_lineEdit.text()
     SellPrice = self.Sell_lineEdit.text()
     NumberofStock = self.NumberofStock_lineEdit.text()
     try:
         discount11 = self.value
         if BuyPrice and SellPrice and NumberofStock:
             with localcontext() as ctx:
                 ctx.rounding = ROUND_HALF_UP
                 BuyFee = (Decimal(BuyPrice) *
                           1000) * (Decimal(NumberofStock)) * (
                               Decimal(0.001425)) * (Decimal(discount11))
                 FinalBuyFee = BuyFee.to_integral_value()
                 SellFee = ((Decimal(SellPrice) * 1000) *
                            (Decimal(NumberofStock)) * (Decimal(0.001425)) *
                            (Decimal(discount11))) + (
                                (Decimal(SellPrice) * 1000) *
                                (Decimal(NumberofStock)) * (Decimal(0.003)))
                 FinalSellFee = SellFee.to_integral_value()
                 FinalFee = FinalBuyFee + FinalSellFee
                 FinalEarn = ((Decimal(SellPrice) * 1000) *
                              (Decimal(NumberofStock))) - (
                                  (Decimal(BuyPrice) * 1000) *
                                  (Decimal(NumberofStock))) - FinalFee
                 if FinalEarn > 0:
                     self.DisResult_label.setText(
                         "+ " + str(format(FinalEarn, ',')))
                     self.DisResult_label.setStyleSheet('color:red')
                     self.Buy_lineEdit.clear()
                     self.Sell_lineEdit.clear()
                     self.NumberofStock_lineEdit.clear()
                 elif FinalEarn == 0:
                     self.DisResult_label.setText(
                         str(format(FinalEarn, ',')))
                     self.Buy_lineEdit.clear()
                     self.Sell_lineEdit.clear()
                     self.NumberofStock_lineEdit.clear()
                 else:
                     self.DisResult_label.setText(
                         str(format(FinalEarn, ',')))
                     self.DisResult_label.setStyleSheet('color:green')
                     self.Buy_lineEdit.clear()
                     self.Sell_lineEdit.clear()
                     self.NumberofStock_lineEdit.clear()
         else:
             error_dialog = QtWidgets.QMessageBox()
             error_dialog.setIcon(QtWidgets.QMessageBox.Critical)
             error_dialog.setText("請輸入買進價、賣出價與股票張數!!!")
             error_dialog.addButton(QtWidgets.QMessageBox.Ok)
             error_dialog.exec()
     except:
         self.value = 1
         discount11 = self.value
         if BuyPrice and SellPrice and NumberofStock:
             with localcontext() as ctx:
                 ctx.rounding = ROUND_HALF_UP
                 BuyFee = (Decimal(BuyPrice) *
                           1000) * (Decimal(NumberofStock)) * (
                               Decimal(0.001425)) * (Decimal(discount11))
                 FinalBuyFee = BuyFee.to_integral_value()
                 SellFee = ((Decimal(SellPrice) * 1000) *
                            (Decimal(NumberofStock)) * (Decimal(0.001425)) *
                            (Decimal(discount11))) + (
                                (Decimal(SellPrice) * 1000) *
                                (Decimal(NumberofStock)) * (Decimal(0.003)))
                 FinalSellFee = SellFee.to_integral_value()
                 FinalFee = FinalBuyFee + FinalSellFee
                 FinalEarn = ((Decimal(SellPrice) * 1000) *
                              (Decimal(NumberofStock))) - (
                                  (Decimal(BuyPrice) * 1000) *
                                  (Decimal(NumberofStock))) - FinalFee
                 if FinalEarn > 0:
                     self.DisResult_label.setText(
                         "+ " + str(format(FinalEarn, ',')))
                     self.DisResult_label.setStyleSheet('color:red')
                     self.Buy_lineEdit.clear()
                     self.Sell_lineEdit.clear()
                     self.NumberofStock_lineEdit.clear()
                 elif FinalEarn == 0:
                     self.DisResult_label.setText(
                         str(format(FinalEarn, ',')))
                     self.Buy_lineEdit.clear()
                     self.Sell_lineEdit.clear()
                     self.NumberofStock_lineEdit.clear()
                 else:
                     self.DisResult_label.setText(
                         str(format(FinalEarn, ',')))
                     self.DisResult_label.setStyleSheet('color:green')
                     self.Buy_lineEdit.clear()
                     self.Sell_lineEdit.clear()
                     self.NumberofStock_lineEdit.clear()
         else:
             error_dialog = QtWidgets.QMessageBox()
             error_dialog.setIcon(QtWidgets.QMessageBox.Critical)
             error_dialog.setText("請輸入買進價、賣出價與股票張數!!!")
             error_dialog.addButton(QtWidgets.QMessageBox.Ok)
             error_dialog.exec()
Пример #32
0
 def was_order_filled(self, order_id):
     '''
     Post: Internal balance/assets is updated if the order was filled.
     '''
     
     if self.is_test:
         try:
             assert(order_id == CryptopiaTrader.simulation_buy_order_id or 
                    order_id == CryptopiaTrader.simulation_sell_order_id)
         except AssertionError as e:
             e.args += ("Invalid order ID: ", order_id)
             raise
         
         # Simulate the trader's order being filled by watching what the market.
         # It is likely that simulation mode results in higher profits as in reality
         # other bots undercut our own trades so our orders are filled less frequently.
         
         # The time frame is an hour because the pipeline's polling frequency
         # could be set to be longer than the default number of seconds.
         r = requests.get('https://www.cryptopia.co.nz/api/GetMarketHistory/'+self.market_ticker+"/1")
         
         for trade in r.json()["Data"]:
             if int(trade["Timestamp"]) < self._last_simulation_transaction_check:
                 break
             else:
                 with localcontext() as context:
                     context.prec = 8
                     
                     if order_id == CryptopiaTrader.simulation_buy_order_id and trade["Type"] == "Sell":
                         self._filled_simulation_assets += Decimal(trade["Amount"])
                         if self._filled_simulation_assets >= self._expecting_simulation_assets:
                             self.assets = self._expecting_simulation_assets * self.post_fee
                             self._active_buy_order = False
                             self._waiting_for_order_to_fill = None
                     elif order_id == CryptopiaTrader.simulation_sell_order_id and trade["Type"] == "Buy":
                         incoming_balance = Decimal(trade["Amount"]) * self._limit_order_price
                         self._filled_simulation_balance += incoming_balance
                         if self._filled_simulation_balance >= self._expecting_simulation_balance:
                             self.balance = self._expecting_simulation_balance * self.post_fee
                             self._active_sell_order = False
                             self._waiting_for_order_to_fill = None
                             
         # Orders up to this moment have been processed, don't process them again.
         self._last_simulation_transaction_check = time.time()
         
     else:
         
         # Lookup the order on the market and check its status.
         # The trader will stop if the order was cancelled as a human intervened.
         # Note: The pipeline never knows the Trader's status so the pipeline will continue
         #       to pass data to the market observer.
         
         open_order = self.lookup_open_order(order_id, self.market_ticker)
         
         if open_order == None:
             # Order was filled or cancelled.
             self.fetch_balance_and_assets()
             if self._active_buy_order == True:
                 self._active_buy_order = False
                 self.balance = Decimal(0)
             elif self._active_sell_order == True:
                 self._active_sell_order = False
                 self.assets = Decimal(0)
             self._waiting_for_order_to_fill = None
         elif open_order["Remaining"] < open_order["Amount"]:
             print("The order has been partially filled. Waiting until it is fully filled.")
Пример #33
0
def root(num, e):
    with localcontext() as context:
        context.prec = 4200
        exp = Decimal(1.) / Decimal(e)
        return int(Decimal(num) ** exp)
Пример #34
0
    def __init__(
            self,
            initial_supply: int = __default_initial_supply,
            first_phase_supply: int = __default_first_phase_supply,
            first_phase_duration: int = __default_first_phase_duration,
            decay_half_life: int = __default_decay_half_life,
            reward_saturation: int = __default_reward_saturation,
            small_stake_multiplier: Decimal = __default_small_stake_multiplier,
            **kwargs):
        """
        :param initial_supply: Number of tokens in circulating supply at t=0
        :param first_phase_supply: Number of tokens in circulating supply at phase switch (variable t)
        :param first_phase_duration: Minimum duration of the first phase
        :param decay_half_life: Time for issuance to halve in years (in second phase only)
        :param reward_saturation: "saturation" time - if staking is longer than T_sat, the reward doesn't get any higher
        :param small_stake_multiplier: Fraction of maximum reward paid to those who are about to unlock tokens
        """

        #
        # Calculated
        #

        with localcontext() as ctx:
            ctx.prec = self._precision

            initial_supply = Decimal(initial_supply)

            first_phase_supply = Decimal(first_phase_supply)

            first_phase_max_issuance = first_phase_supply / first_phase_duration / 365

            # ERC20 Token parameter (See Equation 4 in Mining paper)
            total_supply = initial_supply + first_phase_supply + first_phase_max_issuance * 365 * decay_half_life / LOG2

            # Awarded periods- Escrow parameter
            maximum_rewarded_periods = reward_saturation * 365

            # k2 - Escrow parameter
            lock_duration_coefficient_2 = maximum_rewarded_periods / (
                1 - small_stake_multiplier)

            # k1 - Escrow parameter
            lock_duration_coefficient_1 = lock_duration_coefficient_2 * small_stake_multiplier

            # d - Escrow parameter
            issuance_decay_coefficient = 365 * decay_half_life / LOG2

        #
        # Injected
        #

        self.token_halving = decay_half_life
        self.token_saturation = reward_saturation
        self.small_stake_multiplier = small_stake_multiplier

        super().__init__(
            initial_supply=initial_supply,
            first_phase_supply=first_phase_supply,
            total_supply=total_supply,
            first_phase_max_issuance=first_phase_max_issuance,
            issuance_decay_coefficient=issuance_decay_coefficient,
            lock_duration_coefficient_1=lock_duration_coefficient_1,
            lock_duration_coefficient_2=lock_duration_coefficient_2,
            maximum_rewarded_periods=maximum_rewarded_periods,
            **kwargs)
Пример #35
0
 def inner_decorator(*a, **kwa):
     with localcontext() as ctx:
         ctx.prec = kwargs['prec']
         return f(*a, **kwa)
Пример #36
0
def check_convert_value(val: str, char: Characteristic) -> Any:
    """
    Checks if the given value is of the given type or is convertible into the type. If the value is not convertible, a
    HomeKitTypeException is thrown.

    :param val: the original value
    :param char: the characteristic
    :return: the converted value
    :raises FormatError: if the input value could not be converted to the target type
    """

    if char.format == CharacteristicFormats.bool:
        try:
            val = strtobool(str(val))
        except ValueError:
            raise FormatError('"{v}" is no valid "{t}"!'.format(v=val,
                                                                t=char.format))

        # We have seen iPhone's sending 1 and 0 for True and False
        # This is in spec
        # It is also *required* for Ecobee Switch+ devices (as at Mar 2020)
        return 1 if val else 0

    if char.format in NUMBER_TYPES:
        try:
            val = Decimal(val)
        except ValueError:
            raise FormatError('"{v}" is no valid "{t}"!'.format(v=val,
                                                                t=char.format))

        if char.minValue is not None:
            val = max(Decimal(char.minValue), val)

        if char.maxValue is not None:
            val = min(Decimal(char.maxValue), val)

        # Honeywell T6 Pro cannot handle arbritary precision, the values we send
        # *must* respect minStep
        # See https://github.com/home-assistant/core/issues/37083
        if char.minStep is not None:
            with localcontext() as ctx:
                ctx.prec = 6

                # Python3 uses bankers rounding by default, so 28.5 rounds to 28, not 29.
                # This is surprising for most people
                ctx.rounding = ROUND_HALF_UP

                val = Decimal(val)
                offset = Decimal(
                    char.minValue if char.minValue is not None else 0)
                min_step = Decimal(char.minStep)

                # We use to_integral_value() here rather than round as it respsects
                # ctx.rounding
                val = offset + ((
                    (val - offset) / min_step).to_integral_value() * min_step)

        if char.format in INTEGER_TYPES:
            val = int(val.to_integral_value())
        else:
            val = float(val)

    if char.format == CharacteristicFormats.data:
        try:
            base64.decodebytes(val.encode())
        except binascii.Error:
            raise FormatError('"{v}" is no valid "{t}"!'.format(v=val,
                                                                t=char.format))

    if char.format == CharacteristicFormats.tlv8:
        try:
            tmp_bytes = base64.decodebytes(val.encode())
            TLV.decode_bytes(tmp_bytes)
        except (binascii.Error, TlvParseException):
            raise FormatError('"{v}" is no valid "{t}"!'.format(v=val,
                                                                t=char.format))

    return val
Пример #37
0
def loads(value, encoding="utf-8"):
    with localcontext() as ctx:
        ctx.prec = PRECISION
        return json.loads(value, use_decimal=True, encoding=encoding)
Пример #38
0
 def calculate_distance(self, second_x, second_y):
     with localcontext() as ctx:
         ctx.rounding = ROUND_HALF_UP
         return Decimal(math.sqrt((self.x - second_x) ** 2 + (self.y - second_y) ** 2)).to_integral_value()
f = Decimal('2.1')

print(e + f)

print((a + b) == Decimal('6.3'))
print((c + d) == Decimal('6.3'))
print((e + f) == Decimal('6.3'))

#####使用decimal,控制数字位数和四舍五入运算,先得创建一个本地上下文并更改它的设置
from decimal import localcontext

g = Decimal('4.2')
h = Decimal('1.3')
print(g / h)

with localcontext() as ctx:
    ctx.prec = 3
    print(g / h)

with localcontext() as ctx:
    ctx.prec = 30
    print(g / h)

print(g / h)

# 大数加减
nums = [1.23e+18, 1, -1.23e+18]
print(sum(nums))  #计算错误,计算精度影响

import math
def is_perfect_square(number):
    """Return True if given number is the square of an integer."""
    digit_count = len(str(number))
    with localcontext(Context(prec=digit_count*2)):
        return int(Decimal(number).sqrt())**2 == number
Пример #41
0
def test_str_to_mjds(i_f):
    i, f = i_f
    with decimal.localcontext(decimal.Context(prec=40)):
        assert_closer_than_ns(str_to_mjds(str(decimalify(i, f))), i_f, 1)
Пример #42
0
def test_mjd_jd_pulsar_round_trip_leap_sec_day_edge(i_f):
    with decimal.localcontext(decimal.Context(prec=40)):
        jds = mjds_to_jds_pulsar(*i_f)
        assert_closer_than_ns(jds_to_mjds_pulsar(*jds), i_f, 1)
Пример #43
0
def test_mjd_jd_pulsar_round_trip(i_f):
    i, f = i_f
    assume(not (i in leap_sec_days and (1 - f) * 86400 < 1e-9))
    with decimal.localcontext(decimal.Context(prec=40)):
        jds = mjds_to_jds_pulsar(*i_f)
        assert_closer_than_ns(jds_to_mjds_pulsar(*jds), i_f, 1)
Пример #44
0
def test_localcontext():
    with localcontext() as ctx:
        for precision in range(3, 6):
            ctx.prec = precision
            x = decimal.Decimal(78.96) + decimal.Decimal(90.99)
            print x
Пример #45
0
def _distributor(amount, splits, scale=None, addtl_prec=0):
    """ Evenly (exactly) distributes an amount among a dictionary. Dictionary
    values should be integers (or decimals) representing the ratio the amount
    should be split among. Arithmetic will be performed to `scale` decimal
    places. Amount will be rounded down to `scale` number of decimal places
    _before_ distribution. Remainders from distribution will be given to users
    in order of who deserved the largest remainders, albiet in round robin
    fashion. `addtl_prec` allows you to specify additional precision for
    computing share remainders, allowing a higher likelyhood of fair
    distribution of amount remainders among keys. Usually not needed.  """
    scale = int(scale or 28) * -1
    amount = Decimal(amount)

    if not splits:
        raise Exception("Splits cannot be empty!")

    with decimal.localcontext(decimal.BasicContext) as ctx:
        ctx.rounding = decimal.ROUND_DOWN
        smallest = Decimal((0, (1, ), scale))

        # Set our precision for operations to only what we need it to be,
        # nothing more. This garuntees a large enough precision without setting
        # it so high as to waste a ton of CPU power. A real issue with the
        # slowness of Python Decimals
        # get very largest non-decimal value a share might recieve
        largest_val = int(round(amount))
        # convert to length of digits and add the decimal scale
        ctx.prec = len(str(largest_val)) + (scale * -1) + addtl_prec

        # Round the distribution amount to correct scale. We will distribute
        # exactly this much
        total_count = Decimal(sum(splits.itervalues()))
        new_amount = amount.quantize(smallest)
        # Check that after rounding the distribution amount is within 0.001% of
        # desired
        assert abs(amount - new_amount) < (amount / 10000)
        amount = new_amount

        # Count how much we give out, and also the remainders of adjusting to
        # desired scale
        remainders = {}
        total_distributed = 0
        percent = 0
        for key, value in splits.iteritems():
            if isinstance(value, int):
                value = Decimal(value)
            assert isinstance(value, Decimal)
            share = (value / total_count) * amount
            percent += (value / total_count)
            splits[key] = share.quantize(smallest)
            remainders[key] = share - splits[key]
            total_distributed += splits[key]

        # The amount that hasn't been distributed due to rounding down
        count = (amount - total_distributed) / smallest
        assert total_distributed <= amount
        if count != 0:
            # Loop over the dictionary keys in remainder order until we
            # distribute the leftovers
            keylist = sorted(remainders.iterkeys(), key=remainders.get, reverse=True)
            for i, key in zip(xrange(count), itertools.cycle(keylist)):
                splits[key] += smallest

        total = sum(splits.itervalues())
        # Check that we don't have extra decimal places
        assert total.as_tuple().exponent >= scale
        # And it should come out exact!
        if total != amount:
            raise Exception(
                "Value after distribution ({}) is not equal to amount"
                " to be distributed ({})!".format(total, amount))
        return splits
Пример #46
0
 def update_event(self, inp=-1):
     self.set_output_val(0, decimal.localcontext(self.input(0)))
Пример #47
0
def dumps(value):
    with localcontext() as ctx:
        ctx.prec = PRECISION
        return json.dumps(value, use_decimal=True, default=encode_datetime)
Пример #48
0
#			- ROUND_UP (rounds away from zero)
#			- ROUND_DOWN (rounds towards zero)
# 			- ROUND_CEILING (round to ceiling, towards + inf)
# 			- ROUND_FLOOR (round to floor, towards -inf)
# 			- ROUND_HALF_UP (rounds to nearest, ties away from zero)
# 			- ROUND_HALF_DOWN (rounds to nearest, ties towards zero)
#			- ROUND_HALF_EVEN (rounds to nearest, ties to even)
print('\n\n----Decimals----')
print('----Context----')
g_ctx = decimal.getcontext()
print(g_ctx)
g_ctx.rounding = decimal.ROUND_HALF_DOWN
# or g_ctx.rounrding = 'ROUND_HALF_UP'
print(g_ctx)
print('type(decimal.getcontext()): ', type(g_ctx))
print('type(decimal.localcontext()): ', type(decimal.localcontext()))
# which is similar to default (or global) context in this case

x = Decimal('1.25')
y = Decimal('1.35')

# using context manager of localcontext
print('----Context Manager----')
with decimal.localcontext() as ctx:
    ctx.prec = 6
    ctx.rounding = decimal.ROUND_HALF_UP
    print(ctx)
    print(decimal.getcontext())
    print(round(x, 1))
    print(round(y, 1))
print(round(x, 1))
Пример #49
0
import decimal
x = decimal.Decimal("3.4")
y = decimal.Decimal("4.5")
a = x * y
b = x / y
print a, b
print "-" * 30
decimal.getcontext().prec = 3
c = x * y
d = x / y
print c, d
print "-" * 30
with decimal.localcontext(decimal.Context(prec=10)):
    e = x * y
    f = x / y
    print e, f
Пример #50
0
    def run_test (self):

        # Check that there's no UTXO on none of the nodes
        assert_equal(len(self.nodes[0].listunspent()), 0)
        assert_equal(len(self.nodes[1].listunspent()), 0)
        assert_equal(len(self.nodes[2].listunspent()), 0)

        print("Mining blocks...")

        self.nodes[0].generate(1)

        walletinfo = self.nodes[0].getwalletinfo()
        assert_equal(walletinfo['immature_balance'], 40)
        assert_equal(walletinfo['balance'], 0)

        self.sync_all()
        self.nodes[1].generate(101)
        self.sync_all()

        assert_equal(self.nodes[0].getbalance(), 40)
        assert_equal(self.nodes[1].getbalance(), 40)
        assert_equal(self.nodes[2].getbalance(), 0)

        # Check that only first and second nodes have UTXOs
        assert_equal(len(self.nodes[0].listunspent()), 1)
        assert_equal(len(self.nodes[1].listunspent()), 1)
        assert_equal(len(self.nodes[2].listunspent()), 0)

        # Send 21 BTC from 0 to 2 using sendtoaddress call.
        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)

        walletinfo = self.nodes[0].getwalletinfo()
        assert_equal(walletinfo['immature_balance'], 0)

        # Have node0 mine a block, thus it will collect its own fee.
        self.nodes[0].generate(1)
        self.sync_all()

        # Exercise locking of unspent outputs
        unspent_0 = self.nodes[2].listunspent()[0]
        unspent_0 = {"txid": unspent_0["txid"], "vout": unspent_0["vout"]}
        self.nodes[2].lockunspent(False, [unspent_0])
        assert_raises_message(JSONRPCException, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
        assert_equal([unspent_0], self.nodes[2].listlockunspent())
        self.nodes[2].lockunspent(True, [unspent_0])
        assert_equal(len(self.nodes[2].listlockunspent()), 0)

        # Have node1 generate 100 blocks (so node0 can recover the fee)
        self.nodes[1].generate(100)
        self.sync_all()

        # node0 should end up with 80 btc in block rewards plus fees, but
        # minus the 21 plus fees sent to node2
        assert_equal(self.nodes[0].getbalance(), 80 - 21)
        assert_equal(self.nodes[2].getbalance(), 21)

        # Node0 should have two unspent outputs.
        # Create a couple of transactions to send them to node2, submit them through
        # node1, and make sure both node0 and node2 pick them up properly:
        node0utxos = self.nodes[0].listunspent(1)
        assert_equal(len(node0utxos), 2)

        # create both transactions
        txns_to_send = []
        for utxo in node0utxos:
            inputs = []
            outputs = {}
            inputs.append({ "txid" : utxo["txid"], "vout" : utxo["vout"]})
            outputs[self.nodes[2].getnewaddress("from1")] = utxo["amount"] - 3
            raw_tx = self.nodes[0].createrawtransaction(inputs, outputs)
            txns_to_send.append(self.nodes[0].signrawtransaction(raw_tx))

        # Have node 1 (miner) send the transactions
        self.nodes[1].sendrawtransaction(txns_to_send[0]["hex"], True)
        self.nodes[1].sendrawtransaction(txns_to_send[1]["hex"], True)

        # Have node1 mine a block to confirm transactions:
        self.nodes[1].generate(1)
        self.sync_all()

        assert_equal(self.nodes[0].getbalance(), 0)
        assert_equal(self.nodes[2].getbalance(), 74)
        assert_equal(self.nodes[2].getbalance("from1"), 74-21)

        # Send 10 BTC normal
        address = self.nodes[0].getnewaddress("test")
        fee_per_byte = Decimal('0.001') / 1000
        self.nodes[2].settxfee(fee_per_byte * 1000)
        txid = self.nodes[2].sendtoaddress(address, 10, "", "", False)
        self.nodes[2].generate(1)
        self.sync_all()
        node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), Decimal('64'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
        assert_equal(self.nodes[0].getbalance(), Decimal('10'))

        # Send 10 BTC with subtract fee from amount
        txid = self.nodes[2].sendtoaddress(address, 10, "", "", True)
        self.nodes[2].generate(1)
        self.sync_all()
        node_2_bal -= Decimal('10')
        assert_equal(self.nodes[2].getbalance(), node_2_bal)
        node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), Decimal('20'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))

        # Sendmany 10 BTC
        txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [])
        self.nodes[2].generate(1)
        self.sync_all()
        node_0_bal += Decimal('10')
        node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), node_2_bal - Decimal('10'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
        assert_equal(self.nodes[0].getbalance(), node_0_bal)

        # Sendmany 10 BTC with subtract fee from amount
        txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [address])
        self.nodes[2].generate(1)
        self.sync_all()
        node_2_bal -= Decimal('10')
        assert_equal(self.nodes[2].getbalance(), node_2_bal)
        node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), node_0_bal + Decimal('10'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))

        # Test ResendWalletTransactions:
        # Create a couple of transactions, then start up a fourth
        # node (nodes[3]) and ask nodes[0] to rebroadcast.
        # EXPECT: nodes[3] should have those transactions in its mempool.
        txid1 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1)
        txid2 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1)
        sync_mempools(self.nodes)

        self.nodes.append(start_node(3, self.options.tmpdir, self.extra_args[3]))
        connect_nodes_bi(self.nodes, 0, 3)
        sync_blocks(self.nodes)

        relayed = self.nodes[0].resendwallettransactions()
        assert_equal(set(relayed), {txid1, txid2})
        sync_mempools(self.nodes)

        assert(txid1 in self.nodes[3].getrawmempool())

        # Exercise balance rpcs
        assert_equal(self.nodes[0].getwalletinfo()["unconfirmed_balance"], 1)
        assert_equal(self.nodes[0].getunconfirmedbalance(), 1)

        #check if we can list zero value tx as available coins
        #1. create rawtx
        #2. hex-changed one output to 0.0
        #3. sign and send
        #4. check if recipient (node0) can list the zero value tx
        usp = self.nodes[1].listunspent()
        inputs = [{"txid":usp[0]['txid'], "vout":usp[0]['vout']}]
        outputs = {self.nodes[1].getnewaddress(): 39.998, self.nodes[0].getnewaddress(): 11.11}

        rawTx = self.nodes[1].createrawtransaction(inputs, outputs).replace("c0833842", "00000000") #replace 11.11 with 0.0 (int32)
        decRawTx = self.nodes[1].decoderawtransaction(rawTx)
        signedRawTx = self.nodes[1].signrawtransaction(rawTx)
        decRawTx = self.nodes[1].decoderawtransaction(signedRawTx['hex'])
        zeroValueTxid= decRawTx['txid']
        sendResp = self.nodes[1].sendrawtransaction(signedRawTx['hex'])

        self.sync_all()
        self.nodes[1].generate(1) #mine a block
        self.sync_all()

        unspentTxs = self.nodes[0].listunspent() #zero value tx must be in listunspents output
        found = False
        for uTx in unspentTxs:
            if uTx['txid'] == zeroValueTxid:
                found = True
                assert_equal(uTx['amount'], Decimal('0'))
        assert(found)

        #do some -walletbroadcast tests
        stop_nodes(self.nodes)
        self.nodes = start_nodes(3, self.options.tmpdir, [["-walletbroadcast=0"],["-walletbroadcast=0"],["-walletbroadcast=0"]])
        connect_nodes_bi(self.nodes,0,1)
        connect_nodes_bi(self.nodes,1,2)
        connect_nodes_bi(self.nodes,0,2)
        self.sync_all()

        txIdNotBroadcasted  = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)
        txObjNotBroadcasted = self.nodes[0].gettransaction(txIdNotBroadcasted)
        self.nodes[1].generate(1) #mine a block, tx should not be in there
        self.sync_all()
        assert_equal(self.nodes[2].getbalance(), node_2_bal) #should not be changed because tx was not broadcasted

        #now broadcast from another node, mine a block, sync, and check the balance
        self.nodes[1].sendrawtransaction(txObjNotBroadcasted['hex'])
        self.nodes[1].generate(1)
        self.sync_all()
        node_2_bal += 2
        txObjNotBroadcasted = self.nodes[0].gettransaction(txIdNotBroadcasted)
        assert_equal(self.nodes[2].getbalance(), node_2_bal)

        #create another tx
        txIdNotBroadcasted  = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)

        #restart the nodes with -walletbroadcast=1
        stop_nodes(self.nodes)
        self.nodes = start_nodes(3, self.options.tmpdir)
        connect_nodes_bi(self.nodes,0,1)
        connect_nodes_bi(self.nodes,1,2)
        connect_nodes_bi(self.nodes,0,2)
        sync_blocks(self.nodes)

        self.nodes[0].generate(1)
        sync_blocks(self.nodes)
        node_2_bal += 2

        #tx should be added to balance because after restarting the nodes tx should be broadcastet
        assert_equal(self.nodes[2].getbalance(), node_2_bal)

        #send a tx with value in a string (PR#6380 +)
        txId  = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "2")
        txObj = self.nodes[0].gettransaction(txId)
        assert_equal(txObj['amount'], Decimal('-2'))

        txId  = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "0.0001")
        txObj = self.nodes[0].gettransaction(txId)
        assert_equal(txObj['amount'], Decimal('-0.0001'))

        #check if JSON parser can handle scientific notation in strings
        txId  = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "1e-4")
        txObj = self.nodes[0].gettransaction(txId)
        assert_equal(txObj['amount'], Decimal('-0.0001'))

        # General checks for errors from incorrect inputs
        # This will raise an exception because the amount type is wrong
        assert_raises_jsonrpc(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4")

        # This will raise an exception since generate does not accept a string
        assert_raises_jsonrpc(-1, "not an integer", self.nodes[0].generate, "2")

        # This will raise an exception for the invalid private key format
        assert_raises_jsonrpc(-5, "Invalid private key encoding", self.nodes[0].importprivkey, "invalid")

        # This will raise an exception for importing an address with the PS2H flag
        temp_address = self.nodes[1].getnewaddress()
        assert_raises_jsonrpc(-5, "Cannot use the p2sh flag with an address - use a script instead", self.nodes[0].importaddress, temp_address, "label", False, True)

        # This will raise an exception for attempting to dump the private key of an address you do not own
        otp = self.get_otp(temp_address)
        assert_raises_jsonrpc(-4, f'Private key for address {temp_address} is not known', self.nodes[0].dumpprivkey, temp_address, otp)

        # This will raise an exception for attempting to get the private key of an Invalid Firo address
        otp = self.get_otp("invalid")
        assert_raises_jsonrpc(-5, "Invalid Firo address", self.nodes[0].dumpprivkey, "invalid", otp)

        # # This will raise an exception for attempting to set a label for an Invalid Firo address
        # assert_raises_jsonrpc(-5, "Invalid Firo address", self.nodes[0].setlabel, "invalid address", "label")

        # This will raise an exception for importing an invalid address
        assert_raises_jsonrpc(-5, "Invalid Firo address or script", self.nodes[0].importaddress, "invalid")

        # This will raise an exception for attempting to import a pubkey that isn't in hex
        assert_raises_jsonrpc(-5, "Pubkey must be a hex string", self.nodes[0].importpubkey, "not hex")

        # This will raise an exception for importing an invalid pubkey
        assert_raises_jsonrpc(-5, "Pubkey is not a valid public key", self.nodes[0].importpubkey, "5361746f736869204e616b616d6f746f")

        # Import address and private key to check correct behavior of spendable unspents
        # 1. Send some coins to generate new UTXO
        address_to_import = self.nodes[2].getnewaddress()
        txid = self.nodes[0].sendtoaddress(address_to_import, 1)
        self.nodes[0].generate(1)
        self.sync_all()

        # 2. Import address from node2 to node1
        self.nodes[1].importaddress(address_to_import)

        # 3. Validate that the imported address is watch-only on node1
        assert(self.nodes[1].validateaddress(address_to_import)["iswatchonly"])

        # 4. Check that the unspents after import are not spendable
        assert_array_result(self.nodes[1].listunspent(),
                           {"address": address_to_import},
                           {"spendable": False})

        # 5. Import private key of the previously imported address on node1
        otp = self.get_otp(address_to_import, self.nodes[2])
        priv_key = self.nodes[2].dumpprivkey(address_to_import, otp)
        self.nodes[1].importprivkey(priv_key)

        # 6. Check that the unspents are now spendable on node1
        assert_array_result(self.nodes[1].listunspent(),
                           {"address": address_to_import},
                           {"spendable": True})

        # Mine a block from node0 to an address from node1
        cbAddr = self.nodes[1].getnewaddress()
        blkHash = self.nodes[0].generatetoaddress(1, cbAddr)[0]
        cbTxId = self.nodes[0].getblock(blkHash)['tx'][0]
        self.sync_all()

        # Check that the txid and balance is found by node1
        self.nodes[1].gettransaction(cbTxId)

        # check if wallet or blockchain maintenance changes the balance
        self.sync_all()
        blocks = self.nodes[0].generate(2)
        self.sync_all()
        balance_nodes = [self.nodes[i].getbalance() for i in range(3)]
        block_count = self.nodes[0].getblockcount()

        # Check modes:
        #   - True: unicode escaped as \u....
        #   - False: unicode directly as UTF-8
        for mode in [True, False]:
            self.nodes[0].ensure_ascii = mode
            # unicode check: Basic Multilingual Plane, Supplementary Plane respectively
            for s in [u'б€б‹аБаА', u'№…Ё']:
                addr = self.nodes[0].getaccountaddress(s)
                label = self.nodes[0].getaccount(addr)
                assert_equal(label, s)
                assert(s in self.nodes[0].listaccounts().keys())
        self.nodes[0].ensure_ascii = True # restore to default

        # maintenance tests
        maintenance = [
            '-rescan',
            '-reindex',
            '-zapwallettxes=1',
            '-zapwallettxes=2',
            # disabled until issue is fixed: https://github.com/bitcoin/bitcoin/issues/7463
            # '-salvagewallet',
        ]
        chainlimit = 6
        for m in maintenance:
            print("check " + m)
            stop_nodes(self.nodes)
            # set lower ancestor limit for later
            self.nodes = start_nodes(3, self.options.tmpdir, [[m, "-limitancestorcount="+str(chainlimit)]] * 3)
            while m == '-reindex' and [block_count] * 3 != [self.nodes[i].getblockcount() for i in range(3)]:
                # reindex will leave rpc warm up "early"; Wait for it to finish
                time.sleep(0.1)
            assert_equal(balance_nodes, [self.nodes[i].getbalance() for i in range(3)])

        # Exercise listsinceblock with the last two blocks
        coinbase_tx_1 = self.nodes[0].listsinceblock(blocks[0])
        assert_equal(coinbase_tx_1["lastblock"], blocks[1])
        assert_equal(len(coinbase_tx_1["transactions"]), 1)
        assert_equal(coinbase_tx_1["transactions"][0]["blockhash"], blocks[1])
        assert_equal(len(self.nodes[0].listsinceblock(blocks[1])["transactions"]), 0)

        # ==Check that wallet prefers to use coins that don't exceed mempool limits =====

        # Get all non-zero utxos together
        chain_addrs = [self.nodes[0].getnewaddress(), self.nodes[0].getnewaddress()]
        singletxid = self.nodes[0].sendtoaddress(chain_addrs[0], self.nodes[0].getbalance(), "", "", True)
        self.nodes[0].generate(1)
        node0_balance = self.nodes[0].getbalance()

        # Split into two chains
        with decimal.localcontext() as ctx:
            ctx.prec = 8
            rawtx = self.nodes[0].createrawtransaction(
                [{"txid":singletxid, "vout":0}],
                {chain_addrs[0]:node0_balance/2-Decimal('0.01'), chain_addrs[1]:node0_balance/2-Decimal('0.01')})

        signedtx = self.nodes[0].signrawtransaction(rawtx)
        singletxid = self.nodes[0].sendrawtransaction(signedtx["hex"])
        self.nodes[0].generate(1)

        # Make a long chain of unconfirmed payments without hitting mempool limit
        # Each tx we make leaves only one output of change on a chain 1 longer
        # Since the amount to send is always much less than the outputs, we only ever need one output
        # So we should be able to generate exactly chainlimit txs for each original output
        sending_addr = self.nodes[1].getnewaddress()
        txid_list = []
        for i in range(chainlimit*2):
            txid_list.append(self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001')))
        assert_equal(self.nodes[0].getmempoolinfo()['size'], chainlimit*2)
        assert_equal(len(txid_list), chainlimit*2)

        # Without walletrejectlongchains, we will still generate a txid
        # The tx will be stored in the wallet but not accepted to the mempool
        extra_txid = self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001'))
        assert(extra_txid not in self.nodes[0].getrawmempool())
        assert(extra_txid in [tx["txid"] for tx in self.nodes[0].listtransactions()])
        self.nodes[0].abandontransaction(extra_txid)
        total_txs = len(self.nodes[0].listtransactions("*",99999))

        # Try with walletrejectlongchains
        # Double chain limit but require combining inputs, so we pass SelectCoinsMinConf
        stop_node(self.nodes[0],0)
        self.nodes[0] = start_node(0, self.options.tmpdir, ["-walletrejectlongchains", "-limitancestorcount="+str(2*chainlimit)])

        # wait for loadmempool
        timeout = 10
        while (timeout > 0 and len(self.nodes[0].getrawmempool()) < chainlimit*2):
            time.sleep(0.5)
            timeout -= 0.5
        assert_equal(len(self.nodes[0].getrawmempool()), chainlimit*2)

        node0_balance = self.nodes[0].getbalance()
        # With walletrejectlongchains we will not create the tx and store it in our wallet.
        assert_raises_message(JSONRPCException, "mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))

        # Verify nothing new in wallet
        assert_equal(total_txs, len(self.nodes[0].listtransactions("*",99999)))
Пример #51
0
        Context,
        localcontext,
    )
except ImportError:
    from jepler_udecimal import (
        Decimal,
        getcontext,
        setcontext,
        ExtendedContext,
        DivisionByZero,
        InvalidOperation,
        Context,
        localcontext,
    )

with localcontext():
    setcontext(ExtendedContext)
    print(Decimal(0))
    print(Decimal("1"))
    print(Decimal("-.0123"))
    print(Decimal(123456))
    print(Decimal("123.45e12345678"))
    print(Decimal("1.33") + Decimal("1.27"))
    print(Decimal("12.34") + Decimal("3.87") - Decimal("18.41"))
    dig = Decimal(1)
    print(dig / Decimal(3))
    getcontext().prec = 18
    print(dig / Decimal(3))
    print(dig.sqrt())
    print(Decimal(3).sqrt())
    print(Decimal(3)**123)
Пример #52
0
>>> ctx.prec = 40  # <2>
>>> one_third = decimal.Decimal('1') / decimal.Decimal('3')  # <3>
>>> one_third  # <4>
Decimal('0.3333333333333333333333333333333333333333')
>>> one_third == +one_third  # <5>
True
>>> ctx.prec = 28  # <6>
>>> one_third == +one_third  # <7>
False
>>> +one_third  # <8>
Decimal('0.3333333333333333333333333333')

# END UNARY_PLUS_DECIMAL

"""

import decimal

if __name__ == '__main__':

    with decimal.localcontext() as ctx:
        ctx.prec = 40
        print('precision:', ctx.prec)
        one_third = decimal.Decimal('1') / decimal.Decimal('3')
        print('    one_third:', one_third)
        print('   +one_third:', +one_third)

    print('precision:', decimal.getcontext().prec)
    print('    one_third:', one_third)
    print('   +one_third:', +one_third)
Пример #53
0
 def _read_data(self, n_items, buf, nulls_map=None):
     with localcontext() as ctx:
         ctx.prec = self.max_precision
         return super(DecimalColumn, self)._read_data(n_items,
                                                      buf,
                                                      nulls_map=nulls_map)
Пример #54
0
 def _write_data(self, items, buf):
     with localcontext() as ctx:
         ctx.prec = self.max_precision
         super(DecimalColumn, self)._write_data(items, buf)
Пример #55
0
def fractions2(precision, x, y):
    with localcontext() as ctx:
        ctx.prec = precision
        yield Decimal(x) / Decimal(y)
        yield Decimal(x) / Decimal(y)
Пример #56
0
        def to_foreign(self, obj, name, value):  # pylint:disable=unused-argument
            if not isinstance(value, dec):
                with localcontext(self.DECIMAL_CONTEXT) as ctx:
                    value = ctx.create_decimal(value)

            return Decimal128(value)
Пример #57
0
def test_exact_economics():
    """
    Formula for staking in one period:
    (totalSupply - currentSupply) * (lockedValue / totalLockedValue) * (k1 + allLockedPeriods) / k2

    K2 - Staking coefficient
    K1 - Locked periods coefficient

    if allLockedPeriods > awarded_periods then allLockedPeriods = awarded_periods
    kappa * log(2) / halving_delay === (k1 + allLockedPeriods) / k2

    kappa = (small_stake_multiplier + (1 - small_stake_multiplier) * min(T, T1) / T1)
    where allLockedPeriods == min(T, T1)
    """

    #
    # Expected Output
    #

    # Supply
    expected_total_supply = 3885390081777926911255691439
    expected_supply_ratio = Decimal('3.885390081777926911255691439')
    expected_initial_supply = 1000000000000000000000000000

    # Reward
    expected_reward_supply = 2885390081777926911255691439
    reward_saturation = 1

    # Staking
    halving = 2
    multiplier = 0.5
    expected_locked_periods_coefficient = 365
    expected_staking_coefficient = 768812

    #
    # Sanity
    #

    # Sanity check ratio accuracy
    expected_scaled_ratio = str(expected_supply_ratio).replace('.', '')
    assert str(expected_total_supply) == expected_scaled_ratio

    # Sanity check denomination size
    expected_scale = 28
    assert len(str(expected_total_supply)) == expected_scale
    assert len(str(expected_initial_supply)) == expected_scale
    assert len(str(expected_reward_supply)) == expected_scale

    # Use same precision as economics class
    with localcontext() as ctx:
        ctx.prec = TokenEconomics._precision

        # Sanity check expected testing outputs
        assert Decimal(expected_total_supply
                       ) / expected_initial_supply == expected_supply_ratio
        assert expected_reward_supply == expected_total_supply - expected_initial_supply
        assert reward_saturation * 365 == expected_locked_periods_coefficient
        assert int(365**2 * reward_saturation * halving / log(2) /
                   (1 - multiplier)) == expected_staking_coefficient

    # After sanity checking, assemble expected test deployment parameters
    expected_deployment_parameters = (
        24,  # Hours in single period
        768812,  # Staking coefficient (k2)
        365,  # Locked periods coefficient (k1)
        365,  # Max periods that will be additionally rewarded (awarded_periods)
        30,  # Min amount of periods during which tokens can be locked
        15000000000000000000000,  # min locked NuNits
        4000000000000000000000000)  # max locked NuNits

    #
    # Token Economics
    #

    # Check creation
    e = TokenEconomics()

    with localcontext() as ctx:
        ctx.prec = TokenEconomics._precision

        # Check that total_supply calculated correctly
        assert Decimal(
            e.erc20_total_supply) / e.initial_supply == expected_supply_ratio
        assert e.erc20_total_supply == expected_total_supply

        # Check reward rates
        initial_rate = Decimal(
            (e.erc20_total_supply - e.initial_supply) *
            (e.locked_periods_coefficient + 365) / e.staking_coefficient)
        assert initial_rate == Decimal(
            (e.initial_inflation * e.initial_supply) / 365)

        initial_rate_small = (
            e.erc20_total_supply - e.initial_supply
        ) * e.locked_periods_coefficient / e.staking_coefficient
        assert Decimal(initial_rate_small) == Decimal(initial_rate / 2)

        # Check reward supply
        assert Decimal(
            LOG2 / (e.token_halving * 365) *
            (e.erc20_total_supply - e.initial_supply)) == initial_rate
        assert e.reward_supply == expected_total_supply - expected_initial_supply

        # Check deployment parameters
        assert e.staking_deployment_parameters == expected_deployment_parameters
Пример #58
0
def test_decode_signed_real(high_bit_size,
                            low_bit_size,
                            integer_bit_size,
                            stream_bytes,
                            data_byte_size):
    if integer_bit_size > data_byte_size * 8:
        with pytest.raises(ValueError):
            SignedRealDecoder(
                value_bit_size=integer_bit_size,
                high_bit_size=high_bit_size,
                low_bit_size=low_bit_size,
                data_byte_size=data_byte_size,
            )
        return
    elif high_bit_size + low_bit_size != integer_bit_size:
        with pytest.raises(ValueError):
            SignedRealDecoder(
                value_bit_size=integer_bit_size,
                high_bit_size=high_bit_size,
                low_bit_size=low_bit_size,
                data_byte_size=data_byte_size,
            )
        return
    else:
        decoder = SignedRealDecoder(
            value_bit_size=integer_bit_size,
            high_bit_size=high_bit_size,
            low_bit_size=low_bit_size,
            data_byte_size=data_byte_size,
        )

    stream = ContextFramesBytesIO(stream_bytes)

    padding_offset = data_byte_size - integer_bit_size // 8
    data_offset = padding_offset + integer_bit_size // 8

    padding_bytes = stream_bytes[:data_byte_size][:padding_offset]
    data_bytes = stream_bytes[:data_byte_size][padding_offset:data_offset]

    if len(stream_bytes) < data_byte_size:
        with pytest.raises(InsufficientDataBytes):
            decoder(stream)
        return
    elif not is_valid_padding_bytes(padding_bytes, data_bytes):
        with pytest.raises(NonEmptyPaddingBytes):
            decoder(stream)
        return
    else:
        decoded_value = decoder(stream)

    if padding_bytes:
        if decoded_value >= 0:
            assert bytes(set(padding_bytes)) == b'\x00'
        else:
            assert bytes(set(padding_bytes)) == b'\xff'

    _, upper_bound = compute_signed_integer_bounds(high_bit_size + low_bit_size)

    unsigned_integer_value = big_endian_to_int(data_bytes)
    if unsigned_integer_value >= upper_bound:
        signed_integer_value = unsigned_integer_value - 2 ** (high_bit_size + low_bit_size)
    else:
        signed_integer_value = unsigned_integer_value

    with decimal.localcontext(abi_decimal_context):
        raw_actual_value = decimal.Decimal(signed_integer_value) / 2 ** low_bit_size

    actual_value = quantize_value(raw_actual_value, low_bit_size)

    assert decoded_value == actual_value
Пример #59
0
def test_mjd_jd_round_trip(i_f):
    with decimal.localcontext(decimal.Context(prec=40)):
        assert_closer_than_ns(jds_to_mjds(*mjds_to_jds(*i_f)), i_f, 1)
Пример #60
0
 def discouted_profit(self, profit, fee='0.0025'):
     with localcontext() as ctx:
         ctx.rounding = ROUND_UP
         return profit - max(
             Decimal(fee) * Decimal(profit), Decimal('0E-8'))