예제 #1
0
파일: watson.py 프로젝트: LHBDev/211-WebApp
    def log(self, question, r):
        logging.info('Updating datastore with question.')
        # Insert question into datastore
        response = json.loads(r.content)
        answers = response['question']['answers']
        answer = answers[0]['text'] if len(answers) > 0 else 'No answer given'
        phone_number = int(self.request.get('p', '0'))
        q = Question(phone_number=phone_number,
                     question=question,
                     response=response,
                     answer=answer)
        q.put()

        # Update user stats
        # This isn't atomic, I don't think it's a big deal though.
        user = Stats.query(Stats.phone_number == phone_number).fetch()
        if len(user) > 0:
          user = user[0]
        else:
          user = Stats(phone_number=phone_number,
                       number_of_questions=0,
                       most_recent_question=datetime.min)
        user.number_of_questions += 1
        user.most_recent_question = q.time
        user.put()
예제 #2
0
 def test_get_random(self):
     """Test the get_random method for the Question model."""
     with self.app_context:
         question = Question.get_random(self.c_1.id, [self.q_1.id])
         self.assertIsNone(question)
         question = Question.get_random(self.c_2.id, [self.q_2.id])
         self.assertIsNotNone(question)
         self.assertEqual(question, self.q_3.format())
예제 #3
0
 def edit_question(q_id, question, activate):
     if question != None:
       escaped_question = escape(question)
       Question.by_id(q_id).question = question
     else:
       escaped_question = None
     Question.by_id(q_id).available = activate
     return json.dumps({"id":q_id,"text":escaped_question,"available":activate})
예제 #4
0
    def get_questions():
        questions = Question.get_by_page(request, QUESTIONS_PER_PAGE)

        if len(questions) == 0:
            abort(404)

        return jsonify({
            "questions": questions,
            "total_questions": len(Question.get_all()),
            "success": True,
            "categories": Category.to_dict(),
        })
def getLevel(identifier):
    """Get a level with its questions and their responses"""

    # Get the connection
    conn = getConnection()

    # Get the question
    question_cursor = executeRequest(
        """SELECT Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id
        FROM Level 
        INNER JOIN Question ON Level.Id = Question.IdLevel 
        INNER JOIN Response ON Question.Id = Response.IdQuestion 
        WHERE Level.Id = """ + identifier + """
        ORDER BY Question.Id, Response.Value""", conn)

    if question_cursor is not None:
        level = None
        current_question = None
        for row in question_cursor.fetchall():
            # Title
            if level is None:
                level = Level()
                level.id = row[0]
                level.title = row[1]

            # Question
            if current_question is None or current_question.id != row[1]:
                current_question = Question()
                current_question.id = row[2]
                current_question.question = row[3]
                current_question.id_level = level.id
                level.questions.append(current_question)

            # Responses
            Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id
            response = Response()
            response.value = row[4]
            response.response = row[5]
            response.id = row[6]
            response.id_question = current_question.id
            current_question.responses.append(response)

        # Set the result
        result = getHTTPResponse(200, level)
    else:
        # Level does not exist
        result = getHTTPResponse(500, "This level does not exist", False)

    conn.close()

    return result
예제 #6
0
    def test_load_question_from_index(self):
        question = Question(pub_date=timezone.now() -
                            datetime.timedelta(days=3),
                            question_text='Foo Bar')
        question.save()

        self.selenium.get('%s%s' %
                          (self.live_server_url, reverse('polls:index')))
        self.selenium.find_element_by_css_selector(
            'a[data-question-id="{}"]'.format(question.id)).click()
        # Wait until the response is received
        WebDriverWait(
            self.selenium,
            2).until(lambda driver: driver.find_element_by_tag_name('body'))
예제 #7
0
 def __init__(self, request):        
     # lele add dummy questions le
     if len(Question.get_all()) == 0:
         print "I MAEK DUMMY SHIZZLE"
         userID = g.lti.get_user_id()
         q1 = Question("1","1","What am I?",True,1000)
         q2 = Question("2","1","Who am I?",True,1000)
         q3 = Question("3","1","Where am I?",True,1000)
         session.add(q1)
         session.add(q2)
         session.add(q3)
         a11 = AnswerModel("einseins",1,userID,0,1000.0)
         a12 = AnswerModel("einszwei",1,1338,  0,1000.0)
         a13 = AnswerModel("einsdrei",1,1339,  0,1000.0)
         a21 = AnswerModel("zweieins",2,userID,0,1000.0)
         a22 = AnswerModel("zweizwei",2,1338,  0,1000.0)
         a23 = AnswerModel("zweidrei",2,1339,  0,1000.0)
         a31 = AnswerModel("dreieins",3,userID,0,1000.0)
         a32 = AnswerModel("dreizwei",3,1338,  0,1000.0)
         a33 = AnswerModel("dreidrei",3,1339,  0,1000.0)
         session.add(a11)
         session.add(a12)
         session.add(a13)
         session.add(a21)
         session.add(a22)
         session.add(a23)
         session.add(a31)
         session.add(a32)
         session.add(a33)
         session.commit()
예제 #8
0
 def build_question(article) -> Question:
     return Question(title=get_title(article),
                     time=get_time(article),
                     time_relative=get_time_relative(article),
                     who_asked=get_who_asked(article),
                     answer=get_answer(article),
                     image_url=get_image_url(article))
예제 #9
0
 def create_question(self, quiz_id, temp_question):
     """create a new question and add it to the store and to the quiz"""
     new_question = Question(**temp_question)
     self.get_quiz_by_id(quiz_id).add_question_by_id(
         new_question.question_id)
     self.questions[new_question.question_id] = new_question
     return new_question.question_id
예제 #10
0
    def edit_question(q_id, question, time):
        """Updates a question with given contents and activation status."""
        if g.lti.is_instructor():
            if question is None:
                escaped_question = None
            else:
                escaped_question = escape(question)

            escaped_time = escape(time)
            q = Question.by_id(q_id)
            q.question = escaped_question
            q.time = int(time)
            activate = q.answerable

            session.add(q)
            session.commit()

            return json.dumps({"id": q_id,
                               "text": escaped_question,
                               "answerable": activate,
                               "time":time,
                               "check": g.lti.is_instructor()})
        else:
            return json.dumps({"id": q_id,
                               "text": question,
                               "answerable": activate,
                               "time": time,
                               "check": g.lti.is_instructor()})
    def find_best_split(self, rows):
        """ Find the best question to ask by iterating over every feature / value
        and calculating the information gain. """
        best_gain = 0  # keep track of the best information gain
        best_question = None  # keep train of the feature / value that produced it
        current_uncertainty = self.gini(rows)
        n_features = len(rows[0]) - 1  # number of columns minus one

        for col in range(1, n_features + 1):  # for each feature
            values = set([row[col]
                          for row in rows])  # unique values in the column

            for val in values:  # for each value
                question = Question(self.__header, col, val)

                # try splitting the dataset
                true_rows, false_rows = self.partition(rows, question)

                # Skip this split if it doesn't divide the dataset.
                if len(true_rows) == 0 or len(false_rows) == 0:
                    continue

                # Calculate the information gain from this split
                gain = self.info_gain(true_rows, false_rows,
                                      current_uncertainty)

                if gain >= best_gain:
                    best_gain, best_question = gain, question

        return best_gain, best_question
예제 #12
0
    def delete_question(qid):
        question = Question.by_id(int(qid))
        if g.lti.is_instructor():
            session.delete(question)
            session.commit()

        return json.dumps({'deleted': g.lti.is_instructor()})
예제 #13
0
def new_poll() -> Response:
    form = QuestionForm()
    if form.validate_on_submit() and 'cover' in request.files:
        if 'cover' not in request.files:
            flash('No file')
            return redirect(request.url)

        cover = request.files['cover']
        if cover and allowed_file(cover.filename):
            filename = secure_filename(cover.filename)
            cover.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        question = form.data['question']
        option1 = form.data['option1']
        option2 = form.data['option2']
        option3 = form.data['option3']
        option4 = form.data['option4']

        question = Question(question=question,
                            cover=secure_filename(cover.filename),
                            options=[
                                Options(choice=option1),
                                Options(choice=option2),
                                Options(choice=option3),
                                Options(choice=option4)
                            ])
        db.session.add(question)
        db.session.commit()

        flash('Your poll is added now')
        return redirect(url_for('main'))
    return render_template('polls/newpoll.html', form=form)
예제 #14
0
 def renderanswerform():
     try:
         questionid = int(request.values['question_id'])
         question = Question.by_id(questionid)
     except:
         return abort(404)
     return render_template('student_answer.html', question = question)
예제 #15
0
파일: user.py 프로젝트: wdvill/cloud_admin
def question_create(user, params):
    question_id = utils.safe_id(params.get("question_id"))
    answer = params.get("answer")
    if not question_id or not answer:
        return {"error_code": 80002, "msg": "no enough parameters"}

    question = Question.select().where(Question.id == question_id).first()
    if not question:
        return {"error_code": 20242, "msg": "protect question not exists"}

    uq = UserQuestion.select().where(UserQuestion.user == user).first()
    if uq:
        return {"error_code": 20243, "msg": "password question already exists"}

    u = UserQuestion()
    u.user = user
    u.question = question
    u.answer = answer
    u.save()

    queue.to_queue({
        "type":
        "user_question_create",
        "user_id":
        user.id,
        "team_id":
        user.identify[1:] if user.identify[0] != "f" else None
    })
    return {"error_code": 0, "msg": "ok"}
예제 #16
0
def update_poll(id):
    poll = Question.query.filter_by(id=id).first()
    form = QuestionForm(
        question=poll.question,
        option1=poll.options[0],
        option2=poll.options[1],
        option3=poll.options[2],
        option4=poll.options[3],
    )
    if form.validate_on_submit():
        question = form.data['question']
        option1 = form.data['option1']
        option2 = form.data['option2']
        option3 = form.data['option3']
        option4 = form.data['option4']
        poll = Question(question=question,
                        options=[
                            Options(choice=option1),
                            Options(choice=option2),
                            Options(choice=option3),
                            Options(choice=option4)
                        ])
        db.session.add(poll)
        db.session.commit()
        flash('Your poll is update now')
        return redirect(url_for(f'polls/{id}'))
    return render_template('polls/update_poll.html', poll_data=poll, form=form)
예제 #17
0
def get(q_id):
    query = Question.objects(question_id=q_id)
    if query:
        question = query[0]
        return question.to_dict()
    else:
        return None
예제 #18
0
def add_question(qtype, qtext, hint, img, handler):
    question = Question()
    cookies = h.get_default_cookies(handler)
    current_user = h.get_current_user(cookies)
    if current_user:
        question.user = current_user
    question.qtype = int(qtype)
    question.qtext = qtext
    question.hint = hint
    question.img = img
    question.status = 1
    question.put()
    return question
예제 #19
0
    def questions_by_category(category_id):
        questions = Question.get_by_category_by_page(category_id, request,
                                                     QUESTIONS_PER_PAGE)

        if len(questions) == 0:
            abort(404)

        return jsonify({
            "questions":
            questions,
            "total_questions":
            len(Question.get_by_category(category_id)),
            "current_category":
            Category.get_by_id(category_id).type,
            "success":
            True,
        })
예제 #20
0
    def create_question():
        data = request.get_json()
        question = Question(**data)
        result = question.insert_record()

        if result["error"]:
            abort(500)

        _id = result["id"]
        questions = Question.get_by_page(request, QUESTIONS_PER_PAGE)

        return jsonify({
            "created": _id,
            "questions": questions,
            "total_questions": len(Question.get_all()),
            "success": True,
        })
예제 #21
0
 def get_list():
     questions = Question.get_filtered()
     for question in questions:
         if question is not None and question.activate_time is not None:
             if question.get_time_left() < 0:
                 question.answerable = False
     session.commit()
     return render_template('question_list.html', questions=questions)
예제 #22
0
    def delete_question(qid):
        '''removes the question with the provided id from the database'''
        question = Question.by_id(int(qid))
        if g.lti.is_instructor():
            session.delete(question)
            session.commit()

        return json.dumps({'deleted': g.lti.is_instructor()})
예제 #23
0
def getAll():
    """Get all levels with their questions and their responses"""

    # Get the connection
    conn = getConnection()

    # Get the question
    question_cursor = executeRequest(
        """SELECT Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id
        FROM Level 
        INNER JOIN Question ON Level.Id = Question.IdLevel 
        INNER JOIN Response ON Question.Id = Response.IdQuestion 
        ORDER BY Level.Id, Question.Id, Response.Value""", conn)
    levels = []
    current_level = None
    current_question = None
    for row in question_cursor.fetchall():
        # New level with title
        if current_level is None or current_level.id != row[0]:
            current_level = Level()
            current_level.id = row[0]
            current_level.title = row[1]
            levels.append(current_level)

        # Question
        if current_question is None or current_question.id != row[2]:
            current_question = Question()
            current_question.id = row[2]
            current_question.id_level = current_level.id
            current_question.question = row[3]
            current_level.questions.append(current_question)

        # Responses
        response = Response()
        response.value = row[4]
        response.response = row[5]
        response.id = row[6]
        response.id_question = current_question.id
        current_question.responses.append(response)

    # Set the result
    result = getHTTPResponse(200, levels)
    conn.close()

    return result
예제 #24
0
 def test_get_by_id(self):
     """Test the get_by_id method for the Question model."""
     with self.app_context:
         question = Question.get_by_id(self.q_1.id)
         self.assertIsNotNone(question)
         self.assertEqual(question.question, self.q_1.question)
         self.assertEqual(question.answer, self.q_1.answer)
         self.assertEqual(question.difficulty, self.q_1.difficulty)
         self.assertEqual(question.category_id, self.q_1.category_id)
예제 #25
0
 def get(self):
     c = h.context()
     query = Question.all()
     results = query.fetch(1000)
     for q in results:
         q.i = str(q.img.key())
         q.k = q.key()
     c['questions'] = results
     h.render_out(self, 'question_admin.tplt', c)
예제 #26
0
def delete(q_id):
    question = Question.objects(question_id=q_id).first()
    q_id = question.question_id
    if question:
        question.delete()
        log.debug("## Question Deleted : ID {}".format(q_id))
        return True, None
    else:
        return False, "Question not found"
 def __build_question(post):
     if not post:
         return None
     return Question(title=post['title'],
                     time=post['time'],
                     time_relative=None,
                     who_asked=post['who_asked'],
                     answer=post['answer'],
                     image_url=post['image_url'])
예제 #28
0
파일: main.py 프로젝트: yamap55/peing_clone
def add_user():

    def create_user(name, password):
        salt = create_salt()
        password_hash = calculate_password_hash(password, salt)
        return User(name=name, password_hash=password_hash, salt=salt)

    db.create_all()

    user1 = create_user('a', "aa")
    user2 = create_user('b', "bb")
    user3 = create_user('c', "cc")
    db.session.add(user1)
    db.session.add(user2)
    db.session.add(user3)
    user1.questions = [Question(detail='x?', answer='yy!'), Question(detail='z?')]
    user2.questions = [Question(detail='aaa?', answer='bbb!')]
    db.session.commit()
예제 #29
0
파일: service.py 프로젝트: drootnar/Gabbie
 def add_message(self, room_id, data):
     schema = MessageSchema()
     result = schema.load(data)
     if result.errors:
         abort(400, result.errors)
     question = Question(result.data)
     self.db.session.add(question)
     self.db.session.commit()
     return question
    def __find_questions(self, paragraphs: list) -> list:
        questions = []
        for index, paragraph in enumerate(paragraphs):

            is_list = paragraph.style.name == 'List Paragraph'
            has_question_number = re.match('^[0-9]\.', paragraph.text)
            has_start = re.search('@start', paragraph.text)

            if is_list or has_question_number or has_start:
                leng = len(questions)
                if leng != 0:
                    questions[leng - 1].end = index - 1
                q = Question()
                q.start = index
                questions.append(q)
                self.__format_paragraphs(paragraph, len(questions))
        questions[len(questions) - 1].end = len(paragraphs)
        return questions
예제 #31
0
def generate_questions(group_conf):
    df = group_conf['df']
    name = f"Conseil d'administration {group_conf['semester']}"
    if group_conf['semester'] == 'Annuel':
        description = "Vote de confiance pour les postes annuels au conseil d'administration de l'AGEG."
        code = f"CA{group_conf['semester']}"
        title = "Qui voulez-vous comme administrateurs annuels de l'AGEG?"
    else:
        description = "Vote de confiance pour les postes saisonniers au conseil d'administration de l'AGEG."
        code = "CAS" + group_conf['semester']
        title = "Qui voulez-vous comme administrateurs saisonniers de l'AGEG?"
    group = Group(name, description)

    question_admin = Question(code=code, gid=group.gid, title=title, qtype='F')

    question_admin.add_answer(
        Answer(qid=question_admin.qid, value="Oui", code="A1", order=1))
    question_admin.add_answer(
        Answer(qid=question_admin.qid, value="Non", code="A2", order=2))
    question_admin.add_answer(
        Answer(qid=question_admin.qid,
               value="Non confiance",
               code="A3",
               order=3))

    sous_questions = []
    for index, candidat in df.iterrows():
        subquestion = Subquestion(parent=question_admin.qid,
                                  gid=question_admin.gid,
                                  code=f"SQ{index + 1:02}",
                                  value=candidat[NOM_USUEL],
                                  order=index,
                                  qtype='T')
        sous_questions.append(subquestion)

        question_admin.add_option(
            Option(nom=candidat[NOM_USUEL],
                   promotion=candidat[PROMOTION],
                   concentration=candidat[CONCENTRATION],
                   order=index,
                   description=candidat[TEXTE_DESCRIPTIF],
                   image=candidat[PHOTO]))

    return group, question_admin, sous_questions
예제 #32
0
def generate_questions(conf, group_conf):
    df = group_conf['df']
    name = f"Comité exécutif {group_conf['semester']}"
    description = "Pour cette section, seulement une personne peut-être élue par poste."
    group = Group(name, description)
    postes = conf['postes_exec']

    questions = []
    questions_map = {}

    # clean poste vise
    for poste in postes:
        df.loc[df[POSTE_VISE].str.
               contains(pat=f"(?:^{postes[poste]}|{poste})", regex=True),
               POSTE_VISE] = poste

    applied_posts = [
        poste for poste in postes if poste in df[POSTE_VISE].unique().tolist()
    ]

    for i, poste in enumerate(applied_posts):
        question = Question(
            code=poste + group_conf['semester'],
            gid=group.gid,
            title=f"Qui voulez-vous au poste de {postes[poste]}?",
            qtype='L',
            order=i)

        questions.append(question)
        questions_map[poste] = question

    if 'unused_posts' not in group_conf.keys():
        group_conf['unused_posts'] = []

    for poste in postes:
        if poste not in applied_posts:
            group_conf['unused_posts'].append(poste)

    for _, candidat in df.iterrows():
        poste = candidat[POSTE_VISE]
        option = Option(nom=candidat[NOM_USUEL],
                        promotion=candidat[PROMOTION],
                        concentration=candidat[CONCENTRATION],
                        order=questions_map[poste].answer_count(),
                        description=candidat[TEXTE_DESCRIPTIF],
                        image=candidat[PHOTO])

        questions_map[poste].add_answer(option)
        questions_map[poste].add_option(option)

    for poste in questions_map:
        lachaise = Option.add_chaise(questions_map[poste].answer_count())
        questions_map[poste].add_answer(lachaise)
        questions_map[poste].add_option(lachaise)

    return group, questions
예제 #33
0
 def post(self):
     args = post_parser.parse_args()
     d = {
         'title': args.title,
         'content': args.content,
         'user_id': args.user_id
     }
     q = Question.new(d)
     q.save()
     return q.json(), 201
예제 #34
0
    def delete_question(question_id):
        question = Question.get_by_id(question_id)

        if question is None:
            abort(404)

        result = question.delete_record()

        if result["error"]:
            abort(500)

        questions = Question.get_by_page(request, QUESTIONS_PER_PAGE)

        return jsonify({
            "deleted": question_id,
            "questions": questions,
            "total_questions": len(Question.get_all()),
            "success": True,
        })
예제 #35
0
    def get_list_table(limit,offset):
        (questions, curpage, maxpages, startpage, pagecount) = Question.get_filtered_offset(limit,offset,orderby='created')
        
        for question in questions:
            if question is not None and question.activate_time is not None:
                if question.get_time_left() < 0:         
                    question.answerable = False
        session.commit()

        return render_template('question_list_tbl.html', questions=questions,
                currentpage=curpage,startpage=startpage,pagecount=pagecount,maxpages=maxpages)
예제 #36
0
def collect_questions():
    questions = []
    older_than = datetime.datetime.utcnow() - datetime.timedelta(days=COOLDOWN_DURATION)
    for qt_id in range(1, MAX_NUMBER_OF_DIFFICULTY + 1):
        question = Question.objects(
            Q(question_type=qt_id) &
            Q(modified_at__lte=older_than)
        ).order_by('modified_at').first()
        if question:
            questions.append(question)
    return questions
예제 #37
0
def create(post_data):
    question_text = post_data.get("question_text")
    sample_input = post_data.get("sample_input")
    sample_output = post_data.get("sample_output")
    explanation = post_data.get("explanation")
    question_type = post_data.get("question_type")
    q = Question(question_id=shortuuid.uuid(),
                 question_text=question_text,
                 sample_input=sample_input,
                 sample_output=sample_output,
                 explanation=explanation,
                 question_type=question_type)
    try:
        obj = q.save()
        log.debug("## Question Added: ID {}".format(obj.question_id))
        return_dict = obj.to_dict()
        return return_dict
    except Exception as e:
        log.error(e)
        return response.failure({"status": "Failure occurred."})
예제 #38
0
def createTopic(question, accountId, answerStatusId, isPoll):

    qst = Question()

    qst.Question = question
    qst.AccountId = accountId
    qst.TimeStamp = datetime.date.today()
    qst.AnswerStatusId = answerStatusId
    qst.IsPoll = isPoll
    qst.Score = 0

    db.session.add(qst)
    db.session.commit()
예제 #39
0
def index():
    # Slice of to pagination

    # List of filter by get args:
    # Example: /admin/question/?page=1&name_icontains=apple
    data = request.args.to_dict()

    # Type of filter
    engine_filter = {'content__icontains': str}

    # Prepare filter
    criteria = {}
    for k in data:
        if k in engine_filter:
            criteria[k] = engine_filter[k](data[k])

    pagination = Paginate('admin.question.index', count=len(Question.objects(**criteria)), per_page=10)
    page = pagination.get_page()
    questions = Question.objects(**criteria)[(page-1) * 10:page * 10]
    return render.template('admin/question/index.html', questions=questions, pagination=pagination)
예제 #40
0
    def search_questions():
        search_term = request.get_json()["search_term"]
        questions = Question.search(search_term)

        if len(questions) == 0:
            abort(404)

        return jsonify({
            "questions": questions,
            "total_questions": len(questions),
            "success": True,
        })
예제 #41
0
 def test_get_by_category(self):
     """Test the get_by_category method for the Question model."""
     with self.app_context:
         questions = Question.get_by_category(self.c_2.id)
         self.assertIsNotNone(questions)
         self.assertEqual(len(questions), 2)
         self.assertIn(
             questions[0].format(), [self.q_2.format(), self.q_3.format()]
         )
         self.assertIn(
             questions[1].format(), [self.q_2.format(), self.q_3.format()]
         )
예제 #42
0
 def export_course(course_id, export_answers=True):
     questions = Question.by_course_id(course_id)
     ret = []
     for question in questions:
         q = {'question': question.question}
         if export_answers:
             answers = AnswerModel.get_filtered(questionID=question.id)
             q['answers'] = []
             for x in answers:
                 q['answers'].append(x.text)
         ret.append(q)
     return ret
예제 #43
0
 def test_init(self):
     """Test the __init__ method for the Question class."""
     self.q = Question(
         question="Test Question?",
         answer="Test Answer",
         difficulty="1",
         category_id="2",
     )
     self.assertEqual(self.q.question, "Test Question?")
     self.assertEqual(self.q.answer, "Test Answer")
     self.assertEqual(int(self.q.difficulty), 1)
     self.assertEqual(int(self.q.category_id), 2)
예제 #44
0
    def toggle_options(args):
            try:
                type = args['type']
            except KeyError:
                return

            question = Question.by_id(args['id'])
            if question is None:
                return

            if not g.lti.is_instructor() and type != 'Reviewable':
                return

            if question.state == 'Answerable' and (type == 'Inactive' or type == 'Reviewable' or type == 'Archived'):
                AnswerModel.update_q_history(args['id'])

            rv = None
            if type == 'Inactive':
                rv = question.inactive = True
                question.answerable = question.reviewable = question.closed = False
                question.state = 'Inactive'

            if type == 'Answerable':
                rv = question.answerable = True
                question.activate_time = datetime.now()
                question.inactive = question.reviewable = question.closed = False
                question.state = 'Answerable'

            elif type == 'Reviewable':
                if not question.reviewable:
                    Scheduler(args['id'])
                    question.reviewable = True
                rv = question.reviewable
                question.inactive = question.answerable = question.closed = False
                question.state = 'Reviewable'

            elif type == 'Closed':
                rv = question.closed = True
                question.inactive = question.answerable = question.reviewable = False
                question.state = 'Closed'

            elif type == 'comments':
                rv = question.comment = not question.comment

            elif type == 'tags':
                rv = question.tags = not question.tags

            elif type == 'rating':
                rv = question.rating = not question.rating

            session.commit()
            return json.dumps({"toggle": rv, "check": True})
예제 #45
0
    def save():
        try:
            questionid = int(request.values['questionid'])
            question = Question.by_id(questionid)
            text = request.values['text']
            userid = g.lti.get_user_id()
        except:
            return abort(404)

        if AnswerModel.question_valid(questionid) and text != "":
            AnswerModel.save(questionid, userid, text)

        return redirect('/index_student')
예제 #46
0
    def delete_question(qid):
        '''removes the question with the provided id from the database'''
        question = Question.by_id(int(qid))
        if g.lti.is_instructor():
            session.delete(question)
            #Delete answers
            quid = {"questionID": int(qid)}
            answers = AnswerModel.get_filtered(**quid)
            for x in answers:
                session.delete(x)
            session.commit()

        return json.dumps({'deleted': g.lti.is_instructor()})
예제 #47
0
    def get_remaining_time(q_id):
        question = Question.by_id(q_id)

        if question is not None and question.activate_time is not None:
            time_remaining = question.get_time_left()
            question_time =  question.time
        else:
            time_remaining = 0
            question_time =  0

        return json.dumps({"still_answerable":((question is not None) and question.answerable),
                           "time_remaining":time_remaining,
                           "question_deleted":(question is None) or not question.answerable,
                           "question_time":question_time})
예제 #48
0
 def start_review(request):
     try:
         question_id = request.form['question_id']
     except:
         return json.dumps({'Reviewable':False})
     
     question = Question.by_id(question_id)
     reviewable = False
     if question is not None:
         if g.lti.is_instructor() or \
                 (question.get_time_left() <= 0 and question.time > 0):
             return QuestionController.toggle_options(
             {'id':question_id, 'type':'Reviewable'})
         
     return json.dumps({'Reviewable':reviewable})
예제 #49
0
    def review():
        answer = Schedule.get_answer(g.lti.get_user_id())
        if answer == None:
            return "No answers to review."

        fsession['reviewanswer'] = answer.id

        enabledtags = AnswerTag.get_tag_ids(answer.id)
        reviews = Review.get_list(answer.id)
        question = Question.by_id(answer.questionID)
        if question is None:
            return "Question was not found."

        return render_template('reviewanswer.html', answer=answer,
                               tags=Tag.get_all(), enabledtags=enabledtags,
                               reviews=reviews, question=question)
예제 #50
0
    def get(self):
        c = h.context()
        s = self.request.get("s")
        c["s"] = s
        c["data"] = xrange(6)
        r = list()
        r += [[0, 0]]
        r += [[253, 0]]
        r += [[506, 0]]
        r += [[0, 253]]
        r += [[253, 253]]
        r += [[506, 253]]
        c["rects"] = r
        c["stash_items"] = xrange(7)
        cookies = h.get_default_cookies(self)
        u = h.get_current_user(cookies)
        if u:
            c["uid"] = u.fb_user_id

        # get some appropriate questions
        query = Question.all()
        query.filter("qtype =", 1).filter("status =", 1)
        questions = query.fetch(1000)
        building = list()
        for o in questions:
            d = dict()
            # d['qtype'] = o.qtype
            d["key"] = str(o.key())
            d["qtext"] = o.qtext
            d["hint"] = o.hint
            d["img"] = str(o.img.key())
            # d['status'] = o.status
            # d['created_at'] = str(o.created_at)
            building += [d]
        c["questions"] = simplejson.dumps(building)

        answers = self.get_answers()
        building = list()
        for o in answers:
            d = dict()
            d["key"] = str(o.key())
            d["atext"] = o.atext
            d["qkey"] = str(o.qkey)
            building += [d]
        c["answers"] = simplejson.dumps(building)

        h.render_out(self, "questions.tplt", c)
예제 #51
0
    def availability(args):
        """
        Handles availability via the question_list form
        """
        try:
            type = args['type']
        except KeyError:
            return 
            
        question = Question.by_id(args['id'])
        if question is None:
            return 

        if not g.lti.is_instructor() and type != 'reviewable':
            return
        
        rv = None
        if type == 'answerable':
            rv = question.answerable = not question.answerable
            question.activate_time = datetime.now()

        elif type == 'reviewable':
            if not question.reviewable:
                Scheduler(args['id'])
                question.reviewable = True
            rv = question.reviewable


        elif type == 'archived':
            rv = question.archived = not question.archived
            
        elif type == 'comments':
            rv = question.comment = not question.comment
            
        elif type == 'tags':
            rv = question.tags = not question.tags
            
        elif type == 'rating':
            rv = question.rating = not question.rating
            
        session.commit()
            
        return rv
예제 #52
0
    def get(self):
        phone_number = int(self.request.get('p'))
        query = Question.query()
        query = query.filter(Question.phone_number == phone_number)

        questions = []
        most_recent = datetime.min
        count = 0

        for question in query.fetch():
            count += 1
            if not question.time is None and question.time > most_recent:
                most_recent = question.time
            questions.append({'question': question.question,
                              'time': str(question.time),
                              'answer': question.answer})
        response = {'questions': questions,
                    'phone_number': phone_number,
                    'number_of_questions': count,
                    'most_recent_question': str(most_recent)}
        output = json.dumps(response)
        self.render_json(output)
예제 #53
0
    def render_filtered_tbl(self,limit,offset,**kwargs):
        (answers, curpage, maxpages, startpage, pagecount) = \
                self.get_filtered(limit=limit, offset=offset)

        hasqid = ('questionID'in kwargs)
        course = g.lti.get_course_id()
        
        for a in answers:
            a.tags = ''
            tag_ids = AnswerTag.get_tag_ids(a.id)
            if tag_ids != []:           
                for id in tag_ids:
                    tag_name = Tag.get_tag(id)                     
                    a.tags += tag_name + ', ' 
                a.tags = a.tags[:-2]            

        return render_template('answer_filter_tbl.html',
                answers=answers,currentpage=curpage,
                maxpages=maxpages,startpage=startpage,pagecount=pagecount,
                hasQuestionID=hasqid,
                users=user.UserModel.get_all(),
                questions = [] if hasqid else Question.by_course_id(course))
예제 #54
0
 def render(self):
     try:
         questionid = int(request.values['questionid'])
         answerid1 = int(request.values['answerid1'])
         answerid2 = int(request.values['answerid2'])
     except:
         return abort(404)
         
     try:
         question = Question.by_id(questionid)
         answer1 = AnswerModel.by_id(answerid1)
         answer2 = AnswerModel.by_id(answerid2)
     except:
         return abort(404)
         
     if AnswerModel.question_valid(questionid):
         return render_template('choice.html',
                                question = question,
                                answer1 = answer1,
                                answer2 = answer2)
     else:
         return redirect('/choicelobby?question_id=' + questionid)
예제 #55
0
파일: user.py 프로젝트: wdvill/cloud_admin
def question_create(user, params):
    question_id = utils.safe_id(params.get("question_id"))
    answer = params.get("answer")
    if not question_id or not answer:
        return {"error_code": 80002, "msg": "no enough parameters"}

    question = Question.select().where(Question.id == question_id).first()
    if not question:
        return {"error_code": 20242, "msg": "protect question not exists"}

    uq = UserQuestion.select().where(UserQuestion.user == user).first()
    if uq:
        return {"error_code": 20243, "msg": "password question already exists"}

    u = UserQuestion()
    u.user = user
    u.question = question
    u.answer = answer
    u.save()

    queue.to_queue({"type":"user_question_create", "user_id":user.id,
        "team_id": user.identify[1:] if user.identify[0] != "f" else None})
    return {"error_code": 0, "msg": "ok"}
예제 #56
0
파일: user.py 프로젝트: wdvill/cloud_admin
def question_update(user, params):
    question_id = utils.safe_id(params.get('question_id'))
    answer_old = params.get('answer_old')
    answer = params.get('answer')

    if not question_id or not answer_old or not answer:
        return {"error_code": 80002, "msg": "no enough parameters"}

    question = Question.select().where(Question.id == question_id).first()
    if not question:
        return {"error_code": 20242, "msg": "protect question not exists"}

    uq = UserQuestion.select().where(UserQuestion.user == user).first()
    if not uq:
        return {"error_code": 20241, "msg": "user protect question not exists"}

    if uq.answer != answer_old:
        return {"error_code": 20244, "msg": "error answer"}

    uq.question = question_id
    uq.answer = answer
    uq.create_at = utils.now()
    uq.save()
    return {"error_code": 0, "msg": "ok"}
예제 #57
0
    def get(self):
        img_rows = 3
        
        c = h.context()
        query = self.request.get('q')
        force_quest = self.request.get('force_quest')
        
        if not query: query = "red"
        c['query'] = query

        # fetch the google image results
        ue_query = urllib.quote_plus(query)
        c['ue_query'] = ue_query
        url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=large&q='\
               +ue_query+'&key='\
               +h.cfg['gs_api_key']
        url2 = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=large&start=8&q='\
               +ue_query+'&key='\
               +h.cfg['gs_api_key']
        url3 = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='\
               +ue_query+'&key='\
               +h.cfg['gs_api_key']
        rpcs = []
        
        rpc = urlfetch.create_rpc(10)
        urlfetch.make_fetch_call(rpc,url)
        rpcs.append(rpc)
        rpc = urlfetch.create_rpc(10)
        urlfetch.make_fetch_call(rpc,url2)
        rpcs.append(rpc)
        rpc = urlfetch.create_rpc(10)
        urlfetch.make_fetch_call(rpc,url3)
        rpcs.append(rpc)
        for rpc in rpcs:
            rpc.wait()
        result = rpcs[0].get_result()        
        result2 = rpcs[1].get_result()
        result_web = rpcs[2].get_result()
        
        o = simplejson.loads(result.content)
        o2 = simplejson.loads(result2.content)
        o_web = simplejson.loads(result_web.content)
        
        from print_r import print_r
        #c['content'] = print_r(o_web, False)
        c['ad'] = ""
        all_imgs = o['responseData']['results']+o2['responseData']['results']
        c['web_data'] = o_web['responseData']['results']
        
        # calculate appropriate sizes for image placement
        c['max_height'] = int(max(all_imgs, key=lambda x: int(x['tbHeight']))['tbHeight'])
        c['row_height'] = c['max_height']+20

        # borders to make all the img divs the same size
        for i in all_imgs:
            i['bot_border'] = (c['row_height']-int(i['tbHeight']))/2
            i['top_border'] = c['row_height']-int(i['tbHeight'])-i['bot_border']
            i['right_margin'] = 5

        # init loop variables
        c['mini_imgs'] = list()
        start_img = 0
        curr_img = 0
        done = False

        # begin the super ugly loop to generate rows
        while not done:
            taken_px = 0
            row_done = False
            num_imgs = 0
            # figure out how many images we can place in the row given the normal size
            while not row_done:
                additional_px = 0
                additional_px += 20 # min right & left border
                additional_px += int(all_imgs[curr_img]['tbWidth']) # image itself
                if taken_px+additional_px > 758:
                    row_done = True
                    #done = True
                    num_imgs = curr_img - start_img
                else:
                    additional_px += 5 # white margin between images (the last one doesn't have it)
                    taken_px += additional_px
                    curr_img += 1
                if curr_img >= len(all_imgs):
                    num_imgs = curr_img - start_img
                    row_done = True
                    done = True

            # now take all the remaining space and distribute it to the borders of the images
            remaining_space  = 758-taken_px
            border_px = int(remaining_space/(num_imgs*2)+10)
            remainder = remaining_space-(border_px-10)*2*num_imgs

            row_imgs = all_imgs[start_img:start_img+num_imgs]
            
            # hand out the border px to the images and get rid of the remainder (also add the index)
            for i in row_imgs:
                i['left_border'] = border_px
                if(remainder > 0):
                    i['left_border'] += 1
                    remainder -= 1
                i['right_border'] = border_px
                if(remainder > 0):
                    i['right_border'] += 1
                    remainder -= 1
            
            c['num_imgs'] = num_imgs

            # set the last img in a row to have no 5px margin
            row_imgs[len(row_imgs)-1]['right_margin'] = 0

            c['mini_imgs'].append(row_imgs)
            if len(c['mini_imgs']) >= img_rows: done = True

            start_img += num_imgs

            # pick up the questions and images for the
            q = None
            if not force_quest:
                query = Question.all()
                results = query.fetch(1000)
                if len(results) > 0:
                    import random
                    q = random.choice(results)
                else: # Added this to prevent IndexError: list index out of range in development
                    q = Question()
            else:
                k = db.Key(force_quest)
                q = db.get(k)
            image_key = q.img.key() if q.img is not None else '' # Added to make development safe    
            c['header_img'] = h.cfg['direct_url']+'/public/srp_top_channel_2.png'  #+'/serve/'+str(image_key)
            c['header_txt'] = 'Find something you like!' #q.qtext
            c['hint'] = 'type something.' #q.hint
            c['header_repeat'] = 'repeat-x'
            c['header_height'] = '80px'
            if not c['hint']:
                c['hint'] = "type something."
            c['search_form_display'] = "block"
            c['translucent_overlay_display'] = "none"
            c['little_arrow_display'] = "none"
        h.render_out(self, 'results.tplt', c)
예제 #58
0
 def export_course(course_id):
     questions = Question.by_course_id(course_id)
     return [{'question': question.question} for question in questions]