Esempio n. 1
0
 def test_init(self):
     results = {
         1: [Result.parse('1nn='),
             Result.parse('1nn+1')],
         2: [Result.parse('4ss='),
             Result.parse('4ss-1')]
     }
     rs = VugraphRS(results)
     self.assertEqual(rs.results, results)
Esempio n. 2
0
    def play(self, player_choice):
        votes = {c: set() for c in Choice}
        for ai in self.ais:
            votes[ai.get_choice()].add(ai)

        top_choice = self.vote(votes)

        for ai_choice, voters in votes.items():
            for ai in voters:
                ai.add_result(Result(player_choice, top_choice, ai_choice))

        result = Result(player_choice, top_choice, top_choice)
        self.stats.add_result(result)
        return result
Esempio n. 3
0
def check_username(username,
                   site_id,
                   category_id,
                   total,
                   tracker_id,
                   request_timeout=10,
                   test=False):
    """
    Check if `username` exists on the specified site.
    """

    worker.start_job()
    redis = worker.get_redis()
    db_session = worker.get_session()

    # Make a splash request.
    site = db_session.query(Site).get(site_id)

    # Check site.
    splash_result = _splash_username_request(username, site, request_timeout)
    image_file = _save_image(db_session, splash_result)

    # Save result to DB.
    result = Result(tracker_id=tracker_id,
                    site_name=splash_result['site']['name'],
                    site_url=splash_result['url'],
                    status=splash_result['status'],
                    image_file_id=image_file.id,
                    error=splash_result['error'])
    db_session.add(result)
    db_session.commit()

    if not test:
        # Notify clients of the result.
        current = redis.incr(tracker_id)
        result_dict = result.as_dict()
        result_dict['current'] = current
        # result_dict['image_file_url'] = image_file.url()
        # result_dict['image_name'] = image_file.name
        result_dict['total'] = total
        redis.publish('result', json.dumps(result_dict))

        # If this username search is complete, then queue an archive job.
        if current == total:
            app.queue.schedule_archive(username, category_id, tracker_id)

    worker.finish_job()

    return result.id
Esempio n. 4
0
 def post(self, userid):
     for index in ["a", "b", "c", "d", "e"]:
         if "" not in display[userid][index]:
             game_result = Result(**room[userid])
             game_result.save()
             return "dead"
         for num in [4, 3, 2, 1, 0]:
             if num == 4:
                 continue
             if display[userid][index][num + 1] != "":
                 continue
             if display[userid][index][num] is not "":
                 display[userid][index][num + 1] = display[userid][index][num]
                 display[userid][index][num] = ""
     return dumps(display[userid])
def validate(analysis, dataset_manager, pixel_methods):
    """In each job, the methods are executed with the same dataset split and their results are put in an array."""
    results = []
    train, verify = dataset_manager.get_data_splits()
    if analysis is True:
        data_analysis(train)
    for pixel_method in pixel_methods:
        tp = 0
        fn = 0
        fp = 0
        tn = 0
        time = 0

        pixel_method.train(train)

        start = timer()
        for dat in verify:
            im = dat.get_img()

            mask, im = pixel_method.get_mask(im)
            mask_solution = dat.get_mask_img()

            [local_tp, local_fp, local_fn, local_tn
             ] = evalf.performance_accumulation_pixel(mask, mask_solution)
            tp += local_tp
            fp += local_fp
            fn += local_fn
            tn += local_tn

        time += timer() - start

        results.append(
            Result(tp=tp, fp=fp, fn=fn, tn=tn, time=(time / len(verify))))
    return results
Esempio n. 6
0
def load_results():

    for i in range(0, 30):

        user_id = (random.choice(User.query.all())).user_id
        tweet_id = (random.choice(Tweet.query.all())).tweet_id
        pic_id = (random.choice(Picture.query.all())).giphy_id
        date = fake.date()
        keyword = random.choice(feels)
        block = str(fake.text())
        sentiment = random.choice(range(-5, 5))
        lat = lats[i]
        lng = lngs[i]

        result = Result(user_id=user_id,
                        tweet_id=tweet_id,
                        giphy_id=pic_id,
                        generated_at=date,
                        keywords=keyword,
                        block_text=block,
                        sentiment=sentiment,
                        lat=lat,
                        lng=lng)

        db.session.add(result)

        db.session.commit()
Esempio n. 7
0
 def crawl_results(self, contest_id, db_session):
     json_str = self.crawler.get(
         f'https://beta.atcoder.jp/contests/{contest_id}/standings/json')
     users = json.loads(json_str)['StandingsData']
     tasks = {
         t.path: t.problem_id
         for t in db_session.query(Task).filter(
             Task.contest_id == contest_id)
     }
     user_ids = {i.user_id for i in db_session.query(User.user_id)}
     for user_data in users:
         results = user_data["TaskResults"]
         if not results:
             continue
         user_id = user_data['UserScreenName']
         if user_id not in user_ids:
             user = User(user_id=user_id)
             db_session.add(user)
             user_ids.add(user_id)
         for task_name in results:
             result = results[task_name]
             problem_id = tasks[task_name]
             score = result['Score']
             failure = result['Penalty']
             elapsed = result['Elapsed'] // 1000000000
             result = Result(contest_id=contest_id,
                             problem_id=problem_id,
                             user_id=user_id,
                             score=score,
                             failure=failure,
                             elapsed=elapsed)
             db_session.add(result)
Esempio n. 8
0
def present_content(original, pig, loc):

    ohtml = f'<p style="color:blue;">{original}</p>'
    phtml = f'<p style="color:blue;">{pig}</p>'
    path = f'<a href="{loc}" style="color:blue;">{loc}</a>'

    result = Result(ohtml, phtml, path)
    return result
Esempio n. 9
0
 def test_parse_none_missing(self):
     rs = VugraphRS.parse('1nw+3,1nw+3,5de=,5dw+1,2ns=,3cs-1,4sw=,4sw=')
     self.assertEqual(rs.results[0][0], Result.parse('1nw+3'))
     self.assertEqual(rs.results[0][1], Result.parse('1nw+3'))
     self.assertEqual(rs.results[1][0], Result.parse('5de='))
     self.assertEqual(rs.results[1][1], Result.parse('5dw+1'))
     self.assertEqual(rs.results[2][0], Result.parse('2ns='))
     self.assertEqual(rs.results[2][1], Result.parse('3cs-1'))
     self.assertEqual(rs.results[3][0], Result.parse('4sw='))
     self.assertEqual(rs.results[3][1], Result.parse('4sw='))
def validateMethod(train: List[Data], verify: List[Data], method):
    method.train(train)
    tp = 0
    fn = 0
    fp = 0
    tn = 0
    t = 0
    tp_w = 0
    fn_w = 0
    fp_w = 0

    for pos, dat in enumerate(verify):
        print(method, str(pos) + '/' + str(len(verify)))
        im = dat.get_img()

        start = time.time()
        regions, mask, im = method.get_mask(im)
        mask_solution = dat.get_mask_img()
        t += time.time() - start

        [local_tp, local_fp, local_fn, local_tn] = evalf.performance_accumulation_pixel(
            mask, mask_solution)

        [local_tp_w, local_fn_w, local_fp_w] = performance_accumulation_window(regions, dat.gt)

        tp += local_tp
        fp += local_fp
        fn += local_fn
        tn += local_tn

        tp_w += local_tp_w
        fn_w += local_fn_w
        fp_w += local_fp_w

        """import matplotlib.pyplot as plt
        for region in regions:
            cv2.rectangle(mask, (region.top_left[1], region.top_left[0]),
                          (region.get_bottom_right()[1], region.get_bottom_right()[0]), (255,), thickness=5)
        for gt in dat.gt:
            cv2.rectangle(mask, (gt.top_left[1], gt.top_left[0]),
                          (gt.get_bottom_right()[1], gt.get_bottom_right()[0]), (128,), thickness=5)

        plt.imshow(mask, 'gray', vmax=255)
        plt.title(cv2.countNonZero(mask))
        plt.show()
        pass"""

    return Result(
        tp=tp,
        fp=fp,
        fn=fn,
        tn=tn,
        time=(t / len(verify)),
        tp_w=tp_w,
        fn_w=fn_w,
        fp_w=fp_w
    )
Esempio n. 11
0
def predict():
    Fuel_Type_Diesel = 0
    if request.method == 'POST':
        Year = int(request.form['Year'])
        Present_Price = float(request.form['Present_Price'])
        Kms_Driven = int(request.form['Kms_Driven'])
        Kms_Driven2 = np.log(Kms_Driven)
        Owner = int(request.form['Owner'])
        Fuel_Type_Petrol = request.form['Fuel_Type_Petrol']
        if (Fuel_Type_Petrol == 'Petrol'):
            Fuel_Type_Petrol = 1
            Fuel_Type_Diesel = 0
            fueltype = "petrol"
        else:
            Fuel_Type_Petrol = 0
            Fuel_Type_Diesel = 1
            fueltype = "diesel"
        Year = 2020 - Year
        Seller_Type_Individual = request.form['Seller_Type_Individual']
        if (Seller_Type_Individual == 'Individual'):
            Seller_Type_Individual = 1
            sellertype = "individual"
        else:
            Seller_Type_Individual = 0
            sellertype = "dealer"
        Transmission_Mannual = request.form['Transmission_Mannual']
        if (Transmission_Mannual == 'Mannual'):
            transmission = "mannual"
            Transmission_Mannual = 1
        else:
            transmission = "automatic"
            Transmission_Mannual = 0
        prediction = model.predict([[
            Present_Price, Kms_Driven2, Owner, Year, Fuel_Type_Diesel,
            Fuel_Type_Petrol, Seller_Type_Individual, Transmission_Mannual
        ]])
        output = round(prediction[0], 2)
        if output < 0:
            return render_template(
                'index.html',
                prediction_texts="Sorry you cannot sell this car")
        else:
            result_obj = Result(Year=str(Year),
                                ShowroomPrice=str(Present_Price),
                                Kilometers=str(Kms_Driven),
                                FuelType=str(fueltype),
                                Owners=str(Owner),
                                SellerType=str(sellertype),
                                TransmissionType=str(transmission),
                                PredictedPrice=str(output))
            db.session.add(result_obj)
            db.session.commit()
            return render_template(
                'index.html',
                prediction_text="You Can Sell The Car at {}".format(output))
    else:
        return render_template('index.html')
Esempio n. 12
0
def to_result(json_dict: dict) -> Result:
    """
    Converts json dictionary to Result object
    :param json_dict:
    :return:
    """
    if json_dict is None:
        return None

    result = Result(json_dict['goalsHomeTeam'], json_dict['goalsAwayTeam'],
                    None, None)

    if 'halfTime' in json_dict:
        result.halftime_home_team_goals = json_dict['halfTime'][
            'goalsHomeTeam']
        result.halftime_away_team_goals = json_dict['halfTime'][
            'goalsAwayTeam']

    return result
Esempio n. 13
0
def result(subject_id):
    username = request.get_cookie("username")
    print(username)
    subject = Subject.get(Subject.id == subject_id)
    user = User.get(User.id == int(username))
    responses = Response.select().where(Response.user == user,
                                        Response.subject_code == subject)
    result = Result.get(Result.username == user,
                        Result.subject_code == subject)
    return {"result": result, "subject": subject, "responses": responses}
Esempio n. 14
0
 def test_parse_with_gaps(self):
     rs = VugraphRS.parse(',,,,1nw+3,1nw+3,5de=,5dw+1,2ns=,3cs-1,4sw=,4sw=')
     self.assertFalse(0 in rs.results)
     self.assertFalse(1 in rs.results)
     self.assertEqual(rs.results[2][0], Result.parse('1nw+3'))
     self.assertEqual(rs.results[2][1], Result.parse('1nw+3'))
     self.assertEqual(rs.results[3][0], Result.parse('5de='))
     self.assertEqual(rs.results[3][1], Result.parse('5dw+1'))
     self.assertEqual(rs.results[4][0], Result.parse('2ns='))
     self.assertEqual(rs.results[4][1], Result.parse('3cs-1'))
     self.assertEqual(rs.results[5][0], Result.parse('4sw='))
     self.assertEqual(rs.results[5][1], Result.parse('4sw='))
Esempio n. 15
0
 def test_repr(self):
     self.assertEqual(str(Result.parse('1cn=')), '1cn=')
     self.assertEqual(str(Result.parse('2ds-1')), '2ds-1')
     self.assertEqual(str(Result.parse('3ne+1')), '3ne+1')
     self.assertEqual(str(Result.parse('4hw-2')), '4hw-2')
     self.assertEqual(str(Result.parse('5snx+2')), '5snx+2')
     self.assertEqual(str(Result.parse('6csxx=')), '6csxx=')
def generateResult():
    result = Result()

    student = random.choice(students)
    enrolledCourses = student.getEnrolledCourses()
    randomCourse = random.choice(enrolledCourses)
    exams = randomCourse.getExams()

    result.studentID = student.studentID
    result.examID = exams[0].examID
    result.grade = random.randint(10, 100)

    if result.grade > 55:
        result.passed = 'Y'
    else:
        result.passed = 'N'
    result.insert()
    return result
Esempio n. 17
0
 def parse(rs):
     results_list = rs.split(',')
     results = {}
     index = 0
     while index < len(results_list):
         result_str = results_list[index]
         if '' != result_str:
             result = Result.parse(result_str)
             deal = index // 2
             if deal not in results:
                 results[deal] = []
             results[deal].append(result)
         index += 1
     return VugraphRS(results)
Esempio n. 18
0
    def to_result(self, ignore_classes=False) -> Result:
        if self.cached_result is None:
            tp = 0
            for ground_truth in self.ground_truth:
                for detection in self.detections:
                    if detection.iou(ground_truth) > 0.5 and (ignore_classes or detection.label == ground_truth.label):
                        tp += 1
                        break

            fp = len(self.detections) - tp
            fn = len(self.ground_truth) - tp
            self.cached_result = Result(tp, fp, 0, fn)

        return self.cached_result
Esempio n. 19
0
def get_result_id():

    payload = request.get_json()
    results_json = payload["results"]
    full_name = payload["full_name"]

    result = Result(full_name=full_name, results_json=results_json)
    db.session.add(result)
    db.session.commit()

    db.session.add(result)
    db.session.flush()

    result_id = result.result_id

    return jsonify({'result_id': result_id})
def train_mode(train_dir: str, methods, analysis=False, threads=4, executions=10):
    """In train mode, we split the dataset and evaluate the result of several executions"""
    # Use this class to load and manage states
    dataset_manager = DatasetManager(train_dir)
    # Perform the executions in parallel
    with ThreadPoolExecutor(max_workers=threads) as executor:
        results = [executor.submit(validate, analysis, dataset_manager, methods)
                   for _ in range(executions)]

        # Average the results of each execution
        results = seq(results) \
            .map(lambda fut: seq(fut.result())) \
            .reduce(lambda a, b: seq(a).zip(b).map(lambda l: combine_results(l[0], l[1], executions)).to_list(),
                    [Result() for _i in range(len(methods))]) \
            .to_list()

        return results
Esempio n. 21
0
def load_results(results_json):

    print("Results")

    for i, row in enumerate(open(results_json)):
        row = row.rstrip()
        venue_id, competitor_id, team_id, position = row.split("|")

        result = Result(venue_id=venue_id,
                        competitor_id=competitor_id,
                        team_id=team_id,
                        position=position)

        db.session.add(result)
        print(result)

    db.session.commit()
Esempio n. 22
0
 def test_init_contract(self):
     self.assertEqual(
         Result(Contract.parse('1cn'), 0).contract, Contract.parse('1cn'))
     self.assertEqual(
         Result(Contract.parse('2ds'), -1).contract, Contract.parse('2ds'))
     self.assertEqual(
         Result(Contract.parse('3ne'), 1).contract, Contract.parse('3ne'))
     self.assertEqual(
         Result(Contract.parse('4hw'), -2).contract, Contract.parse('4hw'))
     self.assertEqual(
         Result(Contract.parse('5snx'), 2).contract, Contract.parse('5snx'))
     self.assertEqual(
         Result(Contract.parse('6csxx'), 0).contract,
         Contract.parse('6csxx'))
Esempio n. 23
0
def save_results():
    """Saving the img and the text from results"""

    # Get form variables
    keyword = request.form["keywords"]
    text_results = request.form["twitter"]
    giphy_url = request.form["giphy"]
    block = request.form["b_text"]
    sentiment = request.form["sentiment"]
    lat = request.form["lat"]
    lng = request.form["long"]

    #Saving current user info into the db
    user_id = session.get("user_id")
    #Saving tweet data to db
    save_twit = Tweet(tweet_text=text_results)
    db.session.add(save_twit)
    db.session.commit()
    #Saving giphy data to db
    save_gif = Picture(giphy_url=giphy_url)
    db.session.add(save_gif)
    db.session.commit()


    new_keyword = Result(keywords=keyword, 
                         tweet_id=save_twit.tweet_id, 
                         giphy_id=save_gif.giphy_id,
                         block_text=block,
                         sentiment=sentiment,
                         generated_at=datetime.datetime.now(),
                         user_id=user_id,
                         lat=lat,
                         lng=lng)

    
    db.session.add(new_keyword)
    db.session.commit()


    return redirect("/users/%s" % user_id)
def train_mode(train_dir: str,
               pixel_methods,
               window_method: str,
               analysis=False,
               threads=4,
               executions=10):
    """In train mode, we split the dataset and evaluate the result of several executions"""
    # Use this class to load and manage states
    dataset_manager = DatasetManager(train_dir)

    # Perform the executions in parallel
    results = Parallel(n_jobs=threads)(delayed(
        lambda x: validate(analysis, dataset_manager, pixel_methods))(i)
                                       for i in range(executions))

    # Average the results of each execution
    results = seq(results) \
        .reduce(lambda a, b: seq(a).zip(b).map(lambda l: combine_results(l[0], l[1], executions)).to_list(),
                [Result() for _i in range(executions)]) \
        .to_list()

    return results
Esempio n. 25
0
 def test_parse_invalid(self):
     with self.assertRaises(Exception):
         Result.parse('8cn=')  # 8 not a valid level
     with self.assertRaises(Exception):
         Result.parse('1xs=')  # x not a valid suit
     with self.assertRaises(Exception):
         Result.parse('1cx=')  # x not a valid declarer
     with self.assertRaises(Exception):
         Result.parse('1cn')  # missing score
     with self.assertRaises(Exception):
         Result.parse('1cn=0')  # unexpected trailing 0
     with self.assertRaises(Exception):
         Result.parse('1cn-8')  # -8 not valid result
     with self.assertRaises(Exception):
         Result.parse('1cn+8')  # +8 not valid result
# study = Study()
# study.load(1)
# study = Study()
# study.getStudentsEnrolledInStudy()
# result = Result()
# result.getStudentGrades()
# result.load()
# teacher = Teacher()
# teacher.getTeacher(2)
# teacher.getTeacherStudies(3)
# teacher.getTeacherCourse(2)
# course = Course()
# course.getStudentsInCourse()
# course.load()
# course.studentID = 3
# course.insertIntoStudentCourse()
# teacher.update()
#for i in range (1):
#    boy_name = generatePerson(male_name,last_name,"M", nationality,city_name,study)
#    boy_name.insert();
#    print(boy_name)

result = Result()
result.load_all()
exam = Exam()
exam.load_all()

#for i in range (1):
#	girl_name = generatePerson(female_name,last_name,"F", nationality,city_name,study)
#	print(girl_name)
Esempio n. 27
0
File: main.py Progetto: srijib/gae
 def get(self):
     key = self.request.get("key")
     if not key:
         self.response.out.write('task key required')
         return
     # key ok
     task = db.get(key)
     if not task:
         self.response.out.write('task key not exist')
         return
     # task exist
     u_title = u"Toast测试"
     u_subtitle = u"时间:%s" %str(datetime.datetime.now()+datetime.timedelta(hours=8))
     toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + \
         "<wp:Notification xmlns:wp=\"WPNotification\">" + \
            "<wp:Toast>" + \
                 "<wp:Text1>" + u_title.encode("utf-8") + "</wp:Text1>" + \
                 "<wp:Text2>" + u_subtitle.encode("utf-8") + "</wp:Text2>" + \
            "</wp:Toast> " + \
         "</wp:Notification>"
     request_headers = {
         "Content-Type": "text/xml",
         "X-WindowsPhone-Target": "toast",
         "X-NotificationClass": "2",
     }
     info = ""
     request_content = toastMessage
     response_content = ""
     response_headers = {}
     response_code = None
     subscription_status = ""
     deviceconnection_status = ""
     notification_status = ""
     ok = False
     try:
         response = urlfetch.fetch(url=task.url, headers=request_headers, payload=toastMessage, method="POST")
         response_content = response.content
         response_code = response.status_code
         response_headers = response.headers
         subscription_status = response_headers.get('x-subscriptionstatus', '')
         deviceconnection_status = response_headers.get('x-deviceconnectionstatus', '')
         notification_status = response_headers.get('x-notificationstatus', '')
         if subscription_status or deviceconnection_status or notification_status:
             info = "Result: {subscriptionstatus: %s, deviceconnectionstatus: %s, notificationstatus: %s}" %(subscription_status, deviceconnection_status, notification_status)
         else:
             info = "Result: Error"
         if subscription_status == "Active" and deviceconnection_status == "Connected" and notification_status == "Received" : ok = True
     except DownloadError as e:
         info = "".join(e.args)
     self.response.out.write(info)
     result = Result(
         task = task,
         type = Result.Toast,
         
         request_headers = str(request_headers),
         request_content = request_content.decode("utf-8"),
         
         response_headers = str(response_headers),
         response_content = response_content.decode("utf-8"),
         response_code = response_code,
         
         subscription_status = subscription_status,
         deviceconnection_status = deviceconnection_status,
         notification_status = notification_status,
         
         ok = ok,
         info = info,
     )
     result.put()
     self.response.out.write('<br><br>End Of This Page.')
Esempio n. 28
0
    if diff > 0:
        price = bar.close_ask
        unit = diff
        print("buy @ %s for %s unit" % (price, unit), trader.capital, trader.stock, bar.ssi)
        trader.buy(price, unit)
        logs.add(Log(
            timestamp=bar.timestamp,
            equity=trader.equity,
            stock=trader.stock,
        ))
    elif diff < 0:
        price = bar.close_bid
        unit = -diff
        print("sell @ %s for %s unit" % (price, unit), trader.capital, trader.stock, bar.ssi)
        trader.sell(price, unit)
        logs.add(Log(
            timestamp=bar.timestamp,
            equity=trader.equity,
            stock=trader.stock,
        ))
trader.update_value(bars.last().close_bid)
result = Result(
    capital=capital,
    equity=trader.equity,
    trade_count=trader.trade_count,
    year_count=bars.year_count,
    lowest=logs.lowest(),
    highest=logs.highest(),
)
result.output()
input()
Esempio n. 29
0
              trader.stock, bar.ssi)
        trader.buy(price, unit)
        logs.add(
            Log(
                timestamp=bar.timestamp,
                equity=trader.equity,
                stock=trader.stock,
            ))
    elif diff < 0:
        price = bar.close_bid
        unit = -diff
        print("sell @ %s for %s unit" % (price, unit), trader.capital,
              trader.stock, bar.ssi)
        trader.sell(price, unit)
        logs.add(
            Log(
                timestamp=bar.timestamp,
                equity=trader.equity,
                stock=trader.stock,
            ))
trader.update_value(bars.last().close_bid)
result = Result(
    capital=capital,
    equity=trader.equity,
    trade_count=trader.trade_count,
    year_count=bars.year_count,
    lowest=logs.lowest(),
    highest=logs.highest(),
)
result.output()
input()
Esempio n. 30
0
                    timestamp=bar.timestamp,
                    equity=trader.equity,
                    stock=trader.stock,
                ))
    if trader.stock == 0:
        if ssi >= THRESHOLD:
            unit = base_unit
            trader.sell(bar, unit)
            logs.add(
                Log(
                    timestamp=bar.timestamp,
                    equity=trader.equity,
                    stock=trader.stock,
                ))
        elif ssi <= -THRESHOLD:
            unit = base_unit
            trader.buy(bar, unit)
            logs.add(
                Log(
                    timestamp=bar.timestamp,
                    equity=trader.equity,
                    stock=trader.stock,
                ))
trader.update_value(bars.last())
result = Result(
    trader=trader,
    year_count=bars.year_count,
    logs=logs,
)
result.output()
Esempio n. 31
0
def get_result(res_id: str) -> Result:
    return Result.select().where(Result.id == res_id).get()
Esempio n. 32
0
def sub2(subject_id):

    username = request.get_cookie("username")
    subject = Subject.get(Subject.id == subject_id)
    user = User.get(User.id == int(username))
    print(user)

    result = Result.select().where(Result.username == int(username))
    if (len(result) != 0) and (result[0].is_taken == True):
        return redirect("/result")

    for question in Question.filter(Question.subject_code == subject):
        res = request.forms.get(f"question-{question.id}")
        response = Response(qid=question.id,
                            subject_code=subject_id,
                            user=user,
                            response=res)
        response.save()

        try:
            result = Result.get(Result.username == user,
                                Result.subject_code == subject)
        except:
            result = Result(username=user, subject_code=subject, is_taken=True)

        if int(res) == question.right_option:
            result.marks_obtained += 1

            if result.marks_obtained == 20:
                result.grade = "A"
                result.state = "Outstanding!"

            elif result.marks_obtained > 13:
                result.grade = "B"
                result.state = "Good!"

            elif result.marks_obtained > 7:
                result.grade = "C"
                result.state = "Average!"

            else:
                result.grade = "D"
                result.state = "Poor!"
        else:
            result.marks_obtained += 0

        result.save()
        subject = subject.select()[0]

    return redirect("/choosesub")
Esempio n. 33
0
def add_result(user: str, algo: str, threshold: float, result: float, cost: float):
    uid = uuid.uuid1()
    new_one = Result.create(id=uid,user=user, algo=algo, threshold=threshold, result=result, cost=cost)
    new_one.id = uid
    return new_one