示例#1
0
def PUTstatDownvote(statIDs):
	statID_list = statIDs.split('-')
	try:
		Stat.increment(statID_list, "down_count")
		return respond200()
	except Exception as e:
		return respond500(e)
示例#2
0
	def create_stat(self):
		""" Create stat without creating entry 
			need to create OPP for _OPP and OPP.id 
			Then can delete stat with delete OPP
		"""
		opp = self.POSTopp()
		stat = Stat(_OPP=opp['id'])
		stat.save()
		return stat
示例#3
0
def testingAction(action):
    if action in ['begin']:
        session['testing'] = {
            'tests': [
                t.id for t in Test.query.order_by(func.random()).distinct(
                    Test.id).limit(10).all()
            ],
            'index':
            0,
            'answers': {},
            'correct':
            0
        }

    if action in ['submit']:
        if 'id' and 'option' in request.values:
            session['testing']['answers'].update(
                {request.values['id']: request.values['option']})
        action = 'next'

    if action in ['prev', 'next']:
        index = session['testing']['index']
        index = index + 1 if action == 'next' else index - 1

        if index < 0:
            index = 0

        session['testing'].update({'index': index})

        if session['testing']['index'] > 9:
            return redirect('/testing/result')

    if action in ['result']:
        correct = 0

        for id, value in session['testing']['answers'].iteritems():
            test = Test.query.get(id)

            if test.correctanswer == int(value):
                correct += 1

        session['testing'].update({'correct': correct})

        if 'finished' not in session['testing']:
            stat = Stat(10, session['testing']['correct'], datetime.now())
            db.session.add(stat)
            stat.student = current_user.student
            db.session.commit()

            session['testing'].update({'finished': True})

    return redirect('/testing')
示例#4
0
    def test_simple_show(self):
        date1 = datetime.strptime("2021.03.20", '%Y.%m.%d').date()
        stat = Stat(date=date1, views=100, clicks=50, cost=13.54)
        db.session.add(stat)

        date2 = datetime.strptime("2021.03.21", '%Y.%m.%d').date()
        stat = Stat(date=date2, views=100, clicks=50, cost=13.54)
        db.session.add(stat)

        date3 = datetime.strptime("2021.03.22", '%Y.%m.%d').date()
        stat = Stat(date=date3, views=100, clicks=50, cost=13.54)
        db.session.add(stat)

        db.session.commit()
        result = Stat.get_range(date1, date2, None)
        self.assertEqual(len(result), 2)
示例#5
0
def show():
    date_from = request.args.get('from')
    date_to = request.args.get('to')
    order_by = request.args.get('order_by')
    print(date_from, date_to)
    try:
        date_from = datetime.datetime.strptime(date_from, '%Y.%m.%d').date()
        date_to = datetime.datetime.strptime(date_to, '%Y.%m.%d').date()
    except ValueError:
        return jsonify(error="Incorrect date"), 400
    except TypeError:
        return jsonify(error="Date not found"), 400
    result = Stat.get_range(date_from, date_to, order_by)
    result_arr = []
    for res in result:
        date_json = {
            'date': res[0].strftime("%Y.%m.%d"),
            'views': res[1],
            'clicks': res[2],
            'cost': res[3],
        }
        try:
            date_json['cpc'] = round(res[3] / res[2], 2)
        except ZeroDivisionError:
            date_json['cpc'] = 0
        try:
            date_json['cpm'] = round(res[3] / res[1] * 1000, 2)
        except ZeroDivisionError:
            date_json['cpm'] = 0
        result_arr.append(date_json)
    print(result_arr)
    return jsonify(result=result_arr)
示例#6
0
 def test_add_part_data(self):
     date = datetime.strptime("2021.03.20", '%Y.%m.%d').date()
     stat = Stat(date=date)
     db.session.add(stat)
     db.session.commit()
     count = len(Stat.query.all())
     stat1 = Stat.query.first()
     self.assertEqual(count, 1)
     self.assertEqual(stat1, stat)
示例#7
0
    def test_show(self):
        date1 = datetime.strptime("2021.03.20", '%Y.%m.%d').date()
        stat = Stat(date=date1, views=100, clicks=50, cost=13.54)
        db.session.add(stat)

        date2 = datetime.strptime("2021.03.21", '%Y.%m.%d').date()
        stat = Stat(date=date2, views=100, clicks=51, cost=13.54)
        db.session.add(stat)

        date3 = datetime.strptime("2021.03.22", '%Y.%m.%d').date()
        stat = Stat(date=date3, views=100, clicks=52, cost=13.54)
        db.session.add(stat)

        db.session.commit()
        response = requests.get(
            'http://localhost:5000/show?from=2010.01.01&to=2021.03.21&order_by=clicks'
        )
        self.assertEqual(response.status_code, 200)
示例#8
0
 def test_add_full_data(self):
     date = datetime.strptime("2021.03.20", '%Y.%m.%d').date()
     stat = Stat(date=date, views=100, clicks=50, cost=13.54)
     db.session.add(stat)
     db.session.commit()
     count = len(Stat.query.all())
     stat1 = Stat.query.first()
     self.assertEqual(count, 1)
     self.assertEqual(stat1, stat)
示例#9
0
def unsubscribe_all(update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    subscriptions = db.session.query(Subscription).filter_by(chat_id=chat_id)
    subscriptions.delete(synchronize_session='fetch')

    stat = Stat(chat_id=chat_id, action=Action.unsubscribe.value)
    db.session.add(stat)
    db.session.commit()

    update.message.reply_text(
        "На жаль, ти відписався від всіх усіх розсилок вакансій 😞")
示例#10
0
def add_position(update: Update, context: CallbackContext):
    callback_query: CallbackQuery = update.callback_query
    _, suffix = callback_query.data.strip().split('.')
    position = Position.query.filter_by(id=suffix).first()
    city_id: str = context.user_data['city_id']
    city = City.query.get(city_id)
    message: Message = callback_query.message

    subscription = Subscription(
        chat_id=message.chat_id,
        city_id=city_id,
        position_id=position.id,
    )
    subscription.soft_add()
    db.session.commit()

    callback_query.answer(
        callback_query=callback_query.id,
        text=f"Дякую, я запам'ятав твій вибір",
        cache_time=60,
    )

    message.reply_text(
        text=
        (f"Опитування завершено 🎉 \n"
         f"Тепер я буду тебе сповіщувати про "
         f"нові вакансії у категорії *{position.name}* у місті *{city.name}*."
         f"\n\n"
         f"За мить, ти отримаєш перелік вакансій за обраними параметрами 😉"),
        parse_mode='Markdown',
        reply_markup=get_keyboard_menu(update),
    )
    stat = Stat(chat_id=message.chat_id, action=Action.subscribed.value)
    db.session.add(stat)
    db.session.commit()

    vacancies = parser.update_new_vacancies(city, position)
    if not vacancies:
        message.reply_text(
            text=
            f"🤷‍♀️ На жаль, у місті *{city.name}* немає вакансій в категорії *{position.name}*",
            parse_mode='Markdown',
        )
    # send only 10 vacancies for preventing spamming
    vacancies = vacancies[:10]
    sender.send_vacancies(vacancies, message.chat_id)

    return ConversationHandler.END
示例#11
0
def save():
    data = request.get_json()
    date = data['date'] if 'date' in data else None
    views = data['views'] if 'views' in data else 0
    clicks = data['clicks'] if 'clicks' in data else 0
    cost = data['cost'] if 'cost' in data else 0
    try:
        date = datetime.datetime.strptime(date, '%Y.%m.%d').date()
    except ValueError:
        return jsonify(error="Incorrect date"), 400
    except TypeError:
        return jsonify(error="Date not found"), 400
    print(data, date, views, clicks, cost)
    stat = Stat(date=date, views=views, clicks=clicks, cost=cost)
    db.session.add(stat)
    db.session.commit()
    return jsonify(success=True)
示例#12
0
def stats(de):
    if current_user.tipo_usuario != 1:
        return redirect(url_for('index'))
    if de == '1':
        countu = Stat.getCountByDE1('U')
        countb = Stat.getCountByDE1('B')
        counta = Stat.getCountByDE1('A')
        data = [['Universitario', countu], ['Bachiller', countb],
                ['Acabado', counta]]
    elif de == '2':
        count1 = Stat.getCountByDE2('0-18')
        count2 = Stat.getCountByDE2('19-22')
        count3 = Stat.getCountByDE2('+22')
        data = [['0-18', count1], ['19-22', count2], ['+22', count3]]
    elif de == '3':
        counth = Stat.getCountByDE3('H')
        countm = Stat.getCountByDE3('M')
        data = [['Hombre', counth], ['Mujer', countm]]

    return jsonify(data)
示例#13
0
def delete_subscription(update: Update, context: CallbackContext):
    callback_query: CallbackQuery = update.callback_query
    _, _, suffix = callback_query.data.strip().split('.')

    subscription = Subscription.query.get(suffix)
    if not subscription:
        return

    chat_id = subscription.chat_id

    db.session.delete(subscription)
    db.session.commit()

    if not Subscription.query.first():
        stat = Stat(chat_id=chat_id, action=Action.unsubscribe.value)
        db.session.add(stat)
        db.session.commit()

    list_subscription(update, context)
示例#14
0
文件: db_manager.py 项目: namiszh/fba
    def import_team_stats_by_week(self, team, week):
        # print('import stat for team {} week = {}'.format(team.team_key, week))
        team_stats = self.yahoo.get_team_stat(team, week)
        for team_stat in team_stats:
            stat_id = int(team_stat['stat_id'])

            # check whether need to import, will not import display only
            stat = Category.query.get(stat_id)
            if not stat or stat.display_only == 1:
                continue

            value = team_stat['value']
            stat = Stat.query.filter_by(team_key=team.team_key, week=week, stat_id=stat_id).first()
            if stat:
                stat.value = value
            else:
                stat = Stat(team.team_key, week, stat_id, value)
                db.session.add(stat)
            # print(stat)
        db.session.commit()
示例#15
0
def new_stat():
    # 1. Get user from session
    user = current_user

    # 2. Prepare form data for validation
    form = StatForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    lift_id = request.json['lift_id']

    # 3. Validate form data; if invalid return 400 bad request to user
    if not form.validate_on_submit():
        return {"message": "validation_errors", "data": form.errors}, 400

    # 4. If valid then extract useful data from form
    sets = form.data['sets']
    reps = form.data['reps']
    weight = form.data['weight']
    date = form.data['date']
    difficulty = form.data['difficulty']
    notes = form.data['notes']

    # 5. Create the stat
    stat = Stat(sets=sets,
                reps=reps,
                weight=weight,
                date=date,
                difficulty=difficulty,
                notes=notes,
                lift_id=lift_id)

    # 6. Add and commit the stat
    db.session.add(stat)
    db.session.commit()

    lift = Lift.query.get(lift_id)

    # 7. Send 201 response to the user
    return {"message": "success", "data": lift.to_dict()}, 201
示例#16
0
def stat():
    print('autenticando')
    form = StatForm()
    print(form.validate_on_submit)
    if form.validate_on_submit():
        if current_user.is_authenticated:
            stat = Stat(id_usuario=current_user.id,
                        dato_estadistico_1=request.form['estudios'],
                        dato_estadistico_2=request.form['edad'],
                        dato_estadistico_3=request.form['sexo'])
            print('autenticado')

        else:
            stat = Stat(dato_estadistico_1=request.form['estudios'],
                        dato_estadistico_2=request.form['edad'],
                        dato_estadistico_3=request.form['sexo'])
        stat.addStat()
        print('vaina2')

        return redirect(url_for('index'))
    return render_template('stat.html', title='stat', form=form)
示例#17
0
def PUTstatIncrement(statID, count):
	try:
		Stat.increment([statID], count)
		return respond200()
	except Exception as e:
		return respond500(e)
示例#18
0
def GETallStats():
	stats = Stat.all()
	return dumpJSON([s.jsonify() for s in stats])
示例#19
0
def GETstat(statID):
	stat = Stat.find(statID)
	if stat:
		stat = stat.jsonify()
	return dumpJSON(stat)
示例#20
0
    def testInsertUpdateRemoveStat(self):
        # Insert Stat
        s1 = Stat(id=65535,
                  id_usuario=1,
                  dato_estadistico_1='Dato 1 Test',
                  dato_estadistico_2='Dato 2 Test')
        s1.addStat()
        s2 = Stat.getStatById(65535)
        self.assertTrue(print(s1) == print(s2))

        # Update Stat
        s1 = Stat.getStatById(65535)
        s1.dato_estadistico_1 = 'Dato 1 modified'
        s1.updateStat()
        s2 = Stat.getStatById(65535)
        self.assertTrue(print(s1) == print(s2))

        # Remove Stat
        s1 = Stat.getStatById(65535)
        s1.removeStat()
        s2 = Stat.getStatById(65535)
        self.assertTrue(s2 == None)
示例#21
0
def index():
    form = PosterForm()
    formResponse = ResponseForm()
    formLike = LikeForm()
    posts = Poster.getPostersChecked()
    questions = {}
    for post in posts:
        questions[post.id] = QuestionOption.getOpcionPreguntaByPosterId(
            post.id)

    if formResponse.validate_on_submit():
        options = QuestionOption.getOpcionPreguntaByPosterId(
            formResponse.id.data)
        print("A CONTINUACION ID POSTER")
        print(formResponse.id.data)
        if formResponse.opcion1:
            if (current_user.is_authenticated):
                respuesta = UserResponse(id_usuario=current_user.id,
                                         id_poster=formResponse.id.data,
                                         opcion=options[0].opcion)
            else:
                respuesta = UserResponse(id_poster=formResponse.id.data,
                                         opcion=options[0].opcion)
            respuesta.addUserResponse()

        if formResponse.opcion2.data:
            if (current_user.is_authenticated):
                respuesta = UserResponse(id_usuario=current_user.id,
                                         id_poster=formResponse.id.data,
                                         opcion=options[1].opcion)
            else:
                respuesta = UserResponse(id_poster=formResponse.id.data,
                                         opcion=options[1].opcion)
            respuesta.addUserResponse()

        if formResponse.opcion3.data:
            if (current_user.is_authenticated):
                respuesta = UserResponse(id_usuario=current_user.id,
                                         id_poster=formResponse.id.data,
                                         opcion=options[2].opcion)
            else:
                respuesta = UserResponse(id_poster=formResponse.id.data,
                                         opcion=options[2].opcion)
            respuesta.addUserResponse()

        if formResponse.opcion4.data:
            if (current_user.is_authenticated):
                respuesta = UserResponse(id_usuario=current_user.id,
                                         id_poster=formResponse.id.data,
                                         opcion=options[3].opcion)
            else:
                respuesta = UserResponse(id_poster=formResponse.id.data,
                                         opcion=options[3].opcion)
            respuesta.addUserResponse()
        if (current_user.is_anonymous):
            return redirect(url_for('stat'))
        else:
            stat = Stat.getUsers(current_user.id)
            if (stat is not None):
                return redirect(url_for('index'))
            else:
                return redirect(url_for('stat'))

    if form.validate_on_submit():
        post = Poster(id_usuario=current_user.id,
                      titulo=form.titulo.data,
                      corregido=0,
                      imagen=form.imagen.data,
                      reto=form.reto.data,
                      info=form.info.data,
                      pregunta=form.pregunta.data)
        post.addPoster()
        resp1 = QuestionOption(id_poster=post.id, opcion=form.respuesta1.data)
        resp2 = QuestionOption(id_poster=post.id, opcion=form.respuesta2.data)
        resp3 = QuestionOption(id_poster=post.id, opcion=form.respuesta3.data)
        resp4 = QuestionOption(id_poster=post.id, opcion=form.respuesta4.data)
        resp1.addOpcionPregunta()
        resp2.addOpcionPregunta()
        resp3.addOpcionPregunta()
        resp4.addOpcionPregunta()
        flash(
            'Poster almacenado con éxito. Debes esperar a que un administrador lo corrija para que se pueda mostrar'
        )
        return redirect(url_for('index'))

    return render_template('index.html',
                           title='Home',
                           posts=posts,
                           form=form,
                           formResponse=formResponse,
                           questions=questions,
                           formLike=formLike)