コード例 #1
0
ファイル: views.py プロジェクト: lijintaotzx/shopping_store
    def paying(self):
        """
        发起结算
        :return:
        """
        self.create_tcp_socket()
        request_data = "REQUEST {}".format(self.transform_shopping_cards())
        self.skfd.send(request_data.encode())
        status_code, msg = get_request(self.skfd.recv(1024).decode())

        if status_code == "200":
            self.send_shopping_cards()
            status_code, msg = get_request(self.skfd.recv(1024).decode())

            if status_code == "200":
                total_price = Decimal(
                    get_number_input("请输入付款金额:", is_float=True))
                if total_price < Decimal(msg):
                    print("金额不足")
                else:
                    request_data = "PAYING {}$${}".format(
                        self.transform_shopping_cards(), total_price)
                    self.skfd.send(request_data.encode())
                    status_code, msg = get_request(
                        self.skfd.recv(1024).decode())
                    print(msg)
                    # 清空购物车
                    self.shopping_cart.reset_product_list()
            else:
                self.aph.paying_error(msg)
        else:
            self.aph.paying_error(msg)
コード例 #2
0
    def get_balances(self):
        response = self.rest_client.get_balances()

        if response['success'] is True:
            internal_balances = []
            entries = response['result']
            for entry in entries:
                asset = entry['Currency']
                balance = Decimal(str(entry['Balance']))
                free = Decimal(str(entry['Available']))
                if balance > Decimal(0):
                    internal_balances.append({
                        'asset': asset,
                        'free': free,
                        'locked': balance - free
                    })

            self.notify_callbacks('account',
                                  account_type='balance',
                                  data=internal_balances)

            return internal_balances
        else:
            self.notify_callbacks('account',
                                  account_type='balances_failed',
                                  data={})
            return []
コード例 #3
0
 def get_fisher_value(f3, f4, q):
 return Decimal(abs(f.isf(q, f4,
f3))).quantize(Decimal('.0001')).__float__()
 f3 = (m - 1) * N
 f4 = N - d
 q = 0.05
 theoretical_y = numpy.array([regression_equation(row[0], row[1], row[2],
b_coefficients) for row in x_table])
 average_y = numpy.array(list(map(lambda el: numpy.average(el), y_table)))
 s_ad = m / (N - d) * sum((theoretical_y - average_y) ** 2)
 y_variations = numpy.array(list(map(numpy.var, y_table)))
 s_v = numpy.average(y_variations)
 f_p = float(s_ad / s_v)
 f_t = get_fisher_value(f3, f4, q)
 theoretical_values_to_print = list(
 zip(map(lambda x: "x1 = {0[1]:<10} x2 = {0[2]:<10} x3 =
{0[3]:<10}".format(x), x_table), theoretical_y))
 print("\nПеревірка адекватності моделі за критерієм Фішера: m = {}, N =
{} для таблиці y_table".format(m, N))
 print("Теоретичні значення y для різних комбінацій факторів:")
 print("\n".join(["{arr[0]}: y = {arr[1]}".format(arr=el) for el in
theoretical_values_to_print]))
 print("Fp = {}, Ft = {}".format(f_p, f_t))
 print("Fp < Ft => модель адекватна" if f_p < f_t else "Fp > Ft => модель
неадекватна")
 return True if f_p < f_t else False
コード例 #4
0
    def get_balances(self):
        response = self.rest_client.wallet_info()
        if response['result'] is True:
            internal_balances = []
            entries = response['info']['funds']['free'].keys()
            for entry in entries:
                asset = entry
                locked = Decimal(str(
                    response['info']['funds']['holds'][entry]))
                free = Decimal(str(response['info']['funds']['free'][entry]))
                if (locked > Decimal(0)) or (free > Decimal(0)):
                    internal_balances.append({
                        'asset': asset,
                        'free': free,
                        'locked': locked
                    })

            self.notify_callbacks('account',
                                  account_type='balance',
                                  data=internal_balances)

            return internal_balances
        else:
            self.notify_callbacks('account',
                                  account_type='balances_failed',
                                  data={})
            return []
コード例 #5
0
ファイル: orders.py プロジェクト: basetwode/cypetulip
    def recalculate_price(self):

        tax_rate = self.get_product_tax_rate() + 1
        price = self.get_product_price_b(
        )  # either normal or special net price
        price_wt = round(price * tax_rate)
        price_discounted = price
        price_discounted_wt = round(price_discounted * tax_rate)
        applied_discount = 0

        if self.is_discount_eligible:
            if self.order_detail.discount_percentage:
                price_discounted = Decimal(price) - round(
                    price * self.order_detail.discount_percentage)
                price_discounted_wt = round(price_discounted *
                                            Decimal(tax_rate))
                applied_discount = price_wt - price_discounted_wt
            elif self.order_detail.discount_amount:
                price_discounted = Decimal(price) - Decimal(self.order_detail.discount_amount) \
                    if self.order_detail.discount_amount < self.price else self.price
                price_discounted_wt = round(price_discounted *
                                            Decimal(tax_rate))
                applied_discount = price_wt - price_discounted_wt

        self.price = price
        self.price_wt = price_wt
        self.price_discounted = price_discounted
        self.price_discounted_wt = price_discounted_wt
        self.applied_discount = applied_discount
        self.tax_rate = self.tax_rate if self.tax_rate else self.product.tax * 100
コード例 #6
0
ファイル: mope6.py プロジェクト: dammmula/mope
    def get_cochran_value(f1, f2, q):

        partResult1 = q / f2
        params = [partResult1, f1, (f2 - 1) * f1]
        fisher = f.isf(*params)
        result = fisher / (fisher + (f2 - 1))
        return Decimal(result).quantize(Decimal('.0001')).__float__()
コード例 #7
0
ファイル: views.py プロジェクト: chan3256995/pythonprojects2
    def post(self, request, *args, **kwargs):
        print(request.data)
        try:
            ret = {'code': "1000", 'message': ""}
            d = request.data
            items = d.dict()
            req_data = {}
            for key in items.keys():
                req_data = eval(key)
                break
            # req_data = {"pay":"Ali","uid":"2088012229532543","mark":"1574483704625_12_最初_17pay","money":"50.00","tradeNo":"201909182000400111005400396189"}
            trade_info = trade_models.TradeInfo.objects.filter(
                recharge_number=req_data.get("tradeNo")).first()
            # 如果该支付订单存在则自动审核
            if trade_info is not None:
                if Decimal(str(trade_info.trade_money)) == Decimal(
                        str(req_data.get(
                            "money"))) and trade_info.is_pass is False:
                    back_utils.recharge_pass(trade_info.trade_number)
                    ret['code'] = "1000"
                    ret['message'] = '提交成功'
                    return Response(status=200, data=ret)
                else:
                    ret['code'] = "1001"
                    ret['message'] = '提交失败'
                    logger.info('%s url:%s method:%s' %
                                ("数据库存在该订单 自动审核发现金额不一致或者已经审核通过", request.path,
                                 request.method))
                    return Response(status=400, data=ret)

            if req_data != {}:
                if self.save_pay_info(req_data):
                    trade_info = trade_models.TradeInfo.objects.filter(
                        recharge_number=req_data.get("tradeNo")).first()
                    back_utils.recharge_pass(trade_info.trade_number)
                    ret['code'] = "1000"
                    ret['message'] = '提交成功'
                    return Response(status=200, data=ret)
                else:
                    ret['code'] = "1001"
                    ret['message'] = '提交失败'
                    print("数据库存在该订单 自动审核发现金额不一致或者已经审核通过")
                    logger.info('%s url:%s method:%s' %
                                ("数据库存在该订单 自动审核发现金额不一致或者已经审核通过", request.path,
                                 request.method))
                    return Response(status=400, data=ret)
            else:
                ret['code'] = "1001"
                ret['message'] = '提交失败'
                print("提交数据空")
                return Response(status=400, data=ret)

        except:
            traceback.print_exc()
            logger.info('%s url:%s method:%s' %
                        (traceback.format_exc(), request.path, request.method))
            ret['code'] = "1001"
            ret['message'] = '提交失败'
            return Response(status=400, data=ret)
        return Response(status=200, data=ret)
コード例 #8
0
 def get_student_value(f3, q):
 return Decimal(abs(t.ppf(q / 2,
f3))).quantize(Decimal('.0001')).__float__()
 print("\nПеревірка значимості коефіцієнтів регресії за критерієм
Стьюдента: m = {}, N = {} ".format(m, N))
 average_variation = numpy.average(list(map(numpy.var, y_table)))
 variation_beta_s = average_variation / N / m
 standard_deviation_beta_s = math.sqrt(variation_beta_s)
 t_i = numpy.array([abs(beta_coefficients[i]) / standard_deviation_beta_s
for i in range(len(beta_coefficients))])
 f3 = (m - 1) * N
 q = 0.05
 t_our = get_student_value(f3, q)
 importance = [True if el > t_our else False for el in list(t_i)]
 # print result data
 print("Оцінки коефіцієнтів βs: " + ", ".join(list(map(lambda x:
str(round(float(x), 3)), beta_coefficients))))
 print("Коефіцієнти ts: " + ", ".join(list(map(lambda i:
"{:.2f}".format(i), t_i))))
 print("f3 = {}; q = {}; tтабл = {}".format(f3, q, t_our))
 beta_i = ["β0", "β1", "β2", "β3", "β12", "β13", "β23", "β123", "β11",
"β22", "β33"]
 importance_to_print = ["важливий" if i else "неважливий" for i in
importance]
 to_print = map(lambda x: x[0] + " " + x[1], zip(beta_i,
importance_to_print))
 print(*to_print, sep="; ")
 print_equation(beta_coefficients, importance)
 return importance
コード例 #9
0
ファイル: wallet.py プロジェクト: zhanjiahuan/digrccy
 def query_records(self, address, records, new_records, last_timestamp,
                   start_block, end_block):
     for record in records:
         propertyid = record.get('propertyid')
         valid = record.get('valid')
         block = record.get('block')
         if valid and int(propertyid) == 31 and int(start_block) <= int(
                 block) and int(block) <= int(end_block):
             to_address = record['referenceaddress']  # 是否为收款记录
             current_timestamp = int(record['blocktime'])  # 当前记录时间戳
             confirmations = int(record['confirmations'])  # 交易记录确认数
             record_hash = record['txid']
             amount = Decimal(record['amount'])
             if to_address.lower() != address.lower():
                 continue
             if int(last_timestamp) > int(current_timestamp):
                 continue
             if Order.hash_is_exist(record_hash):
                 continue
             if amount < Decimal('0.0000001'):
                 continue
             if confirmations < 2:
                 break
             else:
                 new_records.append(record)
         else:
             if records is None:
                 logging.error(
                     'Request USDT_TX_API fail address:{} ret:{}, url:{}'.
                     format(address, str(records), self.USDT_TX_API))
     return new_records
コード例 #10
0
ファイル: views.py プロジェクト: RobinLenin/siaa
def cuenta_cobrar_crear(request):
    id = request.POST.get('id')
    fecha_emision = request.POST.get('fecha_emision')
    date = parse_date(fecha_emision)
    interes = CuentaCobrarAppService.calcular_saldo(Decimal(request.POST.get('monto')), int(date.year), int(date.month),
                                                    int(date.day))

    request.POST._mutable = True
    request.POST['interes'] = Decimal(round(interes, 2))
    request.POST._mutable = False

    if id:
        cuenta_cobrar = get_object_or_404(CuentaCobrar, id=id)
    else:
        cuenta_cobrar = CuentaCobrar()

    cuenta_cobrar_form = CuentaCobrarForm(request.POST, instance=cuenta_cobrar)

    if cuenta_cobrar_form.is_valid():
        cuenta_cobrar_form.save()
        messages.success(request, MensajesEnum.ACCION_GUARDAR.value)

    else:
        messages.warning(request, cuenta_cobrar_form.errors)

    return redirect('tesoreria:cuenta_cobrar_listar')
コード例 #11
0
def summary(request, pk):
    customer = get_object_or_404(Customer, pk=pk)
    customers = Customer.objects.filter(created_date__lte=timezone.now())
    services = Service.objects.filter(cust_name=pk)
    products = Product.objects.filter(cust_name=pk)
    sum_service_charge = \
        Service.objects.filter(cust_name=pk).aggregate(Sum('service_charge'))
    sum_product_charge = \
        Product.objects.filter(cust_name=pk).aggregate(Sum('charge'))

    # if no product or service records exist for the customer,
    # change the ‘None’ returned by the query to 0.00
    sum = sum_product_charge.get("charge__sum")
    if sum == None:
        sum_product_charge = {'charge__sum': Decimal('0')}
    sum = sum_service_charge.get("service_charge__sum")
    if sum == None:
        sum_service_charge = {'service_charge__sum': Decimal('0')}

    return render(
        request, 'crm/summary.html', {
            'customer': customer,
            'products': products,
            'services': services,
            'sum_service_charge': sum_service_charge,
            'sum_product_charge': sum_product_charge,
        })
コード例 #12
0
 def do_paying(self, connfd, request_data):
     """
     处理用户支付
     :param connfd: socket连接
     :param request_data:shopping_cards_msg user_pay_money
     :return:
     """
     shopping_cards_msg, user_pay_money = request_data.split("$$")
     total_amount = self.sum_shopping_cards_amount(
         eval(shopping_cards_msg)["shopping_cards"])
     money_return = Decimal(user_pay_money) - Decimal(
         total_amount)  # 计算找零金额
     if money_return >= 0:
         # 结算、减库存
         pay_result = self.reduce_product_count(eval(shopping_cards_msg))
         if len(pay_result.get("success_list", False)):
             # 创建订单记录
             order_id = self.commit_record(pay_result)
             # 打印小票
             ticket_msg = self.export_ticket(order_id, pay_result,
                                             total_amount, user_pay_money,
                                             money_return)
             self.success_send(connfd, ticket_msg)
             # print("{}结算完成".format(self.user_name))
         else:
             # 结算内容全部失败
             self.fail_send(connfd, "订单库存被抢付,支付失败。")
     else:
         self.fail_send(connfd, "支付金额不足!")
コード例 #13
0
    def test_import_communicatie(self):
        kvk_vestiging = kvk.KvkVestiging.objects.create(
            vesid=Decimal('100000000000000000'),
            maatschappelijke_activiteit_id=Decimal('999999999999999999'),
            vestigingsnummer='000033333333',
            eerstehandelsnaam='Onderneming B.V.',
            typeringvestiging='CVS',
            statusobject='Bevraagd',
            veshibver=0,
            nummer1='0206666666',
            soort1='Telefoon',
            toegangscode1=31,
        )
        vestiging = self._convert(kvk_vestiging)

        comm = list(vestiging.communicatiegegevens.all())
        self.assertIsNotNone(comm)
        self.assertNotEqual([], comm)

        c = comm[0]
        self.assertIsNone(c.domeinnaam)
        self.assertIsNone(c.emailadres)
        self.assertEqual('31', c.toegangscode)
        self.assertEqual('0206666666', c.communicatie_nummer)
        self.assertEqual('Telefoon', c.soort_communicatie_nummer)
コード例 #14
0
    def __init__(self, data, cancelled=False):
        """
        Redis money manager.
        Manages money of user for each order that was modified/created
        :param data - order dict with changed/current price and/or quantity
        """
        try:
            self.user_id = data['user_id']
            self.side = data['side']
            self.order_type = data['order_type']
            self.traded_price = Decimal(data['price'])
            self.traded_quantity = Decimal(data['quantity'])
            self.total_quantity = self.traded_price * self.traded_quantity
            main_curr, second_curr = data['pair'].split('_')
            self.curr = main_curr if self.side == 'bid' else second_curr
            self.counter_curr = second_curr if self.side == 'bid' else main_curr
            self.bid_commission = self.total_quantity * Decimal(
                settings.DEFAULT_COMMISSION)
            self.ask_commission = self.traded_quantity * Decimal(
                settings.DEFAULT_COMMISSION)

            # Если ордер отменяется,
            # то traded_quantity - это и есть нынешний объем ордера
            if cancelled and self.traded_quantity != Decimal(
                    data['initial_quantity']):
                self.quantity_triggered = True
        except Exception as e:
            log.exception(f"Error occurred - {e}")
コード例 #15
0
 def __init__(self, raw_data):
     self.raw_data = raw_data
     self.name = self.raw_data.name
     self.cash_return = 0
     self.close_freq = 0
     self.close_reason = ""
     self.cost = 0
     self.__opened = False
     self.closed = False
     self.curr_freq = 0
     self.max_return = 0
     self.max_return_cash_value = Decimal("0")
     self.max_return_freq = 0
     self.max_draw = Decimal("0")
     self.max_draw_cash_value = Decimal("0")
     self.max_draw_freq = 0
     self.max_draw_from_previous_high = 0
     self.max_draw_from_previous_high_freq = 0
     self.__curr_return = 0
     self.start_time = None
     self.start_price = None
     self.shares = 0
     self.initial_capital = None
     self.__curr_time = None
     self.curr_price = None
     self.curr_value = 0
コード例 #16
0
ファイル: supplychain.py プロジェクト: pidipy/supplychainpy
def main():
    start_time = time.time()

    orders_analysis = model_inventory.analyse_orders_abcxyz_from_file(
        file_path="data.csv",
        z_value=Decimal(1.28),
        reorder_cost=Decimal(5000),
        file_type="csv")

    sim = simulate.run_monte_carlo(orders_analysis=orders_analysis.orders,
                                   runs=1,
                                   period_length=12)

    sim_window = simulate.summarize_window(simulation_frame=sim,
                                           period_length=12)

    sim_frame = simulate.summarise_frame(sim_window)

    optimised = simulate.optimise_service_level(
        service_level=95.0,
        frame_summary=sim_frame,
        orders_analysis=orders_analysis.orders,
        runs=1,
        percentage_increase=1.30)
    for s in optimised:
        print(s.orders_summary())

    end_time = time.time()
    elapsed = end_time - start_time
    print(elapsed)
コード例 #17
0
ファイル: utils.py プロジェクト: t0n/fpv-velocidrone-ua-bot
def compare_leaderboards(old, new):
    updates = []
    for new_record in new:
        old_record_found = False
        # Update: sometimes there are 2 records by same player but different versions, so we need to dedup
        for old_record in old:

            if old_record['name'] == new_record['name'] and old_record[
                    'version'] == new_record['version']:
                old_record_found = True
                if Decimal(new_record['time']) < Decimal(old_record['time']):
                    updates.append({
                        'record':
                        new_record,
                        'improved_time':
                        str(
                            Decimal(old_record['time']) -
                            Decimal(new_record['time'])),
                        'improved_position':
                        old_record['position'],
                    })
        if not old_record_found:
            updates.append({
                'record': new_record,
            })

    print('updates: ' + str(updates))
    return updates
コード例 #18
0
    def get_our_orders_by_decimal_price(self):
        our_orders_by_price = {'bids': {}, 'asks': {}}

        open_orders_copy = self.open_orders.copy()

        for order in open_orders_copy:
            order['price'] = Decimal(str(order['price']))
            order['quantity'] = Decimal(str(order['quantity']))
            order['cum_quantity_filled'] = Decimal(
                str(order['cum_quantity_filled']))
            if order['side'] == 'buy':
                if str(order['price']) not in our_orders_by_price['bids']:
                    our_orders_by_price['bids'][order['price']] = order[
                        'quantity'] - order['cum_quantity_filled']
                else:
                    our_orders_by_price['bids'][order['price']] += order[
                        'quantity'] - order['cum_quantity_filled']
            elif order['side'] == 'sell':
                if str(order['price']) not in our_orders_by_price['bids']:
                    our_orders_by_price['asks'][order['price']] = order[
                        'quantity'] - order['cum_quantity_filled']
                else:
                    our_orders_by_price['asks'][order['price']] += order[
                        'quantity'] - order['cum_quantity_filled']

        return our_orders_by_price
コード例 #19
0
    def predict_SubGenre(cls, raw_text: str) -> list:
        """Predict the sub genre label(s) on an unstructured text document.

        Parameters
        ----------
        raw_text : str
            The unstructured text document

        Returns
        -------
        list
            A list of classes and their probability distributions

        Notes
        -----
        Given text must have a significant portion as fantasy
        """
        lblbinarizer = FileManager.read("MultiLabelBinarizer.pickle")

        classifier = cls.load(ClassifierType.MultiClass)
        #p = classifier.predict([raw_text])
        #return lblbinarizer.inverse_transform(p)
        pscores = classifier.predict_proba([raw_text])
        pscores = [
            float(Decimal(p).quantize(Decimal('1.111'), rounding=ROUND_UP))
            for p in pscores[0]
        ]
        prob_map = list(zip(lblbinarizer.classes_, pscores))

        return prob_map
コード例 #20
0
ファイル: state.py プロジェクト: AlephC/QRL
 def total_coin_supply(self):
     # FIXME: This is temporary code. NOT SCALABLE. It is easy to keep a global count
     coins = Decimal(0)
     address_state = qrl_pb2.AddressState()
     for k, v in self.db.RangeIter(b'Q', b'Qz'):
         address_state.ParseFromString(v)
         coins = coins + Decimal(address_state.balance)        # FIXME: decimal math?
     return coins
コード例 #21
0
ファイル: views.py プロジェクト: RobinLenin/siaa
def abono_eliminar(request, id):
    abono = get_object_or_404(Abono, id=id)
    cuenta_cobrar = CuentaCobrar.objects.get(id=str(abono.cuenta_cobrar_id))
    monto = abono.monto
    interes_abono = abono.interes
    diferencia = monto - interes_abono
    saldo = cuenta_cobrar.saldo
    total = saldo + diferencia
    ultimo_abono = Abono.objects.filter(cuenta_cobrar=cuenta_cobrar).last()

    if ultimo_abono.id == abono.id:
        try:
            interes_mensual = InteresMensual.objects.get(cuenta_cobrar=cuenta_cobrar,
                                                         fecha_fin__year=abono.fecha_pago.year,
                                                         fecha_fin__month=abono.fecha_pago.month)

            intereses_mensuales = InteresMensual.objects.filter(cuenta_cobrar=cuenta_cobrar,
                                                                fecha_fin__gt=abono.fecha_pago).order_by('fecha_fin')
        except interes_mensual.DoesNotExist:
            interes_mensual = None
            intereses_mensuales = None

        if not interes_mensual == None:
            interes = (((Decimal(total) * Decimal(interes_mensual.tasa.tasa)) / 100))
            InteresMensual.objects.values('valor').filter(id=interes_mensual.id).update(valor=interes)
            interes_cuenta = 0

            for interesmensual in intereses_mensuales:

                if interesmensual.id != interes_mensual.id:
                    interes_mes = (total * interesmensual.tasa.tasa) / 100
                    InteresMensual.objects.values('valor').filter(id=interesmensual.id).update(valor=interes_mes)

            intereses_mensuales = InteresMensual.objects.filter(cuenta_cobrar=cuenta_cobrar)

            for interesmensual in intereses_mensuales:
                interes_cuenta = interes_cuenta + interesmensual.valor

            CuentaCobrar.objects.values('interes').filter(id=abono.cuenta_cobrar.id).update(saldo=total,
                                                                                            interes=interes_cuenta)

        if total > 0:
            CuentaCobrar.objects.values('estado').filter(id=abono.cuenta_cobrar_id).update(estado=True)

        try:
            if abono.delete():
                messages.success(request, MensajesEnum.ACCION_ELIMINAR.value)
                return redirect('tesoreria:cuenta_cobrar_detalle', abono.cuenta_cobrar_id)
            else:
                messages.warning(request, MensajesEnum.ACCION_ELIMINAR_ERROR.value)
                return redirect('tesoreria:cuenta_cobrar_detalle', id)
        except Exception as e:
            messages.warning(request, str(e))
            return HttpResponseServerError(render(request, '500.html'))
    else:
        messages.warning(request, "Solo puedes eliminar el úlmino abono")
        return redirect('tesoreria:cuenta_cobrar_detalle', abono.cuenta_cobrar_id)
コード例 #22
0
ファイル: tests.py プロジェクト: bulean/djangoTestProject
 def test_decrease_balance_on_account(self):
     account = Account.objects.get(pk=1)
     AccountService().decrease_balance_on_account(account, 10)
     self.assertEquals(account.balance, 90)
     AccountService().decrease_balance_on_account(account, 0)
     self.assertEquals(account.balance, 90)
     AccountService().decrease_balance_on_account(account, 0.01)
     self.assertEquals(account.balance,
                       Decimal(89.99).quantize(Decimal("1.00")))
コード例 #23
0
def refund_tuikuan_bl(order_goods_item):
    try:
        ret = {'code': "error", 'message': ''}
        order_number = order_goods_item['order_number']
        mainid = order_goods_item['order_id']
        sonid = order_goods_item['order_goods_id']

        result = login()
        if result.get('code') == "ok":
            page_parms = init_order_page_parms(result.get('cookies'))
            parms = page_parms.get("parms")

            parms['ctl00$ContentPlaceHolder1$txtOrderNum'] = order_number
            parms['ctl00$ContentPlaceHolder1$btnSearch'] = '查 询'
            parms['ctl00$ContentPlaceHolder1$txtPageSize'] = '20'
            res = load_order_list(result.get('cookies'), parms)

            order_info_list = res['order_info_list']
            if len(order_info_list) > 0:
                # bl 网站没有goods_id 做标记 多个商品的订单暂不支持申请
                if len(order_info_list[0]['order_goods_list']) > 1:
                    ret['code'] = 'error'
                    ret['message'] = '该订单暂不支持申请'
                    return ret
                order_info = order_info_list[0]['order_goods_list'][0]
                if order_info['status'] == '正常':
                    url = '/User/TuiKuan.aspx?sonid=' + order_info[
                        'sonid'] + '&mainid=' + order_info['mainid']
                    refund_parms = get_page_params(url, result.get('cookies'))
                    refund_parms[
                        '__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$btnAdd'
                    refund_parms['__EVENTARGUMENT'] = ''
                    refund_parms[
                        'ctl00$ContentPlaceHolder1$txtTuiKuanShuoMing'] = ''
                    refund_parms['total'] = Decimal(
                        float(order_info['goods_price'])) * Decimal(
                            float(order_info['goods_count']))

                    refund_result = go_refund_tuikuan(refund_parms,
                                                      result.get('cookies'),
                                                      url)
                    if refund_result['code'] == 'ok':
                        ret['code'] = 'ok'
                        ret['message'] = '申请成功'
                    print(refund_parms)
                else:
                    ret['code'] = 'error'
                    ret['message'] = '状态不允许申请仅退款'
            else:
                ret['code'] = 'error'
                ret['message'] = '未找到该订单'
    except:
        print(traceback.format_exc())
        logger.info('%s bl 申请退款失败 ' % (traceback.format_exc()))
        ret['code'] = 'error'
        ret['message'] = '申请失败'
    return ret
コード例 #24
0
def simulation(runs: int = None):
    try:
        database_path = ''
        file_name = ''
        sim_results = []
        sim_summary_results = []
        inventory = []

        if runs is not None:
            config = deserialise_config(ABS_FILE_PATH_APPLICATION_CONFIG)
            database_path = config['database_path']
            file_name = config['file']
            file_path = database_path.replace(
                ' ', '') + '/' + (file_name.replace(' ', ''))
            analysed_orders = analyse(file_path=str(file_path),
                                      z_value=Decimal(1.28),
                                      reorder_cost=Decimal(5000),
                                      file_type=FileFormats.csv.name,
                                      length=12,
                                      currency='USD')
            # run the simulation, populate a database and then retrieve the most current values for the simulation page.
            try:
                with ThreadPoolExecutor(max_workers=1) as executor:
                    sim = executor.submit(simulate.run_monte_carlo,
                                          orders_analysis=analysed_orders,
                                          runs=runs,
                                          period_length=12)
                    sim_results = sim.result()
                    sim_window = executor.submit(simulate.summarize_window,
                                                 simulation_frame=sim_results,
                                                 period_length=12)
                    sim_window_result = sim_window.result()
                    sim_summary = executor.submit(simulate.summarise_frame,
                                                  sim_window_result)
                    sim_summary_results = sim_summary.result()
                    store_simulation(sim_summary_results)
                inventory = db.session.query(MasterSkuList).all()

            except OSError as e:
                print(e)
        elif runs is None and request.method == 'GET':
            try:
                sim_summary_results = select_last_simulation()
                inventory = db.session.query(MasterSkuList).all()
            except AttributeError as e:
                pass

        return flask.render_template('simulation.html',
                                     db=database_path,
                                     file_name=file_name,
                                     sim=sim_summary_results,
                                     runs=sim_results,
                                     inventory=inventory)
    except OSError:
        abort(404)
コード例 #25
0
ファイル: PLPPage.py プロジェクト: pramod7019/ui_tests
 def get_plp_final_product_prices(self):
     final_prices = []
     for price in self.get_plp_product_prices():
         if '\n' in price:
             sale_price = price.split('\n')[1]
             final_prices.append(Decimal(re.sub(r'[^\d.]', '', sale_price)))
         elif price == "Sold out":
             continue
         else:
             final_prices.append(Decimal(re.sub(r'[^\d.]', '', price)))
     return final_prices
コード例 #26
0
 def test_decimal_for_string(self):
     self.assertEqual(decimal_for_string('£1.00'), Decimal('1.00'))
     self.assertEqual(decimal_for_string('£0.99'), Decimal('0.99'))
     self.assertEqual(decimal_for_string('£x'), None)
     self.assertEqual(decimal_for_string('£0.99p'), None)
     self.assertEqual(decimal_for_string('£'), None)
     self.assertEqual(decimal_for_string(''), None)
     self.assertEqual(decimal_for_string('one'), None)
     self.assertEqual(decimal_for_string('1'), Decimal('1.00'))
     self.assertEqual(decimal_for_string('1.99'), Decimal('1.99'))
     self.assertEqual(decimal_for_string('1000.99'), Decimal('1000.99'))
     self.assertEqual(decimal_for_string('1,000.99'), None)
コード例 #27
0
 def post(self, request, *args, **kwargs):
     if not request.user.is_authenticated:
         return Response(data={'msg':'User not logged in'},status=403)
     account = get_object_or_404(Account, uuid=request.data['account_id'])
     serializer = TransactionSerializer(data=request.data)
     if not serializer.is_valid():
         return Response(serializer.error_messages,status=400)
     new_balance = Decimal(account.balance) + Decimal(request.data['amount'])
     with transaction.atomic():
         serializer.save(account=account)
         account.balance = new_balance
         account.save()
         return Response(status=201)
コード例 #28
0
ファイル: serializers.py プロジェクト: GarryGon4ar/freelance
 def validate(self, data):
     with transaction.atomic():
         user = self.context['request'].user
         if data['award'] > user.balance:
             raise serializers.ValidationError(
                 "У вас недостаточно средств, чтобы создать таск.")
         elif user.balance < user.expenses + Decimal(data['award']):
             raise serializers.ValidationError(
                 "Пожалуйста пополните баланс или назначьте меньшую сумму за таск."
             )
         user.expenses = (F('expenses') + Decimal(data['award']))
         user.save()
         return data
コード例 #29
0
def calculate(n, m):
    output = 0
    for i in range(-10, m + 1):

        loop_result = 0

        for j in range(1, n + 1):
            result = (i + j) ** 3
            result = Decimal(result) // Decimal(j ** 2)

            loop_result += result

        output += loop_result
    return output
コード例 #30
0
    def products_for_url(cls, url, category=None, extra_args=None):
        session = session_with_proxy(extra_args)
        soup = BeautifulSoup(
            session.get(url, verify=False).text, 'html.parser')

        name = soup.find('h1').text.strip()
        pricing_container = soup.find('div', 'wrap-product-shop')

        sku = pricing_container.find('p').text.split(':')[1].strip()

        price = Decimal(
            remove_words(
                pricing_container.find('p', 'special-price').find(
                    'span', 'price').contents[0]))

        price *= Decimal('1.19')
        normal_price = price.quantize(0)
        offer_price = normal_price

        description_ids = [
            'tab-descripcion', 'tab-adicional', 'tab-ficha_tecnica'
        ]

        descriptions = []
        for descrption_id in description_ids:
            tag = soup.find('div', {'id': descrption_id})
            if tag:
                descriptions.append(html_to_markdown(str(tag)))

        description = '\n\n'.join(descriptions)

        picture_urls = [tag['href'] for tag in soup.findAll('a', 'colorbox')]

        p = Product(name,
                    cls.__name__,
                    category,
                    url,
                    url,
                    sku,
                    -1,
                    normal_price,
                    offer_price,
                    'CLP',
                    sku=sku,
                    description=description,
                    picture_urls=picture_urls)

        return [p]