示例#1
0
 def encode_to_stream(self, value, out_stream: OutputStream):
     user_context = decimal.getcontext()
     decimal.setcontext(self.context)
     value = value.quantize(self.scale_format)
     bytes_value = str(value).encode("utf-8")
     out_stream.write_bytes(bytes_value, len(bytes_value))
     decimal.setcontext(user_context)
示例#2
0
def start_up() -> None:
    """Initialize the program.

    As far as possible:
    Set up program variables in config.py.
    Load config files from disk - savelocation.ini, config.ini, config_dynamic.ini.
    Load datafile from disk - <program name>.dat.
    """
    decimal.setcontext(decimal.BasicContext)
    config.root_dir, _ = os.path.split(__file__)
    load_values_from_setup_py()  # Get <program name> and version
    start_logger()  # config.root\<program name>.log
    set_savelocation()  # config.root\savelocation.ini points to user data directory
    load_config_ini()  # config.root\config.ini
    load_config_dynamic_ini()  # savelocation_path\config_dynamic_fn
    # Try to load the data file. If not found it is expected the user will navigate to the
    # correct location and open the file from the menu.
    try:
        control.load_program_data()  # savelocation_path\<program name>.dat
    except FileNotFoundError:
        config.data = control.Database()

    # Update version of database
    data_version = getattr(config.data, 'data_version', None)
    if data_version != config.data.data_code_version:
        config.data.version_update(data_version)
示例#3
0
 def decode_from_stream(self, in_stream: InputStream, length=0):
     user_context = decimal.getcontext()
     decimal.setcontext(self.context)
     value = decimal.Decimal(
         in_stream.read_bytes().decode("utf-8")).quantize(self.scale_format)
     decimal.setcontext(user_context)
     return value
示例#4
0
def solve_rpn(equation: str, context=decimal.DefaultContext) -> Decimal:
    '''Solve an arithmetic problem in Reverse Polish Notation.'''
    decimal.setcontext(context)

    stack = []
    for unit in re.split(r'\s+', equation.strip()):
        if number.match(str(unit)):
            stack.append(Decimal(unit))
        elif unit in binary_ops:
            if (len(stack) < 2):
                raise RPNError("Too few arguments for operator "
                               "'{}'".format(unit))

            num = binary_ops[unit](stack.pop(), stack.pop())
            stack.append(num)
        elif unit in unary_ops:
            if (len(stack) < 1):
                raise RPNError("Too few arguments for operator "
                               "'{}'".format(unit))

            num = unary_ops[unit](stack.pop())
            stack.append(num)
        else:
            raise RPNError("Unknown identifier '{}'".format(unit))
    else:
        if (len(stack) > 1):
            raise RPNError("No remaining operator(s) for numbers "
                           "{}".format(', '.join(map(str, stack))))

        return stack[0]
示例#5
0
def drops_to_xrp(drops: str) -> Decimal:
    """
    Convert from drops to decimal XRP.

    Args:
        drops: String representing indivisible drops of XRP

    Returns:
        Decimal representation of the same amount of XRP

    Raises:
        TypeError: if ``drops`` not given as a string
        XRPRangeException: if the given number of drops is invalid
    """
    if type(drops) != str:
        raise TypeError(f"Drops must be provided as string (got {type(drops)})")
    drops = drops.strip()
    setcontext(_DROPS_CONTEXT)
    if not fullmatch(_DROPS_REGEX, drops):
        raise XRPRangeException(f"Not a valid amount of drops: '{drops}'")
    try:
        drops_d = Decimal(drops)
    except InvalidOperation:
        raise XRPRangeException(f"Not a valid amount of drops: '{drops}'")
    xrp_d = drops_d * ONE_DROP
    if xrp_d > MAX_XRP:
        raise XRPRangeException(f"Drops amount {drops} is too large.")
    return xrp_d
    def test_lot_sold(self):
        """
        """       
        
        context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
        decimal.setcontext(context)
    
        category = MarketCategory.objects.all()[0]
        
        now = datetime.datetime.now()
        now_plus_10 = now + datetime.timedelta(seconds=5)
        
        auction = AuctionSession(shop=self.shop, title="Auction Session Nr 1", description="-- no desc --", start=now, end=now_plus_10)
        auction.save()
        
        lot = Lot(shop = self.shop,
                  title = "Coin From Rusia 1901 (PCGS 60)",
                  description = "rare coin",
                  category = category,
                  date_time = now,
                  weight = "5",
                  session=auction, 
                  starting_bid=decimal.Decimal("10.00"), 
                  reserve=decimal.Decimal("0.00"))
        lot.save()
        
        success = self.client.login(username='******', password='******')
        self.assertEqual(success, True, "login failed")
        
        bidder = User.objects.filter(username="******").get()
        cart = Cart(shop=self.shop, bidder=bidder)
        cart.save()
        
        #Check that lot is still active...
        self.assertEqual(lot.is_active(), True , "Failed: The lot should be active!")
        self.assertEqual(lot.bidhistory_set.all().count(), 0 , "Failed: The lot should not have any bid yet!")
        
        my_bid = decimal.Decimal("19.00")
        response = self.client.get(reverse("bidding_view_lot", args=[lot.id]), {'amount': my_bid}, HTTP_HOST=self.HTTP_HOST)
        self.assertEqual(response.status_code, 302, "Failed when trying to bid a valid amount $19.00. This value should be allowed...")    
        
        lot = Lot.objects.get(id=lot.id)
        
        self.assertNotEqual(lot.bidhistory_set.all().count(), 0 , "Failed: The lot should have at least one bid!")
        logging.info("waiting to auction session finish...")
        
        while not lot.session.finished():
            time.sleep(1)
            
        logging.info("Running cron...")
        cron.minute_update()
        
        lot = Lot.objects.get(id=lot.id)

        self.assertEqual(lot.reserve_has_been_met(), True , "Failed, reserved has not been met!")
        self.assertEqual(lot.bid_actual.bid_amount, my_bid , "Failed: The bid actual is wrong, is %s but should be %s" % (lot.bid_actual.bid_amount, my_bid))
        self.assertEqual(lot.bid_actual.bidder.username, "test" , "Failed, wrong bidder won!")
        self.assertEqual(lot.is_active(), False, "Failed: The lot state is wrong, should be SOLD but it is %s" % lot.state)
        self.assertEqual(lot.is_didnt_sell(), False, "Failed: The lot state is wrong, should be SOLD but it is %s" % lot.state)
        self.assertEqual(lot.is_sold(), True, "Failed: The lot state is wrong, should be SOLD but it is %s" % lot.state)
示例#7
0
def best_weight_N_Dwar(opts):
    sN = opts['sN']
    sK = opts['sK']

    trade_least = []
    from decimal import Decimal
    from decimal import setcontext
    from decimal import Context
    setcontext(Context(prec=10))
    items_left = len(sN)

    if items_left == 1:
        bN = sN[0]
        sN.remove(bN)
        return bN

    if sN[0] < sK[0] or sN[-1] < sK[-1]:
        tN = (sK[items_left-1] + sK[items_left-2]) / Decimal(2.0)
        bN = sN[0]
        sN.remove(bN)
        return tN
    else:

        bN = sN[items_left - 1]
        sN.remove(bN)
        return bN
示例#8
0
    def render_button(self, cart, request):
        import decimal
        context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
        decimal.setcontext(context)
        
        url = braintree.TransparentRedirect.url()
        #TODO: Replace this in production
        
        entry_point = request.build_absolute_uri(reverse("braintree_confirm"))
        amount = cart.total_with_taxes()
        logging.warn(amount)
        amount = amount.quantize(decimal.Decimal('.01'))
        tr_data = braintree.Transaction.tr_data_for_sale({
            "transaction": {
                "type": "sale",
                "amount": str(amount),
#                "options": {
#                        "submit_for_settlement": True
#                }
            }
            
        }, entry_point)
        
        html = """
        <form action="%s" method="POST">
            <input type="hidden" name="tr_data" value="%s" />
            <label>Credit Card Number</label><input type="text" name="transaction[credit_card][number]" /><br/>
            <label>Expiration Date</label><input type="text" name="transaction[credit_card][expiration_date]" /><br/>
            <label>CVV</label><input type="text" name="transaction[credit_card][cvv]" /><br/>
            <button class="primaryAction small awesome" type="submit">Pay</button>
        </form>
        """ % (url, tr_data)
        logging.debug("---- BRAINTREE FORM ----- \n%s" % html)
        return html
示例#9
0
    def to_bip(value):
        """
        Convert PIPs to BIPs.
        Use dynamic Decimal precision, depending on value length.
        Args:
            value (int|str|Decimal): value in PIP
        Returns:
            Decimal
        """
        # Check if value is correct PIP value
        value = str(value)
        if not value.isdigit():
            raise ValueError(f'{value} is not correct PIP value')

        # Get default decimal context
        context = decimal.getcontext()
        # Set temporary decimal context for calculation
        decimal.setcontext(
            decimal.Context(prec=len(value), rounding=decimal.ROUND_DOWN))

        # Convert value
        value = decimal.Decimal(value) / decimal.Decimal(PIP)

        # Reset decimal context to default
        decimal.setcontext(context)

        return value
示例#10
0
    def float_to_decimal(f):
        "Convert a floating point number to a Decimal with no loss of information"
        # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
        # exponent.  Double the mantissa until it is an integer.  Use the integer
        # mantissa and exponent to compute an equivalent Decimal.  If this cannot
        # be done exactly, then retry with more precision.

        try:
            mantissa, exponent = math.frexp(f)
        except OverflowError:
            return decimal.Inf

        while mantissa != int(mantissa):
            mantissa *= 2.0
            exponent -= 1
        mantissa = int(mantissa)

        oldcontext = decimal.getcontext()
        decimal.setcontext(decimal.Context(traps=[decimal.Inexact]))
        try:
            while True:
                try:
                    return mantissa * decimal.Decimal(2) ** exponent
                except decimal.Inexact:
                    decimal.getcontext().prec += 1
        finally:
            decimal.setcontext(oldcontext)
示例#11
0
def float2decimal(fval):
    """ Convert a floating point number to a Decimal with no loss of
        information
    """
    # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
    # exponent.  Double the mantissa until it is an integer.  Use the integer
    # mantissa and exponent to compute an equivalent Decimal.  If this cannot
    # be done exactly, then retry with more precision.
    #
    # This routine is from
    # http://docs.python.org/release/2.5.2/lib/decimal-faq.html

    mantissa, exponent = math.frexp(fval)
    try:
        while mantissa != int(mantissa):
            mantissa *= 2.0
            exponent -= 1
        mantissa = int(mantissa)
    except (OverflowError, ValueError):
        return "---"

    oldcontext = decimal.getcontext()
    decimal.setcontext(decimal.Context(traps=[decimal.Inexact]))
    try:
        while True:
            try:
                return mantissa * decimal.Decimal(2) ** exponent
            except decimal.Inexact:
                decimal.getcontext().prec += 1
    finally:
        decimal.setcontext(oldcontext)
示例#12
0
 def decode_from_stream(self, in_stream, nested):
     user_context = decimal.getcontext()
     decimal.setcontext(self.context)
     size = in_stream.read_bigendian_int32()
     value = decimal.Decimal(in_stream.read(size).decode("utf-8")).quantize(self.scale_format)
     decimal.setcontext(user_context)
     return value
示例#13
0
def float2decimal(fval):
    """ Convert a floating point number to a Decimal with no loss of
        information
    """
    # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
    # exponent.  Double the mantissa until it is an integer.  Use the integer
    # mantissa and exponent to compute an equivalent Decimal.  If this cannot
    # be done exactly, then retry with more precision.
    #
    # This routine is from
    # http://docs.python.org/release/2.5.2/lib/decimal-faq.html

    mantissa, exponent = math.frexp(fval)
    try:
        while mantissa != int(mantissa):
            mantissa *= 2.0
            exponent -= 1
        mantissa = int(mantissa)
    except (OverflowError, ValueError):
        return "---"

    oldcontext = decimal.getcontext()
    decimal.setcontext(decimal.Context(traps=[decimal.Inexact]))
    try:
        while True:
            try:
                return mantissa * decimal.Decimal(2)**exponent
            except decimal.Inexact:
                decimal.getcontext().prec += 1
    finally:
        decimal.setcontext(oldcontext)
    def render_button(self, cart):
        import decimal
        context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
        decimal.setcontext(context)
        
        url = braintree.TransparentRedirect.url()
        #TODO: Replace this in production
        entry_point = "http://%s:8080%s" % (cart.shop.default_dns, reverse("braintree_confirm"))
        amount = cart.total_with_taxes()
        logging.warn(amount)
        amount = amount.quantize(decimal.Decimal('.01'))
        tr_data = braintree.Transaction.tr_data_for_sale({
            "transaction": {
                "type": "sale",
                "amount": str(amount),
#                "options": {
#                        "submit_for_settlement": True
#                }
            }
            
        }, entry_point)
        
        html = """
        <form action="%s" method="POST">
            <input type="hidden" name="tr_data" value="%s" />
            <label>Credit Card Number</label><input type="text" name="transaction[credit_card][number]" /><br/>
            <label>Expiration Date</label><input type="text" name="transaction[credit_card][expiration_date]" /><br/>
            <button class="primaryAction small awesome" type="submit">Pay</button>
        </form>
        """ % (url, tr_data)
        logging.debug("---- BRAINTREE FORM ----- \n%s" % html)
        return html
示例#15
0
    def convert_value(cls, value, to, prec=33):
        """
        Convert values from/to pip/bip.
        Args:
            value (string|int|Decimal|float): value to convert
            to (string): coin to convert value to
            prec (int): decimal context precision (decimal number length)
        Returns:
            int|Decimal
        """
        # Get default decimal context
        context = decimal.getcontext()
        # Set temporary decimal context for calculation
        decimal.setcontext(
            decimal.Context(prec=prec, rounding=decimal.ROUND_DOWN))

        # PIP in BIP in Decimal
        default = decimal.Decimal(str(cls.DEFAULT))
        # Value in Decimal
        value = decimal.Decimal(str(value))

        # Make conversion
        if to == 'pip':
            value = int(value * default)
        elif to == 'bip':
            value /= default

        # Reset decimal context to default
        decimal.setcontext(context)

        return value
示例#16
0
 def _label_scalar(cls, bucket):
   context = decimal.getcontext()
   try:
     decimal.setcontext(ROUND_UP_CONTEXT)
     return cls._label_scalar_nocontext(bucket=bucket)
   finally:
     decimal.setcontext(context)
示例#17
0
def invoicer(subtotal=None,context=None):
  if context is None:
    decimal.getcontext().rounding='ROUND_HALF_UP'
  else:
    decimal.setcontext(context)
  subtot=getsubtotal(subtotal)
  contrib=cnpcalc(subtot)
  dototal(subtot,contrib,vatcalc(subtot,contrib),ritacalc(subtot))
示例#18
0
def invoicer(subtotal=None, context=None):
    if context is None:
        decimal.getcontext().rounding = 'ROUND_HALF_UP'
    else:
        decimal.setcontext(context)
    subtot = getsubtotal(subtotal)
    contrib = cnpcalc(subtot)
    dototal(subtot, contrib, vatcalc(subtot, contrib), ritacalc(subtot))
示例#19
0
文件: repeats.py 项目: cgnik/euler
def unit_fraction_cycle(n):
    decimal.setcontext(
        decimal.Context(prec=max_precision, rounding=decimal.ROUND_HALF_DOWN))
    val = str(decimal.Decimal(1) / decimal.Decimal(n))
    if val and '.' in val:
        s = val.split('.')[1][:-1]
        return repeats(s)
    return ''
示例#20
0
def invoicer(subtotal=None, context=None):
    if context is None:
        decimal.getcontext().rounding = "ROUND_HALF_UP"  # Euro rounding rules
    else:
        decimal.setcontext(context)  # set to context arg
    subtot = getsubtotal(subtotal)
    contrib = cnpcalc(subtot)
    dototal(subtot, contrib, vatcalc(subtot, contrib), ritacalc(subtot))
示例#21
0
def invoicer(subtotal=None, context=None):
    if context is None:
        decimal.getcontext().rounding="ROUND_HALF_UP"     # Euro rounding rules
    else:
        decimal.setcontext(context)                       # set to context arg
    subtot = getsubtotal(subtotal)      
    contrib = cnpcalc(subtot)
    dototal(subtot, contrib, vatcalc(subtot, contrib), ritacalc(subtot))
示例#22
0
 def encode_to_stream(self, value, out_stream, nested):
     user_context = decimal.getcontext()
     decimal.setcontext(self.context)
     value = value.quantize(self.scale_format)
     bytes_value = str(value).encode("utf-8")
     out_stream.write_bigendian_int32(len(bytes_value))
     out_stream.write(bytes_value, False)
     decimal.setcontext(user_context)
示例#23
0
def init():
    global SCREEN, threshold
    con = getcontext()
    con.prec = 800
    setcontext(con)
    threshold = D(0.5)

    SCREEN = pygame.display.set_mode((WIDTH, HEIGTH))
示例#24
0
    def phi_approx(self, term):
        thousand_places = decimal.Decimal(10) ** -999
        my_context = decimal.Context(prec = 1000)
        decimal.setcontext(my_context)

        phi_approx = str(decimal.Decimal(Fib_Math().nth_term(term) / Fib_Math().nth_term(term - 1)).quantize(thousand_places))

        return phi_approx
示例#25
0
文件: ecccc.py 项目: ncme/ecccc
def calculate_barrett_constant(quotient, modulus=(2**32), wordcount=8):
    from decimal import getcontext, setcontext, Decimal

    ctx = getcontext()
    ctx.prec = 128
    setcontext(ctx)
    return ctx.divide_int(Decimal((modulus**(2 * wordcount))),
                          Decimal(quotient))
示例#26
0
 def __init__(self,
              excel_filename,
              sheet_name="Sheet1",
              strptime_formats=None):
     self.filename = excel_filename
     self.sheet_name = sheet_name
     self.strptime_formats = strptime_formats or []
     decimal.setcontext(decimal.ExtendedContext)
示例#27
0
 def setDecimalPrecision(self, precision):
   if self.buffers["rounding"] == 0:
     rounding = decimal.ROUND_HALF_EVEN
   if self.buffers["rounding"] == 1:
     rounding = decimal.ROUND_HALF_UP
   else:
     raise ValueError("Rounding must be either 0 or 1.")
   context = decimal.Context(prec=precision, rounding=rounding)
   decimal.setcontext(context)
示例#28
0
 def setDecimalPrecision(self, precision):
     if self.buffers["rounding"] == 0:
         rounding = decimal.ROUND_HALF_EVEN
     if self.buffers["rounding"] == 1:
         rounding = decimal.ROUND_HALF_UP
     else:
         raise ValueError("Rounding must be either 0 or 1.")
     context = decimal.Context(prec=precision, rounding=rounding)
     decimal.setcontext(context)
示例#29
0
def init_context():
    """ Context setup for modules.

    :return: None
    """
    # ensures all threads use same context
    decimal.DefaultContext.prec = 9
    decimal.DefaultContext.rounding = decimal.ROUND_HALF_UP  # >=0.5 rounds away from zero
    decimal.setcontext(decimal.DefaultContext)
示例#30
0
def round_up_or_down(transactions, up=True):
    """Round the list of transactions passed in.
       If up=True (default) ronud up, else round down.
       Return a new list of rounded values
    """
    WHOLE_NUM = Decimal(1)
    context = Context(rounding=ROUND_UP) if up else Context(
        rounding=ROUND_DOWN)
    setcontext(context)
    return [Decimal(num).quantize(WHOLE_NUM) for num in transactions]
    def test_lot_didnt_sell(self):
        """
        Check that a lot get state DIDN'T SELL when there no bidding...
        """       
        
        context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
        decimal.setcontext(context)
    
        category = MarketCategory.objects.all()[0]
        
        now = datetime.datetime.now()
        now_plus_10 = now + datetime.timedelta(seconds=5)
        
        auction = AuctionSession(shop=self.shop, title="Auction Session Nr 2", description="-- no desc --", start=now, end=now_plus_10)
        auction.save()
        
        lot = Lot(shop = self.shop,
                  title = "Coin From Argentina 1890 (PCGS 60)",
                  description = "rare coin",
                  category = category,
                  date_time = now,
                  weight = "5",
                  session=auction, 
                  starting_bid=decimal.Decimal("100.00"), 
                  reserve=decimal.Decimal("0.00"))
        lot.save()
        
        success = self.client.login(username='******', password='******')
        self.assertEqual(success, True, "login failed")
        
        #Check that lot is still active...
        self.assertEqual(lot.is_active(), True , "Failed: The lot should be active!")
        self.assertEqual(lot.bidhistory_set.all().count(), 0 , "Failed: The lot should not have any bid yet!")
        
        my_bid = decimal.Decimal("90.00")
        response = self.client.get(reverse("bidding_view_lot", args=[lot.id]), {'amount': my_bid}, HTTP_HOST=self.HTTP_HOST)
        self.assertEqual(response.status_code, 200, "Failed: this bid is not valid...")    
        
        self.assertEqual(lot.bidhistory_set.all().count(), 0 , "Failed: The lot should not have any bid yet!")
        
        logging.info("waiting to auction session finish...")
        
        while not lot.session.finished():
            time.sleep(1)
        
        logging.info("Running cron...")
        cron.minute_update()
        
        lot = Lot.objects.get(id=lot.id)

        self.assertEqual(lot.reserve_has_been_met(), False , "Failed, the reserved price should not be reached!")
        self.assertEqual(lot.bid_actual, None , "Failed: There were no bids! ")
        self.assertEqual(lot.is_active(), False, "Failed: The lot could not be active, the lot finished and there were no bids!")
        self.assertEqual(lot.is_sold(), False, "Failed: The lot could not be sold, there were no bids!")
        self.assertEqual(lot.is_didnt_sell(), True, "Failed: The lot wasn't sell!")
示例#32
0
def lu_decomposition(A, b):
    """TODO
    
    Arguments:
        A {[type]} -- [description]
        b {[type]} -- [description]
    
    Returns:
        [type] -- [description]
    """

    setcontext(Context(traps=[DivisionByZero, Underflow, Overflow]))
    # Número de linhas e colunas da matriz A
    n = len(A)

    # Cria uma matriz L de tamanho nxn e uma matriz U que recebe o conteúdo da matriz A
    L = [[Decimal(0.0) for _ in range(n)] for _ in range(n)]
    U = list(map(list, A))

    # Faz a fatoração, alterando os valores de L e U
    for pivot in range(n):
        L[pivot][pivot] = Decimal(1.0)
        for row in range(pivot + 1, n):
            L[row][pivot] = U[row][pivot] / U[pivot][pivot]
            for column in range(pivot, n):
                U[row][column] -= L[row][pivot] * U[pivot][column]

    x = [Decimal(0.0) for i in range(n)]
    y = [Decimal(0.0) for i in range(n)]

    # Resolve L . y = b
    for row in range(n):
        for column in range(n):
            if row == column:
                y[row] += b[row]
                break
            y[row] -= L[row][column] * y[column]

    # Resolve U . x = y
    for row in range(n - 1, -1, -1):
        for column in range(n - 1, -1, -1):
            if row == column:
                x[row] += y[row]
                x[row] /= U[row][column]
                break
            x[row] -= U[row][column] * x[column]

    # print()
    # print([[float(A[i][j]) for j in range(n)] for i in range(n)])
    # print([[float(L[i][j]) for j in range(n)] for i in range(n)])
    # print([[float(U[i][j]) for j in range(n)] for i in range(n)])
    # print([float(a) for a in y])
    # print([float(a) for a in x])

    return x
示例#33
0
 def _label_pd(cls, bucket):
   context = decimal.getcontext()
   try:
     decimal.setcontext(ROUND_UP_CONTEXT)
     buckets = cls._to_series(bucket)
     labels = buckets.apply(cls._label_scalar)
     if len(labels) == 0:
       # Empty Series retains its original dtype after apply.
       labels = labels.astype(str)
     return labels
   finally:
     decimal.setcontext(context)
示例#34
0
 def test_quantized(self):
     self.assertEqual( "12.00", self.us_locale.toString(D("12").quantize(D('0.01'))), msg="12 dollars" )
     self.assertEqual( "3,379.70", self.us_locale.toString(D("3379.7").quantize(D('0.01'))) , msg="rubbles" )
     self.assertEqual( "636.40", self.us_locale.toString(D("636.4").quantize(D('0.01'))), msg= "cny" )
     self.assertEqual( "67.56", self.us_locale.toString(D("67.56")), msg= "GBP" )
     self.assertEqual( "103.00", self.us_locale.toString(D("103").quantize(D('0.01'))), msg= "USD" )
     self.assertEqual( "1,000,000", self.us_locale.toString(D(10)**6), msg= "1 million" )
     context = decimal.getcontext()
     context.prec = 30
     decimal.setcontext(context)
     self.assertEqual( "0.333,33", self.us_locale.toString((D("1")/3).quantize(D('0.00001'))) , msg= "1/3" )
     self.assertEqual( "0.50", self.us_locale.toString(D("1").quantize(D('0.01'))/2), msg= "1/2" )
    def test_lot_still_active(self):
        """
        Check that nothing happend to those lots that aren't finished yet when cron is executed
        """ 
        context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
        decimal.setcontext(context)
    
        category = MarketCategory.objects.all()[0]
        
        now = datetime.datetime.now()
        now_plus_10 = now + datetime.timedelta(seconds=5)
        
        auction = AuctionSession(shop=self.shop, title="Auction Session Nr 4", description="-- no desc --", start=now, end=now_plus_10)
        auction.save()
        
        lot = Lot(shop=self.shop,
                  title="Coin From USA 1905 (PCGS 50)",
                  description="rare coin",
                  category=category,
                  date_time=now,
                  weight="5",
                  session=auction, 
                  starting_bid=decimal.Decimal("100.00"), 
                  reserve=decimal.Decimal("300.00"))
        lot.save()
        
        success = self.client.login(username='******', password='******')
        self.assertEqual(success, True, "login failed")
        
        my_bid = decimal.Decimal("120.00")
        response = self.client.get(reverse("bidding_view_lot", args=[lot.id]), {'amount': my_bid}, HTTP_HOST=self.HTTP_HOST)
        self.assertEqual(response.status_code, 302, "Failed when trying to bid a valid amount %s. This value should be allowed..." % my_bid)    
        
        lot = Lot.objects.get(id=lot.id)
        self.assertEqual(lot.bidhistory_set.all().count(), 1 , "Failed: The lot should not have any bid yet!")
        
        logging.info("don't wait for auction session to finish...")

        #Check that lot is still active...
        lot = Lot.objects.get(id=lot.id)
        self.assertEqual(lot.is_active(), True , "Failed: The lot should be active!")

        logging.info("Running cron...")
        
        cron.minute_update()
        
        lot = Lot.objects.get(id=lot.id)

        self.assertEqual(lot.is_active(), True , "Failed: The lot should be active!")
        self.assertEqual(lot.bid_actual.bid_amount, my_bid, "Failed: The bid actual is wrong, is %s but should be %s" % (lot.bid_actual.bid_amount, my_bid))
        self.assertEqual(lot.bid_actual.bidder.username, "test" , "Failed, wrong bidder won!")
        self.assertEqual(lot.is_sold(), False, "Failed: The lot state is wrong, should be ACTIVE but it is %s" % lot.state)
示例#36
0
    def to_significant(self,
                       sig_digits: int,
                       format,
                       rounding=ROUND_HALF_UP) -> Decimal:
        assert isinstance(sig_digits, int)
        assert sig_digits > 0, "significant digits must be positive"

        context = Context(prec=sig_digits + 1, rounding=rounding)
        setcontext(context)

        quotient = Decimal(self.numerator) / Decimal(self.denominator)
        sig_digits = quotient.quantize()
        return sig_digits
示例#37
0
 def test_init_invalid_rate(self, *args, **kwargs):
     """ Test Account.__init__ with invalid rate input. """
     decimal.setcontext(decimal.BasicContext)
     with self.assertRaises(decimal.InvalidOperation):
         account = self.AccountType(self.owner,
                                    *args,
                                    balance=0,
                                    rate="invalid input",
                                    **kwargs)
         # `rate` is not callable if we use non-callable input
         # pylint: disable=comparison-with-callable
         if account.rate == Decimal("NaN"):
             raise decimal.InvalidOperation()
示例#38
0
def calculate_price(base_quantity,
                    quote_quantity,
                    base_divisibility,
                    quote_divisibility,
                    order_type=None):
    if not base_divisibility:
        base_quantity *= config.UNIT
    if not quote_divisibility:
        quote_quantity *= config.UNIT

    try:
        if order_type == 'BUY':
            decimal.setcontext(
                decimal.Context(prec=8, rounding=decimal.ROUND_DOWN))
        elif order_type == 'SELL':
            decimal.setcontext(
                decimal.Context(prec=8, rounding=decimal.ROUND_UP))

        price = format(D(quote_quantity) / D(base_quantity), '.8f')

        decimal.setcontext(
            decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
        return price

    except Exception as e:
        logging.exception(e)
        decimal.setcontext(
            decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
        raise (e)
示例#39
0
def run_tests(filename):

    nextline = give_nextline(filename)
    TESTS = int(next(nextline))

    from decimal import Decimal
    from decimal import setcontext
    from decimal import Context
    setcontext(Context(prec=10))
    for it in range(1, TESTS + 1):
        C, F, X = map(Decimal, next(nextline).split(' '))
        print('Case #' + str(it) + ': ' + str(time_for_cookies(C, F, X)))

    return
示例#40
0
    def test_decimal_american_english(self):  
        TESTINPUT=0
        EXPECTED=1            

        context = decimal.getcontext()
        context.prec = 8+7
        decimal.setcontext(context)
        tests = ( (D("43112279.75467"), "43,112,279.754,67"), (D("0.0101020204"), "0.010,102,020,4"),
            (D("0.00000001"), "0.000,000,01")
            )
        verbose = False
        for c in tests:
            self.assertEqual( str(c[1]), self.us_locale.toString(c[0]), msg="Test case %s" % c[1] )
            self.assertEqual( (c[0], True), self.us_locale.toDecimal(c[1], 10), msg="Test case US locale parsing %s" % c[1] )
def format_price(value, currency_symbol):
    context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
    decimal.setcontext(context)

    if currency_symbol is None:
        currency_symbol = '$$'

    if currency_symbol == 'USD':
        currency_symbol = '$'

    try:
        value = decimal.Decimal(str(value))
    except Exception, e:
        logging.critical("could not convert value %s to decimal" % value)
        return value
示例#42
0
def problem26():
    decimalLength = 10000
    decimal.setcontext(decimal.Context(prec=decimalLength))
    limit = 1001
    longestRecurring = 0
    longestIndex = 0
    for i in range(1, limit + 1):
        fraction = int(
            decimal.Decimal(1.0) / decimal.Decimal(i) * 10**decimalLength)

        if (IsReciprocal(fraction) > longestRecurring):
            longestRecurring = IsReciprocal(fraction)
            print(longestRecurring)
            longestIndex = i
    print(longestIndex)
	def sum(values):
		'''
		Sum up list of numeric strings. Return Decimal value.

		Args:
		values -- list of strings
		'''

		# context set globally for all Decimal arithmetic, not just for this instance of method
		setcontext( Context( prec=None, rounding=None ) )
		# used in calculation of average and when rounding_method is round.max
		sum = Decimal('0')
		for value in values:
			sum += Decimal(value)
		return(sum)
def format_price(value, currency_symbol):
    context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
    decimal.setcontext(context)
    
    if currency_symbol is None:
        currency_symbol = '$$'
    
    if currency_symbol == 'USD':
        currency_symbol = '$'
    
    try:
        value = decimal.Decimal(str(value))
    except Exception,e:
        logging.critical("could not convert value %s to decimal" % value)
        return value
def step_gradient(k1_current, k2_current, points, learningRate):
#     gmpy2.set_context(gmpy2.context(precision=10))
    decimal.setcontext(decimal.Context(prec=10))
    k1_gradient = decimal.Decimal(0.0)
    k2_gradient = decimal.Decimal(0.0)
    N = decimal.Decimal( float(len(points)) )
    for i in range(0, len(points)):
        x = decimal.Decimal( points[i, 0] )
        y = decimal.Decimal( points[i, 1] )
        y_hat = decimal.Decimal( k1_current * x + k2_current * (x**2) )
        k1_gradient += decimal.Decimal( -(2/N) * (y - y_hat) * (x) )
        k2_gradient += decimal.Decimal( -(2/N) * (y - y_hat) * (x ** 2) )
    new_k1 = k1_current - (learningRate * k1_gradient)
    new_k2 = k2_current - (learningRate * k2_gradient)
    return [new_k1, new_k2, k1_gradient, k2_gradient]
def money_format2(value, shop):
    context = decimal.Context(prec=20, rounding=decimal.ROUND_HALF_DOWN)
    decimal.setcontext(context)
    
    currency_symbol =  shop.preference().checkout_currency
    if currency_symbol is None:
        currency_symbol = '$$'
    
    if currency_symbol == 'USD':
        currency_symbol = '$'
    
    try:
        value = decimal.Decimal(value)
    except Exception,e:
        logging.critical("could not convert value %s to decimal" % value)
        return "%s %s" % (currency_symbol, value)
示例#47
0
 def clean(self):
     cleaned_data = super(AdminBlockAttributeForm, self).clean()
     if cleaned_data['key'] == 'points':
         try:
             cont = decimal.Context(prec=28, rounding=decimal.ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
                     capitals=1, clamp=0, flags=[], traps=[decimal.Overflow,
                     decimal.InvalidOperation, decimal.Inexact])
             decimal.setcontext(cont)
             decimal.getcontext().clear_flags()
             points = decimal.Decimal(cleaned_data['value']).quantize(decimal.Decimal('0.01')) #constraints given from marking model Decimal field
             if points>= decimal.Decimal('1000000'):
                 raise ValueError('points too large')
         except (decimal.Inexact, decimal.Overflow, decimal.InvalidOperation, ValueError) as e:
             msg = "'points' can only have 2 decimal places and need to be smaller than 1000000 . (e.g. 1.25)"
             self.add_error('value', msg)
     return cleaned_data
示例#48
0
def enough_decimal_precision(digits=len(str(2 ** 256))):
    """
    By default, Python stores ``Decimal()`` objects to 28 places.  This
    isn't enough for the 256-bit numbers we deal with when calculating
    difficulty, so we provide a context manager to wrap code that needs
    more precision.
    """

    orig_context = decimal.getcontext()
    if orig_context.prec < digits:
        new_context = orig_context.copy()
        new_context.prec = digits
        decimal.setcontext(new_context)

    yield

    decimal.setcontext(orig_context)
	def round(sum, average, rounding_method):
		'''
		Return average that has been rounded

		Use sum and rounding_method to determine appropriate level of precision.

		If the number of sigfigs of of sum is GREATER THAN the sigfigs that
		average has, do nothing. R/QTL will pad average value with
		zeroes so that all values in a column have same precision.

		Using Rounding_method.MAX results in using the rounding rules of
		python's decimal.ROUND_HALF_EVEN:
			Given value xy..., suppose x is a significant digit and y and z are not
			significant.
				ROUND_HALF_EVEN rounds x down
					if y ∈ {0,1,2,3,4}
					else if y == 5
						and x is an even digit (i.e. x ∈ {0,2,4,6,8})
						and all digits after y are 0 or not present at all
				ROUND_HALF_EVEN rounds x up
					if y ∈ {6,7,8,9}
					else if y == 5
						and ( x is an odd digit (i.e. x ∈ {1,3,5,7,9})
						or there exists at least one non-zero digit after y )

		Therefore, for Rounding_method.MAX, the values will be biased towards
		being too high. However, since this MAX keeps more digits than significant
		anyway, it is unlikely for the true value to be affected significantly.

		Args:
		sum -- Decimal value
		average -- Decimal value
		rounding_method -- one of Rounding_method values
		'''
		# access global var. rounding_method set by user
		average_rounded = average  # default is to do no rounding
		if Rounding_method.MAX is rounding_method:
			num_sigfigs = Significant_value.num_significant_digits(str(sum))
			setcontext(Context(prec=num_sigfigs, rounding=ROUND_HALF_EVEN))
			average_rounded = +average
		return(average_rounded)
示例#50
0
    def assertDecimalEqual(self, exp, result, msg=None):
        """
        @param exp:
        @type exp: D
        @param result:
        @type result:
        @return:
        @rtype:
        """
        old_ctx = getcontext()
        setcontext(self.ctx)

        # unary plus forces re-calculation of # digits
        exp = +exp
        result = +result
        not_equal = exp.compare(result)

        setcontext(old_ctx)

        if not_equal:
            raise self.failureException((msg or '') + str(exp) + ' ' + str(result))
示例#51
0
    def _to_type(self,value):

        if self.__decimal_use_local_context__:
            
            with localcontext(self.__decimal_local_context_class__) as ctx:
                self._set_ctx_vars(ctx)
                value = self.to_type(
                    value,
                    ctx
                )
        else:
            ctx = getcontext()
            self._set_ctx_vars(ctx)
            value = self.to_type(
                value,
                ctx
            )

            setcontext(ctx)

        return value
示例#52
0
def calculate_price(base_quantity, quote_quantity, base_divisibility, quote_divisibility, order_type = None):
    if not base_divisibility:
        base_quantity *= config.UNIT
    if not quote_divisibility:
        quote_quantity *= config.UNIT

    try: 
        if order_type == 'BUY':
            decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_DOWN))
        elif order_type == 'SELL':
            decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_UP))

        price = format(D(quote_quantity) / D(base_quantity), '.8f')

        decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
        return price

    except Exception, e:
        decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
        return '0'
示例#53
0
from decimal import Decimal, setcontext, ExtendedContext

setcontext(ExtendedContext)
precision = Decimal('0.000001')


class LocationStore(object):
    def __init__(self):
        self.locations = {}

    def add(self, latitude, longitude, name, url=None, primary=False):
        latitude = makedecimal(latitude).quantize(precision).normalize()
        longitude = makedecimal(longitude).quantize(precision).normalize()

        for location, data in self.locations.iteritems():
            (other_lat, other_lon) = location
            if latitude == other_lat and longitude == other_lon:
                if url is not None:
                    data['url'] = url
                if primary is True:
                    data['primary'] = True
                break
        else:
            #new location
            self.locations[(latitude, longitude)] = {'name': name,
                                                     'primary': primary}
            if url is not None:
                self.locations[(latitude, longitude)]['url'] = url

    def to_list(self):
        out = []
示例#54
0
文件: new_pWHAT.py 项目: ai-se/pWHAT
from __future__ import division
import os, sys, math
import matplotlib.pyplot as plt
import numpy as np
import decimal
decimal.setcontext(decimal.Context(prec=34))


class data_item():
    def __init__(self, id, decisions, objective):
        self.id = id
        self.decisions = decisions
        self.objective = objective

    def __repr__(self):
        return str(self.id)+ "|" +",".join(map(str, self.decisions)) + "|" + str(self.objective)


def euclidean_distance(list1, list2):
    assert(len(list1) == len(list2)), "The points don't have the same dimension"
    distance = sum([(i - j) ** 2 for i, j in zip(list1, list2)]) ** 0.5
    assert(distance >= 0), "Distance can't be less than 0"
    return distance


def similarity(list1, list2):
    """higher score indicates they are very different"""
    same = 0
    diff = 0
    for a, b in zip(list1, list2):
        if a != b: diff += 1
示例#55
0
from datetime import datetime
import logging
import decimal
import base64
import json
import time

from lib import config, util

decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
D = decimal.Decimal


def calculate_price(base_quantity, quote_quantity, base_divisibility, quote_divisibility, order_type = None):
    if not base_divisibility:
        base_quantity *= config.UNIT
    if not quote_divisibility:
        quote_quantity *= config.UNIT

    try: 
        if order_type == 'BUY':
            decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_DOWN))
        elif order_type == 'SELL':
            decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_UP))

        price = format(D(quote_quantity) / D(base_quantity), '.8f')

        decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
        return price

    except Exception, e:
示例#56
0
#!python3

"""
Output a massive list of mathematical expressions that produce
the desired output.
"""

import decimal
import sys

# Automatically take care of divisions by zero etc
decimal.setcontext(decimal.ExtendedContext)

class Expression(object):
    __slots__= ['left', 'right']
    def __init__(self, left, right):
        self.left = left
        self.right = right

class Number(Expression):
    __slots__= ['value']
    def __init__(self, value):
        self.value = decimal.Decimal(value)

    def evaluate(self):
        return self.value

    def __str__(self):
        return str(self.value)

class Addition(Expression):
示例#57
0
文件: common.py 项目: coink/cryptex
import decimal

decimal.DefaultContext.rounding = decimal.ROUND_DOWN
decimal.DefaultContext.traps = decimal.ExtendedContext.traps.copy()
decimal.DefaultContext.traps[decimal.InvalidOperation] = 1
decimal.setcontext(decimal.DefaultContext)

DECIMAL_PRECISION = decimal.Decimal(10) ** -8

def quantize(decimal_value):
	return decimal_value.quantize(DECIMAL_PRECISION)
def step_gradient(k1_current, k2_current, k3_current, points, learningRate):
    decimal.setcontext(decimal.Context(prec=10))
    k1_gradient = decimal.Decimal(0.0)
    k2_gradient = decimal.Decimal(0.0)
    k3_gradient = decimal.Decimal(0.0)
    N = decimal.Decimal( float(len(points)) )
    for i in range(0, len(points)):
        x = decimal.Decimal( points[i, 0] )
        y = decimal.Decimal( points[i, 1] )
        
        try:
            common_part_1 = -(2/N) * (y - (k1_current + k2_current * x) ** k3_current)
        except Exception as e:
            print('Exception #1')
            print('(y - (k1_current + k2_current * x)) : ', (y - (k1_current + k2_current * x)))
            print('k3_current : ', k3_current)
            
        try:
            common_part_2 = (k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
        except Exception as e:
            print('Exception #2')
            print('x : ', x)
            print('k3_current - 1 : ', (k3_current - 1))
            print('k3_current * (k1_current + k2_current * x) : ', (k3_current * (k1_current + k2_current * x)))
            
        try:
            common_part_3 = decimal.Decimal.ln( k1_current + k2_current * x)
        except Exception as e:
            print('Exception #3')
            print('x : ', x)
            print('k1_current + k2_current * x : ', (k1_current + k2_current * x))
            
        try:
            common_part_4 = (k1_current + k2_current * x) ** k3_current
        except Exception as e:
            print('Exception #4')
            print('x : ', x)
            print('k3_current : ', k3_current)
            print('k1_current + k2_current * x : ', (k1_current + k2_current * x))
        
#         common_part_1 = -(2/N) * (y - (k1_current + k2_current * x) ** k3_current)
#         common_part_2 = (k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
#         common_part_3 = decimal.Decimal.ln( k1_current + k2_current * x)
#         common_part_4 = (k1_current + k2_current * x) ** k3_current
        k1_gradient += common_part_1 * common_part_2
        k2_gradient += common_part_1 * common_part_2 * x
        k3_gradient += common_part_1 * common_part_3 * common_part_4
        
#         k1_gradient += -(2/N) * (y - (k1_current + k2_current * x) ** k3_current) * (k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
#         k2_gradient += -(2/N) * (y - (k1_current + k2_current * x) ** k3_current) * (k3_current * (k1_current + k2_current * x) ** (k3_current - 1)) * x
#         k3_gradient += -(2/N) * (y - (k1_current + k2_current * x) ** k3_current) * np.log(k1_current + k2_current * x) * (k1_current + k2_current * x) ** k3_current
        if(dc.is_nan(k1_gradient) or dc.is_nan(k2_gradient) or dc.is_nan(k1_gradient) or
           dc.is_infinite(k1_gradient) or dc.is_infinite(k2_gradient) or dc.is_infinite(k1_gradient)): 
            print('   i=', i)
            print('   x = ', x, ',  y = ', y)
            print('   comPart_2_1 = ', (k3_current * (k1_current + k2_current * x)))
            print('   comPart_2_2 = ', (k3_current - 1))
            print('   comPart_2_3 = ', k3_current * (k1_current + k2_current * x) ** (k3_current - 1))
            print('   k1_cur=', k1_current, '  k2_cur=', k2_current, '  k3_cur=', k3_current)
            print('   common_part_1 = ', common_part_1)
            print('   common_part_2 = ', common_part_2)
            print('   common_part_3 = ', common_part_3)
            print('   k1_gradient = ', k1_gradient)
            print('   k2_gradient = ', k2_gradient) 
            print('   k3_gradient = ', k3_gradient, '\n')
            k1_gradient = 1001.0
            break
        
    new_k1 = k1_current - (learningRate * k1_gradient)
    new_k2 = k2_current - (learningRate * k2_gradient)
    new_k3 = k3_current - (learningRate * k3_gradient)
    return [new_k1, new_k2, new_k3, k1_gradient, k2_gradient, k3_gradient]
示例#59
0
   :synopsis: Main GUI program

.. requires decimal

.. Created on Fri Mar 29 14:58:02 2013
.. codeauthor::  Rod Persky <rodney.persky {removethis} AT gmail _DOT_ com>
.. Licensed under the Academic Free License ("AFL") v. 3.0
.. Source at https://github.com/Rod-Persky/pyIGES
"""


import decimal

this_context = decimal.BasicContext
this_context.prec = 8
decimal.setcontext(this_context)


def format_line(data, section):
    """concatinate data chuncks and add section marker and line counter

    :param data: list of values
    :type data: list

    :param section: letter for the corresponding IGES section
    :type section: string

    """
    out = ""

    for i in range(0, len(data)):
示例#60
0
 def run(self):
     c = decimal.getcontext().copy()
     c.prec = self.prec
     decimal.setcontext(c)
     self.q.put((self.prec, a * b))
     return