Compute number of players, both human and computer.
773687
def _num_players(self):
        """"""
        self._player_num = 0
        self._computer_num = 0
        for player in self._header.scenario.game_settings.player_info:
            if player.type == 'human':
                self._player_num += 1
            elif player.type == 'computer':
                self._computer_num += 1
512263
function WaitingRoom(options) {

        /**
         * ### WaitingRoom.connected
         *
         * Number of players connected
         */
        this.connected = 0;

        /**
         * ### WaitingRoom.poolSize
         *
         * Number of players connected before groups are made
         */
        this.poolSize = 0;

        /**
         * ### WaitingRoom.nGames
         *
         * Total number of games to be dispatched
         *
         * Server will close the waiting room afterwards.
         *
         * Undefined means no limit.
         */
        this.nGames = undefined;

        /**
         * ### WaitingRoom.groupSize
         *
         * The size of the group
         */
        this.groupSize = 0;

        /**
         * ### WaitingRoom.waitTime
         *
         * The time in milliseconds for the timeout to expire
         */
        this.waitTime = null;

        /**
         * ### WaitingRoom.executionMode
         *
         * The execution mode.
         */
        this.executionMode = null;

        /**
         * ### WaitingRoom.startDate
         *
         * The exact date and time when the game starts
         */
        this.startDate = null;

        /**
         * ### WaitingRoom.timeoutId
         *
         * The id of the timeout, if created
         */
        this.timeoutId = null;

        /**
         * ### WaitingRoom.execModeDiv
         *
         * Div containing the span for displaying the number of players
         *
         * @see WaitingRoom.playerCount
         */
        this.execModeDiv = null;

        /**
         * ### WaitingRoom.playerCount
         *
         * Span displaying the number of connected players
         */
        this.playerCount = null;

        /**
         * ### WaitingRoom.startDateDiv
         *
         * Div containing the start date
         */
        this.startDateDiv = null;

        /**
         * ### WaitingRoom.msgDiv
         *
         * Div containing optional messages to display
         */
        this.msgDiv = null;

        /**
         * ### WaitingRoom.timerDiv
         *
         * Div containing the timer
         *
         * @see WaitingRoom.timer
         */
        this.timerDiv = null;

        /**
         * ### WaitingRoom.timer
         *
         * VisualTimer instance for max wait time.
         *
         * @see VisualTimer
         */
        this.timer = null;

        /**
         * ### WaitingRoom.dots
         *
         * Looping dots to give the user the feeling of code execution
         */
        this.dots = null;

        /**
         * ### WaitingRoom.onTimeout
         *
         * Callback to be executed if the timer expires
         */
        this.onTimeout = null;

        /**
         * ### WaitingRoom.disconnectIfNotSelected
         *
         * Flag that indicates whether to disconnect an not selected player
         */
        this.disconnectIfNotSelected = null;

        /**
         * ### WaitingRoom.playWithBotOption
         *
         * If TRUE, it displays a button to begin the game with bots
         *
         * This option is set by the server, local modifications will
         * not have an effect if server does not allow it
         *
         * @see WaitingRoom.playBotBtn
         */
        this.playWithBotOption = null;

        /**
         * ### WaitingRoom.playBotBtn
         *
         * Reference to the button to play with bots
         *
         * Will be created if requested by options.
         *
         * @see WaitingRoom.playWithBotOption
         */
        this.playBotBtn = null;

        /**
         * ### WaitingRoom.selectTreatmentOption
         *
         * If TRUE, it displays a selector to choose the treatment of the game
         *
         * This option is set by the server, local modifications will
         * not have an effect if server does not allow it
         */
        this.selectTreatmentOption = null;

        /**
         * ### WaitingRoom.treatmentBtn
         *
         * Holds the name of selected treatment
         *
         * Only used if `selectTreatmentOption` is enabled
         *
         * @see WaitingRoom.selectTreatmentOption
         */
        this.selectedTreatment = null;

    }
843009
function getPlayerPlays(player, game) {
  // Shuffle so that equal-weighted players aren't
  // always prioritized by their turn order
  return Util.shuffle(game.players)
    .reduce((plays, target) => {
      if (player === target) {
        return plays
      }
      return plays.concat(
        player.hand
          .map((card) => {
            return card.validPlays ? card.validPlays(player, target, game) : []
          })
          .reduce((acc, array) => {
            return acc.concat(array)
          }, [])
      )
    }, [])
    .sort((playA, playB) => playB.weight - playA.weight)
}
173076
function Player(player) {
        var key;

        if ('object' !== typeof player) {
            throw new TypeError('Player constructor: player must be object. ' +
                               'Found: ' + player);
        }
        if ('string' !== typeof player.id) {
            throw new TypeError('Player constructor: id must be string. ' +
                                'Found: ' + player.id);
        }

        // ## Default properties

        /**
         * ### Player.id
         *
         * The nodeGame session id associate to the player
         *
         * Usually it is the same as the Socket.io id, but in
         * case of reconnections it can change
         */
        this.id = player.id;

        /**
         * ### Player.sid
         *
         * The session id received from the nodeGame server
         */
        this.sid = player.sid;

        /**
         * ### Player.clientType
         *
         * The client type (e.g. player, admin, bot, ...)
         */
        this.clientType = player.clientType || null;

        /**
         * ### Player.group
         *
         * The group to which the player belongs
         */
        this.group = player.group || null;

        /**
         * ### Player.role
         *
         * The role of the player
         */
        this.role = player.role || null;

        /**
         * ### Player.partner
         *
         * The partner of the player
         */
        this.partner = player.partner || null;

        /**
         * ### Player.count
         *
         * The ordinal position of the player in a PlayerList object
         *
         * @see PlayerList
         */
        this.count = 'undefined' === typeof player.count ? null : player.count;

        /**
         * ### Player.admin
         *
         * The admin status of the client
         */
        this.admin = !!player.admin;

        /**
         * ### Player.disconnected
         *
         * The connection status of the client
         */
        this.disconnected = !!player.disconnected;

        /**
         * ### Player.ip
         *
         * The ip address of the player
         *
         * Note: this can change in mobile networks
         */
        this.ip = player.ip || null;

        /**
         * ### Player.name
         *
         * An alphanumeric name associated with the player
         */
        this.name = player.name || null;

        /**
         * ### Player.stage
         *
         * Reference to the game-stage the player currently is
         *
         * @see node.game.stage
         * @see GameStage
         */
        this.stage = player.stage || new GameStage();

        /**
         * ### Player.stageLevel
         *
         * The current stage level of the player in the game
         *
         * @see node.stageLevels
         */
        this.stageLevel = player.stageLevel || stageLevels.UNINITIALIZED;

        /**
         * ### Player.stateLevel
         *
         * The current state level of the player in the game
         *
         * @see node.stateLevels
         */
        this.stateLevel = player.stateLevel || stateLevels.UNINITIALIZED;

        /**
         * ### Player.lang
         *
         * The current language used by the player
         *
         * Default language is English with the default path `en/`.
         */
        this.lang = {
            name: 'English',
            shortName: 'en',
            nativeName: 'English',
            path: 'en/'
        };

        /**
         * ## Extra properties
         *
         * For security reasons, they cannot be of type function, and they
         * cannot overwrite any previously defined variable
         */
        for (key in player) {
            if (player.hasOwnProperty(key)) {
                if ('function' !== typeof player[key]) {
                    if (!this.hasOwnProperty(key)) {
                        this[key] = player[key];
                    }
                }
            }
        }
    }
1169518
def idPlayerResults(cfg, rawResult):
    """"""
    result = {}
    knownPlayers = []
    dictResult = {plyrRes.player_id : plyrRes.result for plyrRes in rawResult}
    for p in cfg.players:
        if p.playerID and p.playerID in dictResult: # identified player w/ result
            knownPlayers.append(p)
            result[p.name] = dictResult[p.playerID]
    #if len(knownPlayers) == len(dictResult) - 1: # identified all but one player
    #    for p in cfg.players: # search for the not identified player
    #        if p in knownPlayers: continue # already found
    #        result.append( [p.name, p.playerID, dictResult[p.playerID]] )
    #        break # found missing player; stop searching
    #for r in result:
    #    print("result:>", r)
    return result
540283
def cpu_count() -> int:
    """"""
    if multiprocessing is None:
        return 1
    try:
        return multiprocessing.cpu_count()
    except NotImplementedError:
        pass
    try:
        return os.sysconf("SC_NPROCESSORS_CONF")
    except (AttributeError, ValueError):
        pass
    gen_log.error("Could not detect number of processors; assuming 1")
    return 1
405103
def add_player(num, args={})
      raise "player with number #{num} already exists" if @player[num]
      args[:kfactor] = ICU::RatedPlayer.kfactor(args[:kfactor].merge({ :start => start, :rating => args[:rating] })) if args[:kfactor].is_a?(Hash)
      @player[num] = ICU::RatedPlayer.factory(num, args)
    end
152743
def control(self):
        """"""
        if   self.isComputer:   value = c.COMPUTER
        else:                   value = c.PARTICIPANT
        return c.PlayerControls(value)
34950
def count_moves_in_game_range(self, game_begin, game_end):
        
        rows = self.bt_table.read_rows(
            ROWCOUNT_PREFIX.format(game_begin),
            ROWCOUNT_PREFIX.format(game_end),
            filter_=bigtable_row_filters.ColumnRangeFilter(
                METADATA, MOVE_COUNT, MOVE_COUNT))
        return sum([int(r.cell_value(METADATA, MOVE_COUNT)) for r in rows])
1280584
def data_check(self, participant):
        """"""
        infos = participant.infos()
        return len([info for info in infos if info.chosen]) * 2 == len(infos)
169844
protected function run()
    {
        $pack = $this->rec->getResourcePack();
        $this->version = $this->get(VersionAnalyzer::class);
        $version = $this->version;

        $players = $this->get(PlayerMetaAnalyzer::class);

        // The player number is used for chat messages.
        $playersByNumber = [];
        // The player index is used for game actions.
        $playersByIndex = [];
        foreach ($players as $player) {
            $playersByNumber[$player->number] = $player;
            $playersByIndex[$player->index] = $player;
        }

        $this->playersByNumber = $playersByNumber;

        $size = strlen($this->body);

        $this->position = 0;
        if ($version->isMgl) {
            $this->processGameStart();
        }

        while ($this->position < $size - 3) {
            $operationType = $this->readBody('l', 4);

            if ($operationType === self::OP_CHAT) {
                // AoC and up store the game start message with the same ID
                // as a CHAT message, but chat messages are prefixed with 0xFFFF_FFFF
                $syncChecksumInterval = $this->readBody('l', 4);
                if ($syncChecksumInterval === -1) {
                    $this->processChatMessage();
                } else {
                    $this->position -= 4;
                    $this->processGameStart();
                }
            } else if ($operationType === self::OP_SYNC) {
                $this->syncIndex++;
                // There are a lot of sync packets, so we get a significant
                // speedup just from doing this inline (and not in a separate
                // method), and by using `unpack` and manual position increments
                // instead of `readBody`.
                $data = unpack('l2', substr($this->body, $this->position, 8));
                $this->currentTime += $data[1]; // $this->readBody('l', 4);
                if ($this->syncIndex === $this->syncChecksumInterval) {
                    // no need to parse checksums
                    $this->position += 28;
                }
            } else if ($operationType === self::OP_VIEWLOCK) {
                // just skip for now
                $this->position += 12;
            } else if ($operationType === self::OP_COMMAND) {
                $length = $this->readBody('l', 4);
                $next = $this->position + $length;
                $command = ord($this->body[$this->position]);
                $this->position++;

                switch ($command) {
                    // player resign
                    case self::COMMAND_RESIGN:
                        $playerIndex = ord($this->body[$this->position]);
                        $playerNumber = ord($this->body[$this->position + 1]);
                        $disconnected = ord($this->body[$this->position + 2]);
                        $this->position += 3;
                        $player = $playersByIndex[$playerIndex];
                        if ($player && $player->resignTime === 0) {
                            $player->resignTime = $this->currentTime;
                            $message = sprintf('%s resigned', $player->name);
                            $this->chatMessages[] = new ChatMessage($this->currentTime, null, $message);
                        }
                        break;
                    // researches
                    case self::COMMAND_RESEARCH:
                        $this->position += 3;
                        $buildingId = $this->readBody('l', 4);
                        $playerId = $this->readBody('v', 2);
                        $researchId = $this->readBody('v', 2);
                        $player = $playersByIndex[$playerId];
                        if (!$player) {
                            break;
                        }

                        switch ($researchId) {
                            case self::RESEARCH_FEUDAL:
                                $researchDuration = 130000;
                                $player->feudalTime = $this->currentTime + $researchDuration;
                                break;
                            case self::RESEARCH_CASTLE:
                                // persians have faster research time
                                $researchDuration = 160000;
                                if ($player->civId === Civilization::PERSIANS) {
                                    $researchDuration /= 1.10;
                                }
                                $player->castleTime = $this->currentTime + round($researchDuration);
                                break;
                            case self::RESEARCH_IMPERIAL:
                                $researchDuration = 190000;
                                if ($player->civId === Civilization::PERSIANS) {
                                    $researchDuration /= 1.15;
                                }
                                $player->imperialTime = $this->currentTime + round($researchDuration);
                                break;
                        }
                        $player->addResearch($researchId, $this->currentTime);
                        break;
                    // training unit
                    case self::COMMAND_TRAIN:
                        $this->position += 3;
                        $buildingId = $this->readBody('l', 4);
                        $unitType = $this->readBody('v', 2);
                        $amount = $this->readBody('v', 2);

                        if (!isset($this->units[$unitType])) {
                            $this->units[$unitType] = $amount;
                        } else {
                            $this->units[$unitType] += $amount;
                        }
                        break;
                    // AI trains unit
                    case self::COMMAND_TRAIN_SINGLE:
                        $this->position += 9;
                        $unitType = $this->readBody('v', 2);
                        if (!isset($this->units[$unitType])) {
                            $this->units[$unitType] = 1;
                        } else {
                            $this->units[$unitType] += 1;
                        }
                        break;
                    // building
                    case self::COMMAND_BUILD:
                        $this->position += 1;
                        $playerId = $this->readBody('v', 2);
                        $this->position += 8;
                        $buildingType = $this->readBody('v', 2);

                        $buildingType = $pack->normalizeUnit($buildingType);

                        if (!isset($this->buildings[$playerId][$buildingType])) {
                            $this->buildings[$playerId][$buildingType] = 1;
                        } else {
                            $this->buildings[$playerId][$buildingType]++;
                        }
                        break;
                    // tributing
                    case self::COMMAND_TRIBUTE:
                        $playerIdFrom = ord($this->body[$this->position++]);
                        $playerIdTo = ord($this->body[$this->position++]);
                        $resourceId = ord($this->body[$this->position++]);

                        $playerFrom = $playersByIndex[$playerIdFrom];
                        $playerTo = $playersByIndex[$playerIdTo];

                        if ($playerFrom && $playerTo) {
                            $amount = $this->readBody('f', 4);
                            $marketFee = $this->readBody('f', 4);

                            $tribute = new Tribute();
                            $tribute->time = $this->currentTime;
                            $tribute->playerFrom = $playerFrom;
                            $tribute->playerTo = $playerTo;
                            $tribute->resourceId = $resourceId;
                            $tribute->amount = floor($amount);
                            $tribute->fee = $marketFee;
                            $this->tributes[] = $tribute;
                        } else {
                            $this->position += 8;
                        }
                        break;
                    // multiplayer postgame data in UP1.4 RC2+
                    case self::COMMAND_POSTGAME:
                        $this->postGameData = $this->read(PostgameDataAnalyzer::class);
                        break;
                    default:
                        break;
                }

                $this->position = $next;
            }
        }

        if (!empty($this->chatMessages)) {
            usort($this->chatMessages, function ($a, $b) {
                return $a->time - $b->time;
            });
        }

        if (!empty($this->buildings)) {
            ksort($this->buildings);
        }

        $analysis = new \StdClass;
        $analysis->duration = $this->currentTime;
        $analysis->tributes = $this->tributes;
        $analysis->chatMessages = $this->chatMessages;
        $analysis->units = $this->units;
        $analysis->buildings = $this->buildings;
        $analysis->postGameData = $this->postGameData;

        return $analysis;
    }
1169665
def get_players(self):
        """"""
        ratings = self.get_ratings()
        for i, player in enumerate(self._header.initial.players[1:]):
            achievements = self.get_achievements(player.attributes.player_name)
            if achievements:
                winner = achievements.victory
            else:
                winner = self.guess_winner(i + 1)
            feudal_time = ach(achievements, ['technology', 'feudal_time_int'])
            castle_time = ach(achievements, ['technology', 'castle_time_int'])
            imperial_time = ach(achievements, ['technology', 'imperial_time_int'])
            name = player.attributes.player_name.decode(self.get_encoding())
            yield {
                'name': name,
                'civilization': player.attributes.civilization,
                'human': self._header.scenario.game_settings.player_info[i + 1].type == 'human',
                'number': i + 1,
                'color_id': player.attributes.player_color,
                'winner': winner,
                'mvp': ach(achievements, ['mvp']),
                'score': ach(achievements, ['total_score']),
                'position': (player.attributes.camera_x, player.attributes.camera_y),
                'rate_snapshot': ratings.get(name),
                'achievements': {
                    'military': {
                        'score': ach(achievements, ['military', 'score']),
                        'units_killed': ach(achievements, ['military', 'units_killed']),
                        'hit_points_killed': ach(achievements, ['military', 'hit_points_killed']),
                        'units_lost': ach(achievements, ['military', 'units_lost']),
                        'buildings_razed': ach(achievements, ['military', 'buildings_razed']),
                        'hit_points_razed': ach(achievements, ['military', 'hit_points_razed']),
                        'buildings_lost': ach(achievements, ['military', 'buildings_lost']),
                        'units_converted': ach(achievements, ['military', 'units_converted'])
                    },
                    'economy': {
                        'score': ach(achievements, ['economy', 'score']),
                        'food_collected': ach(achievements, ['economy', 'food_collected']),
                        'wood_collected': ach(achievements, ['economy', 'wood_collected']),
                        'stone_collected': ach(achievements, ['economy', 'stone_collected']),
                        'gold_collected': ach(achievements, ['economy', 'gold_collected']),
                        'tribute_sent': ach(achievements, ['economy', 'tribute_sent']),
                        'tribute_received': ach(achievements, ['economy', 'tribute_received']),
                        'trade_gold': ach(achievements, ['economy', 'trade_gold']),
                        'relic_gold': ach(achievements, ['economy', 'relic_gold'])
                    },
                    'technology': {
                        'score': ach(achievements, ['technology', 'score']),
                        'feudal_time': feudal_time if feudal_time and feudal_time > 0 else None,
                        'castle_time': castle_time if castle_time and castle_time > 0 else None,
                        'imperial_time': imperial_time if imperial_time and imperial_time > 0 else None,
                        'explored_percent': ach(achievements, ['technology', 'explored_percent']),
                        'research_count': ach(achievements, ['technology', 'research_count']),
                        'research_percent': ach(achievements, ['technology', 'research_percent'])
                    },
                    'society': {
                        'score': ach(achievements, ['society', 'score']),
                        'total_wonders': ach(achievements, ['society', 'total_wonders']),
                        'total_castles': ach(achievements, ['society', 'total_castles']),
                        'total_relics': ach(achievements, ['society', 'relics_captured']),
                        'villager_high': ach(achievements, ['society', 'villager_high'])
                    }
                }
            }
137209
def num_workers(self):
        
        size = ctypes.c_int()
        check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size)))
        return size.value
72937
def player
      PLAYERS.each do |player|
        player_load(player) || next

        instance = player_class(player).new
        player_on_platform?(instance) || next

        return instance if player_launched?(instance)
      end
      nil
    end
988652
def get_userplaycount(self):
        """"""

        if not self.username:
            return

        params = self._get_params()
        params["username"] = self.username

        doc = self._request(self.ws_prefix + ".getInfo", True, params)
        return _number(_extract(doc, "userplaycount"))
591854
def update_move_counts(self, start_game, end_game, interval=1000):
        
        for g in range(start_game, end_game, interval):
            with tf.Session() as sess:
                start_row = ROW_PREFIX.format(g)
                end_row = ROW_PREFIX.format(g + interval)
                print('Range:', start_row, end_row)
                start_time = time.time()
                ds = self.tf_table.keys_by_range_dataset(start_row, end_row)
                h = _histogram_move_keys_by_game(sess, ds)
                self._write_move_counts(sess, h)
                end_time = time.time()
                elapsed = end_time - start_time
                print('  games/sec:', len(h)/elapsed)
1364839
def get_playcount(self):
        """"""

        doc = self._request(self.ws_prefix + ".getInfo", True)

        return _number(_extract(doc, "playcount"))