コード例 #1
0
    def get_scores(cls):
        """Returns all Scores existing within the application."""
        # Check that user is authenticated
        get_endpoints_current_user()

        scores = Score.query()
        return ScoreForms(scores=[score.to_form() for score in scores])
コード例 #2
0
class TestScore(TestCase):
    def setUp(self) -> None:
        self.score = Score(1.18991)

    def test_get_rounded_value(self):
        expectedValue = 1.19
        self.assertEqual(expectedValue, self.score.getRoundedValue())
コード例 #3
0
 def setGFI(self, gfi: float) -> None:
     """
     Set the GFI Score
     :param gfi: Set the GFI Score
     :return: None
     """
     LOG.debug(f'Setting {self.gfi_desc} as {gfi}')
     self.gfi = Score(gfi)
コード例 #4
0
 def setSMOG(self, smog: float) -> None:
     """
     Set the SMOG Score
     :param smog: Set the SMOG Score
     :return: None
     """
     LOG.debug(f'Setting {self.smog_desc} as {smog}')
     self.smog = Score(smog)
コード例 #5
0
 def setARI(self, ari: float) -> None:
     """
     Set the ARI Score
     :param ari: Set the ARI Score
     :return: None
     """
     LOG.debug(f'Setting {self.ari_desc} as {ari}')
     self.ari = Score(ari)
コード例 #6
0
 def setFRES(self, fres: float) -> None:
     """
     Set the FRES Score
     :param fres: The FRES score value
     :return: None
     """
     LOG.debug(f'Setting {self.fres_desc} as {fres}')
     self.fres = Score(fres)
コード例 #7
0
 def setFKGL(self, fkgl: float) -> None:
     """
     Set the FKGL Score
     :param fkgl: The FKGL score value
     :return: None
     """
     LOG.debug(f'Setting {self.fkgl_desc} as {fkgl}')
     self.fkgl = Score(fkgl)
コード例 #8
0
 def setFRY(self, fry: float) -> None:
     """
     Set the FRY Score
     :param fry: Set the FRY Score
     :return: None
     """
     LOG.debug(f'Setting {self.fry_desc} as {fry}')
     self.fry = Score(fry)
コード例 #9
0
 def setLWS(self, lws: float) -> None:
     """
     Set the LWS Score
     :param lws: Set the LWS Score
     :return: None
     """
     LOG.debug(f'Setting {self.lws_desc} as {lws}')
     self.lws = Score(lws)
コード例 #10
0
 def setCLI(self, cli: float) -> None:
     """
     Set the CLI Score
     :param cli: Set the CLI Score
     :return: None
     """
     LOG.debug(f'Setting {self.cli_desc} as {cli}')
     self.cli = Score(cli)
コード例 #11
0
    def end_game(cls, game, won=False):
        """Ends the game - if won is True, the player won. - if won is False,
        the player lost."""
        game.game_over = True
        game.put()

        # Add the game to the score 'board'
        score = Score(user=game.user, date=date.today(), won=won,
                      victory_margin=game.user_wins - game.cpu_wins)
        score.put()

        # Update the user's stats with the game result
        user = game.user.get()
        if won:
            user.num_wins += 1
        else:
            user.num_losses += 1
        user.total_victory_margin += (game.user_wins - game.cpu_wins)
        user.put()
コード例 #12
0
    def get_user_scores(cls, request):
        """Returns all Scores associated with the current signed-in User"""
        # Check that current user is authenticated
        get_endpoints_current_user()

        user = User.query(User.email == request.email).get()
        if not user:
            raise NotFoundException(
                'A User with that email address does not exist!')

        scores = Score.query(Score.user == user.key)
        return ScoreForms(scores=[score.to_form() for score in scores])
コード例 #13
0
    def get(self):
        Utils.reset(self)
        # calculate score by linking replay times Race Winnings Data

        event1 = '{"start_bonus": [0.1, 0.2, 0.4], "shift_bonus": [0.2, 0.5, 0.8], "drift_bonus": [0.3, 0.1, 0.9]}'
        event2 = '{"start_bonus": [0.1, 0.2, 0.4], "shift_bonus": [0.2, 0.5, 0.8], "drift_bonus": [0.3, 0.1, 0.9]}'
        laptime1 = 1
        laptime2 = 2
        self.respn = json.dumps(Score.calculate(self, event1, event2, laptime1, laptime2))
        # calculate time taken and return the result
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, 1))
コード例 #14
0
    def get_high_scores(cls, request):
        """
        Returns a list of highscores. The scores are ordered
        in descending order by the margin of victory. In the request,
        the user can specify 'number_of_results' to limit the total
        number of scores returned
        """
        # Check that the current user is authenticated
        get_endpoints_current_user()

        # Get number_of_results limit from request
        number_of_results = request.number_of_results

        if number_of_results < 0:
            raise BadRequestException("Number of results field must be greater than 0!")
        elif number_of_results == 0:
            scores = Score.query().order(-Score.victory_margin)
        else:
            scores = Score.query().order(-Score.victory_margin).fetch(number_of_results)

        return ScoreForms(scores=[score.to_form() for score in scores])
コード例 #15
0
ファイル: Indexer.py プロジェクト: nidawi/2DV515-A3
  def search(self, query: str, **opt) -> List[Score]:
    """
    Performs a recommendation-based search.
    Returns an array of score objects, containing the
    relevant pages and their associated scores.
    """
    scores = []
    queryWords = self.__parse_query_string(query)

    for page in self.__pages:
      # create and calculate scores
      pageScore = Score(page)
      wordFreq = self.__metrics.get_word_frequency_score(page, queryWords)
      docLoc = self.__metrics.get_document_location_score(page, queryWords)
      
      pageScore.set_content_score(wordFreq)
      pageScore.set_location_score(docLoc)
      scores.append(pageScore)

    # normalize scores
    self.__metrics.normalize_scores(scores)

    # generate results
    relevantScores = list(filter(lambda x : x.get_content_score() > 0, scores))

    # sort list
    relevantScores.sort(key=lambda x : x.get_weighted_score(), reverse=True)
    
    if COUNT_ID in opt:
      return relevantScores[0:opt[COUNT_ID]]
    else:
      return relevantScores
コード例 #16
0
 def __init__(self):
     LOG.debug(f"{__name__} init")
     self.fres: Score = Score(0.0)  # Flesch Reading Ease Score
     self.fkgl: Score = Score(0.0)  # Flesch-Kincaid Grade Level
     self.gfi: Score = Score(0.0)  # Gunning Fog Index
     self.ari: Score = Score(0.0)  # Automated Readability Index
     self.smog: Score = Score(0.0)  # Simple Measure of Gobbledygook
     self.cli: Score = Score(0.0)  # Coleman-Liau Index
     self.lws: Score = Score(0.0)  # Linsear Write Score
     self.fry: Score = Score(0.0)  # Fry Readability Formula
     self.fres_desc = "Flesch Reading Ease Score"
     self.fkgl_desc = "Flesch-Kincaid Grade Level"
     self.gfi_desc = "Gunning Fog Index"
     self.ari_desc = "Automated Readability Index"
     self.smog_desc = "Simple Measure of Gobbledygook"
     self.cli_desc = "Coleman-Liau Index"
     self.lws_desc = "Linsear Write Score"
     self.fry_desc = "Fry Readability Formula"
コード例 #17
0
 def setUp(self) -> None:
     self.score = Score(1.18991)
コード例 #18
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # if error, skip this
        if self.error == '':

            # query player state for given uuid
            players = Player.all().filter('uuid =', uuid).ancestor(
                db.Key.from_path('Player',
                                 config.db['playerdb_name'])).fetch(1)
            didDelete = False  # we have not delete anything yet
            for player in players:  # we might have duplicate data, just delete them all

                # query scores for this player and delete them all
                scores = Score.all().filter('uuid =', player.uuid).ancestor(
                    db.Key.from_path('Score', config.db['scoredb_name']))
                for score in scores:
                    score.delete()

                # query items for this player and delete them all
                items = Item.all().filter('uuid =', player.uuid).ancestor(
                    db.Key.from_path('Item', config.db['itemdb_name']))
                for item in items:
                    item.delete()

                # query records for this player and delete them all
                records = Record.all().filter('uuid =', player.uuid).ancestor(
                    db.Key.from_path('Record', config.db['recorddb_name']))
                for record in records:
                    record.delete()

                # query buildings for this player and delete them all
                buildings = Building.all().filter(
                    'uuid =', player.uuid).ancestor(
                        db.Key.from_path('Building',
                                         config.db['buildingdb_name']))
                for building in buildings:
                    building.delete()

                cars = Car.all().filter('uuid =', player.uuid).ancestor(
                    db.Key.from_path('Car', config.db['cardb_name']))
                for car in cars:
                    car.delete()

                # delete all this user's challenge
                Challenge.DeleteByUserId(self, player.uuid)

                # and finally, delete this player
                player.delete()
                didDelete = True

            # compose result
            if didDelete == True:
                self.respn = '"' + uuid + ' was deleted successfully."'
            else:
                self.error = uuid + ' does not exist in Database.'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
コード例 #19
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, GCVars.passwd)
        guid = self.request.get('guid')
        uuid = Utils.required(self, 'uuid')
        uuid2 = Utils.required(self, 'uid2')
        events = Utils.required(self, 'events')
        events2 = Utils.required(self, 'events2')
        laptime = Utils.required(self, 'laptime')
        laptime2 = Utils.required(self, 'laptime2')
        track = Utils.required(self, 'track')

        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')

        Utils.LogRequest(self)
        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # if error, skip this
        #if self.error != '' or self.error is None:
        player = Player.getplayer(self, uuid)
        player2 = Player.getplayer(self, uuid2)
        ai = None
        my_building = None

        win_prize = None
        lose_prize = None

        data = Data.getDataAsObj(self, 'opponent_en', 1.0)
        if data is None:
            opponents = {'obj': json.loads(Score.GetDefaultOpponents())}
        else:
            opponents = data.obj

        for _track in opponents:
            for opponent in opponents[_track]:
                if not win_prize:
                    win_prize = opponent['win_prize']
                if not lose_prize:
                    lose_prize = opponent['lose_prize']
                if player2 is None:
                    if opponent['id'] == uuid2:
                        ai = opponent
                        self.error = ''

        if player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if player is not None:
            scores = Score.calculate(self, events, events2, laptime, laptime2,
                                     win_prize, lose_prize)

            if scores is not None:
                score = scores[0]['total']
                #player.state_obj['cash'] += score
                player.state_obj['updated'] = start_time

                if player2 is not None:
                    player.state_obj[GCVars.total_races] += 1
                    if laptime < laptime2:
                        player.state_obj[GCVars.total_wins] += 1

                if ai is not None:
                    # save the resource to a building, ready for collection
                    my_building = Building.save_resource_to_building(
                        self, lang, version, player.uuid, track, score)
                    if player.state_obj.has_key(GCVars.total_ai_races):
                        player.state_obj[GCVars.total_ai_races] += 1
                    else:
                        player.state_obj.setdefault(GCVars.total_ai_races, 1)

                    if laptime < laptime2:
                        if player.state_obj.has_key(GCVars.total_ai_wins):
                            player.state_obj[GCVars.total_ai_wins] += 1
                        else:
                            player.state_obj.setdefault(
                                GCVars.total_ai_wins, 1)

                        #find star rating
                        difference = float(laptime2) - float(laptime)
                        data = {}
                        star_value = 0
                        new_star_value = 0
                        if player.state_obj.has_key('data'):
                            data = json.loads(player.state_obj['data'])
                        if data.has_key(uuid2):
                            star_value = int(data[uuid2])

                        #0,2,4 = 1 start time, 2 start time, 3 star time
                        if difference > float(ai['1_star_time']):
                            new_star_value = 1
                        if difference > float(ai['2_star_time']):
                            new_star_value = 2
                        if difference > float(ai['3_star_time']):
                            new_star_value = 3

                        if new_star_value > star_value:
                            data[uuid2] = new_star_value

                        logging.debug(
                            str(new_star_value) + ' > star_value:' +
                            str(star_value) + ', laptime 1:' + str(laptime) +
                            ', laptime2: ' + str(laptime2))
                        logging.debug('setting player data to ' +
                                      json.dumps(data))

                        player.state_obj['data'] = json.dumps(data)
                        player.state = json.dumps(player.state_obj)

                Player.setplayer(self, player)
                if 'xxx' in player.state:
                    self.error += '[KNOWN ISSUE] Player car lost. Please visit showroom and buy X1 again.'

                player_score = scores[0]
                scores_to_return = {
                    'score_prize': player_score['prize'],
                    'score_drift': player_score['prizes']['drift_bonus'],
                    'score_shift': player_score['prizes']['shift_bonus'],
                    'score_start': player_score['prizes']['start_bonus']
                }

                logging.debug('finishrace player state:' + player.state)
                self.respn = '{"state":' + player.state
                self.respn += ',"scores":' + json.dumps(scores_to_return)
                if my_building is not None:
                    self.respn += ',"building":['
                    self.respn = Building.compose_mybuilding(
                        self.respn, my_building)
                    self.respn = self.respn.rstrip(',') + ']'
                self.respn += '}'

                if player2 is not None:
                    score = scores[1]['total']
                    #player2.state_obj[GCVars.cash] += score
                    Building.save_resource_to_building(self, lang, version,
                                                       player2.uuid, track,
                                                       score)
                    player2.state_obj[GCVars.updated] = start_time
                    player2.state_obj[GCVars.total_races] += 1
                    if laptime2 < laptime:
                        player2.state_obj[GCVars.total_wins] += 1
                    Player.setplayer(self, player2)
        else:
            self.error = 'Cant find a player for ' + uuid
            #else:
        #    logging.warn('final error ' + self.error)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))