def put(cls, user_id, tournament_id): tournament = TournamentModel.find_by_id(tournament_id) user = UserModel.find_by_id(user_id) if user is not None: tournament.members.append(user) db.session.commit() db.session.close() score = ScoreModel(has_own_game=0, status='uczestnik', end_terra_first=0, end_terra_second=0, group1=None, group2=None, pz1=None, pz2=None, pz3=None, pb1=None, pb2=None, pb_sum=None, tb1=None, tb2=None, user_id=user_id, tournament_id=tournament_id) user.scores.append(score) db.session.add(user) db.session.commit() db.session.close()
def client(): """ Testing client for the scores service """ app.config.from_object('config.TestingConfig') app.app_context().push() db.init_app(app) client = app.test_client() db.create_all() ScoreModel('foo', 'test1', {'notes': []}, True).save_to_db() ScoreModel('bar', 'test1', {'notes': []}, False).save_to_db() ScoreModel('foo', 'test2', {'notes': []}, False).save_to_db() ScoreModel('bar', 'test2', {'notes': []}, True).save_to_db() yield client db.session.close() db.drop_all()
def post(cls): '''Upload user submission''' try: user_mail = get_jwt_identity() # check current submission counts daily_counts = FileModel.get_interval_upload_count_by_mail( email=user_mail, AOEtime=get_AOE_today(to_str=False)) weekly_counts = FileModel.get_interval_upload_count_by_mail( email=user_mail, AOEtime=get_AOE_week(to_str=False)) if (daily_counts >= configs["DAILY_SUBMIT_LIMIT"]) or (weekly_counts >= configs["WEEKLY_SUBMIT_LIMIT"]): return {"message": f"Exceed Submission Limit: You have submitted {daily_counts} times today and {weekly_counts} times this week."}, HTTPStatus.FORBIDDEN # file validation file = request.files['file'] if file.filename == "": return {"message": "No file selected."}, HTTPStatus.FORBIDDEN if not file_upload.zipfile_check(file): return {"message": "Wrong file format."}, HTTPStatus.FORBIDDEN # load form data formData = publicFormSchema.load(request.form) # get file path upload_count = FileModel.get_upload_count_by_mail( email=user_mail) + 1 folder = file_upload.create_folder(user_mail, str(upload_count)) file_path = file_upload.get_full_path(folder, file.filename) # add column for db formData.update({"email": user_mail, "filePath": file_path}) fileObj = FileModel(**formData) scoreObj = ScoreModel() fileObj.scores.append(scoreObj) fileObj.save_to_db() try: file.save(file_path) # start processing thread = Thread(target=metric_calculate_pipeline, kwargs={"file_path": file_path, "submitUUID": formData["submitUUID"]}) thread.start() return {"message": "Upload successfully!"}, HTTPStatus.OK except Exception as e: fileObj.delete_from_db() # Rollback return {"message": "Internal Server Error!"}, HTTPStatus.INTERNAL_SERVER_ERROR except ValidationError as e: return {"message": "There's something worng with your input!"}, HTTPStatus.BAD_REQUEST except Exception as e: print(e) return {"message": "Internal Server Error!"}, HTTPStatus.INTERNAL_SERVER_ERROR
def post(self): data = Score.parser.parse_args() score = ScoreModel(**data) try: score.save_to_db() except: return {"message": "An error occurred inserting the score."}, 500 return score.json(), 201
def post(cls, user_id): data = cls.parser.parse_args() names = (score.name for score in ScoreModel.find_by_user_id(user_id)) if data['name'] not in names: new_score = ScoreModel(data['name'], user_id, data['score'], public=data['public'], description=data['description']) new_score.save_to_db() return { 'message': 'Successfully added new score.', 'content': new_score.json() } return { 'message': f'Name \"{data["name"]}\" was already used, try different name.', }, 409
def course_scorecard(name): if name == 'new': return redirect(url_for('create_course')) course = CourseModel.find_by_name(name) course_details = course.json() _id = course_details['id'] city = course_details['city'] state = course_details['state'] slope = course_details['slope'] par_list = [] distance_list = [] handicap_list = [] for i in range(1, 19): hole = HoleModel.find_by_course_hole(_id, i) hole_details = hole.json() hole_par = hole_details['par'] hole_distance = hole_details['distance'] hole_handicap = hole_details['handicap'] par_list.append(hole_par) distance_list.append(hole_distance) handicap_list.append(hole_handicap) if request.method == "POST": course = CourseModel.find_by_name(name) course_details = course.json() course_name = name course_id = course_details['id'] round_date = request.form.get('round_date') round_datetime = datetime.strptime(round_date, '%Y-%m-%d') round_datetime = round_datetime.astimezone(pytz.utc) round_string = round_datetime.strftime('%Y%m%d%H%M%S') enter_datetime = datetime.now(tz=pytz.utc) enter_string = enter_datetime.strftime('%Y%m%d%H%M%S') for p in range(1, 5): front_9_count = back_9_count = 0 round_scores = [] golfer_string = "golfer_" + str(p) name = request.form.get(golfer_string) player = GolferModel.find_by_name(name) if player: details = player.json() _id = details['id'] for h in range(1, 19): hole_string = "p" + str(p) + "_hole_" + str(h) + "_score" hole_score = request.form.get(hole_string) round_scores.append(hole_score) score = round_scores[h - 1] if score == '': score = 0 else: score = int(score) if h < 10 and score != 0: front_9_count += 1 elif h >= 10 and score != 0: back_9_count += 1 player_score = ScoreModel(course_id, _id, h, score, p, round_string, enter_string) player_score.save_to_db() return redirect( url_for('round', course_name=course_name, enter_string=enter_string)) golfers_list = [golfer for golfer in GolferModel.find_all()] course_dict = { 'name': name, 'city': city, 'state': state, 'slope': slope, 'distance': { 'hole_distances': distance_list, 'front_9_distance': sum(distance_list[:9]), 'back_9_distance': sum(distance_list[9:]), 'total_distance': sum(distance_list) }, 'handicap': { 'hole_handicaps': handicap_list, 'front_9_handicap': sum(handicap_list[:9]), 'back_9_handicap': sum(handicap_list[9:]), 'total_handicap': sum(handicap_list) }, 'par': { 'hole_pars': par_list, 'front_9_par': sum(par_list[:9]), 'back_9_par': sum(par_list[9:]), 'total_par': sum(par_list) } } return render_template('course_scorecard.jinja2', course_dict=course_dict, golfers_list=golfers_list)
previousWeekEnd, userQueueItems[userID]) previousQueueItems = filter( lambda x: x.timeRequested < previousWeekStart, userQueueItems[userID]) currentQuantity = 0 unfulfilledQuantity = 0 for queueItem in newQueueItems: currentQuantity += queueItem.request.quantity for queueItem in previousQueueItems: unfulfilledQuantity += queueItem.quantity unfulfilledQuantity += currentQuantity requested[userID] += unfulfilledQuantity score = ScoreModel.find_by_user_and_categoryType( userID, categoryTypeID) if not score: score = ScoreModel(userID, categoryTypeID) score.save_to_db() alpha = categoryType.price * currentQuantity beta = categoryType.price * unfulfilledQuantity * category.urgency u = 0.5 * (0.5 * currentQuantity * categoryType.price + score.regret + alpha + score.temporalRegret + beta) newRegret = max(score.regret + alpha - u, 0) newTemporalRegret = max(score.temporalRegret + beta - u, 0) score.regret = newRegret score.temporalRegret = newTemporalRegret score.save_to_db() utilities[userID] = u userArr = [] requestedQuantitiesArr = [] uArr = []