コード例 #1
0
 def __init__(self, oid):
     tmp = Que.objects.get(oid=oid)
     self.oid = oid
     self.title = tmp.title
     self.count = len(Ans.objects(question_oid=str(tmp.oid)))
     self.rating = 3
     self.answer = []
     for each in Ans.objects(question_oid=oid):
         self.answer.append(AnswerAnalyseItem(content=each.content))
コード例 #2
0
def add_answer():
    content = request.form.get('answer_content')
    question_id = request.form.get('question_id')
    question = Question.query.filter(Question.id == question_id).first()
    answer = Answer(content=content)
    answer.author = g.user
    answer.question = question
    db.session.add(answer)
    return redirect(url_for('detail', question_id=question_id))
コード例 #3
0
ファイル: server.py プロジェクト: tjhakseth/project_reggie
def event_submit(event_id):
    """Saves registration information about user for an event"""

    # Gets the specific event information
    event = Event.query.get(event_id)

    # Verifies the user
    user_id = session.get("user_id")
    if not user_id:
        flash("Please log in to register for event", "warning")
        return redirect("/")
    # user = User.query.get(user_id)

    # Gets Form Variables
    questions = event.questions
    values = request.form.getlist("question")

    # Gets Id for each question
    question_ids = [q.id for q in questions]

    # Adds a new registration to the session
    new_registration = Registration()
    new_registration.user_id = user_id
    new_registration.event_id = event_id
    new_registration.timestamp = datetime.now()

    db.session.add(new_registration)

    # Adds the answers for each question to the session
    for i in range(len(questions)):
        new_answer = Answer()
        new_answer.value = values[i]
        new_answer.question_id = question_ids[i]
        new_answer.registration = new_registration

        db.session.add(new_answer)
    # Commits both the registration and all the answers to the database
    db.session.commit()

    # Charge the attendee
    token = request.form.get('stripeToken', None)
    if token is not None:
        charged_id = charge_card(token, event.price)
        # TODO: store the charge_id in the event
        if not charged_id:
            raise Exception("Payment error")

    flash("Successfully Registered for event", "success")

    msg = Message("You're Registered!!!!",
                  sender="*****@*****.**",
                  recipients=["*****@*****.**"])
    msg.body = "This is the email body"
    mail.send(msg)

    # return redirect("/user_profile/%s" % user_id)
    return render_template("success.html", event=event, user_id=user_id)
コード例 #4
0
ファイル: server.py プロジェクト: tjhakseth/project_reggie
def event_submit(event_id):
    """Saves registration information about user for an event"""

    # Gets the specific event information
    event = Event.query.get(event_id)

    # Verifies the user
    user_id = session.get("user_id")
    if not user_id:
        flash("Please log in to register for event", "warning")
        return redirect("/")
    # user = User.query.get(user_id)

    # Gets Form Variables
    questions = event.questions
    values = request.form.getlist("question")

    # Gets Id for each question
    question_ids = [q.id for q in questions]

    # Adds a new registration to the session
    new_registration = Registration()
    new_registration.user_id = user_id
    new_registration.event_id = event_id
    new_registration.timestamp = datetime.now()

    db.session.add(new_registration)

    # Adds the answers for each question to the session
    for i in range(len(questions)):
        new_answer = Answer()
        new_answer.value = values[i]
        new_answer.question_id = question_ids[i]
        new_answer.registration = new_registration

        db.session.add(new_answer)
    # Commits both the registration and all the answers to the database
    db.session.commit()

    # Charge the attendee
    token = request.form.get('stripeToken', None)
    if token is not None:
        charged_id = charge_card(token, event.price)
        # TODO: store the charge_id in the event
        if not charged_id:
            raise Exception("Payment error")

    flash("Successfully Registered for event", "success")

    msg = Message("You're Registered!!!!",
                  sender="*****@*****.**",
                  recipients=["*****@*****.**"])
    msg.body = "This is the email body"
    mail.send(msg)

    # return redirect("/user_profile/%s" % user_id)
    return render_template("success.html", event=event, user_id=user_id)
コード例 #5
0
def add_answer():
    content = request.form.get('answer_content')
    question_id = request.form.get('question_id')
    create_time = Answer.query.order_by('-create_time').first()
    answer = Answer(content=content)
    answer.author = g.user
    question = Question.query.filter(Question.id == question_id).first()
    answer.question = question
    db.session.add(answer)
    db.session.commit()

    return redirect(url_for('detail', question_id=question_id))
コード例 #6
0
def vote_callback(bot, update):
    answer_id = update.callback_query.data
    user = update.callback_query.from_user
    voter_name = user.username or user.first_name
    voter_id = user.id
    LOGGER.info("{} ({}) voted {}".format(voter_name, voter_id, answer_id))
    voter = insert_or_update_voter(voter_id, voter_name)
    try:
        answer = Answer.get_by_id(answer_id)
    except Answer.DoesNotExist:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Je n'ai pas trouvé cette réponse dans ma BDD")
        return
    try:
        vote = Vote.get((Vote.voter == voter) & (Vote.answer == answer))
        # Vote already exists, lets delete it
        vote.delete_instance()
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Ton vote a bien été supprimé")
    except Vote.DoesNotExist:
        # Vote does not exist, lets create it
        Vote.create(answer=answer, voter=voter)
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Ton vote a bien été enregistré")
    # Update question text
    poll = answer.poll
    answers = poll.answers
    text, reply_markup = generate_poll_message(poll, answers)
    bot.editMessageText(
        message_id=update.callback_query.message.message_id,
        chat_id=update.callback_query.message.chat.id,
        text=text,
        reply_markup=reply_markup,
    )
コード例 #7
0
ファイル: controller.py プロジェクト: obilodeau/ceopardy
    def answer_normal(column, row, answers):
        app.logger.info("Answers submitted for question ({}, {}): {}".format(
            column, row, answers))
        # Answers looks like: ('team1', '-1'), ('team2', '1'), ('team3', '0')]

        condition = and_(Question.row == row, Question.col == column)
        _q = Question.query.filter(condition).one()

        # Is there already an answer? If so update answers
        prev_answers = Answer.query.filter(Answer.question_id == _q.id).all()
        if prev_answers:
            for _answer in prev_answers:
                _answer.response = Response(int(answers[_answer.team.tid]))
                db.session.add(_answer)

        # Otherwise create new ones
        else:
            for tid, points in answers.items():
                team = Team.query.filter(Team.tid == tid).one()
                question = Question.query.get(_q.id)
                response = Response(int(points))
                db.session.add(Answer(response, team, question))

        db.session.commit()
        return True
コード例 #8
0
def create_answer(id):
    user_id = request.json['user_id']
    content = request.json['content']

    user = User.query.filter_by(user_id=user_id).first()
    question = Question.query.get(id)

    if not question:
        return 'This question is not existed!'

    if question.is_deleted:
        return 'This question was deleted!'

    if question.is_closed:
        return 'This question was closed!'

    if not user:
        return 'This account have been not registed!'

    answer = Answer(content, user_id, id)

    try:
        db.session.add(answer)
        db.session.commit()
    except:
        return 'Error! Fail to create answer!'

    return answer_schema.jsonify(answer)
コード例 #9
0
ファイル: server.py プロジェクト: linuxlewis/project_reggie
def event_submit(event_id):

    event = Event.query.get(event_id)
    user_id = session.get("user_id")

    if not user_id:
        flash("Please log in to register for event")
        return redirect("/")

    questions = event.questions
    values = request.form.getlist("question")

    
    question_ids = [q.id for q in questions]


    new_registration = Registration()
    new_registration.user_id = user_id
    new_registration.event_id= event_id
    new_registration.timestamp= datetime.now()

    db.session.add(new_registration)
    

    for i in range (len(questions)):
        new_answer = Answer()
        new_answer.value = values[i]
        new_answer.question_id = question_ids[i]
        new_answer.registration = new_registration


        db.session.add(new_answer)
    db.session.commit()

    flash("Successfully Registered for event")

    # Charge if necessary
    token = request.form.get('stripeToken', None)
    # import pdb; pdb.set_trace()
    if token is not None:
        charged_id = charge_card(token, event.price)
        # TODO: store the charge_id in the event
        if not charged_id:
            raise Exception("Payment error")
    
    return redirect("/user_profile/%s" % user_id)
コード例 #10
0
def question_callback(bot: telegram.Update, update: telegram.ext.Dispatcher, args: [str]):
    args = _reconstruct_args(args)
    LOGGER.debug("'Question' called with {args}".format(args=args))
    if len(args) < 3:
        update.message.reply_text("Il n'y a pas assez d'arguments:\n\n{}".format(QUESTION_CMD))
        return
    new_poll = Poll.create(question=args[0])
    answers = []
    for answer in args[1:]:
        answers.append(Answer.create(poll=new_poll, answer=answer))
    show_poll(new_poll, answers, update, bot)
コード例 #11
0
def victim_comp_process():
    """"Victim Compensation form is processed"""

    form_id = request.form['form_id']
    form = Form.query.get(form_id)
    victim = Victim.query.get(session["login_id"])

    eastern = pytz.timezone('US/Eastern')
    dt = datetime.now(tz=eastern)
    time_filled = dt.strftime("%A, %d %B %Y %I:%M%p")

    filled_form = Filled_Form(form=form,
                              victim=victim,
                              time_filled=time_filled)
    form_status = Form_Status(filled_form=filled_form,
                              app_received=time_filled)
    #working correctly saving filled_form
    db.session.add(filled_form)
    db.session.add(form_status)
    # db.session.commit()

    #list of question object which shows all questions with form_id 2 meaning all questions asociated with
    # the victim compensation form
    questions_list = filled_form.form.questions
    #looping through the list of question objects
    for question in questions_list:
        # you have a single answer object associated with that question object
        # print question

        # print("Question number: {}".format(question_number))

        key = "section_{}_{}".format(question.section_number,
                                     question.question_number)
        # print key
        answer_text = request.form[key]
        # import pdb; pdb.set_trace()
        # print answer_text

        #     # for answer in question.answers:
        #     #     answer_form = request.form[answer]
        #     print answer_text
        #         # answer_text = answer.answer_text
        answer_object = Answer(question=question,
                               answer_text=answer_text,
                               filled_form=filled_form)

        #     print answer_object
        db.session.add(answer_object)
    db.session.commit()

    flash(
        "You have successfully submitted your Victim Compensation Application")
    return redirect('/results')
コード例 #12
0
def create_prepareranswer(checklist_id, question_id, preparer_answer,
                          preparer_time, preparer_comment):

    prepareranswer = Answer(checklist_id=checklist_id,
                            question_id=question_id,
                            preparer_answer=preparer_answer,
                            preparer_comment=preparer_comment,
                            preparer_time=preparer_time)

    db.session.add(prepareranswer)

    db.session.commit()

    return prepareranswer
コード例 #13
0
ファイル: seed.py プロジェクト: ellakcd/PROJECT
def load_answers():
    """Load answers from seed data into database"""

    print "Answers"

    with open("seed_data/answers.txt") as answers:
        for ans in answers:
            ans = ans.rstrip()
            answer_id, question_id, answer = ans.split("|")

            answer = Answer(answer_id=answer_id,
                            question_id=question_id,
                            answer=answer)

            db.session.add(answer)

    db.session.commit()
コード例 #14
0
def safety_plan_process():
    """"Safety plan form is processed"""

    form_id = request.form['form_id']
    form = Form.query.get(form_id)
    victim = Victim.query.get(session["login_id"])

    eastern = pytz.timezone('US/Eastern')
    dt = datetime.now(tz=eastern)
    time_filled = dt.strftime("%A, %B %d %Y %I:%M%p")

    filled_form = Filled_Form(form=form,
                              victim=victim,
                              time_filled=time_filled)
    form_status = Form_Status(filled_form=filled_form,
                              app_received=time_filled)
    # print filled_form
    db.session.add(filled_form)
    db.session.add(form_status)
    db.session.commit()

    question_list = filled_form.form.questions

    for question in question_list:
        key = "section_{}_{}".format(question.section_number,
                                     question.question_number)
        answer_text = request.form[key]

        anwer_object = Answer(question=question,
                              answer_text=answer_text,
                              filled_form=filled_form)
        db.session.add(anwer_object)
        db.session.commit()

    count = 0
    for answer in filled_form.answers:
        if answer.answer_text == 'yes':
            count += 1
    if count > 5:
        return render_template("safety_plan_alert.html")

    flash("You have successfully submitted your Safety Plan Form")
    return redirect('/results')
コード例 #15
0
def get_signup_info():
    """Add user info to database"""
    password = request.json['password']
    result = test_the_password(password)
    if result:
        return jsonify({'error': result})
    else:
        username = request.json['username']
        email = request.json['email']

        hashed_password = hash_password(password)
        user = User(username=username, password=hashed_password, email=email)

        question_id = request.json['userQuestion']
        user_answer = request.json['answer']
        answer = Answer(question_id=question_id, user=user, answer=user_answer)

        db.session.add_all([user, answer])
        db.session.commit()

        return jsonify({'error': result})
コード例 #16
0
ファイル: main.py プロジェクト: tarnfeld/cosmic-hack
def answersGET(question_id):
	question_id = int(question_id)

	key = ndb.Key(Question, question_id)
	question = key.get()
	if question is None:
		return fail_response('Question not found.')

	answers = Answer.query(Answer.question_id == question.key.integer_id()).fetch()

	question = entity_to_dict(question, enum_map={
		'question_type': QuestionType
	})
	question['answers'] = map(
		lambda e: entity_to_dict(e, enum_map={
			'answer_type': AnswerType
		}),
		answers
	)

	return succesful_response(question)
コード例 #17
0
ファイル: server.py プロジェクト: agnaite/self-check
def submit_self_check(self_check_id):
    """Submit a self-check"""

    self_check = QuestionDefinitionSet.query.get(int(self_check_id))
    questions = self_check.question_definitions

    self_check_session = SelfCheckSession(
        timestamp=datetime.now(),
        question_definition_set_id=int(self_check_id))
    db.session.add(self_check_session)
    db.session.commit()

    for question in questions:
        response = request.form.get(str(question.id))
        answer = Answer(response=response,
                        self_check_session_id=self_check_session.id,
                        question_definition_id=question.id)

        db.session.add(answer)

    db.session.commit()

    return redirect("/self-checks")
コード例 #18
0
def update_revieweranswer(checklist_id, question_id, reviewer_ready,
                          reviewer_time, reviewer_comment):

    updaterevieweranswer = Answer(checklist_id=checklist_id,
                                  question_id=question_id,
                                  reviewer_ready=reviewer_ready,
                                  reviewer_time=reviewer_time,
                                  reviewer_comment=reviewer_comment)

    updaterevieweranswer = db.session.query(
        Answer.question_id).filter(Answer.answer_id == question_id).update(
            {Answer.reviewer_ready: reviewer_ready})

    updaterevieweranswercomment = db.session.query(
        Answer.question_id).filter(Answer.question_id == question_id).update(
            {Answer.reviewer_comment: reviewer_comment})

    updaterevieweranswertime = db.session.query(
        Answer.question_id).filter(Answer.question_id == question_id).update(
            {Answer.reviewer_time: reviewer_time})

    db.session.commit()

    return updaterevieweranswer, updaterevieweranswercomment, updaterevieweranswertime
コード例 #19
0
def update_prepareranswer(checklist_id, question_id, preparer_answer,
                          preparer_time, preparer_comment):

    updateprepareranswer = Answer(checklist_id=checklist_id,
                                  question_id=question_id,
                                  preparer_answer=preparer_answer,
                                  preparer_time=preparer_time,
                                  preparer_comment=preparer_comment)

    updateprepareranswer = db.session.query(
        Answer.question_id).filter(Answer.question_id == question_id).update(
            {Answer.preparer_answer: preparer_answer})

    updateprepareranswertime = db.session.query(
        Answer.question_id).filter(Answer.question_id == question_id).update(
            {Answer.preparer_time: preparer_time})

    updateprepareranswercomment = db.session.query(
        Answer.question_id).filter(Answer.question_id == question_id).update(
            {Answer.preparer_comment: preparer_comment})

    db.session.commit()

    return updateprepareranswer, updateprepareranswertime, updateprepareranswercomment
コード例 #20
0
ファイル: main.py プロジェクト: r08922130/ADL
            shuffle=False,
            dataset=data[name],
            batch_size=4 if name == 'train' else 16,
            collate_fn=data[name].collate_fn)
        print(len(data[name]))
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    bert = BertModel.from_pretrained('bert-base-chinese').to(device)
    #print(bert)
    """for name,param in bert.named_parameters():
        param.requires_grad = False
        if "encoder.layer11" in name :
            break"""

    # +2 For CLS and SEP

    model = Answer(input_size=768, answer_size=pre.ctx_max_len + 2).to(device)
    solver = Solver(device, pre.tokenizer)
    #print(bert)
    solver.train(data['train'],
                 data['dev'],
                 bert,
                 model,
                 ctx_max_len=pre.ctx_max_len + 2)
elif arg[1] == 'test':
    for name in ['dev', 'test']:

        if not os.path.isfile(f'processed_data/{name}_test.pkl'):
            print(f"Start {name}......")
            with open(f"data/{name}.json") as f:
                file = json.load(f)
                file = [data for data in file['data']]
コード例 #21
0
def socket_handler(action):

    if action['type'] == 'server/login':
        account = Account.query.filter(
            Account.email == action['data']['email']).first()
        if account and checkpw(action['data']['password'].encode('utf-8'),
                               account.password.encode('utf-8')):
            game = Game.query.filter(Game.account == account,
                                     Game.finished_at == None).first()
            login(account, game)
        else:
            error_message(action['type'], 'Invalid login')

    elif action['type'] == 'server/logout':
        logout()

    elif action['type'] == 'server/register':
        email = action['data']['email']
        password = action['data']['password']
        account = Account.query.filter(Account.email == email).first()
        if not account:
            password = hashpw(password.encode('utf-8'), gensalt())
            try:
                account = Account(email=email,
                                  password=password.decode('utf-8'))
            except AssertionError:
                error_message(action['type'], 'Invalid email address')
            else:
                commit_to_db(account)
                login(account)

    elif action['type'] == 'server/join_game':
        room_id = action['data']['room_id'].upper()
        name = action['data']['name']
        game = Game.query.filter(Game.room_id == room_id,
                                 Game.finished_at == None).first()
        if game and not game.in_progress:
            player = Player.query.filter(Player.game_id == game.game_id,
                                         Player.name == name).first()
            if not player and len(game.players) < 8:
                player = Player(game=game, name=name)
                commit_to_db(player)
                join_game(game, player)
            elif not player and len(game.players) >= 8:
                error_message(action['type'], 'Game is full')
            else:
                error_message(action['type'], 'Duplicate name')
        elif game and game.in_progress:
            error_message(action['type'], 'Game already in progress')
        else:
            error_message(action['type'], 'Invalid room')

    elif action['type'] == 'server/leave_game':
        player_id = action['data']['player_id']
        game_id = action['data']['game_id']
        player = Player.query.filter(Player.player_id == player_id).one()
        game = Game.query.filter(Game.game_id == game_id).one()
        commit_to_db(player, delete=True)
        leave_game(game)

    elif action['type'] == 'server/create_game':
        account_id = action['data']
        account = Account.query.filter(Account.account_id == account_id).one()
        active_game = Game.query.filter(Game.account == account,
                                        Game.finished_at == None).first()
        if not active_game:
            game = Game(account=account, room_id=generate_room_id())
            commit_to_db(game)
            login(account, game)
        else:
            error_message(action['type'],
                          'Game {} is active'.format(active_game.room_id))

    elif action['type'] == 'server/delete_game':
        account_id = action['data']['account_id']
        game_id = action['data']['game_id']
        account = Account.query.filter(Account.account_id == account_id).one()
        game = Game.query.filter(Game.game_id == game_id).one()
        close_game(game)
        delete_game(game)
        login(account)

    elif action['type'] == 'server/start_game':
        game_id = action['data']['game_id']
        game = Game.query.filter(Game.game_id == game_id).one()
        if len(game.players) >= 3 and not game.in_progress:
            assign_prompts(game.players)
            begin_game(game)
            start_game(game)
        elif game.in_progress:
            error_message(action['type'], 'Game already in progress')
        else:
            error_message(
                action['type'],
                'There must be at least 3 players in game in order to play')

    elif action['type'] == 'server/ready':
        player_id = action['data']['player_id']
        node = PlayerPrompt.query.filter(
            PlayerPrompt.player_id == player_id).first()
        prompt = node.prompt
        answer_phase(prompt)

    elif action['type'] == 'server/answer':
        player_id = action['data']['player_id']
        prompt_id = action['data']['prompt_id']
        answer_text = action['data']['answer']
        if answer_text == '':
            answer_text = 'No Answer'
        player = Player.query.filter(Player.player_id == player_id).one()
        players = [p.player_id for p in player.game.players]
        node = PlayerPrompt.query.filter(
            PlayerPrompt.prompt_id == prompt_id,
            PlayerPrompt.player_id.in_(players)).one()
        answer = Answer(player=player, node=node, text=answer_text)
        commit_to_db(answer)
        if player_id == node.player_id:
            next_node = PlayerPrompt.query.filter(
                PlayerPrompt.node_id == node.next_id).one()
            next_prompt = next_node.prompt
            answer_phase(next_prompt)
        elif sum([len(p.answers) - 2 for p in player.game.players]) == 0:
            vote_phase(player.game, node)
        else:
            answer_wait()

    elif action['type'] == 'server/vote':
        player_id = action['data']['player_id']
        answer_id = action['data']['answer_id']
        player = Player.query.filter(Player.player_id == player_id).one()
        answer = Answer.query.filter(Answer.answer_id == answer_id).one()
        node = answer.node
        game = player.game
        players = [p.player_id for p in game.players]
        nodes = PlayerPrompt.query.filter(
            PlayerPrompt.player_id.in_(players)).all()
        vote = Vote(player=player, answer=answer)
        commit_to_db(vote)
        if sum([len(n.answers[0].votes) + len(n.answers[1].votes) - \
            len(players) + 2 for n in nodes]) == 0:
            vote_display(game, node, last=True)
        elif (len(node.answers[0].votes) + len(node.answers[1].votes) - \
            len(players) + 2) == 0:
            vote_display(game, node)
        else:
            vote_wait(node)
コード例 #22
0
ファイル: import_olddb.py プロジェクト: denever/testmanager
        session.commit()

    print "Importing question in each topic..."
    # current_topic = select_topic(session, current_subject)
    # if not current_topic:
    #     sys.exit(1)

    cur.execute("Select question, qtype, answers, topic_id from questions")
    rows = cur.fetchall()

    for row in rows:
        qa = Question(row['qtype'], row['question'])
        qa.topic_id = int(row['topic_id'])
        for answer in row['answers'].split('\n'):
            if answer:
                answ = Answer(answer[6:])
                answ.question = qa
                session.add(answ)
        session.add(qa)
    session.commit()

    print "Importing classes..."

    cur.execute("Select name from classes")
    rows = cur.fetchall()

    for row in rows:
        ac = AlumnClass(name=row['name'])
        print "Select subject for class", ac
        ac.subject = select_subject(session)
        session.add(ac)
コード例 #23
0
def example_data():
    """ Create some sample data. """

    #Programs
    first_program = Program(
        name="Leadership Development Program",
        description="Leadership Development Program Description")

    second_program = Program(
        name="Cognitive Behavioral Therapy",
        description="Cognitive Behavioral Therapy Description")

    third_program = Program(name="New Parenting",
                            description="New Parenting Description")

    fourth_program = Program(name="Mindful Communication",
                             description="Mindful Communication Description")

    #First program's sections
    section_1 = Section(program_id=1,
                        name="Section 1 Program 1'",
                        description="Section 1 Program 1 Description",
                        order_index=1,
                        image_link="",
                        is_last=False)

    section_2 = Section(program_id=1,
                        name="Section 2 Program 1'",
                        description="Section 2 Program 1 Description",
                        order_index=2,
                        image_link="",
                        is_last=False)

    section_3 = Section(program_id=1,
                        name="Section 3 Program 1'",
                        description="Section 3 Program 1 Description",
                        order_index=3,
                        image_link="",
                        is_last=False)

    section_4 = Section(program_id=1,
                        name="Section 4 Program 1'",
                        description="Section 4 Program 1 Description",
                        order_index=4,
                        image_link="",
                        is_last=False)

    section_5 = Section(program_id=1,
                        name="Section 5 Program 1'",
                        description="Section 5 Program 1 Description",
                        order_index=5,
                        image_link="",
                        is_last=False)

    section_6 = Section(program_id=1,
                        name="Section 6 Program 1'",
                        description="Section 6 Program 1 Description",
                        order_index=6,
                        image_link="",
                        is_last=False)

    section_7 = Section(program_id=1,
                        name="Section 7 Program 1'",
                        description="Section 7 Program 1 Description",
                        order_index=7,
                        image_link="",
                        is_last=False)

    section_8 = Section(program_id=1,
                        name="Section 8 Program 1'",
                        description="Section 8 Program 1 Description",
                        order_index=8,
                        image_link="",
                        is_last=False)

    section_9 = Section(program_id=1,
                        name="Section 9 Program 1'",
                        description="Section 9 Program 1 Description",
                        order_index=9,
                        image_link="",
                        is_last=False)

    section_10 = Section(program_id=1,
                         name="Section 10 Program 1'",
                         description="Section 10 Program 1 Description",
                         order_index=10,
                         image_link="",
                         is_last=False)

    activity_1 = Activity(section_id=1,
                          html_content="",
                          question="Question Activity 1")

    activity_2 = Activity(section_id=2,
                          html_content="<html></html>",
                          question="")

    answer_1 = Answer(activity_id=1, answer_text="Activity 1 Answer Text")

    db.session.add_all([
        first_program, second_program, third_program, fourth_program,
        section_1, section_2, section_3, section_4, section_5, section_6,
        section_7, section_8, section_9, section_10, activity_1, activity_2,
        answer_1
    ])
    db.session.commit()
コード例 #24
0
 def mutate(root, info, oid):
     return Ans.objects(oid=str(oid)).delete()
コード例 #25
0
 def mutate(root, info, answer_input):
     tmp = Ans()
     tmp = obj_copy(answer_input, tmp)
     tmp.save()
     tmp.oid = tmp.auto_id_0
     return CreateAnswer(answer=tmp)
コード例 #26
0
def test_seed_data():
    """Seeding questions from Question class into database"""

    print "Seed Complete."
    #creating forms
    safety_plan_form = Form(form_name="Safety Plan")

    #creating login for a victim and for an advocate
    login_1 = Login(user_name='advocate_1', password='******',
                    email='*****@*****.**', name='Denise')

    login_2 = Login(user_name='victim_1', password='******',
                    email='*****@*****.**', name='Lauren')

    #creating agency type
    agency_type_1 = Agency_Type(agency_type="Domestic Violence Center")

    # #creating agency
    agency_1 = Agency(agency_name="The Haven",
                      agency_address='1412 North Fort Harrison Clearwater Fl',
                      agency_phone=7274424128, agency_type=agency_type_1)

    #creating shelter
    s1 = 'Monday, February 01, 2018'
    shelter_information_1 = Shelter_Information(agency=agency_1, number_beds=42,
                                                next_available_date=datetime.strptime(s1, "%A, %B %d, %Y"))

    #creating advocate
    advocate_1 = Advocate(login=login_1, shelter_information=shelter_information_1,
                          position_name="Legal Advocate")
    #creating victim
    victim_1 = Victim(login=login_2, advocate=advocate_1)


    s2 = 'Monday, January 01, 2019'
    safety_plan_filled_form = Filled_Form(form=safety_plan_form, victim=victim_1,
                                          time_filled=datetime.strptime(s2, "%A, %B %d, %Y"))


# ****************************Safety Plan Form**********************************

    # A "Yes" response to any of Questions #1-3 automatically triggers the protocol referral.
    question_1 = Question(question_text="""Has he/she ever used a weapon against
                          you/threatened you with a weapon""",
                          question_number=1,
                          section_number=1,
                          answer_required=True,
                          form=safety_plan_form)

    question_2 = Question(question_text="""Has he/she threatened to
                          kill you or your children?""",
                          question_number=2,
                          section_number=1,
                          answer_required=True,
                          form=safety_plan_form)

    question_3 = Question(question_text="Do you think he/she might try to kill you?",
                          question_number=3,
                          section_number=1,
                          answer_required=True,
                          form=safety_plan_form)

    # Negative responses to Questions #1-3, but positive responses to at least four of Questions #4-11,
    #trigger the protocol referral.
    question_4 = Question(question_text="""Does he/she have a gun or can he/she
                          get one easily?""",
                          question_number=4,
                          section_number=2,
                          answer_required=True,
                          form=safety_plan_form)

    question_5 = Question(question_text="Has he/she ever tried to choke you?",
                          question_number=5,
                          section_number=2,
                          answer_required=True,
                          form=safety_plan_form)

    question_6 = Question(question_text="""Is he/she violently or constantly
                                    jealous or does he/she control most of your
                                    daily activities?""",
                          question_number=6,
                          section_number=2,
                          answer_required=True,
                          form=safety_plan_form)

    question_7 = Question(question_text="""Have you left him/her or separated
                          after living together or being married?""",
                          question_number=7,
                          section_number=2,
                          answer_required=True,
                          form=safety_plan_form)
    question_8 = Question(question_text="Is he/she unemployed?",
                          question_number=8,
                          section_number=2,
                          answer_required=True,
                          form=safety_plan_form)
    question_9 = Question(question_text="Has he/she ever tried to kill himself/herself?",
                          question_number=9,
                          section_number=2,
                          answer_required=True,
                          form=safety_plan_form)
    question_10 = Question(question_text="Do you have a child that he/she knows is not his/hers?",
                           question_number=10,
                           section_number=2,
                           answer_required=True,
                           form=safety_plan_form)
    question_11 = Question(question_text="""Does he/she follow or spy on
                            you or leave threatening message?""",
                           question_number=11,
                           section_number=2,
                           answer_required=True,
                           form=safety_plan_form)
    question_12 = Question(question_text="""Is there anything else that worries
                            you about your safety? (If 'yes')
                            What worries you?""",
                           question_number=12,
                           section_number=3,
                           answer_required=True,
                           form=safety_plan_form)


    #creating answers for safety plan filled form
    answer_1 = Answer(question=question_1, answer_text='yes',
                      filled_form=safety_plan_filled_form)
    answer_2 = Answer(question=question_2, answer_text='no',
                      filled_form=safety_plan_filled_form)
    answer_3 = Answer(question=question_3, answer_text='yes',
                      filled_form=safety_plan_filled_form)
    answer_4 = Answer(question=question_4, answer_text='no',
                      filled_form=safety_plan_filled_form)
    answer_5 = Answer(question=question_5, answer_text='yes',
                      filled_form=safety_plan_filled_form)
    answer_6 = Answer(question=question_6, answer_text='no',
                      filled_form=safety_plan_filled_form)
    answer_7 = Answer(question=question_7, answer_text='yes',
                      filled_form=safety_plan_filled_form)
    answer_8 = Answer(question=question_8, answer_text='no',
                      filled_form=safety_plan_filled_form)
    answer_9 = Answer(question=question_9, answer_text='yes',
                      filled_form=safety_plan_filled_form)
    answer_10 = Answer(question=question_10, answer_text='no',
                       filled_form=safety_plan_filled_form)
    answer_11 = Answer(question=question_11, answer_text='yes',
                       filled_form=safety_plan_filled_form)
    answer_12 = Answer(question=question_12, answer_text="Im ok",
                       filled_form=safety_plan_filled_form)

    db.session.add_all([safety_plan_form,
                        #Questions to Safety Plan Form 
                        question_1, question_2, question_3, question_4,
                        question_5, question_6, question_7, question_8,
                        question_9, question_10, question_11, question_12,
                        #Answers to Safety Plan Form 
                        answer_1, answer_2, answer_3, answer_4, answer_5,
                        answer_6, answer_7, answer_8, answer_9, answer_10,
                        answer_11, answer_12, 
                        safety_plan_filled_form,
                        login_1, login_2, agency_type_1,
                        agency_1, shelter_information_1, 
                        advocate_1, victim_1])

# *******************Victim Compensation Form**********************************

    victim_comp_form = Form(form_name="Victim Compensation Application")

    question_1 = Question(question_text="Name: (last, first, middle)",
                          question_number=1,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_2 = Question(question_text="Date of Birth: (MM-DD-YYYY)",
                          question_number=2,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_3 = Question(question_text="E-mail address",
                          question_number=3,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_4 = Question(question_text="Address:",
                          question_number=4,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_5 = Question(question_text="City:",
                          question_number=5,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_6 = Question(question_text="State:",
                          question_number=6,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_7 = Question(question_text="Zipcode:",
                          question_number=7,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_8 = Question(question_text="Telephone Number:",
                          question_number=8,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_9 = Question(question_text="Occupation: (optional)",
                          question_number=9,
                          section_number=1,
                          answer_required=True,
                          form=victim_comp_form)

    question_10 = Question(question_text="Race/Ethnicity:",
                           question_number=10,
                           section_number=1,
                           answer_required=True,
                           form=victim_comp_form)

    question_11 = Question(question_text="Gender:",
                           question_number=11,
                           section_number=1,
                           answer_required=True,
                           form=victim_comp_form)

    question_12 = Question(question_text="National Origin:",
                           question_number=12,
                           section_number=1,
                           answer_required=True,
                           form=victim_comp_form)

    question_13 = Question(question_text="Were you disabled before the crime?:",
                           question_number=13,
                           section_number=1,
                           answer_required=True,
                           form=victim_comp_form)

    question_14 = Question(question_text="Name of person assisting with application (last, first, middle):",
                           question_number=14,
                           section_number=2,
                           answer_required=True,
                           form=victim_comp_form)

    question_15 = Question(question_text="Email address:",
                           question_number=15,
                           section_number=2,
                           answer_required=True,
                           form=victim_comp_form)

    question_16 = Question(question_text="Name of Agency/Organization:",
                           question_number=16,
                           section_number=2,
                           answer_required=True,
                           form=victim_comp_form)

    question_17 = Question(question_text="Agency/Organization's Address: (address, city, state, zip code)",
                           question_number=17,
                           section_number=2,
                           answer_required=True,
                           form=victim_comp_form)

    question_18 = Question(question_text="Telephone Number:",
                           question_number=18,
                           section_number=2,
                           answer_required=True,
                           form=victim_comp_form)

    question_19 = Question(question_text="Is Insurance or Medicaid Available to assist with these expenses?:",
                           question_number=19,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_20 = Question(question_text="Medicaid Number:",
                           question_number=20,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_21 = Question(question_text="Company Name:",
                           question_number=21,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_22 = Question(question_text="Policy Number:",
                           question_number=22,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_23 = Question(question_text="Telephone Number:",
                           question_number=23,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_24 = Question(question_text="Address:",
                           question_number=24,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_25 = Question(question_text="City:",
                           question_number=25,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_26 = Question(question_text="State:",
                           question_number=26,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_27 = Question(question_text="Zipcode:",
                           question_number=27,
                           section_number=3,
                           answer_required=False,
                           form=victim_comp_form)

    question_28 = Question(question_text="Name of Law Enforcement Agency:",
                           question_number=28,
                           section_number=4,
                           answer_required=True,
                           form=victim_comp_form)

    question_29 = Question(question_text="Date of Crime:",
                           question_number=29,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_30 = Question(question_text="Date Reported To Law Enforcement Agency:",
                           question_number=30,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_31 = Question(question_text="Was the crime reported to law enforcement within 72 hours?",
                           question_number=31,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_32 = Question(question_text="""If no, please explain. (If no, failure
                           to provide an acceptable explanation
                           in this section will result in a denial of benefits.""",
                           question_number=32,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_33 = Question(question_text="""Is the application and and law
                           enforcement report being submitted within one year
                           from the date of crime?""",
                           question_number=33,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_34 = Question(question_text="""If no, please explain.
                                (Please be advised that most benefi ts apply to
                                treatment losses suffered within one year from
                                the date of crime, with some exceptions for minor victims.
                                If no, failure to provide an acceptable explanation
                                in this section will result in a denial of benefits.)?""",
                           question_number=34,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_35 = Question(question_text="""Type of crime as specified on the
                           law enforcement report?""",
                           question_number=35,
                           section_number=4,
                           answer_required=True,
                           form=victim_comp_form)

    question_36 = Question(question_text="""Law Enforcement report number""",
                           question_number=36,
                           section_number=4,
                           answer_required=True,
                           form=victim_comp_form)

    question_37 = Question(question_text="""Name of Law Enforcement Officer""",
                           question_number=37,
                           section_number=4,
                           answer_required=True,
                           form=victim_comp_form)

    question_38 = Question(question_text="""Name of offender (if known)""",
                           question_number=38,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_39 = Question(question_text="""Name of Assistant State Attorney
                                Handling the case (if applicable)""",
                           question_number=39,
                           section_number=4,
                           answer_required=False,
                           form=victim_comp_form)

    question_40 = Question(question_text="""State Attorney/Clerk of Court case
                           Number""",
                           question_number=40,
                           section_number=4,
                           answer_required=True,
                           form=victim_comp_form)
    #Victim Signature
    question_41 = Question(question_text="""Printed Name""",
                           question_number=41,
                           section_number=5,
                           answer_required=True,
                           form=victim_comp_form)

    question_42 = Question(question_text="""Signature""",
                           question_number=42,
                           section_number=5,
                           answer_required=True,
                           form=victim_comp_form)

    question_43 = Question(question_text="""Date""",
                           question_number=43,
                           section_number=5,
                           answer_required=True,
                           form=victim_comp_form)


    # #TO DO: SEE if can use timestamp in order to see the time the form was sent
    # #creating filled victim compensation form
    s2 = 'Monday, January 01, 2018'
    victim_comp_filled_form = Filled_Form(form=victim_comp_form, victim=victim_1,
                                          time_filled=datetime.strptime(s2, "%A, %B %d, %Y"))

    # #creating answers for safety plan filled form
    answer_1 = Answer(question=question_1, answer_text="Sarah Smith",
                      filled_form=victim_comp_filled_form)
    answer_2 = Answer(question=question_2, answer_text="Answer text 2",
                      filled_form=victim_comp_filled_form)
    answer_3 = Answer(question=question_3, answer_text="Answer text 3",
                      filled_form=victim_comp_filled_form)
    answer_4 = Answer(question=question_4, answer_text="Answer text 4",
                      filled_form=victim_comp_filled_form)
    answer_5 = Answer(question=question_5, answer_text="Answer text 5",
                      filled_form=victim_comp_filled_form)
    answer_6 = Answer(question=question_6, answer_text="Answer text 6",
                      filled_form=victim_comp_filled_form)
    answer_7 = Answer(question=question_7, answer_text="Answer text 7",
                      filled_form=victim_comp_filled_form)
    answer_8 = Answer(question=question_8, answer_text="Answer text 8",
                      filled_form=victim_comp_filled_form)
    answer_9 = Answer(question=question_9, answer_text="Answer text 9",
                      filled_form=victim_comp_filled_form)
    answer_10 = Answer(question=question_10, answer_text="Answer text 10",
                       filled_form=victim_comp_filled_form)
    answer_11 = Answer(question=question_11, answer_text="Answer text 11",
                       filled_form=victim_comp_filled_form)
    answer_12 = Answer(question=question_12, answer_text="Answer text 12",
                       filled_form=victim_comp_filled_form)
    answer_13 = Answer(question=question_13, answer_text="Answer text 13",
                       filled_form=victim_comp_filled_form)
    answer_14 = Answer(question=question_14, answer_text="Answer text 14",
                       filled_form=victim_comp_filled_form)
    answer_15 = Answer(question=question_15, answer_text="Answer text 15",
                       filled_form=victim_comp_filled_form)
    answer_16 = Answer(question=question_16, answer_text="Answer text 16",
                       filled_form=victim_comp_filled_form)
    answer_17 = Answer(question=question_17, answer_text="Answer text 17",
                       filled_form=victim_comp_filled_form)
    answer_18 = Answer(question=question_18, answer_text="Answer text 18",
                       filled_form=victim_comp_filled_form)
    answer_19 = Answer(question=question_19, answer_text="Answer text 19",
                       filled_form=victim_comp_filled_form)
    answer_20 = Answer(question=question_20, answer_text="Answer text 20",
                       filled_form=victim_comp_filled_form)
    answer_21 = Answer(question=question_21, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_22 = Answer(question=question_22, answer_text="Answer text 22",
                       filled_form=victim_comp_filled_form)
    answer_23 = Answer(question=question_23, answer_text="Answer text 23",
                       filled_form=victim_comp_filled_form)
    answer_24 = Answer(question=question_24, answer_text="Answer text 24",
                       filled_form=victim_comp_filled_form)
    answer_25 = Answer(question=question_25, answer_text="Answer text 25",
                       filled_form=victim_comp_filled_form)
    answer_26 = Answer(question=question_26, answer_text="Answer text 26",
                       filled_form=victim_comp_filled_form)
    answer_27 = Answer(question=question_27, answer_text="Answer text 27",
                       filled_form=victim_comp_filled_form)
    answer_28 = Answer(question=question_28, answer_text="Answer text 28",
                       filled_form=victim_comp_filled_form)
    answer_29 = Answer(question=question_29, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_30 = Answer(question=question_30, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_31 = Answer(question=question_31, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_32 = Answer(question=question_32, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_33 = Answer(question=question_33, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_34 = Answer(question=question_34, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_35 = Answer(question=question_35, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_36 = Answer(question=question_36, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_37 = Answer(question=question_37, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_38 = Answer(question=question_38, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_39 = Answer(question=question_39, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_40 = Answer(question=question_40, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_41 = Answer(question=question_41, answer_text="Answer text 21",
                       filled_form=victim_comp_filled_form)
    answer_42 = Answer(question=question_42, answer_text="04/24/2018",
                       filled_form=victim_comp_filled_form)







    # #adding to objects to session
    db.session.add_all([#Questions to Victim Compensation Form 
                        question_1, question_2, question_3, question_4,
                        question_5, question_6, question_7, question_8,
                        question_9, question_10, question_11, question_12,
                        question_13, question_14, question_15, question_16, question_17,
                        question_18, question_19, question_20, question_21, question_22, question_23,
                        question_24, question_25, question_26, question_27, question_28, question_29,
                        question_30, question_31, question_32, question_33, question_34, question_35,
                        question_36, question_37, question_38, question_39, question_40, question_41,
                        question_42, question_43, 
                        #Answers to Victim Compensation Form
                        answer_1, answer_2, answer_3, answer_4, answer_5,
                        answer_6, answer_7, answer_8, answer_9, answer_10,
                        answer_11, answer_12, answer_13, answer_14, answer_15, answer_16, answer_17,
                        answer_18, answer_19, answer_20, answer_21, answer_22,
                        answer_23, answer_24, answer_25, answer_26, answer_27, answer_28, answer_29,
                        answer_30, answer_31, answer_32, answer_33, answer_34,
                        answer_35, answer_36, answer_37, answer_38, answer_39, answer_40, answer_41,
                        answer_6, answer_7, answer_8, answer_9, answer_10,
                        answer_42, victim_comp_form, victim_comp_filled_form])


    #commiting objects
    db.session.commit()
コード例 #27
0
def parse_text(lines):
    code_block_start = False
    code_block_added = False
    questions = []
    question = Question()
    last_matched_pattern = None

    for l, line in enumerate(lines):
        # disregard comments or empty lines
        if line.startswith("--") or line == "\n":
            continue

        # beginning question statement
        matched = question_start.match(line)
        if matched:
            last_matched_pattern = question_start.pattern
            if question.empty and not code_block_start:
                question.before.append(matched.groups()[1].strip())
                continue

        # possible answers statement
        matched = answers.match(line)
        if matched and not question.before:
            last_matched_pattern = answers.pattern
            question.answers.append(Answer(text=matched.groups()[1].strip()))
            continue

        # possible code block
        matched = codeblock.match(line)
        if matched:
            last_matched_pattern = codeblock.pattern
            if code_block_start:
                code_block_start = False
                code_block_added = True
            else:
                code_block_start = True
            continue

        # possible code line - only valid if code_block_start is on
        matched = codeline.match(line)
        if matched:
            last_matched_pattern = codeline.pattern
            if code_block_start:
                question.code.append(matched.groups()[1])
                continue

        # continuing question statement - set last so any lines that don't
        # match are sent here
        matched = question_continue.match(line)
        if matched:
            last_matched_pattern = question_continue.pattern
            container = question.before if not code_block_added else question.after
            container.append(matched.group().strip())
            continue

        # correct answer statement - reached end of question. serialize it
        matched = answer.match(line)
        if matched:
            last_matched_pattern = answer.pattern
            # somehow code block was entered but not correctly escaped
            if code_block_start:
                raise ValueError(f"{l+1}: Code block not correctly ended")
            question.set_correct_answers(matched.groups()[1].strip())

            # serialize question
            serialized_question = question.serialize()
            questions.append(serialized_question)
            question.clear()
            code_block_start = False
            code_block_added = False
            continue

        print_reader_error(question, len(questions), l, line, code_block_start,
                           code_block_added, last_matched_pattern)
        break

    return questions
コード例 #28
0
        if not data['qtype']:
            loop = False if safe_prompt(session, "Continue? ") in ("N",'n','No','no') else True
            continue

        data['question'] = safe_prompt(session, "Question: ")
        if not data['question']:
            loop = False if safe_prompt(session, "Continue? ") in ("N",'n','No','no') else True
            continue

        qa = Question(**data)
        qa.topic = current_topic
        session.add(qa)
        session.commit()
        
        if data['qtype'] in ('BC','bc','b'):
            true = Answer('Vero')
            true.question = qa
            false = Answer('Falso')
            false.question = qa
            session.add(true)
            session.add(false)
        else:
            subloop = True
            answer_id = 1            
            while subloop:
                answer = safe_prompt(session, 'Answer %s: ' % answer_id)
                if not answer: break
                answ = Answer(answer)
                answ.question = qa
                session.add(answ)
                answer_id += 1