Setup a Game object from data read from the  master_scoreboard.xml file
769211
def load_from_scoreboard(element)
        @away_innings = []
        @home_innings = []
        @scoreboard_game_id = element.attributes['id']
        @ampm = element.attributes['ampm']
        @venue = element.attributes['venue']
        @game_pk = element.attributes['game_pk']
        @time = element.attributes['time']
        @time_zone = element.attributes['time_zone']
        @game_type = element.attributes['game_type']
        @away_name_abbrev = element.attributes['away_name_abbrev']
        @home_name_abbrev = element.attributes['home_name_abbrev']
        @away_code = element.attributes['away_code']
        @away_file_code = element.attributes['away_file_code']
        @away_team_id = element.attributes['away_team_id']
        @away_team_city = element.attributes['away_team_city']
        @away_team_name = element.attributes['away_team_name']
        @away_division = element.attributes['away_division']
        @home_code = element.attributes['home_code']
        @home_file_code = element.attributes['home_file_code']
        @home_team_id = element.attributes['home_team_id']
        @home_team_city = element.attributes['home_team_city']
        @home_team_name = element.attributes['home_team_name']
        @home_division = element.attributes['home_division']
        @day = element.attributes['day']
        @gameday_sw = element.attributes['gameday_sw']
        @away_games_back = element.attributes['away_games_back']
        @home_games_back = element.attributes['home_games_back']
        @away_games_back_wildcard = element.attributes['away_games_back_wildcard']
        @home_games_back_wildcard = element.attributes['home_games_back_wildcard']
        @venue_w_chan_loc = element.attributes['venue_w_chan_loc']
        @gameday = element.attributes['gameday']
        @away_win = element.attributes['away_win']
        @away_loss = element.attributes['away_loss']
        @home_win = element.attributes['home_win']
        @home_loss = element.attributes['home_loss']
        @league = element.attributes['league']
      
        set_status(element)
        set_innings(element)
        set_totals(element)
        set_pitchers(element)
        set_homeruns(element)
      end
492718
def getItemXML():
    ''' '''
    xml=""
    for item in range(NUM_GOALS):
        x = str(random.randint(old_div(-ARENA_WIDTH,2),old_div(ARENA_WIDTH,2)))
        z = str(random.randint(old_div(-ARENA_BREADTH,2),old_div(ARENA_BREADTH,2)))
        xml += '''<DrawItem x="''' + x + '''" y="210" z="''' + z + '''" type="''' + GOAL_TYPE + '''"/>'''
    return xml
328496
def load_from_id(gid, pid)
      @gid = gid
      @pid = pid
      @position = 'P'
      @xml_data = GamedayFetcher.fetch_pitcher(gid, pid)
      @xml_doc = REXML::Document.new(@xml_data)
      @team_abbrev = @xml_doc.root.attributes["team"]
      @first_name = @xml_doc.root.attributes["first_name"]
      @last_name = @xml_doc.root.attributes["last_name"]
      @jersey_number = @xml_doc.root.attributes["jersey_number"]
      @height = @xml_doc.root.attributes["height"]
      @weight = @xml_doc.root.attributes["weight"]
      @bats = @xml_doc.root.attributes["bats"]
      @throws = @xml_doc.root.attributes["throws"]
      @dob = @xml_doc.root.attributes['dob']
      set_opponent_stats
    end
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'])
                    }
                }
            }
637281
def make_chunk_for(output_dir=LOCAL_DIR,
                   local_dir=LOCAL_DIR,
                   game_dir=None,
                   model_num=1,
                   positions=EXAMPLES_PER_GENERATION,
                   threads=8,
                   sampling_frac=0.02):
    
    game_dir = game_dir or fsdb.selfplay_dir()
    ensure_dir_exists(output_dir)
    models = [model for model in fsdb.get_models() if model[0] < model_num]
    buf = ExampleBuffer(positions, sampling_frac=sampling_frac)
    files = []
    for _, model in sorted(models, reverse=True):
        local_model_dir = os.path.join(local_dir, model)
        if not tf.gfile.Exists(local_model_dir):
            print("Rsyncing", model)
            _rsync_dir(os.path.join(game_dir, model), local_model_dir)
        files.extend(tf.gfile.Glob(os.path.join(local_model_dir, '*.zz')))
        print("{}: {} games".format(model, len(files)))
        if len(files) * 200 * sampling_frac > positions:
            break

    print("Filling from {} files".format(len(files)))

    buf.parallel_fill(files, threads=threads)
    print(buf)
    output = os.path.join(output_dir, str(model_num) + '.tfrecord.zz')
    print("Writing to", output)
    buf.flush(output)
740217
function generateTableDataInsideScores(table){
	// Save to allow in function referencte
	table = table || this;
	var columns = table.columns*1;

	/*
		Create data table
	*/
	var scores = table.scores;

	// Just warn (DEBUG mode...)
	if(!scores)
		console.log('Table is empty!');

	// Get evaluation method ('min', 'max', custom...)
	var evalMethod = getMethodFor(table.evaluateMethod);

	// List of all the keys to sort
	var keysToSort = ['final'];

	// Go through all scores, creating a unique row
	_(scores).forEach(function(score){
		/*
			Notice score structure:

			{
				tableId: [this table id]
				teamId: xxx,
				scores: {
					  0: {value: xxx, data: {}},
					'1': {value: xxx, data: {}},
					  2: {value: xxx, data: {}}
					  [...],
				}
			}
		*/

		// This will be the object inserted in the table's data array
		// var scoreData = {};

		// Add simple attributes
		// scoreData['id'] = score.id || null;
		// scoreData['teamId'] = score.teamId || null;
		// scoreData['tableId'] = score.tableId || null;
		// scoreData['team'] = score.teamId || null;
		// scoreData.team: score.team.name
		// scoreData.country: score.team.country

		// Add scores data
		var scoreValues = [];
		for(var i = 0; i < columns; i++){

			// Get value and add to scoreValues
			var value = null;
			if(score.scores[i])
				value = score.scores[i].value;

			scoreValues.push(value);

			// Generate field key and saves
			// var field = 'score.'+(i+1);
			// score[field] = score.scores.value || null;
		}

		// Compute final score and adds to scoreData
		var finalScores = '?';

		// If evalMethod is set, let's compute the score. 
		if(evalMethod) {
			finalScores = evalMethod(scoreValues) || 0;
		}

		var showScore = finalScores;

		if(_.isArray(finalScores)){
			showScore = finalScores[0];

			for(var i = 1; i < finalScores.length; i++){
				var fieldKey = 'final'+(i+1); // Like: final2, final3, ...
				score[fieldKey] = finalScores[i];

				if(keysToSort.length <= i)
					keysToSort.push(fieldKey);
			}
		}

		score['final'] = showScore;

		// Add to table data
		// tableRows.push(score)
	});

	// Sort by 'final' field and reverse if needed
	var finalData = _.sortBy(scores, keysToSort);

	if(table.sort == 'desc')
		finalData = finalData.reverse();

	// Rank Table
	var pos = 0;
	var lastRow = null;

	_.forEach(finalData, function(row){
		pos++;

		var sameRanking = (lastRow ? true : false);
		for(var k in keysToSort){
			var key = keysToSort[k];
			if(lastRow && lastRow[key] != row[key]){
				sameRanking = false;
				break;
			}
		}

		if(sameRanking){
			// Keeps the same ranking if scores are the same
			return row.rank = lastRow.rank;
		}else{
			// Set rank as current position
			row.rank = pos;

		}
		// Save current row as last one
		lastRow = row;
	});

	// Self assign the table
	this.scores = finalData;

	// Return the table
	return this.scores;
}
428697
def read_games(glob, existing_paths):
    

    globbed = sorted(gfile.Glob(glob))

    skipped = 0
    to_parse = []
    for sgf_name in tqdm(globbed):
        assert sgf_name.lower().endswith('.sgf'), sgf_name
        sgf_path = canonical_name(sgf_name)
        sgf_filename = os.path.basename(sgf_path)

        if sgf_path in existing_paths or sgf_filename in existing_paths:
            skipped += 1
            continue

        to_parse.append(sgf_name)

    game_data = []
    with multiprocessing.Pool() as pool:
        game_data = pool.map(process_game, tqdm(to_parse), 100)

    print("Read {} SGFs, {} new, {} existing".format(
        len(globbed), len(game_data), skipped))
    return game_data
723592
def load_from_id(gid)
      @gid = gid
      @xml_data = GamedayFetcher.fetch_boxscore(gid)
      @xml_doc = REXML::Document.new(@xml_data)
      if @xml_doc.root
        @game = Game.new(@gid)
        @game.boxscore = self
        set_basic_info
        @linescore = LineScore.new
        @linescore.init(@xml_doc.root.elements["linescore"])
        @home_runs = @linescore.home_team_runs
        @away_runs = @linescore.away_team_runs
        @game_info = @xml_doc.root.elements["game_info"].text
  	    set_batting_text
        set_cities
        set_pitchers
        set_batters
        set_weather
      end
    end
761432
function GameMsgGenerator(gameServer) {
    this.session = gameServer.session;
    this.sender = gameServer.name;
    this.stage = null;
}
935139
def get_game_high_scores(self, *args, **kwargs):
        """"""
        return get_game_high_scores(*args, **self._merge_overrides(**kwargs)).run()
186648
def _replay_index(replay_dir):
  """"""
  run_config = run_configs.get()
  replay_dir = run_config.abs_replay_path(replay_dir)
  print("Checking: ", replay_dir)

  with run_config.start(want_rgb=False) as controller:
    print("-" * 60)
    print(",".join((
        "filename",
        "build",
        "map_name",
        "game_duration_loops",
        "players",
        "P1-outcome",
        "P1-race",
        "P1-apm",
        "P2-race",
        "P2-apm",
    )))

    try:
      bad_replays = []
      for file_path in run_config.replay_paths(replay_dir):
        file_name = os.path.basename(file_path)
        try:
          info = controller.replay_info(run_config.replay_data(file_path))
        except remote_controller.RequestError as e:
          bad_replays.append("%s: %s" % (file_name, e))
          continue
        if info.HasField("error"):
          print("failed:", file_name, info.error, info.error_details)
          bad_replays.append(file_name)
        else:
          out = [
              file_name,
              info.base_build,
              info.map_name,
              info.game_duration_loops,
              len(info.player_info),
              sc_pb.Result.Name(info.player_info[0].player_result.result),
              sc_common.Race.Name(info.player_info[0].player_info.race_actual),
              info.player_info[0].player_apm,
          ]
          if len(info.player_info) >= 2:
            out += [
                sc_common.Race.Name(
                    info.player_info[1].player_info.race_actual),
                info.player_info[1].player_apm,
            ]
          print(u",".join(str(s) for s in out))
    except KeyboardInterrupt:
      pass
    finally:
      if bad_replays:
        print("\n")
        print("Replays with errors:")
        print("\n".join(bad_replays))
154039
def _parse(self, stream, context, path):
        """"""
        num_players = context._._._.replay.num_players
        start = stream.tell()
        # Have to read everything to be able to use find()
        read_bytes = stream.read()
        # Try to find the first marker, a portion of the next player structure
        marker_up14 = read_bytes.find(b"\x16\xc6\x00\x00\x00\x21")
        marker_up15 = read_bytes.find(b"\x16\xf0\x00\x00\x00\x21")
        marker = -1
        if marker_up14 > 0 and marker_up15 < 0:
            marker = marker_up14
        elif marker_up15 > 0 and marker_up14 < 0:
            marker = marker_up15
        # If it exists, we're not on the last player yet
        if marker > 0:
            # Backtrack through the player name
            count = 0
            while struct.unpack("<H", read_bytes[marker-2:marker])[0] != count:
                marker -= 1
                count += 1
            # Backtrack through the rest of the next player structure
            backtrack = 43 + num_players
        # Otherwise, this is the last player
        else:
            # Search for the scenario header
            marker = read_bytes.find(b"\xf6\x28\x9c\x3f")
            # Backtrack through the achievements and initial structure footer
            backtrack = ((1817 * (num_players - 1)) + 4 + 19)
        # Seek to the position we found
        end = start + marker - backtrack
        stream.seek(end)
        return end
1345347
function readData(raw){

            var dataObj = micro.toJSON(new Buffer(raw));
            var type = dataObj._type;

            delete dataObj._type;

            switch (type){
                case "Ping":
                    //Grab latency (if exists) and bounce back the exact same data packet
                    latency = dataObj.latency || latency;
                    socket.send(raw);
                    break;

                case "GameData" :
                    //Initialize the game data and update the each of the zone's player data according to latency
                    gameData.set(dataObj);
                    currentZone = gameData.currentZone.update(latency);
                    break;

                case "Zone":
                    if (!gameData.get("isRunning")) return;

                    //Use dummy Zone Model to first update the data values according to latency
                    dataObj = new Zone(dataObj).update(latency).toJSON();
                    //Set easing to true so we don't simply override each existing player's x,y coordinates
                    currentZone.set(dataObj, {easing:true, silent:true});
                    break;

                case "Player":
                    if (!gameData.get("isRunning")) return;

                    //Use dummy Player Model to update the data values according to latency
                    dataObj = new Player(dataObj).update(latency).toJSON();

                    //Set easing to true so we don't simply override this player's x,y coordinates (if they exist)
                    currentZone.players.set(dataObj, {easing:true, remove:false, silent:true});
                    break;

                case "PlayerUpdate":
                    if (!gameData.get("isRunning")) return;

                    //A player update contains minimal player information, so we don't need to worry about easing
                    currentZone.players.set(dataObj, {add:false, remove:false, silent:true});
                    break;

                default:
                    console.warn("Unknown schema type received: "+type);
                    break;
            }
        }
162842
public function initGame()
    {
        $this->board = array();
        $this->last_player = null;

        for ($x=0; $x<$this->size; $x++) {
            $row = array();

            for ($y=0; $y<$this->size; $y++) {
                $row[] = null;
            }

            $this->board[] = $row;
        }

        $this->display();
    }
723018
def parse_plays_stream(self):
        """"""
        
        lx_doc = self.html_doc()
        if lx_doc is not None:
            parser = PlayParser(self.game_key.season, self.game_key.game_type)
            plays = lx_doc.xpath('//tr[@class = "evenColor"]')
            for p in plays:
                p_obj = parser.build_play(p)
                self.plays.append(p_obj)
                
                yield p_obj
1313236
function() {
      // load a level
        me.levelDirector.loadLevel("map1");

        // reset the score
        game.data.score = 0;

        // add our HUD to the game world
        if (typeof this.HUD === "undefined") {
            this.HUD = new game.HUD.UIContainer();
        }
        me.game.world.addChild(this.HUD);

        // display if debugPanel is enabled or on mobile
        if ((me.plugins.debugPanel && me.plugins.debugPanel.panel.visible) || me.device.touch) {
            if (typeof this.virtualJoypad === "undefined") {
                this.virtualJoypad = new game.HUD.VirtualJoypad();
            }
            me.game.world.addChild(this.virtualJoypad);
        }

        // play some music
        me.audio.playTrack("dst-gameforest");
    }
1082673
def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False,
                      minigui_mode=False):
    """"""
    n = DualNetwork(load_file)
    if cgos_mode:
        player = CGOSPlayer(network=n, seconds_per_move=5, timed_match=True,
                            two_player_mode=True)
    else:
        player = MCTSPlayer(network=n, two_player_mode=True)

    name = "Minigo-" + os.path.basename(load_file)
    version = "0.2"

    engine = gtp_engine.Engine()
    engine.add_cmd_handler(
        gtp_engine.EngineCmdHandler(engine, name, version))

    if kgs_mode:
        engine.add_cmd_handler(KgsCmdHandler(player))
    engine.add_cmd_handler(RegressionsCmdHandler(player))
    engine.add_cmd_handler(GoGuiCmdHandler(player))
    if minigui_mode:
        engine.add_cmd_handler(MiniguiBasicCmdHandler(player, courtesy_pass=kgs_mode))
    else:
        engine.add_cmd_handler(BasicCmdHandler(player, courtesy_pass=kgs_mode))

    return engine