Пример #1
0
    def _save_spread(self, week, spread):
        margins = spread['margin']
        odds = spread['odds']
        query = Score.all()
        result = {}

        query.filter('week =', week)
        result = query.fetch(constants.QUERY_LIMIT)

        if len(result) > 0:
            # By design, we only augment spread-data to existing scores
            for score in result:
                key = score.key()
                matchup = Score.get(key)
                spread_odds = 0.0
                spread_margin = 0.0
                
                if matchup.home_name in odds:
                    # Spread is relative to home team
                    spread_odds = odds[matchup.home_name]

                # Margin is relative only to game, not team
                if matchup.home_name in margins:
                    spread_margin = margins[matchup.home_name]
                elif matchup.away_name in margins:
                    spread_margin = margins[matchup.away_name]

                # Update
                matchup.spread_odds = spread_odds
                matchup.spread_margin = spread_margin
                
                # Push update
                matchup.put()
Пример #2
0
    def confusion(self, y_hat, y):
        """

        :param y_hat:
        :type y_hat:
        :param y:
        :type y:
        :return:
        :rtype:
        """
        assert isinstance(y_hat, pd.Series)
        assert isinstance(y, pd.Series)

        a = y.values.reshape(-1)
        b = pd.Series(a)
        # c = b.drop(['<PAD>', '*', '<STOP>', ','])
        # print(c)
        roll_y = pd.Series(
            y.values.reshape(-1))  #.drop(['<PAD>', '*', '<STOP>', ','])
        roll_y_hat = pd.Series(
            y_hat.values.reshape(-1))  #.drop(['<PAD>', '*', '<STOP>', ','])

        most_reacuent_tags = self.tag_corpus[2:12]
        sc = Score(most_reacuent_tags)
        sc.fit(roll_y, roll_y_hat)
        return sc.matrix_confusion()
Пример #3
0
    def _save_spread(self, week, spread):
        margins = spread['margin']
        odds = spread['odds']
        query = Score.all()
        result = {}

        query.filter('week =', week)
        result = query.fetch(constants.QUERY_LIMIT)

        if len(result) > 0:
            # By design, we only augment spread-data to existing scores
            for score in result:
                key = score.key()
                matchup = Score.get(key)
                spread_odds = 0.0
                spread_margin = 0.0

                if matchup.home_name in odds:
                    # Spread is relative to home team
                    spread_odds = odds[matchup.home_name]

                # Margin is relative only to game, not team
                if matchup.home_name in margins:
                    spread_margin = margins[matchup.home_name]
                elif matchup.away_name in margins:
                    spread_margin = margins[matchup.away_name]

                # Update
                matchup.spread_odds = spread_odds
                matchup.spread_margin = spread_margin

                # Push update
                matchup.put()
Пример #4
0
def test_init_invalid_name_score():
    """ 1001- Test if type of score name is a valid- a string"""
    with pytest.raises(ValueError):
        Score(100, 55)
    with pytest.raises(ValueError):
        Score('', 55)
    with pytest.raises(ValueError):
        Score('valid', '55')
Пример #5
0
 def get_high_scores(self, request):
     """Return all scores ordered by points; an optional parameter
     (number_of_results) limits the number of results returned"""
     num = request.number_of_results
     if num:
         scores = Score.query().order(-Score.points).fetch(num)
     else:
         scores = Score.query().order(-Score.points).fetch()
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #6
0
def update_score(user_id, obj_id, score):
    obj = ObjectiveModel.query.get(obj_id)
    user = models.user.User.query.get(user_id)
    score_obj = Score.query.filter_by(user_id=user.id,
                                      objective_id=obj.id).first()
    if score_obj:
        score_obj.update(score)
    else:
        json = {"user": user, "objective": obj, "score": score}
        score_obj = Score(json)
        score_obj.create()
    return jsonify({'result': score_obj.to_json()}), 201
Пример #7
0
    def test_over_all_acc(self):
        sc = Score(tags)
        sc.fit(y, y)
        cm = sc.over_all_acc()
        self.assertEqual(cm, 1.)
        print(cm)

        sc = Score(tags)
        sc.fit(y, y_bad)
        cm = sc.over_all_acc()
        self.assertNotEqual(cm, 1.)
        print(cm)
Пример #8
0
 def test_matrix_confusion(self):
     sc = Score(tags)
     sc.fit(y, y)
     cm = sc.matrix_confusion()
     print(cm)
     sc = Score(tags)
     sc.fit(y, y_bad)
     cm2 = sc.matrix_confusion()
     print(cm2)
     eq = np.min(np.min(cm == cm2))
     self.assertEqual(eq, 0)
     same_amount = np.min(cm.sum() == cm2.sum())
     self.assertEqual(same_amount, 1)
Пример #9
0
    def acc_per_tag(self, y_hat, y):
        assert isinstance(y_hat, pd.Series)
        assert isinstance(y, pd.Series)

        roll_y = pd.Series(y.values.reshape(-1)).drop(
            ['<PAD>', '*', '<STOP>', ','])
        roll_y_hat = pd.Series(y_hat.values.reshape(-1)).drop(
            ['<PAD>', '*', '<STOP>', ','])

        most_reacuent_tags = self.tag_corpus[:10]
        sc = Score(most_reacuent_tags)
        sc.fit(roll_y, roll_y_hat)
        return sc.acc_per_tag(roll_y, roll_y_hat)
Пример #10
0
    def match_pair(cls, game, pair_1, pair_2):
        """Match a pair and update game state"""
        game.attempts += 1
        game.put()
        card_1 = Card.query(Card.game == game.key).filter(Card.index == pair_1).get()
        card_2 = Card.query(Card.game == game.key).filter(Card.index == pair_2).get()

        if card_1.matched or card_2.matched:
            raise RuntimeError('Could not rematch a matched card')

        form = MatchResultForm()
        if card_1.value == card_2.value:
            card_1.matched = True
            card_1.put()
            card_2.matched = True
            card_2.put()
            game.matched += 2
            game.put()
            form.message = 'Success'
        else:
            form.message = 'Fail'

        # Construct return info form
        form.card_1 = card_1.to_form()
        form.card_2 = card_2.to_form()
        form.matched_count = game.matched

        if game.matched == 52:
            game.game_over = True
            game.put()
            Card.delete_cards_for_game(game)

            # Update average attempts of user
            user = game.user.get()
            games = Game.get_user_finished_games(user)
            count = len(games)
            if user.average_attempts == float('inf'):
                user.average_attempts = 0
            user.average_attempts = ((count - 1) * user.average_attempts + game.attempts) / count
            user.put()

            score = Score(user=game.user, date=date.today(), attempts=game.attempts)
            score.put()
            form.message = 'Win'

        # Create history log
        History.create_history(game=game,
                               card_1=card_1,
                               card_2=card_2,
                               message=form.message)
        return form
Пример #11
0
 def post(self):
     args = Dict(parser.parse_args())
     new_score = Score(name=args.name,
                       score=args.score,
                       added_time=datetime.now())
     new_score.save()
     return {
         'success': 1,
         'message': 'New score added successfully',
         'data': {
             'score': new_score.score,
             'name': new_score.name
         }
     }
Пример #12
0
 def end_game(self, won=False):
     """Ends the game - if won is True, the player won. - if won is False,
     the player lost. Creates a Score object and stores it in the datastore.
     Args:
        won: Indicates whether the player wins or loses.
     """
     self.game_over = True
     self.put()
     # Add the game to the score 'board'
     score = Score(
             user=self.user, date=date.today(), won=won,
             attempts_used=self.attempts - self.attempts_remaining,
             attempts=self.attempts)
     score.put()
Пример #13
0
class TestScoreAbstract(unittest.TestCase):
    def setUp(self):
        self.score = Score()
        self.week = 1

    def tearDown(self):
        pass

    def test_initial(self):
        self.assertIsNone(
            self.score.next,
            "Testing initial state")

    def test_fetch_is_not_implemented(self):
        with self.assertRaises(NotImplementedError):
            self.score.fetch(self.week),

    def test_protected_fetch_is_unimplemented(self):
        with self.assertRaises(NotImplementedError):
            self.score._fetch_score(self.week)

    def test_save_is_not_implemented(self):
        data = {}

        with self.assertRaises(NotImplementedError):
            self.score.save(self.week, data),


    def test_protected_save_is_unimplemented(self):
        data = {}

        with self.assertRaises(NotImplementedError):
            self.score._save_score(self.week, data)
Пример #14
0
 def end_game(self, won=False):
     """Ends the game - if won is True, the player won. - if won is False,
     the player lost. Creates a Score object and stores it in the datastore.
     Args:
        won: Indicates whether the player wins or loses.
     """
     self.game_over = True
     self.put()
     # Add the game to the score 'board'
     score = Score(user=self.user,
                   date=date.today(),
                   won=won,
                   attempts_used=self.attempts - self.attempts_remaining,
                   attempts=self.attempts)
     score.put()
def test_adding_review_and_comment_to_proposal_in_database(database):
    """A reviewed proposal has a score and possible a comment added.

    Put a proposal with user and presenter into the database. Although this is not
    allowed in the application have the user score and comment on their proposal
    to show that this all works in the database.
    """
    user = User(**user_data)
    proposal = Proposal(user, **proposal_data)
    presenter = Presenter(**presenter_data)
    ProposalPresenter(proposal, presenter, True)
    score = Score(proposal, user, 10)
    comment = Comment(proposal, user, 'Perfect')
    database.session.add(user)
    database.session.add(proposal)
    database.session.add(presenter)
    database.session.add(score)
    database.session.add(comment)
    database.session.commit()
    query_result = Proposal.query.filter_by(proposer=user).all()
    assert len(query_result) == 1
    proposal = query_result[0]
    assert proposal.scores is not None
    assert len(proposal.scores) == 1
    assert proposal.scores[0].score == 10
    assert proposal.comments is not None
    assert len(proposal.comments) == 1
    assert proposal.comments[0].comment == 'Perfect'
Пример #16
0
def get_user_scores(request):
    user = User.query(User.name == request.user_name).get()
    if not user:
        raise endpoints.NotFoundException(
            'A User with that name does not exist!')
    scores = Score.query(Score.user == user.key)
    return scores
Пример #17
0
    def get_high_scores(self, request):
        """Generate a list of high scores in descending order, like a leader-board!.
        Args:
            request: The GET_HIGH_SCORES_REQUEST object, which includes optional
            number_of_results, the default being 10.
        Returns:
            ScoreForms: Multiple ScoreForm container that contains all the scores' information,
            sorted by the minimum number of attempts used. In case of a tie, the game with
            higher number of maximum attempts is ranked higher.
        Raises:
            endpoints.NotFoundException: If no scores are found for any games.
        """
        number_of_results = 10
        if request.number_of_results is not None:
            number_of_results = int(request.number_of_results)

        # Fetch all the scores in descending order from the datastore.
        # In case of tie in attempts used by the user, the game with more attempts allowed wins.
        scores = Score.query(Score.won == True) \
            .order(Score.attempts_used, -Score.attempts) \
            .fetch(limit=number_of_results)
        if not scores:
            raise endpoints.NotFoundException(
                    'No scores found for any users!'
            )
        return ScoreForms(items=[score.to_form() for score in scores])
Пример #18
0
 def get_high_scores(self, request):
     """Returns top n highest scores, n is given in request param"""
     limit = request.number_of_results
     if limit <= 0:
         raise endpoints.BadRequestException('Number_of_results must be greater than 0!')
     scores = Score.get_high_scores(limit=limit)
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #19
0
 def get_user_rankings(self, request):
     """Returns a list of users ranked by win percentage"""
     users = User.query()
     if not users:
         raise endpoints.NotFoundException('No users found')
     user_ratings = []
     for user in users:
         user_name = user.name
         scores = Score.query(Score.user == user.key)
         wins = scores.filter(Score.won == True).fetch()
         loses = scores.filter(Score.won == False).fetch()
         if not (wins or loses):
             continue
         win_percentage = (float(len(wins)) /
                           (len(wins) + len(loses))) * 100
         avg_moves = 0
         for score in scores:
             avg_moves += score.moves
         avg_moves = avg_moves / (len(wins) + len(loses))
         user_ratings.append([user_name, win_percentage, avg_moves])
     user_ratings = sorted(user_ratings, key=lambda x: (-x[1], x[2]))
     messages = []
     for rating in user_ratings:
         message = 'Name: ' + rating[0] + ', Win rating: '
         message += '{0:.2f}%, Average Moves: '.format(rating[1])
         message += str(rating[2])
         messages.append(message)
     return StringMessages(items=[m for m in messages])
Пример #20
0
 def checking():
     data = get_request_data(request, cls=LoyalityJSONDecoder)
     host_uid = get_current_host_id()
     if not host_uid:
         return jsonify({'message':
                         "You need to be a staff"}), HTTP_403_FORBIDDEN
     user_uid = data.get('user_id')
     if not user_uid:
         return jsonify({'message':
                         "No user_id provided"}), HTTP_400_BAD_REQUEST
     score_update = data['score'] if data.get('score') else None
     if not score_update or not (isinstance(score_update, int)
                                 or isinstance(score_update, float)):
         return jsonify({'message':
                         "Score value is invalid"}), HTTP_400_BAD_REQUEST
     host = Host(uid=host_uid)
     if host.uid is None:
         return jsonify({'message': "No such host"}), HTTP_404_NOT_FOUND
     if not host.check_loyality(host.loyality_type, host.loyality_param,
                                host.loyality_time_param,
                                host.loyality_burn_param):
         return jsonify({
             'code': 2,
             'message': "Loyality of the host is not set"
         })
     if current_user.uid not in host.staff_uids:
         return jsonify({'message': "You are not a staff of this place"
                         }), HTTP_403_FORBIDDEN
     user = User(uid=user_uid)
     if user.login is None:
         return jsonify({'message': "No such user"}), HTTP_404_NOT_FOUND
     score = Score(host.uid, user.uid)
     return f(host, user, score, score_update)
Пример #21
0
 def get_scores(self, request):
     """Return all scores.
     Args:
         request: None.
     Returns:
         ScoreForms: Multiple ScoreForm container.
     """
     return ScoreForms(items=[score.to_form() for score in Score.query()])
Пример #22
0
 def get_scores(self, request):
     """Return all scores.
     Args:
         request: None.
     Returns:
         ScoreForms: Multiple ScoreForm container.
     """
     return ScoreForms(items=[score.to_form() for score in Score.query()])
Пример #23
0
 def get_user_scores(self, request):
     """Returns all of an individual User's scores"""
     user = User.query(User.name == request.user_name).get()
     if not user:
         raise endpoints.NotFoundException(
             'A User with that name does not exist!')
     scores = Score.get_user_scores(user)
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #24
0
 def get_user_scores(self, request):
     """Returns all of an individual User's scores"""
     user = User.query(User.name == request.user_name).get()
     if not user:
         raise endpoints.NotFoundException(
                 'A User with that name does not exist!')
     scores = Score.query(Score.user == user.key)
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #25
0
 def get_user_scores(self, request):
     '''Returns all of an individual User's scores'''
     user = User.query(User.name == request.user_name).get()
     if not user:
         raise endpoints.NotFoundException(
             'A User with that name does not exist!')
     scores = Score.query(Score.user == user.key).order(-Score.harvest)
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #26
0
 def get(self):
     
     game_id = int(self.request.get('game_id'))
     load_game = self.request.get('load_game')
     
     jplayers = self.request.get('jplayers')
     
     logging.info("jplayers id is |%s|", jplayers)
     
     players = json.loads(jplayers) if jplayers != 'None' else []
         
     scores = []
     
     if load_game == "true":
         scores = Score.query(Score.game_id == game_id).fetch()
     else:
         for player in players:
             score = Score(player_name=player, game_id=game_id, score=int(self.request.get(player)))
             score.put()
             scores.append(score)
             
     final = True
     for score in scores:
         if score.score == None:
             final = False
     
     if final:
         game = get_game(int(game_id))
         
         owings = calculate_owings(scores, game)
         
         payments = calculate_payments_from_owings(owings, game)
     else:
         owings = None
         payments = None
     
     context = {
         'game_id': game_id,
         'scores': scores,
         'players': players,
         'payments': payments
     }
     
     template = JINJA_ENVIRONMENT.get_template('templates/payments.html')
     self.response.write(template.render(context))
Пример #27
0
    def _query_scores(self, week):
        query = {}
        result = {}

        query = Score.all()
        query.filter('week =', week)
        query.order('game_id')
        result = query.fetch(25)

        return result
Пример #28
0
    def _query_scores(self, week):
        query = {}
        result = {}

        query = Score.all()
        query.filter('week =', week)
        query.order('game_id')
        result = query.fetch(25)
        
        return result
Пример #29
0
    def _query_scores(self, week):
        query = {}
        result = {}

        query = Score.all()
        query.filter('week =', week)
        query.order('game_id')
        result = query.fetch(constants.TOTAL_TEAMS)
        
        return result
Пример #30
0
    def _query_scores(self, week):
        query = {}
        result = {}

        query = Score.all()
        query.filter('week =', week)
        query.order('game_id')
        result = query.fetch(constants.TOTAL_TEAMS)

        return result
Пример #31
0
def test_constructor_invalid_incorrectvalue():
    """
    test that a ValueError is raised 
    """
    try:
        with pytest.raises(ValueError):
            player = Score(-100)

    except:
        assert False
Пример #32
0
    def end_game(self, won=False):
        """Ends the game.

        Args:
            won: if won is True, the player won, else the player lost."""
        self.game_over = True

        user = self.user.get()
        if won:
            user.games_won += 1

        # Add the game to the score 'board'
        score = Score(user=self.user,
                      date=date.today(),
                      won=won,
                      harvest=self.plant.get().flowers)

        score.put()
        user.put()
        self.put()
Пример #33
0
 def get_high_scores(self, request):
     '''Returns a leaderboard, in score-descending order'''
     scores = Score.query().order(-Score.harvest)
     if request.number_of_results:
         max_results = int(request.number_of_results)
         # Omit negative values
         if max_results > 0:
             # Force an upper bound of 1000 results
             max_results = min(1000, max_results)
             scores = scores.fetch(max_results)
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #34
0
 def get_high_scores(self, request):
     '''Returns a leaderboard, in score-descending order'''
     scores = Score.query().order(-Score.harvest)
     if request.number_of_results:
         max_results = int(request.number_of_results)
         # Omit negative values
         if max_results > 0:
             # Force an upper bound of 1000 results
             max_results = min(1000, max_results)
             scores = scores.fetch(max_results)
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #35
0
    def end_game(self, won=False):
        """Ends the game.

        Args:
            won: if won is True, the player won, else the player lost."""
        self.game_over = True

        user = self.user.get()
        if won:
            user.games_won += 1

        # Add the game to the score 'board'
        score = Score(user=self.user,
                      date=date.today(),
                      won=won,
                      harvest=self.plant.get().flowers)

        score.put()
        user.put()
        self.put()
Пример #36
0
def get_host():
    host_id = get_request_data(request).get('host_id')
    if not host_id:
        return jsonify({'message':
                        "No host id provided"}), HTTP_400_BAD_REQUEST
    host = Host(uid=host_id)
    # 404 if there is a host with no title in db. No unnamed hosts allowed.
    response = host.to_dict()
    if response is None:
        return jsonify({'message': "No such host in db"}), HTTP_404_NOT_FOUND
    score = Score(host_id, session['user_id'])
    response.update({'score': score.score})
    return jsonify(response)
Пример #37
0
def get_client_score():
    data = get_request_data(request)
    client_id = data.get('client_id')
    if client_id is None:
        return jsonify({'message': "client_id required"}), HTTP_400_BAD_REQUEST
    host_id = session.get('host_id')
    if host_id is None:
        return jsonify({'message':
                        "Please login as a staff"}), HTTP_403_FORBIDDEN
    score = Score(host_id, client_id).score
    if score is None:
        return jsonify({'message': "No host with this id"}), HTTP_404_NOT_FOUND
    return jsonify({'code': 0, 'points': score})
Пример #38
0
    def accuracy(self, y_hat, y):
        """

        :param x:
        :type x:
        :param y:
        :type y:
        :return:
        :rtype:
        """
        assert isinstance(y_hat, pd.Series)
        assert isinstance(y, pd.Series)

        roll_y = pd.Series(y.values.reshape(-1)).drop(
            ['<PAD>', '*', '<STOP>', ','])
        roll_y_hat = pd.Series(y_hat.values.reshape(-1)).drop(
            ['<PAD>', '*', '<STOP>', ','])

        most_reacuent_tags = self.tag_corpus[:10]
        sc = Score(most_reacuent_tags)
        sc.fit(roll_y, roll_y_hat)
        return sc.over_all_acc()
Пример #39
0
 def get(self):
     highest_score = Score.objects().order_by('-score').limit(-1).first()
     if highest_score is None:
         return {'success': 0, 'message': 'No score to return'}
     else:
         return {
             'success': 1,
             'message': 'Top score retrived successfully',
             'data': {
                 'score': highest_score.score,
                 'name': highest_score.name
             }
         }
Пример #40
0
    def from_json(self):
        """ reads data from a json file and creates instance of score to add to instance of score manager

        :param json_file: json file
        :type json_file: JSON
        """
        # Opening JSON file
        with open("models/scores.json", 'r') as openfile:
            # Reading from json file
            json_object = json.load(openfile)
            count = 0
            for obj in json_object['scores']:
                name = obj['name']
                score = Score(obj['score'], obj['name'])
                self.add_score(score)
def get_next_game():
    """Get the next game for given entry"""

    games = [gent.game for gent in g.entry.game_entries]
    games = sorted(games, key=lambda game: game.tournament_round.ordering)

    for game in games:
        if not Score.is_score_entered(game):
            return {
                'game_id': game.id,
                'mission': game.tournament_round.get_mission(),
                'round': game.tournament_round.ordering,
                'opponent': get_opponent(game, g.entry),
                'table': game.table_num,
            }
    raise ValueError("Next game not scheduled. Check with the TO.")
Пример #42
0
 def _cache_average_attempts():
     """
     Populates memcache with the average moves remaining of Games
     """
     scores = Score.query(Score.game_status != 'started').fetch()
     if scores:
         scount = len(scores)
         total_attempts_remaining = sum([(6-score.move_count)
                                         for score in scores])
         average = float(total_attempts_remaining)/scount
         memcache.set('MOVES_REMAINING',
                      'The average moves remaining is {:.2f}'.
                      format(average))
     else:
         memcache.set('MOVES_REMAINING',
                      'No games recorded')
Пример #43
0
 def get_user_games(self, request):
     """Returns all of an individual User's games and scores"""
     self.check_auth()
     player = User.query(User.email == request.player_email).get()
     if not player:
         raise endpoints.NotFoundException(
             'A player with that email does not exist!')
     scores = Score.player_scores(player.key)
     items = []
     score_forms = ScoreForms()
     for scr in scores:
         if scr.game_active:
             items.append(scr.to_form())
         else:
             pass
     score_forms.items = items
     return score_forms
Пример #44
0
    def _save_scores(self, week, scores):
        query = Score.all()
        scorebox = {}
        result = {}

        query.filter('week =', week)
        result = query.fetch(25)

        if len(result) <= 0:
            # Completely new save
            for game in scores:
                scorebox = Score(
                    year=self.get_season_year(),
                    week=week,
                    away_name=game[AWAY_NAME].encode('ascii', 'ignore'),
                    away_score=int(game[AWAY_SCORE]),
                    game_clock=str(game[GAME_CLOCK]),
                    game_day=game[GAME_DAY].encode('ascii', 'ignore'),
                    game_id=int(game[GAME_ID]),
                    game_status=game[GAME_STATUS],
                    game_time=game[GAME_TIME],
                    home_name=game[HOME_NAME].encode('ascii', 'ignore'),
                    home_score=int(game[HOME_SCORE]),
                    timestamp=datetime.datetime.now())

                scorebox.put()
        else:
            current = {}
            for scorebox in result:
                # Find the related game score
                for game in scores:
                    if game[AWAY_NAME] == scorebox.away_name:
                        current = game
                        break

                key = scorebox.key()
                matchup = Score.get(key)

                # Update
                matchup.away_score = int(current[AWAY_SCORE])
                matchup.home_score = int(current[HOME_SCORE])
                matchup.game_clock = str(current[GAME_CLOCK])
                matchup.game_status = current[GAME_STATUS]
                matchup.timestamp = datetime.datetime.now()

                #Push update
                matchup.put()
Пример #45
0
    def get_user_scores(self, request):
        """Returns all of the User's scores.
        Args:
            request: The GET_USER_REQUEST objects, which contains a users
                name.
        Returns:
            ScoreForms: Multiple ScoreForm container.
        Raises:
            endpoints.NotFoundException: If no user found.
        """
        user = User.query(User.name == request.user_name).get()
        # Raise an exception if a user with the user_name does not exist.
        if not user:
            raise endpoints.NotFoundException(
                    'A user with that name does not exist!')

        # Fetch all the scores for the user from the datastore.
        scores = Score.query(Score.user == user.key)

        return ScoreForms(items=[score.to_form() for score in scores])
Пример #46
0
    def get(self):
        # 1. Get ALL scores
        db_scores = Score.objects()

        # 2. Get highest score
        score_list = [{
            'name': db_score.name,
            'score': db_score.score
        } for db_score in db_scores]

        sorted_score_list = sorted(score_list, key=criteria)

        if len(sorted_score_list) > 0:

            highest_score = sorted_score_list[0]

            return {'success': 1, 'data': highest_score}

        else:
            return {'success': 0, 'message': 'No scores'}
Пример #47
0
    def _save_scores(self, week, scores):
        query = Score.all()
        scorebox = {}
        result = {}

        query.filter('week =', week)
        result = query.fetch(25)

        if len(result) <= 0:
            # Completely new save
            for game in scores:
                scorebox = Score(
                    year = self.get_season_year(),
                    week = week,
                    away_name = game[AWAY_NAME].encode('ascii', 'ignore'),
                    away_score = int(game[AWAY_SCORE]),
                    game_clock = str(game[GAME_CLOCK]),
                    game_day = game[GAME_DAY].encode('ascii', 'ignore'),
                    game_id = int(game[GAME_ID]),
                    game_status = game[GAME_STATUS],
                    game_time = game[GAME_TIME],
                    home_name = game[HOME_NAME].encode('ascii', 'ignore'),
                    home_score = int(game[HOME_SCORE]),
                    timestamp = datetime.datetime.now()
                    )

                scorebox.put()
        else:
            current = {}
            for scorebox in result:
                # Find the related game score
                for game in scores:
                    if game[AWAY_NAME] == scorebox.away_name:
                        current = game
                        break

                key = scorebox.key()
                matchup = Score.get(key)

                # Update
                matchup.away_score = int(current[AWAY_SCORE])
                matchup.home_score = int(current[HOME_SCORE])
                matchup.game_clock = str(current[GAME_CLOCK])
                matchup.game_status = current[GAME_STATUS]
                matchup.timestamp = datetime.datetime.now()
                
                #Push update
                matchup.put()
    def test_score_entered(self):
        tourn = Tournament(self.tourn_1)

        score_args = cat('per_round', 50, False, 0, 100)
        cat_1 = ScoreCategory(tournament_id=self.tourn_1, **score_args)
        self.db.session.add(cat_1)
        self.db.session.flush()

        entry_2_id = TournamentEntry.query.filter_by(
            player_id='{}_player_{}'.format(self.tourn_1, 2),
            tournament_id=self.tourn_1).first().id
        entry_3_id = TournamentEntry.query.filter_by(
            player_id='{}_player_{}'.format(self.tourn_1, 3),
            tournament_id=self.tourn_1).first().id
        entry_4_id = TournamentEntry.query.filter_by(
            player_id='{}_player_{}'.format(self.tourn_1, 4),
            tournament_id=self.tourn_1).first().id
        entry_5_id = TournamentEntry.query.filter_by(
            player_id='{}_player_{}'.format(self.tourn_1, 5),
            tournament_id=self.tourn_1).first().id

        # A completed game
        game = self.get_game_by_round(entry_4_id, 1)
        Score(category=cat_1.name, game_id=game.id, tournament=tourn,
              entry_id=entry_2_id, score=2).write()
        Score(category=cat_1.name, game_id=game.id, tournament=tourn,
              entry_id=entry_4_id, score=4).write()
        entrants = [x.entrant_id for x in game.entrants.all()]
        self.assertTrue(entry_2_id in entrants)
        self.assertTrue(entry_4_id in entrants)
        self.assertTrue(Score.is_score_entered(game))

        # A BYE will only have one entrant
        game = self.get_game_by_round(entry_3_id, 1)
        Score(category=cat_1.name, game_id=game.id, tournament=tourn,
              entry_id=entry_3_id, score=3).write()
        entrants = [x.entrant_id for x in game.entrants.all()]
        compare(len(entrants), 1)
        self.assertTrue(entry_3_id in entrants)
        self.assertTrue(Score.is_score_entered(game))

        # Ensure the rd2 game entry_4 vs. entry_5 is listed as not scored. This
        # will force a full check. entry_5's score hasn't been entered.
        game = self.get_game_by_round(entry_4_id, 2)
        game.score_entered = False
        self.db.session.add(game)
        self.db.session.flush()

        game = self.get_game_by_round(entry_4_id, 2)
        entrants = [x.entrant_id for x in game.entrants.all()]
        Score(category=cat_1.name, game_id=game.id, tournament=tourn,
              entry_id=entry_4_id, score=4).write()
        self.assertTrue(entry_4_id in entrants)
        self.assertTrue(entry_5_id in entrants)
        self.assertFalse(Score.is_score_entered(game))

        # Enter the final score for entry_5
        tourn = Tournament(self.tourn_1)
        Score(category=cat_1.name, game_id=game.id, tournament=tourn,
              entry_id=entry_5_id, score=5).write()
        self.assertTrue(Score.is_score_entered(game))
Пример #49
0
    def _save_scores(self, week, scores):
        '''
        Side-Effect: Appends a game's margin & odds
        '''
        current = {}
        _game_status = ''
        key = None
        matchup = None
        query = Score.all()
        query_select = {}
        scorebox = {}
        right_now = (datetime.datetime.now() - 
                datetime.timedelta(hours=constants.UTC_OFFSET))
        
        query.filter('week =', week)
        query_select = query.fetch(constants.TOTAL_TEAMS)

        if len(query_select) == 0:
            # Completely new save
            for game in scores:
                _game_status = game[constants.GAME_STATUS]
                if _game_status == 'final overtime':
                    # Workaround for formatting regarding overtime games
                    _game_status = 'Final Overtime'
                
                scorebox = Score(
                    year = int(game[constants.GAME_SEASON]),
                    week = int(week),
                    away_name = game[constants.AWAY_NAME].encode('ascii',
                                                                    'ignore'),
                    away_score = int(game[constants.AWAY_SCORE]),
                    game_clock = str(game[constants.GAME_CLOCK]),
                    game_day = game[constants.GAME_DAY].encode('ascii',
                                                                    'ignore'),
                    game_id = int(game[constants.GAME_ID]),
                    game_status = _game_status,
                    game_time = game[constants.GAME_TIME],
                    home_name = game[constants.HOME_NAME].encode('ascii',
                                                                    'ignore'),
                    home_score = int(game[constants.HOME_SCORE]),
                    spread_margin = float(game[constants.GAME_SPREAD_MARGIN]),
                    spread_odds = float(game[constants.GAME_SPREAD_ODDS]),
                    timestamp = right_now
                    )
                
                scorebox.put()
        else:
            # Update the scores
            for scorebox in query_select:
                # Find the related game score
                for game in scores:
                    if game[constants.AWAY_NAME] == scorebox.away_name:
                        current = game
                        break

                key = scorebox.key()
                matchup = Score.get(key)
                
                # Update
                matchup.away_score = int(game[constants.AWAY_SCORE])
                matchup.game_clock = str(game[constants.GAME_CLOCK])
                matchup.game_status = game[constants.GAME_STATUS]
                matchup.home_score = int(game[constants.HOME_SCORE])
                matchup.timestamp = right_now
                
                # Pull margin & odds data while we have the data
                game[constants.GAME_SPREAD_MARGIN] = matchup.spread_margin
                game[constants.GAME_SPREAD_ODDS] = matchup.spread_odds
                
                # Push update
                matchup.put()
Пример #50
0
 def setUp(self):
     self.score = Score()
     self.week = 1
Пример #51
0
def record_and_retrieve_score_for_hole(player, game_id, hole, team_score):
    score = get_score(player, game_id)
    if not score:
        score = Score(player_name=player, game_id=game_id)
    score.record_score_for_hole(hole, team_score)
    return score
Пример #52
0
 def get_scores(self, request):
     """Return all scores"""
     return ScoreForms(items=[score.to_form() for score in Score.query()])
Пример #53
0
 def get_high_scores(self, request):
     """Return a specified number of the leader board"""
     # Generates a high score list with descending order
     scores = Score.query().order(-Score.score)\
         .fetch(request.number_of_results)
     return ScoreForms(items=[score.to_form() for score in scores])
Пример #54
0
 def _check_db(self, season, week):
     query = Score.all()
     query.filter('week =', week)
     query_result = query.fetch(50)