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 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 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 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 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 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 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 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_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 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 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 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 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 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 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 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 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 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 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 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 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 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(): for score in request.json: fairway_bool = None if (score['fairway'] == 'false' or score['fairway'] == False): fairway_bool = False elif (score['fairway'] == 'true' or score['fairway'] == True): fairway_bool = True new_score = Score(roundId=score['roundId'], holeId=score['holeId'], score=int(score['score']), numPutts=int(score['numPutts']), fairway=fairway_bool) db.session.add(new_score) # print(new_score) db.session.commit() return '', 200
def post(self): args = parser.parse_args() user = User(name=args["name"].lower()) score = Score(score=0, user=user) db.session.add(user) db.session.add(score) try: db.session.commit() status = {"success": True, "user": args["name"].lower()} 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()} return status, 201
def v1_activity_start(): try: check_params(request, ['session', 'id']) user = validate_session(request.form['session']) except StandardError as e: return respond(str(e), code=400), 400 activity = Activity.query.filter(Activity.id == request.form['id']).first() if activity == None: return respond("Unknown activity", code=105), 400 score = Score(user, activity) db.session.add(score) db.session.commit() return respond("Completed!", data={'id': score.id})
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'
def test_all_scores(self): # add a user u = User(username='******', password='******', confirmed=True) db.session.add(u) db.session.commit() scores = [ { "game": "game1", "score": 10, "is_exam": True }, { "game": "game1", "score": 12, "is_exam": True }, { "game": "game2", "score": 13, "is_exam": True }, { "game": "game3", "score": 14, "is_exam": False }, ] for s in scores: s = Score(user_id=u.id, state='finished', **s) db.session.add(s) db.session.commit() response = self.client.get(url_for('api.all_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 = [10, 12, 13, 14] self.assertEqual(items, expected)
def recover_streak(): try: product = Product.query.filter_by(name="Streak recovery").first() if product.available: current_user.total_score -= product.total_price Purchase( product=product, price=product.total_price, user_id=current_user.id, ).save() Score(user_id=current_user.id, created_at=datetime.datetime.utcnow(), score=0).save() except: abort(400) return jsonify(current_user.to_dict()), 200
def handle(self, *args, **options): try: os.system('python manage.py makemigrations') os.system('python manage.py migrate') user = [[ '123456', 'FF9C92C7SDFABB71566F73422C', 'FF9C92C7SDFABB71566F73422C' ], [ 'aaabbb', '311F8A54SV9K6B5FF4EAB20536', '311F8A54SV9K6B5FF4EAB20536' ]] for i in user: Score(player_num=i[0], fraction=0, flag_num=i[1]).save() Status(target_num=i[2], player_num=i[0], run=1).save() self.stdout.write( self.style.SUCCESS('初始化成功,请尽情使用吧 (~o ̄▽ ̄)~o ~。。。')) except Exception: self.stdout.write(self.style.ERROR('命令执行出错'))