예제 #1
0
 def get_questionset_from_database(self, exam_code):
     '''
     This function returns the questions of a model
     by checking the exam_code
     '''
     question_api = QuestionApi()
     questions = question_api.find_all_questions(
         {"exam_code": int(exam_code)})
     sorted_questions = sorted(
         questions, key=lambda k: k['question_number'])
     return sorted_questions
예제 #2
0
def add_html(request): 
    
    questions = json.loads(request.POST.get('q'))

    for question in questions:
        question_api = QuestionApi()
        question_api.latex_html({"exam_code":int(question['exam_code']), \
            "question_number":question['question_number']}, \
             {"question.html":question['question']['text'], \
             "answer.a.html":question['answer']['a']['text'],
             "answer.b.html":question['answer']['b']['text'],
             "answer.c.html":question['answer']['c']['text'],
             "answer.d.html":question['answer']['d']['text']\
             })
    return render_to_response("sample-tex.html")
예제 #3
0
def load_correctanswer_in_database(request):
    '''
    This function loads the correct answers of each question in the database
    Each document consists of question_id and correct answer choice
    '''
    question_api = QuestionApi()
    questions = question_api.find_all_questions(
        {"exam_code": 103})
    correct_answer_list = []
    for each_question in questions:
        temp = {}
        temp['question_id'] = ObjectId(each_question['uid']['id'])
        temp['correct_answer'] = each_question['answer']['correct']
        correct_answer_list.append(temp)
    correct_answer_database = CorrectAnswerDatabase()
    correct_answer_database.insert_new_correct_answer(correct_answer_list)
    return HttpResponse("Correct Answer saved in the database")
예제 #4
0
def results(request, exam_code):
    parameters ={}
    res={}
    res['exam_code'] = int(exam_code)    
    exam_obj = ExammodelApi()
    exam_details = exam_obj.find_one_exammodel({'exam_code':int(exam_code)})
    res['exam_details'] = exam_details
    ess = ExamStartSignal()            
    ess_check = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id})

    question_obj = QuestionApi()    
    total_questions = question_obj.get_count({"exam_code": int(exam_code), 'marks':1})

    ans = AttemptedAnswerDatabase()
    try:
        all_ans = ans.find_all_atttempted_answer({
            'exam_code':int(exam_code), 
            'user_id':request.user.id,
            'ess_time':ess_check['start_time']
            }, fields={'q_no':1, 'attempt_details':1})
    except:
        all_ans = ''
    answer_list = ''
    anss = []
    for eachAns in all_ans:
        anss.append(eachAns['q_no'])
    for i in range(0,total_questions):       
        try:
            if i in anss:
                answer_list += all_ans[anss.index(i)]['attempt_details'][0]['selected_ans']
            else:
                answer_list +='e'
        except:
            answer_list += 'e'
    exam_handler = ExamHandler()    
    score_dict = exam_handler.check_answers(exam_code, answer_list)
    user_profile_obj = UserProfile()
    user = user_profile_obj.get_user_by_username(request.user.username)
    parameters['user'] = user            
    parameters['result'] = score_dict
    parameters['exam_code'] = exam_code
    parameters['myrankcard'] = {'total':200, 'rank':1}
    return render_to_response('results.html', parameters, context_instance=RequestContext(request))
예제 #5
0
def get_list_of_result(request):
    if request.user.is_authenticated():
        user_id = request.user.id 
        ans = AttemptedAnswerDatabase()
        exam_attempts = ans.get_attempted_exams('exam_code', {'user_id':request.user.id})
        return_dict = []
        for exam_code in exam_attempts['results']:
            exam_obj = ExammodelApi()
            exam_details = exam_obj.find_one_exammodel({'exam_code':int(exam_code)})
            if exam_details['exam_family'] =='DPS':
                continue
            attempt_timestamps = ans.get_attempted_exams('ess_time', 
                {'user_id':request.user.id, 'exam_code':int(exam_code)})
            for eachAttempt in attempt_timestamps['results']:
                all_ans = ans.find_all_atttempted_answer({
                    'exam_code':int(exam_code), 
                    'user_id':user_id,
                    'ess_time':eachAttempt
                    })
                answer_list = ''
                anss = []
                for eachAns in all_ans:
                    anss.append(eachAns['q_no'])
                question_obj = QuestionApi()
                total_questions = question_obj.get_count({"exam_code": int(exam_code)})                    
                for i in range(0,total_questions):       
                    try:
                        if i in anss:
                            answer_list += all_ans[anss.index(i)]['attempt_details'][0]['selected_ans']
                        else:
                            answer_list +='e'
                    except:
                        answer_list += 'e'

                exam_handler = ExamHandler()    
                score_dict = exam_handler.check_answers(exam_code, answer_list)
                rank = 0
                return_dict.append({'exam_code':exam_code, 'ess_time':eachAttempt, 'result':score_dict, 'exam_details':exam_details, 'rank':'0'})
        return HttpResponse(json.dumps({'status':'ok', 'result':return_dict}))
    else:
        return HttpResponse(json.dumps({'status':'error','message':'You are not authorized to perform this action.'}))
예제 #6
0
def load_modelquestion_in_database(request):
    '''
    the function is used to load fake data in question collection
    of mcq database in mongodb
    '''
    for var in range(100,102):
        f = open('apps/exam_api/' + str(var) +'.json', 'rb')
        json_obj = json.loads(f.read())
        for i, x in enumerate(json_obj):
            x['question_number'] = i + 1
        question_api = QuestionApi()
        question_api.insert_new_question(json_obj)

    for var in range(201,204):
        f = open('apps/exam_api/' + str(var) +'.json', 'rb')
        json_obj = json.loads(f.read())
        for i, x in enumerate(json_obj):
            x['question_number'] = i + 1
        question_api = QuestionApi()
        question_api.insert_new_question(json_obj)        
        print var, " saved"
    return HttpResponse("Question saved in the database")
예제 #7
0
def get_scores(request):
    '''
    the function returns api of scores obtained in each subject
    '''
    if request.user.is_authenticated():
        IMPROPER_REQUEST = 'Couldn\'t process improper request'
        try:
            exam_code = int(request.POST['exam_code'])
            answer_list = list(request.POST['answers'])
        except Exception:
            return HttpResponse(
                json.dumps({
                    'status': 'error',
                    'message': IMPROPER_REQUEST
                }))

        from apps.mainapp.classes.query_database import AttemptedAnswerDatabase, QuestionApi
        from apps.mainapp.classes.query_database import ExammodelApi
        exam_obj = ExammodelApi()
        exam_details = exam_obj.find_one_exammodel(
            {'exam_code': int(exam_code)})

        question_obj = QuestionApi()
        ans = AttemptedAnswerDatabase()
        questions = question_obj.find_all_questions(
            {"exam_code": int(exam_code)})
        sorted_questions = sorted(questions,
                                  key=lambda k: k['question_number'])
        attempt_time = time.mktime(datetime.datetime.now().timetuple())
        if exam_details['exam_family'] == 'CPS':
            if (attempt_time - (exam_details['exam_date'] +
                                exam_details['exam_duration'] * 60)) > 15 * 60:
                return HttpResponse(
                    json.dumps({
                        'status':
                        'error',
                        'message':
                        'We are sorry, you are late in submitting your answers.'
                    }))

        for i in range(0, len(answer_list)):
            ans.update_upsert_push(
                {
                    'user_id': request.user.id,
                    'ess_time': int(attempt_time),
                    'attempt_device': 'android',
                    'q_id': sorted_questions[i]['uid']['id'],
                    'exam_code': int(exam_code),
                    'q_no': i
                }, {
                    'attempt_details': {
                        'selected_ans': answer_list[i],
                        'attempt_time': int(attempt_time)
                    }
                })

        exam_handler = ExamHandler()
        score_dict = exam_handler.check_answers(exam_code, answer_list)
        return HttpResponse(json.dumps({'status': 'ok', 'result': score_dict}))
    else:
        return HttpResponse(
            json.dumps({
                'status': 'error',
                'message': 'Not a valid request'
            }))
예제 #8
0
def attend_exam(request,exam_code):
    user_profile_obj = UserProfile()
    subscribed = user_profile_obj.check_subscribed(request.user.username, exam_code)
    if request.user.is_authenticated() and subscribed:
        parameters = {}
        ess = ExamStartSignal()        
        exam_obj = ExammodelApi()

        exam_details = exam_obj.find_one_exammodel({'exam_code':int(exam_code)})
        validate = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id, 'start':1})
        end_validate = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id, 'start':1, 'end':1})        

        atte_ans = AttemptedAnswerDatabase()
        all_answers = atte_ans.find_all_atttempted_answer({
            'exam_code':exam_code, 'user_id':int(request.user.id),
            'ess_starttimestamp':int(validate['start_time'])})
        parameters['all_answers'] = json.dumps(all_answers)

        if end_validate !=None:
            if exam_details['exam_family'] == 'CPS':
                return HttpResponseRedirect('/results/' + str(exam_code) +'/')
            else:
                parameters['all_answers'] = []

        else:
            if validate != None:
                time_elapsed = time.mktime(datetime.datetime.now().timetuple()) - validate['start_time']
                if time_elapsed > exam_details['exam_duration']*60 and exam_details['exam_family']=='CPS':
                    return HttpResponseRedirect('/results/' + str(exam_code) +'/')
                elif time_elapsed > exam_details['exam_duration']*60 and exam_details['exam_family']!='CPS':
                    parameters['all_answers'] = []
            exam_details['exam_duration'] = exam_details['exam_duration'] - time_elapsed/60
        
        try:
            honor_code_accept = request.session[str(exam_code)]
        except:
            honor_code_accept = False

        if not honor_code_accept:
            return HttpResponseRedirect('/honorcode/'+str(exam_code) +'/')
        
        question_obj = QuestionApi()    
        questions = question_obj.find_all_questions({"exam_code": int(exam_code)})
        total_questions = question_obj.get_count({"exam_code": int(exam_code)})
        sorted_questions = sorted(questions, key=lambda k: k['question_number'])

        if exam_details['exam_family'] != 'DPS':
            exam_details['exam_date'] = datetime.datetime.fromtimestamp(int(exam_details['exam_date'])).strftime('%Y-%m-%d')

        parameters['questions'] = json.dumps(sorted_questions)
        parameters['exam_details'] = exam_details
        
        start_question_number = 0 
        try:
            start_question_number = int(request.session['current_question_number'])
            if start_question_number == '':
                start_question_number = 0
        except:
            start_question_number = 0 

        if start_question_number == total_questions:
            start_question_number = start_question_number - 1
            parameters['next_to_start'] = sorted_questions[start_question_number]
        else:            
            parameters['next_to_start'] = sorted_questions[0]
        
        parameters['start_question_number'] = start_question_number
        parameters['start_question'] = sorted_questions[start_question_number]
        parameters['max_questions_number'] =  total_questions

        parameters['exam_code'] = exam_code        
        user_profile_obj = UserProfile()
        user = user_profile_obj.get_user_by_username(request.user.username)
        parameters['user'] = user
        return render_to_response('exam_main.html', parameters, context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/')
예제 #9
0
def show_result(request, exam_code, subject_name):
    user_profile_obj = UserProfile()
    exam_obj = ExammodelApi()
    subscribed = user_profile_obj.check_subscribed(request.user.username, exam_code)
    exam_details = exam_obj.find_one_exammodel({'exam_code':int(exam_code)})
    parameters = {}
    if request.user.is_authenticated() and subscribed:        
        current_time = time.mktime(datetime.datetime.now().timetuple())
        if exam_details['exam_family'] == 'CPS' and current_time - exam_details['exam_date'] < exam_details['exam_duration']*60:
            return HttpResponseRedirect('/')            
        parameters['exam_details'] = exam_details
        question_obj = QuestionApi()    
        questions = question_obj.find_all_questions({"exam_code": int(exam_code),
            'subject':str(subject_name), 'marks':1})
        total_questions = question_obj.get_count({"exam_code": int(exam_code), 
            'subject':subject_name, 'marks':1})

        sorted_questions = sorted(questions, key=lambda k: k['question_number'])
        try:            
            current_q_no = int(request.GET.get('q',''))
            if current_q_no >= total_questions:
                next_q_no = total_questions-1
            else:
                next_q_no = current_q_no + 1
            if current_q_no <= 0:
                previous_q_no = 0
            else:
                previous_q_no = current_q_no -1
        except:
            current_q_no = 0
            previous_q_no = 0
            next_q_no = 1

        if current_q_no >=total_questions:
            current_q_no = total_questions -1
        if current_q_no <=0:
            current_q_no = 0
        parameters['current_q_no'] = current_q_no
        parameters['question_number'] = questions[current_q_no]['question_number']
        parameters['question'] =  questions[current_q_no]
        parameters['subject'] = subject_name
        parameters['exam_code'] = exam_code
        parameters['next_q_no'] = next_q_no
        parameters['previous_q_no'] = previous_q_no

        ess = ExamStartSignal()            
        ans = AttemptedAnswerDatabase()
        ess_check = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id})
        total_questions = question_obj.get_count({"exam_code": int(exam_code)})

        try:
            query = {'exam_code':int(exam_code), 'user_id':int(request.user.id),
                'ess_time':ess_check['start_time'],'q_no':questions[current_q_no]['question_number']}
            att_ans = ans.find_all_atttempted_answer(query)
            parameters['attempted'] = att_ans[0]['attempt_details'][len(att_ans[0]['attempt_details'])-1]['selected_ans']
        except:
            att_ans = ''
            parameters['attempted'] = ''

        user_profile_obj = UserProfile()
        user = user_profile_obj.get_user_by_username(request.user.username)
        parameters['user'] = user        
        return render_to_response('single-result.html', parameters, context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/')        
예제 #10
0
def attend_dps_exam(request,exam_code):
    user_profile_obj = UserProfile()
    subscribed = user_profile_obj.check_subscribed(request.user.username, exam_code)
    if request.user.is_authenticated() and subscribed:
        parameters = {}
        ess = ExamStartSignal()        
        exam_obj = ExammodelApi()
        ess = ExamStartSignal()            

        exam_details = exam_obj.find_one_exammodel({'exam_code':int(exam_code)})
        current_time = time.mktime(datetime.datetime.now().timetuple())

        validate_start = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id, 'start':1,'end':0})        
        
        if validate_start != None:
            check = validate_start['start_time']
        else:
            ess.update_exam_start_signal({
                'exam_code':int(exam_code), 
                'useruid':request.user.id},{
                'start':1, 
                'start_time':int(time.mktime(datetime.datetime.now().timetuple())),
                'end':0,                
                'end_time':''
                })
            validate_start = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id, 'start':1,'end':0})        
            check = validate_start['start_time']

        dps_exam_start = exam_details['exam_family']=='DPS' and current_time - check > exam_details['exam_duration']*60
        if current_time - check > exam_details['exam_duration']*60:            
            ess.update_exam_start_signal({
                'exam_code':int(exam_code), 
                'useruid':request.user.id, 
                'start':1},{'end':1,'start':0, 
                'end_time':int(time.mktime(datetime.datetime.now().timetuple()))})
            ess.update_exam_start_signal({
                'exam_code':int(exam_code), 
                'useruid':request.user.id},{
                'start':1, 
                'start_time':int(time.mktime(datetime.datetime.now().timetuple())),
                'end':0,                
                'end_time':''
                })
            validate_start = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id, 'start':1,'end':0})        
            check = validate_start['start_time']
            

        if current_time - check < exam_details['exam_duration']*60:
            atte_ans = AttemptedAnswerDatabase()
            all_answers = atte_ans.find_all_atttempted_answer({
                'exam_code':int(exam_code), 'user_id':int(request.user.id),
                'ess_time':int(validate_start['start_time'])})
            time_elapsed = time.mktime(datetime.datetime.now().timetuple()) - validate_start['start_time']
            exam_details['exam_duration'] = (exam_details['exam_duration']*60 - time_elapsed)/60

            parameters['all_answers'] = json.dumps(all_answers)                        
            question_obj = QuestionApi()    
            questions = question_obj.find_all_questions({"exam_code": int(exam_code), 'marks':1}, fields={'answer.correct':0})
            total_questions = question_obj.get_count({"exam_code": int(exam_code), 'marks':1})
            sorted_questions = sorted(questions, key=lambda k: k['question_number'])

            parameters['questions'] = json.dumps(sorted_questions)
            parameters['exam_details'] = exam_details
        
            start_question_number = 0 
            cqn = CurrentQuestionNumber()
            current_q_no = cqn.check_current_question_number({
                'exam_code':int(exam_code), 
                'useruid':request.user.id, 
                'ess_time':validate_start['start_time']})
            try:
                start_question_number = current_q_no['cqn']
                if start_question_number == '':
                    start_question_number = 0
            except:
                start_question_number = 0 

            if start_question_number == total_questions:
                start_question_number = start_question_number - 1
                parameters['next_to_start'] = sorted_questions[start_question_number]
            else:            
                parameters['next_to_start'] = sorted_questions[0]
        
            parameters['start_question_number'] = start_question_number
            parameters['start_question'] = sorted_questions[start_question_number]
            parameters['max_questions_number'] =  total_questions

            parameters['exam_code'] = exam_code        
            user_profile_obj = UserProfile()
            user = user_profile_obj.get_user_by_username(request.user.username)
            parameters['user'] = user
            return render_to_response('exam_main.html', parameters, context_instance=RequestContext(request))

    else:
        return HttpResponseRedirect('/')
예제 #11
0
def attend_cps_exam(request, exam_code):
    user_profile_obj = UserProfile()
    subscribed = user_profile_obj.check_subscribed(request.user.username, exam_code)
    if request.user.is_authenticated() and subscribed:
        parameters = {}
        ess = ExamStartSignal()        
        exam_obj = ExammodelApi()
        user_profile_obj = UserProfile()
        question_obj = QuestionApi()    
        h_a_s = HonorCodeAcceptSingal()
        ess = ExamStartSignal()            
        cqn = CurrentQuestionNumber()
        atte_ans = AttemptedAnswerDatabase()
        questions = question_obj.find_all_questions({"exam_code": int(exam_code)}, fields={'answer.correct':0})
        user = user_profile_obj.get_user_by_username(request.user.username)
        exam_details = exam_obj.find_one_exammodel({'exam_code':int(exam_code)})

        if_cps_ended = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id, 'start':0,'end':1}) 
        if if_cps_ended != None:
            return HttpResponseRedirect('/results/' + str(exam_code) + '/')

        current_time = time.mktime(datetime.datetime.now().timetuple())
        if current_time - exam_details['exam_date'] > exam_details['exam_duration']*60:
            return HttpResponseRedirect('/results/' + str(exam_code))

        validate_start = ess.check_exam_started({'exam_code':int(exam_code), 'useruid':request.user.id, 'start':1,'end':0})
        if validate_start != None:
            h_a_s_accepted = h_a_s.check_honor_code_accepted({
                'exam_code':int(exam_code), 
                'useruid':request.user.id,
                'accept':1,
                'ess_time':validate_start['start_time']})
        else:
            h_a_s_accepted = None

        if h_a_s_accepted == None:
            return HttpResponseRedirect('/honorcode/'+str(exam_code) +'/')

        all_answers = atte_ans.find_all_atttempted_answer({
            'exam_code':int(exam_code), 'user_id':int(request.user.id),
            'ess_time':int(validate_start['start_time'])})
        time_elapsed = time.mktime(datetime.datetime.now().timetuple()) - int(exam_details['exam_date'])
        total_questions = question_obj.get_count({"exam_code": int(exam_code)})
        sorted_questions = sorted(questions, key=lambda k: k['question_number'])

        start_question_number = 0 
        current_q_no = cqn.check_current_question_number({
            'exam_code':int(exam_code), 
            'useruid':request.user.id, 
            'ess_time':validate_start['start_time']})
        try:
            start_question_number = current_q_no['cqn']
            if start_question_number == '':
                start_question_number = 0
        except:
            start_question_number = 0 

        if start_question_number == total_questions:
            start_question_number = start_question_number - 1
            parameters['next_to_start'] = sorted_questions[start_question_number]
        else:           
            parameters['next_to_start'] = sorted_questions[0]
    
        parameters['all_answers'] = json.dumps(all_answers)                        
        parameters['questions'] = json.dumps(sorted_questions)
        exam_details['exam_duration'] = (exam_details['exam_duration']*60 - time_elapsed)/60
        exam_details['exam_date'] = datetime.datetime.fromtimestamp(int(exam_details['exam_date'])).strftime('%Y-%m-%d')
        parameters['exam_details'] = exam_details
        parameters['start_question_number'] = start_question_number
        parameters['start_question'] = sorted_questions[start_question_number]
        parameters['max_questions_number'] =  total_questions
        parameters['exam_code'] = exam_code        
        parameters['user'] = user
        return render_to_response('exam_main.html', parameters, context_instance=RequestContext(request))

    else:
        return HttpResponseRedirect('/')
예제 #12
0
    def check_answers(self, exam_code, answer_list):
        '''
        This function receives list of answers and exam_code
        and return the dictionary with correct answers of each subject
        and sum of correct answers
        '''
        question_api = QuestionApi()
        questions = question_api.find_all_questions(
            {"exam_code": int(exam_code), 'marks':1})
        sorted_questions = sorted(
            questions, key=lambda k: k['question_number'])
        subjects = set([i['subject'] for i in sorted_questions])
        print answer_list,len(answer_list)

        correct_answers = {}
        for subs in subjects:
            temp = {}
            temp['total_question'] = 0
            temp['attempted_answer'] = 0
            temp['score'] = 0
            correct_answers[subs] = temp

        for index, choice in enumerate(answer_list):
            correct_answers[
                sorted_questions[index]['subject']]['attempted_answer'] += 1
            correct_answers[
                sorted_questions[index]['subject']]['total_question'] += 1 * \
                int(sorted_questions[index]['marks'])
            if sorted_questions[index]['answer']['correct'] == choice:
                try:
                    correct_answers[
                        sorted_questions[index]['subject']]['score'] += 1 * \
                        int(sorted_questions[index]['marks'])
                except:
                    correct_answers[
                        sorted_questions[index]['subject']]['score'] += 1

        total_score = 0
        total_attempted = 0
        total_marks = 0
        score_list = []

        for key, value in correct_answers.iteritems():
            temp = {}
            temp['subject'] = key
            temp['score'] = value['score']
            temp['attempted'] = value['attempted_answer']
            temp['total_question'] = value['total_question']
            total_score += value['score']
            total_attempted += value['attempted_answer']
            total_marks += value['total_question']
            score_list.append(temp)
        score_list.append(
            {
                'subject': 'Total',
                'score': total_score,
                'attempted': total_attempted,
                'total_question': total_marks
            }
        )
        return score_list