def user(username: str) -> render_template: """ Description ----------- This functions takes a user to their personal page after having logged in Params ------ :username: str The username for a given user on the site. Return ------ Returns a rendered Jinja2 HTML template served over the flask application under the `/user/<username>' path, depending on the username """ scores = Score.get_user_best_scores(username=current_user.username) stats = Score.get_user_stats(username=current_user.username) return render_template('user.html', header="Welcome!", user=current_user, scores=scores, stats=stats, footer="Thanks for logging in <3")
def check_ssh_team2(): current_number = utils.get_current_check('team2', 'ssh') score = Score(team='team2', check_name='ssh', check_number=current_number + 1) creds = SSHCreds.query.all() the_cred = None for cred in creds: if cred.team == 'team2': the_cred = cred logger.info('starting ssh check for team 2') try: result = SSH.check('10.120.2.13', port, username, the_cred.password) print(result) if result: logger.debug('team 2 ssh result: {}'.format(result)) score.success = True except Exception as e: logger.error('team 2 ssh failed with {}'.format(e)) logger.info('finished ssh check for team 2') second_check = utils.get_current_check('team2', 'ssh') if second_check != current_number: score.current_number = second_check + 1 db.session.add(score) db.session.commit()
def check_ping_team2(): logger.info('checking ping for team 2') servers = ['10.120.2.11', '10.120.2.13', '10.120.2.10', '10.120.2.12'] #servers = ['127.0.0.1'] current_number = utils.get_current_check('team2', 'ping') score = Score(team='team2', check_name='ping', check_number=current_number+1) try: score.success = True for server in servers: result = os.system('ping -c 1 ' + server) # for host try 3 times, if all pass it passes if result: logger.debug('team 2 host {} failed ping check'.format(server)) score.success = False if score.success: logger.debug('team 2 passed ping check') except Exception as e: logger.error('team 2 ping {}'.format(e)) logger.info('finished checking ping for team 2') second_check = utils.get_current_check('team2', 'ping') if second_check != current_number: score.current_number = second_check + 1 db.session.add(score) db.session.commit()
def check_http_team2(): logger.info('checking http for team 2') score = Score(team='team1', check_name='http', check_number=1) result = HTTP.check('1.1.1.1', '5') if result: logger.debug('team2 http passed') score.success = True logger.info('finished checking http for team 2')
def post_score(request, id): star = request.POST['star'] user_1 = User.objects.get(id=request.user.id) mov = Movie.objects.get(pk=id) score_1 = Score(value=star, user=user_1, movie=mov) score_1.save() return redirect('app:ranking')
def create_score(): content = request.json name = content.get('name', 'anon') value = int(content['score']) if (user := User.query.filter_by(name=name).first()): score = Score(value=value, user=user) db.session.add(score) db.session.commit() return {'score': score.to_dict()}, 201
def test_score(self): u = User(email='*****@*****.**', password='******') s = Score(user_id=u.id, game="test", score=10, max_score=20, duration=2, state="state", is_exam=True) self.assertIn('is_exam', s.to_json().keys())
def post(self, request, *args, **kwargs): data = request.data user = data['user'] codeid = data['code'] smells = eval(data['smells']) CodeSmell.objects.filter(code_id=codeid, user=user).delete() for s in smells: smell = CodeSmell(code_id=codeid, user_id=user, line=s['line'], smell=s['smell']) try: smell.clean_fields() smell.save() except Exception as error: return Response(error, status=status.HTTP_400_BAD_REQUEST) smells = map(lambda x: (x['line'], x['smell']), smells) origsmells = CodeSmell.objects.filter( code_id=codeid, user=Code.objects.filter(id=codeid)[0].creator) origsmells = map(lambda x: (x.line, x.smell), origsmells) score = 0 correct = [] incorrect = [] missed = [] if len(origsmells) > 0: for s in smells: if s in origsmells: score += 1 correct.append({'line': s[0], 'smell': s[1]}) else: incorrect.append({'line': s[0], 'smell': s[1]}) incorrect_lines = map(lambda x: x['line'], incorrect) for s in origsmells: if s not in smells and s[0] not in incorrect_lines: missed.append({'line': s[0], 'smell': s[1]}) score -= 0.5 * (len(missed) + len(incorrect)) score = score / len(origsmells) * 100 score = max(0, score) Score.objects.filter(code_id=codeid, user_id=user).delete() score = Score(code_id=codeid, user_id=user, score=score) score.save() scores = Score.objects.filter(code_id=codeid) scores = map(lambda x: x.score, scores) avg = sum(scores) / len(scores) code = Code.objects.get(pk=codeid) code.difficulty = (min(len(origsmells) * 10, 100) + 100 - avg) / 2 code.save() data = { 'score': score.score, 'correct': correct, 'incorrect': incorrect, 'missed': missed } return Response(data, status=status.HTTP_200_OK)
def review_heart(request): score = Score() review = Review.objects.get(id=request.POST['review']) score.critic = Critic.objects.get(user=request.user) score.avg = 1 score.save() review.scores.add(score) review.save() return HttpResponse(score.id)
def post(self, request, *args, **kwargs): data = request.data user = data['user'] codeid = data['code'] smells = eval(data['smells']) CodeSmell.objects.filter(code_id=codeid, user=user).delete() for s in smells: smell = CodeSmell(code_id=codeid, user_id=user, line=s['line'], smell=s['smell']) try: smell.clean_fields() smell.save() except Exception as error: return Response(error, status=status.HTTP_400_BAD_REQUEST) smells = map(lambda x:(x['line'], x['smell']), smells) origsmells = CodeSmell.objects.filter(code_id=codeid, user=Code.objects.filter(id=codeid)[0].creator) origsmells = map(lambda x:(x.line, x.smell), origsmells) score = 0 correct = [] incorrect = [] missed = [] if len(origsmells) > 0: for s in smells: if s in origsmells: score += 1 correct.append({'line': s[0], 'smell': s[1]}) else: incorrect.append({'line': s[0], 'smell': s[1]}) incorrect_lines = map(lambda x:x['line'], incorrect) for s in origsmells: if s not in smells and s[0] not in incorrect_lines: missed.append({'line': s[0], 'smell': s[1]}) score -= 0.5 * (len(missed) + len(incorrect)) score = score/len(origsmells) * 100 score = max(0, score) Score.objects.filter(code_id=codeid, user_id=user).delete() score = Score(code_id=codeid, user_id=user, score=score) score.save() scores = Score.objects.filter(code_id=codeid) scores = map(lambda x: x.score, scores) avg = sum(scores)/len(scores) code = Code.objects.get(pk=codeid) code.difficulty = (min(len(origsmells) * 10, 100) + 100 - avg) / 2 code.save() data = { 'score': score.score, 'correct': correct, 'incorrect': incorrect, 'missed': missed } return Response(data, status=status.HTTP_200_OK)
def update_score(): app.app_context().push() users = User.query.filter().all() print(datetime.now()) for user in users: up_score_list = [] if user.school_number and user.identity: response_obj, status = login_cdut(user.school_number, user.identity) score_list = parse_stu_score(response_obj, status) print(user.score_num) print(len(score_list)) if len(score_list) > user.score_num: i = 0 new_num = len(score_list) - user.score_num while i < new_num: score = Score(user_id=user.id, term=score_list[i][0], name=score_list[i][1], teacher=score_list[i][2], credit=score_list[i][3], grade=score_list[i][4], type=score_list[i][5], gpa=score_list[i][6], up_time=score_list[i][7]) db.session.add(score) db.session.commit() up_score_list.append(score) print(score.name) print(score.up_time) i += 1 send_score_update_email(user, up_score_list) user.score_num = len(score_list)
def lucky(): form = LuckyPlayerRollDice() ## this can become a generic function to submit a play dice = Dice() score = current_user.game_scores().first() your_number = None computer_number = None submitted = None if score is None: scores = Score(player=current_user) db.session.add(scores) db.session.commit() return redirect(url_for('games.lucky')) if form.validate_on_submit(): ## this needs to be rewritten to be reusable if form.submit.data: submitted = True your_number = dice.roll() computer_number = dice.roll() if your_number > computer_number: score.win += 1 db.session.commit() elif your_number < computer_number: score.lose += 1 db.session.commit() else: score.draw += 1 db.session.commit() return render_template('games/lucky.html', title='Play Lucky', score=score, form=form, your_number=your_number, computer_number=computer_number, submitted=submitted)
def run_automated_metrics(form_data, metrics, sw, repos_helper): """ Match the selected boxes from the form submission to metrics and run. Save the scores and feedback :param form_data: Metrics to run (List of md5 of the description) :param metrics: List of the available Metrics :param sw: The Software object being tested :param repos_helper: A RepositoryHelper object :return: """ score_ids = [] for metric_id in form_data: for metric in metrics: if metric.IDENTIFIER == metric_id: app.logger.info("Running metric: " + metric.SHORT_DESCRIPTION) metric.run(software=sw, helper=repos_helper) app.logger.info(metric.get_score()) app.logger.info(metric.get_feedback()) score = Score(software_id=sw.id, name=metric.NAME, identifier=metric.IDENTIFIER, category=metric.CATEGORY, short_description=metric.SHORT_DESCRIPTION, long_description=metric.LONG_DESCRIPTION, interactive=metric.SELF_ASSESSMENT, value=metric.get_score(), feedback=metric.get_feedback(), category_importance=form_data['importance'], metric_importance=form_data['IMPORTANCE_' + metric_id]) db.session.add(score) db.session.commit() score_ids.append(score.id) return score_ids
def handle(self, *args, **options): try: os.system('python3 manage.py makemigrations') os.system('python3 manage.py migrate') # 清空数据库 Score.objects.all().delete() Status.objects.all().delete() Flag.objects.all().delete() Logs.objects.all().delete() Round.objects.all().delete() Round(round_index=round_index).save() for i in status: Status(user_name=i[0], run=i[1], round_index=i[2]).save() for i in score: Score(user_name=i[0], fraction=i[1], token=i[2]).save() # for i in logs: # Logs( # user_name=i[0], # hacked_name=i[1], # flag_num=i[2], # info=i[3], # round_index=i[4], # result=i[5] # ).save() # for i in flags: # Flag( # user_name=i[0], # flag_num=i[1], # round_index=i[2] # ).save() self.stdout.write( self.style.SUCCESS('初始化成功,请尽情使用吧 (~o ̄▽ ̄)~o ~。。。')) except Exception: self.stdout.write(self.style.ERROR('命令执行出错'))
def run_automated_metrics(form_data, metrics, sw, repos_helper): """ Match the selected boxes from the form submission to metrics and run. Save the scores and feedback :param form_data: Metrics to run (List of md5 of the description) :param metrics: List of the available Metrics :param sw: The Software object being tested :param repos_helper: A RepositoryHelper object :return: """ score_ids = [] for metric_id in form_data: for metric in metrics: if hashlib.md5(metric.SHORT_DESCRIPTION.encode( 'utf-8')).hexdigest() == metric_id: app.logger.info("Running metric: " + metric.SHORT_DESCRIPTION) metric.run(software=sw, helper=repos_helper) app.logger.info(metric.get_score()) app.logger.info(metric.get_feedback()) score = Score(software_id=sw.id, category=metric.CATEGORY, short_description=metric.SHORT_DESCRIPTION, long_description=metric.LONG_DESCRIPTION, value=metric.get_score(), feedback=metric.get_feedback()) db.session.add(score) db.session.commit() score_ids.append(score.id) return score_ids
def run_interactive_metrics(form_data, all_metrics, sw): """ Match the selected boxes from the form submission to metrics and run. Save the scores and feedback :param form_data: Metrics to run (List of md5 of the description) :param all_metrics: List of the available Metrics :param sw: The Software object being tested :return: """ score_ids = [] for metric_id, value in form_data.items(): if metric_id == "submit" or metric_id == "csrf_token": continue for metric in all_metrics: if hashlib.md5(metric.SHORT_DESCRIPTION.encode( 'utf-8')).hexdigest() == metric_id: app.logger.info("Running metric: " + metric.SHORT_DESCRIPTION) metric.run(software=sw, form_data=value) app.logger.info(metric.get_score()) app.logger.info(metric.get_feedback()) score = Score(software_id=sw.id, category=metric.CATEGORY, short_description=metric.SHORT_DESCRIPTION, long_description=metric.LONG_DESCRIPTION, value=metric.get_score(), feedback=metric.get_feedback()) db.session.add(score) db.session.commit() score_ids.append(score.id) return score_ids
def test_best_scores_by_game(self): # add a user u = User(username='******', password='******', confirmed=True) db.session.add(u) db.session.commit() scores = [ Score(user_id=u.id, state='finished', game='game1', score=10), Score(user_id=u.id, state='finished', game='game1', score=12), Score(user_id=u.id, state='finished', game='game1', score=14), Score(user_id=u.id, state='finished', game='game2', score=12), Score(user_id=u.id, state='finished', game='game2', score=14), Score(user_id=u.id, state='finished', game='game3', score=15), Score(user_id=u.id, state='finished', game='game3', score=16), ] for s in scores: db.session.add(s) db.session.commit() response = self.client.get(url_for('api.best_scores') + '?game=game1', headers=self.get_api_headers('john', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) items = [] for item in json_response["scores"]: items.append(item["score"]) items.sort() expected = [14] self.assertEqual(items, expected)
def get_score(): score = None if request.method == "POST": score = request.form['score'] newscore = Score(score=score, user_id=current_user.id) db.session.add(newscore) db.session.commit() score = Score.query.filter_by( user_id=current_user.id).first().score return render_template('result.html')
def test_last_scores(self): # add a user u = User(username='******', password='******', confirmed=True) db.session.add(u) db.session.commit() scores = [ (datetime.datetime(2017, 1, 1, 0, 0, 0), { "game": "game1", "score": 10 }), (datetime.datetime(2017, 1, 2, 0, 0, 0), { "game": "game1", "score": 12 }), (datetime.datetime(2017, 1, 3, 0, 0, 0), { "game": "game2", "score": 13 }), (datetime.datetime(2017, 1, 4, 0, 0, 0), { "game": "game3", "score": 14 }), ] for d, s in scores: s = Score(user_id=u.id, state='finished', **s) s.created = d db.session.add(s) db.session.commit() response = self.client.get(url_for('api.last_scores'), headers=self.get_api_headers('john', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) items = [] for item in json_response["scores"]: items.append(item["score"]) expected = [12, 13, 14] self.assertEqual(items, expected)
def post(self): args = parser.parse_args() user = User.query.filter_by(name=args["name"].lower()).first() if user == None: status = { "success": False, "user": args["name"].lower(), "score": args["score"], "message": "User does not exist" } return status, 422 # Check if the user's score exists score = Score.query.filter_by(user=user).first() if score == None: # The user's score does not exist, add new score = Score(score=int(args["score"]), user=user) else: score.score = int(args["score"]) db.session.add(score) try: db.session.commit() status = { "success": True, "user": args["name"].lower(), "score": args["score"] } except Exception as _e: # TODO: Log the exception # log your exception in the way you want -> log to file, log as error with default logging, send by email. It's upon you db.session.rollback() db.session.flush() # for resetting non-commited .add() status = { "success": False, "user": args["name"].lower(), "score": args["score"] } return status, 201
def api_game_score(game_token): """Post a score from the game once the game is over to this endpoint to save it""" def check_score(score, game_start_timestamp): """ Checks to see if a given score is even feasible. Given it takes 5 seconds to go across the stage left-to-right and there are 120 points available per stage crossing attempt. We know when you started playing as well as what time it is now so we can calculate if your score is even feasible. """ seconds_to_cross_stage = 5 points_per_coin = 10 points_per_stage_cross = 12 * points_per_coin seconds_elapsed = time() - float(game_start_timestamp) practical_maximum = (seconds_elapsed / seconds_to_cross_stage) * points_per_stage_cross if score > practical_maximum or score % points_per_coin != 0: return False else: return True try: token, score_str = base64.standard_b64decode(game_token).decode( 'utf-8').split(',') score = int(score_str) except ValueError: abort(400) game_instance = Score.verify_web_token(token) if not game_instance: abort(400) valid_score = check_score(score, game_instance.created_at) if game_instance.token_used or not valid_score: return Response(json.dumps({ 'text': 'Permission Denied, score not updated.', 'score': score }), status=403, mimetype='application/json') else: game_score = int(score) game_instance.update(score=game_score, token_used=True, last_modified_at=time()) return Response(json.dumps({ 'text': 'Score updated', 'score': game_score }), status=200, mimetype="application/json")
def victory(quiz_id): user = _get_user() last_attempt = Answer.query.filter_by(user=user).order_by( Answer.id.desc()).first().attempt last_score = Score.query.filter_by(user=user).order_by( Score.id.desc()).first() attempt = last_score.attempt if last_score else 0 current_quiz = Quiz.query.filter_by(id=user.quiz_id).first() current_topic = current_quiz.topic if user.streak_start_date is None or user.last_score_age > 36: user.streak_start_date = datetime.datetime.utcnow() # Make True to allow reloading victory # if True: if last_attempt > attempt: final_score = calculate_score(quiz_id, user) user.total_score += final_score Score(score=final_score, user=user, quiz_id=quiz_id, attempt=last_attempt) # Activity feed Activity(user=user, body_html="%s finished %s in the %s skill" % (user.username, current_quiz.name, current_topic.name), public=True) if current_topic.quizzes[-1] == current_quiz: Activity(user=user, body_html="%s finished the %s skill" % (user.username, current_topic.name), public=True) # Don't update user.quiz _id if this is a redo if user.quiz_id <= quiz_id: user.quiz_id += 1 else: return redirect(url_for('quiz.ask', id=user.quiz_id)) return render_template( 'quiz/quiz_victory.html', title="Quiz", id=user.quiz_id, score=final_score, day_names=day_names(), daily_scores=daily_scores(), current_topic=current_topic, )
def game(): """Returns the webpage for the javascript based game.""" if not current_user.is_authenticated: username = None login_url = url_for('login') new_login_url = url_for('new_login') header_extra = f"<br><a href={login_url}>Sign in</a> or <a href={new_login_url}>create a profile</a> to track your scores." else: username = current_user.username header_extra = "" now = time() score = Score(username=username, score=0, token_used=False, created_at=now, last_modified_at=now) score.save() game_token = score.issue_web_token() top_scores = Score.get_best_scores() return render_template( 'game.html', header= f"Try and beat the high score!<br>Use arrow keys to move and jump, reload the page to start over.{header_extra}", token=game_token, footer= 'I made this game using the <a href="https://phaser.io/tutorials/making-your-first-phaser-3-game/part1">PhaserJS</a> tutorial.', scores=top_scores)
def leaderboard(): if request.method == 'POST': scoreNumber = request.get_json()["score"] score = Score(body=scoreNumber, user_id=current_user.get_id()) db.session.add(score) db.session.commit() return Response(status=200) else: score = Score.query.filter_by(user_id=current_user.get_id()).order_by( Score.body.desc()).limit(10).all() return render_template('leaderboard.html', title='Leaderboard', score=score)
def update_scores(self, model): users = User.query.all() items = Item.query.all() for user in users: for item in items: score = Score(user_id=user.id, item_id=item.id, score=model.score(user, item)) db.session.add(score) db.session.commit()
def check_imap(host, team): current_number = utils.get_current_check(team, 'imap') score = Score(team=team, check_name='imap', check_number=current_number + 1) creds = SSHCreds.query.all() for cred in creds: if cred.team == team: the_cred = cred logger.info('starting imap check for {}'.format(team)) try: result = IMAP.check(host, 143, 'superadmin', the_cred.password) if result: logger.debug('{} imap result: {}'.format(team, result)) score.success = True except Exception as e: logger.error('{} imap failed with {}'.format(team, e)) logger.info('finished imap check for {}'.format(team)) second_check = utils.get_current_check(team, 'imap') if second_check != current_number: score.current_number = second_check + 1 db.session.add(score) db.session.commit()
def test_follow_posts(self): # create four users u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) # create four posts now = datetime.utcnow() p1 = Score(testname="Score from john", score=12, author=u1, timestamp=now + timedelta(seconds=1)) p2 = Score(testname="Score from susan", score=12, author=u2, timestamp=now + timedelta(seconds=4)) p3 = Score(testname="Score from mary", score=12, author=u3, timestamp=now + timedelta(seconds=3)) p4 = Score(testname="Score from david", score=12, author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows david db.session.commit() # check the followed Scores of each user f1 = u1.followed_scores().all() f2 = u2.followed_scores().all() f3 = u3.followed_scores().all() f4 = u4.followed_scores().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def store(request, user_id, game_id): userToAddScore = UserCourse.objects.get(user_id=user_id) gamePlayed = Game.objects.get(pk=game_id) newScore = Score() newScore.game = gamePlayed newScore.student = userToAddScore.user newScore.value = request.POST['score'] newScore.save() return JsonResponse({'status':'OK'})
def create_score(): score_item = request.get_json() username = json.dumps(score_item[0].get("username")).strip('"') score = json.dumps(score_item[0].get("score")).strip('"') accuracy = json.dumps(score_item[0].get("accuracy")).strip('"') user_id = json.dumps(score_item[0].get("user_id")).strip('"') new_score = Score(username=username, score=float(score), accuracy=float(accuracy), user_id=int(user_id)) db.session.add(new_score) db.session.commit() resp = make_response(jsonify({"message": "JSON Received"}), 200) # not neccesary code return (resp) # not neccesary
def add_score(message): already = False print('submit score request: username={}\tscore={}'.format( message[0], message[1])) try: int(message[1]) except ValueError: print('score wasnt integer, stopping') return if not isUsername(message[0]): print('username is wrong, exiting') return if int(message[1]) >= 1000000000 or int(message[1]) % 10 != 0: return # make sure there's no exact duplicates for score in Score.query.all(): #print('checking duplicate: ' + score.username + ' and ' + message[0] + '\t' + str(score.score) + ' and ' + str(message[1])) if score.username == message[0]: already = True if score.score > message[1]: return new = Score(username=message[0], score=message[1]) db.session.delete(score) db.session.add(new) db.session.commit() if not already: new = Score(username=message[0], score=message[1]) db.session.add(new) db.session.commit()
def check_dns(host, team): current_number = utils.get_current_check(team, 'dns') score = Score(team=team, check_name='dns', check_number=current_number + 1) logger.info('starting dns check for {}'.format(team)) try: result = DNS.check(host, 'wakanda.{}.benron'.format(team)) if result: logger.debug('{} dns result: {}'.format(team, result)) if team == 'team1': if result.address == '10.1.1.20': logger.debug('team 1 passed dns') score.success = True else: if result.address == '10.2.2.20': logger.debug('team 2 passed dns') score.success = True except Exception as e: logger.error('{} dns failed with {}'.format(team, e)) logger.info('finished dns check for {}'.format(team)) second_check = utils.get_current_check(team, 'dns') if second_check != current_number: score.current_number = second_check + 1 db.session.add(score) db.session.commit()
def score(data=None, decrypt=True): data = data or request.data if not data: logging.warning('Empty request') return 'No data', 400 print('got a score!!') print(data) data = dumb_decryption(data) if decrypt else data try: player = Player.query.get(data['player']['id']) if not player: player = Player(data['player']) else: player.update_fields(data['player']) chart = Chart.query.get(data['chart']['chart_id']) if not chart: chart = Chart(data['chart']) else: chart.update_fields(data['chart']) data['score']['hash'] = data['chart'].get('hash') score = Score(data['score'], chart) score.achieved_at = datetime.utcnow() score.player = player score.version = 6 if not score.is_supported(): db.session.rollback() print('score ignored because not supported') return 'Not OK' db.session.add_all([player, chart, score]) db.session.commit() print('pushed to db! ({} played by {})'.format(chart.name, player.username)) score.set_osmos() print('osmos set') print('updating pb if needed') if update_pb_for_score(player, score): print('updated pb returned true') update_player_osmos(player) player.playcount += 1 db.session.commit() except Exception as e: db.session.rollback() logging.warning(f'Malformed score payload: \n{data}') raise logging.warning(e, exc_info=True) return 'OK'
codesmell.save() # calculate score for test's answers score = 0 correct = [] incorrect = [] missed = [] if len(origsmells) > 0: for s in usersmells: if s in origsmells: score += 1 correct.append({'line': s[0], 'smell': s[1]}) else: incorrect.append({'line': s[0], 'smell': s[1]}) incorrect_lines = map(lambda x:x['line'], incorrect) for s in origsmells: if s not in usersmells and s[0] not in incorrect_lines: missed.append({'line': s[0], 'smell': s[1]}) score -= 0.5 * (len(missed) + len(incorrect)) score = score/len(origsmells) * 100 score = max(0, score) score = Score(code=code, user=user, score=score) score.save() flag = True title = line[2:] content = '' num_lines = 0 continue content += line num_lines += 1
def post(self, request, *args, **kwargs): """ Submit a list of code smells and check it against the original uploader's code snippets to calculate a score for the user. Example POST body: <code> { "user" : 17, "code" : 38, "smells" : "[{'line': 1, 'smell': 'Vague string'}, {'line': 2, 'smell': 'Bad variable name'}]" } </code> Get back a list of incorrect, missed, and correct code smells labelled. --- parameters: - name: body paramType: body description: See example POST body above consumes: - application/json """ data = request.data user = data['user'] codeid = data['code'] smells = eval(data['smells']) CodeSmell.objects.filter(code_id=codeid, user=user).delete() for s in smells: smell = CodeSmell(code_id=codeid, user_id=user, line=s['line'], smell=s['smell']) try: smell.clean_fields() smell.save() except Exception as error: return Response(error, status=status.HTTP_400_BAD_REQUEST) smells = map(lambda x:(x['line'], x['smell']), smells) """ Code smells are compared against answers (code smells assigned by creator) """ origsmells = CodeSmell.objects.filter(code_id=codeid, user=Code.objects.filter(id=codeid)[0].creator) origsmells = map(lambda x:(x.line, x.smell), origsmells) score = 0 correct = [] incorrect = [] missed = [] """ Score is calculated as follows: ((# correct answers) - 0.5*((# missed answers) + (# incorrect answers)))/(# originally assigned code smells) """ if len(origsmells) > 0: for s in smells: if s in origsmells: score += 1 correct.append({'line': s[0], 'smell': s[1]}) else: incorrect.append({'line': s[0], 'smell': s[1]}) incorrect_lines = map(lambda x:x['line'], incorrect) for s in origsmells: if s not in smells and s[0] not in incorrect_lines: missed.append({'line': s[0], 'smell': s[1]}) score -= 0.5 * (len(missed) + len(incorrect)) score = score/len(origsmells) * 100 score = max(0, score) Score.objects.filter(code_id=codeid, user_id=user).delete() score = Score(code_id=codeid, user_id=user, score=score) score.save() """ Code's difficulty is assigned based on number of code smells (capped at 10) and average score """ scores = Score.objects.filter(code_id=codeid) scores = map(lambda x: x.score, scores) avg = sum(scores)/len(scores) code = Code.objects.get(pk=codeid) code.difficulty = (min(len(origsmells) * 10, 100) + 100 - avg) / 2 code.save() data = { 'score': score.score, 'correct': correct, 'incorrect': incorrect, 'missed': missed } return Response(data, status=status.HTTP_200_OK)