示例#1
0
def dev_step(dev_data):
    print("test the model")
    model.eval()
    predict_entity=[]
    gold_entity=[]
    origin=0.
    found=0.
    correct=0.
    for j in range(0,len(dev_data),config.batch_size):
        batch = dev_data[j:j + config.batch_size]
        sentence_tensor, tags_tensor, length_tensor = get_batch(batch)
        _,paths=model(sentence_tensor,length_tensor)
        for sentence,tags ,path,length in zip(sentence_tensor,tags_tensor,paths,length_tensor):
            sentence=sentence[:length]
            tags=tags[:length]
            sentence=list(sentence.cpu().numpy())
            tags=list(tags.cpu().numpy())
            predict_entity=utils.calculate(sentence,path,config.id2words,config.id2tags)
            gold_entity=utils.calculate(sentence,tags,config.id2words,config.id2tags)
            origin+=len(gold_entity)
            found+=len(predict_entity)
            for p_tag in predict_entity:
                if p_tag in gold_entity:
                    correct+=1

    p=0. if found==0 else (correct/found)
    r=0. if origin==0 else (correct/origin)
    f1=0. if p+r==0 else (2*p*r)/(p+r)
    print("precision : %.3f , recall : %.3f , f1 : %.3f " % (p,r,f1))
    return f1
示例#2
0
    def test_calculate_case_subtract(self):
        test_data = [
            {"op1": 1, "op2": 2, "operator": "-", "output": -1},
            {"op1": -7, "op2": 15, "operator": "-", "output": -22}
        ]

        for test_case in test_data:
            self.assertAlmostEqual(calculate(test_case["op1"], test_case["op2"],
                                             test_case["operator"]),
                                   test_case["output"])
示例#3
0
    def test_calculate_case_divide(self):
        test_data = [
            {"op1": 5, "op2": 3, "operator": "/", "output": 1.66666666667},
            {"op1": -7, "op2": 15, "operator": "/", "output": -0.46666666666}
        ]

        for test_case in test_data:
            self.assertAlmostEqual(calculate(test_case["op1"], test_case["op2"],
                                             test_case["operator"]),
                                   test_case["output"])
示例#4
0
    def test_calculate_case_add(self):
        test_data = [
            {"op1": 1, "op2": 2, "operator": "+", "output": 3},
            {"op1": -7, "op2": 15, "operator": "+", "output": 8}
        ]

        for test_case in test_data:
            self.assertAlmostEqual(calculate(test_case["op1"], test_case["op2"],
                                             test_case["operator"]),
                                   test_case["output"])
示例#5
0
    def test_calculate_case_multiply(self):
        test_data = [
            {"op1": 1, "op2": 2, "operator": "*", "output": 2},
            {"op1": -7, "op2": 15, "operator": "*", "output": -105}
        ]

        for test_case in test_data:
            self.assertAlmostEqual(calculate(test_case["op1"], test_case["op2"],
                                             test_case["operator"]),
                                   test_case["output"])
示例#6
0
def calc():
    if request.method == 'GET':
        return 'Hello, World!'

    if request.method == 'POST':
        data = request.get_json()
        a = data['op1']
        b = data['op2']
        operator = data['op']

        if operator not in ('+', '-', '/', '*'):
            return 'Unexpected Operator!!'
        else:
            result = calculate(a, b, operator)
            return jsonify({'result': result})
示例#7
0
def create_pago(sender, instance, created, *args, **kwargs):
	curso = instance.curso

	if created and instance.method == 'deposit':
		send_mail('curso_info', { 'curso': curso }, 'Informacion para realizar pago al %s de Mejorando.la INC' % curso.nombre, instance.email)

	if instance.charged and not instance.sent:
		vs = calculate(int(instance.quantity), curso.precio)

		vs['curso'] = curso
		vs['pago']  = instance

		send_mail('curso_pago', vs, 'Gracias por tu pago al %s de Mejorando.la INC' % curso.nombre, instance.email)

		instance.sent = True
		instance.save()
示例#8
0
def draw(x, y):
    for _ in range(10):
        c=0.0
        scaleX = 99
        scaleY = 59

        x, y = calculate(x, y, random.random(), fern_type[fern])

        if fern == 'mutant':
            c = -80
            scaleX = 130
            scaleY = 70

        X, Y = x*scaleX, y*scaleY
        pygame.draw.circle(display, GREEN,
            [int(WINDOW[0]//2 - 20 + X) , int(WINDOW[1] - Y + c)], 0)
    pygame.display.update()
    return x, y
示例#9
0
def calc():
    if request.method == 'GET':
        return 'Hello, World!'

    if request.method == 'POST':
        data = request.get_json()
        try:
            a = data['op1']
            b = data['op2']
            operator = data['op']

            if operator not in ('+', '-', '/', '*'):
                return 'Unexpected Operator!!'
            else:
                result = calculate(a, b, operator)
                return jsonify({'result': result})

        except KeyError:
            return 'Please provide the required arguments.', 400
示例#10
0
def create_pago(sender, instance, created, *args, **kwargs):
    curso = instance.curso

    if created and instance.method == 'deposit':
        send_mail(
            'curso_info', {'curso': curso},
            'Informacion para realizar pago al %s de Mejorando.la INC' %
            curso.nombre, instance.email)

    if instance.charged and not instance.sent:
        vs = calculate(int(instance.quantity), curso.precio)

        vs['curso'] = curso
        vs['pago'] = instance

        send_mail(
            'curso_pago', vs,
            'Gracias por tu pago al %s de Mejorando.la INC' % curso.nombre,
            instance.email)

        instance.sent = True
        instance.save()
示例#11
0
def calc():
    my_client = pymongo.MongoClient("mongodb://localhost:27017/")
    db = my_client["test_database"]
    col = db['last_operation']

    if request.method == 'GET':
        records = [doc for doc in col.find(projection={'_id': 0})]
        no_of_documents = col.count_documents({})
        return jsonify({'records': records, 'total records': no_of_documents})

    if request.method == 'POST':
        data = request.get_json()
        a = data['op1']
        b = data['op2']
        operator = data['op']

        if operator not in ('+', '-', '/', '*'):
            return 'Unexpected Operator!!'
        else:
            result = calculate(a, b, operator)
            condition = {'operator': operator}
            updated_result = {"$set": {'op1': a, 'op2': b, 'result': result}}
            record = col.update_one(condition, updated_result, upsert=True)
            return 'Result inserted successfully !!'
def start_services_terminals(services, slack_client):
	config = load_config()
	channel = config['slack']['channels']['server']
	project = config['project']

	# Calculate the needed x,y for terminals
	calculate()

	slack_client.api_call(
		"chat.postMessage",
		channel=channel['id'],
		text="Beginning 'docker-compose up' for %s" % (services),
		icon_emoji=':robot_face:'
	)
	if services == 'all':
		services = project['services']
	else:
		names = re.split(',', services)
		services = []
		for service in project['services']:
			if service['name'] in names:
				services.append(service)
	errors = []
	t_width = project['t_size']['width']
	t_height = project['t_size']['height']
	window = config['display']['window']
	for service in services:
		geometry = "%sx%s+%s+%s" % (t_width, t_height, (service['t_x'] + window['leftPadding']), (service['t_y'] + window['topPadding']))
		command = 'cd %s/%s; %s' % (project['dir'], service['dir'], 'docker-compose up; exit; exec $SHELL')
		script = 'sudo gnome-terminal --geometry %s -- sh -c "%s"' % (geometry, command)
		slack_client.api_call(
			"chat.postMessage",
			channel=channel['id'],
			text="Beginning 'docker-compose up' for %s" % (service['name']),
			icon_emoji=':robot_face:'
		)
		if os.system(script) != 0:
			errors.append(service['name'])
			slack_client.api_call(
				"chat.postMessage",
				channel=channel['id'],
				text="Error running 'docker-compose up' for %s" % (service['name']),
				icon_emoji=':robot_face:'
			)
		else:
			slack_client.api_call(
				"chat.postMessage",
				channel=channel['id'],
				text="Successful 'docker-compose up' for %s" % (service['name']),
				icon_emoji=':robot_face:'
			)
	if len(errors) != 0:
		slack_client.api_call(
			"chat.postMessage",
			channel=channel['id'],
			text="Error running 'docker-compose up' for %s" % (errors),
			icon_emoji=':robot_face:'
		)
		return False
	else:
		slack_client.api_call(
			"chat.postMessage",
			channel=channel['id'],
			text="Successful ran 'docker-compose up'",
			icon_emoji=':robot_face:'
		)
		return True
示例#13
0
def test(args, processor, tokenizer, model, device, domains, tags_list):
    if args.model is not None:
        model = torch.load(args.model)
        logging.info("Load model:" + args.model)
    elif os.path.exists(os.path.join(args.output_dir, 'checkpoint-best.pkl')):
        model = torch.load(os.path.join(args.output_dir, 'checkpoint-best.pkl'))
        logging.info("Load model:" + os.path.join(args.output_dir, 'checkpoint-best.pkl'))
    elif os.path.exists(os.path.join(args.output_dir, 'checkpoint-last.pkl')):
        model = torch.load(os.path.join(args.output_dir, 'checkpoint-last.pkl'))
        logging.info("Load model:" + os.path.join(args.output_dir, 'checkpoint-last.pkl'))
    else:
        logging.info("Error! The model file does not exist!")
        exit(1)

    start_time = time.time()
    datasets = {}
    all_sentence_num = 0
    for domain in domains:
        logging.info("--- {} ---".format(domain))
        dataset, sentences = processor.load_test_dataset(os.path.join(args.data_dir, domain, "test.txt"), tokenizer,
                                                           tags_list)
        all_sentence_num += len(dataset)
        datasets[domain] = {
            "dataset": dataset,
            "sentences": sentences
        }
    model.eval()
    logging.info("***** Running Testing *****")
    logging.info("  Num examples = %d", all_sentence_num)
    logging.info("  Batch size = %d", args.test_batch_size)

    dataloader_dict = {}
    for domain, dataset in datasets.items():
        dataloader = torch.utils.data.DataLoader(dataset["dataset"], batch_size=args.test_batch_size, shuffle=False)
        dataloader_dict[domain] = dataloader
    all_data = {}
    for domain, dataloader in dataloader_dict.items():
        outputs, labels, mask_ids_list = get_one_domain_predict(dataloader, model, device,
                                                                "Test-{}".format(domain), args.architecture)
        all_data[domain] = {
            "outputs": outputs,
            "labels": labels,
            "mask_ids": mask_ids_list
        }
    _, predict_dict = evaluate(all_data, tags_list, "Testing", args.architecture, True)
    test_dir = os.path.join(args.output_dir, "test")
    if not os.path.exists(test_dir):
        os.makedirs(test_dir)
    all_data = {}
    for domain in datasets:
        sentences = datasets[domain]['sentences']
        predict_list = predict_dict[domain]
        write_data_list = []
        m = 0
        for i in range(len(sentences)):
            sentence = sentences[i]
            result = []
            while len(result) < len(sentence):
                predict, length = predict_list[m]
                m += 1
                predict_tags = ['O'] * length
                for entity in predict:
                    if args.architecture == 'span':
                        tag = tags_list[entity[2] - 1]
                    elif args.architecture == 'softmax' or args.architecture == 'crf':
                        tag = entity[2]
                    predict_tags[entity[0] - 1] = "B-" + tag
                    for j in range(entity[0], entity[1] - 1):
                        predict_tags[j] = "I-" + tag
                result += predict_tags
            assert len(result) == len(sentence)
            write_data = []
            for j in range(len(sentence)):
                write_data.append((sentence[j][0], sentence[j][1], result[j]))
            write_data_list.append(write_data)
        all_data[domain] = write_data_list

        with open(os.path.join(args.output_dir, "test", "{}.txt".format(domain)), "w", encoding="utf8") as fout:
            for sentence in write_data_list:
                for data in sentence:
                    fout.write(data[0] + '\t' + data[1] + '\t' + data[2] + '\n')
                fout.write('\n')
    logging.info("Prediction data is written to directory: " + os.path.join(args.output_dir, "test") + '!')

    end_time = time.time()
    logging.info("Testing end, speed: {:.1f} sentences/s, all time: {:.2f}s".format(
        all_sentence_num / (end_time - start_time), end_time - start_time))

    def change_label(tags):
        i = 0
        result = []
        while i < len(tags):
            if tags[i][0] == "B":
                class_type = tags[i][2:]
                start_index = i
                i += 1
                while i < len(tags) and tags[i] == "I-" + class_type:
                    i += 1
                result.append((start_index, i, class_type))
                i -= 1
            i += 1
        return result
    if args.architecture == 'span':
        domain_entities_dict = {x: [0, 0, 0] for x in tags_list}
    elif args.architecture == 'crf' or args.architecture == "softmax":
        domain_entities_dict = {}
        for tag in tags_list:
            if tag[0] == 'B':
                domain_entities_dict[tag[2:]] = [0, 0, 0]
    for domain, write_data_list in all_data.items():
        if args.architecture == "span":
            entities_dict = {x: [0, 0, 0] for x in tags_list}
        else:
            entities_dict = {}
            for tag in tags_list:
                if tag[0] == 'B':
                    entities_dict[tag[2:]] = [0, 0, 0]
        for sentence in write_data_list:
            predict_data = []
            label_data = []
            for data in sentence:
                predict_data.append(data[2])
                label_data.append(data[1])
            predict_list = change_label(predict_data)
            label_list = change_label(label_data)
            for label in label_list:
                entities_dict[label[2]][1] += 1
            for predict in predict_list:
                entities_dict[predict[2]][0] += 1
                if predict in label_list:
                    entities_dict[predict[2]][2] += 1
        all_result = [0, 0, 0]
        for entity in entities_dict:
            if entities_dict[entity][1] > 0:
                for i in range(len(entities_dict[entity])):
                    all_result[i] += entities_dict[entity][i]
        logging.info("***** {} *****".format(domain))
        p, r, f1 = calculate(all_result)
        logging.info("ALL Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, right: {}".format(
            p, r, f1, all_result[0], all_result[1], all_result[2]))
        for tag_type in entities_dict:
            if entities_dict[tag_type][1] > 0:
                p, r, f1 = calculate(entities_dict[tag_type])
                logging.info("{} Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, "
                             "right: {}".format(tag_type, p, r, f1, entities_dict[tag_type][0],
                                                entities_dict[tag_type][1], entities_dict[tag_type][2]))
        for entity in entities_dict:
            if entities_dict[entity][1] > 0:
                for i in range(len(entities_dict[entity])):
                    domain_entities_dict[entity][i] += entities_dict[entity][i]
    all_result = [0, 0, 0]
    for entity in domain_entities_dict:
        for i in range(len(domain_entities_dict[entity])):
            all_result[i] += domain_entities_dict[entity][i]
    logging.info("***** ALL *****")
    p, r, f1 = calculate(all_result)
    logging.info("ALL Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, right: {}".format(
        p, r, f1, all_result[0], all_result[1], all_result[2]))
    for tag_type in domain_entities_dict:
        p, r, f1 = calculate(domain_entities_dict[tag_type])
        logging.info("{} Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, "
                     "right: {}".format(tag_type, p, r, f1, domain_entities_dict[tag_type][0],
                                        domain_entities_dict[tag_type][1], domain_entities_dict[tag_type][2]))
示例#14
0
def evaluate(data, tags_list, title, mode, test_flag=False):
    def change_label_span(start_tags, end_tags, length):
        i = 0
        result = []
        while i < length - 1:
            if start_tags[i] != 0:
                tag = start_tags[i]
                start_index = i
                while i < length and end_tags[i] == 0:
                    i += 1
                if i < length and end_tags[i] == tag:
                    result.append((start_index, i + 1, tag.item()))
            i += 1
        return result

    result_f1 = None
    result_dict = {}
    if mode == 'span':
        domain_entities_dict = {x + 1: [0, 0, 0] for x in range(len(tags_list))}
    logging.info("***** {} Evaluation *****".format(title))
    for domain, domain_data in data.items():
        outputs = domain_data['outputs']
        labels = domain_data['labels']
        mask_ids = domain_data["mask_ids"]
        sentence_num = outputs['num']
        if mode == 'span':
            entities_dict = {x + 1: [0, 0, 0] for x in range(len(tags_list))}
        result_list = []
        for i in range(sentence_num):
            if mode == 'span':
                length = mask_ids[i].sum()
                predict_list = change_label_span(outputs['start_outputs'][i], outputs['end_outputs'][i], length)
            result_list.append((predict_list, length - 2))
            if not test_flag:
                if mode == 'span':
                    label_list = change_label_span(labels['start_labels_ids'][i], labels['end_labels_ids'][i], length)
                for label in label_list:
                    entities_dict[label[2]][1] += 1
                for predict in predict_list:
                    entities_dict[predict[2]][0] += 1
                    if predict in label_list:
                        entities_dict[predict[2]][2] += 1
        result_dict[domain] = result_list
        if not test_flag:
            all_result = [0, 0, 0]
            for entity in entities_dict:
                for i in range(len(entities_dict[entity])):
                    all_result[i] += entities_dict[entity][i]
            logging.info("***** {} *****".format(domain))
            p, r, f1 = calculate(all_result)
            logging.info("ALL Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, right: {}".format(
                p, r, f1, all_result[0], all_result[1], all_result[2]))
            for tag_type in entities_dict:
                if mode == "span":
                    tag = tags_list[tag_type - 1]
                p, r, f1 = calculate(entities_dict[tag_type])
                logging.info("{} Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, "
                             "right: {}".format(tag, p, r, f1, entities_dict[tag_type][0],
                                                entities_dict[tag_type][1], entities_dict[tag_type][2]))
            for entity in entities_dict:
                for i in range(len(entities_dict[entity])):
                    domain_entities_dict[entity][i] += entities_dict[entity][i]
    if not test_flag:
        all_result = [0, 0, 0]
        for entity in domain_entities_dict:
            for i in range(len(domain_entities_dict[entity])):
                all_result[i] += domain_entities_dict[entity][i]
        logging.info("***** ALL *****")
        p, r, f1 = calculate(all_result)
        logging.info("ALL Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, right: {}".format(
            p, r, f1, all_result[0], all_result[1], all_result[2]))
        result_f1 = f1
        for tag_type in domain_entities_dict:
            if mode == "span":
                tag = tags_list[tag_type - 1]
            p, r, f1 = calculate(domain_entities_dict[tag_type])
            logging.info("{} Precision={:.4f}, Recall={:.4f}, F1={:.4f}, predict: {}, truth: {}, "
                         "right: {}".format(tag, p, r, f1, domain_entities_dict[tag_type][0],
                                            domain_entities_dict[tag_type][1], domain_entities_dict[tag_type][2]))
    return result_f1, result_dict
示例#15
0
    sys.exit(2)

for o, a in opts:
    if o == '-d':
        utils.dictionary_file = a
    elif o == '-p':
        utils.postings_file = a
    elif o == '-q':
        utils.file_of_queries = a
    elif o == '-o':
        utils.output_file_of_results = a
    else:
        assert False, "unhandled option"

if utils.dictionary_file == None or utils.postings_file == None or utils.file_of_queries == None or utils.output_file_of_results == None:
    usage()
    sys.exit(2)

utils.initialize()

f = open(utils.file_of_queries)
f_ans = open(utils.output_file_of_results, 'w')
for line in f:
    # transform the infix expression to postfix expression
    expr = utils.transform(line.strip())
    # calculate the result of the postfix expression
    result = utils.calculate(expr)
    # output the result to file
    write_to_file(f_ans, result)
f.close()
f_ans.close()
示例#16
0
def curso(req, curso_slug):
    if req.method == 'POST':
        curso = get_object_or_404(Curso, slug=curso_slug)
        vs = {'curso': curso}  # variables para el rendereo de la plantilla
        action = req.POST.get('action')

        if action and curso.activado:
            if action == 'buy':
                nombre = req.POST.get('nombre')
                email = req.POST.get('email')
                tel = req.POST.get('telefono')
                quantity = req.POST.get('quantity')
                token = req.POST.get('stripeToken')

                if email:
                    try:
                        validate_email(email)
                    except ValidationError:
                        email = False

                # si ya ha pagado hoy
                if CursoPago.objects.filter(email=email, curso=curso, charged=True, fecha__gt=datetime.now() - timedelta(days=1)).exists():
                    return HttpResponse('ERR ALREADY COMPLETED')

                if CursoPago.objects.filter(email=email, curso=curso, charged=False, fecha__gt=datetime.now() - timedelta(days=1)).count() > 5:
                    return HttpResponse('ERR TOO MANY TRIES')

                if nombre and email and tel and quantity and token:
                    # realizar el cargo con la api de stripe
                    p = CursoPago(nombre=nombre, email=email, telefono=tel, pais=get_pais(req.META), ip=get_ip(req.META), ua=req.META['HTTP_USER_AGENT'], quantity=quantity, curso=curso, method='card')
                    p.save()

                    concept = calculate(int(quantity), curso.precio)

                    try:
                        charge = stripe.Charge.create(
                            amount=concept['amount'] * 100,
                            currency='usd',
                            card=token,
                            description=email
                        )
                    except Exception, e:
                        p.error = str(e)
                        p.save()

                        send_mail(u'¿Podemos ayudarte de alguna forma?', u'Vimos que tuviste problemas pagando el %s de Mejorando.la\n¿Podemos ayudarte de alguna forma?\nNo olvides que puedes contactarnos vía skype en mejorandola' % curso.nombre, 'Ventas Mejorando.la <*****@*****.**>', [p.email], fail_silently=True)

                        return HttpResponse('ERR')

                    # si no se realiza el cargo regresar error
                    if not charge.paid:
                        return HttpResponse('ERR')

                    p.charged = True
                    p.save()

                    req.session['p32'] = p.id

                    return HttpResponse('OK')

                else:
                    return HttpResponse('ERR')

            elif action == 'deposit' or action == 'paypal':

                nombre = req.POST.get('nombre')
                email = req.POST.get('email')
                tel = req.POST.get('telefono')
                quantity = req.POST.get('quantity')

                if email:
                    try:
                        validate_email(email)
                    except ValidationError:
                        email = False

                if CursoPago.objects.filter(email=email, curso=curso, charged=False, fecha__gt=datetime.now() - timedelta(days=1)).count() > 5:
                    return HttpResponse('ERR TOO MANY TRIES')

                if nombre and email and tel and quantity:
                    p = CursoPago(nombre=nombre, email=email, telefono=tel, pais=get_pais(req.META), ip=get_ip(req.META), ua=req.META['HTTP_USER_AGENT'], quantity=quantity, curso=curso, method=action)
                    p.save()

                    return HttpResponse('OK')

                else:
                    return HttpResponse('ERR')

            elif action == 'register':
                email = req.POST.getlist('email')
                pago = req.session.get('p32')

                if email and pago:
                    p = get_object_or_404(CursoPago, id=pago)

                    # no permitir registro sin haber pagado
                    if not p.charged:
                        return HttpResponse('ERR')

                    for e in email:
                        r = CursoRegistro(email=e, pago=p)
                        r.save()

                    return HttpResponse('OK')

                else:
                    return HttpResponse('ERR')

            else:
                return HttpResponse('ERR')
        else:
            return HttpResponse('ERR')
示例#17
0
needed = {}

# 如果长度不相等
if len(items) != len(count):
    print("Command line parameter error")
    exit(-1)

# 将需要的设置成字典
for i in range(0, len(items)):
    needed[items[i]] = int(count[i])

# 获得表
table = data_manage.get_table()

# 获得数据
while utils.calculate(table, needed, exist)[1]:
    needed = utils.calculate(table, needed, exist)[0]
    # print(needed)

print("Raw data: {}".format(str(needed)))

# 处理数据
for (key, value) in needed.items():
    if value >= 64:
        if value % 64 != 0:
            print(
                "{}: {}组{}个".format(
                    key,
                    int(value // 64),
                    int(value % 64),
                )
示例#18
0
def curso(req, curso_slug):
	if req.method == 'POST':
		curso  = get_object_or_404(Curso, slug=curso_slug)
		vs 	   = { 'curso': curso } # variables para el rendereo de la plantilla
		action = req.POST.get('action')

		if action:
			if action == 'buy':
				nombre 	 = req.POST.get('nombre')
				email  	 = req.POST.get('email')
				tel    	 = req.POST.get('telefono')
				quantity = req.POST.get('quantity')
				token 	 = req.POST.get('stripeToken')

				if nombre and email and tel and quantity and token:
					# realizar el cargo con la api de stripe
					p = CursoPago(nombre=nombre, email=email, telefono=tel, pais=get_pais(req.META), quantity=quantity, curso=curso, method='card')
					p.save()

					concept = calculate(int(quantity), curso.precio)

					try:
						charge = stripe.Charge.create(
							amount		= concept['amount']*100,
							currency	= 'usd',
							card	    = token,
							description = email
						)
					except:  return HttpResponse('ERR')

					# si no se realiza el cargo regresar error
					if not charge.paid: return HttpResponse('ERR')

					p.charged = True
					p.save()

					req.session['p32'] = p.id

					return HttpResponse('OK')

				else: return HttpResponse('ERR')

			elif action == 'deposit' or action == 'paypal':
				nombre 	 = req.POST.get('nombre')
				email  	 = req.POST.get('email')
				tel    	 = req.POST.get('telefono')
				quantity = req.POST.get('quantity')

				if nombre and email and tel and quantity:
					p = CursoPago(nombre=nombre, email=email, telefono=tel, pais=get_pais(req.META), quantity=quantity, curso=curso, method=action)	
					p.save()

					return HttpResponse('OK')

				else: return HttpResponse('ERR')

			elif action == 'register': 
				email = req.POST.getlist('email')
				pago  = req.session.get('p32')

				if email and pago:
					p = get_object_or_404(CursoPago, id=pago)

					# no permitir registro sin haber pagado
					if not p.charged: return HttpResponse('ERR')

					for e in email:
						r = CursoRegistro(email=e, pago=p)
						r.save()

					return HttpResponse('OK')
					
				else: return HttpResponse('ERR')

			else: return HttpResponse('ERR')
		else: return HttpResponse('ERR')

	try:
		curso = Curso.objects.get(slug=curso_slug)
	except Curso.DoesNotExist: curso = None

	vs = RequestContext(req, { 'curso': curso, 'publishable_key': settings.STRIPE_PUBLISHABLE_KEY })
	try:
		return render_to_response('%s.html' % curso_slug, vs)
	except TemplateDoesNotExist:
		if not curso: raise Http404

		return render_to_response('cursos/curso.html', vs)
示例#19
0
    (True, 'expen-ses food dinner cost = 20'),
    (False, 'test'),
    (False, 'expenses food dinner cost:30'),
    (False, '@2015-10-03T08:30 dinner cost=30 @2015-10-05:03:20'),
]

results = []

for i, t in enumerate(tests):
    if i != 0 and False:
        continue
    r, s = t
    try:
        results += [(r, s, None)]
        data = parser.parse(s, parser.token_exprs)
        if not r:
            r = not r
            raise Exception('False Positive')
        print '%02d Pass' % (i + 1)
        results[-1] = (r, s, data)
    except Exception, e:
        if not r:
            print '%02d Pass' % (i + 1)
        else:
            print '%02d FAIL: %s' % (i + 1, e)

all_data = [r[-1] for r in results if r[-1] is not None]
print utils.calculate(all_data, lambda d: 'food' in d, utils.mean, 'cost')
print utils.calculate(all_data, lambda d: 'food' in d, utils.mean, 'cost', 'rest')
print utils.calculate(all_data, lambda d: 'food' in d, len, 'cost', 'rest')
示例#20
0
def curso(req, curso_slug):
	if req.method == 'POST':
		curso  = get_object_or_404(Curso, slug=curso_slug)
		vs 	   = { 'curso': curso } # variables para el rendereo de la plantilla
		action = req.POST.get('action')

		if action:
			if action == 'buy':
				nombre 	 = req.POST.get('nombre')
				email  	 = req.POST.get('email')
				tel    	 = req.POST.get('telefono')
				quantity = req.POST.get('quantity')
				token 	 = req.POST.get('stripeToken')

				if nombre and email and tel and quantity and token:
					# realizar el cargo con la api de stripe
					p = CursoPago(nombre=nombre, email=email, telefono=tel, pais=get_pais(req.META), quantity=quantity, curso=curso, method='card')
					p.save()

					concept = calculate(int(quantity), curso.precio)

					try:
						charge = stripe.Charge.create(
							amount		= concept['amount']*100,
							currency	= 'usd',
							card	    = token,
							description = email
						)
					except Exception, e:  
						p.error = str(e)
						p.save()

						send_mail(u'¿Podemos ayudarte de alguna forma?', u'Vimos que tuviste problemas pagando el %s de Mejorando.la\n¿Podemos ayudarte de alguna forma?\nNo olvides que puedes contactarnos vía skype en mejorandola' % curso.nombre, 'Ventas Mejorando.la <*****@*****.**>', [p.email], fail_silently=True)

						return HttpResponse('ERR')

					# si no se realiza el cargo regresar error
					if not charge.paid: return HttpResponse('ERR')

					p.charged = True
					p.save()

					req.session['p32'] = p.id

					return HttpResponse('OK')

				else: return HttpResponse('ERR')

			elif action == 'deposit' or action == 'paypal':
				nombre 	 = req.POST.get('nombre')
				email  	 = req.POST.get('email')
				tel    	 = req.POST.get('telefono')
				quantity = req.POST.get('quantity')

				if nombre and email and tel and quantity:
					p = CursoPago(nombre=nombre, email=email, telefono=tel, pais=get_pais(req.META), quantity=quantity, curso=curso, method=action)	
					p.save()

					return HttpResponse('OK')

				else: return HttpResponse('ERR')

			elif action == 'register': 
				email = req.POST.getlist('email')
				pago  = req.session.get('p32')

				if email and pago:
					p = get_object_or_404(CursoPago, id=pago)

					# no permitir registro sin haber pagado
					if not p.charged: return HttpResponse('ERR')

					for e in email:
						r = CursoRegistro(email=e, pago=p)
						r.save()

					return HttpResponse('OK')
					
				else: return HttpResponse('ERR')

			else: return HttpResponse('ERR')
		else: return HttpResponse('ERR')